1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-*
3 * Copyright (c) 2009 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* copyThreadsLoadCommand(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* copyDyldEnvLoadCommand(uint8_t* p, const char* env) const;
111 uint32_t sectionFlags(ld::Internal::FinalSection* sect) const;
112 bool sectionTakesNoDiskSpace(ld::Internal::FinalSection* sect) const;
115 const Options& _options;
116 ld::Internal& _state;
119 bool _hasDyldInfoLoadCommand;
120 bool _hasDyldLoadCommand;
121 bool _hasDylibIDLoadCommand;
122 bool _hasThreadLoadCommand;
123 bool _hasEncryptionLoadCommand;
124 bool _hasSplitSegInfoLoadCommand;
125 bool _hasRoutinesLoadCommand;
126 bool _hasUUIDLoadCommand;
127 bool _hasSymbolTableLoadCommand;
128 bool _hasDynamicSymbolTableLoadCommand;
129 bool _hasRPathLoadCommands;
130 bool _hasSubFrameworkLoadCommand;
131 bool _hasVersionLoadCommand;
132 bool _hasFunctionStartsLoadCommand;
133 uint32_t _dylibLoadCommmandsCount;
134 uint32_t _allowableClientLoadCommmandsCount;
135 uint32_t _dyldEnvironExrasCount;
136 std::vector<const char*> _subLibraryNames;
137 std::vector<const char*> _subUmbrellaNames;
139 mutable macho_uuid_command<P>* _uuidCmdInOutputBuffer;
141 static ld::Section _s_section;
142 static ld::Section _s_preload_section;
145 template <typename A>
146 ld::Section HeaderAndLoadCommandsAtom<A>::_s_section("__TEXT", "__mach_header", ld::Section::typeMachHeader, true);
147 template <typename A>
148 ld::Section HeaderAndLoadCommandsAtom<A>::_s_preload_section("__HEADER", "__mach_header", ld::Section::typeMachHeader, true);
151 template <typename A>
152 HeaderAndLoadCommandsAtom<A>::HeaderAndLoadCommandsAtom(const Options& opts, ld::Internal& state, OutputFile& writer)
153 : HeaderAndLoadCommandsAbtract((opts.outputKind() == Options::kPreload) ? _s_preload_section : _s_section,
154 ld::Atom::definitionRegular, ld::Atom::combineNever,
155 ld::Atom::scopeTranslationUnit, ld::Atom::typeUnclassified,
156 ld::Atom::symbolTableNotIn, false, false, false,
157 (opts.outputKind() == Options::kPreload) ? ld::Atom::Alignment(0) : ld::Atom::Alignment(12) ),
158 _options(opts), _state(state), _writer(writer), _address(0), _uuidCmdInOutputBuffer(NULL)
161 _hasDyldInfoLoadCommand = opts.makeCompressedDyldInfo();
162 _hasDyldLoadCommand = ((opts.outputKind() == Options::kDynamicExecutable) || (_options.outputKind() == Options::kDyld));
163 _hasDylibIDLoadCommand = (opts.outputKind() == Options::kDynamicLibrary);
164 _hasThreadLoadCommand = _hasDyldLoadCommand || (opts.outputKind() == Options::kStaticExecutable)
165 || (opts.outputKind() == Options::kPreload)
166 || (opts.outputKind() == Options::kDyld);
167 _hasEncryptionLoadCommand = opts.makeEncryptable();
168 _hasSplitSegInfoLoadCommand = opts.sharedRegionEligible();
169 _hasRoutinesLoadCommand = (opts.initFunctionName() != NULL);
170 _hasSymbolTableLoadCommand = true;
171 _hasUUIDLoadCommand = (opts.UUIDMode() != Options::kUUIDNone);
172 switch ( opts.outputKind() ) {
173 case Options::kDynamicExecutable:
174 case Options::kDynamicLibrary:
175 case Options::kDynamicBundle:
177 case Options::kKextBundle:
178 _hasDynamicSymbolTableLoadCommand = true;
180 case Options::kObjectFile:
181 if ( ! state.someObjectFileHasDwarf )
182 _hasUUIDLoadCommand = false;
183 _hasDynamicSymbolTableLoadCommand = false;
184 for (std::vector<ld::Internal::FinalSection*>::iterator it = _state.sections.begin(); it != _state.sections.end(); ++it) {
185 if ( (*it)->type() == ld::Section::typeNonLazyPointer ) {
186 _hasDynamicSymbolTableLoadCommand = true;
191 case Options::kStaticExecutable:
192 _hasDynamicSymbolTableLoadCommand = false;
194 case Options::kPreload:
195 _hasDynamicSymbolTableLoadCommand = opts.positionIndependentExecutable();
198 _hasRPathLoadCommands = (_options.rpaths().size() != 0);
199 _hasSubFrameworkLoadCommand = (_options.umbrellaName() != NULL);
200 _hasVersionLoadCommand = _options.addVersionLoadCommand();
201 _hasFunctionStartsLoadCommand = _options.addFunctionStarts();
202 _dylibLoadCommmandsCount = _writer.dylibCount();
203 _allowableClientLoadCommmandsCount = _options.allowableClients().size();
204 _dyldEnvironExrasCount = _options.dyldEnvironExtras().size();
205 if ( ! _options.useSimplifiedDylibReExports() ) {
206 // target OS does not support LC_REEXPORT_DYLIB, so use old complicated load commands
207 for(uint32_t ord=1; ord <= _writer.dylibCount(); ++ord) {
208 const ld::dylib::File* dylib = _writer.dylibByOrdinal(ord);
209 if ( dylib->willBeReExported() ) {
210 // if child says it is an sub-framework of the image being created, then nothing to do here
211 bool isSubFramework = false;
212 const char* childInUmbrella = dylib->parentUmbrella();
213 if ( childInUmbrella != NULL ) {
214 const char* myLeaf = strrchr(_options.installPath(), '/');
215 if ( myLeaf != NULL ) {
216 if ( strcmp(childInUmbrella, &myLeaf[1]) == 0 )
217 isSubFramework = true;
220 // LC_SUB_FRAMEWORK is in child, so do nothing in parent
221 if ( ! isSubFramework ) {
222 // this dylib also needs a sub_x load command
223 bool isFrameworkReExport = false;
224 const char* lastSlash = strrchr(dylib->installPath(), '/');
225 if ( lastSlash != NULL ) {
226 char frameworkName[strlen(lastSlash)+20];
227 sprintf(frameworkName, "/%s.framework/", &lastSlash[1]);
228 isFrameworkReExport = (strstr(dylib->installPath(), frameworkName) != NULL);
230 if ( isFrameworkReExport ) {
231 // needs a LC_SUB_UMBRELLA command
232 _subUmbrellaNames.push_back(&lastSlash[1]);
235 // needs a LC_SUB_LIBRARY command
236 const char* nameStart = &lastSlash[1];
237 if ( lastSlash == NULL )
238 nameStart = dylib->installPath();
239 int len = strlen(nameStart);
240 const char* dot = strchr(nameStart, '.');
242 len = dot - nameStart;
243 char* subLibName = new char[len+1];
244 strlcpy(subLibName, nameStart, len+1);
245 _subLibraryNames.push_back(subLibName);
253 template <typename A>
254 uint32_t HeaderAndLoadCommandsAtom<A>::alignedSize(uint32_t size)
256 if ( sizeof(pint_t) == 4 )
257 return ((size+3) & (-4)); // 4-byte align all load commands for 32-bit mach-o
259 return ((size+7) & (-8)); // 8-byte align all load commands for 64-bit mach-o
263 template <typename A>
264 unsigned int HeaderAndLoadCommandsAtom<A>::nonHiddenSectionCount() const
266 unsigned int count = 0;
267 for (std::vector<ld::Internal::FinalSection*>::iterator it = _state.sections.begin(); it != _state.sections.end(); ++it) {
268 if ( ! (*it)->isSectionHidden() && ((*it)->type() != ld::Section::typeTentativeDefs) )
274 template <typename A>
275 unsigned int HeaderAndLoadCommandsAtom<A>::segmentCount() const
277 if ( _options.outputKind() == Options::kObjectFile ) {
278 // .o files have one anonymous segment that contains all sections
282 unsigned int count = 0;
283 const char* lastSegName = "";
284 for (std::vector<ld::Internal::FinalSection*>::iterator it = _state.sections.begin(); it != _state.sections.end(); ++it) {
285 if ( _options.outputKind() == Options::kPreload ) {
286 if ( (*it)->type() == ld::Section::typeMachHeader )
287 continue; // for -preload, don't put hidden __HEADER segment into output
288 if ( (*it)->type() == ld::Section::typeLinkEdit )
289 continue; // for -preload, don't put hidden __LINKEDIT segment into output
291 if ( strcmp(lastSegName, (*it)->segmentName()) != 0 ) {
292 lastSegName = (*it)->segmentName();
300 template <typename A>
301 uint64_t HeaderAndLoadCommandsAtom<A>::size() const
303 uint32_t sz = sizeof(macho_header<P>);
305 sz += sizeof(macho_segment_command<P>) * this->segmentCount();
306 sz += sizeof(macho_section<P>) * this->nonHiddenSectionCount();
308 if ( _hasDylibIDLoadCommand )
309 sz += alignedSize(sizeof(macho_dylib_command<P>) + strlen(_options.installPath()) + 1);
311 if ( _hasDyldInfoLoadCommand )
312 sz += sizeof(macho_dyld_info_command<P>);
314 if ( _hasSymbolTableLoadCommand )
315 sz += sizeof(macho_symtab_command<P>);
317 if ( _hasDynamicSymbolTableLoadCommand )
318 sz += sizeof(macho_dysymtab_command<P>);
320 if ( _hasDyldLoadCommand )
321 sz += alignedSize(sizeof(macho_dylinker_command<P>) + strlen(_options.dyldInstallPath()) + 1);
323 if ( _hasRoutinesLoadCommand )
324 sz += sizeof(macho_routines_command<P>);
326 if ( _hasUUIDLoadCommand )
327 sz += sizeof(macho_uuid_command<P>);
329 if ( _hasVersionLoadCommand )
330 sz += sizeof(macho_version_min_command<P>);
332 if ( _hasThreadLoadCommand )
333 sz += this->threadLoadCommandSize();
335 if ( _hasEncryptionLoadCommand )
336 sz += sizeof(macho_encryption_info_command<P>);
338 if ( _hasSplitSegInfoLoadCommand )
339 sz += sizeof(macho_linkedit_data_command<P>);
341 for(uint32_t ord=1; ord <= _writer.dylibCount(); ++ord) {
342 sz += alignedSize(sizeof(macho_dylib_command<P>) + strlen(_writer.dylibByOrdinal(ord)->installPath()) + 1);
345 if ( _hasRPathLoadCommands ) {
346 const std::vector<const char*>& rpaths = _options.rpaths();
347 for (std::vector<const char*>::const_iterator it = rpaths.begin(); it != rpaths.end(); ++it) {
348 sz += alignedSize(sizeof(macho_rpath_command<P>) + strlen(*it) + 1);
352 if ( _hasSubFrameworkLoadCommand )
353 sz += alignedSize(sizeof(macho_sub_framework_command<P>) + strlen(_options.umbrellaName()) + 1);
355 for (std::vector<const char*>::const_iterator it = _subLibraryNames.begin(); it != _subLibraryNames.end(); ++it) {
356 sz += alignedSize(sizeof(macho_sub_library_command<P>) + strlen(*it) + 1);
359 for (std::vector<const char*>::const_iterator it = _subUmbrellaNames.begin(); it != _subUmbrellaNames.end(); ++it) {
360 sz += alignedSize(sizeof(macho_sub_umbrella_command<P>) + strlen(*it) + 1);
363 if ( _allowableClientLoadCommmandsCount != 0 ) {
364 const std::vector<const char*>& clients = _options.allowableClients();
365 for (std::vector<const char*>::const_iterator it = clients.begin(); it != clients.end(); ++it) {
366 sz += alignedSize(sizeof(macho_sub_client_command<P>) + strlen(*it) + 1);
370 if ( _dyldEnvironExrasCount != 0 ) {
371 const std::vector<const char*>& extras = _options.dyldEnvironExtras();
372 for (std::vector<const char*>::const_iterator it = extras.begin(); it != extras.end(); ++it) {
373 sz += alignedSize(sizeof(macho_dylinker_command<P>) + strlen(*it) + 1);
377 if ( _hasFunctionStartsLoadCommand )
378 sz += sizeof(macho_linkedit_data_command<P>);
383 template <typename A>
384 uint32_t HeaderAndLoadCommandsAtom<A>::commandsCount() const
386 uint32_t count = this->segmentCount();
388 if ( _hasDylibIDLoadCommand )
391 if ( _hasDyldInfoLoadCommand )
394 if ( _hasSymbolTableLoadCommand )
397 if ( _hasDynamicSymbolTableLoadCommand )
400 if ( _hasDyldLoadCommand )
403 if ( _hasRoutinesLoadCommand )
406 if ( _hasUUIDLoadCommand )
409 if ( _hasVersionLoadCommand )
412 if ( _hasThreadLoadCommand )
415 if ( _hasEncryptionLoadCommand )
418 if ( _hasSplitSegInfoLoadCommand )
421 count += _dylibLoadCommmandsCount;
423 count += _options.rpaths().size();
425 if ( _hasSubFrameworkLoadCommand )
428 count += _subLibraryNames.size();
430 count += _subUmbrellaNames.size();
432 count += _allowableClientLoadCommmandsCount;
434 count += _dyldEnvironExrasCount;
436 if ( _hasFunctionStartsLoadCommand )
442 template <typename A>
443 uint32_t HeaderAndLoadCommandsAtom<A>::fileType() const
445 switch ( _options.outputKind() ) {
446 case Options::kDynamicExecutable:
447 case Options::kStaticExecutable:
449 case Options::kDynamicLibrary:
451 case Options::kDynamicBundle:
453 case Options::kObjectFile:
457 case Options::kPreload:
459 case Options::kKextBundle:
460 return MH_KEXT_BUNDLE;
462 throw "unknonwn mach-o file type";
465 template <typename A>
466 uint32_t HeaderAndLoadCommandsAtom<A>::flags() const
469 if ( _options.outputKind() == Options::kObjectFile ) {
470 if ( _state.allObjectFilesScatterable )
471 bits = MH_SUBSECTIONS_VIA_SYMBOLS;
474 if ( _options.outputKind() == Options::kStaticExecutable ) {
477 else if ( _options.outputKind() == Options::kPreload ) {
479 if ( _options.positionIndependentExecutable() )
484 switch ( _options.nameSpace() ) {
485 case Options::kTwoLevelNameSpace:
486 bits |= MH_TWOLEVEL | MH_NOUNDEFS;
488 case Options::kFlatNameSpace:
490 case Options::kForceFlatNameSpace:
491 bits |= MH_FORCE_FLAT;
494 if ( _writer.hasWeakExternalSymbols || _writer.overridesWeakExternalSymbols )
495 bits |= MH_WEAK_DEFINES;
496 if ( _writer.usesWeakExternalSymbols || _writer.hasWeakExternalSymbols )
497 bits |= MH_BINDS_TO_WEAK;
498 if ( _options.prebind() )
500 if ( _options.splitSeg() )
501 bits |= MH_SPLIT_SEGS;
502 if ( (_options.outputKind() == Options::kDynamicLibrary)
503 && _writer._noReExportedDylibs
504 && _options.useSimplifiedDylibReExports() ) {
505 bits |= MH_NO_REEXPORTED_DYLIBS;
507 if ( _options.positionIndependentExecutable() && ! _writer.pieDisabled )
509 if ( _options.markAutoDeadStripDylib() )
510 bits |= MH_DEAD_STRIPPABLE_DYLIB;
511 if ( _writer.hasThreadLocalVariableDefinitions )
512 bits |= MH_HAS_TLV_DESCRIPTORS;
513 if ( _options.hasNonExecutableHeap() )
514 bits |= MH_NO_HEAP_EXECUTION;
516 if ( _options.hasExecutableStack() )
517 bits |= MH_ALLOW_STACK_EXECUTION;
522 template <> uint32_t HeaderAndLoadCommandsAtom<x86>::magic() const { return MH_MAGIC; }
523 template <> uint32_t HeaderAndLoadCommandsAtom<x86_64>::magic() const { return MH_MAGIC_64; }
524 template <> uint32_t HeaderAndLoadCommandsAtom<arm>::magic() const { return MH_MAGIC; }
526 template <> uint32_t HeaderAndLoadCommandsAtom<x86>::cpuType() const { return CPU_TYPE_I386; }
527 template <> uint32_t HeaderAndLoadCommandsAtom<x86_64>::cpuType() const { return CPU_TYPE_X86_64; }
528 template <> uint32_t HeaderAndLoadCommandsAtom<arm>::cpuType() const { return CPU_TYPE_ARM; }
533 uint32_t HeaderAndLoadCommandsAtom<x86>::cpuSubType() const
535 return CPU_SUBTYPE_I386_ALL;
539 uint32_t HeaderAndLoadCommandsAtom<x86_64>::cpuSubType() const
541 if ( (_options.outputKind() == Options::kDynamicExecutable) && (_options.macosxVersionMin() >= ld::mac10_5) )
542 return (CPU_SUBTYPE_X86_64_ALL | 0x80000000);
544 return CPU_SUBTYPE_X86_64_ALL;
548 uint32_t HeaderAndLoadCommandsAtom<arm>::cpuSubType() const
550 return _state.cpuSubType;
555 template <typename A>
556 uint8_t* HeaderAndLoadCommandsAtom<A>::copySingleSegmentLoadCommand(uint8_t* p) const
558 // in .o files there is just one segment load command with a blank name
559 // and all sections under it
560 macho_segment_command<P>* cmd = (macho_segment_command<P>*)p;
561 cmd->set_cmd(macho_segment_command<P>::CMD);
562 cmd->set_segname("");
563 cmd->set_vmaddr(_options.baseAddress());
564 cmd->set_vmsize(0); // updated after sections set
565 cmd->set_fileoff(0); // updated after sections set
566 cmd->set_filesize(0); // updated after sections set
567 cmd->set_maxprot(VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE);
568 cmd->set_initprot(VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE);
569 cmd->set_nsects(this->nonHiddenSectionCount());
571 // add sections array
572 macho_section<P>* msect = (macho_section<P>*)&p[sizeof(macho_segment_command<P>)];
573 for (std::vector<ld::Internal::FinalSection*>::iterator sit = _state.sections.begin(); sit != _state.sections.end(); ++sit) {
574 ld::Internal::FinalSection* fsect = *sit;
575 if ( fsect->isSectionHidden() )
577 if ( fsect->type() == ld::Section::typeTentativeDefs )
579 msect->set_sectname(fsect->sectionName());
580 msect->set_segname(fsect->segmentName());
581 msect->set_addr(fsect->address);
582 msect->set_size(fsect->size);
583 msect->set_offset(fsect->fileOffset);
584 msect->set_align(fsect->alignment);
585 msect->set_reloff((fsect->relocCount == 0) ? 0 : _writer.sectionRelocationsSection->fileOffset + fsect->relocStart * sizeof(macho_relocation_info<P>));
586 msect->set_nreloc(fsect->relocCount);
587 msect->set_flags(sectionFlags(fsect));
588 msect->set_reserved1(fsect->indirectSymTabStartIndex);
589 msect->set_reserved2(fsect->indirectSymTabElementSize);
590 // update segment info
591 if ( cmd->fileoff() == 0 )
592 cmd->set_fileoff(fsect->fileOffset);
593 cmd->set_vmsize(fsect->address + fsect->size - cmd->vmaddr());
594 if ( (fsect->type() != ld::Section::typeZeroFill) && (fsect->type() != ld::Section::typeTentativeDefs) )
595 cmd->set_filesize(fsect->fileOffset + fsect->size - cmd->fileoff());
598 cmd->set_cmdsize(sizeof(macho_segment_command<P>) + cmd->nsects()*sizeof(macho_section<P>));
599 return p + cmd->cmdsize();
603 SegInfo(const char* n, const Options&);
605 uint32_t nonHiddenSectionCount;
608 std::vector<ld::Internal::FinalSection*> sections;
612 SegInfo::SegInfo(const char* n, const Options& opts)
613 : segName(n), nonHiddenSectionCount(0), maxProt(opts.maxSegProtection(n)), initProt(opts.initialSegProtection(n))
618 template <typename A>
619 uint32_t HeaderAndLoadCommandsAtom<A>::sectionFlags(ld::Internal::FinalSection* sect) const
622 switch ( sect->type() ) {
623 case ld::Section::typeUnclassified:
624 if ( strcmp(sect->segmentName(), "__OBJC") == 0 )
625 return S_REGULAR | S_ATTR_NO_DEAD_STRIP;
626 else if ( (strcmp(sect->sectionName(), "__objc_classlist") == 0) && (strcmp(sect->segmentName(), "__DATA") == 0) )
627 return S_REGULAR | S_ATTR_NO_DEAD_STRIP;
628 else if ( (strcmp(sect->sectionName(), "__objc_catlist") == 0) && (strcmp(sect->segmentName(), "__DATA") == 0) )
629 return S_REGULAR | S_ATTR_NO_DEAD_STRIP;
630 else if ( (strncmp(sect->sectionName(), "__objc_superrefs", 16) == 0) && (strcmp(sect->segmentName(), "__DATA") == 0) )
631 return S_REGULAR | S_ATTR_NO_DEAD_STRIP;
632 else if ( (strncmp(sect->sectionName(), "__objc_nlclslist", 16) == 0) && (strcmp(sect->segmentName(), "__DATA") == 0) )
633 return S_REGULAR | S_ATTR_NO_DEAD_STRIP;
636 case ld::Section::typeCode:
637 bits = S_REGULAR | S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS;
638 if ( sect->hasLocalRelocs && ! _writer.pieDisabled )
639 bits |= S_ATTR_LOC_RELOC;
640 if ( sect->hasExternalRelocs )
641 bits |= S_ATTR_EXT_RELOC;
643 case ld::Section::typePageZero:
645 case ld::Section::typeImportProxies:
647 case ld::Section::typeLinkEdit:
649 case ld::Section::typeMachHeader:
651 case ld::Section::typeStack:
653 case ld::Section::typeLiteral4:
654 return S_4BYTE_LITERALS;
655 case ld::Section::typeLiteral8:
656 return S_8BYTE_LITERALS;
657 case ld::Section::typeLiteral16:
658 return S_16BYTE_LITERALS;
659 case ld::Section::typeConstants:
661 case ld::Section::typeTempLTO:
662 assert(0 && "typeTempLTO should not make it to final linked image");
664 case ld::Section::typeAbsoluteSymbols:
665 assert(0 && "typeAbsoluteSymbols should not make it to final linked image");
667 case ld::Section::typeCString:
668 case ld::Section::typeNonStdCString:
669 return S_CSTRING_LITERALS;
670 case ld::Section::typeCStringPointer:
671 return S_LITERAL_POINTERS | S_ATTR_NO_DEAD_STRIP;
672 case ld::Section::typeUTF16Strings:
674 case ld::Section::typeCFString:
676 case ld::Section::typeObjC1Classes:
677 return S_REGULAR | S_ATTR_NO_DEAD_STRIP;
678 case ld::Section::typeCFI:
680 case ld::Section::typeLSDA:
682 case ld::Section::typeDtraceDOF:
684 case ld::Section::typeUnwindInfo:
686 case ld::Section::typeObjCClassRefs:
687 case ld::Section::typeObjC2CategoryList:
688 return S_REGULAR | S_ATTR_NO_DEAD_STRIP;
689 case ld::Section::typeZeroFill:
690 if ( _options.optimizeZeroFill() )
694 case ld::Section::typeTentativeDefs:
695 assert(0 && "typeTentativeDefs should not make it to final linked image");
697 case ld::Section::typeLazyPointer:
698 case ld::Section::typeLazyPointerClose:
699 return S_LAZY_SYMBOL_POINTERS;
700 case ld::Section::typeStubClose:
701 case ld::Section::typeStub:
702 if ( sect->hasLocalRelocs )
703 return S_SYMBOL_STUBS | S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS | S_ATTR_LOC_RELOC;
705 return S_SYMBOL_STUBS | S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS;
706 case ld::Section::typeNonLazyPointer:
707 return S_NON_LAZY_SYMBOL_POINTERS;
708 case ld::Section::typeDyldInfo:
710 case ld::Section::typeLazyDylibPointer:
711 return S_LAZY_DYLIB_SYMBOL_POINTERS;
712 case ld::Section::typeStubHelper:
713 if ( sect->hasLocalRelocs )
714 return S_REGULAR | S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS | S_ATTR_LOC_RELOC;
716 return S_REGULAR | S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS;
717 case ld::Section::typeInitializerPointers:
718 return S_MOD_INIT_FUNC_POINTERS;
719 case ld::Section::typeTerminatorPointers:
720 return S_MOD_TERM_FUNC_POINTERS;
721 case ld::Section::typeTLVInitialValues:
722 return S_THREAD_LOCAL_REGULAR;
723 case ld::Section::typeTLVZeroFill:
724 return S_THREAD_LOCAL_ZEROFILL;
725 case ld::Section::typeTLVDefs:
726 return S_THREAD_LOCAL_VARIABLES;
727 case ld::Section::typeTLVInitializerPointers:
728 return S_THREAD_LOCAL_INIT_FUNCTION_POINTERS;
729 case ld::Section::typeTLVPointers:
730 return S_THREAD_LOCAL_VARIABLE_POINTERS;
731 case ld::Section::typeFirstSection:
732 assert(0 && "typeFirstSection should not make it to final linked image");
734 case ld::Section::typeLastSection:
735 assert(0 && "typeLastSection should not make it to final linked image");
737 case ld::Section::typeDebug:
738 return S_REGULAR | S_ATTR_DEBUG;
744 template <typename A>
745 bool HeaderAndLoadCommandsAtom<A>::sectionTakesNoDiskSpace(ld::Internal::FinalSection* sect) const
747 switch ( sect->type() ) {
748 case ld::Section::typeZeroFill:
749 case ld::Section::typeTLVZeroFill:
750 return _options.optimizeZeroFill();
751 case ld::Section::typeAbsoluteSymbols:
752 case ld::Section::typeTentativeDefs:
753 case ld::Section::typeLastSection:
762 template <typename A>
763 uint8_t* HeaderAndLoadCommandsAtom<A>::copySegmentLoadCommands(uint8_t* p) const
765 // group sections into segments
766 std::vector<SegInfo> segs;
767 const char* lastSegName = "";
768 for (std::vector<ld::Internal::FinalSection*>::iterator it = _state.sections.begin(); it != _state.sections.end(); ++it) {
769 ld::Internal::FinalSection* sect = *it;
770 if ( _options.outputKind() == Options::kPreload ) {
771 if ( (*it)->type() == ld::Section::typeMachHeader )
772 continue; // for -preload, don't put hidden __HEADER segment into output
773 if ( (*it)->type() == ld::Section::typeLinkEdit )
774 continue; // for -preload, don't put hidden __LINKEDIT segment into output
776 if ( strcmp(lastSegName, sect->segmentName()) != 0 ) {
777 SegInfo si(sect->segmentName(), _options);
779 lastSegName = sect->segmentName();
781 if ( ! sect->isSectionHidden() )
782 segs.back().nonHiddenSectionCount++;
783 segs.back().sections.push_back(sect);
785 // write out segment load commands for each section with trailing sections
786 for (std::vector<SegInfo>::iterator it = segs.begin(); it != segs.end(); ++it) {
788 ld::Internal::FinalSection* lastNonZeroFillSection = NULL;
789 for (int i=si.sections.size()-1; i >= 0; --i) {
790 if ( !sectionTakesNoDiskSpace(si.sections[i]) ) {
791 lastNonZeroFillSection = si.sections[i];
795 uint64_t vmsize = si.sections.back()->address + si.sections.back()->size - si.sections.front()->address;
796 vmsize = ((vmsize+_options.segmentAlignment()-1) & (-_options.segmentAlignment()));
797 uint64_t filesize = 0;
798 if ( lastNonZeroFillSection != NULL ) {
799 filesize = lastNonZeroFillSection->address + lastNonZeroFillSection->size - si.sections.front()->address;
800 // round up all segments to page aligned, except __LINKEDIT
801 if ( (si.sections[0]->type() != ld::Section::typeLinkEdit) && (si.sections[0]->type() != ld::Section::typeImportProxies) )
802 filesize = (filesize + _options.segmentAlignment()-1) & (-_options.segmentAlignment());
804 if ( si.sections.front()->type() == ld::Section::typePageZero )
806 else if ( si.sections.front()->type() == ld::Section::typeStack )
808 macho_segment_command<P>* segCmd = (macho_segment_command<P>*)p;
809 segCmd->set_cmd(macho_segment_command<P>::CMD);
810 segCmd->set_cmdsize(sizeof(macho_segment_command<P>) + si.nonHiddenSectionCount*sizeof(macho_section<P>));
811 segCmd->set_segname(si.sections.front()->segmentName());
812 segCmd->set_vmaddr(si.sections.front()->address);
813 segCmd->set_vmsize(vmsize);
814 segCmd->set_fileoff(si.sections.front()->fileOffset);
815 segCmd->set_filesize(filesize);
816 segCmd->set_maxprot(si.maxProt);
817 segCmd->set_initprot(si.initProt);
818 segCmd->set_nsects(si.nonHiddenSectionCount);
819 segCmd->set_flags(0);
820 p += sizeof(macho_segment_command<P>);
821 macho_section<P>* msect = (macho_section<P>*)p;
822 for (std::vector<ld::Internal::FinalSection*>::iterator sit = si.sections.begin(); sit != si.sections.end(); ++sit) {
823 ld::Internal::FinalSection* fsect = *sit;
824 if ( ! fsect->isSectionHidden() ) {
825 msect->set_sectname(fsect->sectionName());
826 msect->set_segname(fsect->segmentName());
827 msect->set_addr(fsect->address);
828 msect->set_size(fsect->size);
829 msect->set_offset(sectionTakesNoDiskSpace(fsect) ? 0 : fsect->fileOffset);
830 msect->set_align(fsect->alignment);
831 msect->set_reloff(0);
832 msect->set_nreloc(0);
833 msect->set_flags(sectionFlags(fsect));
834 msect->set_reserved1(fsect->indirectSymTabStartIndex);
835 msect->set_reserved2(fsect->indirectSymTabElementSize);
836 p += sizeof(macho_section<P>);
846 template <typename A>
847 uint8_t* HeaderAndLoadCommandsAtom<A>::copySymbolTableLoadCommand(uint8_t* p) const
849 // build LC_SYMTAB command
850 macho_symtab_command<P>* symbolTableCmd = (macho_symtab_command<P>*)p;
851 symbolTableCmd->set_cmd(LC_SYMTAB);
852 symbolTableCmd->set_cmdsize(sizeof(macho_symtab_command<P>));
853 symbolTableCmd->set_nsyms(_writer.symbolTableSection->size/sizeof(macho_nlist<P>));
854 symbolTableCmd->set_symoff(_writer.symbolTableSection->size == 0 ? 0 : _writer.symbolTableSection->fileOffset);
855 symbolTableCmd->set_stroff(_writer.stringPoolSection->size == 0 ? 0 : _writer.stringPoolSection->fileOffset );
856 symbolTableCmd->set_strsize(_writer.stringPoolSection->size);
857 return p + sizeof(macho_symtab_command<P>);
860 template <typename A>
861 uint8_t* HeaderAndLoadCommandsAtom<A>::copyDynamicSymbolTableLoadCommand(uint8_t* p) const
863 // build LC_SYMTAB command
864 macho_dysymtab_command<P>* dynamicSymbolTableCmd = (macho_dysymtab_command<P>*)p;
865 dynamicSymbolTableCmd->set_cmd(LC_DYSYMTAB);
866 dynamicSymbolTableCmd->set_cmdsize(sizeof(macho_dysymtab_command<P>));
867 dynamicSymbolTableCmd->set_ilocalsym(0);
868 dynamicSymbolTableCmd->set_nlocalsym(_writer._localSymbolsCount);
869 dynamicSymbolTableCmd->set_iextdefsym(dynamicSymbolTableCmd->ilocalsym()+dynamicSymbolTableCmd->nlocalsym());
870 dynamicSymbolTableCmd->set_nextdefsym(_writer._globalSymbolsCount);
871 dynamicSymbolTableCmd->set_iundefsym(dynamicSymbolTableCmd->iextdefsym()+dynamicSymbolTableCmd->nextdefsym());
872 dynamicSymbolTableCmd->set_nundefsym(_writer._importSymbolsCount);
874 // FIX ME: support for 10.3 dylibs which need modules
875 //if ( fWriter.fModuleInfoAtom != NULL ) {
876 // dynamicSymbolTableCmd->set_tocoff(fWriter.fModuleInfoAtom->getTableOfContentsFileOffset());
877 // dynamicSymbolTableCmd->set_ntoc(fWriter.fSymbolTableExportCount);
878 // dynamicSymbolTableCmd->set_modtaboff(fWriter.fModuleInfoAtom->getModuleTableFileOffset());
879 // dynamicSymbolTableCmd->set_nmodtab(1);
880 // dynamicSymbolTableCmd->set_extrefsymoff(fWriter.fModuleInfoAtom->getReferencesFileOffset());
881 // dynamicSymbolTableCmd->set_nextrefsyms(fWriter.fModuleInfoAtom->getReferencesCount());
884 bool hasIndirectSymbols = ( (_writer.indirectSymbolTableSection != NULL) && (_writer.indirectSymbolTableSection->size != 0) );
885 dynamicSymbolTableCmd->set_indirectsymoff(hasIndirectSymbols ? _writer.indirectSymbolTableSection->fileOffset : 0);
886 dynamicSymbolTableCmd->set_nindirectsyms( hasIndirectSymbols ? _writer.indirectSymbolTableSection->size/sizeof(uint32_t) : 0);
888 // FIX ME: support for classic relocations
889 if ( _options.outputKind() != Options::kObjectFile ) {
890 bool hasExternalRelocs = ( (_writer.externalRelocationsSection != NULL) && (_writer.externalRelocationsSection->size != 0) );
891 dynamicSymbolTableCmd->set_extreloff(hasExternalRelocs ? _writer.externalRelocationsSection->fileOffset : 0);
892 dynamicSymbolTableCmd->set_nextrel( hasExternalRelocs ? _writer.externalRelocationsSection->size/8 : 0);
893 bool hasLocalRelocs = ( (_writer.localRelocationsSection != NULL) && (_writer.localRelocationsSection->size != 0) );
894 dynamicSymbolTableCmd->set_locreloff(hasLocalRelocs ? _writer.localRelocationsSection->fileOffset : 0);
895 dynamicSymbolTableCmd->set_nlocrel (hasLocalRelocs ? _writer.localRelocationsSection->size/8 : 0);
897 return p + sizeof(macho_dysymtab_command<P>);
901 template <typename A>
902 uint8_t* HeaderAndLoadCommandsAtom<A>::copyDyldInfoLoadCommand(uint8_t* p) const
904 // build LC_DYLD_INFO command
905 macho_dyld_info_command<P>* cmd = (macho_dyld_info_command<P>*)p;
907 cmd->set_cmd(LC_DYLD_INFO_ONLY);
908 cmd->set_cmdsize(sizeof(macho_dyld_info_command<P>));
909 if ( _writer.rebaseSection->size != 0 ) {
910 cmd->set_rebase_off(_writer.rebaseSection->fileOffset);
911 cmd->set_rebase_size(_writer.rebaseSection->size);
913 if ( _writer.bindingSection->size != 0 ) {
914 cmd->set_bind_off(_writer.bindingSection->fileOffset);
915 cmd->set_bind_size(_writer.bindingSection->size);
917 if ( _writer.weakBindingSection->size != 0 ) {
918 cmd->set_weak_bind_off(_writer.weakBindingSection->fileOffset);
919 cmd->set_weak_bind_size(_writer.weakBindingSection->size);
921 if ( _writer.lazyBindingSection->size != 0 ) {
922 cmd->set_lazy_bind_off(_writer.lazyBindingSection->fileOffset);
923 cmd->set_lazy_bind_size(_writer.lazyBindingSection->size);
925 if ( _writer.exportSection->size != 0 ) {
926 cmd->set_export_off(_writer.exportSection->fileOffset);
927 cmd->set_export_size(_writer.exportSection->size);
929 return p + sizeof(macho_dyld_info_command<P>);
933 template <typename A>
934 uint8_t* HeaderAndLoadCommandsAtom<A>::copyDyldLoadCommand(uint8_t* p) const
936 uint32_t sz = alignedSize(sizeof(macho_dylinker_command<P>) + strlen(_options.dyldInstallPath()) + 1);
937 macho_dylinker_command<P>* cmd = (macho_dylinker_command<P>*)p;
938 if ( _options.outputKind() == Options::kDyld )
939 cmd->set_cmd(LC_ID_DYLINKER);
941 cmd->set_cmd(LC_LOAD_DYLINKER);
942 cmd->set_cmdsize(sz);
943 cmd->set_name_offset();
944 strcpy((char*)&p[sizeof(macho_dylinker_command<P>)], _options.dyldInstallPath());
949 template <typename A>
950 uint8_t* HeaderAndLoadCommandsAtom<A>::copyDylibIDLoadCommand(uint8_t* p) const
952 uint32_t sz = alignedSize(sizeof(macho_dylib_command<P>) + strlen(_options.installPath()) + 1);
953 macho_dylib_command<P>* cmd = (macho_dylib_command<P>*)p;
954 cmd->set_cmd(LC_ID_DYLIB);
955 cmd->set_cmdsize(sz);
956 cmd->set_name_offset();
957 cmd->set_timestamp(1); // needs to be some constant value that is different than DylibLoadCommandsAtom uses
958 cmd->set_current_version(_options.currentVersion32());
959 cmd->set_compatibility_version(_options.compatibilityVersion());
960 strcpy((char*)&p[sizeof(macho_dylib_command<P>)], _options.installPath());
964 template <typename A>
965 uint8_t* HeaderAndLoadCommandsAtom<A>::copyRoutinesLoadCommand(uint8_t* p) const
967 pint_t initAddr = _state.entryPoint->finalAddress();
968 if ( _state.entryPoint->isThumb() )
970 macho_routines_command<P>* cmd = (macho_routines_command<P>*)p;
971 cmd->set_cmd(macho_routines_command<P>::CMD);
972 cmd->set_cmdsize(sizeof(macho_routines_command<P>));
973 cmd->set_init_address(initAddr);
974 return p + sizeof(macho_routines_command<P>);
978 template <typename A>
979 void HeaderAndLoadCommandsAtom<A>::recopyUUIDCommand()
981 assert(_uuidCmdInOutputBuffer != NULL);
982 _uuidCmdInOutputBuffer->set_uuid(_uuid);
986 template <typename A>
987 uint8_t* HeaderAndLoadCommandsAtom<A>::copyUUIDLoadCommand(uint8_t* p) const
989 macho_uuid_command<P>* cmd = (macho_uuid_command<P>*)p;
990 cmd->set_cmd(LC_UUID);
991 cmd->set_cmdsize(sizeof(macho_uuid_command<P>));
992 cmd->set_uuid(_uuid);
993 _uuidCmdInOutputBuffer = cmd; // save for later re-write by recopyUUIDCommand()
994 return p + sizeof(macho_uuid_command<P>);
998 template <typename A>
999 uint8_t* HeaderAndLoadCommandsAtom<A>::copyVersionLoadCommand(uint8_t* p) const
1001 macho_version_min_command<P>* cmd = (macho_version_min_command<P>*)p;
1002 ld::MacVersionMin macVersion = _options.macosxVersionMin();
1003 ld::IOSVersionMin iOSVersion = _options.iOSVersionMin();
1004 assert( (macVersion != ld::macVersionUnset) || (iOSVersion != ld::iOSVersionUnset) );
1005 if ( macVersion != ld::macVersionUnset ) {
1006 cmd->set_cmd(LC_VERSION_MIN_MACOSX);
1007 cmd->set_cmdsize(sizeof(macho_version_min_command<P>));
1008 cmd->set_version((uint32_t)macVersion);
1012 cmd->set_cmd(LC_VERSION_MIN_IPHONEOS);
1013 cmd->set_cmdsize(sizeof(macho_version_min_command<P>));
1014 cmd->set_version((uint32_t)iOSVersion);
1017 return p + sizeof(macho_version_min_command<P>);
1023 uint32_t HeaderAndLoadCommandsAtom<x86>::threadLoadCommandSize() const
1025 return this->alignedSize(16 + 16*4); // base size + i386_THREAD_STATE_COUNT * 4
1029 uint8_t* HeaderAndLoadCommandsAtom<x86>::copyThreadsLoadCommand(uint8_t* p) const
1031 assert(_state.entryPoint != NULL);
1032 pint_t start = _state.entryPoint->finalAddress();
1033 macho_thread_command<P>* cmd = (macho_thread_command<P>*)p;
1034 cmd->set_cmd(LC_UNIXTHREAD);
1035 cmd->set_cmdsize(threadLoadCommandSize());
1036 cmd->set_flavor(1); // i386_THREAD_STATE
1037 cmd->set_count(16); // i386_THREAD_STATE_COUNT;
1038 cmd->set_thread_register(10, start);
1039 if ( _options.hasCustomStack() )
1040 cmd->set_thread_register(7, _options.customStackAddr()); // r1
1041 return p + threadLoadCommandSize();
1045 uint32_t HeaderAndLoadCommandsAtom<x86_64>::threadLoadCommandSize() const
1047 return this->alignedSize(16 + x86_THREAD_STATE64_COUNT * 4);
1051 uint8_t* HeaderAndLoadCommandsAtom<x86_64>::copyThreadsLoadCommand(uint8_t* p) const
1053 assert(_state.entryPoint != NULL);
1054 pint_t start = _state.entryPoint->finalAddress();
1055 macho_thread_command<P>* cmd = (macho_thread_command<P>*)p;
1056 cmd->set_cmd(LC_UNIXTHREAD);
1057 cmd->set_cmdsize(threadLoadCommandSize());
1058 cmd->set_flavor(x86_THREAD_STATE64);
1059 cmd->set_count(x86_THREAD_STATE64_COUNT);
1060 cmd->set_thread_register(16, start); // rip
1061 if ( _options.hasCustomStack() )
1062 cmd->set_thread_register(7, _options.customStackAddr()); // r1
1063 return p + threadLoadCommandSize();
1067 uint32_t HeaderAndLoadCommandsAtom<arm>::threadLoadCommandSize() const
1069 return this->alignedSize(16 + 17 * 4); // base size + ARM_THREAD_STATE_COUNT * 4
1073 uint8_t* HeaderAndLoadCommandsAtom<arm>::copyThreadsLoadCommand(uint8_t* p) const
1075 assert(_state.entryPoint != NULL);
1076 pint_t start = _state.entryPoint->finalAddress();
1077 if ( _state.entryPoint->isThumb() )
1079 macho_thread_command<P>* cmd = (macho_thread_command<P>*)p;
1080 cmd->set_cmd(LC_UNIXTHREAD);
1081 cmd->set_cmdsize(threadLoadCommandSize());
1084 cmd->set_thread_register(15, start); // pc
1085 if ( _options.hasCustomStack() )
1086 cmd->set_thread_register(13, _options.customStackAddr()); // sp
1087 return p + threadLoadCommandSize();
1090 template <typename A>
1091 uint8_t* HeaderAndLoadCommandsAtom<A>::copyEncryptionLoadCommand(uint8_t* p) const
1093 macho_encryption_info_command<P>* cmd = (macho_encryption_info_command<P>*)p;
1094 cmd->set_cmd(LC_ENCRYPTION_INFO);
1095 cmd->set_cmdsize(sizeof(macho_encryption_info_command<P>));
1096 assert(_writer.encryptedTextStartOffset() != 0);
1097 assert(_writer.encryptedTextEndOffset() != 0);
1098 cmd->set_cryptoff(_writer.encryptedTextStartOffset());
1099 cmd->set_cryptsize(_writer.encryptedTextEndOffset()-_writer.encryptedTextStartOffset());
1100 cmd->set_cryptid(0);
1101 return p + sizeof(macho_encryption_info_command<P>);
1105 template <typename A>
1106 uint8_t* HeaderAndLoadCommandsAtom<A>::copySplitSegInfoLoadCommand(uint8_t* p) const
1108 macho_linkedit_data_command<P>* cmd = (macho_linkedit_data_command<P>*)p;
1109 cmd->set_cmd(LC_SEGMENT_SPLIT_INFO);
1110 cmd->set_cmdsize(sizeof(macho_linkedit_data_command<P>));
1111 cmd->set_dataoff(_writer.splitSegInfoSection->fileOffset);
1112 cmd->set_datasize(_writer.splitSegInfoSection->size);
1113 return p + sizeof(macho_linkedit_data_command<P>);
1117 template <typename A>
1118 uint8_t* HeaderAndLoadCommandsAtom<A>::copyDylibLoadCommand(uint8_t* p, const ld::dylib::File* dylib) const
1120 uint32_t sz = alignedSize(sizeof(macho_dylib_command<P>) + strlen(dylib->installPath()) + 1);
1121 macho_dylib_command<P>* cmd = (macho_dylib_command<P>*)p;
1122 if ( dylib->willBeLazyLoadedDylib() )
1123 cmd->set_cmd(LC_LAZY_LOAD_DYLIB);
1124 else if ( dylib->forcedWeakLinked() || dylib->allSymbolsAreWeakImported() )
1125 cmd->set_cmd(LC_LOAD_WEAK_DYLIB);
1126 else if ( dylib->willBeReExported() && _options.useSimplifiedDylibReExports() )
1127 cmd->set_cmd(LC_REEXPORT_DYLIB);
1128 else if ( dylib->willBeUpwardDylib() && _options.useUpwardDylibs() )
1129 cmd->set_cmd(LC_LOAD_UPWARD_DYLIB);
1131 cmd->set_cmd(LC_LOAD_DYLIB);
1132 cmd->set_cmdsize(sz);
1133 cmd->set_timestamp(2); // needs to be some constant value that is different than DylibIDLoadCommandsAtom uses
1134 cmd->set_current_version(dylib->currentVersion());
1135 cmd->set_compatibility_version(dylib->compatibilityVersion());
1136 cmd->set_name_offset();
1137 strcpy((char*)&p[sizeof(macho_dylib_command<P>)], dylib->installPath());
1141 template <typename A>
1142 uint8_t* HeaderAndLoadCommandsAtom<A>::copyRPathLoadCommand(uint8_t* p, const char* path) const
1144 uint32_t sz = alignedSize(sizeof(macho_rpath_command<P>) + strlen(path) + 1);
1145 macho_rpath_command<P>* cmd = (macho_rpath_command<P>*)p;
1146 cmd->set_cmd(LC_RPATH);
1147 cmd->set_cmdsize(sz);
1148 cmd->set_path_offset();
1149 strcpy((char*)&p[sizeof(macho_rpath_command<P>)], path);
1153 template <typename A>
1154 uint8_t* HeaderAndLoadCommandsAtom<A>::copySubFrameworkLoadCommand(uint8_t* p) const
1156 const char* umbrellaName = _options.umbrellaName();
1157 uint32_t sz = alignedSize(sizeof(macho_sub_framework_command<P>) + strlen(umbrellaName) + 1);
1158 macho_sub_framework_command<P>* cmd = (macho_sub_framework_command<P>*)p;
1159 cmd->set_cmd(LC_SUB_FRAMEWORK);
1160 cmd->set_cmdsize(sz);
1161 cmd->set_umbrella_offset();
1162 strcpy((char*)&p[sizeof(macho_sub_framework_command<P>)], umbrellaName);
1167 template <typename A>
1168 uint8_t* HeaderAndLoadCommandsAtom<A>::copyAllowableClientLoadCommand(uint8_t* p, const char* client) const
1170 uint32_t sz = alignedSize(sizeof(macho_sub_client_command<P>) + strlen(client) + 1);
1171 macho_sub_client_command<P>* cmd = (macho_sub_client_command<P>*)p;
1172 cmd->set_cmd(LC_SUB_CLIENT);
1173 cmd->set_cmdsize(sz);
1174 cmd->set_client_offset();
1175 strcpy((char*)&p[sizeof(macho_sub_client_command<P>)], client);
1179 template <typename A>
1180 uint8_t* HeaderAndLoadCommandsAtom<A>::copyDyldEnvLoadCommand(uint8_t* p, const char* env) const
1182 uint32_t sz = alignedSize(sizeof(macho_dylinker_command<P>) + strlen(env) + 1);
1183 macho_dylinker_command<P>* cmd = (macho_dylinker_command<P>*)p;
1184 cmd->set_cmd(LC_DYLD_ENVIRONMENT);
1185 cmd->set_cmdsize(sz);
1186 cmd->set_name_offset();
1187 strcpy((char*)&p[sizeof(macho_dylinker_command<P>)], env);
1191 template <typename A>
1192 uint8_t* HeaderAndLoadCommandsAtom<A>::copySubUmbrellaLoadCommand(uint8_t* p, const char* nm) const
1194 uint32_t sz = alignedSize(sizeof(macho_sub_umbrella_command<P>) + strlen(nm) + 1);
1195 macho_sub_umbrella_command<P>* cmd = (macho_sub_umbrella_command<P>*)p;
1196 cmd->set_cmd(LC_SUB_UMBRELLA);
1197 cmd->set_cmdsize(sz);
1198 cmd->set_sub_umbrella_offset();
1199 strcpy((char*)&p[sizeof(macho_sub_umbrella_command<P>)], nm);
1203 template <typename A>
1204 uint8_t* HeaderAndLoadCommandsAtom<A>::copySubLibraryLoadCommand(uint8_t* p, const char* nm) const
1206 uint32_t sz = alignedSize(sizeof(macho_sub_library_command<P>) + strlen(nm) + 1);
1207 macho_sub_library_command<P>* cmd = (macho_sub_library_command<P>*)p;
1208 cmd->set_cmd(LC_SUB_LIBRARY);
1209 cmd->set_cmdsize(sz);
1210 cmd->set_sub_library_offset();
1211 strcpy((char*)&p[sizeof(macho_sub_library_command<P>)], nm);
1215 template <typename A>
1216 uint8_t* HeaderAndLoadCommandsAtom<A>::copyFunctionStartsLoadCommand(uint8_t* p) const
1218 macho_linkedit_data_command<P>* cmd = (macho_linkedit_data_command<P>*)p;
1219 cmd->set_cmd(LC_FUNCTION_STARTS);
1220 cmd->set_cmdsize(sizeof(macho_linkedit_data_command<P>));
1221 cmd->set_dataoff(_writer.functionStartsSection->fileOffset);
1222 cmd->set_datasize(_writer.functionStartsSection->size);
1223 return p + sizeof(macho_linkedit_data_command<P>);
1227 template <typename A>
1228 void HeaderAndLoadCommandsAtom<A>::copyRawContent(uint8_t buffer[]) const
1230 macho_header<P>* mh = (macho_header<P>*)buffer;
1231 bzero(buffer, this->size());
1234 mh->set_magic(this->magic());
1235 mh->set_cputype(this->cpuType());
1236 mh->set_cpusubtype(this->cpuSubType());
1237 mh->set_filetype(this->fileType());
1238 mh->set_ncmds(this->commandsCount());
1239 mh->set_sizeofcmds(this->size()-sizeof(macho_header<P>));
1240 mh->set_flags(this->flags());
1242 // copy load commands
1243 uint8_t* p = &buffer[sizeof(macho_header<P>)];
1245 if ( _options.outputKind() == Options::kObjectFile )
1246 p = this->copySingleSegmentLoadCommand(p);
1248 p = this->copySegmentLoadCommands(p);
1250 if ( _hasDylibIDLoadCommand )
1251 p = this->copyDylibIDLoadCommand(p);
1253 if ( _hasDyldInfoLoadCommand )
1254 p = this->copyDyldInfoLoadCommand(p);
1256 if ( _hasSymbolTableLoadCommand )
1257 p = this->copySymbolTableLoadCommand(p);
1259 if ( _hasDynamicSymbolTableLoadCommand )
1260 p = this->copyDynamicSymbolTableLoadCommand(p);
1262 if ( _hasDyldLoadCommand )
1263 p = this->copyDyldLoadCommand(p);
1265 if ( _hasRoutinesLoadCommand )
1266 p = this->copyRoutinesLoadCommand(p);
1268 if ( _hasUUIDLoadCommand )
1269 p = this->copyUUIDLoadCommand(p);
1271 if ( _hasVersionLoadCommand )
1272 p = this->copyVersionLoadCommand(p);
1274 if ( _hasThreadLoadCommand )
1275 p = this->copyThreadsLoadCommand(p);
1277 if ( _hasEncryptionLoadCommand )
1278 p = this->copyEncryptionLoadCommand(p);
1280 if ( _hasSplitSegInfoLoadCommand )
1281 p = this->copySplitSegInfoLoadCommand(p);
1283 for(uint32_t ord=1; ord <= _writer.dylibCount(); ++ord) {
1284 p = this->copyDylibLoadCommand(p, _writer.dylibByOrdinal(ord));
1287 if ( _hasRPathLoadCommands ) {
1288 const std::vector<const char*>& rpaths = _options.rpaths();
1289 for (std::vector<const char*>::const_iterator it = rpaths.begin(); it != rpaths.end(); ++it) {
1290 p = this->copyRPathLoadCommand(p, *it);
1294 if ( _hasSubFrameworkLoadCommand )
1295 p = this->copySubFrameworkLoadCommand(p);
1297 for (std::vector<const char*>::const_iterator it = _subLibraryNames.begin(); it != _subLibraryNames.end(); ++it) {
1298 p = this->copySubLibraryLoadCommand(p, *it);
1301 for (std::vector<const char*>::const_iterator it = _subUmbrellaNames.begin(); it != _subUmbrellaNames.end(); ++it) {
1302 p = this->copySubUmbrellaLoadCommand(p, *it);
1305 if ( _allowableClientLoadCommmandsCount != 0 ) {
1306 const std::vector<const char*>& clients = _options.allowableClients();
1307 for (std::vector<const char*>::const_iterator it = clients.begin(); it != clients.end(); ++it) {
1308 p = this->copyAllowableClientLoadCommand(p, *it);
1312 if ( _dyldEnvironExrasCount != 0 ) {
1313 const std::vector<const char*>& extras = _options.dyldEnvironExtras();
1314 for (std::vector<const char*>::const_iterator it = extras.begin(); it != extras.end(); ++it) {
1315 p = this->copyDyldEnvLoadCommand(p, *it);
1319 if ( _hasFunctionStartsLoadCommand )
1320 p = this->copyFunctionStartsLoadCommand(p);
1329 #endif // __HEADER_LOAD_COMMANDS_HPP__