2 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
4 * Copyright (c) 2005-2011 Apple Inc. All rights reserved.
6 * @APPLE_LICENSE_HEADER_START@
8 * This file contains Original Code and/or Modifications of Original Code
9 * as defined in and that are subject to the Apple Public Source License
10 * Version 2.0 (the 'License'). You may not use this file except in
11 * compliance with the License. Please obtain a copy of the License at
12 * http://www.opensource.apple.com/apsl/ and read it before using this
15 * The Original Code and all software distributed under the License are
16 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
17 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
18 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
20 * Please see the License for the specific language governing rights and
21 * limitations under the License.
23 * @APPLE_LICENSE_HEADER_END@
30 #include <sys/param.h>
37 #include <unordered_map>
38 #include <unordered_set>
40 #include "Architectures.hpp"
41 #include "MachOFileAbstraction.hpp"
42 #include "MachOTrie.hpp"
43 #include "macho_dylib_file.h"
44 #include "../code-sign-blobs/superblob.h"
51 template <typename A
> class File
;
55 // An ExportAtom has no content. It exists so that the linker can track which imported
56 // symbols came from which dynamic libraries.
59 class ExportAtom
: public ld::Atom
62 ExportAtom(const File
<A
>& f
, const char* nm
, bool weakDef
,
63 bool tlv
, typename
A::P::uint_t address
)
64 : ld::Atom(f
._importProxySection
, ld::Atom::definitionProxy
,
65 (weakDef
? ld::Atom::combineByName
: ld::Atom::combineNever
),
66 ld::Atom::scopeLinkageUnit
,
67 (tlv
? ld::Atom::typeTLV
: ld::Atom::typeUnclassified
),
68 symbolTableNotIn
, false, false, false, ld::Atom::Alignment(0)),
69 _file(f
), _name(nm
), _address(address
) {}
70 // overrides of ld::Atom
71 virtual const ld::File
* file() const { return &_file
; }
72 virtual const char* name() const { return _name
; }
73 virtual uint64_t size() const { return 0; }
74 virtual uint64_t objectAddress() const { return _address
; }
75 virtual void copyRawContent(uint8_t buffer
[]) const { }
76 virtual void setScope(Scope
) { }
79 typedef typename
A::P P
;
80 typedef typename
A::P::uint_t pint_t
;
82 virtual ~ExportAtom() {}
92 // An ImportAtom has no content. It exists so that when linking a main executable flat-namespace
93 // the imports of all flat dylibs are checked
96 class ImportAtom
: public ld::Atom
99 ImportAtom(File
<A
>& f
, std::vector
<const char*>& imports
);
101 // overrides of ld::Atom
102 virtual ld::File
* file() const { return &_file
; }
103 virtual const char* name() const { return "import-atom"; }
104 virtual uint64_t size() const { return 0; }
105 virtual uint64_t objectAddress() const { return 0; }
106 virtual void copyRawContent(uint8_t buffer
[]) const { }
107 virtual void setScope(Scope
) { }
108 virtual ld::Fixup::iterator
fixupsBegin() const { return &_undefs
[0]; }
109 virtual ld::Fixup::iterator
fixupsEnd() const { return &_undefs
[_undefs
.size()]; }
112 typedef typename
A::P P
;
114 virtual ~ImportAtom() {}
118 mutable std::vector
<ld::Fixup
> _undefs
;
121 template <typename A
>
122 ImportAtom
<A
>::ImportAtom(File
<A
>& f
, std::vector
<const char*>& imports
)
123 : ld::Atom(f
._flatDummySection
, ld::Atom::definitionRegular
, ld::Atom::combineNever
, ld::Atom::scopeTranslationUnit
,
124 ld::Atom::typeUnclassified
, symbolTableNotIn
, false, false, false, ld::Atom::Alignment(0)), _file(f
)
126 for(std::vector
<const char*>::iterator it
=imports
.begin(); it
!= imports
.end(); ++it
) {
127 _undefs
.push_back(ld::Fixup(0, ld::Fixup::k1of1
, ld::Fixup::kindNone
, false, strdup(*it
)));
134 // The reader for a dylib extracts all exported symbols names from the memory-mapped
135 // dylib, builds a hash table, then unmaps the file. This is an important memory
136 // savings for large dylibs.
138 template <typename A
>
139 class File
: public ld::dylib::File
142 static bool validFile(const uint8_t* fileContent
, bool executableOrDylib
);
143 File(const uint8_t* fileContent
, uint64_t fileLength
, const char* path
,
144 time_t mTime
, ld::File::Ordinal ordinal
, bool linkingFlatNamespace
,
145 bool linkingMainExecutable
, bool hoistImplicitPublicDylibs
,
146 ld::MacVersionMin macMin
, ld::IOSVersionMin iPhoneMin
, bool allowSimToMacOSX
, bool addVers
,
147 bool logAllFiles
, const char* installPath
, bool indirectDylib
);
150 // overrides of ld::File
151 virtual bool forEachAtom(ld::File::AtomHandler
&) const;
152 virtual bool justInTimeforEachAtom(const char* name
, ld::File::AtomHandler
&) const;
153 virtual ld::File::ObjcConstraint
objCConstraint() const { return _objcContraint
; }
155 // overrides of ld::dylib::File
156 virtual void processIndirectLibraries(ld::dylib::File::DylibHandler
*, bool);
157 virtual bool providedExportAtom() const { return _providedAtom
; }
158 virtual const char* parentUmbrella() const { return _parentUmbrella
; }
159 virtual const std::vector
<const char*>* allowableClients() const { return _allowableClients
.size() != 0 ? &_allowableClients
: NULL
; }
160 virtual bool hasWeakExternals() const { return _hasWeakExports
; }
161 virtual bool deadStrippable() const { return _deadStrippable
; }
162 virtual bool hasPublicInstallName() const{ return _hasPublicInstallName
; }
163 virtual bool hasWeakDefinition(const char* name
) const;
164 virtual bool allSymbolsAreWeakImported() const;
165 virtual const void* codeSignatureDR() const { return _codeSignatureDR
; }
166 virtual bool installPathVersionSpecific() const { return _installPathOverride
; }
171 struct ReExportChain
{ ReExportChain
* prev
; File
<A
>* file
; };
173 void assertNoReExportCycles(ReExportChain
*);
176 typedef typename
A::P P
;
177 typedef typename
A::P::E E
;
178 typedef typename
A::P::uint_t pint_t
;
180 friend class ExportAtom
<A
>;
181 friend class ImportAtom
<A
>;
184 std::size_t operator()(const char* __s
) const {
185 unsigned long __h
= 0;
187 __h
= 5 * __h
+ *__s
;
191 struct AtomAndWeak
{ ld::Atom
* atom
; bool weakDef
; bool tlv
; pint_t address
; };
192 typedef std::unordered_map
<const char*, AtomAndWeak
, ld::CStringHash
, ld::CStringEquals
> NameToAtomMap
;
193 typedef std::unordered_set
<const char*, CStringHash
, ld::CStringEquals
> NameSet
;
195 struct Dependent
{ const char* path
; File
<A
>* dylib
; bool reExport
; };
197 bool containsOrReExports(const char* name
, bool* weakDef
, bool* tlv
, pint_t
* defAddress
) const;
198 bool isPublicLocation(const char* pth
);
199 bool wrongOS() { return _wrongOS
; }
200 void addSymbol(const char* name
, bool weak
, bool tlv
, pint_t address
);
201 void addDyldFastStub();
202 void buildExportHashTableFromExportInfo(const macho_dyld_info_command
<P
>* dyldInfo
,
203 const uint8_t* fileContent
);
204 void buildExportHashTableFromSymbolTable(const macho_dysymtab_command
<P
>* dynamicInfo
,
205 const macho_nlist
<P
>* symbolTable
, const char* strings
,
206 const uint8_t* fileContent
);
207 static const char* objCInfoSegmentName();
208 static const char* objCInfoSectionName();
210 const ld::MacVersionMin _macVersionMin
;
211 const ld::IOSVersionMin _iOSVersionMin
;
212 const bool _allowSimToMacOSXLinking
;
213 const bool _addVersionLoadCommand
;
215 bool _implicitlyLinkPublicDylibs
;
216 ld::File::ObjcConstraint _objcContraint
;
217 ld::Section _importProxySection
;
218 ld::Section _flatDummySection
;
219 std::vector
<Dependent
> _dependentDylibs
;
220 std::vector
<const char*> _allowableClients
;
221 mutable NameToAtomMap _atoms
;
222 NameSet _ignoreExports
;
223 const char* _parentUmbrella
;
224 ImportAtom
<A
>* _importAtom
;
225 const void* _codeSignatureDR
;
227 bool _hasWeakExports
;
228 bool _deadStrippable
;
229 bool _hasPublicInstallName
;
230 mutable bool _providedAtom
;
231 bool _explictReExportFound
;
233 bool _installPathOverride
;
235 static bool _s_logHashtable
;
238 template <typename A
>
239 bool File
<A
>::_s_logHashtable
= false;
241 template <> const char* File
<x86_64
>::objCInfoSegmentName() { return "__DATA"; }
242 template <> const char* File
<arm
>::objCInfoSegmentName() { return "__DATA"; }
243 template <typename A
> const char* File
<A
>::objCInfoSegmentName() { return "__OBJC"; }
245 template <> const char* File
<x86_64
>::objCInfoSectionName() { return "__objc_imageinfo"; }
246 template <> const char* File
<arm
>::objCInfoSectionName() { return "__objc_imageinfo"; }
247 template <typename A
> const char* File
<A
>::objCInfoSectionName() { return "__image_info"; }
249 template <typename A
>
250 File
<A
>::File(const uint8_t* fileContent
, uint64_t fileLength
, const char* pth
, time_t mTime
, ld::File::Ordinal ord
,
251 bool linkingFlatNamespace
, bool linkingMainExecutable
, bool hoistImplicitPublicDylibs
,
252 ld::MacVersionMin macMin
, ld::IOSVersionMin iOSMin
, bool allowSimToMacOSX
, bool addVers
,
253 bool logAllFiles
, const char* targetInstallPath
, bool indirectDylib
)
254 : ld::dylib::File(strdup(pth
), mTime
, ord
),
255 _macVersionMin(macMin
), _iOSVersionMin(iOSMin
), _allowSimToMacOSXLinking(allowSimToMacOSX
), _addVersionLoadCommand(addVers
),
256 _linkingFlat(linkingFlatNamespace
), _implicitlyLinkPublicDylibs(hoistImplicitPublicDylibs
),
257 _objcContraint(ld::File::objcConstraintNone
),
258 _importProxySection("__TEXT", "__import", ld::Section::typeImportProxies
, true),
259 _flatDummySection("__LINKEDIT", "__flat_dummy", ld::Section::typeLinkEdit
, true),
260 _parentUmbrella(NULL
), _importAtom(NULL
), _codeSignatureDR(NULL
),
261 _noRexports(false), _hasWeakExports(false),
262 _deadStrippable(false), _hasPublicInstallName(false),
263 _providedAtom(false), _explictReExportFound(false), _wrongOS(false), _installPathOverride(false)
265 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
266 const uint32_t cmd_count
= header
->ncmds();
267 const macho_load_command
<P
>* const cmds
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>));
268 const macho_load_command
<P
>* const cmdsEnd
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>) + header
->sizeofcmds());
270 // write out path for -t option
274 // a "blank" stub has zero load commands
275 if ( (header
->filetype() == MH_DYLIB_STUB
) && (cmd_count
== 0) ) {
276 // no further processing needed
277 munmap((caddr_t
)fileContent
, fileLength
);
282 // optimize the case where we know there is no reason to look at indirect dylibs
283 _noRexports
= (header
->flags() & MH_NO_REEXPORTED_DYLIBS
)
284 || (header
->filetype() == MH_BUNDLE
)
285 || (header
->filetype() == MH_EXECUTE
); // bundles and exectuables can be used via -bundle_loader
286 _hasWeakExports
= (header
->flags() & MH_WEAK_DEFINES
);
287 _deadStrippable
= (header
->flags() & MH_DEAD_STRIPPABLE_DYLIB
);
289 // pass 1: get pointers, and see if this dylib uses compressed LINKEDIT format
290 const macho_dysymtab_command
<P
>* dynamicInfo
= NULL
;
291 const macho_dyld_info_command
<P
>* dyldInfo
= NULL
;
292 const macho_linkedit_data_command
<P
>* codeSignature
= NULL
;
293 const macho_nlist
<P
>* symbolTable
= NULL
;
294 const char* strings
= NULL
;
295 bool compressedLinkEdit
= false;
296 uint32_t dependentLibCount
= 0;
297 const macho_load_command
<P
>* cmd
= cmds
;
298 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
299 macho_dylib_command
<P
>* dylibID
;
300 const macho_symtab_command
<P
>* symtab
;
301 switch (cmd
->cmd()) {
303 symtab
= (macho_symtab_command
<P
>*)cmd
;
304 symbolTable
= (const macho_nlist
<P
>*)((char*)header
+ symtab
->symoff());
305 strings
= (char*)header
+ symtab
->stroff();
306 if ( (symtab
->stroff() + symtab
->strsize()) > fileLength
)
307 throwf("mach-o string pool extends beyond end of file in %s", pth
);
310 dynamicInfo
= (macho_dysymtab_command
<P
>*)cmd
;
313 case LC_DYLD_INFO_ONLY
:
314 dyldInfo
= (macho_dyld_info_command
<P
>*)cmd
;
315 compressedLinkEdit
= true;
318 dylibID
= (macho_dylib_command
<P
>*)cmd
;
319 _dylibInstallPath
= strdup(dylibID
->name());
320 _dylibTimeStamp
= dylibID
->timestamp();
321 _dylibCurrentVersion
= dylibID
->current_version();
322 _dylibCompatibilityVersion
= dylibID
->compatibility_version();
323 _hasPublicInstallName
= isPublicLocation(_dylibInstallPath
);
326 case LC_LOAD_WEAK_DYLIB
:
329 case LC_REEXPORT_DYLIB
:
330 _explictReExportFound
= true;
333 case LC_SUB_FRAMEWORK
:
334 _parentUmbrella
= strdup(((macho_sub_framework_command
<P
>*)cmd
)->umbrella());
337 _allowableClients
.push_back(strdup(((macho_sub_client_command
<P
>*)cmd
)->client()));
339 case LC_VERSION_MIN_MACOSX
:
340 if ( (_iOSVersionMin
!= ld::iOSVersionUnset
) && !_allowSimToMacOSXLinking
) {
342 if ( _addVersionLoadCommand
&& !indirectDylib
)
343 throw "building for iOS Simulator, but linking against dylib built for MacOSX";
346 case LC_VERSION_MIN_IPHONEOS
:
347 if ( _macVersionMin
!= ld::macVersionUnset
) {
349 if ( _addVersionLoadCommand
&& !indirectDylib
)
350 throw "building for MacOSX, but linking against dylib built for iOS Simulator";
353 case LC_CODE_SIGNATURE
:
354 codeSignature
= (macho_linkedit_data_command
<P
>* )cmd
;
356 case macho_segment_command
<P
>::CMD
:
357 // check for Objective-C info
358 if ( strcmp(((macho_segment_command
<P
>*)cmd
)->segname(), objCInfoSegmentName()) == 0 ) {
359 const macho_segment_command
<P
>* segment
= (macho_segment_command
<P
>*)cmd
;
360 const macho_section
<P
>* const sectionsStart
= (macho_section
<P
>*)((char*)segment
+ sizeof(macho_segment_command
<P
>));
361 const macho_section
<P
>* const sectionsEnd
= §ionsStart
[segment
->nsects()];
362 for (const macho_section
<P
>* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
363 if ( strncmp(sect
->sectname(), objCInfoSectionName(), strlen(objCInfoSectionName())) == 0 ) {
364 // struct objc_image_info {
365 // uint32_t version; // initially 0
368 // #define OBJC_IMAGE_SUPPORTS_GC 2
369 // #define OBJC_IMAGE_GC_ONLY 4
370 // #define OBJC_IMAGE_IS_SIMULATED 32
372 const uint32_t* contents
= (uint32_t*)(&fileContent
[sect
->offset()]);
373 if ( (sect
->size() >= 8) && (contents
[0] == 0) ) {
374 uint32_t flags
= E::get32(contents
[1]);
375 if ( (flags
& 4) == 4 )
376 _objcContraint
= ld::File::objcConstraintGC
;
377 else if ( (flags
& 2) == 2 )
378 _objcContraint
= ld::File::objcConstraintRetainReleaseOrGC
;
379 else if ( (flags
& 32) == 32 )
380 _objcContraint
= ld::File::objcConstraintRetainReleaseForSimulator
;
382 _objcContraint
= ld::File::objcConstraintRetainRelease
;
384 else if ( sect
->size() > 0 ) {
385 warning("can't parse %s/%s section in %s", objCInfoSegmentName(), objCInfoSectionName(), this->path());
391 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
393 throwf("malformed dylb, load command #%d is outside size of load commands in %s", i
, pth
);
396 // figure out if we need to examine dependent dylibs
397 // with compressed LINKEDIT format, MH_NO_REEXPORTED_DYLIBS can be trusted
398 bool processDependentLibraries
= true;
399 if ( compressedLinkEdit
&& _noRexports
&& !linkingFlatNamespace
)
400 processDependentLibraries
= false;
402 if ( processDependentLibraries
) {
403 // pass 2 builds list of all dependent libraries
404 _dependentDylibs
.reserve(dependentLibCount
);
406 unsigned int reExportDylibCount
= 0;
407 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
408 switch (cmd
->cmd()) {
410 case LC_LOAD_WEAK_DYLIB
:
411 // with new linkedit format only care about LC_REEXPORT_DYLIB
412 if ( compressedLinkEdit
&& !linkingFlatNamespace
)
414 case LC_REEXPORT_DYLIB
:
415 ++reExportDylibCount
;
417 entry
.path
= strdup(((macho_dylib_command
<P
>*)cmd
)->name());
419 entry
.reExport
= (cmd
->cmd() == LC_REEXPORT_DYLIB
);
420 if ( (targetInstallPath
== NULL
) || (strcmp(targetInstallPath
, entry
.path
) != 0) )
421 _dependentDylibs
.push_back(entry
);
424 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
426 // verify MH_NO_REEXPORTED_DYLIBS bit was correct
427 if ( compressedLinkEdit
&& !linkingFlatNamespace
) {
428 assert(reExportDylibCount
!= 0);
430 // pass 3 add re-export info
432 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
433 const char* frameworkLeafName
;
434 const char* dylibBaseName
;
435 switch (cmd
->cmd()) {
436 case LC_SUB_UMBRELLA
:
437 frameworkLeafName
= ((macho_sub_umbrella_command
<P
>*)cmd
)->sub_umbrella();
438 for (typename
std::vector
<Dependent
>::iterator it
= _dependentDylibs
.begin(); it
!= _dependentDylibs
.end(); ++it
) {
439 const char* dylibName
= it
->path
;
440 const char* lastSlash
= strrchr(dylibName
, '/');
441 if ( (lastSlash
!= NULL
) && (strcmp(&lastSlash
[1], frameworkLeafName
) == 0) )
446 dylibBaseName
= ((macho_sub_library_command
<P
>*)cmd
)->sub_library();
447 for (typename
std::vector
<Dependent
>::iterator it
= _dependentDylibs
.begin(); it
!= _dependentDylibs
.end(); ++it
) {
448 const char* dylibName
= it
->path
;
449 const char* lastSlash
= strrchr(dylibName
, '/');
450 const char* leafStart
= &lastSlash
[1];
451 if ( lastSlash
== NULL
)
452 leafStart
= dylibName
;
453 const char* firstDot
= strchr(leafStart
, '.');
454 int len
= strlen(leafStart
);
455 if ( firstDot
!= NULL
)
456 len
= firstDot
- leafStart
;
457 if ( strncmp(leafStart
, dylibBaseName
, len
) == 0 )
462 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
466 // validate minimal load commands
467 if ( (_dylibInstallPath
== NULL
) && ((header
->filetype() == MH_DYLIB
) || (header
->filetype() == MH_DYLIB_STUB
)) )
468 throwf("dylib %s missing LC_ID_DYLIB load command", pth
);
469 if ( dyldInfo
== NULL
) {
470 if ( symbolTable
== NULL
)
471 throw "binary missing LC_SYMTAB load command";
472 if ( dynamicInfo
== NULL
)
473 throw "binary missing LC_DYSYMTAB load command";
476 // if linking flat and this is a flat dylib, create one atom that references all imported symbols
477 if ( linkingFlatNamespace
&& linkingMainExecutable
&& ((header
->flags() & MH_TWOLEVEL
) == 0) ) {
478 std::vector
<const char*> importNames
;
479 importNames
.reserve(dynamicInfo
->nundefsym());
480 const macho_nlist
<P
>* start
= &symbolTable
[dynamicInfo
->iundefsym()];
481 const macho_nlist
<P
>* end
= &start
[dynamicInfo
->nundefsym()];
482 for (const macho_nlist
<P
>* sym
=start
; sym
< end
; ++sym
) {
483 importNames
.push_back(&strings
[sym
->n_strx()]);
485 _importAtom
= new ImportAtom
<A
>(*this, importNames
);
488 // if the dylib is code signed, look for its Designated Requirement
489 if ( codeSignature
!= NULL
) {
490 const Security::BlobCore
* overallSignature
= (Security::BlobCore
*)((char*)header
+ codeSignature
->dataoff());
491 typedef Security::SuperBlob
<Security::kSecCodeMagicEmbeddedSignature
> EmbeddedSignatureBlob
;
492 typedef Security::SuperBlob
<Security::kSecCodeMagicRequirementSet
> InternalRequirementsBlob
;
493 const EmbeddedSignatureBlob
* signature
= EmbeddedSignatureBlob::specific(overallSignature
);
494 if ( signature
->validateBlob(codeSignature
->datasize()) ) {
495 const InternalRequirementsBlob
* ireq
= signature
->find
<InternalRequirementsBlob
>(Security::cdRequirementsSlot
);
496 if ( (ireq
!= NULL
) && ireq
->validateBlob() ) {
497 const Security::BlobCore
* dr
= ireq
->find(Security::kSecDesignatedRequirementType
);
498 if ( (dr
!= NULL
) && dr
->validateBlob(Security::kSecCodeMagicRequirement
) ) {
499 // <rdar://problem/10968461> make copy because mapped file is about to be unmapped
500 _codeSignatureDR
= ::malloc(dr
->length());
501 ::memcpy((void*)_codeSignatureDR
, dr
, dr
->length());
508 if ( dyldInfo
!= NULL
)
509 buildExportHashTableFromExportInfo(dyldInfo
, fileContent
);
511 buildExportHashTableFromSymbolTable(dynamicInfo
, symbolTable
, strings
, fileContent
);
514 munmap((caddr_t
)fileContent
, fileLength
);
518 template <typename A
>
519 void File
<A
>::buildExportHashTableFromSymbolTable(const macho_dysymtab_command
<P
>* dynamicInfo
,
520 const macho_nlist
<P
>* symbolTable
, const char* strings
,
521 const uint8_t* fileContent
)
523 if ( dynamicInfo
->tocoff() == 0 ) {
524 if ( _s_logHashtable
) fprintf(stderr
, "ld: building hashtable of %u toc entries for %s\n", dynamicInfo
->nextdefsym(), this->path());
525 const macho_nlist
<P
>* start
= &symbolTable
[dynamicInfo
->iextdefsym()];
526 const macho_nlist
<P
>* end
= &start
[dynamicInfo
->nextdefsym()];
527 _atoms
.reserve(dynamicInfo
->nextdefsym()); // set initial bucket count
528 for (const macho_nlist
<P
>* sym
=start
; sym
< end
; ++sym
) {
529 this->addSymbol(&strings
[sym
->n_strx()], (sym
->n_desc() & N_WEAK_DEF
) != 0, false, sym
->n_value());
533 int32_t count
= dynamicInfo
->ntoc();
534 _atoms
.reserve(count
); // set initial bucket count
535 if ( _s_logHashtable
) fprintf(stderr
, "ld: building hashtable of %u entries for %s\n", count
, this->path());
536 const struct dylib_table_of_contents
* toc
= (dylib_table_of_contents
*)(fileContent
+ dynamicInfo
->tocoff());
537 for (int32_t i
= 0; i
< count
; ++i
) {
538 const uint32_t index
= E::get32(toc
[i
].symbol_index
);
539 const macho_nlist
<P
>* sym
= &symbolTable
[index
];
540 this->addSymbol(&strings
[sym
->n_strx()], (sym
->n_desc() & N_WEAK_DEF
) != 0, false, sym
->n_value());
544 // special case old libSystem
545 if ( (_dylibInstallPath
!= NULL
) && (strcmp(_dylibInstallPath
, "/usr/lib/libSystem.B.dylib") == 0) )
550 template <typename A
>
551 void File
<A
>::buildExportHashTableFromExportInfo(const macho_dyld_info_command
<P
>* dyldInfo
,
552 const uint8_t* fileContent
)
554 if ( _s_logHashtable
) fprintf(stderr
, "ld: building hashtable from export info in %s\n", this->path());
555 if ( dyldInfo
->export_size() > 0 ) {
556 const uint8_t* start
= fileContent
+ dyldInfo
->export_off();
557 const uint8_t* end
= &start
[dyldInfo
->export_size()];
558 std::vector
<mach_o::trie::Entry
> list
;
559 parseTrie(start
, end
, list
);
560 for (std::vector
<mach_o::trie::Entry
>::iterator it
=list
.begin(); it
!= list
.end(); ++it
)
561 this->addSymbol(it
->name
,
562 it
->flags
& EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION
,
563 (it
->flags
& EXPORT_SYMBOL_FLAGS_KIND_MASK
) == EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL
,
570 void File
<x86_64
>::addDyldFastStub()
572 addSymbol("dyld_stub_binder", false, false, 0);
576 void File
<x86
>::addDyldFastStub()
578 addSymbol("dyld_stub_binder", false, false, 0);
581 template <typename A
>
582 void File
<A
>::addDyldFastStub()
587 template <typename A
>
588 void File
<A
>::addSymbol(const char* name
, bool weakDef
, bool tlv
, pint_t address
)
590 //fprintf(stderr, "addSymbol() %s\n", name);
591 // symbols that start with $ld$ are meta-data to the static linker
592 // <rdar://problem/5182537> need way for ld and dyld to see different exported symbols in a dylib
593 if ( strncmp(name
, "$ld$", 4) == 0 ) {
594 // $ld$ <action> $ <condition> $ <symbol-name>
595 const char* symAction
= &name
[4];
596 const char* symCond
= strchr(symAction
, '$');
597 if ( symCond
!= NULL
) {
599 if ( _macVersionMin
!= ld::macVersionUnset
) {
600 sprintf(curOSVers
, "$os%d.%d$", (_macVersionMin
>> 16), ((_macVersionMin
>> 8) & 0xFF));
602 else if ( _iOSVersionMin
!= ld::iOSVersionUnset
) {
603 sprintf(curOSVers
, "$os%d.%d$", (_iOSVersionMin
>> 16), ((_iOSVersionMin
>> 8) & 0xFF));
606 assert(0 && "targeting neither macosx nor iphoneos");
608 if ( strncmp(symCond
, curOSVers
, strlen(curOSVers
)) == 0 ) {
609 const char* symName
= strchr(&symCond
[1], '$');
610 if ( symName
!= NULL
) {
612 if ( strncmp(symAction
, "hide$", 5) == 0 ) {
613 if ( _s_logHashtable
) fprintf(stderr
, " adding %s to ignore set for %s\n", symName
, this->path());
614 _ignoreExports
.insert(strdup(symName
));
617 else if ( strncmp(symAction
, "add$", 4) == 0 ) {
618 this->addSymbol(symName
, weakDef
, false, 0);
621 else if ( strncmp(symAction
, "install_name$", 13) == 0 ) {
622 _dylibInstallPath
= symName
;
623 _installPathOverride
= true;
627 warning("bad symbol action: %s in dylib %s", name
, this->path());
633 warning("bad symbol condition: %s in dylib %s", name
, this->path());
637 // add symbol as possible export if we are not supposed to ignore it
638 if ( _ignoreExports
.count(name
) == 0 ) {
641 bucket
.weakDef
= weakDef
;
643 bucket
.address
= address
;
644 if ( _s_logHashtable
) fprintf(stderr
, " adding %s to hash table for %s\n", name
, this->path());
645 _atoms
[strdup(name
)] = bucket
;
650 template <typename A
>
651 bool File
<A
>::forEachAtom(ld::File::AtomHandler
& handler
) const
653 handler
.doFile(*this);
654 // if doing flatnamespace and need all this dylib's imports resolve
655 // add atom which references alls undefines in this dylib
656 if ( _importAtom
!= NULL
) {
657 handler
.doAtom(*_importAtom
);
663 template <typename A
>
664 bool File
<A
>::hasWeakDefinition(const char* name
) const
666 // if supposed to ignore this export, then pretend I don't have it
667 if ( _ignoreExports
.count(name
) != 0 )
670 typename
NameToAtomMap::const_iterator pos
= _atoms
.find(name
);
671 if ( pos
!= _atoms
.end() ) {
672 return pos
->second
.weakDef
;
675 // look in children that I re-export
676 for (typename
std::vector
<Dependent
>::const_iterator it
= _dependentDylibs
.begin(); it
!= _dependentDylibs
.end(); ++it
) {
677 if ( it
->reExport
) {
678 //fprintf(stderr, "getJustInTimeAtomsFor: %s NOT found in %s, looking in child %s\n", name, this->path(), (*it)->getInstallPath());
679 typename
NameToAtomMap::iterator cpos
= it
->dylib
->_atoms
.find(name
);
680 if ( cpos
!= it
->dylib
->_atoms
.end() )
681 return cpos
->second
.weakDef
;
689 // <rdar://problem/5529626> If only weak_import symbols are used, linker should use LD_LOAD_WEAK_DYLIB
690 template <typename A
>
691 bool File
<A
>::allSymbolsAreWeakImported() const
693 bool foundNonWeakImport
= false;
694 bool foundWeakImport
= false;
695 //fprintf(stderr, "%s:\n", this->path());
696 for (typename
NameToAtomMap::const_iterator it
= _atoms
.begin(); it
!= _atoms
.end(); ++it
) {
697 const ld::Atom
* atom
= it
->second
.atom
;
698 if ( atom
!= NULL
) {
699 if ( atom
->weakImported() )
700 foundWeakImport
= true;
702 foundNonWeakImport
= true;
703 //fprintf(stderr, " weak_import=%d, name=%s\n", atom->weakImported(), it->first);
707 // don't automatically weak link dylib with no imports
708 // so at least one weak import symbol and no non-weak-imported symbols must be found
709 return foundWeakImport
&& !foundNonWeakImport
;
713 template <typename A
>
714 bool File
<A
>::containsOrReExports(const char* name
, bool* weakDef
, bool* tlv
, pint_t
* defAddress
) const
716 if ( _ignoreExports
.count(name
) != 0 )
720 typename
NameToAtomMap::iterator pos
= _atoms
.find(name
);
721 if ( pos
!= _atoms
.end() ) {
722 *weakDef
= pos
->second
.weakDef
;
723 *tlv
= pos
->second
.tlv
;
724 *defAddress
= pos
->second
.address
;
728 // check dylibs I re-export
729 for (typename
std::vector
<Dependent
>::const_iterator it
= _dependentDylibs
.begin(); it
!= _dependentDylibs
.end(); ++it
) {
730 if ( it
->reExport
&& !it
->dylib
->implicitlyLinked() ) {
731 if ( it
->dylib
->containsOrReExports(name
, weakDef
, tlv
, defAddress
) )
740 template <typename A
>
741 bool File
<A
>::justInTimeforEachAtom(const char* name
, ld::File::AtomHandler
& handler
) const
743 // if supposed to ignore this export, then pretend I don't have it
744 if ( _ignoreExports
.count(name
) != 0 )
749 if ( this->containsOrReExports(name
, &bucket
.weakDef
, &bucket
.tlv
, &bucket
.address
) ) {
750 bucket
.atom
= new ExportAtom
<A
>(*this, name
, bucket
.weakDef
, bucket
.tlv
, bucket
.address
);
751 _atoms
[name
] = bucket
;
752 _providedAtom
= true;
753 if ( _s_logHashtable
) fprintf(stderr
, "getJustInTimeAtomsFor: %s found in %s\n", name
, this->path());
754 // call handler with new export atom
755 handler
.doAtom(*bucket
.atom
);
764 template <typename A
>
765 bool File
<A
>::isPublicLocation(const char* pth
)
767 // -no_implicit_dylibs disables this optimization
768 if ( ! _implicitlyLinkPublicDylibs
)
771 // /usr/lib is a public location
772 if ( (strncmp(pth
, "/usr/lib/", 9) == 0) && (strchr(&pth
[9], '/') == NULL
) )
775 // /System/Library/Frameworks/ is a public location
776 if ( strncmp(pth
, "/System/Library/Frameworks/", 27) == 0 ) {
777 const char* frameworkDot
= strchr(&pth
[27], '.');
778 // but only top level framework
779 // /System/Library/Frameworks/Foo.framework/Versions/A/Foo ==> true
780 // /System/Library/Frameworks/Foo.framework/Resources/libBar.dylib ==> false
781 // /System/Library/Frameworks/Foo.framework/Frameworks/Bar.framework/Bar ==> false
782 // /System/Library/Frameworks/Foo.framework/Frameworks/Xfoo.framework/XFoo ==> false
783 if ( frameworkDot
!= NULL
) {
784 int frameworkNameLen
= frameworkDot
- &pth
[27];
785 if ( strncmp(&pth
[strlen(pth
)-frameworkNameLen
-1], &pth
[26], frameworkNameLen
+1) == 0 )
793 template <typename A
>
794 void File
<A
>::processIndirectLibraries(ld::dylib::File::DylibHandler
* handler
, bool addImplicitDylibs
)
796 const static bool log
= false;
797 if ( log
) fprintf(stderr
, "processIndirectLibraries(%s)\n", this->installPath());
798 if ( _linkingFlat
) {
799 for (typename
std::vector
<Dependent
>::iterator it
= _dependentDylibs
.begin(); it
!= _dependentDylibs
.end(); it
++) {
800 it
->dylib
= (File
<A
>*)handler
->findDylib(it
->path
, this->path());
803 else if ( _noRexports
) {
804 // MH_NO_REEXPORTED_DYLIBS bit set, then nothing to do
807 // two-level, might have re-exports
808 for (typename
std::vector
<Dependent
>::iterator it
= _dependentDylibs
.begin(); it
!= _dependentDylibs
.end(); it
++) {
809 if ( it
->reExport
) {
810 if ( log
) fprintf(stderr
, "processIndirectLibraries() parent=%s, child=%s\n", this->installPath(), it
->path
);
811 // a LC_REEXPORT_DYLIB, LC_SUB_UMBRELLA or LC_SUB_LIBRARY says we re-export this child
812 it
->dylib
= (File
<A
>*)handler
->findDylib(it
->path
, this->path());
813 if ( it
->dylib
->hasPublicInstallName() && !it
->dylib
->wrongOS() ) {
814 // promote this child to be automatically added as a direct dependent if this already is
815 if ( (this->explicitlyLinked() || this->implicitlyLinked()) && (strcmp(it
->path
,it
->dylib
->installPath()) == 0) ) {
816 if ( log
) fprintf(stderr
, "processIndirectLibraries() implicitly linking %s\n", it
->dylib
->installPath());
817 it
->dylib
->setImplicitlyLinked();
819 else if ( it
->dylib
->explicitlyLinked() || it
->dylib
->implicitlyLinked() ) {
820 if ( log
) fprintf(stderr
, "processIndirectLibraries() parent is not directly linked, but child is, so no need to re-export child\n");
823 if ( log
) fprintf(stderr
, "processIndirectLibraries() parent is not directly linked, so parent=%s will re-export child=%s\n", this->installPath(), it
->path
);
827 // add all child's symbols to me
828 if ( log
) fprintf(stderr
, "processIndirectLibraries() child is not public, so parent=%s will re-export child=%s\n", this->installPath(), it
->path
);
831 else if ( !_explictReExportFound
) {
832 // see if child contains LC_SUB_FRAMEWORK with my name
833 it
->dylib
= (File
<A
>*)handler
->findDylib(it
->path
, this->path());
834 const char* parentUmbrellaName
= it
->dylib
->parentUmbrella();
835 if ( parentUmbrellaName
!= NULL
) {
836 const char* parentName
= this->path();
837 const char* lastSlash
= strrchr(parentName
, '/');
838 if ( (lastSlash
!= NULL
) && (strcmp(&lastSlash
[1], parentUmbrellaName
) == 0) ) {
839 // add all child's symbols to me
841 if ( log
) fprintf(stderr
, "processIndirectLibraries() umbrella=%s will re-export child=%s\n", this->installPath(), it
->path
);
848 // check for re-export cycles
852 this->assertNoReExportCycles(&chain
);
855 template <typename A
>
856 void File
<A
>::assertNoReExportCycles(ReExportChain
* prev
)
858 // recursively check my re-exported dylibs
862 for (typename
std::vector
<Dependent
>::iterator it
= _dependentDylibs
.begin(); it
!= _dependentDylibs
.end(); it
++) {
863 if ( it
->reExport
) {
864 ld::File
* child
= it
->dylib
;
865 // check child is not already in chain
866 for (ReExportChain
* p
= prev
; p
!= NULL
; p
= p
->prev
) {
867 if ( p
->file
== child
) {
868 throwf("cycle in dylib re-exports with %s and %s", child
->path(), this->path());
871 if ( it
->dylib
!= NULL
)
872 it
->dylib
->assertNoReExportCycles(&chain
);
878 template <typename A
>
882 typedef typename
A::P P
;
884 static bool validFile(const uint8_t* fileContent
, bool executableOrDyliborBundle
);
885 static const char* fileKind(const uint8_t* fileContent
);
886 static ld::dylib::File
* parse(const uint8_t* fileContent
, uint64_t fileLength
,
887 const char* path
, time_t mTime
,
888 ld::File::Ordinal ordinal
, const Options
& opts
, bool indirectDylib
) {
889 return new File
<A
>(fileContent
, fileLength
, path
, mTime
,
890 ordinal
, opts
.flatNamespace(),
891 opts
.linkingMainExecutable(),
892 opts
.implicitlyLinkIndirectPublicDylibs(),
893 opts
.macosxVersionMin(),
894 opts
.iOSVersionMin(),
895 opts
.allowSimulatorToLinkWithMacOSX(),
896 opts
.addVersionLoadCommand(),
907 bool Parser
<x86
>::validFile(const uint8_t* fileContent
, bool executableOrDyliborBundle
)
909 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
910 if ( header
->magic() != MH_MAGIC
)
912 if ( header
->cputype() != CPU_TYPE_I386
)
914 switch ( header
->filetype() ) {
919 if ( executableOrDyliborBundle
)
922 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
924 if ( executableOrDyliborBundle
)
927 throw "can't link with a main executable";
934 bool Parser
<x86_64
>::validFile(const uint8_t* fileContent
, bool executableOrDyliborBundle
)
936 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
937 if ( header
->magic() != MH_MAGIC_64
)
939 if ( header
->cputype() != CPU_TYPE_X86_64
)
941 switch ( header
->filetype() ) {
946 if ( executableOrDyliborBundle
)
949 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
951 if ( executableOrDyliborBundle
)
954 throw "can't link with a main executable";
961 bool Parser
<arm
>::validFile(const uint8_t* fileContent
, bool executableOrDyliborBundle
)
963 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
964 if ( header
->magic() != MH_MAGIC
)
966 if ( header
->cputype() != CPU_TYPE_ARM
)
968 switch ( header
->filetype() ) {
973 if ( executableOrDyliborBundle
)
976 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
978 if ( executableOrDyliborBundle
)
981 throw "can't link with a main executable";
990 bool Parser
<arm64
>::validFile(const uint8_t* fileContent
, bool executableOrDyliborBundle
)
992 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
993 if ( header
->magic() != MH_MAGIC_64
)
995 if ( header
->cputype() != CPU_TYPE_ARM64
)
997 switch ( header
->filetype() ) {
1002 if ( executableOrDyliborBundle
)
1005 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
1007 if ( executableOrDyliborBundle
)
1010 throw "can't link with a main executable";
1017 bool isDylibFile(const uint8_t* fileContent
, cpu_type_t
* result
, cpu_subtype_t
* subResult
)
1019 if ( Parser
<x86_64
>::validFile(fileContent
, false) ) {
1020 *result
= CPU_TYPE_X86_64
;
1021 *subResult
= CPU_SUBTYPE_X86_64_ALL
;
1024 if ( Parser
<x86
>::validFile(fileContent
, false) ) {
1025 *result
= CPU_TYPE_I386
;
1026 *subResult
= CPU_SUBTYPE_X86_ALL
;
1029 if ( Parser
<arm
>::validFile(fileContent
, false) ) {
1030 *result
= CPU_TYPE_ARM
;
1031 const macho_header
<Pointer32
<LittleEndian
> >* header
= (const macho_header
<Pointer32
<LittleEndian
> >*)fileContent
;
1032 *subResult
= header
->cpusubtype();
1035 if ( Parser
<arm64
>::validFile(fileContent
, false) ) {
1036 *result
= CPU_TYPE_ARM64
;
1037 *subResult
= CPU_SUBTYPE_ARM64_ALL
;
1040 if ( Parser
<ppc
>::validFile(fileContent
, false) ) {
1041 *result
= CPU_TYPE_POWERPC
;
1042 const macho_header
<Pointer32
<BigEndian
> >* header
= (const macho_header
<Pointer32
<BigEndian
> >*)fileContent
;
1043 *subResult
= header
->cpusubtype();
1046 if ( Parser
<ppc64
>::validFile(fileContent
, false) ) {
1047 *result
= CPU_TYPE_POWERPC64
;
1048 *subResult
= CPU_SUBTYPE_POWERPC_ALL
;
1055 const char* Parser
<x86
>::fileKind(const uint8_t* fileContent
)
1057 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1058 if ( header
->magic() != MH_MAGIC
)
1060 if ( header
->cputype() != CPU_TYPE_I386
)
1066 const char* Parser
<x86_64
>::fileKind(const uint8_t* fileContent
)
1068 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1069 if ( header
->magic() != MH_MAGIC_64
)
1071 if ( header
->cputype() != CPU_TYPE_X86_64
)
1077 const char* Parser
<arm
>::fileKind(const uint8_t* fileContent
)
1079 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1080 if ( header
->magic() != MH_MAGIC
)
1082 if ( header
->cputype() != CPU_TYPE_ARM
)
1084 for (const ArchInfo
* t
=archInfoArray
; t
->archName
!= NULL
; ++t
) {
1085 if ( (t
->cpuType
== CPU_TYPE_ARM
) && ((cpu_subtype_t
)header
->cpusubtype() == t
->cpuSubType
) ) {
1092 #if SUPPORT_ARCH_arm64
1094 const char* Parser
<arm64
>::fileKind(const uint8_t* fileContent
)
1096 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1097 if ( header
->magic() != MH_MAGIC_64
)
1099 if ( header
->cputype() != CPU_TYPE_ARM64
)
1106 // used by linker is error messages to describe mismatched files
1108 const char* archName(const uint8_t* fileContent
)
1110 if ( Parser
<x86_64
>::validFile(fileContent
, true) ) {
1111 return Parser
<x86_64
>::fileKind(fileContent
);
1113 if ( Parser
<x86
>::validFile(fileContent
, true) ) {
1114 return Parser
<x86
>::fileKind(fileContent
);
1116 if ( Parser
<arm
>::validFile(fileContent
, true) ) {
1117 return Parser
<arm
>::fileKind(fileContent
);
1119 #if SUPPORT_ARCH_arm64
1120 if ( Parser
<arm64
>::validFile(fileContent
, false) ) {
1121 return Parser
<arm64
>::fileKind(fileContent
);
1129 // main function used by linker to instantiate ld::Files
1131 ld::dylib::File
* parse(const uint8_t* fileContent
, uint64_t fileLength
,
1132 const char* path
, time_t modTime
, const Options
& opts
, ld::File::Ordinal ordinal
,
1133 bool bundleLoader
, bool indirectDylib
)
1135 switch ( opts
.architecture() ) {
1136 #if SUPPORT_ARCH_x86_64
1137 case CPU_TYPE_X86_64
:
1138 if ( Parser
<x86_64
>::validFile(fileContent
, bundleLoader
) )
1139 return Parser
<x86_64
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
, indirectDylib
);
1142 #if SUPPORT_ARCH_i386
1144 if ( Parser
<x86
>::validFile(fileContent
, bundleLoader
) )
1145 return Parser
<x86
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
, indirectDylib
);
1148 #if SUPPORT_ARCH_arm_any
1150 if ( Parser
<arm
>::validFile(fileContent
, bundleLoader
) )
1151 return Parser
<arm
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
, indirectDylib
);
1154 #if SUPPORT_ARCH_arm64
1155 case CPU_TYPE_ARM64
:
1156 if ( Parser
<arm64
>::validFile(fileContent
, bundleLoader
) )
1157 return Parser
<arm64
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
, indirectDylib
);
1165 }; // namespace dylib
1166 }; // namespace mach_o