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>
38 #include "Architectures.hpp"
39 #include "Bitcode.hpp"
40 #include "MachOFileAbstraction.hpp"
41 #include "MachOTrie.hpp"
42 #include "generic_dylib_file.hpp"
43 #include "macho_dylib_file.h"
44 #include "../code-sign-blobs/superblob.h"
50 // The reader for a dylib extracts all exported symbols names from the memory-mapped
51 // dylib, builds a hash table, then unmaps the file. This is an important memory
52 // savings for large dylibs.
55 class File final
: public generic::dylib::File
<A
>
57 using Base
= generic::dylib::File
<A
>;
60 static bool validFile(const uint8_t* fileContent
, bool executableOrDylib
, bool subTypeMustMatch
=false);
61 File(const uint8_t* fileContent
, uint64_t fileLength
, const char* path
,
62 time_t mTime
, ld::File::Ordinal ordinal
, bool linkingFlatNamespace
,
63 bool linkingMainExecutable
, bool hoistImplicitPublicDylibs
,
64 Options::Platform platform
, uint32_t linkMinOSVersion
, bool allowWeakImports
,
65 bool allowSimToMacOSX
, bool addVers
, bool buildingForSimulator
,
66 bool logAllFiles
, const char* installPath
,
67 bool indirectDylib
, bool ignoreMismatchPlatform
, bool usingBitcode
);
68 virtual ~File() noexcept {}
71 using P
= typename
A::P
;
72 using E
= typename
A::P::E
;
73 using pint_t
= typename
A::P::uint_t
;
75 void addDyldFastStub();
76 void buildExportHashTableFromExportInfo(const macho_dyld_info_command
<P
>* dyldInfo
,
77 const uint8_t* fileContent
);
78 void buildExportHashTableFromSymbolTable(const macho_dysymtab_command
<P
>* dynamicInfo
,
79 const macho_nlist
<P
>* symbolTable
, const char* strings
,
80 const uint8_t* fileContent
);
81 void addSymbol(const char* name
, bool weakDef
= false, bool tlv
= false, pint_t address
= 0);
82 static const char* objCInfoSegmentName();
83 static const char* objCInfoSectionName();
87 uint32_t _linkeditStartOffset
;
91 template <> const char* File
<x86_64
>::objCInfoSegmentName() { return "__DATA"; }
92 template <> const char* File
<arm
>::objCInfoSegmentName() { return "__DATA"; }
93 template <typename A
> const char* File
<A
>::objCInfoSegmentName() { return "__OBJC"; }
95 template <> const char* File
<x86_64
>::objCInfoSectionName() { return "__objc_imageinfo"; }
96 template <> const char* File
<arm
>::objCInfoSectionName() { return "__objc_imageinfo"; }
97 template <typename A
> const char* File
<A
>::objCInfoSectionName() { return "__image_info"; }
100 File
<A
>::File(const uint8_t* fileContent
, uint64_t fileLength
, const char* path
, time_t mTime
,
101 ld::File::Ordinal ord
, bool linkingFlatNamespace
, bool linkingMainExecutable
,
102 bool hoistImplicitPublicDylibs
, Options::Platform platform
, uint32_t linkMinOSVersion
, bool allowWeakImports
,
103 bool allowSimToMacOSX
, bool addVers
, bool buildingForSimulator
, bool logAllFiles
,
104 const char* targetInstallPath
, bool indirectDylib
, bool ignoreMismatchPlatform
, bool usingBitcode
)
105 : Base(strdup(path
), mTime
, ord
, platform
, linkMinOSVersion
, allowWeakImports
, linkingFlatNamespace
,
106 hoistImplicitPublicDylibs
, allowSimToMacOSX
, addVers
), _fileLength(fileLength
), _linkeditStartOffset(0)
108 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
109 const uint32_t cmd_count
= header
->ncmds();
110 const macho_load_command
<P
>* const cmds
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>));
111 const macho_load_command
<P
>* const cmdsEnd
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>) + header
->sizeofcmds());
113 // write out path for -t option
115 printf("%s\n", path
);
117 // a "blank" stub has zero load commands
118 if ( (header
->filetype() == MH_DYLIB_STUB
) && (cmd_count
== 0) ) {
119 // no further processing needed
120 munmap((caddr_t
)fileContent
, fileLength
);
125 // optimize the case where we know there is no reason to look at indirect dylibs
126 this->_noRexports
= (header
->flags() & MH_NO_REEXPORTED_DYLIBS
)
127 || (header
->filetype() == MH_BUNDLE
)
128 || (header
->filetype() == MH_EXECUTE
); // bundles and exectuables can be used via -bundle_loader
129 this->_hasWeakExports
= (header
->flags() & MH_WEAK_DEFINES
);
130 this->_deadStrippable
= (header
->flags() & MH_DEAD_STRIPPABLE_DYLIB
);
131 this->_appExtensionSafe
= (header
->flags() & MH_APP_EXTENSION_SAFE
);
133 // pass 1: get pointers, and see if this dylib uses compressed LINKEDIT format
134 const macho_dysymtab_command
<P
>* dynamicInfo
= nullptr;
135 const macho_dyld_info_command
<P
>* dyldInfo
= nullptr;
136 const macho_nlist
<P
>* symbolTable
= nullptr;
137 const macho_symtab_command
<P
>* symtab
= nullptr;
138 const char* strings
= nullptr;
139 bool compressedLinkEdit
= false;
140 uint32_t dependentLibCount
= 0;
141 Options::Platform lcPlatform
= Options::kPlatformUnknown
;
142 const macho_load_command
<P
>* cmd
= cmds
;
143 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
144 macho_dylib_command
<P
>* dylibID
;
145 uint32_t cmdLength
= cmd
->cmdsize();
146 switch (cmd
->cmd()) {
148 symtab
= (macho_symtab_command
<P
>*)cmd
;
149 symbolTable
= (const macho_nlist
<P
>*)((char*)header
+ symtab
->symoff());
150 strings
= (char*)header
+ symtab
->stroff();
151 if ( (symtab
->stroff() + symtab
->strsize()) > fileLength
)
152 throwf("mach-o string pool extends beyond end of file in %s", path
);
155 dynamicInfo
= (macho_dysymtab_command
<P
>*)cmd
;
158 case LC_DYLD_INFO_ONLY
:
159 dyldInfo
= (macho_dyld_info_command
<P
>*)cmd
;
160 compressedLinkEdit
= true;
163 dylibID
= (macho_dylib_command
<P
>*)cmd
;
164 if ( dylibID
->name_offset() > cmdLength
)
165 throwf("malformed mach-o: LC_ID_DYLIB load command has offset (%u) outside its size (%u)", dylibID
->name_offset(), cmdLength
);
166 if ( (dylibID
->name_offset() + strlen(dylibID
->name()) + 1) > cmdLength
)
167 throwf("malformed mach-o: LC_ID_DYLIB load command string extends beyond end of load command");
168 this->_dylibInstallPath
= strdup(dylibID
->name());
169 this->_dylibTimeStamp
= dylibID
->timestamp();
170 this->_dylibCurrentVersion
= dylibID
->current_version();
171 this->_dylibCompatibilityVersion
= dylibID
->compatibility_version();
172 this->_hasPublicInstallName
= this->isPublicLocation(this->_dylibInstallPath
);
175 case LC_LOAD_WEAK_DYLIB
:
178 case LC_REEXPORT_DYLIB
:
179 this->_explictReExportFound
= true;
182 case LC_SUB_FRAMEWORK
:
183 this->_parentUmbrella
= strdup(((macho_sub_framework_command
<P
>*)cmd
)->umbrella());
186 this->_allowableClients
.push_back(strdup(((macho_sub_client_command
<P
>*)cmd
)->client()));
187 // <rdar://problem/20627554> Don't hoist "public" (in /usr/lib/) dylibs that should not be directly linked
188 this->_hasPublicInstallName
= false;
191 this->_rpaths
.push_back(strdup(((macho_rpath_command
<P
>*)cmd
)->path()));
193 case LC_VERSION_MIN_MACOSX
:
194 case LC_VERSION_MIN_IPHONEOS
:
195 case LC_VERSION_MIN_WATCHOS
:
197 case LC_VERSION_MIN_TVOS
:
199 this->_minVersionInDylib
= (ld::MacVersionMin
)((macho_version_min_command
<P
>*)cmd
)->version();
200 this->_platformInDylib
= cmd
->cmd();
201 lcPlatform
= Options::platformForLoadCommand(this->_platformInDylib
);
203 case LC_CODE_SIGNATURE
:
205 case macho_segment_command
<P
>::CMD
:
206 // check for Objective-C info
207 if ( strncmp(((macho_segment_command
<P
>*)cmd
)->segname(), objCInfoSegmentName(), 6) == 0 ) {
208 const macho_segment_command
<P
>* segment
= (macho_segment_command
<P
>*)cmd
;
209 const macho_section
<P
>* const sectionsStart
= (macho_section
<P
>*)((char*)segment
+ sizeof(macho_segment_command
<P
>));
210 const macho_section
<P
>* const sectionsEnd
= §ionsStart
[segment
->nsects()];
211 for (const macho_section
<P
>* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
212 if ( strncmp(sect
->sectname(), objCInfoSectionName(), strlen(objCInfoSectionName())) == 0 ) {
213 // struct objc_image_info {
214 // uint32_t version; // initially 0
217 // #define OBJC_IMAGE_SUPPORTS_GC 2
218 // #define OBJC_IMAGE_GC_ONLY 4
219 // #define OBJC_IMAGE_IS_SIMULATED 32
221 const uint32_t* contents
= (uint32_t*)(&fileContent
[sect
->offset()]);
222 if ( (sect
->size() >= 8) && (contents
[0] == 0) ) {
223 uint32_t flags
= E::get32(contents
[1]);
224 if ( (flags
& 4) == 4 )
225 this->_objcConstraint
= ld::File::objcConstraintGC
;
226 else if ( (flags
& 2) == 2 )
227 this->_objcConstraint
= ld::File::objcConstraintRetainReleaseOrGC
;
228 else if ( (flags
& 32) == 32 )
229 this->_objcConstraint
= ld::File::objcConstraintRetainReleaseForSimulator
;
231 this->_objcConstraint
= ld::File::objcConstraintRetainRelease
;
232 this->_swiftVersion
= ((flags
>> 8) & 0xFF);
234 else if ( sect
->size() > 0 ) {
235 warning("can't parse %s/%s section in %s", objCInfoSegmentName(), objCInfoSectionName(), path
);
240 // Construct bitcode if there is a bitcode bundle section in the dylib
241 // Record the size of the section because the content is not checked
242 else if ( strcmp(((macho_segment_command
<P
>*)cmd
)->segname(), "__LLVM") == 0 ) {
243 const macho_section
<P
>* const sect
= (macho_section
<P
>*)((char*)cmd
+ sizeof(macho_segment_command
<P
>));
244 if ( strncmp(sect
->sectname(), "__bundle", 8) == 0 )
245 this->_bitcode
= std::unique_ptr
<ld::Bitcode
>(new ld::Bitcode(NULL
, sect
->size()));
247 else if ( strcmp(((macho_segment_command
<P
>*)cmd
)->segname(), "__LINKEDIT") == 0 ) {
248 _linkeditStartOffset
= ((macho_segment_command
<P
>*)cmd
)->fileoff();
251 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmdLength
);
253 throwf("malformed dylb, load command #%d is outside size of load commands in %s", i
, path
);
255 // arm/arm64 objects are default to ios platform if not set.
256 // rdar://problem/21746314
257 if (lcPlatform
== Options::kPlatformUnknown
&&
258 (std::is_same
<A
, arm
>::value
|| std::is_same
<A
, arm64
>::value
))
259 lcPlatform
= Options::kPlatformiOS
;
261 // check cross-linking
262 if ( lcPlatform
!= platform
) {
263 this->_wrongOS
= true;
264 if ( this->_addVersionLoadCommand
&& !indirectDylib
&& !ignoreMismatchPlatform
) {
265 if ( buildingForSimulator
) {
266 if ( !this->_allowSimToMacOSXLinking
) {
268 case Options::kPlatformOSX
:
269 case Options::kPlatformiOS
:
270 if ( lcPlatform
== Options::kPlatformUnknown
)
272 // fall through if the Platform is not Unknown
273 case Options::kPlatformWatchOS
:
274 // WatchOS errors on cross-linking when building for bitcode
276 throwf("building for %s simulator, but linking against dylib built for %s,",
277 Options::platformName(platform
),
278 Options::platformName(lcPlatform
));
280 warning("URGENT: building for %s simulator, but linking against dylib (%s) built for %s. "
281 "Note: This will be an error in the future.",
282 Options::platformName(platform
), path
,
283 Options::platformName(lcPlatform
));
286 case Options::kPlatform_tvOS
:
287 // tvOS is a warning temporarily. rdar://problem/21746965
289 throwf("building for %s simulator, but linking against dylib built for %s,",
290 Options::platformName(platform
),
291 Options::platformName(lcPlatform
));
293 warning("URGENT: building for %s simulator, but linking against dylib (%s) built for %s. "
294 "Note: This will be an error in the future.",
295 Options::platformName(platform
), path
,
296 Options::platformName(lcPlatform
));
299 case Options::kPlatformUnknown
:
300 // skip if the target platform is unknown
307 case Options::kPlatformOSX
:
308 case Options::kPlatformiOS
:
309 if ( lcPlatform
== Options::kPlatformUnknown
)
311 // fall through if the Platform is not Unknown
312 case Options::kPlatformWatchOS
:
313 // WatchOS errors on cross-linking when building for bitcode
315 throwf("building for %s, but linking against dylib built for %s,",
316 Options::platformName(platform
),
317 Options::platformName(lcPlatform
));
319 warning("URGENT: building for %s, but linking against dylib (%s) built for %s. "
320 "Note: This will be an error in the future.",
321 Options::platformName(platform
), path
,
322 Options::platformName(lcPlatform
));
325 case Options::kPlatform_tvOS
:
326 // tvOS is a warning temporarily. rdar://problem/21746965
328 throwf("building for %s, but linking against dylib built for %s,",
329 Options::platformName(platform
),
330 Options::platformName(lcPlatform
));
332 warning("URGENT: building for %s, but linking against dylib (%s) built for %s. "
333 "Note: This will be an error in the future.",
334 Options::platformName(platform
), path
,
335 Options::platformName(lcPlatform
));
338 case Options::kPlatformUnknown
:
339 // skip if the target platform is unknown
346 // figure out if we need to examine dependent dylibs
347 // with compressed LINKEDIT format, MH_NO_REEXPORTED_DYLIBS can be trusted
348 bool processDependentLibraries
= true;
349 if ( compressedLinkEdit
&& this->_noRexports
&& !linkingFlatNamespace
)
350 processDependentLibraries
= false;
352 if ( processDependentLibraries
) {
353 // pass 2 builds list of all dependent libraries
354 this->_dependentDylibs
.reserve(dependentLibCount
);
356 unsigned int reExportDylibCount
= 0;
357 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
358 uint32_t cmdLength
= cmd
->cmdsize();
359 const macho_dylib_command
<P
>* dylibCmd
= (macho_dylib_command
<P
>*)cmd
;
360 switch (cmd
->cmd()) {
362 case LC_LOAD_WEAK_DYLIB
:
363 // with new linkedit format only care about LC_REEXPORT_DYLIB
364 if ( compressedLinkEdit
&& !linkingFlatNamespace
)
366 case LC_REEXPORT_DYLIB
:
367 ++reExportDylibCount
;
368 if ( dylibCmd
->name_offset() > cmdLength
)
369 throwf("malformed mach-o: LC_*_DYLIB load command has offset (%u) outside its size (%u)", dylibCmd
->name_offset(), cmdLength
);
370 if ( (dylibCmd
->name_offset() + strlen(dylibCmd
->name()) + 1) > cmdLength
)
371 throwf("malformed mach-o: LC_*_DYLIB load command string extends beyond end of load command");
372 const char *path
= strdup(dylibCmd
->name());
373 bool reExport
= (cmd
->cmd() == LC_REEXPORT_DYLIB
);
374 if ( (targetInstallPath
== nullptr) || (strcmp(targetInstallPath
, path
) != 0) )
375 this->_dependentDylibs
.emplace_back(path
, reExport
);
378 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmdLength
);
380 // verify MH_NO_REEXPORTED_DYLIBS bit was correct
381 if ( compressedLinkEdit
&& !linkingFlatNamespace
) {
382 if ( reExportDylibCount
== 0 )
383 throwf("malformed dylib has MH_NO_REEXPORTED_DYLIBS flag but no LC_REEXPORT_DYLIB load commands: %s", path
);
385 // pass 3 add re-export info
387 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
388 const char* frameworkLeafName
;
389 const char* dylibBaseName
;
390 switch (cmd
->cmd()) {
391 case LC_SUB_UMBRELLA
:
392 frameworkLeafName
= ((macho_sub_umbrella_command
<P
>*)cmd
)->sub_umbrella();
393 for (auto &dep
: this->_dependentDylibs
) {
394 const char* dylibName
= dep
.path
;
395 const char* lastSlash
= strrchr(dylibName
, '/');
396 if ( (lastSlash
!= nullptr) && (strcmp(&lastSlash
[1], frameworkLeafName
) == 0) )
401 dylibBaseName
= ((macho_sub_library_command
<P
>*)cmd
)->sub_library();
402 for (auto &dep
: this->_dependentDylibs
) {
403 const char* dylibName
= dep
.path
;
404 const char* lastSlash
= strrchr(dylibName
, '/');
405 const char* leafStart
= &lastSlash
[1];
406 if ( lastSlash
== nullptr )
407 leafStart
= dylibName
;
408 const char* firstDot
= strchr(leafStart
, '.');
409 int len
= strlen(leafStart
);
410 if ( firstDot
!= nullptr )
411 len
= firstDot
- leafStart
;
412 if ( strncmp(leafStart
, dylibBaseName
, len
) == 0 )
417 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
421 // if framework, capture framework name
422 if ( this->_dylibInstallPath
!= NULL
) {
423 const char* lastSlash
= strrchr(this->_dylibInstallPath
, '/');
424 if ( lastSlash
!= NULL
) {
425 const char* leafName
= lastSlash
+1;
426 char frname
[strlen(leafName
)+32];
427 strcpy(frname
, leafName
);
428 strcat(frname
, ".framework/");
430 if ( strstr(this->_dylibInstallPath
, frname
) != NULL
)
431 this->_frameworkName
= leafName
;
435 // validate minimal load commands
436 if ( (this->_dylibInstallPath
== nullptr) && ((header
->filetype() == MH_DYLIB
) || (header
->filetype() == MH_DYLIB_STUB
)) )
437 throwf("dylib %s missing LC_ID_DYLIB load command", path
);
438 if ( dyldInfo
== nullptr ) {
439 if ( symbolTable
== nullptr )
440 throw "binary missing LC_SYMTAB load command";
441 if ( dynamicInfo
== nullptr )
442 throw "binary missing LC_DYSYMTAB load command";
445 if ( symtab
!= nullptr ) {
446 if ( symtab
->symoff() < _linkeditStartOffset
)
447 throwf("malformed mach-o, symbol table not in __LINKEDIT");
448 if ( symtab
->stroff() < _linkeditStartOffset
)
449 throwf("malformed mach-o, symbol table strings not in __LINKEDIT");
452 // if linking flat and this is a flat dylib, create one atom that references all imported symbols
453 if ( linkingFlatNamespace
&& linkingMainExecutable
&& ((header
->flags() & MH_TWOLEVEL
) == 0) ) {
454 std::vector
<const char*> importNames
;
455 importNames
.reserve(dynamicInfo
->nundefsym());
456 const macho_nlist
<P
>* start
= &symbolTable
[dynamicInfo
->iundefsym()];
457 const macho_nlist
<P
>* end
= &start
[dynamicInfo
->nundefsym()];
458 for (const macho_nlist
<P
>* sym
=start
; sym
< end
; ++sym
) {
459 importNames
.push_back(&strings
[sym
->n_strx()]);
461 this->_importAtom
= new generic::dylib::ImportAtom
<A
>(*this, importNames
);
465 if ( dyldInfo
!= nullptr )
466 buildExportHashTableFromExportInfo(dyldInfo
, fileContent
);
468 buildExportHashTableFromSymbolTable(dynamicInfo
, symbolTable
, strings
, fileContent
);
471 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
,
477 const char* strings
, const uint8_t* fileContent
)
479 if ( dynamicInfo
->tocoff() == 0 ) {
480 if ( this->_s_logHashtable
)
481 fprintf(stderr
, "ld: building hashtable of %u toc entries for %s\n", dynamicInfo
->nextdefsym(), this->path());
482 const macho_nlist
<P
>* start
= &symbolTable
[dynamicInfo
->iextdefsym()];
483 const macho_nlist
<P
>* end
= &start
[dynamicInfo
->nextdefsym()];
484 this->_atoms
.reserve(dynamicInfo
->nextdefsym()); // set initial bucket count
485 for (const macho_nlist
<P
>* sym
=start
; sym
< end
; ++sym
) {
486 this->addSymbol(&strings
[sym
->n_strx()], (sym
->n_desc() & N_WEAK_DEF
) != 0, false, sym
->n_value());
490 int32_t count
= dynamicInfo
->ntoc();
491 this->_atoms
.reserve(count
); // set initial bucket count
492 if ( this->_s_logHashtable
)
493 fprintf(stderr
, "ld: building hashtable of %u entries for %s\n", count
, this->path());
494 const auto* toc
= reinterpret_cast<const dylib_table_of_contents
*>(fileContent
+ dynamicInfo
->tocoff());
495 for (int32_t i
= 0; i
< count
; ++i
) {
496 const uint32_t index
= E::get32(toc
[i
].symbol_index
);
497 const macho_nlist
<P
>* sym
= &symbolTable
[index
];
498 this->addSymbol(&strings
[sym
->n_strx()], (sym
->n_desc() & N_WEAK_DEF
) != 0, false, sym
->n_value());
502 // special case old libSystem
503 if ( (this->_dylibInstallPath
!= nullptr) && (strcmp(this->_dylibInstallPath
, "/usr/lib/libSystem.B.dylib") == 0) )
508 template <typename A
>
509 void File
<A
>::buildExportHashTableFromExportInfo(const macho_dyld_info_command
<P
>* dyldInfo
,
510 const uint8_t* fileContent
)
512 if ( this->_s_logHashtable
)
513 fprintf(stderr
, "ld: building hashtable from export info in %s\n", this->path());
514 if ( dyldInfo
->export_size() > 0 ) {
515 const uint8_t* start
= fileContent
+ dyldInfo
->export_off();
516 const uint8_t* end
= &start
[dyldInfo
->export_size()];
517 if ( (dyldInfo
->export_off() + dyldInfo
->export_size()) > _fileLength
)
518 throwf("malformed mach-o dylib, exports trie extends beyond end of file, ");
519 std::vector
<mach_o::trie::Entry
> list
;
520 parseTrie(start
, end
, list
);
521 for (const auto &entry
: list
)
522 this->addSymbol(entry
.name
,
523 entry
.flags
& EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION
,
524 (entry
.flags
& EXPORT_SYMBOL_FLAGS_KIND_MASK
) == EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL
,
529 template <typename A
>
530 void File
<A
>::addSymbol(const char* name
, bool weakDef
, bool tlv
, pint_t address
)
532 // symbols that start with $ld$ are meta-data to the static linker
533 // <rdar://problem/5182537> need way for ld and dyld to see different exported symbols in a dylib
534 if ( strncmp(name
, "$ld$", 4) == 0 ) {
535 // $ld$ <action> $ <condition> $ <symbol-name>
536 const char* symAction
= &name
[4];
537 const char* symCond
= strchr(symAction
, '$');
538 if ( symCond
!= nullptr ) {
540 sprintf(curOSVers
, "$os%d.%d$", (this->_linkMinOSVersion
>> 16), ((this->_linkMinOSVersion
>> 8) & 0xFF));
541 if ( strncmp(symCond
, curOSVers
, strlen(curOSVers
)) == 0 ) {
542 const char* symName
= strchr(&symCond
[1], '$');
543 if ( symName
!= nullptr ) {
545 if ( strncmp(symAction
, "hide$", 5) == 0 ) {
546 if ( this->_s_logHashtable
)
547 fprintf(stderr
, " adding %s to ignore set for %s\n", symName
, this->path());
548 this->_ignoreExports
.insert(strdup(symName
));
551 else if ( strncmp(symAction
, "add$", 4) == 0 ) {
552 this->addSymbol(symName
, weakDef
);
555 else if ( strncmp(symAction
, "weak$", 5) == 0 ) {
556 if ( !this->_allowWeakImports
)
557 this->_ignoreExports
.insert(strdup(symName
));
559 else if ( strncmp(symAction
, "install_name$", 13) == 0 ) {
560 this->_dylibInstallPath
= symName
;
561 this->_installPathOverride
= true;
562 // <rdar://problem/14448206> CoreGraphics redirects to ApplicationServices, but with wrong compat version
563 if ( strcmp(this->_dylibInstallPath
, "/System/Library/Frameworks/ApplicationServices.framework/Versions/A/ApplicationServices") == 0 )
564 this->_dylibCompatibilityVersion
= Options::parseVersionNumber32("1.0");
567 else if ( strncmp(symAction
, "compatibility_version$", 22) == 0 ) {
568 this->_dylibCompatibilityVersion
= Options::parseVersionNumber32(symName
);
572 warning("bad symbol action: %s in dylib %s", name
, this->path());
578 warning("bad symbol condition: %s in dylib %s", name
, this->path());
582 // add symbol as possible export if we are not supposed to ignore it
583 if ( this->_ignoreExports
.count(name
) == 0 ) {
584 typename
Base::AtomAndWeak bucket
= { nullptr, weakDef
, tlv
, address
};
585 if ( this->_s_logHashtable
)
586 fprintf(stderr
, " adding %s to hash table for %s\n", name
, this->path());
587 this->_atoms
[strdup(name
)] = bucket
;
592 void File
<x86_64
>::addDyldFastStub()
594 addSymbol("dyld_stub_binder");
598 void File
<x86
>::addDyldFastStub()
600 addSymbol("dyld_stub_binder");
603 template <typename A
>
604 void File
<A
>::addDyldFastStub()
609 template <typename A
>
613 using P
= typename
A::P
;
615 static bool validFile(const uint8_t* fileContent
, bool executableOrDyliborBundle
, bool subTypeMustMatch
=false, uint32_t subType
=0);
616 static const char* fileKind(const uint8_t* fileContent
);
617 static ld::dylib::File
* parse(const uint8_t* fileContent
, uint64_t fileLength
, const char* path
,
618 time_t mTime
, ld::File::Ordinal ordinal
, const Options
& opts
,
621 return new File
<A
>(fileContent
, fileLength
, path
, mTime
, ordinal
, opts
.flatNamespace(),
622 opts
.linkingMainExecutable(), opts
.implicitlyLinkIndirectPublicDylibs(),
623 opts
.platform(), opts
.minOSversion(), opts
.allowWeakImports(),
624 opts
.allowSimulatorToLinkWithMacOSX(), opts
.addVersionLoadCommand(),
625 opts
.targetIOSSimulator(), opts
.logAllFiles(), opts
.installPath(),
626 indirectDylib
, opts
.outputKind() == Options::kPreload
, opts
.bundleBitcode());
634 bool Parser
<x86
>::validFile(const uint8_t* fileContent
, bool executableOrDyliborBundle
, bool subTypeMustMatch
, uint32_t subType
)
636 const auto* header
= reinterpret_cast<const macho_header
<P
>*>(fileContent
);
637 if ( header
->magic() != MH_MAGIC
)
639 if ( header
->cputype() != CPU_TYPE_I386
)
641 switch ( header
->filetype() ) {
646 if ( executableOrDyliborBundle
)
649 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
651 if ( executableOrDyliborBundle
)
654 throw "can't link with a main executable";
661 bool Parser
<x86_64
>::validFile(const uint8_t* fileContent
, bool executableOrDyliborBundle
, bool subTypeMustMatch
, uint32_t subType
)
663 const auto* header
= reinterpret_cast<const macho_header
<P
>*>(fileContent
);
664 if ( header
->magic() != MH_MAGIC_64
)
666 if ( header
->cputype() != CPU_TYPE_X86_64
)
668 switch ( header
->filetype() ) {
673 if ( executableOrDyliborBundle
)
676 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
678 if ( executableOrDyliborBundle
)
681 throw "can't link with a main executable";
688 bool Parser
<arm
>::validFile(const uint8_t* fileContent
, bool executableOrDyliborBundle
, bool subTypeMustMatch
, uint32_t subType
)
690 const auto* header
= reinterpret_cast<const macho_header
<P
>*>(fileContent
);
691 if ( header
->magic() != MH_MAGIC
)
693 if ( header
->cputype() != CPU_TYPE_ARM
)
695 if ( subTypeMustMatch
&& (header
->cpusubtype() != subType
) )
697 switch ( header
->filetype() ) {
702 if ( executableOrDyliborBundle
)
705 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
707 if ( executableOrDyliborBundle
)
710 throw "can't link with a main executable";
719 bool Parser
<arm64
>::validFile(const uint8_t* fileContent
, bool executableOrDyliborBundle
, bool subTypeMustMatch
, uint32_t subType
)
721 const auto* header
= reinterpret_cast<const macho_header
<P
>*>(fileContent
);
722 if ( header
->magic() != MH_MAGIC_64
)
724 if ( header
->cputype() != CPU_TYPE_ARM64
)
726 switch ( header
->filetype() ) {
731 if ( executableOrDyliborBundle
)
734 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
736 if ( executableOrDyliborBundle
)
739 throw "can't link with a main executable";
746 bool isDylibFile(const uint8_t* fileContent
, cpu_type_t
* result
, cpu_subtype_t
* subResult
)
748 if ( Parser
<x86_64
>::validFile(fileContent
, false) ) {
749 *result
= CPU_TYPE_X86_64
;
750 const auto* header
= reinterpret_cast<const macho_header
<Pointer64
<LittleEndian
>>*>(fileContent
);
751 *subResult
= header
->cpusubtype();
754 if ( Parser
<x86
>::validFile(fileContent
, false) ) {
755 *result
= CPU_TYPE_I386
;
756 *subResult
= CPU_SUBTYPE_X86_ALL
;
759 if ( Parser
<arm
>::validFile(fileContent
, false) ) {
760 *result
= CPU_TYPE_ARM
;
761 const auto* header
= reinterpret_cast<const macho_header
<Pointer32
<LittleEndian
>>*>(fileContent
);
762 *subResult
= header
->cpusubtype();
765 if ( Parser
<arm64
>::validFile(fileContent
, false) ) {
766 *result
= CPU_TYPE_ARM64
;
767 *subResult
= CPU_SUBTYPE_ARM64_ALL
;
774 const char* Parser
<x86
>::fileKind(const uint8_t* fileContent
)
776 const auto* header
= reinterpret_cast<const macho_header
<P
>*>(fileContent
);
777 if ( header
->magic() != MH_MAGIC
)
779 if ( header
->cputype() != CPU_TYPE_I386
)
785 const char* Parser
<x86_64
>::fileKind(const uint8_t* fileContent
)
787 const auto* header
= reinterpret_cast<const macho_header
<P
>*>(fileContent
);
788 if ( header
->magic() != MH_MAGIC_64
)
790 if ( header
->cputype() != CPU_TYPE_X86_64
)
796 const char* Parser
<arm
>::fileKind(const uint8_t* fileContent
)
798 const auto* header
= reinterpret_cast<const macho_header
<P
>*>(fileContent
);
799 if ( header
->magic() != MH_MAGIC
)
801 if ( header
->cputype() != CPU_TYPE_ARM
)
803 for (const auto* t
= archInfoArray
; t
->archName
!= nullptr; ++t
) {
804 if ( (t
->cpuType
== CPU_TYPE_ARM
) && ((cpu_subtype_t
)header
->cpusubtype() == t
->cpuSubType
) ) {
811 #if SUPPORT_ARCH_arm64
813 const char* Parser
<arm64
>::fileKind(const uint8_t* fileContent
)
815 const auto* header
= reinterpret_cast<const macho_header
<P
>*>(fileContent
);
816 if ( header
->magic() != MH_MAGIC_64
)
818 if ( header
->cputype() != CPU_TYPE_ARM64
)
826 // used by linker is error messages to describe mismatched files
828 const char* archName(const uint8_t* fileContent
)
830 if ( Parser
<x86_64
>::validFile(fileContent
, true) ) {
831 return Parser
<x86_64
>::fileKind(fileContent
);
833 if ( Parser
<x86
>::validFile(fileContent
, true) ) {
834 return Parser
<x86
>::fileKind(fileContent
);
836 if ( Parser
<arm
>::validFile(fileContent
, true) ) {
837 return Parser
<arm
>::fileKind(fileContent
);
839 #if SUPPORT_ARCH_arm64
840 if ( Parser
<arm64
>::validFile(fileContent
, false) ) {
841 return Parser
<arm64
>::fileKind(fileContent
);
849 // main function used by linker to instantiate ld::Files
851 ld::dylib::File
* parse(const uint8_t* fileContent
, uint64_t fileLength
, const char* path
,
852 time_t modTime
, const Options
& opts
, ld::File::Ordinal ordinal
,
853 bool bundleLoader
, bool indirectDylib
)
855 bool subTypeMustMatch
= opts
.enforceDylibSubtypesMatch();
856 switch ( opts
.architecture() ) {
857 #if SUPPORT_ARCH_x86_64
858 case CPU_TYPE_X86_64
:
859 if ( Parser
<x86_64
>::validFile(fileContent
, bundleLoader
, subTypeMustMatch
, opts
.subArchitecture()) )
860 return Parser
<x86_64
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
, indirectDylib
);
863 #if SUPPORT_ARCH_i386
865 if ( Parser
<x86
>::validFile(fileContent
, bundleLoader
, subTypeMustMatch
, opts
.subArchitecture()) )
866 return Parser
<x86
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
, indirectDylib
);
869 #if SUPPORT_ARCH_arm_any
871 if ( Parser
<arm
>::validFile(fileContent
, bundleLoader
, subTypeMustMatch
, opts
.subArchitecture()) )
872 return Parser
<arm
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
, indirectDylib
);
875 #if SUPPORT_ARCH_arm64
877 if ( Parser
<arm64
>::validFile(fileContent
, bundleLoader
, subTypeMustMatch
, opts
.subArchitecture()) )
878 return Parser
<arm64
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
, indirectDylib
);
886 }; // namespace dylib
887 }; // namespace mach_o