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 <ext/hash_map>
37 #include <ext/hash_set>
39 #include "Architectures.hpp"
40 #include "MachOFileAbstraction.hpp"
41 #include "MachOTrie.hpp"
42 #include "macho_dylib_file.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 bool translationUnitSource(const char** dir
, const char** nm
) const
73 virtual const char* name() const { return _name
; }
74 virtual uint64_t size() const { return 0; }
75 virtual uint64_t objectAddress() const { return _address
; }
76 virtual void copyRawContent(uint8_t buffer
[]) const { }
77 virtual void setScope(Scope
) { }
80 typedef typename
A::P P
;
81 typedef typename
A::P::uint_t pint_t
;
83 virtual ~ExportAtom() {}
93 // An ImportAtom has no content. It exists so that when linking a main executable flat-namespace
94 // the imports of all flat dylibs are checked
97 class ImportAtom
: public ld::Atom
100 ImportAtom(File
<A
>& f
, std::vector
<const char*>& imports
);
102 // overrides of ld::Atom
103 virtual ld::File
* file() const { return &_file
; }
104 virtual bool translationUnitSource(const char** dir
, const char** nm
) const
106 virtual const char* name() const { return "import-atom"; }
107 virtual uint64_t size() const { return 0; }
108 virtual uint64_t objectAddress() const { return 0; }
109 virtual void copyRawContent(uint8_t buffer
[]) const { }
110 virtual void setScope(Scope
) { }
111 virtual ld::Fixup::iterator
fixupsBegin() const { return &_undefs
[0]; }
112 virtual ld::Fixup::iterator
fixupsEnd() const { return &_undefs
[_undefs
.size()]; }
115 typedef typename
A::P P
;
117 virtual ~ImportAtom() {}
121 mutable std::vector
<ld::Fixup
> _undefs
;
124 template <typename A
>
125 ImportAtom
<A
>::ImportAtom(File
<A
>& f
, std::vector
<const char*>& imports
)
126 : ld::Atom(f
._flatDummySection
, ld::Atom::definitionRegular
, ld::Atom::combineNever
, ld::Atom::scopeTranslationUnit
,
127 ld::Atom::typeUnclassified
, symbolTableNotIn
, false, false, false, ld::Atom::Alignment(0)), _file(f
)
129 for(std::vector
<const char*>::iterator it
=imports
.begin(); it
!= imports
.end(); ++it
) {
130 _undefs
.push_back(ld::Fixup(0, ld::Fixup::k1of1
, ld::Fixup::kindNone
, false, strdup(*it
)));
137 // The reader for a dylib extracts all exported symbols names from the memory-mapped
138 // dylib, builds a hash table, then unmaps the file. This is an important memory
139 // savings for large dylibs.
141 template <typename A
>
142 class File
: public ld::dylib::File
145 static bool validFile(const uint8_t* fileContent
, bool executableOrDylib
);
146 File(const uint8_t* fileContent
, uint64_t fileLength
, const char* path
,
147 time_t mTime
, uint32_t ordinal
, bool linkingFlatNamespace
,
148 bool linkingMainExecutable
, bool hoistImplicitPublicDylibs
,
149 ld::MacVersionMin macMin
, ld::IOSVersionMin iPhoneMin
, bool addVers
,
150 bool logAllFiles
, const char* installPath
, bool indirectDylib
);
153 // overrides of ld::File
154 virtual bool forEachAtom(ld::File::AtomHandler
&) const;
155 virtual bool justInTimeforEachAtom(const char* name
, ld::File::AtomHandler
&) const;
156 virtual ld::File::ObjcConstraint
objCConstraint() const { return _objcContraint
; }
158 // overrides of ld::dylib::File
159 virtual void processIndirectLibraries(ld::dylib::File::DylibHandler
*, bool);
160 virtual bool providedExportAtom() const { return _providedAtom
; }
161 virtual const char* parentUmbrella() const { return _parentUmbrella
; }
162 virtual const std::vector
<const char*>* allowableClients() const { return _allowableClients
.size() != 0 ? &_allowableClients
: NULL
; }
163 virtual bool hasWeakExternals() const { return _hasWeakExports
; }
164 virtual bool deadStrippable() const { return _deadStrippable
; }
165 virtual bool hasPublicInstallName() const{ return _hasPublicInstallName
; }
166 virtual bool hasWeakDefinition(const char* name
) const;
167 virtual bool allSymbolsAreWeakImported() const;
172 struct ReExportChain
{ ReExportChain
* prev
; File
<A
>* file
; };
174 void assertNoReExportCycles(ReExportChain
*);
177 typedef typename
A::P P
;
178 typedef typename
A::P::E E
;
179 typedef typename
A::P::uint_t pint_t
;
181 friend class ExportAtom
<A
>;
182 friend class ImportAtom
<A
>;
187 bool operator()(const char* left
, const char* right
) const { return (strcmp(left
, right
) == 0); }
189 struct AtomAndWeak
{ ld::Atom
* atom
; bool weakDef
; bool tlv
; pint_t address
; };
190 typedef __gnu_cxx::hash_map
<const char*, AtomAndWeak
, __gnu_cxx::hash
<const char*>, CStringEquals
> NameToAtomMap
;
191 typedef __gnu_cxx::hash_set
<const char*, __gnu_cxx::hash
<const char*>, 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
;
222 bool _hasWeakExports
;
223 bool _deadStrippable
;
224 bool _hasPublicInstallName
;
225 mutable bool _providedAtom
;
226 bool _explictReExportFound
;
228 static bool _s_logHashtable
;
231 template <typename A
>
232 bool File
<A
>::_s_logHashtable
= false;
234 template <> const char* File
<x86_64
>::objCInfoSegmentName() { return "__DATA"; }
235 template <> const char* File
<arm
>::objCInfoSegmentName() { return "__DATA"; }
236 template <typename A
> const char* File
<A
>::objCInfoSegmentName() { return "__OBJC"; }
238 template <> const char* File
<x86_64
>::objCInfoSectionName() { return "__objc_imageinfo"; }
239 template <> const char* File
<arm
>::objCInfoSectionName() { return "__objc_imageinfo"; }
240 template <typename A
> const char* File
<A
>::objCInfoSectionName() { return "__image_info"; }
242 template <typename A
>
243 File
<A
>::File(const uint8_t* fileContent
, uint64_t fileLength
, const char* pth
, time_t mTime
, uint32_t ord
,
244 bool linkingFlatNamespace
, bool linkingMainExecutable
, bool hoistImplicitPublicDylibs
,
245 ld::MacVersionMin macMin
, ld::IOSVersionMin iOSMin
, bool addVers
,
246 bool logAllFiles
, const char* targetInstallPath
, bool indirectDylib
)
247 : ld::dylib::File(strdup(pth
), mTime
, ord
),
248 _macVersionMin(macMin
), _iOSVersionMin(iOSMin
), _addVersionLoadCommand(addVers
),
249 _linkingFlat(linkingFlatNamespace
), _implicitlyLinkPublicDylibs(hoistImplicitPublicDylibs
),
250 _objcContraint(ld::File::objcConstraintNone
),
251 _importProxySection("__TEXT", "__import", ld::Section::typeImportProxies
, true),
252 _flatDummySection("__LINKEDIT", "__flat_dummy", ld::Section::typeLinkEdit
, true),
253 _parentUmbrella(NULL
), _importAtom(NULL
), _noRexports(false), _hasWeakExports(false),
254 _deadStrippable(false), _hasPublicInstallName(false),
255 _providedAtom(false), _explictReExportFound(false)
257 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
258 const uint32_t cmd_count
= header
->ncmds();
259 const macho_load_command
<P
>* const cmds
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>));
260 const macho_load_command
<P
>* const cmdsEnd
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>) + header
->sizeofcmds());
262 // write out path for -t option
266 // a "blank" stub has zero load commands
267 if ( (header
->filetype() == MH_DYLIB_STUB
) && (cmd_count
== 0) ) {
268 // no further processing needed
269 munmap((caddr_t
)fileContent
, fileLength
);
274 // optimize the case where we know there is no reason to look at indirect dylibs
275 _noRexports
= (header
->flags() & MH_NO_REEXPORTED_DYLIBS
)
276 || (header
->filetype() == MH_BUNDLE
)
277 || (header
->filetype() == MH_EXECUTE
); // bundles and exectuables can be used via -bundle_loader
278 _hasWeakExports
= (header
->flags() & MH_WEAK_DEFINES
);
279 _deadStrippable
= (header
->flags() & MH_DEAD_STRIPPABLE_DYLIB
);
281 // pass 1: get pointers, and see if this dylib uses compressed LINKEDIT format
282 const macho_dysymtab_command
<P
>* dynamicInfo
= NULL
;
283 const macho_dyld_info_command
<P
>* dyldInfo
= NULL
;
284 const macho_nlist
<P
>* symbolTable
= NULL
;
285 const char* strings
= NULL
;
286 bool compressedLinkEdit
= false;
287 uint32_t dependentLibCount
= 0;
288 const macho_load_command
<P
>* cmd
= cmds
;
289 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
290 macho_dylib_command
<P
>* dylibID
;
291 const macho_symtab_command
<P
>* symtab
;
292 switch (cmd
->cmd()) {
294 symtab
= (macho_symtab_command
<P
>*)cmd
;
295 symbolTable
= (const macho_nlist
<P
>*)((char*)header
+ symtab
->symoff());
296 strings
= (char*)header
+ symtab
->stroff();
299 dynamicInfo
= (macho_dysymtab_command
<P
>*)cmd
;
302 case LC_DYLD_INFO_ONLY
:
303 dyldInfo
= (macho_dyld_info_command
<P
>*)cmd
;
304 compressedLinkEdit
= true;
307 dylibID
= (macho_dylib_command
<P
>*)cmd
;
308 _dylibInstallPath
= strdup(dylibID
->name());
309 _dylibTimeStamp
= dylibID
->timestamp();
310 _dylibCurrentVersion
= dylibID
->current_version();
311 _dylibCompatibilityVersion
= dylibID
->compatibility_version();
312 _hasPublicInstallName
= isPublicLocation(_dylibInstallPath
);
315 case LC_LOAD_WEAK_DYLIB
:
318 case LC_REEXPORT_DYLIB
:
319 _explictReExportFound
= true;
322 case LC_SUB_FRAMEWORK
:
323 _parentUmbrella
= strdup(((macho_sub_framework_command
<P
>*)cmd
)->umbrella());
326 _allowableClients
.push_back(strdup(((macho_sub_client_command
<P
>*)cmd
)->client()));
328 case LC_VERSION_MIN_MACOSX
:
329 if ( _addVersionLoadCommand
&& !indirectDylib
&& (_iOSVersionMin
!= ld::iOSVersionUnset
) )
330 warning("building for iOS, but linking against dylib built for MacOSX: %s", pth
);
332 case LC_VERSION_MIN_IPHONEOS
:
333 if ( _addVersionLoadCommand
&& !indirectDylib
&& (_macVersionMin
!= ld::macVersionUnset
) )
334 warning("building for MacOSX, but linking against dylib built for iOS: %s", pth
);
336 case macho_segment_command
<P
>::CMD
:
337 // check for Objective-C info
338 if ( strcmp(((macho_segment_command
<P
>*)cmd
)->segname(), objCInfoSegmentName()) == 0 ) {
339 const macho_segment_command
<P
>* segment
= (macho_segment_command
<P
>*)cmd
;
340 const macho_section
<P
>* const sectionsStart
= (macho_section
<P
>*)((char*)segment
+ sizeof(macho_segment_command
<P
>));
341 const macho_section
<P
>* const sectionsEnd
= §ionsStart
[segment
->nsects()];
342 for (const macho_section
<P
>* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
343 if ( strncmp(sect
->sectname(), objCInfoSectionName(), strlen(objCInfoSectionName())) == 0 ) {
344 // struct objc_image_info {
345 // uint32_t version; // initially 0
348 // #define OBJC_IMAGE_SUPPORTS_GC 2
349 // #define OBJC_IMAGE_GC_ONLY 4
351 const uint32_t* contents
= (uint32_t*)(&fileContent
[sect
->offset()]);
352 if ( (sect
->size() >= 8) && (contents
[0] == 0) ) {
353 uint32_t flags
= E::get32(contents
[1]);
354 if ( (flags
& 4) == 4 )
355 _objcContraint
= ld::File::objcConstraintGC
;
356 else if ( (flags
& 2) == 2 )
357 _objcContraint
= ld::File::objcConstraintRetainReleaseOrGC
;
359 _objcContraint
= ld::File::objcConstraintRetainRelease
;
361 else if ( sect
->size() > 0 ) {
362 warning("can't parse %s/%s section in %s", objCInfoSegmentName(), objCInfoSectionName(), this->path());
368 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
370 throwf("malformed dylb, load command #%d is outside size of load commands in %s", i
, pth
);
373 // figure out if we need to examine dependent dylibs
374 // with compressed LINKEDIT format, MH_NO_REEXPORTED_DYLIBS can be trusted
375 bool processDependentLibraries
= true;
376 if ( compressedLinkEdit
&& _noRexports
&& !linkingFlatNamespace
)
377 processDependentLibraries
= false;
379 if ( processDependentLibraries
) {
380 // pass 2 builds list of all dependent libraries
381 _dependentDylibs
.reserve(dependentLibCount
);
383 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
384 switch (cmd
->cmd()) {
386 case LC_LOAD_WEAK_DYLIB
:
387 // with new linkedit format only care about LC_REEXPORT_DYLIB
388 if ( compressedLinkEdit
&& !linkingFlatNamespace
)
390 case LC_REEXPORT_DYLIB
:
392 entry
.path
= strdup(((macho_dylib_command
<P
>*)cmd
)->name());
394 entry
.reExport
= (cmd
->cmd() == LC_REEXPORT_DYLIB
);
395 if ( (targetInstallPath
== NULL
) || (strcmp(targetInstallPath
, entry
.path
) != 0) )
396 _dependentDylibs
.push_back(entry
);
399 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
401 // verify MH_NO_REEXPORTED_DYLIBS bit was correct
402 if ( compressedLinkEdit
&& !linkingFlatNamespace
) {
403 assert(_dependentDylibs
.size() != 0);
405 // pass 3 add re-export info
407 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
408 const char* frameworkLeafName
;
409 const char* dylibBaseName
;
410 switch (cmd
->cmd()) {
411 case LC_SUB_UMBRELLA
:
412 frameworkLeafName
= ((macho_sub_umbrella_command
<P
>*)cmd
)->sub_umbrella();
413 for (typename
std::vector
<Dependent
>::iterator it
= _dependentDylibs
.begin(); it
!= _dependentDylibs
.end(); ++it
) {
414 const char* dylibName
= it
->path
;
415 const char* lastSlash
= strrchr(dylibName
, '/');
416 if ( (lastSlash
!= NULL
) && (strcmp(&lastSlash
[1], frameworkLeafName
) == 0) )
421 dylibBaseName
= ((macho_sub_library_command
<P
>*)cmd
)->sub_library();
422 for (typename
std::vector
<Dependent
>::iterator it
= _dependentDylibs
.begin(); it
!= _dependentDylibs
.end(); ++it
) {
423 const char* dylibName
= it
->path
;
424 const char* lastSlash
= strrchr(dylibName
, '/');
425 const char* leafStart
= &lastSlash
[1];
426 if ( lastSlash
== NULL
)
427 leafStart
= dylibName
;
428 const char* firstDot
= strchr(leafStart
, '.');
429 int len
= strlen(leafStart
);
430 if ( firstDot
!= NULL
)
431 len
= firstDot
- leafStart
;
432 if ( strncmp(leafStart
, dylibBaseName
, len
) == 0 )
437 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
441 // validate minimal load commands
442 if ( (_dylibInstallPath
== NULL
) && ((header
->filetype() == MH_DYLIB
) || (header
->filetype() == MH_DYLIB_STUB
)) )
443 throwf("dylib %s missing LC_ID_DYLIB load command", pth
);
444 if ( dyldInfo
== NULL
) {
445 if ( symbolTable
== NULL
)
446 throw "binary missing LC_SYMTAB load command";
447 if ( dynamicInfo
== NULL
)
448 throw "binary missing LC_DYSYMTAB load command";
451 // if linking flat and this is a flat dylib, create one atom that references all imported symbols
452 if ( linkingFlatNamespace
&& linkingMainExecutable
&& ((header
->flags() & MH_TWOLEVEL
) == 0) ) {
453 std::vector
<const char*> importNames
;
454 importNames
.reserve(dynamicInfo
->nundefsym());
455 const macho_nlist
<P
>* start
= &symbolTable
[dynamicInfo
->iundefsym()];
456 const macho_nlist
<P
>* end
= &start
[dynamicInfo
->nundefsym()];
457 for (const macho_nlist
<P
>* sym
=start
; sym
< end
; ++sym
) {
458 importNames
.push_back(&strings
[sym
->n_strx()]);
460 _importAtom
= new ImportAtom
<A
>(*this, importNames
);
464 if ( dyldInfo
!= NULL
)
465 buildExportHashTableFromExportInfo(dyldInfo
, fileContent
);
467 buildExportHashTableFromSymbolTable(dynamicInfo
, symbolTable
, strings
, fileContent
);
470 munmap((caddr_t
)fileContent
, fileLength
);
474 template <typename A
>
475 void File
<A
>::buildExportHashTableFromSymbolTable(const macho_dysymtab_command
<P
>* dynamicInfo
,
476 const macho_nlist
<P
>* symbolTable
, const char* strings
,
477 const uint8_t* fileContent
)
479 if ( dynamicInfo
->tocoff() == 0 ) {
480 if ( _s_logHashtable
) fprintf(stderr
, "ld: building hashtable of %u toc entries for %s\n", dynamicInfo
->nextdefsym(), this->path());
481 const macho_nlist
<P
>* start
= &symbolTable
[dynamicInfo
->iextdefsym()];
482 const macho_nlist
<P
>* end
= &start
[dynamicInfo
->nextdefsym()];
483 _atoms
.resize(dynamicInfo
->nextdefsym()); // set initial bucket count
484 for (const macho_nlist
<P
>* sym
=start
; sym
< end
; ++sym
) {
485 this->addSymbol(&strings
[sym
->n_strx()], (sym
->n_desc() & N_WEAK_DEF
) != 0, false, sym
->n_value());
489 int32_t count
= dynamicInfo
->ntoc();
490 _atoms
.resize(count
); // set initial bucket count
491 if ( _s_logHashtable
) fprintf(stderr
, "ld: building hashtable of %u entries for %s\n", count
, this->path());
492 const struct dylib_table_of_contents
* toc
= (dylib_table_of_contents
*)(fileContent
+ dynamicInfo
->tocoff());
493 for (int32_t i
= 0; i
< count
; ++i
) {
494 const uint32_t index
= E::get32(toc
[i
].symbol_index
);
495 const macho_nlist
<P
>* sym
= &symbolTable
[index
];
496 this->addSymbol(&strings
[sym
->n_strx()], (sym
->n_desc() & N_WEAK_DEF
) != 0, false, sym
->n_value());
500 // special case old libSystem
501 if ( (_dylibInstallPath
!= NULL
) && (strcmp(_dylibInstallPath
, "/usr/lib/libSystem.B.dylib") == 0) )
506 template <typename A
>
507 void File
<A
>::buildExportHashTableFromExportInfo(const macho_dyld_info_command
<P
>* dyldInfo
,
508 const uint8_t* fileContent
)
510 if ( _s_logHashtable
) fprintf(stderr
, "ld: building hashtable from export info in %s\n", this->path());
511 if ( dyldInfo
->export_size() > 0 ) {
512 const uint8_t* start
= fileContent
+ dyldInfo
->export_off();
513 const uint8_t* end
= &start
[dyldInfo
->export_size()];
514 std::vector
<mach_o::trie::Entry
> list
;
515 parseTrie(start
, end
, list
);
516 for (std::vector
<mach_o::trie::Entry
>::iterator it
=list
.begin(); it
!= list
.end(); ++it
)
517 this->addSymbol(it
->name
,
518 it
->flags
& EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION
,
519 (it
->flags
& EXPORT_SYMBOL_FLAGS_KIND_MASK
) == EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL
,
526 void File
<x86_64
>::addDyldFastStub()
528 addSymbol("dyld_stub_binder", false, false, 0);
532 void File
<x86
>::addDyldFastStub()
534 addSymbol("dyld_stub_binder", false, false, 0);
537 template <typename A
>
538 void File
<A
>::addDyldFastStub()
543 template <typename A
>
544 void File
<A
>::addSymbol(const char* name
, bool weakDef
, bool tlv
, pint_t address
)
547 assert(_hasWeakExports
);
549 //fprintf(stderr, "addSymbol() %s\n", name);
550 // symbols that start with $ld$ are meta-data to the static linker
551 // <rdar://problem/5182537> need way for ld and dyld to see different exported symbols in a dylib
552 if ( strncmp(name
, "$ld$", 4) == 0 ) {
553 // $ld$ <action> $ <condition> $ <symbol-name>
554 const char* symAction
= &name
[4];
555 const char* symCond
= strchr(symAction
, '$');
556 if ( symCond
!= NULL
) {
558 if ( _macVersionMin
!= ld::macVersionUnset
) {
559 sprintf(curOSVers
, "$os%d.%d$", (_macVersionMin
>> 16), ((_macVersionMin
>> 8) & 0xFF));
561 else if ( _iOSVersionMin
!= ld::iOSVersionUnset
) {
562 sprintf(curOSVers
, "$os%d.%d$", (_iOSVersionMin
>> 16), ((_iOSVersionMin
>> 8) & 0xFF));
565 assert(0 && "targeting neither macosx nor iphoneos");
567 if ( strncmp(symCond
, curOSVers
, strlen(curOSVers
)) == 0 ) {
568 const char* symName
= strchr(&symCond
[1], '$');
569 if ( symName
!= NULL
) {
571 if ( strncmp(symAction
, "hide$", 5) == 0 ) {
572 if ( _s_logHashtable
) fprintf(stderr
, " adding %s to ignore set for %s\n", symName
, this->path());
573 _ignoreExports
.insert(strdup(symName
));
576 else if ( strncmp(symAction
, "add$", 4) == 0 ) {
577 this->addSymbol(symName
, weakDef
, false, 0);
581 warning("bad symbol action: %s in dylib %s", name
, this->path());
587 warning("bad symbol condition: %s in dylib %s", name
, this->path());
591 // add symbol as possible export if we are not supposed to ignore it
592 if ( _ignoreExports
.count(name
) == 0 ) {
595 bucket
.weakDef
= weakDef
;
597 bucket
.address
= address
;
598 if ( _s_logHashtable
) fprintf(stderr
, " adding %s to hash table for %s\n", name
, this->path());
599 _atoms
[strdup(name
)] = bucket
;
604 template <typename A
>
605 bool File
<A
>::forEachAtom(ld::File::AtomHandler
& handler
) const
607 handler
.doFile(*this);
608 // if doing flatnamespace and need all this dylib's imports resolve
609 // add atom which references alls undefines in this dylib
610 if ( _importAtom
!= NULL
) {
611 handler
.doAtom(*_importAtom
);
617 template <typename A
>
618 bool File
<A
>::hasWeakDefinition(const char* name
) const
620 // if supposed to ignore this export, then pretend I don't have it
621 if ( _ignoreExports
.count(name
) != 0 )
624 typename
NameToAtomMap::const_iterator pos
= _atoms
.find(name
);
625 if ( pos
!= _atoms
.end() ) {
626 return pos
->second
.weakDef
;
629 // look in children that I re-export
630 for (typename
std::vector
<Dependent
>::const_iterator it
= _dependentDylibs
.begin(); it
!= _dependentDylibs
.end(); ++it
) {
631 if ( it
->reExport
) {
632 //fprintf(stderr, "getJustInTimeAtomsFor: %s NOT found in %s, looking in child %s\n", name, this->path(), (*it)->getInstallPath());
633 typename
NameToAtomMap::iterator cpos
= it
->dylib
->_atoms
.find(name
);
634 if ( cpos
!= it
->dylib
->_atoms
.end() )
635 return cpos
->second
.weakDef
;
643 // <rdar://problem/5529626> If only weak_import symbols are used, linker should use LD_LOAD_WEAK_DYLIB
644 template <typename A
>
645 bool File
<A
>::allSymbolsAreWeakImported() const
647 bool foundNonWeakImport
= false;
648 bool foundWeakImport
= false;
649 //fprintf(stderr, "%s:\n", this->path());
650 for (typename
NameToAtomMap::const_iterator it
= _atoms
.begin(); it
!= _atoms
.end(); ++it
) {
651 const ld::Atom
* atom
= it
->second
.atom
;
652 if ( atom
!= NULL
) {
653 if ( atom
->weakImported() )
654 foundWeakImport
= true;
656 foundNonWeakImport
= true;
657 //fprintf(stderr, " weak_import=%d, name=%s\n", atom->weakImported(), it->first);
661 // don't automatically weak link dylib with no imports
662 // so at least one weak import symbol and no non-weak-imported symbols must be found
663 return foundWeakImport
&& !foundNonWeakImport
;
667 template <typename A
>
668 bool File
<A
>::containsOrReExports(const char* name
, bool* weakDef
, bool* tlv
, pint_t
* defAddress
) const
670 if ( _ignoreExports
.count(name
) != 0 )
674 typename
NameToAtomMap::iterator pos
= _atoms
.find(name
);
675 if ( pos
!= _atoms
.end() ) {
676 *weakDef
= pos
->second
.weakDef
;
677 *tlv
= pos
->second
.tlv
;
678 *defAddress
= pos
->second
.address
;
682 // check dylibs I re-export
683 for (typename
std::vector
<Dependent
>::const_iterator it
= _dependentDylibs
.begin(); it
!= _dependentDylibs
.end(); ++it
) {
684 if ( it
->reExport
&& !it
->dylib
->implicitlyLinked() ) {
685 if ( it
->dylib
->containsOrReExports(name
, weakDef
, tlv
, defAddress
) )
694 template <typename A
>
695 bool File
<A
>::justInTimeforEachAtom(const char* name
, ld::File::AtomHandler
& handler
) const
697 // if supposed to ignore this export, then pretend I don't have it
698 if ( _ignoreExports
.count(name
) != 0 )
703 if ( this->containsOrReExports(name
, &bucket
.weakDef
, &bucket
.tlv
, &bucket
.address
) ) {
704 bucket
.atom
= new ExportAtom
<A
>(*this, name
, bucket
.weakDef
, bucket
.tlv
, bucket
.address
);
705 _atoms
[name
] = bucket
;
706 _providedAtom
= true;
707 if ( _s_logHashtable
) fprintf(stderr
, "getJustInTimeAtomsFor: %s found in %s\n", name
, this->path());
708 // call handler with new export atom
709 handler
.doAtom(*bucket
.atom
);
718 template <typename A
>
719 bool File
<A
>::isPublicLocation(const char* pth
)
721 // -no_implicit_dylibs disables this optimization
722 if ( ! _implicitlyLinkPublicDylibs
)
725 // /usr/lib is a public location
726 if ( (strncmp(pth
, "/usr/lib/", 9) == 0) && (strchr(&pth
[9], '/') == NULL
) )
729 // /System/Library/Frameworks/ is a public location
730 if ( strncmp(pth
, "/System/Library/Frameworks/", 27) == 0 ) {
731 const char* frameworkDot
= strchr(&pth
[27], '.');
732 // but only top level framework
733 // /System/Library/Frameworks/Foo.framework/Versions/A/Foo ==> true
734 // /System/Library/Frameworks/Foo.framework/Resources/libBar.dylib ==> false
735 // /System/Library/Frameworks/Foo.framework/Frameworks/Bar.framework/Bar ==> false
736 // /System/Library/Frameworks/Foo.framework/Frameworks/Xfoo.framework/XFoo ==> false
737 if ( frameworkDot
!= NULL
) {
738 int frameworkNameLen
= frameworkDot
- &pth
[27];
739 if ( strncmp(&pth
[strlen(pth
)-frameworkNameLen
-1], &pth
[26], frameworkNameLen
+1) == 0 )
747 template <typename A
>
748 void File
<A
>::processIndirectLibraries(ld::dylib::File::DylibHandler
* handler
, bool addImplicitDylibs
)
750 const static bool log
= false;
751 if ( log
) fprintf(stderr
, "processIndirectLibraries(%s)\n", this->installPath());
752 if ( _linkingFlat
) {
753 for (typename
std::vector
<Dependent
>::iterator it
= _dependentDylibs
.begin(); it
!= _dependentDylibs
.end(); it
++) {
754 it
->dylib
= (File
<A
>*)handler
->findDylib(it
->path
, this->path());
757 else if ( _noRexports
) {
758 // MH_NO_REEXPORTED_DYLIBS bit set, then nothing to do
761 // two-level, might have re-exports
762 for (typename
std::vector
<Dependent
>::iterator it
= _dependentDylibs
.begin(); it
!= _dependentDylibs
.end(); it
++) {
763 if ( it
->reExport
) {
764 if ( log
) fprintf(stderr
, "processIndirectLibraries() parent=%s, child=%s\n", this->installPath(), it
->path
);
765 // a LC_REEXPORT_DYLIB, LC_SUB_UMBRELLA or LC_SUB_LIBRARY says we re-export this child
766 it
->dylib
= (File
<A
>*)handler
->findDylib(it
->path
, this->path());
767 if ( it
->dylib
->hasPublicInstallName() ) {
768 // promote this child to be automatically added as a direct dependent if this already is
769 if ( (this->explicitlyLinked() || this->implicitlyLinked()) && (strcmp(it
->path
,it
->dylib
->installPath()) == 0) ) {
770 if ( log
) fprintf(stderr
, "processIndirectLibraries() implicitly linking %s\n", it
->dylib
->installPath());
771 it
->dylib
->setImplicitlyLinked();
773 else if ( it
->dylib
->explicitlyLinked() || it
->dylib
->implicitlyLinked() ) {
774 if ( log
) fprintf(stderr
, "processIndirectLibraries() parent is not directly linked, but child is, so no need to re-export child\n");
777 if ( log
) fprintf(stderr
, "processIndirectLibraries() parent is not directly linked, so parent=%s will re-export child=%s\n", this->installPath(), it
->path
);
781 // add all child's symbols to me
782 if ( log
) fprintf(stderr
, "processIndirectLibraries() child is not public, so parent=%s will re-export child=%s\n", this->installPath(), it
->path
);
785 else if ( !_explictReExportFound
) {
786 // see if child contains LC_SUB_FRAMEWORK with my name
787 it
->dylib
= (File
<A
>*)handler
->findDylib(it
->path
, this->path());
788 const char* parentUmbrellaName
= it
->dylib
->parentUmbrella();
789 if ( parentUmbrellaName
!= NULL
) {
790 const char* parentName
= this->path();
791 const char* lastSlash
= strrchr(parentName
, '/');
792 if ( (lastSlash
!= NULL
) && (strcmp(&lastSlash
[1], parentUmbrellaName
) == 0) ) {
793 // add all child's symbols to me
795 if ( log
) fprintf(stderr
, "processIndirectLibraries() umbrella=%s will re-export child=%s\n", this->installPath(), it
->path
);
802 // check for re-export cycles
806 this->assertNoReExportCycles(&chain
);
809 template <typename A
>
810 void File
<A
>::assertNoReExportCycles(ReExportChain
* prev
)
812 // recursively check my re-exported dylibs
816 for (typename
std::vector
<Dependent
>::iterator it
= _dependentDylibs
.begin(); it
!= _dependentDylibs
.end(); it
++) {
817 if ( it
->reExport
) {
818 ld::File
* child
= it
->dylib
;
819 // check child is not already in chain
820 for (ReExportChain
* p
= prev
; p
!= NULL
; p
= p
->prev
) {
821 if ( p
->file
== child
) {
822 throwf("cycle in dylib re-exports with %s and %s", child
->path(), this->path());
825 if ( it
->dylib
!= NULL
)
826 it
->dylib
->assertNoReExportCycles(&chain
);
832 template <typename A
>
836 typedef typename
A::P P
;
838 static bool validFile(const uint8_t* fileContent
, bool executableOrDyliborBundle
);
839 static ld::dylib::File
* parse(const uint8_t* fileContent
, uint64_t fileLength
,
840 const char* path
, time_t mTime
,
841 uint32_t ordinal
, const Options
& opts
, bool indirectDylib
) {
842 return new File
<A
>(fileContent
, fileLength
, path
, mTime
,
843 ordinal
, opts
.flatNamespace(),
844 opts
.linkingMainExecutable(),
845 opts
.implicitlyLinkIndirectPublicDylibs(),
846 opts
.macosxVersionMin(),
847 opts
.iOSVersionMin(),
848 opts
.addVersionLoadCommand(),
859 bool Parser
<x86
>::validFile(const uint8_t* fileContent
, bool executableOrDyliborBundle
)
861 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
862 if ( header
->magic() != MH_MAGIC
)
864 if ( header
->cputype() != CPU_TYPE_I386
)
866 switch ( header
->filetype() ) {
871 if ( executableOrDyliborBundle
)
874 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
876 if ( executableOrDyliborBundle
)
879 throw "can't link with a main executable";
886 bool Parser
<x86_64
>::validFile(const uint8_t* fileContent
, bool executableOrDyliborBundle
)
888 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
889 if ( header
->magic() != MH_MAGIC_64
)
891 if ( header
->cputype() != CPU_TYPE_X86_64
)
893 switch ( header
->filetype() ) {
898 if ( executableOrDyliborBundle
)
901 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
903 if ( executableOrDyliborBundle
)
906 throw "can't link with a main executable";
913 bool Parser
<arm
>::validFile(const uint8_t* fileContent
, bool executableOrDyliborBundle
)
915 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
916 if ( header
->magic() != MH_MAGIC
)
918 if ( header
->cputype() != CPU_TYPE_ARM
)
920 switch ( header
->filetype() ) {
925 if ( executableOrDyliborBundle
)
928 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
930 if ( executableOrDyliborBundle
)
933 throw "can't link with a main executable";
942 // main function used by linker to instantiate ld::Files
944 ld::dylib::File
* parse(const uint8_t* fileContent
, uint64_t fileLength
,
945 const char* path
, time_t modTime
, const Options
& opts
, uint32_t ordinal
,
946 bool bundleLoader
, bool indirectDylib
)
948 switch ( opts
.architecture() ) {
949 case CPU_TYPE_X86_64
:
950 if ( Parser
<x86_64
>::validFile(fileContent
, bundleLoader
) )
951 return Parser
<x86_64
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
, indirectDylib
);
954 if ( Parser
<x86
>::validFile(fileContent
, bundleLoader
) )
955 return Parser
<x86
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
, indirectDylib
);
958 if ( Parser
<arm
>::validFile(fileContent
, bundleLoader
) )
959 return Parser
<arm
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
, indirectDylib
);
966 }; // namespace dylib
967 }; // namespace mach_o