]> git.saurik.com Git - apple/ld64.git/blob - src/ld/parsers/macho_dylib_file.cpp
ld64-274.1.tar.gz
[apple/ld64.git] / src / ld / parsers / macho_dylib_file.cpp
1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
2 *
3 * Copyright (c) 2005-2011 Apple Inc. All rights reserved.
4 *
5 * @APPLE_LICENSE_HEADER_START@
6 *
7 * This file contains Original Code and/or Modifications of Original Code
8 * as defined in and that are subject to the Apple Public Source License
9 * Version 2.0 (the 'License'). You may not use this file except in
10 * compliance with the License. Please obtain a copy of the License at
11 * http://www.opensource.apple.com/apsl/ and read it before using this
12 * file.
13 *
14 * The Original Code and all software distributed under the License are
15 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
19 * Please see the License for the specific language governing rights and
20 * limitations under the License.
21 *
22 * @APPLE_LICENSE_HEADER_END@
23 */
24
25
26 #include <stdint.h>
27 #include <math.h>
28 #include <unistd.h>
29 #include <sys/param.h>
30 #include <sys/mman.h>
31
32
33 #include <vector>
34 #include <set>
35 #include <map>
36 #include <algorithm>
37
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"
45
46 namespace mach_o {
47 namespace dylib {
48
49 //
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.
53 //
54 template <typename A>
55 class File final : public generic::dylib::File<A>
56 {
57 using Base = generic::dylib::File<A>;
58
59 public:
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 {}
69
70 private:
71 using P = typename A::P;
72 using E = typename A::P::E;
73 using pint_t = typename A::P::uint_t;
74
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();
84
85
86 uint64_t _fileLength;
87 uint32_t _linkeditStartOffset;
88
89 };
90
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"; }
94
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"; }
98
99 template <typename A>
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)
107 {
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());
112
113 // write out path for -t option
114 if ( logAllFiles )
115 printf("%s\n", path);
116
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);
121 return;
122 }
123
124
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);
132
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()) {
147 case LC_SYMTAB:
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);
153 break;
154 case LC_DYSYMTAB:
155 dynamicInfo = (macho_dysymtab_command<P>*)cmd;
156 break;
157 case LC_DYLD_INFO:
158 case LC_DYLD_INFO_ONLY:
159 dyldInfo = (macho_dyld_info_command<P>*)cmd;
160 compressedLinkEdit = true;
161 break;
162 case LC_ID_DYLIB:
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);
173 break;
174 case LC_LOAD_DYLIB:
175 case LC_LOAD_WEAK_DYLIB:
176 ++dependentLibCount;
177 break;
178 case LC_REEXPORT_DYLIB:
179 this->_explictReExportFound = true;
180 ++dependentLibCount;
181 break;
182 case LC_SUB_FRAMEWORK:
183 this->_parentUmbrella = strdup(((macho_sub_framework_command<P>*)cmd)->umbrella());
184 break;
185 case LC_SUB_CLIENT:
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;
189 break;
190 case LC_RPATH:
191 this->_rpaths.push_back(strdup(((macho_rpath_command<P>*)cmd)->path()));
192 break;
193 case LC_VERSION_MIN_MACOSX:
194 case LC_VERSION_MIN_IPHONEOS:
195 case LC_VERSION_MIN_WATCHOS:
196 #if SUPPORT_APPLE_TV
197 case LC_VERSION_MIN_TVOS:
198 #endif
199 this->_minVersionInDylib = (ld::MacVersionMin)((macho_version_min_command<P>*)cmd)->version();
200 this->_platformInDylib = cmd->cmd();
201 lcPlatform = Options::platformForLoadCommand(this->_platformInDylib);
202 break;
203 case LC_CODE_SIGNATURE:
204 break;
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 = &sectionsStart[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
215 // uint32_t flags;
216 // };
217 // #define OBJC_IMAGE_SUPPORTS_GC 2
218 // #define OBJC_IMAGE_GC_ONLY 4
219 // #define OBJC_IMAGE_IS_SIMULATED 32
220 //
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;
230 else
231 this->_objcConstraint = ld::File::objcConstraintRetainRelease;
232 this->_swiftVersion = ((flags >> 8) & 0xFF);
233 }
234 else if ( sect->size() > 0 ) {
235 warning("can't parse %s/%s section in %s", objCInfoSegmentName(), objCInfoSectionName(), path);
236 }
237 }
238 }
239 }
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()));
246 }
247 else if ( strcmp(((macho_segment_command<P>*)cmd)->segname(), "__LINKEDIT") == 0 ) {
248 _linkeditStartOffset = ((macho_segment_command<P>*)cmd)->fileoff();
249 }
250 }
251 cmd = (const macho_load_command<P>*)(((char*)cmd)+cmdLength);
252 if ( cmd > cmdsEnd )
253 throwf("malformed dylb, load command #%d is outside size of load commands in %s", i, path);
254 }
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;
260
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 ) {
267 switch (platform) {
268 case Options::kPlatformOSX:
269 case Options::kPlatformiOS:
270 if ( lcPlatform == Options::kPlatformUnknown )
271 break;
272 // fall through if the Platform is not Unknown
273 case Options::kPlatformWatchOS:
274 // WatchOS errors on cross-linking when building for bitcode
275 if ( usingBitcode )
276 throwf("building for %s simulator, but linking against dylib built for %s,",
277 Options::platformName(platform),
278 Options::platformName(lcPlatform));
279 else
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));
284 break;
285 #if SUPPORT_APPLE_TV
286 case Options::kPlatform_tvOS:
287 // tvOS is a warning temporarily. rdar://problem/21746965
288 if ( usingBitcode )
289 throwf("building for %s simulator, but linking against dylib built for %s,",
290 Options::platformName(platform),
291 Options::platformName(lcPlatform));
292 else
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));
297 break;
298 #endif
299 case Options::kPlatformUnknown:
300 // skip if the target platform is unknown
301 break;
302 }
303 }
304 }
305 else {
306 switch (platform) {
307 case Options::kPlatformOSX:
308 case Options::kPlatformiOS:
309 if ( lcPlatform == Options::kPlatformUnknown )
310 break;
311 // fall through if the Platform is not Unknown
312 case Options::kPlatformWatchOS:
313 // WatchOS errors on cross-linking when building for bitcode
314 if ( usingBitcode )
315 throwf("building for %s, but linking against dylib built for %s,",
316 Options::platformName(platform),
317 Options::platformName(lcPlatform));
318 else
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));
323 break;
324 #if SUPPORT_APPLE_TV
325 case Options::kPlatform_tvOS:
326 // tvOS is a warning temporarily. rdar://problem/21746965
327 if ( usingBitcode )
328 throwf("building for %s, but linking against dylib built for %s,",
329 Options::platformName(platform),
330 Options::platformName(lcPlatform));
331 else
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));
336 break;
337 #endif
338 case Options::kPlatformUnknown:
339 // skip if the target platform is unknown
340 break;
341 }
342 }
343 }
344 }
345
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;
351
352 if ( processDependentLibraries ) {
353 // pass 2 builds list of all dependent libraries
354 this->_dependentDylibs.reserve(dependentLibCount);
355 cmd = cmds;
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()) {
361 case LC_LOAD_DYLIB:
362 case LC_LOAD_WEAK_DYLIB:
363 // with new linkedit format only care about LC_REEXPORT_DYLIB
364 if ( compressedLinkEdit && !linkingFlatNamespace )
365 break;
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);
376 break;
377 }
378 cmd = (const macho_load_command<P>*)(((char*)cmd)+cmdLength);
379 }
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);
384 }
385 // pass 3 add re-export info
386 cmd = cmds;
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) )
397 dep.reExport = true;
398 }
399 break;
400 case LC_SUB_LIBRARY:
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 )
413 dep.reExport = true;
414 }
415 break;
416 }
417 cmd = (const macho_load_command<P>*)(((char*)cmd)+cmd->cmdsize());
418 }
419 }
420
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/");
429
430 if ( strstr(this->_dylibInstallPath, frname) != NULL )
431 this->_frameworkName = leafName;
432 }
433 }
434
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";
443 }
444
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");
450 }
451
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()]);
460 }
461 this->_importAtom = new generic::dylib::ImportAtom<A>(*this, importNames);
462 }
463
464 // build hash table
465 if ( dyldInfo != nullptr )
466 buildExportHashTableFromExportInfo(dyldInfo, fileContent);
467 else
468 buildExportHashTableFromSymbolTable(dynamicInfo, symbolTable, strings, fileContent);
469
470 // unmap file
471 munmap((caddr_t)fileContent, fileLength);
472 }
473
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)
478 {
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());
487 }
488 }
489 else {
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());
499 }
500 }
501
502 // special case old libSystem
503 if ( (this->_dylibInstallPath != nullptr) && (strcmp(this->_dylibInstallPath, "/usr/lib/libSystem.B.dylib") == 0) )
504 addDyldFastStub();
505 }
506
507
508 template <typename A>
509 void File<A>::buildExportHashTableFromExportInfo(const macho_dyld_info_command<P>* dyldInfo,
510 const uint8_t* fileContent)
511 {
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,
525 entry.address);
526 }
527 }
528
529 template <typename A>
530 void File<A>::addSymbol(const char* name, bool weakDef, bool tlv, pint_t address)
531 {
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 ) {
539 char curOSVers[16];
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 ) {
544 ++symName;
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));
549 return;
550 }
551 else if ( strncmp(symAction, "add$", 4) == 0 ) {
552 this->addSymbol(symName, weakDef);
553 return;
554 }
555 else if ( strncmp(symAction, "weak$", 5) == 0 ) {
556 if ( !this->_allowWeakImports )
557 this->_ignoreExports.insert(strdup(symName));
558 }
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");
565 return;
566 }
567 else if ( strncmp(symAction, "compatibility_version$", 22) == 0 ) {
568 this->_dylibCompatibilityVersion = Options::parseVersionNumber32(symName);
569 return;
570 }
571 else {
572 warning("bad symbol action: %s in dylib %s", name, this->path());
573 }
574 }
575 }
576 }
577 else {
578 warning("bad symbol condition: %s in dylib %s", name, this->path());
579 }
580 }
581
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;
588 }
589 }
590
591 template <>
592 void File<x86_64>::addDyldFastStub()
593 {
594 addSymbol("dyld_stub_binder");
595 }
596
597 template <>
598 void File<x86>::addDyldFastStub()
599 {
600 addSymbol("dyld_stub_binder");
601 }
602
603 template <typename A>
604 void File<A>::addDyldFastStub()
605 {
606 // do nothing
607 }
608
609 template <typename A>
610 class Parser
611 {
612 public:
613 using P = typename A::P;
614
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,
619 bool indirectDylib)
620 {
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());
627 }
628
629 };
630
631
632
633 template <>
634 bool Parser<x86>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle, bool subTypeMustMatch, uint32_t subType)
635 {
636 const auto* header = reinterpret_cast<const macho_header<P>*>(fileContent);
637 if ( header->magic() != MH_MAGIC )
638 return false;
639 if ( header->cputype() != CPU_TYPE_I386 )
640 return false;
641 switch ( header->filetype() ) {
642 case MH_DYLIB:
643 case MH_DYLIB_STUB:
644 return true;
645 case MH_BUNDLE:
646 if ( executableOrDyliborBundle )
647 return true;
648 else
649 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
650 case MH_EXECUTE:
651 if ( executableOrDyliborBundle )
652 return true;
653 else
654 throw "can't link with a main executable";
655 default:
656 return false;
657 }
658 }
659
660 template <>
661 bool Parser<x86_64>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle, bool subTypeMustMatch, uint32_t subType)
662 {
663 const auto* header = reinterpret_cast<const macho_header<P>*>(fileContent);
664 if ( header->magic() != MH_MAGIC_64 )
665 return false;
666 if ( header->cputype() != CPU_TYPE_X86_64 )
667 return false;
668 switch ( header->filetype() ) {
669 case MH_DYLIB:
670 case MH_DYLIB_STUB:
671 return true;
672 case MH_BUNDLE:
673 if ( executableOrDyliborBundle )
674 return true;
675 else
676 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
677 case MH_EXECUTE:
678 if ( executableOrDyliborBundle )
679 return true;
680 else
681 throw "can't link with a main executable";
682 default:
683 return false;
684 }
685 }
686
687 template <>
688 bool Parser<arm>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle, bool subTypeMustMatch, uint32_t subType)
689 {
690 const auto* header = reinterpret_cast<const macho_header<P>*>(fileContent);
691 if ( header->magic() != MH_MAGIC )
692 return false;
693 if ( header->cputype() != CPU_TYPE_ARM )
694 return false;
695 if ( subTypeMustMatch && (header->cpusubtype() != subType) )
696 return false;
697 switch ( header->filetype() ) {
698 case MH_DYLIB:
699 case MH_DYLIB_STUB:
700 return true;
701 case MH_BUNDLE:
702 if ( executableOrDyliborBundle )
703 return true;
704 else
705 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
706 case MH_EXECUTE:
707 if ( executableOrDyliborBundle )
708 return true;
709 else
710 throw "can't link with a main executable";
711 default:
712 return false;
713 }
714 }
715
716
717
718 template <>
719 bool Parser<arm64>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle, bool subTypeMustMatch, uint32_t subType)
720 {
721 const auto* header = reinterpret_cast<const macho_header<P>*>(fileContent);
722 if ( header->magic() != MH_MAGIC_64 )
723 return false;
724 if ( header->cputype() != CPU_TYPE_ARM64 )
725 return false;
726 switch ( header->filetype() ) {
727 case MH_DYLIB:
728 case MH_DYLIB_STUB:
729 return true;
730 case MH_BUNDLE:
731 if ( executableOrDyliborBundle )
732 return true;
733 else
734 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
735 case MH_EXECUTE:
736 if ( executableOrDyliborBundle )
737 return true;
738 else
739 throw "can't link with a main executable";
740 default:
741 return false;
742 }
743 }
744
745
746 bool isDylibFile(const uint8_t* fileContent, cpu_type_t* result, cpu_subtype_t* subResult)
747 {
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();
752 return true;
753 }
754 if ( Parser<x86>::validFile(fileContent, false) ) {
755 *result = CPU_TYPE_I386;
756 *subResult = CPU_SUBTYPE_X86_ALL;
757 return true;
758 }
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();
763 return true;
764 }
765 if ( Parser<arm64>::validFile(fileContent, false) ) {
766 *result = CPU_TYPE_ARM64;
767 *subResult = CPU_SUBTYPE_ARM64_ALL;
768 return true;
769 }
770 return false;
771 }
772
773 template <>
774 const char* Parser<x86>::fileKind(const uint8_t* fileContent)
775 {
776 const auto* header = reinterpret_cast<const macho_header<P>*>(fileContent);
777 if ( header->magic() != MH_MAGIC )
778 return nullptr;
779 if ( header->cputype() != CPU_TYPE_I386 )
780 return nullptr;
781 return "i386";
782 }
783
784 template <>
785 const char* Parser<x86_64>::fileKind(const uint8_t* fileContent)
786 {
787 const auto* header = reinterpret_cast<const macho_header<P>*>(fileContent);
788 if ( header->magic() != MH_MAGIC_64 )
789 return nullptr;
790 if ( header->cputype() != CPU_TYPE_X86_64 )
791 return nullptr;
792 return "x86_64";
793 }
794
795 template <>
796 const char* Parser<arm>::fileKind(const uint8_t* fileContent)
797 {
798 const auto* header = reinterpret_cast<const macho_header<P>*>(fileContent);
799 if ( header->magic() != MH_MAGIC )
800 return nullptr;
801 if ( header->cputype() != CPU_TYPE_ARM )
802 return nullptr;
803 for (const auto* t = archInfoArray; t->archName != nullptr; ++t) {
804 if ( (t->cpuType == CPU_TYPE_ARM) && ((cpu_subtype_t)header->cpusubtype() == t->cpuSubType) ) {
805 return t->archName;
806 }
807 }
808 return "arm???";
809 }
810
811 #if SUPPORT_ARCH_arm64
812 template <>
813 const char* Parser<arm64>::fileKind(const uint8_t* fileContent)
814 {
815 const auto* header = reinterpret_cast<const macho_header<P>*>(fileContent);
816 if ( header->magic() != MH_MAGIC_64 )
817 return nullptr;
818 if ( header->cputype() != CPU_TYPE_ARM64 )
819 return nullptr;
820 return "arm64";
821 }
822 #endif
823
824
825 //
826 // used by linker is error messages to describe mismatched files
827 //
828 const char* archName(const uint8_t* fileContent)
829 {
830 if ( Parser<x86_64>::validFile(fileContent, true) ) {
831 return Parser<x86_64>::fileKind(fileContent);
832 }
833 if ( Parser<x86>::validFile(fileContent, true) ) {
834 return Parser<x86>::fileKind(fileContent);
835 }
836 if ( Parser<arm>::validFile(fileContent, true) ) {
837 return Parser<arm>::fileKind(fileContent);
838 }
839 #if SUPPORT_ARCH_arm64
840 if ( Parser<arm64>::validFile(fileContent, false) ) {
841 return Parser<arm64>::fileKind(fileContent);
842 }
843 #endif
844 return nullptr;
845 }
846
847
848 //
849 // main function used by linker to instantiate ld::Files
850 //
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)
854 {
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);
861 break;
862 #endif
863 #if SUPPORT_ARCH_i386
864 case CPU_TYPE_I386:
865 if ( Parser<x86>::validFile(fileContent, bundleLoader, subTypeMustMatch, opts.subArchitecture()) )
866 return Parser<x86>::parse(fileContent, fileLength, path, modTime, ordinal, opts, indirectDylib);
867 break;
868 #endif
869 #if SUPPORT_ARCH_arm_any
870 case CPU_TYPE_ARM:
871 if ( Parser<arm>::validFile(fileContent, bundleLoader, subTypeMustMatch, opts.subArchitecture()) )
872 return Parser<arm>::parse(fileContent, fileLength, path, modTime, ordinal, opts, indirectDylib);
873 break;
874 #endif
875 #if SUPPORT_ARCH_arm64
876 case CPU_TYPE_ARM64:
877 if ( Parser<arm64>::validFile(fileContent, bundleLoader, subTypeMustMatch, opts.subArchitecture()) )
878 return Parser<arm64>::parse(fileContent, fileLength, path, modTime, ordinal, opts, indirectDylib);
879 break;
880 #endif
881 }
882 return nullptr;
883 }
884
885
886 }; // namespace dylib
887 }; // namespace mach_o