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 bool translationUnitSource(const char** dir, const char** nm) const
65 virtual const char* name() const { return "mach-o header and load commands"; }
66 virtual uint64_t size() const;
67 virtual uint64_t objectAddress() const { return _address; }
68 virtual void copyRawContent(uint8_t buffer[]) const;
70 // overrides of HeaderAndLoadCommandsAbtract
71 virtual void setUUID(const uint8_t digest[16]) { memcpy(_uuid, digest, 16); }
72 virtual void recopyUUIDCommand();
75 typedef typename A::P P;
76 typedef typename A::P::E E;
77 typedef typename A::P::uint_t pint_t;
79 unsigned int nonHiddenSectionCount() const;
80 unsigned int segmentCount() const;
81 static uint32_t alignedSize(uint32_t x);
82 uint32_t magic() const;
83 uint32_t cpuType() const;
84 uint32_t cpuSubType() const;
85 uint32_t flags() const;
86 uint32_t fileType() const;
87 uint32_t commandsCount() const;
88 uint32_t threadLoadCommandSize() const;
89 uint8_t* copySingleSegmentLoadCommand(uint8_t* p) const;
90 uint8_t* copySegmentLoadCommands(uint8_t* p) const;
91 uint8_t* copyDyldInfoLoadCommand(uint8_t* p) const;
92 uint8_t* copySymbolTableLoadCommand(uint8_t* p) const;
93 uint8_t* copyDynamicSymbolTableLoadCommand(uint8_t* p) const;
94 uint8_t* copyDyldLoadCommand(uint8_t* p) const;
95 uint8_t* copyDylibIDLoadCommand(uint8_t* p) const;
96 uint8_t* copyRoutinesLoadCommand(uint8_t* p) const;
97 uint8_t* copyUUIDLoadCommand(uint8_t* p) const;
98 uint8_t* copyVersionLoadCommand(uint8_t* p) const;
99 uint8_t* copySourceVersionLoadCommand(uint8_t* p) const;
100 uint8_t* copyThreadsLoadCommand(uint8_t* p) const;
101 uint8_t* copyEntryPointLoadCommand(uint8_t* p) const;
102 uint8_t* copyEncryptionLoadCommand(uint8_t* p) const;
103 uint8_t* copySplitSegInfoLoadCommand(uint8_t* p) const;
104 uint8_t* copyDylibLoadCommand(uint8_t* p, const ld::dylib::File*) const;
105 uint8_t* copyRPathLoadCommand(uint8_t* p, const char*) const;
106 uint8_t* copySubFrameworkLoadCommand(uint8_t* p) const;
107 uint8_t* copyAllowableClientLoadCommand(uint8_t* p, const char* client) const;
108 uint8_t* copySubLibraryLoadCommand(uint8_t* p, const char* name) const;
109 uint8_t* copySubUmbrellaLoadCommand(uint8_t* p, const char* name) const;
110 uint8_t* copyFunctionStartsLoadCommand(uint8_t* p) const;
111 uint8_t* copyDataInCodeLoadCommand(uint8_t* p) const;
112 uint8_t* copyDependentDRLoadCommand(uint8_t* p) const;
113 uint8_t* copyDyldEnvLoadCommand(uint8_t* p, const char* env) 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 uint32_t _dylibLoadCommmandsCount;
142 uint32_t _allowableClientLoadCommmandsCount;
143 uint32_t _dyldEnvironExrasCount;
144 std::vector<const char*> _subLibraryNames;
145 std::vector<const char*> _subUmbrellaNames;
147 mutable macho_uuid_command<P>* _uuidCmdInOutputBuffer;
149 static ld::Section _s_section;
150 static ld::Section _s_preload_section;
153 template <typename A>
154 ld::Section HeaderAndLoadCommandsAtom<A>::_s_section("__TEXT", "__mach_header", ld::Section::typeMachHeader, true);
155 template <typename A>
156 ld::Section HeaderAndLoadCommandsAtom<A>::_s_preload_section("__HEADER", "__mach_header", ld::Section::typeMachHeader, true);
159 template <typename A>
160 HeaderAndLoadCommandsAtom<A>::HeaderAndLoadCommandsAtom(const Options& opts, ld::Internal& state, OutputFile& writer)
161 : HeaderAndLoadCommandsAbtract((opts.outputKind() == Options::kPreload) ? _s_preload_section : _s_section,
162 ld::Atom::definitionRegular, ld::Atom::combineNever,
163 ld::Atom::scopeTranslationUnit, ld::Atom::typeUnclassified,
164 ld::Atom::symbolTableNotIn, false, false, false,
165 (opts.outputKind() == Options::kPreload) ? ld::Atom::Alignment(0) : ld::Atom::Alignment(12) ),
166 _options(opts), _state(state), _writer(writer), _address(0), _uuidCmdInOutputBuffer(NULL)
169 _hasDyldInfoLoadCommand = opts.makeCompressedDyldInfo();
170 _hasDyldLoadCommand = ((opts.outputKind() == Options::kDynamicExecutable) || (_options.outputKind() == Options::kDyld));
171 _hasDylibIDLoadCommand = (opts.outputKind() == Options::kDynamicLibrary);
172 _hasThreadLoadCommand = _options.needsThreadLoadCommand();
173 _hasEntryPointLoadCommand = _options.needsEntryPointLoadCommand();
174 _hasEncryptionLoadCommand = opts.makeEncryptable();
175 _hasSplitSegInfoLoadCommand = opts.sharedRegionEligible();
176 _hasRoutinesLoadCommand = (opts.initFunctionName() != NULL);
177 _hasSymbolTableLoadCommand = true;
178 _hasUUIDLoadCommand = (opts.UUIDMode() != Options::kUUIDNone);
179 switch ( opts.outputKind() ) {
180 case Options::kDynamicExecutable:
181 case Options::kDynamicLibrary:
182 case Options::kDynamicBundle:
184 case Options::kKextBundle:
185 _hasDynamicSymbolTableLoadCommand = true;
187 case Options::kObjectFile:
188 if ( ! state.someObjectFileHasDwarf )
189 _hasUUIDLoadCommand = false;
190 _hasDynamicSymbolTableLoadCommand = false;
191 for (std::vector<ld::Internal::FinalSection*>::iterator it = _state.sections.begin(); it != _state.sections.end(); ++it) {
192 if ( (*it)->type() == ld::Section::typeNonLazyPointer ) {
193 _hasDynamicSymbolTableLoadCommand = true;
198 case Options::kStaticExecutable:
199 _hasDynamicSymbolTableLoadCommand = opts.positionIndependentExecutable();
201 case Options::kPreload:
202 _hasDynamicSymbolTableLoadCommand = opts.positionIndependentExecutable();
205 _hasRPathLoadCommands = (_options.rpaths().size() != 0);
206 _hasSubFrameworkLoadCommand = (_options.umbrellaName() != NULL);
207 _hasVersionLoadCommand = _options.addVersionLoadCommand();
208 _hasFunctionStartsLoadCommand = _options.addFunctionStarts();
209 _hasDataInCodeLoadCommand = _options.addDataInCodeInfo();
210 _hasSourceVersionLoadCommand = _options.needsSourceVersionLoadCommand();
211 _hasDependentDRInfo = _options.needsDependentDRInfo();
212 _dylibLoadCommmandsCount = _writer.dylibCount();
213 _allowableClientLoadCommmandsCount = _options.allowableClients().size();
214 _dyldEnvironExrasCount = _options.dyldEnvironExtras().size();
215 if ( ! _options.useSimplifiedDylibReExports() ) {
216 // target OS does not support LC_REEXPORT_DYLIB, so use old complicated load commands
217 for(uint32_t ord=1; ord <= _writer.dylibCount(); ++ord) {
218 const ld::dylib::File* dylib = _writer.dylibByOrdinal(ord);
219 if ( dylib->willBeReExported() ) {
220 // if child says it is an sub-framework of the image being created, then nothing to do here
221 bool isSubFramework = false;
222 const char* childInUmbrella = dylib->parentUmbrella();
223 if ( childInUmbrella != NULL ) {
224 const char* myLeaf = strrchr(_options.installPath(), '/');
225 if ( myLeaf != NULL ) {
226 if ( strcmp(childInUmbrella, &myLeaf[1]) == 0 )
227 isSubFramework = true;
230 // LC_SUB_FRAMEWORK is in child, so do nothing in parent
231 if ( ! isSubFramework ) {
232 // this dylib also needs a sub_x load command
233 bool isFrameworkReExport = false;
234 const char* lastSlash = strrchr(dylib->installPath(), '/');
235 if ( lastSlash != NULL ) {
236 char frameworkName[strlen(lastSlash)+20];
237 sprintf(frameworkName, "/%s.framework/", &lastSlash[1]);
238 isFrameworkReExport = (strstr(dylib->installPath(), frameworkName) != NULL);
240 if ( isFrameworkReExport ) {
241 // needs a LC_SUB_UMBRELLA command
242 _subUmbrellaNames.push_back(&lastSlash[1]);
245 // needs a LC_SUB_LIBRARY command
246 const char* nameStart = &lastSlash[1];
247 if ( lastSlash == NULL )
248 nameStart = dylib->installPath();
249 int len = strlen(nameStart);
250 const char* dot = strchr(nameStart, '.');
252 len = dot - nameStart;
253 char* subLibName = new char[len+1];
254 strlcpy(subLibName, nameStart, len+1);
255 _subLibraryNames.push_back(subLibName);
263 template <typename A>
264 uint32_t HeaderAndLoadCommandsAtom<A>::alignedSize(uint32_t size)
266 if ( sizeof(pint_t) == 4 )
267 return ((size+3) & (-4)); // 4-byte align all load commands for 32-bit mach-o
269 return ((size+7) & (-8)); // 8-byte align all load commands for 64-bit mach-o
273 template <typename A>
274 unsigned int HeaderAndLoadCommandsAtom<A>::nonHiddenSectionCount() const
276 unsigned int count = 0;
277 for (std::vector<ld::Internal::FinalSection*>::iterator it = _state.sections.begin(); it != _state.sections.end(); ++it) {
278 if ( ! (*it)->isSectionHidden() && ((*it)->type() != ld::Section::typeTentativeDefs) )
284 template <typename A>
285 unsigned int HeaderAndLoadCommandsAtom<A>::segmentCount() const
287 if ( _options.outputKind() == Options::kObjectFile ) {
288 // .o files have one anonymous segment that contains all sections
292 unsigned int count = 0;
293 const char* lastSegName = "";
294 for (std::vector<ld::Internal::FinalSection*>::iterator it = _state.sections.begin(); it != _state.sections.end(); ++it) {
295 if ( _options.outputKind() == Options::kPreload ) {
296 if ( (*it)->type() == ld::Section::typeMachHeader )
297 continue; // for -preload, don't put hidden __HEADER segment into output
298 if ( (*it)->type() == ld::Section::typeLinkEdit )
299 continue; // for -preload, don't put hidden __LINKEDIT segment into output
301 if ( strcmp(lastSegName, (*it)->segmentName()) != 0 ) {
302 lastSegName = (*it)->segmentName();
310 template <typename A>
311 uint64_t HeaderAndLoadCommandsAtom<A>::size() const
313 uint32_t sz = sizeof(macho_header<P>);
315 sz += sizeof(macho_segment_command<P>) * this->segmentCount();
316 sz += sizeof(macho_section<P>) * this->nonHiddenSectionCount();
318 if ( _hasDylibIDLoadCommand )
319 sz += alignedSize(sizeof(macho_dylib_command<P>) + strlen(_options.installPath()) + 1);
321 if ( _hasDyldInfoLoadCommand )
322 sz += sizeof(macho_dyld_info_command<P>);
324 if ( _hasSymbolTableLoadCommand )
325 sz += sizeof(macho_symtab_command<P>);
327 if ( _hasDynamicSymbolTableLoadCommand )
328 sz += sizeof(macho_dysymtab_command<P>);
330 if ( _hasDyldLoadCommand )
331 sz += alignedSize(sizeof(macho_dylinker_command<P>) + strlen(_options.dyldInstallPath()) + 1);
333 if ( _hasRoutinesLoadCommand )
334 sz += sizeof(macho_routines_command<P>);
336 if ( _hasUUIDLoadCommand )
337 sz += sizeof(macho_uuid_command<P>);
339 if ( _hasVersionLoadCommand )
340 sz += sizeof(macho_version_min_command<P>);
342 if ( _hasSourceVersionLoadCommand )
343 sz += sizeof(macho_source_version_command<P>);
345 if ( _hasThreadLoadCommand )
346 sz += this->threadLoadCommandSize();
348 if ( _hasEntryPointLoadCommand )
349 sz += sizeof(macho_entry_point_command<P>);
351 if ( _hasEncryptionLoadCommand )
352 sz += sizeof(macho_encryption_info_command<P>);
354 if ( _hasSplitSegInfoLoadCommand )
355 sz += sizeof(macho_linkedit_data_command<P>);
357 for(uint32_t ord=1; ord <= _writer.dylibCount(); ++ord) {
358 sz += alignedSize(sizeof(macho_dylib_command<P>) + strlen(_writer.dylibByOrdinal(ord)->installPath()) + 1);
361 if ( _hasRPathLoadCommands ) {
362 const std::vector<const char*>& rpaths = _options.rpaths();
363 for (std::vector<const char*>::const_iterator it = rpaths.begin(); it != rpaths.end(); ++it) {
364 sz += alignedSize(sizeof(macho_rpath_command<P>) + strlen(*it) + 1);
368 if ( _hasSubFrameworkLoadCommand )
369 sz += alignedSize(sizeof(macho_sub_framework_command<P>) + strlen(_options.umbrellaName()) + 1);
371 for (std::vector<const char*>::const_iterator it = _subLibraryNames.begin(); it != _subLibraryNames.end(); ++it) {
372 sz += alignedSize(sizeof(macho_sub_library_command<P>) + strlen(*it) + 1);
375 for (std::vector<const char*>::const_iterator it = _subUmbrellaNames.begin(); it != _subUmbrellaNames.end(); ++it) {
376 sz += alignedSize(sizeof(macho_sub_umbrella_command<P>) + strlen(*it) + 1);
379 if ( _allowableClientLoadCommmandsCount != 0 ) {
380 const std::vector<const char*>& clients = _options.allowableClients();
381 for (std::vector<const char*>::const_iterator it = clients.begin(); it != clients.end(); ++it) {
382 sz += alignedSize(sizeof(macho_sub_client_command<P>) + strlen(*it) + 1);
386 if ( _dyldEnvironExrasCount != 0 ) {
387 const std::vector<const char*>& extras = _options.dyldEnvironExtras();
388 for (std::vector<const char*>::const_iterator it = extras.begin(); it != extras.end(); ++it) {
389 sz += alignedSize(sizeof(macho_dylinker_command<P>) + strlen(*it) + 1);
393 if ( _hasFunctionStartsLoadCommand )
394 sz += sizeof(macho_linkedit_data_command<P>);
396 if ( _hasDataInCodeLoadCommand )
397 sz += sizeof(macho_linkedit_data_command<P>);
399 if ( _hasDependentDRInfo )
400 sz += sizeof(macho_linkedit_data_command<P>);
405 template <typename A>
406 uint32_t HeaderAndLoadCommandsAtom<A>::commandsCount() const
408 uint32_t count = this->segmentCount();
410 if ( _hasDylibIDLoadCommand )
413 if ( _hasDyldInfoLoadCommand )
416 if ( _hasSymbolTableLoadCommand )
419 if ( _hasDynamicSymbolTableLoadCommand )
422 if ( _hasDyldLoadCommand )
425 if ( _hasRoutinesLoadCommand )
428 if ( _hasUUIDLoadCommand )
431 if ( _hasVersionLoadCommand )
434 if ( _hasSourceVersionLoadCommand )
437 if ( _hasThreadLoadCommand )
440 if ( _hasEntryPointLoadCommand )
443 if ( _hasEncryptionLoadCommand )
446 if ( _hasSplitSegInfoLoadCommand )
449 count += _dylibLoadCommmandsCount;
451 count += _options.rpaths().size();
453 if ( _hasSubFrameworkLoadCommand )
456 count += _subLibraryNames.size();
458 count += _subUmbrellaNames.size();
460 count += _allowableClientLoadCommmandsCount;
462 count += _dyldEnvironExrasCount;
464 if ( _hasFunctionStartsLoadCommand )
467 if ( _hasDataInCodeLoadCommand )
470 if ( _hasDependentDRInfo )
476 template <typename A>
477 uint32_t HeaderAndLoadCommandsAtom<A>::fileType() const
479 switch ( _options.outputKind() ) {
480 case Options::kDynamicExecutable:
481 case Options::kStaticExecutable:
483 case Options::kDynamicLibrary:
485 case Options::kDynamicBundle:
487 case Options::kObjectFile:
491 case Options::kPreload:
493 case Options::kKextBundle:
494 return MH_KEXT_BUNDLE;
496 throw "unknonwn mach-o file type";
499 template <typename A>
500 uint32_t HeaderAndLoadCommandsAtom<A>::flags() const
503 if ( _options.outputKind() == Options::kObjectFile ) {
504 if ( _state.allObjectFilesScatterable )
505 bits = MH_SUBSECTIONS_VIA_SYMBOLS;
508 if ( _options.outputKind() == Options::kStaticExecutable ) {
510 if ( _options.positionIndependentExecutable() )
513 else if ( _options.outputKind() == Options::kPreload ) {
515 if ( _options.positionIndependentExecutable() )
520 switch ( _options.nameSpace() ) {
521 case Options::kTwoLevelNameSpace:
522 bits |= MH_TWOLEVEL | MH_NOUNDEFS;
524 case Options::kFlatNameSpace:
526 case Options::kForceFlatNameSpace:
527 bits |= MH_FORCE_FLAT;
530 if ( _writer.hasWeakExternalSymbols || _writer.overridesWeakExternalSymbols )
531 bits |= MH_WEAK_DEFINES;
532 if ( _writer.usesWeakExternalSymbols || _writer.hasWeakExternalSymbols )
533 bits |= MH_BINDS_TO_WEAK;
534 if ( _options.prebind() )
536 if ( _options.splitSeg() )
537 bits |= MH_SPLIT_SEGS;
538 if ( (_options.outputKind() == Options::kDynamicLibrary)
539 && _writer._noReExportedDylibs
540 && _options.useSimplifiedDylibReExports() ) {
541 bits |= MH_NO_REEXPORTED_DYLIBS;
543 if ( _options.positionIndependentExecutable() && ! _writer.pieDisabled )
545 if ( _options.markAutoDeadStripDylib() )
546 bits |= MH_DEAD_STRIPPABLE_DYLIB;
547 if ( _writer.hasThreadLocalVariableDefinitions )
548 bits |= MH_HAS_TLV_DESCRIPTORS;
549 if ( _options.hasNonExecutableHeap() )
550 bits |= MH_NO_HEAP_EXECUTION;
552 if ( _options.hasExecutableStack() )
553 bits |= MH_ALLOW_STACK_EXECUTION;
558 template <> uint32_t HeaderAndLoadCommandsAtom<x86>::magic() const { return MH_MAGIC; }
559 template <> uint32_t HeaderAndLoadCommandsAtom<x86_64>::magic() const { return MH_MAGIC_64; }
560 template <> uint32_t HeaderAndLoadCommandsAtom<arm>::magic() const { return MH_MAGIC; }
562 template <> uint32_t HeaderAndLoadCommandsAtom<x86>::cpuType() const { return CPU_TYPE_I386; }
563 template <> uint32_t HeaderAndLoadCommandsAtom<x86_64>::cpuType() const { return CPU_TYPE_X86_64; }
564 template <> uint32_t HeaderAndLoadCommandsAtom<arm>::cpuType() const { return CPU_TYPE_ARM; }
569 uint32_t HeaderAndLoadCommandsAtom<x86>::cpuSubType() const
571 return CPU_SUBTYPE_I386_ALL;
575 uint32_t HeaderAndLoadCommandsAtom<x86_64>::cpuSubType() const
577 if ( (_options.outputKind() == Options::kDynamicExecutable) && (_options.macosxVersionMin() >= ld::mac10_5) )
578 return (CPU_SUBTYPE_X86_64_ALL | 0x80000000);
580 return CPU_SUBTYPE_X86_64_ALL;
584 uint32_t HeaderAndLoadCommandsAtom<arm>::cpuSubType() const
586 return _state.cpuSubType;
591 template <typename A>
592 uint8_t* HeaderAndLoadCommandsAtom<A>::copySingleSegmentLoadCommand(uint8_t* p) const
594 // in .o files there is just one segment load command with a blank name
595 // and all sections under it
596 macho_segment_command<P>* cmd = (macho_segment_command<P>*)p;
597 cmd->set_cmd(macho_segment_command<P>::CMD);
598 cmd->set_segname("");
599 cmd->set_vmaddr(_options.baseAddress());
600 cmd->set_vmsize(0); // updated after sections set
601 cmd->set_fileoff(0); // updated after sections set
602 cmd->set_filesize(0); // updated after sections set
603 cmd->set_maxprot(VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE);
604 cmd->set_initprot(VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE);
605 cmd->set_nsects(this->nonHiddenSectionCount());
607 // add sections array
608 macho_section<P>* msect = (macho_section<P>*)&p[sizeof(macho_segment_command<P>)];
609 for (std::vector<ld::Internal::FinalSection*>::iterator sit = _state.sections.begin(); sit != _state.sections.end(); ++sit) {
610 ld::Internal::FinalSection* fsect = *sit;
611 if ( fsect->isSectionHidden() )
613 if ( fsect->type() == ld::Section::typeTentativeDefs )
615 msect->set_sectname(fsect->sectionName());
616 msect->set_segname(fsect->segmentName());
617 msect->set_addr(fsect->address);
618 msect->set_size(fsect->size);
619 msect->set_offset(fsect->fileOffset);
620 msect->set_align(fsect->alignment);
621 msect->set_reloff((fsect->relocCount == 0) ? 0 : _writer.sectionRelocationsSection->fileOffset + fsect->relocStart * sizeof(macho_relocation_info<P>));
622 msect->set_nreloc(fsect->relocCount);
623 msect->set_flags(sectionFlags(fsect));
624 msect->set_reserved1(fsect->indirectSymTabStartIndex);
625 msect->set_reserved2(fsect->indirectSymTabElementSize);
626 // update segment info
627 if ( cmd->fileoff() == 0 )
628 cmd->set_fileoff(fsect->fileOffset);
629 cmd->set_vmsize(fsect->address + fsect->size - cmd->vmaddr());
630 if ( (fsect->type() != ld::Section::typeZeroFill) && (fsect->type() != ld::Section::typeTentativeDefs) )
631 cmd->set_filesize(fsect->fileOffset + fsect->size - cmd->fileoff());
634 cmd->set_cmdsize(sizeof(macho_segment_command<P>) + cmd->nsects()*sizeof(macho_section<P>));
635 return p + cmd->cmdsize();
639 SegInfo(const char* n, const Options&);
641 uint32_t nonHiddenSectionCount;
644 std::vector<ld::Internal::FinalSection*> sections;
648 SegInfo::SegInfo(const char* n, const Options& opts)
649 : segName(n), nonHiddenSectionCount(0), maxProt(opts.maxSegProtection(n)), initProt(opts.initialSegProtection(n))
654 template <typename A>
655 uint32_t HeaderAndLoadCommandsAtom<A>::sectionFlags(ld::Internal::FinalSection* sect) const
658 switch ( sect->type() ) {
659 case ld::Section::typeUnclassified:
660 if ( strcmp(sect->segmentName(), "__OBJC") == 0 )
661 return S_REGULAR | S_ATTR_NO_DEAD_STRIP;
662 else if ( (strcmp(sect->sectionName(), "__objc_classlist") == 0) && (strcmp(sect->segmentName(), "__DATA") == 0) )
663 return S_REGULAR | S_ATTR_NO_DEAD_STRIP;
664 else if ( (strcmp(sect->sectionName(), "__objc_catlist") == 0) && (strcmp(sect->segmentName(), "__DATA") == 0) )
665 return S_REGULAR | S_ATTR_NO_DEAD_STRIP;
666 else if ( (strncmp(sect->sectionName(), "__objc_superrefs", 16) == 0) && (strcmp(sect->segmentName(), "__DATA") == 0) )
667 return S_REGULAR | S_ATTR_NO_DEAD_STRIP;
668 else if ( (strncmp(sect->sectionName(), "__objc_nlclslist", 16) == 0) && (strcmp(sect->segmentName(), "__DATA") == 0) )
669 return S_REGULAR | S_ATTR_NO_DEAD_STRIP;
672 case ld::Section::typeCode:
673 bits = S_REGULAR | S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS;
674 if ( sect->hasLocalRelocs && ! _writer.pieDisabled )
675 bits |= S_ATTR_LOC_RELOC;
676 if ( sect->hasExternalRelocs )
677 bits |= S_ATTR_EXT_RELOC;
679 case ld::Section::typePageZero:
681 case ld::Section::typeImportProxies:
683 case ld::Section::typeLinkEdit:
685 case ld::Section::typeMachHeader:
687 case ld::Section::typeStack:
689 case ld::Section::typeLiteral4:
690 return S_4BYTE_LITERALS;
691 case ld::Section::typeLiteral8:
692 return S_8BYTE_LITERALS;
693 case ld::Section::typeLiteral16:
694 return S_16BYTE_LITERALS;
695 case ld::Section::typeConstants:
697 case ld::Section::typeTempLTO:
698 assert(0 && "typeTempLTO should not make it to final linked image");
700 case ld::Section::typeAbsoluteSymbols:
701 assert(0 && "typeAbsoluteSymbols should not make it to final linked image");
703 case ld::Section::typeCString:
704 case ld::Section::typeNonStdCString:
705 return S_CSTRING_LITERALS;
706 case ld::Section::typeCStringPointer:
707 return S_LITERAL_POINTERS | S_ATTR_NO_DEAD_STRIP;
708 case ld::Section::typeUTF16Strings:
710 case ld::Section::typeCFString:
712 case ld::Section::typeObjC1Classes:
713 return S_REGULAR | S_ATTR_NO_DEAD_STRIP;
714 case ld::Section::typeCFI:
716 case ld::Section::typeLSDA:
718 case ld::Section::typeDtraceDOF:
720 case ld::Section::typeUnwindInfo:
722 case ld::Section::typeObjCClassRefs:
723 case ld::Section::typeObjC2CategoryList:
724 return S_REGULAR | S_ATTR_NO_DEAD_STRIP;
725 case ld::Section::typeZeroFill:
726 if ( _options.optimizeZeroFill() )
730 case ld::Section::typeTentativeDefs:
731 assert(0 && "typeTentativeDefs should not make it to final linked image");
733 case ld::Section::typeLazyPointer:
734 case ld::Section::typeLazyPointerClose:
735 return S_LAZY_SYMBOL_POINTERS;
736 case ld::Section::typeStubClose:
737 case ld::Section::typeStub:
738 if ( sect->hasLocalRelocs )
739 return S_SYMBOL_STUBS | S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS | S_ATTR_LOC_RELOC;
741 return S_SYMBOL_STUBS | S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS;
742 case ld::Section::typeNonLazyPointer:
743 if ( _options.outputKind() == Options::kKextBundle )
745 else if ( (_options.outputKind() == Options::kStaticExecutable) && _options.positionIndependentExecutable() )
748 return S_NON_LAZY_SYMBOL_POINTERS;
749 case ld::Section::typeDyldInfo:
751 case ld::Section::typeLazyDylibPointer:
752 return S_LAZY_DYLIB_SYMBOL_POINTERS;
753 case ld::Section::typeStubHelper:
754 if ( sect->hasLocalRelocs )
755 return S_REGULAR | S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS | S_ATTR_LOC_RELOC;
757 return S_REGULAR | S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS;
758 case ld::Section::typeInitializerPointers:
759 // <rdar://problem/11456679> i386 kexts need different section type
760 if ( (_options.outputKind() == Options::kObjectFile)
761 && (strcmp(sect->sectionName(), "__constructor") == 0)
762 && (strcmp(sect->segmentName(), "__TEXT") == 0) )
765 return S_MOD_INIT_FUNC_POINTERS;
766 case ld::Section::typeTerminatorPointers:
767 return S_MOD_TERM_FUNC_POINTERS;
768 case ld::Section::typeTLVInitialValues:
769 return S_THREAD_LOCAL_REGULAR;
770 case ld::Section::typeTLVZeroFill:
771 return S_THREAD_LOCAL_ZEROFILL;
772 case ld::Section::typeTLVDefs:
773 return S_THREAD_LOCAL_VARIABLES;
774 case ld::Section::typeTLVInitializerPointers:
775 return S_THREAD_LOCAL_INIT_FUNCTION_POINTERS;
776 case ld::Section::typeTLVPointers:
777 return S_THREAD_LOCAL_VARIABLE_POINTERS;
778 case ld::Section::typeFirstSection:
779 assert(0 && "typeFirstSection should not make it to final linked image");
781 case ld::Section::typeLastSection:
782 assert(0 && "typeLastSection should not make it to final linked image");
784 case ld::Section::typeDebug:
785 return S_REGULAR | S_ATTR_DEBUG;
791 template <typename A>
792 bool HeaderAndLoadCommandsAtom<A>::sectionTakesNoDiskSpace(ld::Internal::FinalSection* sect) const
794 switch ( sect->type() ) {
795 case ld::Section::typeZeroFill:
796 case ld::Section::typeTLVZeroFill:
797 return _options.optimizeZeroFill();
798 case ld::Section::typeAbsoluteSymbols:
799 case ld::Section::typeTentativeDefs:
800 case ld::Section::typeLastSection:
809 template <typename A>
810 uint8_t* HeaderAndLoadCommandsAtom<A>::copySegmentLoadCommands(uint8_t* p) const
812 // group sections into segments
813 std::vector<SegInfo> segs;
814 const char* lastSegName = "";
815 for (std::vector<ld::Internal::FinalSection*>::iterator it = _state.sections.begin(); it != _state.sections.end(); ++it) {
816 ld::Internal::FinalSection* sect = *it;
817 if ( _options.outputKind() == Options::kPreload ) {
818 if ( (*it)->type() == ld::Section::typeMachHeader )
819 continue; // for -preload, don't put hidden __HEADER segment into output
820 if ( (*it)->type() == ld::Section::typeLinkEdit )
821 continue; // for -preload, don't put hidden __LINKEDIT segment into output
823 if ( strcmp(lastSegName, sect->segmentName()) != 0 ) {
824 SegInfo si(sect->segmentName(), _options);
826 lastSegName = sect->segmentName();
828 if ( ! sect->isSectionHidden() )
829 segs.back().nonHiddenSectionCount++;
830 segs.back().sections.push_back(sect);
832 // write out segment load commands for each section with trailing sections
833 for (std::vector<SegInfo>::iterator it = segs.begin(); it != segs.end(); ++it) {
835 ld::Internal::FinalSection* lastNonZeroFillSection = NULL;
836 for (int i=si.sections.size()-1; i >= 0; --i) {
837 if ( !sectionTakesNoDiskSpace(si.sections[i]) ) {
838 lastNonZeroFillSection = si.sections[i];
842 uint64_t vmsize = si.sections.back()->address + si.sections.back()->size - si.sections.front()->address;
843 vmsize = ((vmsize+_options.segmentAlignment()-1) & (-_options.segmentAlignment()));
844 uint64_t filesize = 0;
845 if ( lastNonZeroFillSection != NULL ) {
846 filesize = lastNonZeroFillSection->address + lastNonZeroFillSection->size - si.sections.front()->address;
847 // round up all segments to page aligned, except __LINKEDIT
848 if ( (si.sections[0]->type() != ld::Section::typeLinkEdit) && (si.sections[0]->type() != ld::Section::typeImportProxies) )
849 filesize = (filesize + _options.segmentAlignment()-1) & (-_options.segmentAlignment());
851 if ( si.sections.front()->type() == ld::Section::typePageZero )
853 else if ( si.sections.front()->type() == ld::Section::typeStack )
855 macho_segment_command<P>* segCmd = (macho_segment_command<P>*)p;
856 segCmd->set_cmd(macho_segment_command<P>::CMD);
857 segCmd->set_cmdsize(sizeof(macho_segment_command<P>) + si.nonHiddenSectionCount*sizeof(macho_section<P>));
858 segCmd->set_segname(si.sections.front()->segmentName());
859 segCmd->set_vmaddr(si.sections.front()->address);
860 segCmd->set_vmsize(vmsize);
861 segCmd->set_fileoff(si.sections.front()->fileOffset);
862 segCmd->set_filesize(filesize);
863 segCmd->set_maxprot(si.maxProt);
864 segCmd->set_initprot(si.initProt);
865 segCmd->set_nsects(si.nonHiddenSectionCount);
866 segCmd->set_flags(0);
867 p += sizeof(macho_segment_command<P>);
868 macho_section<P>* msect = (macho_section<P>*)p;
869 for (std::vector<ld::Internal::FinalSection*>::iterator sit = si.sections.begin(); sit != si.sections.end(); ++sit) {
870 ld::Internal::FinalSection* fsect = *sit;
871 if ( ! fsect->isSectionHidden() ) {
872 msect->set_sectname(fsect->sectionName());
873 msect->set_segname(fsect->segmentName());
874 msect->set_addr(fsect->address);
875 msect->set_size(fsect->size);
876 msect->set_offset(sectionTakesNoDiskSpace(fsect) ? 0 : fsect->fileOffset);
877 msect->set_align(fsect->alignment);
878 msect->set_reloff(0);
879 msect->set_nreloc(0);
880 msect->set_flags(sectionFlags(fsect));
881 msect->set_reserved1(fsect->indirectSymTabStartIndex);
882 msect->set_reserved2(fsect->indirectSymTabElementSize);
883 p += sizeof(macho_section<P>);
893 template <typename A>
894 uint8_t* HeaderAndLoadCommandsAtom<A>::copySymbolTableLoadCommand(uint8_t* p) const
896 // build LC_SYMTAB command
897 macho_symtab_command<P>* symbolTableCmd = (macho_symtab_command<P>*)p;
898 symbolTableCmd->set_cmd(LC_SYMTAB);
899 symbolTableCmd->set_cmdsize(sizeof(macho_symtab_command<P>));
900 symbolTableCmd->set_nsyms(_writer.symbolTableSection->size/sizeof(macho_nlist<P>));
901 symbolTableCmd->set_symoff(_writer.symbolTableSection->size == 0 ? 0 : _writer.symbolTableSection->fileOffset);
902 symbolTableCmd->set_stroff(_writer.stringPoolSection->size == 0 ? 0 : _writer.stringPoolSection->fileOffset );
903 symbolTableCmd->set_strsize(_writer.stringPoolSection->size);
904 return p + sizeof(macho_symtab_command<P>);
907 template <typename A>
908 uint8_t* HeaderAndLoadCommandsAtom<A>::copyDynamicSymbolTableLoadCommand(uint8_t* p) const
910 // build LC_SYMTAB command
911 macho_dysymtab_command<P>* dynamicSymbolTableCmd = (macho_dysymtab_command<P>*)p;
912 dynamicSymbolTableCmd->set_cmd(LC_DYSYMTAB);
913 dynamicSymbolTableCmd->set_cmdsize(sizeof(macho_dysymtab_command<P>));
914 dynamicSymbolTableCmd->set_ilocalsym(0);
915 dynamicSymbolTableCmd->set_nlocalsym(_writer._localSymbolsCount);
916 dynamicSymbolTableCmd->set_iextdefsym(dynamicSymbolTableCmd->ilocalsym()+dynamicSymbolTableCmd->nlocalsym());
917 dynamicSymbolTableCmd->set_nextdefsym(_writer._globalSymbolsCount);
918 dynamicSymbolTableCmd->set_iundefsym(dynamicSymbolTableCmd->iextdefsym()+dynamicSymbolTableCmd->nextdefsym());
919 dynamicSymbolTableCmd->set_nundefsym(_writer._importSymbolsCount);
921 // FIX ME: support for 10.3 dylibs which need modules
922 //if ( fWriter.fModuleInfoAtom != NULL ) {
923 // dynamicSymbolTableCmd->set_tocoff(fWriter.fModuleInfoAtom->getTableOfContentsFileOffset());
924 // dynamicSymbolTableCmd->set_ntoc(fWriter.fSymbolTableExportCount);
925 // dynamicSymbolTableCmd->set_modtaboff(fWriter.fModuleInfoAtom->getModuleTableFileOffset());
926 // dynamicSymbolTableCmd->set_nmodtab(1);
927 // dynamicSymbolTableCmd->set_extrefsymoff(fWriter.fModuleInfoAtom->getReferencesFileOffset());
928 // dynamicSymbolTableCmd->set_nextrefsyms(fWriter.fModuleInfoAtom->getReferencesCount());
931 bool hasIndirectSymbols = ( (_writer.indirectSymbolTableSection != NULL) && (_writer.indirectSymbolTableSection->size != 0) );
932 dynamicSymbolTableCmd->set_indirectsymoff(hasIndirectSymbols ? _writer.indirectSymbolTableSection->fileOffset : 0);
933 dynamicSymbolTableCmd->set_nindirectsyms( hasIndirectSymbols ? _writer.indirectSymbolTableSection->size/sizeof(uint32_t) : 0);
935 // FIX ME: support for classic relocations
936 if ( _options.outputKind() != Options::kObjectFile ) {
937 bool hasExternalRelocs = ( (_writer.externalRelocationsSection != NULL) && (_writer.externalRelocationsSection->size != 0) );
938 dynamicSymbolTableCmd->set_extreloff(hasExternalRelocs ? _writer.externalRelocationsSection->fileOffset : 0);
939 dynamicSymbolTableCmd->set_nextrel( hasExternalRelocs ? _writer.externalRelocationsSection->size/8 : 0);
940 bool hasLocalRelocs = ( (_writer.localRelocationsSection != NULL) && (_writer.localRelocationsSection->size != 0) );
941 dynamicSymbolTableCmd->set_locreloff(hasLocalRelocs ? _writer.localRelocationsSection->fileOffset : 0);
942 dynamicSymbolTableCmd->set_nlocrel (hasLocalRelocs ? _writer.localRelocationsSection->size/8 : 0);
944 return p + sizeof(macho_dysymtab_command<P>);
948 template <typename A>
949 uint8_t* HeaderAndLoadCommandsAtom<A>::copyDyldInfoLoadCommand(uint8_t* p) const
951 // build LC_DYLD_INFO command
952 macho_dyld_info_command<P>* cmd = (macho_dyld_info_command<P>*)p;
954 cmd->set_cmd(LC_DYLD_INFO_ONLY);
955 cmd->set_cmdsize(sizeof(macho_dyld_info_command<P>));
956 if ( _writer.rebaseSection->size != 0 ) {
957 cmd->set_rebase_off(_writer.rebaseSection->fileOffset);
958 cmd->set_rebase_size(_writer.rebaseSection->size);
960 if ( _writer.bindingSection->size != 0 ) {
961 cmd->set_bind_off(_writer.bindingSection->fileOffset);
962 cmd->set_bind_size(_writer.bindingSection->size);
964 if ( _writer.weakBindingSection->size != 0 ) {
965 cmd->set_weak_bind_off(_writer.weakBindingSection->fileOffset);
966 cmd->set_weak_bind_size(_writer.weakBindingSection->size);
968 if ( _writer.lazyBindingSection->size != 0 ) {
969 cmd->set_lazy_bind_off(_writer.lazyBindingSection->fileOffset);
970 cmd->set_lazy_bind_size(_writer.lazyBindingSection->size);
972 if ( _writer.exportSection->size != 0 ) {
973 cmd->set_export_off(_writer.exportSection->fileOffset);
974 cmd->set_export_size(_writer.exportSection->size);
976 return p + sizeof(macho_dyld_info_command<P>);
980 template <typename A>
981 uint8_t* HeaderAndLoadCommandsAtom<A>::copyDyldLoadCommand(uint8_t* p) const
983 uint32_t sz = alignedSize(sizeof(macho_dylinker_command<P>) + strlen(_options.dyldInstallPath()) + 1);
984 macho_dylinker_command<P>* cmd = (macho_dylinker_command<P>*)p;
985 if ( _options.outputKind() == Options::kDyld )
986 cmd->set_cmd(LC_ID_DYLINKER);
988 cmd->set_cmd(LC_LOAD_DYLINKER);
989 cmd->set_cmdsize(sz);
990 cmd->set_name_offset();
991 strcpy((char*)&p[sizeof(macho_dylinker_command<P>)], _options.dyldInstallPath());
996 template <typename A>
997 uint8_t* HeaderAndLoadCommandsAtom<A>::copyDylibIDLoadCommand(uint8_t* p) const
999 uint32_t sz = alignedSize(sizeof(macho_dylib_command<P>) + strlen(_options.installPath()) + 1);
1000 macho_dylib_command<P>* cmd = (macho_dylib_command<P>*)p;
1001 cmd->set_cmd(LC_ID_DYLIB);
1002 cmd->set_cmdsize(sz);
1003 cmd->set_name_offset();
1004 cmd->set_timestamp(1); // needs to be some constant value that is different than DylibLoadCommandsAtom uses
1005 cmd->set_current_version(_options.currentVersion32());
1006 cmd->set_compatibility_version(_options.compatibilityVersion());
1007 strcpy((char*)&p[sizeof(macho_dylib_command<P>)], _options.installPath());
1011 template <typename A>
1012 uint8_t* HeaderAndLoadCommandsAtom<A>::copyRoutinesLoadCommand(uint8_t* p) const
1014 pint_t initAddr = _state.entryPoint->finalAddress();
1015 if ( _state.entryPoint->isThumb() )
1017 macho_routines_command<P>* cmd = (macho_routines_command<P>*)p;
1018 cmd->set_cmd(macho_routines_command<P>::CMD);
1019 cmd->set_cmdsize(sizeof(macho_routines_command<P>));
1020 cmd->set_init_address(initAddr);
1021 return p + sizeof(macho_routines_command<P>);
1025 template <typename A>
1026 void HeaderAndLoadCommandsAtom<A>::recopyUUIDCommand()
1028 assert(_uuidCmdInOutputBuffer != NULL);
1029 _uuidCmdInOutputBuffer->set_uuid(_uuid);
1033 template <typename A>
1034 uint8_t* HeaderAndLoadCommandsAtom<A>::copyUUIDLoadCommand(uint8_t* p) const
1036 macho_uuid_command<P>* cmd = (macho_uuid_command<P>*)p;
1037 cmd->set_cmd(LC_UUID);
1038 cmd->set_cmdsize(sizeof(macho_uuid_command<P>));
1039 cmd->set_uuid(_uuid);
1040 _uuidCmdInOutputBuffer = cmd; // save for later re-write by recopyUUIDCommand()
1041 return p + sizeof(macho_uuid_command<P>);
1045 template <typename A>
1046 uint8_t* HeaderAndLoadCommandsAtom<A>::copyVersionLoadCommand(uint8_t* p) const
1048 macho_version_min_command<P>* cmd = (macho_version_min_command<P>*)p;
1049 ld::MacVersionMin macVersion = _options.macosxVersionMin();
1050 ld::IOSVersionMin iOSVersion = _options.iOSVersionMin();
1051 assert( (macVersion != ld::macVersionUnset) || (iOSVersion != ld::iOSVersionUnset) );
1052 if ( macVersion != ld::macVersionUnset ) {
1053 cmd->set_cmd(LC_VERSION_MIN_MACOSX);
1054 cmd->set_cmdsize(sizeof(macho_version_min_command<P>));
1055 cmd->set_version((uint32_t)macVersion);
1056 cmd->set_sdk(_options.sdkVersion());
1059 cmd->set_cmd(LC_VERSION_MIN_IPHONEOS);
1060 cmd->set_cmdsize(sizeof(macho_version_min_command<P>));
1061 cmd->set_version((uint32_t)iOSVersion);
1062 cmd->set_sdk(_options.sdkVersion());
1064 return p + sizeof(macho_version_min_command<P>);
1067 template <typename A>
1068 uint8_t* HeaderAndLoadCommandsAtom<A>::copySourceVersionLoadCommand(uint8_t* p) const
1070 macho_source_version_command<P>* cmd = (macho_source_version_command<P>*)p;
1071 cmd->set_cmd(LC_SOURCE_VERSION);
1072 cmd->set_cmdsize(sizeof(macho_source_version_command<P>));
1073 cmd->set_version(_options.sourceVersion());
1074 return p + sizeof(macho_source_version_command<P>);
1079 uint32_t HeaderAndLoadCommandsAtom<x86>::threadLoadCommandSize() const
1081 return this->alignedSize(16 + 16*4); // base size + i386_THREAD_STATE_COUNT * 4
1085 uint8_t* HeaderAndLoadCommandsAtom<x86>::copyThreadsLoadCommand(uint8_t* p) const
1087 assert(_state.entryPoint != NULL);
1088 pint_t start = _state.entryPoint->finalAddress();
1089 macho_thread_command<P>* cmd = (macho_thread_command<P>*)p;
1090 cmd->set_cmd(LC_UNIXTHREAD);
1091 cmd->set_cmdsize(threadLoadCommandSize());
1092 cmd->set_flavor(1); // i386_THREAD_STATE
1093 cmd->set_count(16); // i386_THREAD_STATE_COUNT;
1094 cmd->set_thread_register(10, start);
1095 if ( _options.hasCustomStack() )
1096 cmd->set_thread_register(7, _options.customStackAddr()); // r1
1097 return p + threadLoadCommandSize();
1101 uint32_t HeaderAndLoadCommandsAtom<x86_64>::threadLoadCommandSize() const
1103 return this->alignedSize(16 + x86_THREAD_STATE64_COUNT * 4);
1107 uint8_t* HeaderAndLoadCommandsAtom<x86_64>::copyThreadsLoadCommand(uint8_t* p) const
1109 assert(_state.entryPoint != NULL);
1110 pint_t start = _state.entryPoint->finalAddress();
1111 macho_thread_command<P>* cmd = (macho_thread_command<P>*)p;
1112 cmd->set_cmd(LC_UNIXTHREAD);
1113 cmd->set_cmdsize(threadLoadCommandSize());
1114 cmd->set_flavor(x86_THREAD_STATE64);
1115 cmd->set_count(x86_THREAD_STATE64_COUNT);
1116 cmd->set_thread_register(16, start); // rip
1117 if ( _options.hasCustomStack() )
1118 cmd->set_thread_register(7, _options.customStackAddr()); // r1
1119 return p + threadLoadCommandSize();
1123 uint32_t HeaderAndLoadCommandsAtom<arm>::threadLoadCommandSize() const
1125 return this->alignedSize(16 + 17 * 4); // base size + ARM_THREAD_STATE_COUNT * 4
1129 uint8_t* HeaderAndLoadCommandsAtom<arm>::copyThreadsLoadCommand(uint8_t* p) const
1131 assert(_state.entryPoint != NULL);
1132 pint_t start = _state.entryPoint->finalAddress();
1133 if ( _state.entryPoint->isThumb() )
1135 macho_thread_command<P>* cmd = (macho_thread_command<P>*)p;
1136 cmd->set_cmd(LC_UNIXTHREAD);
1137 cmd->set_cmdsize(threadLoadCommandSize());
1140 cmd->set_thread_register(15, start); // pc
1141 if ( _options.hasCustomStack() )
1142 cmd->set_thread_register(13, _options.customStackAddr()); // sp
1143 return p + threadLoadCommandSize();
1148 template <typename A>
1149 uint8_t* HeaderAndLoadCommandsAtom<A>::copyEntryPointLoadCommand(uint8_t* p) const
1151 macho_entry_point_command<P>* cmd = (macho_entry_point_command<P>*)p;
1152 cmd->set_cmd(LC_MAIN);
1153 cmd->set_cmdsize(sizeof(macho_entry_point_command<P>));
1154 assert(_state.entryPoint != NULL);
1155 pint_t start = _state.entryPoint->finalAddress();
1156 if ( _state.entryPoint->isThumb() )
1158 cmd->set_entryoff(start - this->finalAddress());
1159 cmd->set_stacksize(_options.hasCustomStack() ? _options.customStackSize() : 0 );
1160 return p + sizeof(macho_entry_point_command<P>);
1164 template <typename A>
1165 uint8_t* HeaderAndLoadCommandsAtom<A>::copyEncryptionLoadCommand(uint8_t* p) const
1167 macho_encryption_info_command<P>* cmd = (macho_encryption_info_command<P>*)p;
1168 cmd->set_cmd(LC_ENCRYPTION_INFO);
1169 cmd->set_cmdsize(sizeof(macho_encryption_info_command<P>));
1170 assert(_writer.encryptedTextStartOffset() != 0);
1171 assert(_writer.encryptedTextEndOffset() != 0);
1172 cmd->set_cryptoff(_writer.encryptedTextStartOffset());
1173 cmd->set_cryptsize(_writer.encryptedTextEndOffset()-_writer.encryptedTextStartOffset());
1174 cmd->set_cryptid(0);
1175 return p + sizeof(macho_encryption_info_command<P>);
1179 template <typename A>
1180 uint8_t* HeaderAndLoadCommandsAtom<A>::copySplitSegInfoLoadCommand(uint8_t* p) const
1182 macho_linkedit_data_command<P>* cmd = (macho_linkedit_data_command<P>*)p;
1183 cmd->set_cmd(LC_SEGMENT_SPLIT_INFO);
1184 cmd->set_cmdsize(sizeof(macho_linkedit_data_command<P>));
1185 cmd->set_dataoff(_writer.splitSegInfoSection->fileOffset);
1186 cmd->set_datasize(_writer.splitSegInfoSection->size);
1187 return p + sizeof(macho_linkedit_data_command<P>);
1191 template <typename A>
1192 uint8_t* HeaderAndLoadCommandsAtom<A>::copyDylibLoadCommand(uint8_t* p, const ld::dylib::File* dylib) const
1194 uint32_t sz = alignedSize(sizeof(macho_dylib_command<P>) + strlen(dylib->installPath()) + 1);
1195 macho_dylib_command<P>* cmd = (macho_dylib_command<P>*)p;
1196 if ( dylib->willBeLazyLoadedDylib() )
1197 cmd->set_cmd(LC_LAZY_LOAD_DYLIB);
1198 else if ( dylib->forcedWeakLinked() || dylib->allSymbolsAreWeakImported() )
1199 cmd->set_cmd(LC_LOAD_WEAK_DYLIB);
1200 else if ( dylib->willBeReExported() && _options.useSimplifiedDylibReExports() )
1201 cmd->set_cmd(LC_REEXPORT_DYLIB);
1202 else if ( dylib->willBeUpwardDylib() && _options.useUpwardDylibs() )
1203 cmd->set_cmd(LC_LOAD_UPWARD_DYLIB);
1205 cmd->set_cmd(LC_LOAD_DYLIB);
1206 cmd->set_cmdsize(sz);
1207 cmd->set_timestamp(2); // needs to be some constant value that is different than DylibIDLoadCommandsAtom uses
1208 cmd->set_current_version(dylib->currentVersion());
1209 cmd->set_compatibility_version(dylib->compatibilityVersion());
1210 cmd->set_name_offset();
1211 strcpy((char*)&p[sizeof(macho_dylib_command<P>)], dylib->installPath());
1215 template <typename A>
1216 uint8_t* HeaderAndLoadCommandsAtom<A>::copyRPathLoadCommand(uint8_t* p, const char* path) const
1218 uint32_t sz = alignedSize(sizeof(macho_rpath_command<P>) + strlen(path) + 1);
1219 macho_rpath_command<P>* cmd = (macho_rpath_command<P>*)p;
1220 cmd->set_cmd(LC_RPATH);
1221 cmd->set_cmdsize(sz);
1222 cmd->set_path_offset();
1223 strcpy((char*)&p[sizeof(macho_rpath_command<P>)], path);
1227 template <typename A>
1228 uint8_t* HeaderAndLoadCommandsAtom<A>::copySubFrameworkLoadCommand(uint8_t* p) const
1230 const char* umbrellaName = _options.umbrellaName();
1231 uint32_t sz = alignedSize(sizeof(macho_sub_framework_command<P>) + strlen(umbrellaName) + 1);
1232 macho_sub_framework_command<P>* cmd = (macho_sub_framework_command<P>*)p;
1233 cmd->set_cmd(LC_SUB_FRAMEWORK);
1234 cmd->set_cmdsize(sz);
1235 cmd->set_umbrella_offset();
1236 strcpy((char*)&p[sizeof(macho_sub_framework_command<P>)], umbrellaName);
1241 template <typename A>
1242 uint8_t* HeaderAndLoadCommandsAtom<A>::copyAllowableClientLoadCommand(uint8_t* p, const char* client) const
1244 uint32_t sz = alignedSize(sizeof(macho_sub_client_command<P>) + strlen(client) + 1);
1245 macho_sub_client_command<P>* cmd = (macho_sub_client_command<P>*)p;
1246 cmd->set_cmd(LC_SUB_CLIENT);
1247 cmd->set_cmdsize(sz);
1248 cmd->set_client_offset();
1249 strcpy((char*)&p[sizeof(macho_sub_client_command<P>)], client);
1253 template <typename A>
1254 uint8_t* HeaderAndLoadCommandsAtom<A>::copyDyldEnvLoadCommand(uint8_t* p, const char* env) const
1256 uint32_t sz = alignedSize(sizeof(macho_dylinker_command<P>) + strlen(env) + 1);
1257 macho_dylinker_command<P>* cmd = (macho_dylinker_command<P>*)p;
1258 cmd->set_cmd(LC_DYLD_ENVIRONMENT);
1259 cmd->set_cmdsize(sz);
1260 cmd->set_name_offset();
1261 strcpy((char*)&p[sizeof(macho_dylinker_command<P>)], env);
1265 template <typename A>
1266 uint8_t* HeaderAndLoadCommandsAtom<A>::copySubUmbrellaLoadCommand(uint8_t* p, const char* nm) const
1268 uint32_t sz = alignedSize(sizeof(macho_sub_umbrella_command<P>) + strlen(nm) + 1);
1269 macho_sub_umbrella_command<P>* cmd = (macho_sub_umbrella_command<P>*)p;
1270 cmd->set_cmd(LC_SUB_UMBRELLA);
1271 cmd->set_cmdsize(sz);
1272 cmd->set_sub_umbrella_offset();
1273 strcpy((char*)&p[sizeof(macho_sub_umbrella_command<P>)], nm);
1277 template <typename A>
1278 uint8_t* HeaderAndLoadCommandsAtom<A>::copySubLibraryLoadCommand(uint8_t* p, const char* nm) const
1280 uint32_t sz = alignedSize(sizeof(macho_sub_library_command<P>) + strlen(nm) + 1);
1281 macho_sub_library_command<P>* cmd = (macho_sub_library_command<P>*)p;
1282 cmd->set_cmd(LC_SUB_LIBRARY);
1283 cmd->set_cmdsize(sz);
1284 cmd->set_sub_library_offset();
1285 strcpy((char*)&p[sizeof(macho_sub_library_command<P>)], nm);
1289 template <typename A>
1290 uint8_t* HeaderAndLoadCommandsAtom<A>::copyFunctionStartsLoadCommand(uint8_t* p) const
1292 macho_linkedit_data_command<P>* cmd = (macho_linkedit_data_command<P>*)p;
1293 cmd->set_cmd(LC_FUNCTION_STARTS);
1294 cmd->set_cmdsize(sizeof(macho_linkedit_data_command<P>));
1295 cmd->set_dataoff(_writer.functionStartsSection->fileOffset);
1296 cmd->set_datasize(_writer.functionStartsSection->size);
1297 return p + sizeof(macho_linkedit_data_command<P>);
1301 template <typename A>
1302 uint8_t* HeaderAndLoadCommandsAtom<A>::copyDataInCodeLoadCommand(uint8_t* p) const
1304 macho_linkedit_data_command<P>* cmd = (macho_linkedit_data_command<P>*)p;
1305 cmd->set_cmd(LC_DATA_IN_CODE);
1306 cmd->set_cmdsize(sizeof(macho_linkedit_data_command<P>));
1307 cmd->set_dataoff(_writer.dataInCodeSection->fileOffset);
1308 cmd->set_datasize(_writer.dataInCodeSection->size);
1309 return p + sizeof(macho_linkedit_data_command<P>);
1313 template <typename A>
1314 uint8_t* HeaderAndLoadCommandsAtom<A>::copyDependentDRLoadCommand(uint8_t* p) const
1316 macho_linkedit_data_command<P>* cmd = (macho_linkedit_data_command<P>*)p;
1317 cmd->set_cmd(LC_DYLIB_CODE_SIGN_DRS);
1318 cmd->set_cmdsize(sizeof(macho_linkedit_data_command<P>));
1319 cmd->set_dataoff(_writer.dependentDRsSection->fileOffset);
1320 cmd->set_datasize(_writer.dependentDRsSection->size);
1321 return p + sizeof(macho_linkedit_data_command<P>);
1325 template <typename A>
1326 void HeaderAndLoadCommandsAtom<A>::copyRawContent(uint8_t buffer[]) const
1328 macho_header<P>* mh = (macho_header<P>*)buffer;
1329 bzero(buffer, this->size());
1332 mh->set_magic(this->magic());
1333 mh->set_cputype(this->cpuType());
1334 mh->set_cpusubtype(this->cpuSubType());
1335 mh->set_filetype(this->fileType());
1336 mh->set_ncmds(this->commandsCount());
1337 mh->set_sizeofcmds(this->size()-sizeof(macho_header<P>));
1338 mh->set_flags(this->flags());
1340 // copy load commands
1341 uint8_t* p = &buffer[sizeof(macho_header<P>)];
1343 if ( _options.outputKind() == Options::kObjectFile )
1344 p = this->copySingleSegmentLoadCommand(p);
1346 p = this->copySegmentLoadCommands(p);
1348 if ( _hasDylibIDLoadCommand )
1349 p = this->copyDylibIDLoadCommand(p);
1351 if ( _hasDyldInfoLoadCommand )
1352 p = this->copyDyldInfoLoadCommand(p);
1354 if ( _hasSymbolTableLoadCommand )
1355 p = this->copySymbolTableLoadCommand(p);
1357 if ( _hasDynamicSymbolTableLoadCommand )
1358 p = this->copyDynamicSymbolTableLoadCommand(p);
1360 if ( _hasDyldLoadCommand )
1361 p = this->copyDyldLoadCommand(p);
1363 if ( _hasRoutinesLoadCommand )
1364 p = this->copyRoutinesLoadCommand(p);
1366 if ( _hasUUIDLoadCommand )
1367 p = this->copyUUIDLoadCommand(p);
1369 if ( _hasVersionLoadCommand )
1370 p = this->copyVersionLoadCommand(p);
1372 if ( _hasSourceVersionLoadCommand )
1373 p = this->copySourceVersionLoadCommand(p);
1375 if ( _hasThreadLoadCommand )
1376 p = this->copyThreadsLoadCommand(p);
1378 if ( _hasEntryPointLoadCommand )
1379 p = this->copyEntryPointLoadCommand(p);
1381 if ( _hasEncryptionLoadCommand )
1382 p = this->copyEncryptionLoadCommand(p);
1384 if ( _hasSplitSegInfoLoadCommand )
1385 p = this->copySplitSegInfoLoadCommand(p);
1387 for(uint32_t ord=1; ord <= _writer.dylibCount(); ++ord) {
1388 p = this->copyDylibLoadCommand(p, _writer.dylibByOrdinal(ord));
1391 if ( _hasRPathLoadCommands ) {
1392 const std::vector<const char*>& rpaths = _options.rpaths();
1393 for (std::vector<const char*>::const_iterator it = rpaths.begin(); it != rpaths.end(); ++it) {
1394 p = this->copyRPathLoadCommand(p, *it);
1398 if ( _hasSubFrameworkLoadCommand )
1399 p = this->copySubFrameworkLoadCommand(p);
1401 for (std::vector<const char*>::const_iterator it = _subLibraryNames.begin(); it != _subLibraryNames.end(); ++it) {
1402 p = this->copySubLibraryLoadCommand(p, *it);
1405 for (std::vector<const char*>::const_iterator it = _subUmbrellaNames.begin(); it != _subUmbrellaNames.end(); ++it) {
1406 p = this->copySubUmbrellaLoadCommand(p, *it);
1409 if ( _allowableClientLoadCommmandsCount != 0 ) {
1410 const std::vector<const char*>& clients = _options.allowableClients();
1411 for (std::vector<const char*>::const_iterator it = clients.begin(); it != clients.end(); ++it) {
1412 p = this->copyAllowableClientLoadCommand(p, *it);
1416 if ( _dyldEnvironExrasCount != 0 ) {
1417 const std::vector<const char*>& extras = _options.dyldEnvironExtras();
1418 for (std::vector<const char*>::const_iterator it = extras.begin(); it != extras.end(); ++it) {
1419 p = this->copyDyldEnvLoadCommand(p, *it);
1423 if ( _hasFunctionStartsLoadCommand )
1424 p = this->copyFunctionStartsLoadCommand(p);
1426 if ( _hasDataInCodeLoadCommand )
1427 p = this->copyDataInCodeLoadCommand(p);
1429 if ( _hasDependentDRInfo )
1430 p = this->copyDependentDRLoadCommand(p);
1439 #endif // __HEADER_LOAD_COMMANDS_HPP__