]> git.saurik.com Git - apple/ld64.git/blame - src/ld/HeaderAndLoadCommands.hpp
ld64-128.2.tar.gz
[apple/ld64.git] / src / ld / HeaderAndLoadCommands.hpp
CommitLineData
a645023d
A
1/* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-*
2 *
3 * Copyright (c) 2009 Apple Inc. All rights reserved.
4 *
5 * @APPLE_LICENSE_HEADER_START@
6 *
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
12 * file.
13 *
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.
21 *
22 * @APPLE_LICENSE_HEADER_END@
23 */
24
25#ifndef __HEADER_LOAD_COMMANDS_HPP__
26#define __HEADER_LOAD_COMMANDS_HPP__
27
28#include <stdlib.h>
29#include <limits.h>
30#include <unistd.h>
31#include <mach-o/loader.h>
32
33#include <vector>
34
35#include "MachOFileAbstraction.hpp"
36#include "Options.h"
37#include "ld.hpp"
38
39namespace ld {
40namespace tool {
41
42class HeaderAndLoadCommandsAbtract : public ld::Atom
43{
44public:
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) { }
49
50 virtual void setUUID(const uint8_t digest[16]) = 0;
51 virtual void recopyUUIDCommand() = 0;
52};
53
54template <typename A>
55class HeaderAndLoadCommandsAtom : public HeaderAndLoadCommandsAbtract
56{
57public:
58 HeaderAndLoadCommandsAtom(const Options& opts, ld::Internal& state,
59 OutputFile& writer);
60
61 // overrides of ld::Atom
62 virtual ld::File* file() const { return NULL; }
63 virtual bool translationUnitSource(const char** dir, const char** nm) const
64 { return false; }
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;
69
70 // overrides of HeaderAndLoadCommandsAbtract
71 virtual void setUUID(const uint8_t digest[16]) { memcpy(_uuid, digest, 16); }
72 virtual void recopyUUIDCommand();
73
74private:
75 typedef typename A::P P;
76 typedef typename A::P::E E;
77 typedef typename A::P::uint_t pint_t;
78
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;
110
111 uint32_t sectionFlags(ld::Internal::FinalSection* sect) const;
112 bool sectionTakesNoDiskSpace(ld::Internal::FinalSection* sect) const;
113
114
115 const Options& _options;
116 ld::Internal& _state;
117 OutputFile& _writer;
118 pint_t _address;
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;
138 uint8_t _uuid[16];
139 mutable macho_uuid_command<P>* _uuidCmdInOutputBuffer;
140
141 static ld::Section _s_section;
142 static ld::Section _s_preload_section;
143};
144
145template <typename A>
146ld::Section HeaderAndLoadCommandsAtom<A>::_s_section("__TEXT", "__mach_header", ld::Section::typeMachHeader, true);
147template <typename A>
148ld::Section HeaderAndLoadCommandsAtom<A>::_s_preload_section("__HEADER", "__mach_header", ld::Section::typeMachHeader, true);
149
150
151template <typename A>
152HeaderAndLoadCommandsAtom<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)
159{
160 bzero(_uuid, 16);
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:
176 case Options::kDyld:
177 case Options::kKextBundle:
178 _hasDynamicSymbolTableLoadCommand = true;
179 break;
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;
187 break;
188 }
189 }
190 break;
191 case Options::kStaticExecutable:
192 _hasDynamicSymbolTableLoadCommand = false;
193 break;
194 case Options::kPreload:
195 _hasDynamicSymbolTableLoadCommand = opts.positionIndependentExecutable();
196 break;
197 }
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;
218 }
219 }
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);
229 }
230 if ( isFrameworkReExport ) {
231 // needs a LC_SUB_UMBRELLA command
232 _subUmbrellaNames.push_back(&lastSlash[1]);
233 }
234 else {
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, '.');
241 if ( dot != NULL )
242 len = dot - nameStart;
243 char* subLibName = new char[len+1];
244 strlcpy(subLibName, nameStart, len+1);
245 _subLibraryNames.push_back(subLibName);
246 }
247 }
248 }
249 }
250 }
251}
252
253template <typename A>
254uint32_t HeaderAndLoadCommandsAtom<A>::alignedSize(uint32_t size)
255{
256 if ( sizeof(pint_t) == 4 )
257 return ((size+3) & (-4)); // 4-byte align all load commands for 32-bit mach-o
258 else
259 return ((size+7) & (-8)); // 8-byte align all load commands for 64-bit mach-o
260}
261
262
263template <typename A>
264unsigned int HeaderAndLoadCommandsAtom<A>::nonHiddenSectionCount() const
265{
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) )
269 ++count;
270 }
271 return count;
272}
273
274template <typename A>
275unsigned int HeaderAndLoadCommandsAtom<A>::segmentCount() const
276{
277 if ( _options.outputKind() == Options::kObjectFile ) {
278 // .o files have one anonymous segment that contains all sections
279 return 1;
280 }
281
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
290 }
291 if ( strcmp(lastSegName, (*it)->segmentName()) != 0 ) {
292 lastSegName = (*it)->segmentName();
293 ++count;
294 }
295 }
296 return count;
297}
298
299
300template <typename A>
301uint64_t HeaderAndLoadCommandsAtom<A>::size() const
302{
303 uint32_t sz = sizeof(macho_header<P>);
304
305 sz += sizeof(macho_segment_command<P>) * this->segmentCount();
306 sz += sizeof(macho_section<P>) * this->nonHiddenSectionCount();
307
308 if ( _hasDylibIDLoadCommand )
309 sz += alignedSize(sizeof(macho_dylib_command<P>) + strlen(_options.installPath()) + 1);
310
311 if ( _hasDyldInfoLoadCommand )
312 sz += sizeof(macho_dyld_info_command<P>);
313
314 if ( _hasSymbolTableLoadCommand )
315 sz += sizeof(macho_symtab_command<P>);
316
317 if ( _hasDynamicSymbolTableLoadCommand )
318 sz += sizeof(macho_dysymtab_command<P>);
319
320 if ( _hasDyldLoadCommand )
321 sz += alignedSize(sizeof(macho_dylinker_command<P>) + strlen(_options.dyldInstallPath()) + 1);
322
323 if ( _hasRoutinesLoadCommand )
324 sz += sizeof(macho_routines_command<P>);
325
326 if ( _hasUUIDLoadCommand )
327 sz += sizeof(macho_uuid_command<P>);
328
329 if ( _hasVersionLoadCommand )
330 sz += sizeof(macho_version_min_command<P>);
331
332 if ( _hasThreadLoadCommand )
333 sz += this->threadLoadCommandSize();
334
335 if ( _hasEncryptionLoadCommand )
336 sz += sizeof(macho_encryption_info_command<P>);
337
338 if ( _hasSplitSegInfoLoadCommand )
339 sz += sizeof(macho_linkedit_data_command<P>);
340
341 for(uint32_t ord=1; ord <= _writer.dylibCount(); ++ord) {
342 sz += alignedSize(sizeof(macho_dylib_command<P>) + strlen(_writer.dylibByOrdinal(ord)->installPath()) + 1);
343 }
344
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);
349 }
350 }
351
352 if ( _hasSubFrameworkLoadCommand )
353 sz += alignedSize(sizeof(macho_sub_framework_command<P>) + strlen(_options.umbrellaName()) + 1);
354
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);
357 }
358
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);
361 }
362
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);
367 }
368 }
369
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);
374 }
375 }
376
377 if ( _hasFunctionStartsLoadCommand )
378 sz += sizeof(macho_linkedit_data_command<P>);
379
380 return sz;
381}
382
383template <typename A>
384uint32_t HeaderAndLoadCommandsAtom<A>::commandsCount() const
385{
386 uint32_t count = this->segmentCount();
387
388 if ( _hasDylibIDLoadCommand )
389 ++count;
390
391 if ( _hasDyldInfoLoadCommand )
392 ++count;
393
394 if ( _hasSymbolTableLoadCommand )
395 ++count;
396
397 if ( _hasDynamicSymbolTableLoadCommand )
398 ++count;
399
400 if ( _hasDyldLoadCommand )
401 ++count;
402
403 if ( _hasRoutinesLoadCommand )
404 ++count;
405
406 if ( _hasUUIDLoadCommand )
407 ++count;
408
409 if ( _hasVersionLoadCommand )
410 ++count;
411
412 if ( _hasThreadLoadCommand )
413 ++count;
414
415 if ( _hasEncryptionLoadCommand )
416 ++count;
417
418 if ( _hasSplitSegInfoLoadCommand )
419 ++count;
420
421 count += _dylibLoadCommmandsCount;
422
423 count += _options.rpaths().size();
424
425 if ( _hasSubFrameworkLoadCommand )
426 ++count;
427
428 count += _subLibraryNames.size();
429
430 count += _subUmbrellaNames.size();
431
432 count += _allowableClientLoadCommmandsCount;
433
434 count += _dyldEnvironExrasCount;
435
436 if ( _hasFunctionStartsLoadCommand )
437 ++count;
438
439 return count;
440}
441
442template <typename A>
443uint32_t HeaderAndLoadCommandsAtom<A>::fileType() const
444{
445 switch ( _options.outputKind() ) {
446 case Options::kDynamicExecutable:
447 case Options::kStaticExecutable:
448 return MH_EXECUTE;
449 case Options::kDynamicLibrary:
450 return MH_DYLIB;
451 case Options::kDynamicBundle:
452 return MH_BUNDLE;
453 case Options::kObjectFile:
454 return MH_OBJECT;
455 case Options::kDyld:
456 return MH_DYLINKER;
457 case Options::kPreload:
458 return MH_PRELOAD;
459 case Options::kKextBundle:
460 return MH_KEXT_BUNDLE;
461 }
462 throw "unknonwn mach-o file type";
463}
464
465template <typename A>
466uint32_t HeaderAndLoadCommandsAtom<A>::flags() const
467{
468 uint32_t bits = 0;
469 if ( _options.outputKind() == Options::kObjectFile ) {
470 if ( _state.allObjectFilesScatterable )
471 bits = MH_SUBSECTIONS_VIA_SYMBOLS;
472 }
473 else {
474 if ( _options.outputKind() == Options::kStaticExecutable ) {
475 bits |= MH_NOUNDEFS;
476 }
477 else if ( _options.outputKind() == Options::kPreload ) {
478 bits |= MH_NOUNDEFS;
479 if ( _options.positionIndependentExecutable() )
480 bits |= MH_PIE;
481 }
482 else {
483 bits = MH_DYLDLINK;
484 switch ( _options.nameSpace() ) {
485 case Options::kTwoLevelNameSpace:
486 bits |= MH_TWOLEVEL | MH_NOUNDEFS;
487 break;
488 case Options::kFlatNameSpace:
489 break;
490 case Options::kForceFlatNameSpace:
491 bits |= MH_FORCE_FLAT;
492 break;
493 }
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() )
499 bits |= MH_PREBOUND;
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;
506 }
507 if ( _options.positionIndependentExecutable() && ! _writer.pieDisabled )
508 bits |= MH_PIE;
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;
515 }
516 if ( _options.hasExecutableStack() )
517 bits |= MH_ALLOW_STACK_EXECUTION;
518 }
519 return bits;
520}
521
a645023d
A
522template <> uint32_t HeaderAndLoadCommandsAtom<x86>::magic() const { return MH_MAGIC; }
523template <> uint32_t HeaderAndLoadCommandsAtom<x86_64>::magic() const { return MH_MAGIC_64; }
524template <> uint32_t HeaderAndLoadCommandsAtom<arm>::magic() const { return MH_MAGIC; }
525
a645023d
A
526template <> uint32_t HeaderAndLoadCommandsAtom<x86>::cpuType() const { return CPU_TYPE_I386; }
527template <> uint32_t HeaderAndLoadCommandsAtom<x86_64>::cpuType() const { return CPU_TYPE_X86_64; }
528template <> uint32_t HeaderAndLoadCommandsAtom<arm>::cpuType() const { return CPU_TYPE_ARM; }
529
530
a645023d
A
531
532template <>
533uint32_t HeaderAndLoadCommandsAtom<x86>::cpuSubType() const
534{
535 return CPU_SUBTYPE_I386_ALL;
536}
537
538template <>
539uint32_t HeaderAndLoadCommandsAtom<x86_64>::cpuSubType() const
540{
541 if ( (_options.outputKind() == Options::kDynamicExecutable) && (_options.macosxVersionMin() >= ld::mac10_5) )
542 return (CPU_SUBTYPE_X86_64_ALL | 0x80000000);
543 else
544 return CPU_SUBTYPE_X86_64_ALL;
545}
546
547template <>
548uint32_t HeaderAndLoadCommandsAtom<arm>::cpuSubType() const
549{
550 return _state.cpuSubType;
551}
552
553
554
555template <typename A>
556uint8_t* HeaderAndLoadCommandsAtom<A>::copySingleSegmentLoadCommand(uint8_t* p) const
557{
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());
570 cmd->set_flags(0);
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() )
576 continue;
577 if ( fsect->type() == ld::Section::typeTentativeDefs )
578 continue;
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());
596 ++msect;
597 }
598 cmd->set_cmdsize(sizeof(macho_segment_command<P>) + cmd->nsects()*sizeof(macho_section<P>));
599 return p + cmd->cmdsize();
600}
601
602struct SegInfo {
603 SegInfo(const char* n, const Options&);
604 const char* segName;
605 uint32_t nonHiddenSectionCount;
606 uint32_t maxProt;
607 uint32_t initProt;
608 std::vector<ld::Internal::FinalSection*> sections;
609};
610
611
612SegInfo::SegInfo(const char* n, const Options& opts)
613 : segName(n), nonHiddenSectionCount(0), maxProt(opts.maxSegProtection(n)), initProt(opts.initialSegProtection(n))
614{
615}
616
617
618template <typename A>
619uint32_t HeaderAndLoadCommandsAtom<A>::sectionFlags(ld::Internal::FinalSection* sect) const
620{
621 uint32_t bits;
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;
afe874b1
A
632 else if ( (strncmp(sect->sectionName(), "__objc_nlclslist", 16) == 0) && (strcmp(sect->segmentName(), "__DATA") == 0) )
633 return S_REGULAR | S_ATTR_NO_DEAD_STRIP;
a645023d
A
634 else
635 return S_REGULAR;
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;
642 return bits;
643 case ld::Section::typePageZero:
644 return S_REGULAR;
645 case ld::Section::typeImportProxies:
646 return S_REGULAR;
647 case ld::Section::typeLinkEdit:
648 return S_REGULAR;
649 case ld::Section::typeMachHeader:
650 return S_REGULAR;
651 case ld::Section::typeStack:
652 return S_REGULAR;
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:
660 return S_REGULAR;
661 case ld::Section::typeTempLTO:
662 assert(0 && "typeTempLTO should not make it to final linked image");
663 return S_REGULAR;
664 case ld::Section::typeAbsoluteSymbols:
665 assert(0 && "typeAbsoluteSymbols should not make it to final linked image");
666 return S_REGULAR;
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:
673 return S_REGULAR;
674 case ld::Section::typeCFString:
675 return S_REGULAR;
676 case ld::Section::typeObjC1Classes:
677 return S_REGULAR | S_ATTR_NO_DEAD_STRIP;
678 case ld::Section::typeCFI:
679 return S_REGULAR;
680 case ld::Section::typeLSDA:
681 return S_REGULAR;
682 case ld::Section::typeDtraceDOF:
683 return S_DTRACE_DOF;
684 case ld::Section::typeUnwindInfo:
685 return S_REGULAR;
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() )
691 return S_ZEROFILL;
692 else
693 return S_REGULAR;
694 case ld::Section::typeTentativeDefs:
695 assert(0 && "typeTentativeDefs should not make it to final linked image");
696 return S_REGULAR;
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;
704 else
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:
709 return S_REGULAR;
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;
715 else
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");
733 return S_REGULAR;
734 case ld::Section::typeLastSection:
735 assert(0 && "typeLastSection should not make it to final linked image");
736 return S_REGULAR;
afe874b1
A
737 case ld::Section::typeDebug:
738 return S_REGULAR | S_ATTR_DEBUG;
a645023d
A
739 }
740 return S_REGULAR;
741}
742
743
744template <typename A>
745bool HeaderAndLoadCommandsAtom<A>::sectionTakesNoDiskSpace(ld::Internal::FinalSection* sect) const
746{
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:
754 return true;
755 default:
756 break;
757 }
758 return false;
759}
760
761
762template <typename A>
763uint8_t* HeaderAndLoadCommandsAtom<A>::copySegmentLoadCommands(uint8_t* p) const
764{
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
775 }
776 if ( strcmp(lastSegName, sect->segmentName()) != 0 ) {
777 SegInfo si(sect->segmentName(), _options);
778 segs.push_back(si);
779 lastSegName = sect->segmentName();
780 }
781 if ( ! sect->isSectionHidden() )
782 segs.back().nonHiddenSectionCount++;
783 segs.back().sections.push_back(sect);
784 }
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) {
787 SegInfo& si = *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];
792 break;
793 }
794 }
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());
803 }
804 if ( si.sections.front()->type() == ld::Section::typePageZero )
805 filesize = 0;
806 else if ( si.sections.front()->type() == ld::Section::typeStack )
807 filesize = 0;
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>);
837 ++msect;
838 }
839 }
840 }
841
842 return p;
843}
844
845
846template <typename A>
847uint8_t* HeaderAndLoadCommandsAtom<A>::copySymbolTableLoadCommand(uint8_t* p) const
848{
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>);
858}
859
860template <typename A>
861uint8_t* HeaderAndLoadCommandsAtom<A>::copyDynamicSymbolTableLoadCommand(uint8_t* p) const
862{
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);
873
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());
882 //}
883
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);
887
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);
896 }
897 return p + sizeof(macho_dysymtab_command<P>);
898}
899
900
901template <typename A>
902uint8_t* HeaderAndLoadCommandsAtom<A>::copyDyldInfoLoadCommand(uint8_t* p) const
903{
904 // build LC_DYLD_INFO command
905 macho_dyld_info_command<P>* cmd = (macho_dyld_info_command<P>*)p;
906
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);
912 }
913 if ( _writer.bindingSection->size != 0 ) {
914 cmd->set_bind_off(_writer.bindingSection->fileOffset);
915 cmd->set_bind_size(_writer.bindingSection->size);
916 }
917 if ( _writer.weakBindingSection->size != 0 ) {
918 cmd->set_weak_bind_off(_writer.weakBindingSection->fileOffset);
919 cmd->set_weak_bind_size(_writer.weakBindingSection->size);
920 }
921 if ( _writer.lazyBindingSection->size != 0 ) {
922 cmd->set_lazy_bind_off(_writer.lazyBindingSection->fileOffset);
923 cmd->set_lazy_bind_size(_writer.lazyBindingSection->size);
924 }
925 if ( _writer.exportSection->size != 0 ) {
926 cmd->set_export_off(_writer.exportSection->fileOffset);
927 cmd->set_export_size(_writer.exportSection->size);
928 }
929 return p + sizeof(macho_dyld_info_command<P>);
930}
931
932
933template <typename A>
934uint8_t* HeaderAndLoadCommandsAtom<A>::copyDyldLoadCommand(uint8_t* p) const
935{
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);
940 else
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());
945 return p + sz;
946}
947
948
949template <typename A>
950uint8_t* HeaderAndLoadCommandsAtom<A>::copyDylibIDLoadCommand(uint8_t* p) const
951{
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
b2fa67a8 958 cmd->set_current_version(_options.currentVersion32());
a645023d
A
959 cmd->set_compatibility_version(_options.compatibilityVersion());
960 strcpy((char*)&p[sizeof(macho_dylib_command<P>)], _options.installPath());
961 return p + sz;
962}
963
964template <typename A>
965uint8_t* HeaderAndLoadCommandsAtom<A>::copyRoutinesLoadCommand(uint8_t* p) const
966{
967 pint_t initAddr = _state.entryPoint->finalAddress();
968 if ( _state.entryPoint->isThumb() )
969 initAddr |= 1ULL;
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>);
975}
976
977
978template <typename A>
979void HeaderAndLoadCommandsAtom<A>::recopyUUIDCommand()
980{
981 assert(_uuidCmdInOutputBuffer != NULL);
982 _uuidCmdInOutputBuffer->set_uuid(_uuid);
983}
984
985
986template <typename A>
987uint8_t* HeaderAndLoadCommandsAtom<A>::copyUUIDLoadCommand(uint8_t* p) const
988{
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>);
995}
996
997
998template <typename A>
999uint8_t* HeaderAndLoadCommandsAtom<A>::copyVersionLoadCommand(uint8_t* p) const
1000{
1001 macho_version_min_command<P>* cmd = (macho_version_min_command<P>*)p;
afe874b1
A
1002 ld::MacVersionMin macVersion = _options.macosxVersionMin();
1003 ld::IOSVersionMin iOSVersion = _options.iOSVersionMin();
1004 assert( (macVersion != ld::macVersionUnset) || (iOSVersion != ld::iOSVersionUnset) );
a645023d
A
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);
b2fa67a8 1009 cmd->set_sdk(0);
a645023d
A
1010 }
1011 else {
1012 cmd->set_cmd(LC_VERSION_MIN_IPHONEOS);
1013 cmd->set_cmdsize(sizeof(macho_version_min_command<P>));
afe874b1 1014 cmd->set_version((uint32_t)iOSVersion);
b2fa67a8 1015 cmd->set_sdk(0);
a645023d
A
1016 }
1017 return p + sizeof(macho_version_min_command<P>);
1018}
1019
1020
a645023d
A
1021
1022template <>
1023uint32_t HeaderAndLoadCommandsAtom<x86>::threadLoadCommandSize() const
1024{
1025 return this->alignedSize(16 + 16*4); // base size + i386_THREAD_STATE_COUNT * 4
1026}
1027
1028template <>
1029uint8_t* HeaderAndLoadCommandsAtom<x86>::copyThreadsLoadCommand(uint8_t* p) const
1030{
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();
1042}
1043
1044template <>
1045uint32_t HeaderAndLoadCommandsAtom<x86_64>::threadLoadCommandSize() const
1046{
1047 return this->alignedSize(16 + x86_THREAD_STATE64_COUNT * 4);
1048}
1049
1050template <>
1051uint8_t* HeaderAndLoadCommandsAtom<x86_64>::copyThreadsLoadCommand(uint8_t* p) const
1052{
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();
1064}
1065
1066template <>
1067uint32_t HeaderAndLoadCommandsAtom<arm>::threadLoadCommandSize() const
1068{
1069 return this->alignedSize(16 + 17 * 4); // base size + ARM_THREAD_STATE_COUNT * 4
1070}
1071
1072template <>
1073uint8_t* HeaderAndLoadCommandsAtom<arm>::copyThreadsLoadCommand(uint8_t* p) const
1074{
1075 assert(_state.entryPoint != NULL);
1076 pint_t start = _state.entryPoint->finalAddress();
1077 if ( _state.entryPoint->isThumb() )
1078 start |= 1ULL;
1079 macho_thread_command<P>* cmd = (macho_thread_command<P>*)p;
1080 cmd->set_cmd(LC_UNIXTHREAD);
1081 cmd->set_cmdsize(threadLoadCommandSize());
1082 cmd->set_flavor(1);
1083 cmd->set_count(17);
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();
1088}
1089
1090template <typename A>
1091uint8_t* HeaderAndLoadCommandsAtom<A>::copyEncryptionLoadCommand(uint8_t* p) const
1092{
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>);
1102}
1103
1104
1105template <typename A>
1106uint8_t* HeaderAndLoadCommandsAtom<A>::copySplitSegInfoLoadCommand(uint8_t* p) const
1107{
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>);
1114}
1115
1116
1117template <typename A>
1118uint8_t* HeaderAndLoadCommandsAtom<A>::copyDylibLoadCommand(uint8_t* p, const ld::dylib::File* dylib) const
1119{
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;
a645023d
A
1122 if ( dylib->willBeLazyLoadedDylib() )
1123 cmd->set_cmd(LC_LAZY_LOAD_DYLIB);
afe874b1 1124 else if ( dylib->forcedWeakLinked() || dylib->allSymbolsAreWeakImported() )
a645023d
A
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);
1130 else
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());
1138 return p + sz;
1139}
1140
1141template <typename A>
1142uint8_t* HeaderAndLoadCommandsAtom<A>::copyRPathLoadCommand(uint8_t* p, const char* path) const
1143{
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);
1150 return p + sz;
1151}
1152
1153template <typename A>
1154uint8_t* HeaderAndLoadCommandsAtom<A>::copySubFrameworkLoadCommand(uint8_t* p) const
1155{
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);
1163 return p + sz;
1164}
1165
1166
1167template <typename A>
1168uint8_t* HeaderAndLoadCommandsAtom<A>::copyAllowableClientLoadCommand(uint8_t* p, const char* client) const
1169{
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);
1176 return p + sz;
1177}
1178
1179template <typename A>
1180uint8_t* HeaderAndLoadCommandsAtom<A>::copyDyldEnvLoadCommand(uint8_t* p, const char* env) const
1181{
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);
1188 return p + sz;
1189}
1190
1191template <typename A>
1192uint8_t* HeaderAndLoadCommandsAtom<A>::copySubUmbrellaLoadCommand(uint8_t* p, const char* nm) const
1193{
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);
1200 return p + sz;
1201}
1202
1203template <typename A>
1204uint8_t* HeaderAndLoadCommandsAtom<A>::copySubLibraryLoadCommand(uint8_t* p, const char* nm) const
1205{
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);
1212 return p + sz;
1213}
1214
1215template <typename A>
1216uint8_t* HeaderAndLoadCommandsAtom<A>::copyFunctionStartsLoadCommand(uint8_t* p) const
1217{
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>);
1224}
1225
1226
1227template <typename A>
1228void HeaderAndLoadCommandsAtom<A>::copyRawContent(uint8_t buffer[]) const
1229{
1230 macho_header<P>* mh = (macho_header<P>*)buffer;
1231 bzero(buffer, this->size());
1232
1233 // copy mach_header
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());
1241
1242 // copy load commands
1243 uint8_t* p = &buffer[sizeof(macho_header<P>)];
1244
1245 if ( _options.outputKind() == Options::kObjectFile )
1246 p = this->copySingleSegmentLoadCommand(p);
1247 else
1248 p = this->copySegmentLoadCommands(p);
1249
1250 if ( _hasDylibIDLoadCommand )
1251 p = this->copyDylibIDLoadCommand(p);
1252
1253 if ( _hasDyldInfoLoadCommand )
1254 p = this->copyDyldInfoLoadCommand(p);
1255
1256 if ( _hasSymbolTableLoadCommand )
1257 p = this->copySymbolTableLoadCommand(p);
1258
1259 if ( _hasDynamicSymbolTableLoadCommand )
1260 p = this->copyDynamicSymbolTableLoadCommand(p);
1261
1262 if ( _hasDyldLoadCommand )
1263 p = this->copyDyldLoadCommand(p);
1264
1265 if ( _hasRoutinesLoadCommand )
1266 p = this->copyRoutinesLoadCommand(p);
1267
1268 if ( _hasUUIDLoadCommand )
1269 p = this->copyUUIDLoadCommand(p);
1270
1271 if ( _hasVersionLoadCommand )
1272 p = this->copyVersionLoadCommand(p);
1273
1274 if ( _hasThreadLoadCommand )
1275 p = this->copyThreadsLoadCommand(p);
1276
1277 if ( _hasEncryptionLoadCommand )
1278 p = this->copyEncryptionLoadCommand(p);
1279
1280 if ( _hasSplitSegInfoLoadCommand )
1281 p = this->copySplitSegInfoLoadCommand(p);
1282
1283 for(uint32_t ord=1; ord <= _writer.dylibCount(); ++ord) {
1284 p = this->copyDylibLoadCommand(p, _writer.dylibByOrdinal(ord));
1285 }
1286
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);
1291 }
1292 }
1293
1294 if ( _hasSubFrameworkLoadCommand )
1295 p = this->copySubFrameworkLoadCommand(p);
1296
1297 for (std::vector<const char*>::const_iterator it = _subLibraryNames.begin(); it != _subLibraryNames.end(); ++it) {
1298 p = this->copySubLibraryLoadCommand(p, *it);
1299 }
1300
1301 for (std::vector<const char*>::const_iterator it = _subUmbrellaNames.begin(); it != _subUmbrellaNames.end(); ++it) {
1302 p = this->copySubUmbrellaLoadCommand(p, *it);
1303 }
1304
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);
1309 }
1310 }
1311
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);
1316 }
1317 }
1318
1319 if ( _hasFunctionStartsLoadCommand )
1320 p = this->copyFunctionStartsLoadCommand(p);
1321
1322}
1323
1324
1325
1326} // namespace tool
1327} // namespace ld
1328
1329#endif // __HEADER_LOAD_COMMANDS_HPP__