1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-*
3 * Copyright (c) 2009-2011 Apple Inc. All rights reserved.
5 * @APPLE_LICENSE_HEADER_START@
7 * This file contains Original Code and/or Modifications of Original Code
8 * as defined in and that are subject to the Apple Public Source License
9 * Version 2.0 (the 'License'). You may not use this file except in
10 * compliance with the License. Please obtain a copy of the License at
11 * http://www.opensource.apple.com/apsl/ and read it before using this
14 * The Original Code and all software distributed under the License are
15 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
19 * Please see the License for the specific language governing rights and
20 * limitations under the License.
22 * @APPLE_LICENSE_HEADER_END@
25 #ifndef __HEADER_LOAD_COMMANDS_HPP__
26 #define __HEADER_LOAD_COMMANDS_HPP__
31 #include <mach-o/loader.h>
35 #include "MachOFileAbstraction.hpp"
42 class HeaderAndLoadCommandsAbtract : public ld::Atom
45 HeaderAndLoadCommandsAbtract(const ld::Section& sect, ld::Atom::Definition d,
46 ld::Atom::Combine c, ld::Atom::Scope s, ld::Atom::ContentType ct,
47 ld::Atom::SymbolTableInclusion i, bool dds, bool thumb, bool al,
48 ld::Atom::Alignment a) : ld::Atom(sect, d, c, s, ct, i, dds, thumb, al, a) { }
50 virtual void setUUID(const uint8_t digest[16]) = 0;
51 virtual void recopyUUIDCommand() = 0;
55 class HeaderAndLoadCommandsAtom : public HeaderAndLoadCommandsAbtract
58 HeaderAndLoadCommandsAtom(const Options& opts, ld::Internal& state,
61 // overrides of ld::Atom
62 virtual ld::File* file() const { return NULL; }
63 virtual const char* name() const { return "mach-o header and load commands"; }
64 virtual uint64_t size() const;
65 virtual uint64_t objectAddress() const { return _address; }
66 virtual void copyRawContent(uint8_t buffer[]) const;
68 // overrides of HeaderAndLoadCommandsAbtract
69 virtual void setUUID(const uint8_t digest[16]) { memcpy(_uuid, digest, 16); }
70 virtual void recopyUUIDCommand();
73 typedef typename A::P P;
74 typedef typename A::P::E E;
75 typedef typename A::P::uint_t pint_t;
77 unsigned int nonHiddenSectionCount() const;
78 unsigned int segmentCount() const;
79 static uint32_t alignedSize(uint32_t x);
80 uint32_t magic() const;
81 uint32_t cpuType() const;
82 uint32_t cpuSubType() const;
83 uint32_t flags() const;
84 uint32_t fileType() const;
85 uint32_t commandsCount() const;
86 uint32_t threadLoadCommandSize() const;
87 uint8_t* copySingleSegmentLoadCommand(uint8_t* p) const;
88 uint8_t* copySegmentLoadCommands(uint8_t* p) const;
89 uint8_t* copyDyldInfoLoadCommand(uint8_t* p) const;
90 uint8_t* copySymbolTableLoadCommand(uint8_t* p) const;
91 uint8_t* copyDynamicSymbolTableLoadCommand(uint8_t* p) const;
92 uint8_t* copyDyldLoadCommand(uint8_t* p) const;
93 uint8_t* copyDylibIDLoadCommand(uint8_t* p) const;
94 uint8_t* copyRoutinesLoadCommand(uint8_t* p) const;
95 uint8_t* copyUUIDLoadCommand(uint8_t* p) const;
96 uint8_t* copyVersionLoadCommand(uint8_t* p) const;
97 uint8_t* copySourceVersionLoadCommand(uint8_t* p) const;
98 uint8_t* copyThreadsLoadCommand(uint8_t* p) const;
99 uint8_t* copyEntryPointLoadCommand(uint8_t* p) const;
100 uint8_t* copyEncryptionLoadCommand(uint8_t* p) const;
101 uint8_t* copySplitSegInfoLoadCommand(uint8_t* p) const;
102 uint8_t* copyDylibLoadCommand(uint8_t* p, const ld::dylib::File*) const;
103 uint8_t* copyRPathLoadCommand(uint8_t* p, const char*) const;
104 uint8_t* copySubFrameworkLoadCommand(uint8_t* p) const;
105 uint8_t* copyAllowableClientLoadCommand(uint8_t* p, const char* client) const;
106 uint8_t* copySubLibraryLoadCommand(uint8_t* p, const char* name) const;
107 uint8_t* copySubUmbrellaLoadCommand(uint8_t* p, const char* name) const;
108 uint8_t* copyFunctionStartsLoadCommand(uint8_t* p) const;
109 uint8_t* copyDataInCodeLoadCommand(uint8_t* p) const;
110 uint8_t* copyDependentDRLoadCommand(uint8_t* p) const;
111 uint8_t* copyDyldEnvLoadCommand(uint8_t* p, const char* env) const;
112 uint8_t* copyLinkerOptionsLoadCommand(uint8_t* p, const std::vector<const char*>&) const;
113 uint8_t* copyOptimizationHintsLoadCommand(uint8_t* p) const;
115 uint32_t sectionFlags(ld::Internal::FinalSection* sect) const;
116 bool sectionTakesNoDiskSpace(ld::Internal::FinalSection* sect) const;
119 const Options& _options;
120 ld::Internal& _state;
123 bool _hasDyldInfoLoadCommand;
124 bool _hasDyldLoadCommand;
125 bool _hasDylibIDLoadCommand;
126 bool _hasThreadLoadCommand;
127 bool _hasEntryPointLoadCommand;
128 bool _hasEncryptionLoadCommand;
129 bool _hasSplitSegInfoLoadCommand;
130 bool _hasRoutinesLoadCommand;
131 bool _hasUUIDLoadCommand;
132 bool _hasSymbolTableLoadCommand;
133 bool _hasDynamicSymbolTableLoadCommand;
134 bool _hasRPathLoadCommands;
135 bool _hasSubFrameworkLoadCommand;
136 bool _hasVersionLoadCommand;
137 bool _hasFunctionStartsLoadCommand;
138 bool _hasDataInCodeLoadCommand;
139 bool _hasSourceVersionLoadCommand;
140 bool _hasDependentDRInfo;
141 bool _hasOptimizationHints;
142 uint32_t _dylibLoadCommmandsCount;
143 uint32_t _allowableClientLoadCommmandsCount;
144 uint32_t _dyldEnvironExrasCount;
145 std::vector<const char*> _subLibraryNames;
146 std::vector<const char*> _subUmbrellaNames;
148 mutable macho_uuid_command<P>* _uuidCmdInOutputBuffer;
149 std::vector< std::vector<const char*> > _linkerOptions;
151 static ld::Section _s_section;
152 static ld::Section _s_preload_section;
155 template <typename A>
156 ld::Section HeaderAndLoadCommandsAtom<A>::_s_section("__TEXT", "__mach_header", ld::Section::typeMachHeader, true);
157 template <typename A>
158 ld::Section HeaderAndLoadCommandsAtom<A>::_s_preload_section("__HEADER", "__mach_header", ld::Section::typeMachHeader, true);
161 template <typename A>
162 HeaderAndLoadCommandsAtom<A>::HeaderAndLoadCommandsAtom(const Options& opts, ld::Internal& state, OutputFile& writer)
163 : HeaderAndLoadCommandsAbtract((opts.outputKind() == Options::kPreload) ? _s_preload_section : _s_section,
164 ld::Atom::definitionRegular, ld::Atom::combineNever,
165 ld::Atom::scopeTranslationUnit, ld::Atom::typeUnclassified,
166 ld::Atom::symbolTableNotIn, false, false, false,
167 (opts.outputKind() == Options::kPreload) ? ld::Atom::Alignment(0) : ld::Atom::Alignment(12) ),
168 _options(opts), _state(state), _writer(writer), _address(0), _uuidCmdInOutputBuffer(NULL)
171 _hasDyldInfoLoadCommand = opts.makeCompressedDyldInfo();
172 _hasDyldLoadCommand = ((opts.outputKind() == Options::kDynamicExecutable) || (_options.outputKind() == Options::kDyld));
173 _hasDylibIDLoadCommand = (opts.outputKind() == Options::kDynamicLibrary);
174 _hasThreadLoadCommand = _options.needsThreadLoadCommand();
175 _hasEntryPointLoadCommand = _options.needsEntryPointLoadCommand();
176 _hasEncryptionLoadCommand = opts.makeEncryptable();
177 _hasSplitSegInfoLoadCommand = opts.sharedRegionEligible();
178 _hasRoutinesLoadCommand = (opts.initFunctionName() != NULL);
179 _hasSymbolTableLoadCommand = true;
180 _hasUUIDLoadCommand = (opts.UUIDMode() != Options::kUUIDNone);
181 _hasOptimizationHints = (_state.someObjectHasOptimizationHints && (opts.outputKind() == Options::kObjectFile));
182 switch ( opts.outputKind() ) {
183 case Options::kDynamicExecutable:
184 case Options::kDynamicLibrary:
185 case Options::kDynamicBundle:
187 case Options::kKextBundle:
188 _hasDynamicSymbolTableLoadCommand = true;
190 case Options::kObjectFile:
191 if ( ! state.someObjectFileHasDwarf )
192 _hasUUIDLoadCommand = false;
193 _hasDynamicSymbolTableLoadCommand = false;
194 for (std::vector<ld::Internal::FinalSection*>::iterator it = _state.sections.begin(); it != _state.sections.end(); ++it) {
195 if ( (*it)->type() == ld::Section::typeNonLazyPointer ) {
196 _hasDynamicSymbolTableLoadCommand = true;
200 for (CStringSet::const_iterator it = _state.linkerOptionFrameworks.begin(); it != _state.linkerOptionFrameworks.end(); ++it) {
201 const char* frameWorkName = *it;
202 std::vector<const char*>* lo = new std::vector<const char*>();
203 lo->push_back("-framework");
204 lo->push_back(frameWorkName);
205 _linkerOptions.push_back(*lo);
207 for (CStringSet::const_iterator it = _state.linkerOptionLibraries.begin(); it != _state.linkerOptionLibraries.end(); ++it) {
208 const char* libName = *it;
209 std::vector<const char*>* lo = new std::vector<const char*>();
210 char * s = new char[strlen(libName)+3];
214 _linkerOptions.push_back(*lo);
217 case Options::kStaticExecutable:
218 _hasDynamicSymbolTableLoadCommand = opts.positionIndependentExecutable();
220 case Options::kPreload:
221 _hasDynamicSymbolTableLoadCommand = opts.positionIndependentExecutable();
224 _hasRPathLoadCommands = (_options.rpaths().size() != 0);
225 _hasSubFrameworkLoadCommand = (_options.umbrellaName() != NULL);
226 _hasVersionLoadCommand = _options.addVersionLoadCommand();
227 _hasFunctionStartsLoadCommand = _options.addFunctionStarts();
228 _hasDataInCodeLoadCommand = _options.addDataInCodeInfo();
229 _hasSourceVersionLoadCommand = _options.needsSourceVersionLoadCommand();
230 _hasDependentDRInfo = _options.needsDependentDRInfo();
231 _dylibLoadCommmandsCount = _writer.dylibCount();
232 _allowableClientLoadCommmandsCount = _options.allowableClients().size();
233 _dyldEnvironExrasCount = _options.dyldEnvironExtras().size();
235 if ( ! _options.useSimplifiedDylibReExports() ) {
236 // target OS does not support LC_REEXPORT_DYLIB, so use old complicated load commands
237 for(uint32_t ord=1; ord <= _writer.dylibCount(); ++ord) {
238 const ld::dylib::File* dylib = _writer.dylibByOrdinal(ord);
239 if ( dylib->willBeReExported() ) {
240 // if child says it is an sub-framework of the image being created, then nothing to do here
241 bool isSubFramework = false;
242 const char* childInUmbrella = dylib->parentUmbrella();
243 if ( childInUmbrella != NULL ) {
244 const char* myLeaf = strrchr(_options.installPath(), '/');
245 if ( myLeaf != NULL ) {
246 if ( strcmp(childInUmbrella, &myLeaf[1]) == 0 )
247 isSubFramework = true;
250 // LC_SUB_FRAMEWORK is in child, so do nothing in parent
251 if ( ! isSubFramework ) {
252 // this dylib also needs a sub_x load command
253 bool isFrameworkReExport = false;
254 const char* lastSlash = strrchr(dylib->installPath(), '/');
255 if ( lastSlash != NULL ) {
256 char frameworkName[strlen(lastSlash)+20];
257 sprintf(frameworkName, "/%s.framework/", &lastSlash[1]);
258 isFrameworkReExport = (strstr(dylib->installPath(), frameworkName) != NULL);
260 if ( isFrameworkReExport ) {
261 // needs a LC_SUB_UMBRELLA command
262 _subUmbrellaNames.push_back(&lastSlash[1]);
265 // needs a LC_SUB_LIBRARY command
266 const char* nameStart = &lastSlash[1];
267 if ( lastSlash == NULL )
268 nameStart = dylib->installPath();
269 int len = strlen(nameStart);
270 const char* dot = strchr(nameStart, '.');
272 len = dot - nameStart;
273 char* subLibName = new char[len+1];
274 strlcpy(subLibName, nameStart, len+1);
275 _subLibraryNames.push_back(subLibName);
283 template <typename A>
284 uint32_t HeaderAndLoadCommandsAtom<A>::alignedSize(uint32_t size)
286 if ( sizeof(pint_t) == 4 )
287 return ((size+3) & (-4)); // 4-byte align all load commands for 32-bit mach-o
289 return ((size+7) & (-8)); // 8-byte align all load commands for 64-bit mach-o
293 template <typename A>
294 unsigned int HeaderAndLoadCommandsAtom<A>::nonHiddenSectionCount() const
296 unsigned int count = 0;
297 for (std::vector<ld::Internal::FinalSection*>::iterator it = _state.sections.begin(); it != _state.sections.end(); ++it) {
298 if ( ! (*it)->isSectionHidden() && ((*it)->type() != ld::Section::typeTentativeDefs) )
304 template <typename A>
305 unsigned int HeaderAndLoadCommandsAtom<A>::segmentCount() const
307 if ( _options.outputKind() == Options::kObjectFile ) {
308 // .o files have one anonymous segment that contains all sections
312 unsigned int count = 0;
313 const char* lastSegName = "";
314 for (std::vector<ld::Internal::FinalSection*>::iterator it = _state.sections.begin(); it != _state.sections.end(); ++it) {
315 if ( _options.outputKind() == Options::kPreload ) {
316 if ( (*it)->type() == ld::Section::typeMachHeader )
317 continue; // for -preload, don't put hidden __HEADER segment into output
318 if ( (*it)->type() == ld::Section::typeLinkEdit )
319 continue; // for -preload, don't put hidden __LINKEDIT segment into output
321 if ( strcmp(lastSegName, (*it)->segmentName()) != 0 ) {
322 lastSegName = (*it)->segmentName();
330 template <typename A>
331 uint64_t HeaderAndLoadCommandsAtom<A>::size() const
333 uint32_t sz = sizeof(macho_header<P>);
335 sz += sizeof(macho_segment_command<P>) * this->segmentCount();
336 sz += sizeof(macho_section<P>) * this->nonHiddenSectionCount();
338 if ( _hasDylibIDLoadCommand )
339 sz += alignedSize(sizeof(macho_dylib_command<P>) + strlen(_options.installPath()) + 1);
341 if ( _hasDyldInfoLoadCommand )
342 sz += sizeof(macho_dyld_info_command<P>);
344 if ( _hasSymbolTableLoadCommand )
345 sz += sizeof(macho_symtab_command<P>);
347 if ( _hasDynamicSymbolTableLoadCommand )
348 sz += sizeof(macho_dysymtab_command<P>);
350 if ( _hasDyldLoadCommand )
351 sz += alignedSize(sizeof(macho_dylinker_command<P>) + strlen(_options.dyldInstallPath()) + 1);
353 if ( _hasRoutinesLoadCommand )
354 sz += sizeof(macho_routines_command<P>);
356 if ( _hasUUIDLoadCommand )
357 sz += sizeof(macho_uuid_command<P>);
359 if ( _hasVersionLoadCommand )
360 sz += sizeof(macho_version_min_command<P>);
362 if ( _hasSourceVersionLoadCommand )
363 sz += sizeof(macho_source_version_command<P>);
365 if ( _hasThreadLoadCommand )
366 sz += this->threadLoadCommandSize();
368 if ( _hasEntryPointLoadCommand )
369 sz += sizeof(macho_entry_point_command<P>);
371 if ( _hasEncryptionLoadCommand )
372 sz += sizeof(macho_encryption_info_command<P>);
374 if ( _hasSplitSegInfoLoadCommand )
375 sz += sizeof(macho_linkedit_data_command<P>);
377 for(uint32_t ord=1; ord <= _writer.dylibCount(); ++ord) {
378 sz += alignedSize(sizeof(macho_dylib_command<P>) + strlen(_writer.dylibByOrdinal(ord)->installPath()) + 1);
381 if ( _hasRPathLoadCommands ) {
382 const std::vector<const char*>& rpaths = _options.rpaths();
383 for (std::vector<const char*>::const_iterator it = rpaths.begin(); it != rpaths.end(); ++it) {
384 sz += alignedSize(sizeof(macho_rpath_command<P>) + strlen(*it) + 1);
388 if ( _hasSubFrameworkLoadCommand )
389 sz += alignedSize(sizeof(macho_sub_framework_command<P>) + strlen(_options.umbrellaName()) + 1);
391 for (std::vector<const char*>::const_iterator it = _subLibraryNames.begin(); it != _subLibraryNames.end(); ++it) {
392 sz += alignedSize(sizeof(macho_sub_library_command<P>) + strlen(*it) + 1);
395 for (std::vector<const char*>::const_iterator it = _subUmbrellaNames.begin(); it != _subUmbrellaNames.end(); ++it) {
396 sz += alignedSize(sizeof(macho_sub_umbrella_command<P>) + strlen(*it) + 1);
399 if ( _allowableClientLoadCommmandsCount != 0 ) {
400 const std::vector<const char*>& clients = _options.allowableClients();
401 for (std::vector<const char*>::const_iterator it = clients.begin(); it != clients.end(); ++it) {
402 sz += alignedSize(sizeof(macho_sub_client_command<P>) + strlen(*it) + 1);
406 if ( _dyldEnvironExrasCount != 0 ) {
407 const std::vector<const char*>& extras = _options.dyldEnvironExtras();
408 for (std::vector<const char*>::const_iterator it = extras.begin(); it != extras.end(); ++it) {
409 sz += alignedSize(sizeof(macho_dylinker_command<P>) + strlen(*it) + 1);
413 if ( _hasFunctionStartsLoadCommand )
414 sz += sizeof(macho_linkedit_data_command<P>);
416 if ( _hasDataInCodeLoadCommand )
417 sz += sizeof(macho_linkedit_data_command<P>);
419 if ( !_linkerOptions.empty() ) {
420 for (ld::relocatable::File::LinkerOptionsList::const_iterator it = _linkerOptions.begin(); it != _linkerOptions.end(); ++it) {
421 uint32_t s = sizeof(macho_linker_option_command<P>);
422 const std::vector<const char*>& options = *it;
423 for (std::vector<const char*>::const_iterator t=options.begin(); t != options.end(); ++t) {
424 s += (strlen(*t) + 1);
426 sz += alignedSize(s);
430 if ( _hasDependentDRInfo )
431 sz += sizeof(macho_linkedit_data_command<P>);
433 if ( _hasOptimizationHints )
434 sz += sizeof(macho_linkedit_data_command<P>);
439 template <typename A>
440 uint32_t HeaderAndLoadCommandsAtom<A>::commandsCount() const
442 uint32_t count = this->segmentCount();
444 if ( _hasDylibIDLoadCommand )
447 if ( _hasDyldInfoLoadCommand )
450 if ( _hasSymbolTableLoadCommand )
453 if ( _hasDynamicSymbolTableLoadCommand )
456 if ( _hasDyldLoadCommand )
459 if ( _hasRoutinesLoadCommand )
462 if ( _hasUUIDLoadCommand )
465 if ( _hasVersionLoadCommand )
468 if ( _hasSourceVersionLoadCommand )
471 if ( _hasThreadLoadCommand )
474 if ( _hasEntryPointLoadCommand )
477 if ( _hasEncryptionLoadCommand )
480 if ( _hasSplitSegInfoLoadCommand )
483 count += _dylibLoadCommmandsCount;
485 count += _options.rpaths().size();
487 if ( _hasSubFrameworkLoadCommand )
490 count += _subLibraryNames.size();
492 count += _subUmbrellaNames.size();
494 count += _allowableClientLoadCommmandsCount;
496 count += _dyldEnvironExrasCount;
498 if ( _hasFunctionStartsLoadCommand )
501 if ( _hasDataInCodeLoadCommand )
504 if ( !_linkerOptions.empty() ) {
505 for (ld::relocatable::File::LinkerOptionsList::const_iterator it = _linkerOptions.begin(); it != _linkerOptions.end(); ++it) {
510 if ( _hasDependentDRInfo )
513 if ( _hasOptimizationHints )
519 template <typename A>
520 uint32_t HeaderAndLoadCommandsAtom<A>::fileType() const
522 switch ( _options.outputKind() ) {
523 case Options::kDynamicExecutable:
524 case Options::kStaticExecutable:
526 case Options::kDynamicLibrary:
528 case Options::kDynamicBundle:
530 case Options::kObjectFile:
534 case Options::kPreload:
536 case Options::kKextBundle:
537 return MH_KEXT_BUNDLE;
539 throw "unknonwn mach-o file type";
542 template <typename A>
543 uint32_t HeaderAndLoadCommandsAtom<A>::flags() const
546 if ( _options.outputKind() == Options::kObjectFile ) {
547 if ( _state.allObjectFilesScatterable )
548 bits = MH_SUBSECTIONS_VIA_SYMBOLS;
551 if ( _options.outputKind() == Options::kStaticExecutable ) {
553 if ( _options.positionIndependentExecutable() )
556 else if ( _options.outputKind() == Options::kPreload ) {
558 if ( _options.positionIndependentExecutable() )
563 switch ( _options.nameSpace() ) {
564 case Options::kTwoLevelNameSpace:
565 bits |= MH_TWOLEVEL | MH_NOUNDEFS;
567 case Options::kFlatNameSpace:
569 case Options::kForceFlatNameSpace:
570 bits |= MH_FORCE_FLAT;
573 if ( _state.hasWeakExternalSymbols || _writer.overridesWeakExternalSymbols )
574 bits |= MH_WEAK_DEFINES;
575 if ( _writer.usesWeakExternalSymbols || _state.hasWeakExternalSymbols )
576 bits |= MH_BINDS_TO_WEAK;
577 if ( _options.prebind() )
579 if ( _options.splitSeg() )
580 bits |= MH_SPLIT_SEGS;
581 if ( (_options.outputKind() == Options::kDynamicLibrary)
582 && _writer._noReExportedDylibs
583 && _options.useSimplifiedDylibReExports() ) {
584 bits |= MH_NO_REEXPORTED_DYLIBS;
586 if ( _options.positionIndependentExecutable() && ! _writer.pieDisabled )
588 if ( _options.markAutoDeadStripDylib() )
589 bits |= MH_DEAD_STRIPPABLE_DYLIB;
590 if ( _state.hasThreadLocalVariableDefinitions )
591 bits |= MH_HAS_TLV_DESCRIPTORS;
592 if ( _options.hasNonExecutableHeap() )
593 bits |= MH_NO_HEAP_EXECUTION;
594 if ( _options.markAppExtensionSafe() && (_options.outputKind() == Options::kDynamicLibrary) )
595 bits |= MH_APP_EXTENSION_SAFE;
597 if ( _options.hasExecutableStack() )
598 bits |= MH_ALLOW_STACK_EXECUTION;
603 template <> uint32_t HeaderAndLoadCommandsAtom<x86>::magic() const { return MH_MAGIC; }
604 template <> uint32_t HeaderAndLoadCommandsAtom<x86_64>::magic() const { return MH_MAGIC_64; }
605 template <> uint32_t HeaderAndLoadCommandsAtom<arm>::magic() const { return MH_MAGIC; }
606 template <> uint32_t HeaderAndLoadCommandsAtom<arm64>::magic() const { return MH_MAGIC_64; }
608 template <> uint32_t HeaderAndLoadCommandsAtom<x86>::cpuType() const { return CPU_TYPE_I386; }
609 template <> uint32_t HeaderAndLoadCommandsAtom<x86_64>::cpuType() const { return CPU_TYPE_X86_64; }
610 template <> uint32_t HeaderAndLoadCommandsAtom<arm>::cpuType() const { return CPU_TYPE_ARM; }
611 template <> uint32_t HeaderAndLoadCommandsAtom<arm64>::cpuType() const { return CPU_TYPE_ARM64; }
616 uint32_t HeaderAndLoadCommandsAtom<x86>::cpuSubType() const
618 return CPU_SUBTYPE_I386_ALL;
622 uint32_t HeaderAndLoadCommandsAtom<x86_64>::cpuSubType() const
624 if ( (_options.outputKind() == Options::kDynamicExecutable) && (_state.cpuSubType == CPU_SUBTYPE_X86_64_ALL) && (_options.macosxVersionMin() >= ld::mac10_5) )
625 return (_state.cpuSubType | 0x80000000);
627 return _state.cpuSubType;
631 uint32_t HeaderAndLoadCommandsAtom<arm>::cpuSubType() const
633 return _state.cpuSubType;
637 uint32_t HeaderAndLoadCommandsAtom<arm64>::cpuSubType() const
639 return CPU_SUBTYPE_ARM64_ALL;
644 template <typename A>
645 uint8_t* HeaderAndLoadCommandsAtom<A>::copySingleSegmentLoadCommand(uint8_t* p) const
647 // in .o files there is just one segment load command with a blank name
648 // and all sections under it
649 macho_segment_command<P>* cmd = (macho_segment_command<P>*)p;
650 cmd->set_cmd(macho_segment_command<P>::CMD);
651 cmd->set_segname("");
652 cmd->set_vmaddr(_options.baseAddress());
653 cmd->set_vmsize(0); // updated after sections set
654 cmd->set_fileoff(0); // updated after sections set
655 cmd->set_filesize(0); // updated after sections set
656 cmd->set_maxprot(VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE);
657 cmd->set_initprot(VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE);
658 cmd->set_nsects(this->nonHiddenSectionCount());
660 // add sections array
661 macho_section<P>* msect = (macho_section<P>*)&p[sizeof(macho_segment_command<P>)];
662 for (std::vector<ld::Internal::FinalSection*>::iterator sit = _state.sections.begin(); sit != _state.sections.end(); ++sit) {
663 ld::Internal::FinalSection* fsect = *sit;
664 if ( fsect->isSectionHidden() )
666 if ( fsect->type() == ld::Section::typeTentativeDefs )
668 msect->set_sectname(fsect->sectionName());
669 msect->set_segname(fsect->segmentName());
670 msect->set_addr(fsect->address);
671 msect->set_size(fsect->size);
672 msect->set_offset(fsect->fileOffset);
673 msect->set_align(fsect->alignment);
674 msect->set_reloff((fsect->relocCount == 0) ? 0 : _writer.sectionRelocationsSection->fileOffset + fsect->relocStart * sizeof(macho_relocation_info<P>));
675 msect->set_nreloc(fsect->relocCount);
676 msect->set_flags(sectionFlags(fsect));
677 msect->set_reserved1(fsect->indirectSymTabStartIndex);
678 msect->set_reserved2(fsect->indirectSymTabElementSize);
679 // update segment info
680 if ( cmd->fileoff() == 0 )
681 cmd->set_fileoff(fsect->fileOffset);
682 cmd->set_vmsize(fsect->address + fsect->size - cmd->vmaddr());
683 if ( (fsect->type() != ld::Section::typeZeroFill) && (fsect->type() != ld::Section::typeTentativeDefs) )
684 cmd->set_filesize(fsect->fileOffset + fsect->size - cmd->fileoff());
687 cmd->set_cmdsize(sizeof(macho_segment_command<P>) + cmd->nsects()*sizeof(macho_section<P>));
688 return p + cmd->cmdsize();
692 SegInfo(const char* n, const Options&);
694 uint32_t nonHiddenSectionCount;
697 std::vector<ld::Internal::FinalSection*> sections;
701 SegInfo::SegInfo(const char* n, const Options& opts)
702 : segName(n), nonHiddenSectionCount(0), maxProt(opts.maxSegProtection(n)), initProt(opts.initialSegProtection(n))
707 template <typename A>
708 uint32_t HeaderAndLoadCommandsAtom<A>::sectionFlags(ld::Internal::FinalSection* sect) const
711 switch ( sect->type() ) {
712 case ld::Section::typeUnclassified:
713 if ( strcmp(sect->segmentName(), "__OBJC") == 0 )
714 return S_REGULAR | S_ATTR_NO_DEAD_STRIP;
715 else if ( (strcmp(sect->sectionName(), "__objc_classlist") == 0) && (strcmp(sect->segmentName(), "__DATA") == 0) )
716 return S_REGULAR | S_ATTR_NO_DEAD_STRIP;
717 else if ( (strcmp(sect->sectionName(), "__objc_catlist") == 0) && (strcmp(sect->segmentName(), "__DATA") == 0) )
718 return S_REGULAR | S_ATTR_NO_DEAD_STRIP;
719 else if ( (strncmp(sect->sectionName(), "__objc_superrefs", 16) == 0) && (strcmp(sect->segmentName(), "__DATA") == 0) )
720 return S_REGULAR | S_ATTR_NO_DEAD_STRIP;
721 else if ( (strncmp(sect->sectionName(), "__objc_nlclslist", 16) == 0) && (strcmp(sect->segmentName(), "__DATA") == 0) )
722 return S_REGULAR | S_ATTR_NO_DEAD_STRIP;
723 else if ( (strncmp(sect->sectionName(), "__objc_nlcatlist", 16) == 0) && (strcmp(sect->segmentName(), "__DATA") == 0) )
724 return S_REGULAR | S_ATTR_NO_DEAD_STRIP;
727 case ld::Section::typeCode:
728 bits = S_REGULAR | S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS;
729 if ( sect->hasLocalRelocs && ! _writer.pieDisabled )
730 bits |= S_ATTR_LOC_RELOC;
731 if ( sect->hasExternalRelocs )
732 bits |= S_ATTR_EXT_RELOC;
734 case ld::Section::typePageZero:
736 case ld::Section::typeImportProxies:
738 case ld::Section::typeLinkEdit:
740 case ld::Section::typeMachHeader:
742 case ld::Section::typeStack:
744 case ld::Section::typeLiteral4:
745 return S_4BYTE_LITERALS;
746 case ld::Section::typeLiteral8:
747 return S_8BYTE_LITERALS;
748 case ld::Section::typeLiteral16:
749 return S_16BYTE_LITERALS;
750 case ld::Section::typeConstants:
752 case ld::Section::typeTempLTO:
753 assert(0 && "typeTempLTO should not make it to final linked image");
755 case ld::Section::typeTempAlias:
756 assert(0 && "typeAlias should not make it to final linked image");
758 case ld::Section::typeAbsoluteSymbols:
759 assert(0 && "typeAbsoluteSymbols should not make it to final linked image");
761 case ld::Section::typeCString:
762 case ld::Section::typeNonStdCString:
763 return S_CSTRING_LITERALS;
764 case ld::Section::typeCStringPointer:
765 return S_LITERAL_POINTERS | S_ATTR_NO_DEAD_STRIP;
766 case ld::Section::typeUTF16Strings:
768 case ld::Section::typeCFString:
770 case ld::Section::typeObjC1Classes:
771 return S_REGULAR | S_ATTR_NO_DEAD_STRIP;
772 case ld::Section::typeCFI:
774 case ld::Section::typeLSDA:
776 case ld::Section::typeDtraceDOF:
778 case ld::Section::typeUnwindInfo:
780 case ld::Section::typeObjCClassRefs:
781 case ld::Section::typeObjC2CategoryList:
782 return S_REGULAR | S_ATTR_NO_DEAD_STRIP;
783 case ld::Section::typeZeroFill:
784 if ( _options.optimizeZeroFill() )
788 case ld::Section::typeTentativeDefs:
789 assert(0 && "typeTentativeDefs should not make it to final linked image");
791 case ld::Section::typeLazyPointer:
792 case ld::Section::typeLazyPointerClose:
793 return S_LAZY_SYMBOL_POINTERS;
794 case ld::Section::typeStubClose:
795 case ld::Section::typeStub:
796 if ( sect->hasLocalRelocs )
797 return S_SYMBOL_STUBS | S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS | S_ATTR_LOC_RELOC;
799 return S_SYMBOL_STUBS | S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS;
800 case ld::Section::typeNonLazyPointer:
801 if ( _options.outputKind() == Options::kKextBundle )
803 else if ( (_options.outputKind() == Options::kStaticExecutable) && _options.positionIndependentExecutable() )
806 return S_NON_LAZY_SYMBOL_POINTERS;
807 case ld::Section::typeDyldInfo:
809 case ld::Section::typeLazyDylibPointer:
810 return S_LAZY_DYLIB_SYMBOL_POINTERS;
811 case ld::Section::typeStubHelper:
812 if ( sect->hasLocalRelocs )
813 return S_REGULAR | S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS | S_ATTR_LOC_RELOC;
815 return S_REGULAR | S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS;
816 case ld::Section::typeInitializerPointers:
817 // <rdar://problem/11456679> i386 kexts need different section type
818 if ( (_options.outputKind() == Options::kObjectFile)
819 && (strcmp(sect->sectionName(), "__constructor") == 0)
820 && (strcmp(sect->segmentName(), "__TEXT") == 0) )
823 return S_MOD_INIT_FUNC_POINTERS;
824 case ld::Section::typeTerminatorPointers:
825 return S_MOD_TERM_FUNC_POINTERS;
826 case ld::Section::typeTLVInitialValues:
827 return S_THREAD_LOCAL_REGULAR;
828 case ld::Section::typeTLVZeroFill:
829 return S_THREAD_LOCAL_ZEROFILL;
830 case ld::Section::typeTLVDefs:
831 return S_THREAD_LOCAL_VARIABLES;
832 case ld::Section::typeTLVInitializerPointers:
833 return S_THREAD_LOCAL_INIT_FUNCTION_POINTERS;
834 case ld::Section::typeTLVPointers:
835 return S_THREAD_LOCAL_VARIABLE_POINTERS;
836 case ld::Section::typeFirstSection:
837 assert(0 && "typeFirstSection should not make it to final linked image");
839 case ld::Section::typeLastSection:
840 assert(0 && "typeLastSection should not make it to final linked image");
842 case ld::Section::typeDebug:
843 return S_REGULAR | S_ATTR_DEBUG;
849 template <typename A>
850 bool HeaderAndLoadCommandsAtom<A>::sectionTakesNoDiskSpace(ld::Internal::FinalSection* sect) const
852 switch ( sect->type() ) {
853 case ld::Section::typeZeroFill:
854 case ld::Section::typeTLVZeroFill:
855 return _options.optimizeZeroFill();
856 case ld::Section::typeAbsoluteSymbols:
857 case ld::Section::typeTentativeDefs:
858 case ld::Section::typeLastSection:
867 template <typename A>
868 uint8_t* HeaderAndLoadCommandsAtom<A>::copySegmentLoadCommands(uint8_t* p) const
870 // group sections into segments
871 std::vector<SegInfo> segs;
872 const char* lastSegName = "";
873 for (std::vector<ld::Internal::FinalSection*>::iterator it = _state.sections.begin(); it != _state.sections.end(); ++it) {
874 ld::Internal::FinalSection* sect = *it;
875 if ( _options.outputKind() == Options::kPreload ) {
876 if ( (*it)->type() == ld::Section::typeMachHeader )
877 continue; // for -preload, don't put hidden __HEADER segment into output
878 if ( (*it)->type() == ld::Section::typeLinkEdit )
879 continue; // for -preload, don't put hidden __LINKEDIT segment into output
881 if ( strcmp(lastSegName, sect->segmentName()) != 0 ) {
882 SegInfo si(sect->segmentName(), _options);
884 lastSegName = sect->segmentName();
886 if ( ! sect->isSectionHidden() )
887 segs.back().nonHiddenSectionCount++;
888 segs.back().sections.push_back(sect);
890 // write out segment load commands for each section with trailing sections
891 for (std::vector<SegInfo>::iterator it = segs.begin(); it != segs.end(); ++it) {
893 ld::Internal::FinalSection* lastNonZeroFillSection = NULL;
894 for (int i=si.sections.size()-1; i >= 0; --i) {
895 if ( !sectionTakesNoDiskSpace(si.sections[i]) ) {
896 lastNonZeroFillSection = si.sections[i];
900 uint64_t vmsize = si.sections.back()->address + si.sections.back()->size - si.sections.front()->address;
901 vmsize = ((vmsize+_options.segmentAlignment()-1) & (-_options.segmentAlignment()));
902 uint64_t filesize = 0;
903 if ( lastNonZeroFillSection != NULL ) {
904 filesize = lastNonZeroFillSection->address + lastNonZeroFillSection->size - si.sections.front()->address;
905 // round up all segments to page aligned, except __LINKEDIT
906 if ( (si.sections[0]->type() != ld::Section::typeLinkEdit) && (si.sections[0]->type() != ld::Section::typeImportProxies) )
907 filesize = (filesize + _options.segmentAlignment()-1) & (-_options.segmentAlignment());
909 if ( si.sections.front()->type() == ld::Section::typePageZero )
911 else if ( si.sections.front()->type() == ld::Section::typeStack )
913 macho_segment_command<P>* segCmd = (macho_segment_command<P>*)p;
914 segCmd->set_cmd(macho_segment_command<P>::CMD);
915 segCmd->set_cmdsize(sizeof(macho_segment_command<P>) + si.nonHiddenSectionCount*sizeof(macho_section<P>));
916 segCmd->set_segname(si.sections.front()->segmentName());
917 segCmd->set_vmaddr(si.sections.front()->address);
918 segCmd->set_vmsize(vmsize);
919 segCmd->set_fileoff(si.sections.front()->fileOffset);
920 segCmd->set_filesize(filesize);
921 segCmd->set_maxprot(si.maxProt);
922 segCmd->set_initprot(si.initProt);
923 segCmd->set_nsects(si.nonHiddenSectionCount);
924 segCmd->set_flags(0);
925 p += sizeof(macho_segment_command<P>);
926 macho_section<P>* msect = (macho_section<P>*)p;
927 for (std::vector<ld::Internal::FinalSection*>::iterator sit = si.sections.begin(); sit != si.sections.end(); ++sit) {
928 ld::Internal::FinalSection* fsect = *sit;
929 if ( ! fsect->isSectionHidden() ) {
930 msect->set_sectname(fsect->sectionName());
931 msect->set_segname(fsect->segmentName());
932 msect->set_addr(fsect->address);
933 msect->set_size(fsect->size);
934 msect->set_offset(sectionTakesNoDiskSpace(fsect) ? 0 : fsect->fileOffset);
935 msect->set_align(fsect->alignment);
936 msect->set_reloff(0);
937 msect->set_nreloc(0);
938 msect->set_flags(sectionFlags(fsect));
939 msect->set_reserved1(fsect->indirectSymTabStartIndex);
940 msect->set_reserved2(fsect->indirectSymTabElementSize);
941 p += sizeof(macho_section<P>);
951 template <typename A>
952 uint8_t* HeaderAndLoadCommandsAtom<A>::copySymbolTableLoadCommand(uint8_t* p) const
954 // build LC_SYMTAB command
955 macho_symtab_command<P>* symbolTableCmd = (macho_symtab_command<P>*)p;
956 symbolTableCmd->set_cmd(LC_SYMTAB);
957 symbolTableCmd->set_cmdsize(sizeof(macho_symtab_command<P>));
958 symbolTableCmd->set_nsyms(_writer.symbolTableSection->size/sizeof(macho_nlist<P>));
959 symbolTableCmd->set_symoff(_writer.symbolTableSection->size == 0 ? 0 : _writer.symbolTableSection->fileOffset);
960 symbolTableCmd->set_stroff(_writer.stringPoolSection->size == 0 ? 0 : _writer.stringPoolSection->fileOffset );
961 symbolTableCmd->set_strsize(_writer.stringPoolSection->size);
962 return p + sizeof(macho_symtab_command<P>);
965 template <typename A>
966 uint8_t* HeaderAndLoadCommandsAtom<A>::copyDynamicSymbolTableLoadCommand(uint8_t* p) const
968 // build LC_SYMTAB command
969 macho_dysymtab_command<P>* dynamicSymbolTableCmd = (macho_dysymtab_command<P>*)p;
970 dynamicSymbolTableCmd->set_cmd(LC_DYSYMTAB);
971 dynamicSymbolTableCmd->set_cmdsize(sizeof(macho_dysymtab_command<P>));
972 dynamicSymbolTableCmd->set_ilocalsym(0);
973 dynamicSymbolTableCmd->set_nlocalsym(_writer._localSymbolsCount);
974 dynamicSymbolTableCmd->set_iextdefsym(dynamicSymbolTableCmd->ilocalsym()+dynamicSymbolTableCmd->nlocalsym());
975 dynamicSymbolTableCmd->set_nextdefsym(_writer._globalSymbolsCount);
976 dynamicSymbolTableCmd->set_iundefsym(dynamicSymbolTableCmd->iextdefsym()+dynamicSymbolTableCmd->nextdefsym());
977 dynamicSymbolTableCmd->set_nundefsym(_writer._importSymbolsCount);
979 // FIX ME: support for 10.3 dylibs which need modules
980 //if ( fWriter.fModuleInfoAtom != NULL ) {
981 // dynamicSymbolTableCmd->set_tocoff(fWriter.fModuleInfoAtom->getTableOfContentsFileOffset());
982 // dynamicSymbolTableCmd->set_ntoc(fWriter.fSymbolTableExportCount);
983 // dynamicSymbolTableCmd->set_modtaboff(fWriter.fModuleInfoAtom->getModuleTableFileOffset());
984 // dynamicSymbolTableCmd->set_nmodtab(1);
985 // dynamicSymbolTableCmd->set_extrefsymoff(fWriter.fModuleInfoAtom->getReferencesFileOffset());
986 // dynamicSymbolTableCmd->set_nextrefsyms(fWriter.fModuleInfoAtom->getReferencesCount());
989 bool hasIndirectSymbols = ( (_writer.indirectSymbolTableSection != NULL) && (_writer.indirectSymbolTableSection->size != 0) );
990 dynamicSymbolTableCmd->set_indirectsymoff(hasIndirectSymbols ? _writer.indirectSymbolTableSection->fileOffset : 0);
991 dynamicSymbolTableCmd->set_nindirectsyms( hasIndirectSymbols ? _writer.indirectSymbolTableSection->size/sizeof(uint32_t) : 0);
993 // FIX ME: support for classic relocations
994 if ( _options.outputKind() != Options::kObjectFile ) {
995 bool hasExternalRelocs = ( (_writer.externalRelocationsSection != NULL) && (_writer.externalRelocationsSection->size != 0) );
996 dynamicSymbolTableCmd->set_extreloff(hasExternalRelocs ? _writer.externalRelocationsSection->fileOffset : 0);
997 dynamicSymbolTableCmd->set_nextrel( hasExternalRelocs ? _writer.externalRelocationsSection->size/8 : 0);
998 bool hasLocalRelocs = ( (_writer.localRelocationsSection != NULL) && (_writer.localRelocationsSection->size != 0) );
999 dynamicSymbolTableCmd->set_locreloff(hasLocalRelocs ? _writer.localRelocationsSection->fileOffset : 0);
1000 dynamicSymbolTableCmd->set_nlocrel (hasLocalRelocs ? _writer.localRelocationsSection->size/8 : 0);
1002 return p + sizeof(macho_dysymtab_command<P>);
1006 template <typename A>
1007 uint8_t* HeaderAndLoadCommandsAtom<A>::copyDyldInfoLoadCommand(uint8_t* p) const
1009 // build LC_DYLD_INFO command
1010 macho_dyld_info_command<P>* cmd = (macho_dyld_info_command<P>*)p;
1012 cmd->set_cmd(LC_DYLD_INFO_ONLY);
1013 cmd->set_cmdsize(sizeof(macho_dyld_info_command<P>));
1014 if ( _writer.rebaseSection->size != 0 ) {
1015 cmd->set_rebase_off(_writer.rebaseSection->fileOffset);
1016 cmd->set_rebase_size(_writer.rebaseSection->size);
1018 if ( _writer.bindingSection->size != 0 ) {
1019 cmd->set_bind_off(_writer.bindingSection->fileOffset);
1020 cmd->set_bind_size(_writer.bindingSection->size);
1022 if ( _writer.weakBindingSection->size != 0 ) {
1023 cmd->set_weak_bind_off(_writer.weakBindingSection->fileOffset);
1024 cmd->set_weak_bind_size(_writer.weakBindingSection->size);
1026 if ( _writer.lazyBindingSection->size != 0 ) {
1027 cmd->set_lazy_bind_off(_writer.lazyBindingSection->fileOffset);
1028 cmd->set_lazy_bind_size(_writer.lazyBindingSection->size);
1030 if ( _writer.exportSection->size != 0 ) {
1031 cmd->set_export_off(_writer.exportSection->fileOffset);
1032 cmd->set_export_size(_writer.exportSection->size);
1034 return p + sizeof(macho_dyld_info_command<P>);
1038 template <typename A>
1039 uint8_t* HeaderAndLoadCommandsAtom<A>::copyDyldLoadCommand(uint8_t* p) const
1041 uint32_t sz = alignedSize(sizeof(macho_dylinker_command<P>) + strlen(_options.dyldInstallPath()) + 1);
1042 macho_dylinker_command<P>* cmd = (macho_dylinker_command<P>*)p;
1043 if ( _options.outputKind() == Options::kDyld )
1044 cmd->set_cmd(LC_ID_DYLINKER);
1046 cmd->set_cmd(LC_LOAD_DYLINKER);
1047 cmd->set_cmdsize(sz);
1048 cmd->set_name_offset();
1049 strcpy((char*)&p[sizeof(macho_dylinker_command<P>)], _options.dyldInstallPath());
1054 template <typename A>
1055 uint8_t* HeaderAndLoadCommandsAtom<A>::copyDylibIDLoadCommand(uint8_t* p) const
1057 uint32_t sz = alignedSize(sizeof(macho_dylib_command<P>) + strlen(_options.installPath()) + 1);
1058 macho_dylib_command<P>* cmd = (macho_dylib_command<P>*)p;
1059 cmd->set_cmd(LC_ID_DYLIB);
1060 cmd->set_cmdsize(sz);
1061 cmd->set_name_offset();
1062 cmd->set_timestamp(1); // needs to be some constant value that is different than DylibLoadCommandsAtom uses
1063 cmd->set_current_version(_options.currentVersion32());
1064 cmd->set_compatibility_version(_options.compatibilityVersion());
1065 strcpy((char*)&p[sizeof(macho_dylib_command<P>)], _options.installPath());
1069 template <typename A>
1070 uint8_t* HeaderAndLoadCommandsAtom<A>::copyRoutinesLoadCommand(uint8_t* p) const
1072 pint_t initAddr = _state.entryPoint->finalAddress();
1073 if ( _state.entryPoint->isThumb() )
1075 macho_routines_command<P>* cmd = (macho_routines_command<P>*)p;
1076 cmd->set_cmd(macho_routines_command<P>::CMD);
1077 cmd->set_cmdsize(sizeof(macho_routines_command<P>));
1078 cmd->set_init_address(initAddr);
1079 return p + sizeof(macho_routines_command<P>);
1083 template <typename A>
1084 void HeaderAndLoadCommandsAtom<A>::recopyUUIDCommand()
1086 assert(_uuidCmdInOutputBuffer != NULL);
1087 _uuidCmdInOutputBuffer->set_uuid(_uuid);
1091 template <typename A>
1092 uint8_t* HeaderAndLoadCommandsAtom<A>::copyUUIDLoadCommand(uint8_t* p) const
1094 macho_uuid_command<P>* cmd = (macho_uuid_command<P>*)p;
1095 cmd->set_cmd(LC_UUID);
1096 cmd->set_cmdsize(sizeof(macho_uuid_command<P>));
1097 cmd->set_uuid(_uuid);
1098 _uuidCmdInOutputBuffer = cmd; // save for later re-write by recopyUUIDCommand()
1099 return p + sizeof(macho_uuid_command<P>);
1103 template <typename A>
1104 uint8_t* HeaderAndLoadCommandsAtom<A>::copyVersionLoadCommand(uint8_t* p) const
1106 macho_version_min_command<P>* cmd = (macho_version_min_command<P>*)p;
1107 ld::MacVersionMin macVersion = _options.macosxVersionMin();
1108 ld::IOSVersionMin iOSVersion = _options.iOSVersionMin();
1109 assert( (macVersion != ld::macVersionUnset) || (iOSVersion != ld::iOSVersionUnset) );
1110 if ( macVersion != ld::macVersionUnset ) {
1111 cmd->set_cmd(LC_VERSION_MIN_MACOSX);
1112 cmd->set_cmdsize(sizeof(macho_version_min_command<P>));
1113 cmd->set_version((uint32_t)macVersion);
1114 cmd->set_sdk(_options.sdkVersion());
1117 cmd->set_cmd(LC_VERSION_MIN_IPHONEOS);
1118 cmd->set_cmdsize(sizeof(macho_version_min_command<P>));
1119 cmd->set_version((uint32_t)iOSVersion);
1120 cmd->set_sdk(_options.sdkVersion());
1122 return p + sizeof(macho_version_min_command<P>);
1125 template <typename A>
1126 uint8_t* HeaderAndLoadCommandsAtom<A>::copySourceVersionLoadCommand(uint8_t* p) const
1128 macho_source_version_command<P>* cmd = (macho_source_version_command<P>*)p;
1129 cmd->set_cmd(LC_SOURCE_VERSION);
1130 cmd->set_cmdsize(sizeof(macho_source_version_command<P>));
1131 cmd->set_version(_options.sourceVersion());
1132 return p + sizeof(macho_source_version_command<P>);
1137 uint32_t HeaderAndLoadCommandsAtom<x86>::threadLoadCommandSize() const
1139 return this->alignedSize(16 + 16*4); // base size + i386_THREAD_STATE_COUNT * 4
1143 uint8_t* HeaderAndLoadCommandsAtom<x86>::copyThreadsLoadCommand(uint8_t* p) const
1145 assert(_state.entryPoint != NULL);
1146 pint_t start = _state.entryPoint->finalAddress();
1147 macho_thread_command<P>* cmd = (macho_thread_command<P>*)p;
1148 cmd->set_cmd(LC_UNIXTHREAD);
1149 cmd->set_cmdsize(threadLoadCommandSize());
1150 cmd->set_flavor(1); // i386_THREAD_STATE
1151 cmd->set_count(16); // i386_THREAD_STATE_COUNT;
1152 cmd->set_thread_register(10, start);
1153 if ( _options.hasCustomStack() )
1154 cmd->set_thread_register(7, _options.customStackAddr()); // r1
1155 return p + threadLoadCommandSize();
1159 uint32_t HeaderAndLoadCommandsAtom<x86_64>::threadLoadCommandSize() const
1161 return this->alignedSize(16 + x86_THREAD_STATE64_COUNT * 4);
1165 uint8_t* HeaderAndLoadCommandsAtom<x86_64>::copyThreadsLoadCommand(uint8_t* p) const
1167 assert(_state.entryPoint != NULL);
1168 pint_t start = _state.entryPoint->finalAddress();
1169 macho_thread_command<P>* cmd = (macho_thread_command<P>*)p;
1170 cmd->set_cmd(LC_UNIXTHREAD);
1171 cmd->set_cmdsize(threadLoadCommandSize());
1172 cmd->set_flavor(x86_THREAD_STATE64);
1173 cmd->set_count(x86_THREAD_STATE64_COUNT);
1174 cmd->set_thread_register(16, start); // rip
1175 if ( _options.hasCustomStack() )
1176 cmd->set_thread_register(7, _options.customStackAddr()); // r1
1177 return p + threadLoadCommandSize();
1181 uint32_t HeaderAndLoadCommandsAtom<arm>::threadLoadCommandSize() const
1183 return this->alignedSize(16 + 17 * 4); // base size + ARM_THREAD_STATE_COUNT * 4
1187 uint8_t* HeaderAndLoadCommandsAtom<arm>::copyThreadsLoadCommand(uint8_t* p) const
1189 assert(_state.entryPoint != NULL);
1190 pint_t start = _state.entryPoint->finalAddress();
1191 if ( _state.entryPoint->isThumb() )
1193 macho_thread_command<P>* cmd = (macho_thread_command<P>*)p;
1194 cmd->set_cmd(LC_UNIXTHREAD);
1195 cmd->set_cmdsize(threadLoadCommandSize());
1198 cmd->set_thread_register(15, start); // pc
1199 if ( _options.hasCustomStack() )
1200 cmd->set_thread_register(13, _options.customStackAddr()); // sp
1201 return p + threadLoadCommandSize();
1206 uint32_t HeaderAndLoadCommandsAtom<arm64>::threadLoadCommandSize() const
1208 return this->alignedSize(16 + 34 * 8); // base size + ARM_EXCEPTION_STATE64_COUNT * 4
1212 uint8_t* HeaderAndLoadCommandsAtom<arm64>::copyThreadsLoadCommand(uint8_t* p) const
1214 assert(_state.entryPoint != NULL);
1215 pint_t start = _state.entryPoint->finalAddress();
1216 macho_thread_command<P>* cmd = (macho_thread_command<P>*)p;
1217 cmd->set_cmd(LC_UNIXTHREAD);
1218 cmd->set_cmdsize(threadLoadCommandSize());
1219 cmd->set_flavor(6); // ARM_THREAD_STATE64
1220 cmd->set_count(68); // ARM_EXCEPTION_STATE64_COUNT
1221 cmd->set_thread_register(32, start); // pc
1222 if ( _options.hasCustomStack() )
1223 cmd->set_thread_register(31, _options.customStackAddr()); // sp
1224 return p + threadLoadCommandSize();
1228 template <typename A>
1229 uint8_t* HeaderAndLoadCommandsAtom<A>::copyEntryPointLoadCommand(uint8_t* p) const
1231 macho_entry_point_command<P>* cmd = (macho_entry_point_command<P>*)p;
1232 cmd->set_cmd(LC_MAIN);
1233 cmd->set_cmdsize(sizeof(macho_entry_point_command<P>));
1234 assert(_state.entryPoint != NULL);
1235 pint_t start = _state.entryPoint->finalAddress();
1236 if ( _state.entryPoint->isThumb() )
1238 cmd->set_entryoff(start - this->finalAddress());
1239 cmd->set_stacksize(_options.hasCustomStack() ? _options.customStackSize() : 0 );
1240 return p + sizeof(macho_entry_point_command<P>);
1244 template <typename A>
1245 uint8_t* HeaderAndLoadCommandsAtom<A>::copyEncryptionLoadCommand(uint8_t* p) const
1247 macho_encryption_info_command<P>* cmd = (macho_encryption_info_command<P>*)p;
1248 cmd->set_cmd(sizeof(typename A::P::uint_t) == 4 ? LC_ENCRYPTION_INFO : LC_ENCRYPTION_INFO_64);
1249 cmd->set_cmdsize(sizeof(macho_encryption_info_command<P>));
1250 assert(_writer.encryptedTextStartOffset() != 0);
1251 assert(_writer.encryptedTextEndOffset() != 0);
1252 cmd->set_cryptoff(_writer.encryptedTextStartOffset());
1253 cmd->set_cryptsize(_writer.encryptedTextEndOffset()-_writer.encryptedTextStartOffset());
1254 cmd->set_cryptid(0);
1255 return p + sizeof(macho_encryption_info_command<P>);
1259 template <typename A>
1260 uint8_t* HeaderAndLoadCommandsAtom<A>::copySplitSegInfoLoadCommand(uint8_t* p) const
1262 macho_linkedit_data_command<P>* cmd = (macho_linkedit_data_command<P>*)p;
1263 cmd->set_cmd(LC_SEGMENT_SPLIT_INFO);
1264 cmd->set_cmdsize(sizeof(macho_linkedit_data_command<P>));
1265 cmd->set_dataoff(_writer.splitSegInfoSection->fileOffset);
1266 cmd->set_datasize(_writer.splitSegInfoSection->size);
1267 return p + sizeof(macho_linkedit_data_command<P>);
1271 template <typename A>
1272 uint8_t* HeaderAndLoadCommandsAtom<A>::copyDylibLoadCommand(uint8_t* p, const ld::dylib::File* dylib) const
1274 uint32_t sz = alignedSize(sizeof(macho_dylib_command<P>) + strlen(dylib->installPath()) + 1);
1275 macho_dylib_command<P>* cmd = (macho_dylib_command<P>*)p;
1276 if ( dylib->willBeLazyLoadedDylib() )
1277 cmd->set_cmd(LC_LAZY_LOAD_DYLIB);
1278 else if ( dylib->forcedWeakLinked() || dylib->allSymbolsAreWeakImported() )
1279 cmd->set_cmd(LC_LOAD_WEAK_DYLIB);
1280 else if ( dylib->willBeReExported() && _options.useSimplifiedDylibReExports() )
1281 cmd->set_cmd(LC_REEXPORT_DYLIB);
1282 else if ( dylib->willBeUpwardDylib() && _options.useUpwardDylibs() )
1283 cmd->set_cmd(LC_LOAD_UPWARD_DYLIB);
1285 cmd->set_cmd(LC_LOAD_DYLIB);
1286 cmd->set_cmdsize(sz);
1287 cmd->set_timestamp(2); // needs to be some constant value that is different than DylibIDLoadCommandsAtom uses
1288 cmd->set_current_version(dylib->currentVersion());
1289 cmd->set_compatibility_version(dylib->compatibilityVersion());
1290 cmd->set_name_offset();
1291 strcpy((char*)&p[sizeof(macho_dylib_command<P>)], dylib->installPath());
1295 template <typename A>
1296 uint8_t* HeaderAndLoadCommandsAtom<A>::copyRPathLoadCommand(uint8_t* p, const char* path) const
1298 uint32_t sz = alignedSize(sizeof(macho_rpath_command<P>) + strlen(path) + 1);
1299 macho_rpath_command<P>* cmd = (macho_rpath_command<P>*)p;
1300 cmd->set_cmd(LC_RPATH);
1301 cmd->set_cmdsize(sz);
1302 cmd->set_path_offset();
1303 strcpy((char*)&p[sizeof(macho_rpath_command<P>)], path);
1307 template <typename A>
1308 uint8_t* HeaderAndLoadCommandsAtom<A>::copySubFrameworkLoadCommand(uint8_t* p) const
1310 const char* umbrellaName = _options.umbrellaName();
1311 uint32_t sz = alignedSize(sizeof(macho_sub_framework_command<P>) + strlen(umbrellaName) + 1);
1312 macho_sub_framework_command<P>* cmd = (macho_sub_framework_command<P>*)p;
1313 cmd->set_cmd(LC_SUB_FRAMEWORK);
1314 cmd->set_cmdsize(sz);
1315 cmd->set_umbrella_offset();
1316 strcpy((char*)&p[sizeof(macho_sub_framework_command<P>)], umbrellaName);
1321 template <typename A>
1322 uint8_t* HeaderAndLoadCommandsAtom<A>::copyAllowableClientLoadCommand(uint8_t* p, const char* client) const
1324 uint32_t sz = alignedSize(sizeof(macho_sub_client_command<P>) + strlen(client) + 1);
1325 macho_sub_client_command<P>* cmd = (macho_sub_client_command<P>*)p;
1326 cmd->set_cmd(LC_SUB_CLIENT);
1327 cmd->set_cmdsize(sz);
1328 cmd->set_client_offset();
1329 strcpy((char*)&p[sizeof(macho_sub_client_command<P>)], client);
1333 template <typename A>
1334 uint8_t* HeaderAndLoadCommandsAtom<A>::copyDyldEnvLoadCommand(uint8_t* p, const char* env) const
1336 uint32_t sz = alignedSize(sizeof(macho_dylinker_command<P>) + strlen(env) + 1);
1337 macho_dylinker_command<P>* cmd = (macho_dylinker_command<P>*)p;
1338 cmd->set_cmd(LC_DYLD_ENVIRONMENT);
1339 cmd->set_cmdsize(sz);
1340 cmd->set_name_offset();
1341 strcpy((char*)&p[sizeof(macho_dylinker_command<P>)], env);
1345 template <typename A>
1346 uint8_t* HeaderAndLoadCommandsAtom<A>::copySubUmbrellaLoadCommand(uint8_t* p, const char* nm) const
1348 uint32_t sz = alignedSize(sizeof(macho_sub_umbrella_command<P>) + strlen(nm) + 1);
1349 macho_sub_umbrella_command<P>* cmd = (macho_sub_umbrella_command<P>*)p;
1350 cmd->set_cmd(LC_SUB_UMBRELLA);
1351 cmd->set_cmdsize(sz);
1352 cmd->set_sub_umbrella_offset();
1353 strcpy((char*)&p[sizeof(macho_sub_umbrella_command<P>)], nm);
1357 template <typename A>
1358 uint8_t* HeaderAndLoadCommandsAtom<A>::copySubLibraryLoadCommand(uint8_t* p, const char* nm) const
1360 uint32_t sz = alignedSize(sizeof(macho_sub_library_command<P>) + strlen(nm) + 1);
1361 macho_sub_library_command<P>* cmd = (macho_sub_library_command<P>*)p;
1362 cmd->set_cmd(LC_SUB_LIBRARY);
1363 cmd->set_cmdsize(sz);
1364 cmd->set_sub_library_offset();
1365 strcpy((char*)&p[sizeof(macho_sub_library_command<P>)], nm);
1369 template <typename A>
1370 uint8_t* HeaderAndLoadCommandsAtom<A>::copyFunctionStartsLoadCommand(uint8_t* p) const
1372 macho_linkedit_data_command<P>* cmd = (macho_linkedit_data_command<P>*)p;
1373 cmd->set_cmd(LC_FUNCTION_STARTS);
1374 cmd->set_cmdsize(sizeof(macho_linkedit_data_command<P>));
1375 cmd->set_dataoff(_writer.functionStartsSection->fileOffset);
1376 cmd->set_datasize(_writer.functionStartsSection->size);
1377 return p + sizeof(macho_linkedit_data_command<P>);
1381 template <typename A>
1382 uint8_t* HeaderAndLoadCommandsAtom<A>::copyDataInCodeLoadCommand(uint8_t* p) const
1384 macho_linkedit_data_command<P>* cmd = (macho_linkedit_data_command<P>*)p;
1385 cmd->set_cmd(LC_DATA_IN_CODE);
1386 cmd->set_cmdsize(sizeof(macho_linkedit_data_command<P>));
1387 cmd->set_dataoff(_writer.dataInCodeSection->fileOffset);
1388 cmd->set_datasize(_writer.dataInCodeSection->size);
1389 return p + sizeof(macho_linkedit_data_command<P>);
1393 template <typename A>
1394 uint8_t* HeaderAndLoadCommandsAtom<A>::copyLinkerOptionsLoadCommand(uint8_t* p, const std::vector<const char*>& options) const
1396 macho_linker_option_command<P>* cmd = (macho_linker_option_command<P>*)p;
1397 cmd->set_cmd(LC_LINKER_OPTION);
1398 cmd->set_count(options.size());
1399 char* buffer = cmd->buffer();
1400 uint32_t sz = sizeof(macho_linker_option_command<P>);
1401 for (std::vector<const char*>::const_iterator it=options.begin(); it != options.end(); ++it) {
1402 const char* opt = *it;
1403 uint32_t len = strlen(opt);
1404 strcpy(buffer, opt);
1406 buffer += (len + 1);
1408 sz = alignedSize(sz);
1409 cmd->set_cmdsize(sz);
1414 template <typename A>
1415 uint8_t* HeaderAndLoadCommandsAtom<A>::copyDependentDRLoadCommand(uint8_t* p) const
1417 macho_linkedit_data_command<P>* cmd = (macho_linkedit_data_command<P>*)p;
1418 cmd->set_cmd(LC_DYLIB_CODE_SIGN_DRS);
1419 cmd->set_cmdsize(sizeof(macho_linkedit_data_command<P>));
1420 cmd->set_dataoff(_writer.dependentDRsSection->fileOffset);
1421 cmd->set_datasize(_writer.dependentDRsSection->size);
1422 return p + sizeof(macho_linkedit_data_command<P>);
1427 template <typename A>
1428 uint8_t* HeaderAndLoadCommandsAtom<A>::copyOptimizationHintsLoadCommand(uint8_t* p) const
1430 macho_linkedit_data_command<P>* cmd = (macho_linkedit_data_command<P>*)p;
1431 cmd->set_cmd(LC_LINKER_OPTIMIZATION_HINTS);
1432 cmd->set_cmdsize(sizeof(macho_linkedit_data_command<P>));
1433 cmd->set_dataoff(_writer.optimizationHintsSection->fileOffset);
1434 cmd->set_datasize(_writer.optimizationHintsSection->size);
1435 return p + sizeof(macho_linkedit_data_command<P>);
1439 template <typename A>
1440 void HeaderAndLoadCommandsAtom<A>::copyRawContent(uint8_t buffer[]) const
1442 macho_header<P>* mh = (macho_header<P>*)buffer;
1443 bzero(buffer, this->size());
1446 mh->set_magic(this->magic());
1447 mh->set_cputype(this->cpuType());
1448 mh->set_cpusubtype(this->cpuSubType());
1449 mh->set_filetype(this->fileType());
1450 mh->set_ncmds(this->commandsCount());
1451 mh->set_sizeofcmds(this->size()-sizeof(macho_header<P>));
1452 mh->set_flags(this->flags());
1454 // copy load commands
1455 uint8_t* p = &buffer[sizeof(macho_header<P>)];
1457 if ( _options.outputKind() == Options::kObjectFile )
1458 p = this->copySingleSegmentLoadCommand(p);
1460 p = this->copySegmentLoadCommands(p);
1462 if ( _hasDylibIDLoadCommand )
1463 p = this->copyDylibIDLoadCommand(p);
1465 if ( _hasDyldInfoLoadCommand )
1466 p = this->copyDyldInfoLoadCommand(p);
1468 if ( _hasSymbolTableLoadCommand )
1469 p = this->copySymbolTableLoadCommand(p);
1471 if ( _hasDynamicSymbolTableLoadCommand )
1472 p = this->copyDynamicSymbolTableLoadCommand(p);
1474 if ( _hasDyldLoadCommand )
1475 p = this->copyDyldLoadCommand(p);
1477 if ( _hasRoutinesLoadCommand )
1478 p = this->copyRoutinesLoadCommand(p);
1480 if ( _hasUUIDLoadCommand )
1481 p = this->copyUUIDLoadCommand(p);
1483 if ( _hasVersionLoadCommand )
1484 p = this->copyVersionLoadCommand(p);
1486 if ( _hasSourceVersionLoadCommand )
1487 p = this->copySourceVersionLoadCommand(p);
1489 if ( _hasThreadLoadCommand )
1490 p = this->copyThreadsLoadCommand(p);
1492 if ( _hasEntryPointLoadCommand )
1493 p = this->copyEntryPointLoadCommand(p);
1495 if ( _hasEncryptionLoadCommand )
1496 p = this->copyEncryptionLoadCommand(p);
1498 if ( _hasSplitSegInfoLoadCommand )
1499 p = this->copySplitSegInfoLoadCommand(p);
1501 for (uint32_t ord=1; ord <= _writer.dylibCount(); ++ord) {
1502 p = this->copyDylibLoadCommand(p, _writer.dylibByOrdinal(ord));
1505 if ( _hasRPathLoadCommands ) {
1506 const std::vector<const char*>& rpaths = _options.rpaths();
1507 for (std::vector<const char*>::const_iterator it = rpaths.begin(); it != rpaths.end(); ++it) {
1508 p = this->copyRPathLoadCommand(p, *it);
1512 if ( _hasSubFrameworkLoadCommand )
1513 p = this->copySubFrameworkLoadCommand(p);
1515 for (std::vector<const char*>::const_iterator it = _subLibraryNames.begin(); it != _subLibraryNames.end(); ++it) {
1516 p = this->copySubLibraryLoadCommand(p, *it);
1519 for (std::vector<const char*>::const_iterator it = _subUmbrellaNames.begin(); it != _subUmbrellaNames.end(); ++it) {
1520 p = this->copySubUmbrellaLoadCommand(p, *it);
1523 if ( _allowableClientLoadCommmandsCount != 0 ) {
1524 const std::vector<const char*>& clients = _options.allowableClients();
1525 for (std::vector<const char*>::const_iterator it = clients.begin(); it != clients.end(); ++it) {
1526 p = this->copyAllowableClientLoadCommand(p, *it);
1530 if ( _dyldEnvironExrasCount != 0 ) {
1531 const std::vector<const char*>& extras = _options.dyldEnvironExtras();
1532 for (std::vector<const char*>::const_iterator it = extras.begin(); it != extras.end(); ++it) {
1533 p = this->copyDyldEnvLoadCommand(p, *it);
1537 if ( _hasFunctionStartsLoadCommand )
1538 p = this->copyFunctionStartsLoadCommand(p);
1540 if ( _hasDataInCodeLoadCommand )
1541 p = this->copyDataInCodeLoadCommand(p);
1543 if ( !_linkerOptions.empty() ) {
1544 for (ld::relocatable::File::LinkerOptionsList::const_iterator it = _linkerOptions.begin(); it != _linkerOptions.end(); ++it) {
1545 p = this->copyLinkerOptionsLoadCommand(p, *it);
1549 if ( _hasDependentDRInfo )
1550 p = this->copyDependentDRLoadCommand(p);
1552 if ( _hasOptimizationHints )
1553 p = this->copyOptimizationHintsLoadCommand(p);
1562 #endif // __HEADER_LOAD_COMMANDS_HPP__