1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
3 * Copyright (c) 2005-2011 Apple Inc. All rights reserved.
5 * @APPLE_LICENSE_HEADER_START@
7 * This file contains Original Code and/or Modifications of Original Code
8 * as defined in and that are subject to the Apple Public Source License
9 * Version 2.0 (the 'License'). You may not use this file except in
10 * compliance with the License. Please obtain a copy of the License at
11 * http://www.opensource.apple.com/apsl/ and read it before using this
14 * The Original Code and all software distributed under the License are
15 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
19 * Please see the License for the specific language governing rights and
20 * limitations under the License.
22 * @APPLE_LICENSE_HEADER_END@
29 #include <sys/param.h>
36 #include <unordered_map>
37 #include <unordered_set>
39 #include "Architectures.hpp"
40 #include "MachOFileAbstraction.hpp"
41 #include "MachOTrie.hpp"
42 #include "macho_dylib_file.h"
43 #include "../code-sign-blobs/superblob.h"
50 template <typename A
> class File
;
54 // An ExportAtom has no content. It exists so that the linker can track which imported
55 // symbols came from which dynamic libraries.
58 class ExportAtom
: public ld::Atom
61 ExportAtom(const File
<A
>& f
, const char* nm
, bool weakDef
,
62 bool tlv
, typename
A::P::uint_t address
)
63 : ld::Atom(f
._importProxySection
, ld::Atom::definitionProxy
,
64 (weakDef
? ld::Atom::combineByName
: ld::Atom::combineNever
),
65 ld::Atom::scopeLinkageUnit
,
66 (tlv
? ld::Atom::typeTLV
: ld::Atom::typeUnclassified
),
67 symbolTableNotIn
, false, false, false, ld::Atom::Alignment(0)),
68 _file(f
), _name(nm
), _address(address
) {}
69 // overrides of ld::Atom
70 virtual const ld::File
* file() const { return &_file
; }
71 virtual const char* name() const { return _name
; }
72 virtual uint64_t size() const { return 0; }
73 virtual uint64_t objectAddress() const { return _address
; }
74 virtual void copyRawContent(uint8_t buffer
[]) const { }
75 virtual void setScope(Scope
) { }
78 typedef typename
A::P P
;
79 typedef typename
A::P::uint_t pint_t
;
81 virtual ~ExportAtom() {}
91 // An ImportAtom has no content. It exists so that when linking a main executable flat-namespace
92 // the imports of all flat dylibs are checked
95 class ImportAtom
: public ld::Atom
98 ImportAtom(File
<A
>& f
, std::vector
<const char*>& imports
);
100 // overrides of ld::Atom
101 virtual ld::File
* file() const { return &_file
; }
102 virtual const char* name() const { return "import-atom"; }
103 virtual uint64_t size() const { return 0; }
104 virtual uint64_t objectAddress() const { return 0; }
105 virtual void copyRawContent(uint8_t buffer
[]) const { }
106 virtual void setScope(Scope
) { }
107 virtual ld::Fixup::iterator
fixupsBegin() const { return &_undefs
[0]; }
108 virtual ld::Fixup::iterator
fixupsEnd() const { return &_undefs
[_undefs
.size()]; }
111 typedef typename
A::P P
;
113 virtual ~ImportAtom() {}
117 mutable std::vector
<ld::Fixup
> _undefs
;
120 template <typename A
>
121 ImportAtom
<A
>::ImportAtom(File
<A
>& f
, std::vector
<const char*>& imports
)
122 : ld::Atom(f
._flatDummySection
, ld::Atom::definitionRegular
, ld::Atom::combineNever
, ld::Atom::scopeTranslationUnit
,
123 ld::Atom::typeUnclassified
, symbolTableNotIn
, false, false, false, ld::Atom::Alignment(0)), _file(f
)
125 for(std::vector
<const char*>::iterator it
=imports
.begin(); it
!= imports
.end(); ++it
) {
126 _undefs
.push_back(ld::Fixup(0, ld::Fixup::k1of1
, ld::Fixup::kindNone
, false, strdup(*it
)));
133 // The reader for a dylib extracts all exported symbols names from the memory-mapped
134 // dylib, builds a hash table, then unmaps the file. This is an important memory
135 // savings for large dylibs.
137 template <typename A
>
138 class File
: public ld::dylib::File
141 static bool validFile(const uint8_t* fileContent
, bool executableOrDylib
);
142 File(const uint8_t* fileContent
, uint64_t fileLength
, const char* path
,
143 time_t mTime
, ld::File::Ordinal ordinal
, bool linkingFlatNamespace
,
144 bool linkingMainExecutable
, bool hoistImplicitPublicDylibs
,
145 ld::MacVersionMin macMin
, ld::IOSVersionMin iPhoneMin
, bool addVers
,
146 bool logAllFiles
, const char* installPath
, bool indirectDylib
);
149 // overrides of ld::File
150 virtual bool forEachAtom(ld::File::AtomHandler
&) const;
151 virtual bool justInTimeforEachAtom(const char* name
, ld::File::AtomHandler
&) const;
152 virtual ld::File::ObjcConstraint
objCConstraint() const { return _objcContraint
; }
154 // overrides of ld::dylib::File
155 virtual void processIndirectLibraries(ld::dylib::File::DylibHandler
*, bool);
156 virtual bool providedExportAtom() const { return _providedAtom
; }
157 virtual const char* parentUmbrella() const { return _parentUmbrella
; }
158 virtual const std::vector
<const char*>* allowableClients() const { return _allowableClients
.size() != 0 ? &_allowableClients
: NULL
; }
159 virtual bool hasWeakExternals() const { return _hasWeakExports
; }
160 virtual bool deadStrippable() const { return _deadStrippable
; }
161 virtual bool hasPublicInstallName() const{ return _hasPublicInstallName
; }
162 virtual bool hasWeakDefinition(const char* name
) const;
163 virtual bool allSymbolsAreWeakImported() const;
164 virtual const void* codeSignatureDR() const { return _codeSignatureDR
; }
169 struct ReExportChain
{ ReExportChain
* prev
; File
<A
>* file
; };
171 void assertNoReExportCycles(ReExportChain
*);
174 typedef typename
A::P P
;
175 typedef typename
A::P::E E
;
176 typedef typename
A::P::uint_t pint_t
;
178 friend class ExportAtom
<A
>;
179 friend class ImportAtom
<A
>;
182 std::size_t operator()(const char* __s
) const {
183 unsigned long __h
= 0;
185 __h
= 5 * __h
+ *__s
;
189 struct AtomAndWeak
{ ld::Atom
* atom
; bool weakDef
; bool tlv
; pint_t address
; };
190 typedef std::unordered_map
<const char*, AtomAndWeak
, ld::CStringHash
, ld::CStringEquals
> NameToAtomMap
;
191 typedef std::unordered_set
<const char*, CStringHash
, ld::CStringEquals
> NameSet
;
193 struct Dependent
{ const char* path
; File
<A
>* dylib
; bool reExport
; };
195 bool containsOrReExports(const char* name
, bool* weakDef
, bool* tlv
, pint_t
* defAddress
) const;
196 bool isPublicLocation(const char* pth
);
197 void addSymbol(const char* name
, bool weak
, bool tlv
, pint_t address
);
198 void addDyldFastStub();
199 void buildExportHashTableFromExportInfo(const macho_dyld_info_command
<P
>* dyldInfo
,
200 const uint8_t* fileContent
);
201 void buildExportHashTableFromSymbolTable(const macho_dysymtab_command
<P
>* dynamicInfo
,
202 const macho_nlist
<P
>* symbolTable
, const char* strings
,
203 const uint8_t* fileContent
);
204 static const char* objCInfoSegmentName();
205 static const char* objCInfoSectionName();
207 const ld::MacVersionMin _macVersionMin
;
208 const ld::IOSVersionMin _iOSVersionMin
;
209 const bool _addVersionLoadCommand
;
211 bool _implicitlyLinkPublicDylibs
;
212 ld::File::ObjcConstraint _objcContraint
;
213 ld::Section _importProxySection
;
214 ld::Section _flatDummySection
;
215 std::vector
<Dependent
> _dependentDylibs
;
216 std::vector
<const char*> _allowableClients
;
217 mutable NameToAtomMap _atoms
;
218 NameSet _ignoreExports
;
219 const char* _parentUmbrella
;
220 ImportAtom
<A
>* _importAtom
;
221 const void* _codeSignatureDR
;
223 bool _hasWeakExports
;
224 bool _deadStrippable
;
225 bool _hasPublicInstallName
;
226 mutable bool _providedAtom
;
227 bool _explictReExportFound
;
229 static bool _s_logHashtable
;
232 template <typename A
>
233 bool File
<A
>::_s_logHashtable
= false;
235 template <> const char* File
<x86_64
>::objCInfoSegmentName() { return "__DATA"; }
236 template <> const char* File
<arm
>::objCInfoSegmentName() { return "__DATA"; }
237 template <typename A
> const char* File
<A
>::objCInfoSegmentName() { return "__OBJC"; }
239 template <> const char* File
<x86_64
>::objCInfoSectionName() { return "__objc_imageinfo"; }
240 template <> const char* File
<arm
>::objCInfoSectionName() { return "__objc_imageinfo"; }
241 template <typename A
> const char* File
<A
>::objCInfoSectionName() { return "__image_info"; }
243 template <typename A
>
244 File
<A
>::File(const uint8_t* fileContent
, uint64_t fileLength
, const char* pth
, time_t mTime
, ld::File::Ordinal ord
,
245 bool linkingFlatNamespace
, bool linkingMainExecutable
, bool hoistImplicitPublicDylibs
,
246 ld::MacVersionMin macMin
, ld::IOSVersionMin iOSMin
, bool addVers
,
247 bool logAllFiles
, const char* targetInstallPath
, bool indirectDylib
)
248 : ld::dylib::File(strdup(pth
), mTime
, ord
),
249 _macVersionMin(macMin
), _iOSVersionMin(iOSMin
), _addVersionLoadCommand(addVers
),
250 _linkingFlat(linkingFlatNamespace
), _implicitlyLinkPublicDylibs(hoistImplicitPublicDylibs
),
251 _objcContraint(ld::File::objcConstraintNone
),
252 _importProxySection("__TEXT", "__import", ld::Section::typeImportProxies
, true),
253 _flatDummySection("__LINKEDIT", "__flat_dummy", ld::Section::typeLinkEdit
, true),
254 _parentUmbrella(NULL
), _importAtom(NULL
), _codeSignatureDR(NULL
),
255 _noRexports(false), _hasWeakExports(false),
256 _deadStrippable(false), _hasPublicInstallName(false),
257 _providedAtom(false), _explictReExportFound(false)
259 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
260 const uint32_t cmd_count
= header
->ncmds();
261 const macho_load_command
<P
>* const cmds
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>));
262 const macho_load_command
<P
>* const cmdsEnd
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>) + header
->sizeofcmds());
264 // write out path for -t option
268 // a "blank" stub has zero load commands
269 if ( (header
->filetype() == MH_DYLIB_STUB
) && (cmd_count
== 0) ) {
270 // no further processing needed
271 munmap((caddr_t
)fileContent
, fileLength
);
276 // optimize the case where we know there is no reason to look at indirect dylibs
277 _noRexports
= (header
->flags() & MH_NO_REEXPORTED_DYLIBS
)
278 || (header
->filetype() == MH_BUNDLE
)
279 || (header
->filetype() == MH_EXECUTE
); // bundles and exectuables can be used via -bundle_loader
280 _hasWeakExports
= (header
->flags() & MH_WEAK_DEFINES
);
281 _deadStrippable
= (header
->flags() & MH_DEAD_STRIPPABLE_DYLIB
);
283 // pass 1: get pointers, and see if this dylib uses compressed LINKEDIT format
284 const macho_dysymtab_command
<P
>* dynamicInfo
= NULL
;
285 const macho_dyld_info_command
<P
>* dyldInfo
= NULL
;
286 const macho_linkedit_data_command
<P
>* codeSignature
= NULL
;
287 const macho_nlist
<P
>* symbolTable
= NULL
;
288 const char* strings
= NULL
;
289 bool compressedLinkEdit
= false;
290 uint32_t dependentLibCount
= 0;
291 const macho_load_command
<P
>* cmd
= cmds
;
292 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
293 macho_dylib_command
<P
>* dylibID
;
294 const macho_symtab_command
<P
>* symtab
;
295 switch (cmd
->cmd()) {
297 symtab
= (macho_symtab_command
<P
>*)cmd
;
298 symbolTable
= (const macho_nlist
<P
>*)((char*)header
+ symtab
->symoff());
299 strings
= (char*)header
+ symtab
->stroff();
300 if ( (symtab
->stroff() + symtab
->strsize()) > fileLength
)
301 throwf("mach-o string pool extends beyond end of file in %s", pth
);
304 dynamicInfo
= (macho_dysymtab_command
<P
>*)cmd
;
307 case LC_DYLD_INFO_ONLY
:
308 dyldInfo
= (macho_dyld_info_command
<P
>*)cmd
;
309 compressedLinkEdit
= true;
312 dylibID
= (macho_dylib_command
<P
>*)cmd
;
313 _dylibInstallPath
= strdup(dylibID
->name());
314 _dylibTimeStamp
= dylibID
->timestamp();
315 _dylibCurrentVersion
= dylibID
->current_version();
316 _dylibCompatibilityVersion
= dylibID
->compatibility_version();
317 _hasPublicInstallName
= isPublicLocation(_dylibInstallPath
);
320 case LC_LOAD_WEAK_DYLIB
:
323 case LC_REEXPORT_DYLIB
:
324 _explictReExportFound
= true;
327 case LC_SUB_FRAMEWORK
:
328 _parentUmbrella
= strdup(((macho_sub_framework_command
<P
>*)cmd
)->umbrella());
331 _allowableClients
.push_back(strdup(((macho_sub_client_command
<P
>*)cmd
)->client()));
333 case LC_VERSION_MIN_MACOSX
:
334 if ( _addVersionLoadCommand
&& !indirectDylib
&& (_iOSVersionMin
!= ld::iOSVersionUnset
) )
335 warning("building for iOS, but linking against dylib built for MacOSX: %s", pth
);
337 case LC_VERSION_MIN_IPHONEOS
:
338 if ( _addVersionLoadCommand
&& !indirectDylib
&& (_macVersionMin
!= ld::macVersionUnset
) )
339 warning("building for MacOSX, but linking against dylib built for iOS: %s", pth
);
341 case LC_CODE_SIGNATURE
:
342 codeSignature
= (macho_linkedit_data_command
<P
>* )cmd
;
344 case macho_segment_command
<P
>::CMD
:
345 // check for Objective-C info
346 if ( strcmp(((macho_segment_command
<P
>*)cmd
)->segname(), objCInfoSegmentName()) == 0 ) {
347 const macho_segment_command
<P
>* segment
= (macho_segment_command
<P
>*)cmd
;
348 const macho_section
<P
>* const sectionsStart
= (macho_section
<P
>*)((char*)segment
+ sizeof(macho_segment_command
<P
>));
349 const macho_section
<P
>* const sectionsEnd
= §ionsStart
[segment
->nsects()];
350 for (const macho_section
<P
>* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
351 if ( strncmp(sect
->sectname(), objCInfoSectionName(), strlen(objCInfoSectionName())) == 0 ) {
352 // struct objc_image_info {
353 // uint32_t version; // initially 0
356 // #define OBJC_IMAGE_SUPPORTS_GC 2
357 // #define OBJC_IMAGE_GC_ONLY 4
359 const uint32_t* contents
= (uint32_t*)(&fileContent
[sect
->offset()]);
360 if ( (sect
->size() >= 8) && (contents
[0] == 0) ) {
361 uint32_t flags
= E::get32(contents
[1]);
362 if ( (flags
& 4) == 4 )
363 _objcContraint
= ld::File::objcConstraintGC
;
364 else if ( (flags
& 2) == 2 )
365 _objcContraint
= ld::File::objcConstraintRetainReleaseOrGC
;
367 _objcContraint
= ld::File::objcConstraintRetainRelease
;
369 else if ( sect
->size() > 0 ) {
370 warning("can't parse %s/%s section in %s", objCInfoSegmentName(), objCInfoSectionName(), this->path());
376 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
378 throwf("malformed dylb, load command #%d is outside size of load commands in %s", i
, pth
);
381 // figure out if we need to examine dependent dylibs
382 // with compressed LINKEDIT format, MH_NO_REEXPORTED_DYLIBS can be trusted
383 bool processDependentLibraries
= true;
384 if ( compressedLinkEdit
&& _noRexports
&& !linkingFlatNamespace
)
385 processDependentLibraries
= false;
387 if ( processDependentLibraries
) {
388 // pass 2 builds list of all dependent libraries
389 _dependentDylibs
.reserve(dependentLibCount
);
391 unsigned int reExportDylibCount
= 0;
392 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
393 switch (cmd
->cmd()) {
395 case LC_LOAD_WEAK_DYLIB
:
396 // with new linkedit format only care about LC_REEXPORT_DYLIB
397 if ( compressedLinkEdit
&& !linkingFlatNamespace
)
399 case LC_REEXPORT_DYLIB
:
400 ++reExportDylibCount
;
402 entry
.path
= strdup(((macho_dylib_command
<P
>*)cmd
)->name());
404 entry
.reExport
= (cmd
->cmd() == LC_REEXPORT_DYLIB
);
405 if ( (targetInstallPath
== NULL
) || (strcmp(targetInstallPath
, entry
.path
) != 0) )
406 _dependentDylibs
.push_back(entry
);
409 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
411 // verify MH_NO_REEXPORTED_DYLIBS bit was correct
412 if ( compressedLinkEdit
&& !linkingFlatNamespace
) {
413 assert(reExportDylibCount
!= 0);
415 // pass 3 add re-export info
417 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
418 const char* frameworkLeafName
;
419 const char* dylibBaseName
;
420 switch (cmd
->cmd()) {
421 case LC_SUB_UMBRELLA
:
422 frameworkLeafName
= ((macho_sub_umbrella_command
<P
>*)cmd
)->sub_umbrella();
423 for (typename
std::vector
<Dependent
>::iterator it
= _dependentDylibs
.begin(); it
!= _dependentDylibs
.end(); ++it
) {
424 const char* dylibName
= it
->path
;
425 const char* lastSlash
= strrchr(dylibName
, '/');
426 if ( (lastSlash
!= NULL
) && (strcmp(&lastSlash
[1], frameworkLeafName
) == 0) )
431 dylibBaseName
= ((macho_sub_library_command
<P
>*)cmd
)->sub_library();
432 for (typename
std::vector
<Dependent
>::iterator it
= _dependentDylibs
.begin(); it
!= _dependentDylibs
.end(); ++it
) {
433 const char* dylibName
= it
->path
;
434 const char* lastSlash
= strrchr(dylibName
, '/');
435 const char* leafStart
= &lastSlash
[1];
436 if ( lastSlash
== NULL
)
437 leafStart
= dylibName
;
438 const char* firstDot
= strchr(leafStart
, '.');
439 int len
= strlen(leafStart
);
440 if ( firstDot
!= NULL
)
441 len
= firstDot
- leafStart
;
442 if ( strncmp(leafStart
, dylibBaseName
, len
) == 0 )
447 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
451 // validate minimal load commands
452 if ( (_dylibInstallPath
== NULL
) && ((header
->filetype() == MH_DYLIB
) || (header
->filetype() == MH_DYLIB_STUB
)) )
453 throwf("dylib %s missing LC_ID_DYLIB load command", pth
);
454 if ( dyldInfo
== NULL
) {
455 if ( symbolTable
== NULL
)
456 throw "binary missing LC_SYMTAB load command";
457 if ( dynamicInfo
== NULL
)
458 throw "binary missing LC_DYSYMTAB load command";
461 // if linking flat and this is a flat dylib, create one atom that references all imported symbols
462 if ( linkingFlatNamespace
&& linkingMainExecutable
&& ((header
->flags() & MH_TWOLEVEL
) == 0) ) {
463 std::vector
<const char*> importNames
;
464 importNames
.reserve(dynamicInfo
->nundefsym());
465 const macho_nlist
<P
>* start
= &symbolTable
[dynamicInfo
->iundefsym()];
466 const macho_nlist
<P
>* end
= &start
[dynamicInfo
->nundefsym()];
467 for (const macho_nlist
<P
>* sym
=start
; sym
< end
; ++sym
) {
468 importNames
.push_back(&strings
[sym
->n_strx()]);
470 _importAtom
= new ImportAtom
<A
>(*this, importNames
);
473 // if the dylib is code signed, look for its Designated Requirement
474 if ( codeSignature
!= NULL
) {
475 const Security::BlobCore
* overallSignature
= (Security::BlobCore
*)((char*)header
+ codeSignature
->dataoff());
476 typedef Security::SuperBlob
<Security::kSecCodeMagicEmbeddedSignature
> EmbeddedSignatureBlob
;
477 typedef Security::SuperBlob
<Security::kSecCodeMagicRequirementSet
> InternalRequirementsBlob
;
478 const EmbeddedSignatureBlob
* signature
= EmbeddedSignatureBlob::specific(overallSignature
);
479 if ( signature
->validateBlob(codeSignature
->datasize()) ) {
480 const InternalRequirementsBlob
* ireq
= signature
->find
<InternalRequirementsBlob
>(Security::cdRequirementsSlot
);
481 if ( (ireq
!= NULL
) && ireq
->validateBlob() ) {
482 const Security::BlobCore
* dr
= ireq
->find(Security::kSecDesignatedRequirementType
);
483 if ( (dr
!= NULL
) && dr
->validateBlob(Security::kSecCodeMagicRequirement
) ) {
484 // <rdar://problem/10968461> make copy because mapped file is about to be unmapped
485 _codeSignatureDR
= ::malloc(dr
->length());
486 ::memcpy((void*)_codeSignatureDR
, dr
, dr
->length());
493 if ( dyldInfo
!= NULL
)
494 buildExportHashTableFromExportInfo(dyldInfo
, fileContent
);
496 buildExportHashTableFromSymbolTable(dynamicInfo
, symbolTable
, strings
, fileContent
);
499 munmap((caddr_t
)fileContent
, fileLength
);
503 template <typename A
>
504 void File
<A
>::buildExportHashTableFromSymbolTable(const macho_dysymtab_command
<P
>* dynamicInfo
,
505 const macho_nlist
<P
>* symbolTable
, const char* strings
,
506 const uint8_t* fileContent
)
508 if ( dynamicInfo
->tocoff() == 0 ) {
509 if ( _s_logHashtable
) fprintf(stderr
, "ld: building hashtable of %u toc entries for %s\n", dynamicInfo
->nextdefsym(), this->path());
510 const macho_nlist
<P
>* start
= &symbolTable
[dynamicInfo
->iextdefsym()];
511 const macho_nlist
<P
>* end
= &start
[dynamicInfo
->nextdefsym()];
512 _atoms
.reserve(dynamicInfo
->nextdefsym()); // set initial bucket count
513 for (const macho_nlist
<P
>* sym
=start
; sym
< end
; ++sym
) {
514 this->addSymbol(&strings
[sym
->n_strx()], (sym
->n_desc() & N_WEAK_DEF
) != 0, false, sym
->n_value());
518 int32_t count
= dynamicInfo
->ntoc();
519 _atoms
.reserve(count
); // set initial bucket count
520 if ( _s_logHashtable
) fprintf(stderr
, "ld: building hashtable of %u entries for %s\n", count
, this->path());
521 const struct dylib_table_of_contents
* toc
= (dylib_table_of_contents
*)(fileContent
+ dynamicInfo
->tocoff());
522 for (int32_t i
= 0; i
< count
; ++i
) {
523 const uint32_t index
= E::get32(toc
[i
].symbol_index
);
524 const macho_nlist
<P
>* sym
= &symbolTable
[index
];
525 this->addSymbol(&strings
[sym
->n_strx()], (sym
->n_desc() & N_WEAK_DEF
) != 0, false, sym
->n_value());
529 // special case old libSystem
530 if ( (_dylibInstallPath
!= NULL
) && (strcmp(_dylibInstallPath
, "/usr/lib/libSystem.B.dylib") == 0) )
535 template <typename A
>
536 void File
<A
>::buildExportHashTableFromExportInfo(const macho_dyld_info_command
<P
>* dyldInfo
,
537 const uint8_t* fileContent
)
539 if ( _s_logHashtable
) fprintf(stderr
, "ld: building hashtable from export info in %s\n", this->path());
540 if ( dyldInfo
->export_size() > 0 ) {
541 const uint8_t* start
= fileContent
+ dyldInfo
->export_off();
542 const uint8_t* end
= &start
[dyldInfo
->export_size()];
543 std::vector
<mach_o::trie::Entry
> list
;
544 parseTrie(start
, end
, list
);
545 for (std::vector
<mach_o::trie::Entry
>::iterator it
=list
.begin(); it
!= list
.end(); ++it
)
546 this->addSymbol(it
->name
,
547 it
->flags
& EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION
,
548 (it
->flags
& EXPORT_SYMBOL_FLAGS_KIND_MASK
) == EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL
,
555 void File
<x86_64
>::addDyldFastStub()
557 addSymbol("dyld_stub_binder", false, false, 0);
561 void File
<x86
>::addDyldFastStub()
563 addSymbol("dyld_stub_binder", false, false, 0);
566 template <typename A
>
567 void File
<A
>::addDyldFastStub()
572 template <typename A
>
573 void File
<A
>::addSymbol(const char* name
, bool weakDef
, bool tlv
, pint_t address
)
575 //fprintf(stderr, "addSymbol() %s\n", name);
576 // symbols that start with $ld$ are meta-data to the static linker
577 // <rdar://problem/5182537> need way for ld and dyld to see different exported symbols in a dylib
578 if ( strncmp(name
, "$ld$", 4) == 0 ) {
579 // $ld$ <action> $ <condition> $ <symbol-name>
580 const char* symAction
= &name
[4];
581 const char* symCond
= strchr(symAction
, '$');
582 if ( symCond
!= NULL
) {
584 if ( _macVersionMin
!= ld::macVersionUnset
) {
585 sprintf(curOSVers
, "$os%d.%d$", (_macVersionMin
>> 16), ((_macVersionMin
>> 8) & 0xFF));
587 else if ( _iOSVersionMin
!= ld::iOSVersionUnset
) {
588 sprintf(curOSVers
, "$os%d.%d$", (_iOSVersionMin
>> 16), ((_iOSVersionMin
>> 8) & 0xFF));
591 assert(0 && "targeting neither macosx nor iphoneos");
593 if ( strncmp(symCond
, curOSVers
, strlen(curOSVers
)) == 0 ) {
594 const char* symName
= strchr(&symCond
[1], '$');
595 if ( symName
!= NULL
) {
597 if ( strncmp(symAction
, "hide$", 5) == 0 ) {
598 if ( _s_logHashtable
) fprintf(stderr
, " adding %s to ignore set for %s\n", symName
, this->path());
599 _ignoreExports
.insert(strdup(symName
));
602 else if ( strncmp(symAction
, "add$", 4) == 0 ) {
603 this->addSymbol(symName
, weakDef
, false, 0);
606 else if ( strncmp(symAction
, "install_name$", 13) == 0 ) {
607 _dylibInstallPath
= symName
;
611 warning("bad symbol action: %s in dylib %s", name
, this->path());
617 warning("bad symbol condition: %s in dylib %s", name
, this->path());
621 // add symbol as possible export if we are not supposed to ignore it
622 if ( _ignoreExports
.count(name
) == 0 ) {
625 bucket
.weakDef
= weakDef
;
627 bucket
.address
= address
;
628 if ( _s_logHashtable
) fprintf(stderr
, " adding %s to hash table for %s\n", name
, this->path());
629 _atoms
[strdup(name
)] = bucket
;
634 template <typename A
>
635 bool File
<A
>::forEachAtom(ld::File::AtomHandler
& handler
) const
637 handler
.doFile(*this);
638 // if doing flatnamespace and need all this dylib's imports resolve
639 // add atom which references alls undefines in this dylib
640 if ( _importAtom
!= NULL
) {
641 handler
.doAtom(*_importAtom
);
647 template <typename A
>
648 bool File
<A
>::hasWeakDefinition(const char* name
) const
650 // if supposed to ignore this export, then pretend I don't have it
651 if ( _ignoreExports
.count(name
) != 0 )
654 typename
NameToAtomMap::const_iterator pos
= _atoms
.find(name
);
655 if ( pos
!= _atoms
.end() ) {
656 return pos
->second
.weakDef
;
659 // look in children that I re-export
660 for (typename
std::vector
<Dependent
>::const_iterator it
= _dependentDylibs
.begin(); it
!= _dependentDylibs
.end(); ++it
) {
661 if ( it
->reExport
) {
662 //fprintf(stderr, "getJustInTimeAtomsFor: %s NOT found in %s, looking in child %s\n", name, this->path(), (*it)->getInstallPath());
663 typename
NameToAtomMap::iterator cpos
= it
->dylib
->_atoms
.find(name
);
664 if ( cpos
!= it
->dylib
->_atoms
.end() )
665 return cpos
->second
.weakDef
;
673 // <rdar://problem/5529626> If only weak_import symbols are used, linker should use LD_LOAD_WEAK_DYLIB
674 template <typename A
>
675 bool File
<A
>::allSymbolsAreWeakImported() const
677 bool foundNonWeakImport
= false;
678 bool foundWeakImport
= false;
679 //fprintf(stderr, "%s:\n", this->path());
680 for (typename
NameToAtomMap::const_iterator it
= _atoms
.begin(); it
!= _atoms
.end(); ++it
) {
681 const ld::Atom
* atom
= it
->second
.atom
;
682 if ( atom
!= NULL
) {
683 if ( atom
->weakImported() )
684 foundWeakImport
= true;
686 foundNonWeakImport
= true;
687 //fprintf(stderr, " weak_import=%d, name=%s\n", atom->weakImported(), it->first);
691 // don't automatically weak link dylib with no imports
692 // so at least one weak import symbol and no non-weak-imported symbols must be found
693 return foundWeakImport
&& !foundNonWeakImport
;
697 template <typename A
>
698 bool File
<A
>::containsOrReExports(const char* name
, bool* weakDef
, bool* tlv
, pint_t
* defAddress
) const
700 if ( _ignoreExports
.count(name
) != 0 )
704 typename
NameToAtomMap::iterator pos
= _atoms
.find(name
);
705 if ( pos
!= _atoms
.end() ) {
706 *weakDef
= pos
->second
.weakDef
;
707 *tlv
= pos
->second
.tlv
;
708 *defAddress
= pos
->second
.address
;
712 // check dylibs I re-export
713 for (typename
std::vector
<Dependent
>::const_iterator it
= _dependentDylibs
.begin(); it
!= _dependentDylibs
.end(); ++it
) {
714 if ( it
->reExport
&& !it
->dylib
->implicitlyLinked() ) {
715 if ( it
->dylib
->containsOrReExports(name
, weakDef
, tlv
, defAddress
) )
724 template <typename A
>
725 bool File
<A
>::justInTimeforEachAtom(const char* name
, ld::File::AtomHandler
& handler
) const
727 // if supposed to ignore this export, then pretend I don't have it
728 if ( _ignoreExports
.count(name
) != 0 )
733 if ( this->containsOrReExports(name
, &bucket
.weakDef
, &bucket
.tlv
, &bucket
.address
) ) {
734 bucket
.atom
= new ExportAtom
<A
>(*this, name
, bucket
.weakDef
, bucket
.tlv
, bucket
.address
);
735 _atoms
[name
] = bucket
;
736 _providedAtom
= true;
737 if ( _s_logHashtable
) fprintf(stderr
, "getJustInTimeAtomsFor: %s found in %s\n", name
, this->path());
738 // call handler with new export atom
739 handler
.doAtom(*bucket
.atom
);
748 template <typename A
>
749 bool File
<A
>::isPublicLocation(const char* pth
)
751 // -no_implicit_dylibs disables this optimization
752 if ( ! _implicitlyLinkPublicDylibs
)
755 // /usr/lib is a public location
756 if ( (strncmp(pth
, "/usr/lib/", 9) == 0) && (strchr(&pth
[9], '/') == NULL
) )
759 // /System/Library/Frameworks/ is a public location
760 if ( strncmp(pth
, "/System/Library/Frameworks/", 27) == 0 ) {
761 const char* frameworkDot
= strchr(&pth
[27], '.');
762 // but only top level framework
763 // /System/Library/Frameworks/Foo.framework/Versions/A/Foo ==> true
764 // /System/Library/Frameworks/Foo.framework/Resources/libBar.dylib ==> false
765 // /System/Library/Frameworks/Foo.framework/Frameworks/Bar.framework/Bar ==> false
766 // /System/Library/Frameworks/Foo.framework/Frameworks/Xfoo.framework/XFoo ==> false
767 if ( frameworkDot
!= NULL
) {
768 int frameworkNameLen
= frameworkDot
- &pth
[27];
769 if ( strncmp(&pth
[strlen(pth
)-frameworkNameLen
-1], &pth
[26], frameworkNameLen
+1) == 0 )
777 template <typename A
>
778 void File
<A
>::processIndirectLibraries(ld::dylib::File::DylibHandler
* handler
, bool addImplicitDylibs
)
780 const static bool log
= false;
781 if ( log
) fprintf(stderr
, "processIndirectLibraries(%s)\n", this->installPath());
782 if ( _linkingFlat
) {
783 for (typename
std::vector
<Dependent
>::iterator it
= _dependentDylibs
.begin(); it
!= _dependentDylibs
.end(); it
++) {
784 it
->dylib
= (File
<A
>*)handler
->findDylib(it
->path
, this->path());
787 else if ( _noRexports
) {
788 // MH_NO_REEXPORTED_DYLIBS bit set, then nothing to do
791 // two-level, might have re-exports
792 for (typename
std::vector
<Dependent
>::iterator it
= _dependentDylibs
.begin(); it
!= _dependentDylibs
.end(); it
++) {
793 if ( it
->reExport
) {
794 if ( log
) fprintf(stderr
, "processIndirectLibraries() parent=%s, child=%s\n", this->installPath(), it
->path
);
795 // a LC_REEXPORT_DYLIB, LC_SUB_UMBRELLA or LC_SUB_LIBRARY says we re-export this child
796 it
->dylib
= (File
<A
>*)handler
->findDylib(it
->path
, this->path());
797 if ( it
->dylib
->hasPublicInstallName() ) {
798 // promote this child to be automatically added as a direct dependent if this already is
799 if ( (this->explicitlyLinked() || this->implicitlyLinked()) && (strcmp(it
->path
,it
->dylib
->installPath()) == 0) ) {
800 if ( log
) fprintf(stderr
, "processIndirectLibraries() implicitly linking %s\n", it
->dylib
->installPath());
801 it
->dylib
->setImplicitlyLinked();
803 else if ( it
->dylib
->explicitlyLinked() || it
->dylib
->implicitlyLinked() ) {
804 if ( log
) fprintf(stderr
, "processIndirectLibraries() parent is not directly linked, but child is, so no need to re-export child\n");
807 if ( log
) fprintf(stderr
, "processIndirectLibraries() parent is not directly linked, so parent=%s will re-export child=%s\n", this->installPath(), it
->path
);
811 // add all child's symbols to me
812 if ( log
) fprintf(stderr
, "processIndirectLibraries() child is not public, so parent=%s will re-export child=%s\n", this->installPath(), it
->path
);
815 else if ( !_explictReExportFound
) {
816 // see if child contains LC_SUB_FRAMEWORK with my name
817 it
->dylib
= (File
<A
>*)handler
->findDylib(it
->path
, this->path());
818 const char* parentUmbrellaName
= it
->dylib
->parentUmbrella();
819 if ( parentUmbrellaName
!= NULL
) {
820 const char* parentName
= this->path();
821 const char* lastSlash
= strrchr(parentName
, '/');
822 if ( (lastSlash
!= NULL
) && (strcmp(&lastSlash
[1], parentUmbrellaName
) == 0) ) {
823 // add all child's symbols to me
825 if ( log
) fprintf(stderr
, "processIndirectLibraries() umbrella=%s will re-export child=%s\n", this->installPath(), it
->path
);
832 // check for re-export cycles
836 this->assertNoReExportCycles(&chain
);
839 template <typename A
>
840 void File
<A
>::assertNoReExportCycles(ReExportChain
* prev
)
842 // recursively check my re-exported dylibs
846 for (typename
std::vector
<Dependent
>::iterator it
= _dependentDylibs
.begin(); it
!= _dependentDylibs
.end(); it
++) {
847 if ( it
->reExport
) {
848 ld::File
* child
= it
->dylib
;
849 // check child is not already in chain
850 for (ReExportChain
* p
= prev
; p
!= NULL
; p
= p
->prev
) {
851 if ( p
->file
== child
) {
852 throwf("cycle in dylib re-exports with %s and %s", child
->path(), this->path());
855 if ( it
->dylib
!= NULL
)
856 it
->dylib
->assertNoReExportCycles(&chain
);
862 template <typename A
>
866 typedef typename
A::P P
;
868 static bool validFile(const uint8_t* fileContent
, bool executableOrDyliborBundle
);
869 static ld::dylib::File
* parse(const uint8_t* fileContent
, uint64_t fileLength
,
870 const char* path
, time_t mTime
,
871 ld::File::Ordinal ordinal
, const Options
& opts
, bool indirectDylib
) {
872 return new File
<A
>(fileContent
, fileLength
, path
, mTime
,
873 ordinal
, opts
.flatNamespace(),
874 opts
.linkingMainExecutable(),
875 opts
.implicitlyLinkIndirectPublicDylibs(),
876 opts
.macosxVersionMin(),
877 opts
.iOSVersionMin(),
878 opts
.addVersionLoadCommand(),
889 bool Parser
<x86
>::validFile(const uint8_t* fileContent
, bool executableOrDyliborBundle
)
891 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
892 if ( header
->magic() != MH_MAGIC
)
894 if ( header
->cputype() != CPU_TYPE_I386
)
896 switch ( header
->filetype() ) {
901 if ( executableOrDyliborBundle
)
904 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
906 if ( executableOrDyliborBundle
)
909 throw "can't link with a main executable";
916 bool Parser
<x86_64
>::validFile(const uint8_t* fileContent
, bool executableOrDyliborBundle
)
918 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
919 if ( header
->magic() != MH_MAGIC_64
)
921 if ( header
->cputype() != CPU_TYPE_X86_64
)
923 switch ( header
->filetype() ) {
928 if ( executableOrDyliborBundle
)
931 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
933 if ( executableOrDyliborBundle
)
936 throw "can't link with a main executable";
943 bool Parser
<arm
>::validFile(const uint8_t* fileContent
, bool executableOrDyliborBundle
)
945 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
946 if ( header
->magic() != MH_MAGIC
)
948 if ( header
->cputype() != CPU_TYPE_ARM
)
950 switch ( header
->filetype() ) {
955 if ( executableOrDyliborBundle
)
958 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
960 if ( executableOrDyliborBundle
)
963 throw "can't link with a main executable";
972 // main function used by linker to instantiate ld::Files
974 ld::dylib::File
* parse(const uint8_t* fileContent
, uint64_t fileLength
,
975 const char* path
, time_t modTime
, const Options
& opts
, ld::File::Ordinal ordinal
,
976 bool bundleLoader
, bool indirectDylib
)
978 switch ( opts
.architecture() ) {
979 #if SUPPORT_ARCH_x86_64
980 case CPU_TYPE_X86_64
:
981 if ( Parser
<x86_64
>::validFile(fileContent
, bundleLoader
) )
982 return Parser
<x86_64
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
, indirectDylib
);
985 #if SUPPORT_ARCH_i386
987 if ( Parser
<x86
>::validFile(fileContent
, bundleLoader
) )
988 return Parser
<x86
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
, indirectDylib
);
991 #if SUPPORT_ARCH_arm_any
993 if ( Parser
<arm
>::validFile(fileContent
, bundleLoader
) )
994 return Parser
<arm
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
, indirectDylib
);
1002 }; // namespace dylib
1003 }; // namespace mach_o