]> git.saurik.com Git - apple/ld64.git/blob - src/ld/Resolver.cpp
ld64-274.1.tar.gz
[apple/ld64.git] / src / ld / Resolver.cpp
1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-*
2 *
3 * Copyright (c) 2009-2010 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 <stdlib.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <sys/mman.h>
30 #include <sys/sysctl.h>
31 #include <fcntl.h>
32 #include <errno.h>
33 #include <limits.h>
34 #include <unistd.h>
35 #include <mach/mach_time.h>
36 #include <mach/vm_statistics.h>
37 #include <mach/mach_init.h>
38 #include <mach/mach_host.h>
39 #include <dlfcn.h>
40 #include <mach-o/dyld.h>
41 #include <mach-o/fat.h>
42
43 #include <string>
44 #include <map>
45 #include <set>
46 #include <string>
47 #include <vector>
48 #include <list>
49 #include <algorithm>
50 #include <dlfcn.h>
51 #include <AvailabilityMacros.h>
52
53 #include "Options.h"
54
55 #include "ld.hpp"
56 #include "Bitcode.hpp"
57 #include "InputFiles.h"
58 #include "SymbolTable.h"
59 #include "Resolver.h"
60 #include "parsers/lto_file.h"
61
62
63 namespace ld {
64 namespace tool {
65
66
67 //
68 // An ExportAtom has no content. It exists so that the linker can track which imported
69 // symbols came from which dynamic libraries.
70 //
71 class UndefinedProxyAtom : public ld::Atom
72 {
73 public:
74 UndefinedProxyAtom(const char* nm)
75 : ld::Atom(_s_section, ld::Atom::definitionProxy,
76 ld::Atom::combineNever, ld::Atom::scopeLinkageUnit,
77 ld::Atom::typeUnclassified,
78 ld::Atom::symbolTableIn, false, false, false, ld::Atom::Alignment(0)),
79 _name(nm) {}
80 // overrides of ld::Atom
81 virtual const ld::File* file() const { return NULL; }
82 virtual const char* name() const { return _name; }
83 virtual uint64_t size() const { return 0; }
84 virtual uint64_t objectAddress() const { return 0; }
85 virtual void copyRawContent(uint8_t buffer[]) const { }
86 virtual void setScope(Scope) { }
87
88 protected:
89
90 virtual ~UndefinedProxyAtom() {}
91
92 const char* _name;
93
94 static ld::Section _s_section;
95 };
96
97 ld::Section UndefinedProxyAtom::_s_section("__TEXT", "__import", ld::Section::typeImportProxies, true);
98
99
100
101
102 class AliasAtom : public ld::Atom
103 {
104 public:
105 AliasAtom(const ld::Atom& target, const char* nm) :
106 ld::Atom(target.section(), target.definition(), ld::Atom::combineNever,
107 ld::Atom::scopeGlobal, target.contentType(),
108 target.symbolTableInclusion(), target.dontDeadStrip(),
109 target.isThumb(), true, target.alignment()),
110 _name(nm),
111 _aliasOf(target),
112 _fixup(0, ld::Fixup::k1of1, ld::Fixup::kindNoneFollowOn, &target) { }
113
114 // overrides of ld::Atom
115 virtual const ld::File* file() const { return _aliasOf.file(); }
116 virtual const char* translationUnitSource() const
117 { return _aliasOf.translationUnitSource(); }
118 virtual const char* name() const { return _name; }
119 virtual uint64_t size() const { return 0; }
120 virtual uint64_t objectAddress() const { return _aliasOf.objectAddress(); }
121 virtual void copyRawContent(uint8_t buffer[]) const { }
122 virtual const uint8_t* rawContentPointer() const { return NULL; }
123 virtual unsigned long contentHash(const class ld::IndirectBindingTable& ibt) const
124 { return _aliasOf.contentHash(ibt); }
125 virtual bool canCoalesceWith(const ld::Atom& rhs, const class ld::IndirectBindingTable& ibt) const
126 { return _aliasOf.canCoalesceWith(rhs,ibt); }
127 virtual ld::Fixup::iterator fixupsBegin() const { return (ld::Fixup*)&_fixup; }
128 virtual ld::Fixup::iterator fixupsEnd() const { return &((ld::Fixup*)&_fixup)[1]; }
129 virtual ld::Atom::UnwindInfo::iterator beginUnwind() const { return NULL; }
130 virtual ld::Atom::UnwindInfo::iterator endUnwind() const { return NULL; }
131 virtual ld::Atom::LineInfo::iterator beginLineInfo() const { return NULL; }
132 virtual ld::Atom::LineInfo::iterator endLineInfo() const { return NULL; }
133
134 void setFinalAliasOf() const {
135 (const_cast<AliasAtom*>(this))->setAttributesFromAtom(_aliasOf);
136 (const_cast<AliasAtom*>(this))->setScope(ld::Atom::scopeGlobal);
137 }
138
139 private:
140 const char* _name;
141 const ld::Atom& _aliasOf;
142 ld::Fixup _fixup;
143 };
144
145
146
147 class SectionBoundaryAtom : public ld::Atom
148 {
149 public:
150 static SectionBoundaryAtom* makeSectionBoundaryAtom(const char* name, bool start, const char* segSectName);
151 static SectionBoundaryAtom* makeOldSectionBoundaryAtom(const char* name, bool start);
152
153 // overrides of ld::Atom
154 virtual const ld::File* file() const { return NULL; }
155 virtual const char* name() const { return _name; }
156 virtual uint64_t size() const { return 0; }
157 virtual void copyRawContent(uint8_t buffer[]) const { }
158 virtual const uint8_t* rawContentPointer() const { return NULL; }
159 virtual uint64_t objectAddress() const { return 0; }
160
161 private:
162
163 SectionBoundaryAtom(const char* nm, const ld::Section& sect,
164 ld::Atom::ContentType cont) :
165 ld::Atom(sect,
166 ld::Atom::definitionRegular,
167 ld::Atom::combineNever,
168 ld::Atom::scopeLinkageUnit,
169 cont,
170 ld::Atom::symbolTableNotIn,
171 false, false, true, ld::Atom::Alignment(0)),
172 _name(nm) { }
173
174 const char* _name;
175 };
176
177 SectionBoundaryAtom* SectionBoundaryAtom::makeSectionBoundaryAtom(const char* name, bool start, const char* segSectName)
178 {
179
180 const char* segSectDividor = strrchr(segSectName, '$');
181 if ( segSectDividor == NULL )
182 throwf("malformed section$ symbol name: %s", name);
183 const char* sectionName = segSectDividor + 1;
184 int segNameLen = segSectDividor - segSectName;
185 if ( segNameLen > 16 )
186 throwf("malformed section$ symbol name: %s", name);
187 char segName[18];
188 strlcpy(segName, segSectName, segNameLen+1);
189
190 const ld::Section* section = new ld::Section(strdup(segName), sectionName, ld::Section::typeUnclassified);
191 return new SectionBoundaryAtom(name, *section, (start ? ld::Atom::typeSectionStart : typeSectionEnd));
192 }
193
194 SectionBoundaryAtom* SectionBoundaryAtom::makeOldSectionBoundaryAtom(const char* name, bool start)
195 {
196 // e.g. __DATA__bss__begin
197 char segName[18];
198 strlcpy(segName, name, 7);
199
200 char sectName[18];
201 int nameLen = strlen(name);
202 strlcpy(sectName, &name[6], (start ? nameLen-12 : nameLen-10));
203 warning("grandfathering in old symbol '%s' as alias for 'section$%s$%s$%s'", name, start ? "start" : "end", segName, sectName);
204 const ld::Section* section = new ld::Section(strdup(segName), strdup(sectName), ld::Section::typeUnclassified);
205 return new SectionBoundaryAtom(name, *section, (start ? ld::Atom::typeSectionStart : typeSectionEnd));
206 }
207
208
209
210
211 class SegmentBoundaryAtom : public ld::Atom
212 {
213 public:
214 static SegmentBoundaryAtom* makeSegmentBoundaryAtom(const char* name, bool start, const char* segName);
215 static SegmentBoundaryAtom* makeOldSegmentBoundaryAtom(const char* name, bool start);
216
217 // overrides of ld::Atom
218 virtual const ld::File* file() const { return NULL; }
219 virtual const char* name() const { return _name; }
220 virtual uint64_t size() const { return 0; }
221 virtual void copyRawContent(uint8_t buffer[]) const { }
222 virtual const uint8_t* rawContentPointer() const { return NULL; }
223 virtual uint64_t objectAddress() const { return 0; }
224
225 private:
226
227 SegmentBoundaryAtom(const char* nm, const ld::Section& sect,
228 ld::Atom::ContentType cont) :
229 ld::Atom(sect,
230 ld::Atom::definitionRegular,
231 ld::Atom::combineNever,
232 ld::Atom::scopeLinkageUnit,
233 cont,
234 ld::Atom::symbolTableNotIn,
235 false, false, true, ld::Atom::Alignment(0)),
236 _name(nm) { }
237
238 const char* _name;
239 };
240
241 SegmentBoundaryAtom* SegmentBoundaryAtom::makeSegmentBoundaryAtom(const char* name, bool start, const char* segName)
242 {
243 if ( *segName == '\0' )
244 throwf("malformed segment$ symbol name: %s", name);
245 if ( strlen(segName) > 16 )
246 throwf("malformed segment$ symbol name: %s", name);
247
248 if ( start ) {
249 const ld::Section* section = new ld::Section(segName, "__start", ld::Section::typeFirstSection, true);
250 return new SegmentBoundaryAtom(name, *section, ld::Atom::typeSectionStart);
251 }
252 else {
253 const ld::Section* section = new ld::Section(segName, "__end", ld::Section::typeLastSection, true);
254 return new SegmentBoundaryAtom(name, *section, ld::Atom::typeSectionEnd);
255 }
256 }
257
258 SegmentBoundaryAtom* SegmentBoundaryAtom::makeOldSegmentBoundaryAtom(const char* name, bool start)
259 {
260 // e.g. __DATA__begin
261 char temp[18];
262 strlcpy(temp, name, 7);
263 char* segName = strdup(temp);
264
265 warning("grandfathering in old symbol '%s' as alias for 'segment$%s$%s'", name, start ? "start" : "end", segName);
266
267 if ( start ) {
268 const ld::Section* section = new ld::Section(segName, "__start", ld::Section::typeFirstSection, true);
269 return new SegmentBoundaryAtom(name, *section, ld::Atom::typeSectionStart);
270 }
271 else {
272 const ld::Section* section = new ld::Section(segName, "__end", ld::Section::typeLastSection, true);
273 return new SegmentBoundaryAtom(name, *section, ld::Atom::typeSectionEnd);
274 }
275 }
276
277 void Resolver::initializeState()
278 {
279 // set initial objc constraint based on command line options
280 if ( _options.objcGc() )
281 _internal.objcObjectConstraint = ld::File::objcConstraintRetainReleaseOrGC;
282 else if ( _options.objcGcOnly() )
283 _internal.objcObjectConstraint = ld::File::objcConstraintGC;
284
285 _internal.cpuSubType = _options.subArchitecture();
286 _internal.minOSVersion = _options.minOSversion();
287 _internal.derivedPlatformLoadCommand = 0;
288
289 // In -r mode, look for -linker_option additions
290 if ( _options.outputKind() == Options::kObjectFile ) {
291 ld::relocatable::File::LinkerOptionsList lo = _options.linkerOptions();
292 for (relocatable::File::LinkerOptionsList::const_iterator it=lo.begin(); it != lo.end(); ++it) {
293 doLinkerOption(*it, "command line");
294 }
295 }
296 }
297
298 void Resolver::buildAtomList()
299 {
300 // each input files contributes initial atoms
301 _atoms.reserve(1024);
302 _inputFiles.forEachInitialAtom(*this, _internal);
303
304 _completedInitialObjectFiles = true;
305
306 //_symbolTable.printStatistics();
307 }
308
309
310 void Resolver::doLinkerOption(const std::vector<const char*>& linkerOption, const char* fileName)
311 {
312 if ( linkerOption.size() == 1 ) {
313 const char* lo1 = linkerOption.front();
314 if ( strncmp(lo1, "-l", 2) == 0) {
315 if (_internal.linkerOptionLibraries.count(&lo1[2]) == 0) {
316 _internal.unprocessedLinkerOptionLibraries.insert(&lo1[2]);
317 }
318 }
319 else {
320 warning("unknown linker option from object file ignored: '%s' in %s", lo1, fileName);
321 }
322 }
323 else if ( linkerOption.size() == 2 ) {
324 const char* lo2a = linkerOption[0];
325 const char* lo2b = linkerOption[1];
326 if ( strcmp(lo2a, "-framework") == 0) {
327 if (_internal.linkerOptionFrameworks.count(lo2b) == 0) {
328 _internal.unprocessedLinkerOptionFrameworks.insert(lo2b);
329 }
330 }
331 else {
332 warning("unknown linker option from object file ignored: '%s' '%s' from %s", lo2a, lo2b, fileName);
333 }
334 }
335 else {
336 warning("unknown linker option from object file ignored, starting with: '%s' from %s", linkerOption.front(), fileName);
337 }
338 }
339
340 static void userReadableSwiftVersion(uint8_t value, char versionString[64])
341 {
342 switch (value) {
343 case 1:
344 strcpy(versionString, "1.0");
345 break;
346 case 2:
347 strcpy(versionString, "1.1");
348 break;
349 case 3:
350 strcpy(versionString, "2.0");
351 break;
352 case 4:
353 strcpy(versionString, "3.0");
354 break;
355 default:
356 sprintf(versionString, "unknown ABI version 0x%02X", value);
357 }
358 }
359
360 void Resolver::doFile(const ld::File& file)
361 {
362 const ld::relocatable::File* objFile = dynamic_cast<const ld::relocatable::File*>(&file);
363 const ld::dylib::File* dylibFile = dynamic_cast<const ld::dylib::File*>(&file);
364
365 if ( objFile != NULL ) {
366 // if file has linker options, process them
367 ld::relocatable::File::LinkerOptionsList* lo = objFile->linkerOptions();
368 if ( lo != NULL && !_options.ignoreAutoLink() ) {
369 for (relocatable::File::LinkerOptionsList::const_iterator it=lo->begin(); it != lo->end(); ++it) {
370 this->doLinkerOption(*it, file.path());
371 }
372 // <rdar://problem/23053404> process any additional linker-options introduced by this new archive member being loaded
373 if ( _completedInitialObjectFiles ) {
374 _inputFiles.addLinkerOptionLibraries(_internal, *this);
375 _inputFiles.createIndirectDylibs();
376 }
377 }
378 // Resolve bitcode section in the object file
379 if ( _options.bundleBitcode() ) {
380 if ( objFile->getBitcode() == NULL ) {
381 // No bitcode section, figure out if the object file comes from LTO/compiler static library
382 if (objFile->sourceKind() != ld::relocatable::File::kSourceLTO &&
383 objFile->sourceKind() != ld::relocatable::File::kSourceCompilerArchive ) {
384 switch ( _options.platform() ) {
385 case Options::kPlatformOSX:
386 case Options::kPlatformUnknown:
387 warning("all bitcode will be dropped because '%s' was built without bitcode. "
388 "You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE), obtain an updated library from the vendor, or disable bitcode for this target. ", file.path());
389 _internal.filesWithBitcode.clear();
390 _internal.dropAllBitcode = true;
391 break;
392 case Options::kPlatformiOS:
393 throwf("'%s' does not contain bitcode. "
394 "You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE), obtain an updated library from the vendor, or disable bitcode for this target.", file.path());
395 break;
396 case Options::kPlatformWatchOS:
397 #if SUPPORT_APPLE_TV
398 case Options::kPlatform_tvOS:
399 #endif
400 throwf("'%s' does not contain bitcode. "
401 "You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE) or obtain an updated library from the vendor", file.path());
402 break;
403 }
404 }
405 } else {
406 // contains bitcode, check if it is just a marker
407 if ( objFile->getBitcode()->isMarker() ) {
408 // if -bitcode_verify_bundle is used, check if all the object files participate in the linking have full bitcode embedded.
409 // error on any marker encountered.
410 if ( _options.verifyBitcode() )
411 throwf("bitcode bundle could not be generated because '%s' was built without full bitcode. "
412 "All object files and libraries for bitcode must be generated from Xcode Archive or Install build",
413 objFile->path());
414 // update the internal state that marker is encountered.
415 _internal.embedMarkerOnly = true;
416 _internal.filesWithBitcode.clear();
417 _internal.dropAllBitcode = true;
418 } else if ( !_internal.dropAllBitcode )
419 _internal.filesWithBitcode.push_back(objFile);
420 }
421 }
422
423 // update which form of ObjC is being used
424 switch ( file.objCConstraint() ) {
425 case ld::File::objcConstraintNone:
426 break;
427 case ld::File::objcConstraintRetainRelease:
428 if ( _internal.objcObjectConstraint == ld::File::objcConstraintGC )
429 throwf("%s built with incompatible Garbage Collection settings to link with previous .o files", file.path());
430 if ( _options.objcGcOnly() )
431 throwf("command line specified -objc_gc_only, but file is retain/release based: %s", file.path());
432 if ( _options.objcGc() )
433 throwf("command line specified -objc_gc, but file is retain/release based: %s", file.path());
434 if ( !_options.targetIOSSimulator() && (_internal.objcObjectConstraint != ld::File::objcConstraintRetainReleaseForSimulator) )
435 _internal.objcObjectConstraint = ld::File::objcConstraintRetainRelease;
436 break;
437 case ld::File::objcConstraintRetainReleaseOrGC:
438 if ( _internal.objcObjectConstraint == ld::File::objcConstraintNone )
439 _internal.objcObjectConstraint = ld::File::objcConstraintRetainReleaseOrGC;
440 if ( _options.targetIOSSimulator() )
441 warning("linking ObjC for iOS Simulator, but object file (%s) was compiled for MacOSX", file.path());
442 break;
443 case ld::File::objcConstraintGC:
444 if ( _internal.objcObjectConstraint == ld::File::objcConstraintRetainRelease )
445 throwf("%s built with incompatible Garbage Collection settings to link with previous .o files", file.path());
446 _internal.objcObjectConstraint = ld::File::objcConstraintGC;
447 if ( _options.targetIOSSimulator() )
448 warning("linking ObjC for iOS Simulator, but object file (%s) was compiled for MacOSX", file.path());
449 break;
450 case ld::File::objcConstraintRetainReleaseForSimulator:
451 if ( _internal.objcObjectConstraint == ld::File::objcConstraintNone ) {
452 if ( !_options.targetIOSSimulator() && (_options.outputKind() != Options::kObjectFile) )
453 warning("ObjC object file (%s) was compiled for iOS Simulator, but linking for MacOSX", file.path());
454 _internal.objcObjectConstraint = ld::File::objcConstraintRetainReleaseForSimulator;
455 }
456 else if ( _internal.objcObjectConstraint != ld::File::objcConstraintRetainReleaseForSimulator ) {
457 _internal.objcObjectConstraint = ld::File::objcConstraintRetainReleaseForSimulator;
458 }
459 break;
460 }
461
462 // verify all files use same version of Swift language
463 if ( file.swiftVersion() != 0 ) {
464 if ( _internal.swiftVersion == 0 ) {
465 _internal.swiftVersion = file.swiftVersion();
466 }
467 else if ( file.swiftVersion() != _internal.swiftVersion ) {
468 char fileVersion[64];
469 char otherVersion[64];
470 userReadableSwiftVersion(file.swiftVersion(), fileVersion);
471 userReadableSwiftVersion(_internal.swiftVersion, otherVersion);
472 if ( file.swiftVersion() > _internal.swiftVersion ) {
473 throwf("%s compiled with newer version of Swift language (%s) than previous files (%s)",
474 file.path(), fileVersion, otherVersion);
475 }
476 else {
477 throwf("%s compiled with older version of Swift language (%s) than previous files (%s)",
478 file.path(), fileVersion, otherVersion);
479 }
480 }
481 }
482
483 // in -r mode, if any .o files have dwarf then add UUID to output .o file
484 if ( objFile->debugInfo() == ld::relocatable::File::kDebugInfoDwarf )
485 _internal.someObjectFileHasDwarf = true;
486
487 // remember if any .o file did not have MH_SUBSECTIONS_VIA_SYMBOLS bit set
488 if ( ! objFile->canScatterAtoms() )
489 _internal.allObjectFilesScatterable = false;
490
491 // update minOSVersion off all .o files
492 uint32_t objMinOS = objFile->minOSVersion();
493 if ( !objMinOS )
494 _internal.objectFileFoundWithNoVersion = true;
495
496 uint32_t objPlatformLC = objFile->platformLoadCommand();
497 if ( (objPlatformLC != 0) && (_internal.derivedPlatformLoadCommand == 0) && (_options.outputKind() == Options::kObjectFile) )
498 _internal.derivedPlatformLoadCommand = objPlatformLC;
499
500 if ( (_options.outputKind() == Options::kObjectFile) && (objMinOS > _internal.minOSVersion) )
501 _internal.minOSVersion = objMinOS;
502
503 // update cpu-sub-type
504 cpu_subtype_t nextObjectSubType = file.cpuSubType();
505 switch ( _options.architecture() ) {
506 case CPU_TYPE_ARM:
507 if ( _options.subArchitecture() != nextObjectSubType ) {
508 if ( (_options.subArchitecture() == CPU_SUBTYPE_ARM_ALL) && _options.forceCpuSubtypeAll() ) {
509 // hack to support gcc multillib build that tries to make sub-type-all slice
510 }
511 else if ( nextObjectSubType == CPU_SUBTYPE_ARM_ALL ) {
512 warning("CPU_SUBTYPE_ARM_ALL subtype is deprecated: %s", file.path());
513 }
514 else if ( _options.allowSubArchitectureMismatches() ) {
515 //warning("object file %s was built for different arm sub-type (%d) than link command line (%d)",
516 // file.path(), nextObjectSubType, _options.subArchitecture());
517 }
518 else {
519 throwf("object file %s was built for different arm sub-type (%d) than link command line (%d)",
520 file.path(), nextObjectSubType, _options.subArchitecture());
521 }
522 }
523 break;
524
525 case CPU_TYPE_I386:
526 _internal.cpuSubType = CPU_SUBTYPE_I386_ALL;
527 break;
528
529 case CPU_TYPE_X86_64:
530 if ( _options.subArchitecture() != nextObjectSubType ) {
531 if ( _options.allowSubArchitectureMismatches() ) {
532 warning("object file %s was built for different x86_64 sub-type (%d) than link command line (%d)",
533 file.path(), nextObjectSubType, _options.subArchitecture());
534 }
535 else {
536 throwf("object file %s was built for different x86_64 sub-type (%d) than link command line (%d)",
537 file.path(), nextObjectSubType, _options.subArchitecture());
538 }
539 }
540 break;
541 }
542 }
543 if ( dylibFile != NULL ) {
544 // Check dylib for bitcode, if the library install path is relative path or @rpath, it has to contain bitcode
545 if ( _options.bundleBitcode() ) {
546 bool isSystemFramework = ( dylibFile->installPath() != NULL ) && ( dylibFile->installPath()[0] == '/' );
547 if ( dylibFile->getBitcode() == NULL && !isSystemFramework ) {
548 // Check if the dylib is from toolchain by checking the path
549 char tcLibPath[PATH_MAX];
550 char ldPath[PATH_MAX];
551 char tempPath[PATH_MAX];
552 uint32_t bufSize = PATH_MAX;
553 // toolchain library path should pointed to *.xctoolchain/usr/lib
554 if ( _NSGetExecutablePath(ldPath, &bufSize) != -1 ) {
555 if ( realpath(ldPath, tempPath) != NULL ) {
556 char* lastSlash = strrchr(tempPath, '/');
557 if ( lastSlash != NULL )
558 strcpy(lastSlash, "/../lib");
559 }
560 }
561 // Compare toolchain library path to the dylib path
562 if ( realpath(tempPath, tcLibPath) == NULL ||
563 realpath(dylibFile->path(), tempPath) == NULL ||
564 strncmp(tcLibPath, tempPath, strlen(tcLibPath)) != 0 ) {
565 switch ( _options.platform() ) {
566 case Options::kPlatformOSX:
567 case Options::kPlatformUnknown:
568 warning("all bitcode will be dropped because '%s' was built without bitcode. "
569 "You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE), obtain an updated library from the vendor, or disable bitcode for this target.", file.path());
570 _internal.filesWithBitcode.clear();
571 _internal.dropAllBitcode = true;
572 break;
573 case Options::kPlatformiOS:
574 throwf("'%s' does not contain bitcode. "
575 "You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE), obtain an updated library from the vendor, or disable bitcode for this target.", file.path());
576 break;
577 case Options::kPlatformWatchOS:
578 #if SUPPORT_APPLE_TV
579 case Options::kPlatform_tvOS:
580 #endif
581 throwf("'%s' does not contain bitcode. "
582 "You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE) or obtain an updated library from the vendor", file.path());
583 break;
584 }
585 }
586 }
587 // Error on bitcode marker in non-system frameworks if -bitcode_verify is used
588 if ( _options.verifyBitcode() && !isSystemFramework &&
589 dylibFile->getBitcode() != NULL && dylibFile->getBitcode()->isMarker() )
590 throwf("bitcode bundle could not be generated because '%s' was built without full bitcode. "
591 "All frameworks and dylibs for bitcode must be generated from Xcode Archive or Install build",
592 dylibFile->path());
593 }
594
595 // update which form of ObjC dylibs are being linked
596 switch ( dylibFile->objCConstraint() ) {
597 case ld::File::objcConstraintNone:
598 break;
599 case ld::File::objcConstraintRetainRelease:
600 if ( _internal.objcDylibConstraint == ld::File::objcConstraintGC )
601 throwf("%s built with incompatible Garbage Collection settings to link with previous dylibs", file.path());
602 if ( _options.objcGcOnly() )
603 throwf("command line specified -objc_gc_only, but dylib is retain/release based: %s", file.path());
604 if ( _options.objcGc() )
605 throwf("command line specified -objc_gc, but dylib is retain/release based: %s", file.path());
606 if ( _options.targetIOSSimulator() )
607 warning("linking ObjC for iOS Simulator, but dylib (%s) was compiled for MacOSX", file.path());
608 _internal.objcDylibConstraint = ld::File::objcConstraintRetainRelease;
609 break;
610 case ld::File::objcConstraintRetainReleaseOrGC:
611 if ( _internal.objcDylibConstraint == ld::File::objcConstraintNone )
612 _internal.objcDylibConstraint = ld::File::objcConstraintRetainReleaseOrGC;
613 if ( _options.targetIOSSimulator() )
614 warning("linking ObjC for iOS Simulator, but dylib (%s) was compiled for MacOSX", file.path());
615 break;
616 case ld::File::objcConstraintGC:
617 if ( _internal.objcDylibConstraint == ld::File::objcConstraintRetainRelease )
618 throwf("%s built with incompatible Garbage Collection settings to link with previous dylibs", file.path());
619 if ( _options.targetIOSSimulator() )
620 warning("linking ObjC for iOS Simulator, but dylib (%s) was compiled for MacOSX", file.path());
621 _internal.objcDylibConstraint = ld::File::objcConstraintGC;
622 break;
623 case ld::File::objcConstraintRetainReleaseForSimulator:
624 if ( _internal.objcDylibConstraint == ld::File::objcConstraintNone )
625 _internal.objcDylibConstraint = ld::File::objcConstraintRetainReleaseForSimulator;
626 else if ( _internal.objcDylibConstraint != ld::File::objcConstraintRetainReleaseForSimulator ) {
627 warning("ObjC dylib (%s) was compiled for iOS Simulator, but dylibs others were compiled for MacOSX", file.path());
628 _internal.objcDylibConstraint = ld::File::objcConstraintRetainReleaseForSimulator;
629 }
630 break;
631 }
632
633 // <rdar://problem/25680358> verify dylibs use same version of Swift language
634 if ( file.swiftVersion() != 0 ) {
635 if ( _internal.swiftVersion == 0 ) {
636 _internal.swiftVersion = file.swiftVersion();
637 }
638 else if ( file.swiftVersion() != _internal.swiftVersion ) {
639 char fileVersion[64];
640 char otherVersion[64];
641 userReadableSwiftVersion(file.swiftVersion(), fileVersion);
642 userReadableSwiftVersion(_internal.swiftVersion, otherVersion);
643 if ( file.swiftVersion() > _internal.swiftVersion ) {
644 throwf("%s compiled with newer version of Swift language (%s) than previous files (%s)",
645 file.path(), fileVersion, otherVersion);
646 }
647 else {
648 throwf("%s compiled with older version of Swift language (%s) than previous files (%s)",
649 file.path(), fileVersion, otherVersion);
650 }
651 }
652 }
653
654 if ( _options.checkDylibsAreAppExtensionSafe() && !dylibFile->appExtensionSafe() ) {
655 warning("linking against a dylib which is not safe for use in application extensions: %s", file.path());
656 }
657 const char* depInstallName = dylibFile->installPath();
658 // <rdar://problem/17229513> embedded frameworks are only supported on iOS 8 and later
659 if ( (depInstallName != NULL) && (depInstallName[0] != '/') ) {
660 if ( (_options.iOSVersionMin() != iOSVersionUnset) && (_options.iOSVersionMin() < iOS_8_0) ) {
661 // <rdar://problem/17598404> only warn about linking against embedded dylib if it is built for iOS 8 or later
662 if ( dylibFile->minOSVersion() >= iOS_8_0 )
663 throwf("embedded dylibs/frameworks are only supported on iOS 8.0 and later (%s)", depInstallName);
664 }
665 }
666 if ( _options.sharedRegionEligible() ) {
667 assert(depInstallName != NULL);
668 if ( depInstallName[0] == '@' ) {
669 warning("invalid -install_name (%s) in dependent dylib (%s). Dylibs/frameworks which might go in dyld shared cache "
670 "cannot link with dylib that uses @rpath, @loader_path, etc.", depInstallName, dylibFile->path());
671 } else if ( (strncmp(depInstallName, "/usr/lib/", 9) != 0) && (strncmp(depInstallName, "/System/Library/", 16) != 0) ) {
672 warning("invalid -install_name (%s) in dependent dylib (%s). Dylibs/frameworks which might go in dyld shared cache "
673 "cannot link with dylibs that won't be in the shared cache", depInstallName, dylibFile->path());
674 }
675 }
676 }
677
678 }
679
680 void Resolver::doAtom(const ld::Atom& atom)
681 {
682 //fprintf(stderr, "Resolver::doAtom(%p), name=%s, sect=%s, scope=%d\n", &atom, atom.name(), atom.section().sectionName(), atom.scope());
683 if ( _ltoCodeGenFinished && (atom.contentType() == ld::Atom::typeLTOtemporary) && (atom.scope() != ld::Atom::scopeTranslationUnit) )
684 warning("'%s' is implemented in bitcode, but it was loaded too late", atom.name());
685
686 // add to list of known atoms
687 _atoms.push_back(&atom);
688
689 // adjust scope
690 if ( _options.hasExportRestrictList() || _options.hasReExportList() ) {
691 const char* name = atom.name();
692 switch ( atom.scope() ) {
693 case ld::Atom::scopeTranslationUnit:
694 break;
695 case ld::Atom::scopeLinkageUnit:
696 if ( _options.hasExportMaskList() && _options.shouldExport(name) ) {
697 // <rdar://problem/5062685> ld does not report error when -r is used and exported symbols are not defined.
698 if ( _options.outputKind() == Options::kObjectFile )
699 throwf("cannot export hidden symbol %s", name);
700 // .objc_class_name_* symbols are special
701 if ( atom.section().type() != ld::Section::typeObjC1Classes ) {
702 if ( atom.definition() == ld::Atom::definitionProxy ) {
703 // .exp file says to export a symbol, but that symbol is in some dylib being linked
704 if ( _options.canReExportSymbols() ) {
705 // marking proxy atom as global triggers the re-export
706 (const_cast<ld::Atom*>(&atom))->setScope(ld::Atom::scopeGlobal);
707 }
708 else if ( _options.outputKind() == Options::kDynamicLibrary ) {
709 if ( atom.file() != NULL )
710 warning("target OS does not support re-exporting symbol %s from %s\n", _options.demangleSymbol(name), atom.file()->path());
711 else
712 warning("target OS does not support re-exporting symbol %s\n", _options.demangleSymbol(name));
713 }
714 }
715 else {
716 if ( atom.file() != NULL )
717 warning("cannot export hidden symbol %s from %s", _options.demangleSymbol(name), atom.file()->path());
718 else
719 warning("cannot export hidden symbol %s", _options.demangleSymbol(name));
720 }
721 }
722 }
723 else if ( _options.shouldReExport(name) && _options.canReExportSymbols() ) {
724 if ( atom.definition() == ld::Atom::definitionProxy ) {
725 // marking proxy atom as global triggers the re-export
726 (const_cast<ld::Atom*>(&atom))->setScope(ld::Atom::scopeGlobal);
727 }
728 else {
729 throwf("requested re-export symbol %s is not from a dylib, but from %s\n", _options.demangleSymbol(name), atom.file()->path());
730 }
731 }
732 break;
733 case ld::Atom::scopeGlobal:
734 // check for globals that are downgraded to hidden
735 if ( ! _options.shouldExport(name) ) {
736 (const_cast<ld::Atom*>(&atom))->setScope(ld::Atom::scopeLinkageUnit);
737 //fprintf(stderr, "demote %s to hidden\n", name);
738 }
739 if ( _options.canReExportSymbols() && _options.shouldReExport(name) ) {
740 throwf("requested re-export symbol %s is not from a dylib, but from %s\n", _options.demangleSymbol(name), atom.file()->path());
741 }
742 break;
743 }
744 }
745
746 // work around for kernel that uses 'l' labels in assembly code
747 if ( (atom.symbolTableInclusion() == ld::Atom::symbolTableNotInFinalLinkedImages)
748 && (atom.name()[0] == 'l') && (_options.outputKind() == Options::kStaticExecutable)
749 && (strncmp(atom.name(), "ltmp", 4) != 0) )
750 (const_cast<ld::Atom*>(&atom))->setSymbolTableInclusion(ld::Atom::symbolTableIn);
751
752
753 // tell symbol table about non-static atoms
754 if ( atom.scope() != ld::Atom::scopeTranslationUnit ) {
755 _symbolTable.add(atom, _options.deadCodeStrip() && (_completedInitialObjectFiles || _options.allowDeadDuplicates()));
756
757 // add symbol aliases defined on the command line
758 if ( _options.haveCmdLineAliases() ) {
759 const std::vector<Options::AliasPair>& aliases = _options.cmdLineAliases();
760 for (std::vector<Options::AliasPair>::const_iterator it=aliases.begin(); it != aliases.end(); ++it) {
761 if ( strcmp(it->realName, atom.name()) == 0 ) {
762 if ( strcmp(it->realName, it->alias) == 0 ) {
763 warning("ignoring alias of itself '%s'", it->realName);
764 }
765 else {
766 const AliasAtom* alias = new AliasAtom(atom, it->alias);
767 _aliasesFromCmdLine.push_back(alias);
768 this->doAtom(*alias);
769 }
770 }
771 }
772 }
773 }
774
775 // convert references by-name or by-content to by-slot
776 this->convertReferencesToIndirect(atom);
777
778 // remember if any atoms are proxies that require LTO
779 if ( atom.contentType() == ld::Atom::typeLTOtemporary )
780 _haveLLVMObjs = true;
781
782 // remember if any atoms are aliases
783 if ( atom.section().type() == ld::Section::typeTempAlias )
784 _haveAliases = true;
785
786 if ( _options.deadCodeStrip() ) {
787 // add to set of dead-strip-roots, all symbols that the compiler marks as don't strip
788 if ( atom.dontDeadStrip() )
789 _deadStripRoots.insert(&atom);
790 else if ( atom.dontDeadStripIfReferencesLive() )
791 _dontDeadStripIfReferencesLive.push_back(&atom);
792
793 if ( atom.scope() == ld::Atom::scopeGlobal ) {
794 // <rdar://problem/5524973> -exported_symbols_list that has wildcards and -dead_strip
795 // in dylibs, every global atom in initial .o files is a root
796 if ( _options.hasWildCardExportRestrictList() || _options.allGlobalsAreDeadStripRoots() ) {
797 if ( _options.shouldExport(atom.name()) )
798 _deadStripRoots.insert(&atom);
799 }
800 }
801 }
802 }
803
804 bool Resolver::isDtraceProbe(ld::Fixup::Kind kind)
805 {
806 switch (kind) {
807 case ld::Fixup::kindStoreX86DtraceCallSiteNop:
808 case ld::Fixup::kindStoreX86DtraceIsEnableSiteClear:
809 case ld::Fixup::kindStoreARMDtraceCallSiteNop:
810 case ld::Fixup::kindStoreARMDtraceIsEnableSiteClear:
811 case ld::Fixup::kindStoreARM64DtraceCallSiteNop:
812 case ld::Fixup::kindStoreARM64DtraceIsEnableSiteClear:
813 case ld::Fixup::kindStoreThumbDtraceCallSiteNop:
814 case ld::Fixup::kindStoreThumbDtraceIsEnableSiteClear:
815 case ld::Fixup::kindDtraceExtra:
816 return true;
817 default:
818 break;
819 }
820 return false;
821 }
822
823 void Resolver::convertReferencesToIndirect(const ld::Atom& atom)
824 {
825 // convert references by-name or by-content to by-slot
826 SymbolTable::IndirectBindingSlot slot;
827 const ld::Atom* dummy;
828 ld::Fixup::iterator end = atom.fixupsEnd();
829 for (ld::Fixup::iterator fit=atom.fixupsBegin(); fit != end; ++fit) {
830 if ( fit->kind == ld::Fixup::kindLinkerOptimizationHint )
831 _internal.someObjectHasOptimizationHints = true;
832 switch ( fit->binding ) {
833 case ld::Fixup::bindingByNameUnbound:
834 if ( isDtraceProbe(fit->kind) && (_options.outputKind() != Options::kObjectFile ) ) {
835 // in final linked images, remove reference
836 fit->binding = ld::Fixup::bindingNone;
837 }
838 else {
839 slot = _symbolTable.findSlotForName(fit->u.name);
840 fit->binding = ld::Fixup::bindingsIndirectlyBound;
841 fit->u.bindingIndex = slot;
842 }
843 break;
844 case ld::Fixup::bindingByContentBound:
845 switch ( fit->u.target->combine() ) {
846 case ld::Atom::combineNever:
847 case ld::Atom::combineByName:
848 assert(0 && "wrong combine type for bind by content");
849 break;
850 case ld::Atom::combineByNameAndContent:
851 slot = _symbolTable.findSlotForContent(fit->u.target, &dummy);
852 fit->binding = ld::Fixup::bindingsIndirectlyBound;
853 fit->u.bindingIndex = slot;
854 break;
855 case ld::Atom::combineByNameAndReferences:
856 slot = _symbolTable.findSlotForReferences(fit->u.target, &dummy);
857 fit->binding = ld::Fixup::bindingsIndirectlyBound;
858 fit->u.bindingIndex = slot;
859 break;
860 }
861 break;
862 case ld::Fixup::bindingNone:
863 case ld::Fixup::bindingDirectlyBound:
864 case ld::Fixup::bindingsIndirectlyBound:
865 break;
866 }
867 }
868 }
869
870
871 void Resolver::addInitialUndefines()
872 {
873 // add initial undefines from -u option
874 for (Options::UndefinesIterator it=_options.initialUndefinesBegin(); it != _options.initialUndefinesEnd(); ++it) {
875 _symbolTable.findSlotForName(*it);
876 }
877 }
878
879 void Resolver::resolveUndefines()
880 {
881 // keep looping until no more undefines were added in last loop
882 unsigned int undefineGenCount = 0xFFFFFFFF;
883 while ( undefineGenCount != _symbolTable.updateCount() ) {
884 undefineGenCount = _symbolTable.updateCount();
885 std::vector<const char*> undefineNames;
886 _symbolTable.undefines(undefineNames);
887 for(std::vector<const char*>::iterator it = undefineNames.begin(); it != undefineNames.end(); ++it) {
888 const char* undef = *it;
889 // load for previous undefine may also have loaded this undefine, so check again
890 if ( ! _symbolTable.hasName(undef) ) {
891 _inputFiles.searchLibraries(undef, true, true, false, *this);
892 if ( !_symbolTable.hasName(undef) && (_options.outputKind() != Options::kObjectFile) ) {
893 if ( strncmp(undef, "section$", 8) == 0 ) {
894 if ( strncmp(undef, "section$start$", 14) == 0 ) {
895 this->doAtom(*SectionBoundaryAtom::makeSectionBoundaryAtom(undef, true, &undef[14]));
896 }
897 else if ( strncmp(undef, "section$end$", 12) == 0 ) {
898 this->doAtom(*SectionBoundaryAtom::makeSectionBoundaryAtom(undef, false, &undef[12]));
899 }
900 }
901 else if ( strncmp(undef, "segment$", 8) == 0 ) {
902 if ( strncmp(undef, "segment$start$", 14) == 0 ) {
903 this->doAtom(*SegmentBoundaryAtom::makeSegmentBoundaryAtom(undef, true, &undef[14]));
904 }
905 else if ( strncmp(undef, "segment$end$", 12) == 0 ) {
906 this->doAtom(*SegmentBoundaryAtom::makeSegmentBoundaryAtom(undef, false, &undef[12]));
907 }
908 }
909 else if ( _options.outputKind() == Options::kPreload ) {
910 // for iBoot grandfather in old style section labels
911 int undefLen = strlen(undef);
912 if ( strcmp(&undef[undefLen-7], "__begin") == 0 ) {
913 if ( undefLen > 13 )
914 this->doAtom(*SectionBoundaryAtom::makeOldSectionBoundaryAtom(undef, true));
915 else
916 this->doAtom(*SegmentBoundaryAtom::makeOldSegmentBoundaryAtom(undef, true));
917 }
918 else if ( strcmp(&undef[undefLen-5], "__end") == 0 ) {
919 if ( undefLen > 11 )
920 this->doAtom(*SectionBoundaryAtom::makeOldSectionBoundaryAtom(undef, false));
921 else
922 this->doAtom(*SegmentBoundaryAtom::makeOldSegmentBoundaryAtom(undef, false));
923 }
924 }
925 }
926 }
927 }
928 // <rdar://problem/5894163> need to search archives for overrides of common symbols
929 if ( _symbolTable.hasExternalTentativeDefinitions() ) {
930 bool searchDylibs = (_options.commonsMode() == Options::kCommonsOverriddenByDylibs);
931 std::vector<const char*> tents;
932 _symbolTable.tentativeDefs(tents);
933 for(std::vector<const char*>::iterator it = tents.begin(); it != tents.end(); ++it) {
934 // load for previous tentative may also have loaded this tentative, so check again
935 const ld::Atom* curAtom = _symbolTable.atomForSlot(_symbolTable.findSlotForName(*it));
936 assert(curAtom != NULL);
937 if ( curAtom->definition() == ld::Atom::definitionTentative ) {
938 _inputFiles.searchLibraries(*it, searchDylibs, true, true, *this);
939 }
940 }
941 }
942 }
943
944 // Use linker options to resolve any remaining undefined symbols
945 if ( !_internal.linkerOptionLibraries.empty() || !_internal.linkerOptionFrameworks.empty() ) {
946 std::vector<const char*> undefineNames;
947 _symbolTable.undefines(undefineNames);
948 if ( undefineNames.size() != 0 ) {
949 for (std::vector<const char*>::iterator it = undefineNames.begin(); it != undefineNames.end(); ++it) {
950 const char* undef = *it;
951 if ( ! _symbolTable.hasName(undef) ) {
952 _inputFiles.searchLibraries(undef, true, true, false, *this);
953 }
954 }
955 }
956 }
957
958 // create proxies as needed for undefined symbols
959 if ( (_options.undefinedTreatment() != Options::kUndefinedError) || (_options.outputKind() == Options::kObjectFile) ) {
960 std::vector<const char*> undefineNames;
961 _symbolTable.undefines(undefineNames);
962 for(std::vector<const char*>::iterator it = undefineNames.begin(); it != undefineNames.end(); ++it) {
963 const char* undefName = *it;
964 // <rdar://problem/14547001> "ld -r -exported_symbol _foo" has wrong error message if _foo is undefined
965 bool makeProxy = true;
966 if ( (_options.outputKind() == Options::kObjectFile) && _options.hasExportMaskList() && _options.shouldExport(undefName) )
967 makeProxy = false;
968
969 if ( makeProxy )
970 this->doAtom(*new UndefinedProxyAtom(undefName));
971 }
972 }
973
974 // support -U option
975 if ( _options.someAllowedUndefines() ) {
976 std::vector<const char*> undefineNames;
977 _symbolTable.undefines(undefineNames);
978 for(std::vector<const char*>::iterator it = undefineNames.begin(); it != undefineNames.end(); ++it) {
979 if ( _options.allowedUndefined(*it) ) {
980 // make proxy
981 this->doAtom(*new UndefinedProxyAtom(*it));
982 }
983 }
984 }
985
986 // After resolving all the undefs within the linkageUnit, record all the remaining undefs and all the proxies.
987 if (_options.bundleBitcode() && _options.hideSymbols())
988 _symbolTable.mustPreserveForBitcode(_internal.allUndefProxies);
989
990 }
991
992
993 void Resolver::markLive(const ld::Atom& atom, WhyLiveBackChain* previous)
994 {
995 //fprintf(stderr, "markLive(%p) %s\n", &atom, atom.name());
996 // if -why_live cares about this symbol, then dump chain
997 if ( (previous->referer != NULL) && _options.printWhyLive(atom.name()) ) {
998 fprintf(stderr, "%s from %s\n", atom.name(), atom.file()->path());
999 int depth = 1;
1000 for(WhyLiveBackChain* p = previous; p != NULL; p = p->previous, ++depth) {
1001 for(int i=depth; i > 0; --i)
1002 fprintf(stderr, " ");
1003 fprintf(stderr, "%s from %s\n", p->referer->name(), p->referer->file()->path());
1004 }
1005 }
1006
1007 // if already marked live, then done (stop recursion)
1008 if ( atom.live() )
1009 return;
1010
1011 // mark this atom is live
1012 (const_cast<ld::Atom*>(&atom))->setLive();
1013
1014 // mark all atoms it references as live
1015 WhyLiveBackChain thisChain;
1016 thisChain.previous = previous;
1017 thisChain.referer = &atom;
1018 for (ld::Fixup::iterator fit = atom.fixupsBegin(), end=atom.fixupsEnd(); fit != end; ++fit) {
1019 const ld::Atom* target;
1020 switch ( fit->kind ) {
1021 case ld::Fixup::kindNone:
1022 case ld::Fixup::kindNoneFollowOn:
1023 case ld::Fixup::kindNoneGroupSubordinate:
1024 case ld::Fixup::kindNoneGroupSubordinateFDE:
1025 case ld::Fixup::kindNoneGroupSubordinateLSDA:
1026 case ld::Fixup::kindNoneGroupSubordinatePersonality:
1027 case ld::Fixup::kindSetTargetAddress:
1028 case ld::Fixup::kindSubtractTargetAddress:
1029 case ld::Fixup::kindStoreTargetAddressLittleEndian32:
1030 case ld::Fixup::kindStoreTargetAddressLittleEndian64:
1031 case ld::Fixup::kindStoreTargetAddressBigEndian32:
1032 case ld::Fixup::kindStoreTargetAddressBigEndian64:
1033 case ld::Fixup::kindStoreTargetAddressX86PCRel32:
1034 case ld::Fixup::kindStoreTargetAddressX86BranchPCRel32:
1035 case ld::Fixup::kindStoreTargetAddressX86PCRel32GOTLoad:
1036 case ld::Fixup::kindStoreTargetAddressX86PCRel32GOTLoadNowLEA:
1037 case ld::Fixup::kindStoreTargetAddressX86PCRel32TLVLoad:
1038 case ld::Fixup::kindStoreTargetAddressX86PCRel32TLVLoadNowLEA:
1039 case ld::Fixup::kindStoreTargetAddressX86Abs32TLVLoad:
1040 case ld::Fixup::kindStoreTargetAddressX86Abs32TLVLoadNowLEA:
1041 case ld::Fixup::kindStoreTargetAddressARMBranch24:
1042 case ld::Fixup::kindStoreTargetAddressThumbBranch22:
1043 #if SUPPORT_ARCH_arm64
1044 case ld::Fixup::kindStoreTargetAddressARM64Branch26:
1045 case ld::Fixup::kindStoreTargetAddressARM64Page21:
1046 case ld::Fixup::kindStoreTargetAddressARM64GOTLoadPage21:
1047 case ld::Fixup::kindStoreTargetAddressARM64GOTLeaPage21:
1048 case ld::Fixup::kindStoreTargetAddressARM64TLVPLoadPage21:
1049 case ld::Fixup::kindStoreTargetAddressARM64TLVPLoadNowLeaPage21:
1050 #endif
1051 if ( fit->binding == ld::Fixup::bindingByContentBound ) {
1052 // normally this was done in convertReferencesToIndirect()
1053 // but a archive loaded .o file may have a forward reference
1054 SymbolTable::IndirectBindingSlot slot;
1055 const ld::Atom* dummy;
1056 switch ( fit->u.target->combine() ) {
1057 case ld::Atom::combineNever:
1058 case ld::Atom::combineByName:
1059 assert(0 && "wrong combine type for bind by content");
1060 break;
1061 case ld::Atom::combineByNameAndContent:
1062 slot = _symbolTable.findSlotForContent(fit->u.target, &dummy);
1063 fit->binding = ld::Fixup::bindingsIndirectlyBound;
1064 fit->u.bindingIndex = slot;
1065 break;
1066 case ld::Atom::combineByNameAndReferences:
1067 slot = _symbolTable.findSlotForReferences(fit->u.target, &dummy);
1068 fit->binding = ld::Fixup::bindingsIndirectlyBound;
1069 fit->u.bindingIndex = slot;
1070 break;
1071 }
1072 }
1073 switch ( fit->binding ) {
1074 case ld::Fixup::bindingDirectlyBound:
1075 markLive(*(fit->u.target), &thisChain);
1076 break;
1077 case ld::Fixup::bindingByNameUnbound:
1078 // doAtom() did not convert to indirect in dead-strip mode, so that now
1079 fit->u.bindingIndex = _symbolTable.findSlotForName(fit->u.name);
1080 fit->binding = ld::Fixup::bindingsIndirectlyBound;
1081 // fall into next case
1082 case ld::Fixup::bindingsIndirectlyBound:
1083 target = _internal.indirectBindingTable[fit->u.bindingIndex];
1084 if ( target == NULL ) {
1085 const char* targetName = _symbolTable.indirectName(fit->u.bindingIndex);
1086 _inputFiles.searchLibraries(targetName, true, true, false, *this);
1087 target = _internal.indirectBindingTable[fit->u.bindingIndex];
1088 }
1089 if ( target != NULL ) {
1090 if ( target->definition() == ld::Atom::definitionTentative ) {
1091 // <rdar://problem/5894163> need to search archives for overrides of common symbols
1092 bool searchDylibs = (_options.commonsMode() == Options::kCommonsOverriddenByDylibs);
1093 _inputFiles.searchLibraries(target->name(), searchDylibs, true, true, *this);
1094 // recompute target since it may have been overridden by searchLibraries()
1095 target = _internal.indirectBindingTable[fit->u.bindingIndex];
1096 }
1097 this->markLive(*target, &thisChain);
1098 }
1099 else {
1100 _atomsWithUnresolvedReferences.push_back(&atom);
1101 }
1102 break;
1103 default:
1104 assert(0 && "bad binding during dead stripping");
1105 }
1106 break;
1107 default:
1108 break;
1109 }
1110 }
1111
1112 }
1113
1114 class NotLiveLTO {
1115 public:
1116 bool operator()(const ld::Atom* atom) const {
1117 if (atom->live() || atom->dontDeadStrip() )
1118 return false;
1119 // don't kill combinable atoms in first pass
1120 switch ( atom->combine() ) {
1121 case ld::Atom::combineByNameAndContent:
1122 case ld::Atom::combineByNameAndReferences:
1123 return false;
1124 default:
1125 return true;
1126 }
1127 }
1128 };
1129
1130 void Resolver::deadStripOptimize(bool force)
1131 {
1132 // only do this optimization with -dead_strip
1133 if ( ! _options.deadCodeStrip() )
1134 return;
1135
1136 // add entry point (main) to live roots
1137 const ld::Atom* entry = this->entryPoint(true);
1138 if ( entry != NULL )
1139 _deadStripRoots.insert(entry);
1140
1141 // add -exported_symbols_list, -init, and -u entries to live roots
1142 for (Options::UndefinesIterator uit=_options.initialUndefinesBegin(); uit != _options.initialUndefinesEnd(); ++uit) {
1143 SymbolTable::IndirectBindingSlot slot = _symbolTable.findSlotForName(*uit);
1144 if ( _internal.indirectBindingTable[slot] == NULL ) {
1145 _inputFiles.searchLibraries(*uit, false, true, false, *this);
1146 }
1147 if ( _internal.indirectBindingTable[slot] != NULL )
1148 _deadStripRoots.insert(_internal.indirectBindingTable[slot]);
1149 }
1150
1151 // this helper is only referenced by synthesize stubs, assume it will be used
1152 if ( _internal.classicBindingHelper != NULL )
1153 _deadStripRoots.insert(_internal.classicBindingHelper);
1154
1155 // this helper is only referenced by synthesize stubs, assume it will be used
1156 if ( _internal.compressedFastBinderProxy != NULL )
1157 _deadStripRoots.insert(_internal.compressedFastBinderProxy);
1158
1159 // this helper is only referenced by synthesized lazy stubs, assume it will be used
1160 if ( _internal.lazyBindingHelper != NULL )
1161 _deadStripRoots.insert(_internal.lazyBindingHelper);
1162
1163 // add all dont-dead-strip atoms as roots
1164 for (std::vector<const ld::Atom*>::const_iterator it=_atoms.begin(); it != _atoms.end(); ++it) {
1165 const ld::Atom* atom = *it;
1166 if ( atom->dontDeadStrip() ) {
1167 //fprintf(stderr, "dont dead strip: %p %s %s\n", atom, atom->section().sectionName(), atom->name());
1168 _deadStripRoots.insert(atom);
1169 // unset liveness, so markLive() will recurse
1170 (const_cast<ld::Atom*>(atom))->setLive(0);
1171 }
1172 }
1173
1174 // mark all roots as live, and all atoms they reference
1175 for (std::set<const ld::Atom*>::iterator it=_deadStripRoots.begin(); it != _deadStripRoots.end(); ++it) {
1176 WhyLiveBackChain rootChain;
1177 rootChain.previous = NULL;
1178 rootChain.referer = *it;
1179 this->markLive(**it, &rootChain);
1180 }
1181
1182 // special case atoms that need to be live if they reference something live
1183 if ( ! _dontDeadStripIfReferencesLive.empty() ) {
1184 for (std::vector<const ld::Atom*>::iterator it=_dontDeadStripIfReferencesLive.begin(); it != _dontDeadStripIfReferencesLive.end(); ++it) {
1185 const Atom* liveIfRefLiveAtom = *it;
1186 //fprintf(stderr, "live-if-live atom: %s\n", liveIfRefLiveAtom->name());
1187 if ( liveIfRefLiveAtom->live() )
1188 continue;
1189 bool hasLiveRef = false;
1190 for (ld::Fixup::iterator fit=liveIfRefLiveAtom->fixupsBegin(); fit != liveIfRefLiveAtom->fixupsEnd(); ++fit) {
1191 const Atom* target = NULL;
1192 switch ( fit->binding ) {
1193 case ld::Fixup::bindingDirectlyBound:
1194 target = fit->u.target;
1195 break;
1196 case ld::Fixup::bindingsIndirectlyBound:
1197 target = _internal.indirectBindingTable[fit->u.bindingIndex];
1198 break;
1199 default:
1200 break;
1201 }
1202 if ( (target != NULL) && target->live() )
1203 hasLiveRef = true;
1204 }
1205 if ( hasLiveRef ) {
1206 WhyLiveBackChain rootChain;
1207 rootChain.previous = NULL;
1208 rootChain.referer = liveIfRefLiveAtom;
1209 this->markLive(*liveIfRefLiveAtom, &rootChain);
1210 }
1211 }
1212 }
1213
1214 // now remove all non-live atoms from _atoms
1215 const bool log = false;
1216 if ( log ) {
1217 fprintf(stderr, "deadStripOptimize() all %ld atoms with liveness:\n", _atoms.size());
1218 for (std::vector<const ld::Atom*>::const_iterator it=_atoms.begin(); it != _atoms.end(); ++it) {
1219 const ld::File* file = (*it)->file();
1220 fprintf(stderr, " live=%d atom=%p name=%s from=%s\n", (*it)->live(), *it, (*it)->name(), (file ? file->path() : "<internal>"));
1221 }
1222 }
1223
1224 if ( _haveLLVMObjs && !force ) {
1225 std::copy_if(_atoms.begin(), _atoms.end(), std::back_inserter(_internal.deadAtoms), NotLiveLTO() );
1226 // <rdar://problem/9777977> don't remove combinable atoms, they may come back in lto output
1227 _atoms.erase(std::remove_if(_atoms.begin(), _atoms.end(), NotLiveLTO()), _atoms.end());
1228 _symbolTable.removeDeadAtoms();
1229 }
1230 else {
1231 std::copy_if(_atoms.begin(), _atoms.end(), std::back_inserter(_internal.deadAtoms), NotLive() );
1232 _atoms.erase(std::remove_if(_atoms.begin(), _atoms.end(), NotLive()), _atoms.end());
1233 }
1234
1235 if ( log ) {
1236 fprintf(stderr, "deadStripOptimize() %ld remaining atoms\n", _atoms.size());
1237 for (std::vector<const ld::Atom*>::const_iterator it=_atoms.begin(); it != _atoms.end(); ++it) {
1238 fprintf(stderr, " live=%d atom=%p name=%s\n", (*it)->live(), *it, (*it)->name());
1239 }
1240 }
1241 }
1242
1243
1244 // This is called when LTO is used but -dead_strip is not used.
1245 // Some undefines were eliminated by LTO, but others were not.
1246 void Resolver::remainingUndefines(std::vector<const char*>& undefs)
1247 {
1248 StringSet undefSet;
1249 // search all atoms for references that are unbound
1250 for (std::vector<const ld::Atom*>::const_iterator it=_atoms.begin(); it != _atoms.end(); ++it) {
1251 const ld::Atom* atom = *it;
1252 for (ld::Fixup::iterator fit=atom->fixupsBegin(); fit != atom->fixupsEnd(); ++fit) {
1253 switch ( (ld::Fixup::TargetBinding)fit->binding ) {
1254 case ld::Fixup::bindingByNameUnbound:
1255 assert(0 && "should not be by-name this late");
1256 undefSet.insert(fit->u.name);
1257 break;
1258 case ld::Fixup::bindingsIndirectlyBound:
1259 if ( _internal.indirectBindingTable[fit->u.bindingIndex] == NULL ) {
1260 undefSet.insert(_symbolTable.indirectName(fit->u.bindingIndex));
1261 }
1262 break;
1263 case ld::Fixup::bindingByContentBound:
1264 case ld::Fixup::bindingNone:
1265 case ld::Fixup::bindingDirectlyBound:
1266 break;
1267 }
1268 }
1269 }
1270 // look for any initial undefines that are still undefined
1271 for (Options::UndefinesIterator uit=_options.initialUndefinesBegin(); uit != _options.initialUndefinesEnd(); ++uit) {
1272 if ( ! _symbolTable.hasName(*uit) ) {
1273 undefSet.insert(*uit);
1274 }
1275 }
1276
1277 // copy set to vector
1278 for (StringSet::const_iterator it=undefSet.begin(); it != undefSet.end(); ++it) {
1279 fprintf(stderr, "undef: %s\n", *it);
1280 undefs.push_back(*it);
1281 }
1282 }
1283
1284 void Resolver::liveUndefines(std::vector<const char*>& undefs)
1285 {
1286 StringSet undefSet;
1287 // search all live atoms for references that are unbound
1288 for (std::vector<const ld::Atom*>::const_iterator it=_atoms.begin(); it != _atoms.end(); ++it) {
1289 const ld::Atom* atom = *it;
1290 if ( ! atom->live() )
1291 continue;
1292 for (ld::Fixup::iterator fit=atom->fixupsBegin(); fit != atom->fixupsEnd(); ++fit) {
1293 switch ( (ld::Fixup::TargetBinding)fit->binding ) {
1294 case ld::Fixup::bindingByNameUnbound:
1295 assert(0 && "should not be by-name this late");
1296 undefSet.insert(fit->u.name);
1297 break;
1298 case ld::Fixup::bindingsIndirectlyBound:
1299 if ( _internal.indirectBindingTable[fit->u.bindingIndex] == NULL ) {
1300 undefSet.insert(_symbolTable.indirectName(fit->u.bindingIndex));
1301 }
1302 break;
1303 case ld::Fixup::bindingByContentBound:
1304 case ld::Fixup::bindingNone:
1305 case ld::Fixup::bindingDirectlyBound:
1306 break;
1307 }
1308 }
1309 }
1310 // look for any initial undefines that are still undefined
1311 for (Options::UndefinesIterator uit=_options.initialUndefinesBegin(); uit != _options.initialUndefinesEnd(); ++uit) {
1312 if ( ! _symbolTable.hasName(*uit) ) {
1313 undefSet.insert(*uit);
1314 }
1315 }
1316
1317 // copy set to vector
1318 for (StringSet::const_iterator it=undefSet.begin(); it != undefSet.end(); ++it) {
1319 undefs.push_back(*it);
1320 }
1321 }
1322
1323
1324
1325 // <rdar://problem/8252819> warn when .objc_class_name_* symbol missing
1326 class ExportedObjcClass
1327 {
1328 public:
1329 ExportedObjcClass(const Options& opt) : _options(opt) {}
1330
1331 bool operator()(const char* name) const {
1332 if ( (strncmp(name, ".objc_class_name_", 17) == 0) && _options.shouldExport(name) ) {
1333 warning("ignoring undefined symbol %s from -exported_symbols_list", name);
1334 return true;
1335 }
1336 const char* s = strstr(name, "CLASS_$_");
1337 if ( s != NULL ) {
1338 char temp[strlen(name)+16];
1339 strcpy(temp, ".objc_class_name_");
1340 strcat(temp, &s[8]);
1341 if ( _options.wasRemovedExport(temp) ) {
1342 warning("ignoring undefined symbol %s from -exported_symbols_list", temp);
1343 return true;
1344 }
1345 }
1346 return false;
1347 }
1348 private:
1349 const Options& _options;
1350 };
1351
1352
1353 // temp hack for undefined aliases
1354 class UndefinedAlias
1355 {
1356 public:
1357 UndefinedAlias(const Options& opt) : _aliases(opt.cmdLineAliases()) {}
1358
1359 bool operator()(const char* name) const {
1360 for (std::vector<Options::AliasPair>::const_iterator it=_aliases.begin(); it != _aliases.end(); ++it) {
1361 if ( strcmp(it->realName, name) == 0 ) {
1362 warning("undefined base symbol '%s' for alias '%s'", name, it->alias);
1363 return true;
1364 }
1365 }
1366 return false;
1367 }
1368 private:
1369 const std::vector<Options::AliasPair>& _aliases;
1370 };
1371
1372
1373
1374 static const char* pathLeafName(const char* path)
1375 {
1376 const char* shortPath = strrchr(path, '/');
1377 if ( shortPath == NULL )
1378 return path;
1379 else
1380 return &shortPath[1];
1381 }
1382
1383 bool Resolver::printReferencedBy(const char* name, SymbolTable::IndirectBindingSlot slot)
1384 {
1385 unsigned foundReferenceCount = 0;
1386 for (std::vector<const ld::Atom*>::const_iterator it=_atoms.begin(); it != _atoms.end(); ++it) {
1387 const ld::Atom* atom = *it;
1388 for (ld::Fixup::iterator fit=atom->fixupsBegin(); fit != atom->fixupsEnd(); ++fit) {
1389 if ( fit->binding == ld::Fixup::bindingsIndirectlyBound ) {
1390 if ( fit->u.bindingIndex == slot ) {
1391 if ( atom->contentType() == ld::Atom::typeNonLazyPointer ) {
1392 const ld::Atom* existingAtom;
1393 unsigned int nlSlot = _symbolTable.findSlotForReferences(atom, &existingAtom);
1394 if ( printReferencedBy(name, nlSlot) )
1395 ++foundReferenceCount;
1396 }
1397 else if ( atom->contentType() == ld::Atom::typeCFI ) {
1398 fprintf(stderr, " Dwarf Exception Unwind Info (__eh_frame) in %s\n", pathLeafName(atom->file()->path()));
1399 ++foundReferenceCount;
1400 }
1401 else {
1402 fprintf(stderr, " %s in %s\n", _options.demangleSymbol(atom->name()), pathLeafName(atom->file()->path()));
1403 ++foundReferenceCount;
1404 break; // if undefined used twice in a function, only show first
1405 }
1406 }
1407 }
1408 }
1409 if ( foundReferenceCount > 6 ) {
1410 fprintf(stderr, " ...\n");
1411 break; // only show first six uses of undefined symbol
1412 }
1413 }
1414 return (foundReferenceCount != 0);
1415 }
1416
1417 void Resolver::checkUndefines(bool force)
1418 {
1419 // when using LTO, undefines are checked after bitcode is optimized
1420 if ( _haveLLVMObjs && !force )
1421 return;
1422
1423 // error out on any remaining undefines
1424 bool doPrint = true;
1425 bool doError = true;
1426 switch ( _options.undefinedTreatment() ) {
1427 case Options::kUndefinedError:
1428 break;
1429 case Options::kUndefinedDynamicLookup:
1430 doError = false;
1431 break;
1432 case Options::kUndefinedWarning:
1433 doError = false;
1434 break;
1435 case Options::kUndefinedSuppress:
1436 doError = false;
1437 doPrint = false;
1438 break;
1439 }
1440 std::vector<const char*> unresolvableUndefines;
1441 if ( _options.deadCodeStrip() )
1442 this->liveUndefines(unresolvableUndefines);
1443 else if( _haveLLVMObjs )
1444 this->remainingUndefines(unresolvableUndefines); // <rdar://problem/10052396> LTO may have eliminated need for some undefines
1445 else
1446 _symbolTable.undefines(unresolvableUndefines);
1447
1448 // <rdar://problem/8252819> assert when .objc_class_name_* symbol missing
1449 if ( _options.hasExportMaskList() ) {
1450 unresolvableUndefines.erase(std::remove_if(unresolvableUndefines.begin(), unresolvableUndefines.end(), ExportedObjcClass(_options)), unresolvableUndefines.end());
1451 }
1452
1453 // hack to temporarily make missing aliases a warning
1454 if ( _options.haveCmdLineAliases() ) {
1455 unresolvableUndefines.erase(std::remove_if(unresolvableUndefines.begin(), unresolvableUndefines.end(), UndefinedAlias(_options)), unresolvableUndefines.end());
1456 }
1457
1458 const int unresolvableCount = unresolvableUndefines.size();
1459 int unresolvableExportsCount = 0;
1460 if ( unresolvableCount != 0 ) {
1461 if ( doPrint ) {
1462 if ( _options.printArchPrefix() )
1463 fprintf(stderr, "Undefined symbols for architecture %s:\n", _options.architectureName());
1464 else
1465 fprintf(stderr, "Undefined symbols:\n");
1466 for (int i=0; i < unresolvableCount; ++i) {
1467 const char* name = unresolvableUndefines[i];
1468 unsigned int slot = _symbolTable.findSlotForName(name);
1469 fprintf(stderr, " \"%s\", referenced from:\n", _options.demangleSymbol(name));
1470 // scan all atoms for references
1471 bool foundAtomReference = printReferencedBy(name, slot);
1472 // scan command line options
1473 if ( !foundAtomReference ) {
1474 // might be from -init command line option
1475 if ( (_options.initFunctionName() != NULL) && (strcmp(name, _options.initFunctionName()) == 0) ) {
1476 fprintf(stderr, " -init command line option\n");
1477 }
1478 // or might be from exported symbol option
1479 else if ( _options.hasExportMaskList() && _options.shouldExport(name) ) {
1480 fprintf(stderr, " -exported_symbol[s_list] command line option\n");
1481 }
1482 // or might be from re-exported symbol option
1483 else if ( _options.hasReExportList() && _options.shouldReExport(name) ) {
1484 fprintf(stderr, " -reexported_symbols_list command line option\n");
1485 }
1486 else if ( (_options.outputKind() == Options::kDynamicExecutable)
1487 && (_options.entryName() != NULL) && (strcmp(name, _options.entryName()) == 0) ) {
1488 fprintf(stderr, " implicit entry/start for main executable\n");
1489 }
1490 else {
1491 bool isInitialUndefine = false;
1492 for (Options::UndefinesIterator uit=_options.initialUndefinesBegin(); uit != _options.initialUndefinesEnd(); ++uit) {
1493 if ( strcmp(*uit, name) == 0 ) {
1494 isInitialUndefine = true;
1495 break;
1496 }
1497 }
1498 if ( isInitialUndefine )
1499 fprintf(stderr, " -u command line option\n");
1500 }
1501 ++unresolvableExportsCount;
1502 }
1503 // be helpful and check for typos
1504 bool printedStart = false;
1505 for (SymbolTable::byNameIterator sit=_symbolTable.begin(); sit != _symbolTable.end(); sit++) {
1506 const ld::Atom* atom = *sit;
1507 if ( (atom != NULL) && (atom->symbolTableInclusion() == ld::Atom::symbolTableIn) && (strstr(atom->name(), name) != NULL) ) {
1508 if ( ! printedStart ) {
1509 fprintf(stderr, " (maybe you meant: %s", atom->name());
1510 printedStart = true;
1511 }
1512 else {
1513 fprintf(stderr, ", %s ", atom->name());
1514 }
1515 }
1516 }
1517 if ( printedStart )
1518 fprintf(stderr, ")\n");
1519 // <rdar://problem/8989530> Add comment to error message when __ZTV symbols are undefined
1520 if ( strncmp(name, "__ZTV", 5) == 0 ) {
1521 fprintf(stderr, " NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.\n");
1522 }
1523 }
1524 }
1525 if ( doError )
1526 throw "symbol(s) not found";
1527 }
1528
1529 }
1530
1531
1532
1533 void Resolver::checkDylibSymbolCollisions()
1534 {
1535 for (SymbolTable::byNameIterator it=_symbolTable.begin(); it != _symbolTable.end(); it++) {
1536 const ld::Atom* atom = *it;
1537 if ( atom == NULL )
1538 continue;
1539 if ( atom->scope() == ld::Atom::scopeGlobal ) {
1540 // <rdar://problem/5048861> No warning about tentative definition conflicting with dylib definition
1541 // for each tentative definition in symbol table look for dylib that exports same symbol name
1542 if ( atom->definition() == ld::Atom::definitionTentative ) {
1543 _inputFiles.searchLibraries(atom->name(), true, false, false, *this);
1544 }
1545 // record any overrides of weak symbols in any linked dylib
1546 if ( (atom->definition() == ld::Atom::definitionRegular) && (atom->symbolTableInclusion() == ld::Atom::symbolTableIn) ) {
1547 if ( _inputFiles.searchWeakDefInDylib(atom->name()) )
1548 (const_cast<ld::Atom*>(atom))->setOverridesDylibsWeakDef();
1549 }
1550 }
1551 }
1552 }
1553
1554
1555 const ld::Atom* Resolver::entryPoint(bool searchArchives)
1556 {
1557 const char* symbolName = NULL;
1558 bool makingDylib = false;
1559 switch ( _options.outputKind() ) {
1560 case Options::kDynamicExecutable:
1561 case Options::kStaticExecutable:
1562 case Options::kDyld:
1563 case Options::kPreload:
1564 symbolName = _options.entryName();
1565 break;
1566 case Options::kDynamicLibrary:
1567 symbolName = _options.initFunctionName();
1568 makingDylib = true;
1569 break;
1570 case Options::kObjectFile:
1571 case Options::kDynamicBundle:
1572 case Options::kKextBundle:
1573 return NULL;
1574 break;
1575 }
1576 if ( symbolName != NULL ) {
1577 SymbolTable::IndirectBindingSlot slot = _symbolTable.findSlotForName(symbolName);
1578 if ( (_internal.indirectBindingTable[slot] == NULL) && searchArchives ) {
1579 // <rdar://problem/7043256> ld64 can not find a -e entry point from an archive
1580 _inputFiles.searchLibraries(symbolName, false, true, false, *this);
1581 }
1582 if ( _internal.indirectBindingTable[slot] == NULL ) {
1583 if ( strcmp(symbolName, "start") == 0 )
1584 throwf("entry point (%s) undefined. Usually in crt1.o", symbolName);
1585 else
1586 throwf("entry point (%s) undefined.", symbolName);
1587 }
1588 else if ( _internal.indirectBindingTable[slot]->definition() == ld::Atom::definitionProxy ) {
1589 if ( makingDylib )
1590 throwf("-init function (%s) found in linked dylib, must be in dylib being linked", symbolName);
1591 }
1592 return _internal.indirectBindingTable[slot];
1593 }
1594 return NULL;
1595 }
1596
1597
1598 void Resolver::fillInHelpersInInternalState()
1599 {
1600 // look up well known atoms
1601 bool needsStubHelper = true;
1602 switch ( _options.outputKind() ) {
1603 case Options::kDynamicExecutable:
1604 case Options::kDynamicLibrary:
1605 case Options::kDynamicBundle:
1606 needsStubHelper = true;
1607 break;
1608 case Options::kDyld:
1609 case Options::kKextBundle:
1610 case Options::kObjectFile:
1611 case Options::kStaticExecutable:
1612 case Options::kPreload:
1613 needsStubHelper = false;
1614 break;
1615 }
1616
1617 _internal.classicBindingHelper = NULL;
1618 if ( needsStubHelper && !_options.makeCompressedDyldInfo() ) {
1619 // "dyld_stub_binding_helper" comes from .o file, so should already exist in symbol table
1620 if ( _symbolTable.hasName("dyld_stub_binding_helper") ) {
1621 SymbolTable::IndirectBindingSlot slot = _symbolTable.findSlotForName("dyld_stub_binding_helper");
1622 _internal.classicBindingHelper = _internal.indirectBindingTable[slot];
1623 }
1624 }
1625
1626 _internal.lazyBindingHelper = NULL;
1627 if ( _options.usingLazyDylibLinking() ) {
1628 // "dyld_lazy_dylib_stub_binding_helper" comes from lazydylib1.o file, so should already exist in symbol table
1629 if ( _symbolTable.hasName("dyld_lazy_dylib_stub_binding_helper") ) {
1630 SymbolTable::IndirectBindingSlot slot = _symbolTable.findSlotForName("dyld_lazy_dylib_stub_binding_helper");
1631 _internal.lazyBindingHelper = _internal.indirectBindingTable[slot];
1632 }
1633 if ( _internal.lazyBindingHelper == NULL )
1634 throw "symbol dyld_lazy_dylib_stub_binding_helper not defined (usually in lazydylib1.o)";
1635 }
1636
1637 _internal.compressedFastBinderProxy = NULL;
1638 if ( needsStubHelper && _options.makeCompressedDyldInfo() ) {
1639 // "dyld_stub_binder" comes from libSystem.dylib so will need to manually resolve
1640 if ( !_symbolTable.hasName("dyld_stub_binder") ) {
1641 _inputFiles.searchLibraries("dyld_stub_binder", true, false, false, *this);
1642 }
1643 if ( _symbolTable.hasName("dyld_stub_binder") ) {
1644 SymbolTable::IndirectBindingSlot slot = _symbolTable.findSlotForName("dyld_stub_binder");
1645 _internal.compressedFastBinderProxy = _internal.indirectBindingTable[slot];
1646 }
1647 if ( _internal.compressedFastBinderProxy == NULL ) {
1648 if ( _options.undefinedTreatment() != Options::kUndefinedError ) {
1649 // make proxy
1650 _internal.compressedFastBinderProxy = new UndefinedProxyAtom("dyld_stub_binder");
1651 this->doAtom(*_internal.compressedFastBinderProxy);
1652 }
1653 }
1654 }
1655 }
1656
1657
1658 void Resolver::fillInInternalState()
1659 {
1660 // store atoms into their final section
1661 for (std::vector<const ld::Atom*>::iterator it = _atoms.begin(); it != _atoms.end(); ++it) {
1662 _internal.addAtom(**it);
1663 }
1664
1665 // <rdar://problem/7783918> make sure there is a __text section so that codesigning works
1666 if ( (_options.outputKind() == Options::kDynamicLibrary) || (_options.outputKind() == Options::kDynamicBundle) )
1667 _internal.getFinalSection(*new ld::Section("__TEXT", "__text", ld::Section::typeCode));
1668 }
1669
1670 void Resolver::fillInEntryPoint()
1671 {
1672 _internal.entryPoint = this->entryPoint(true);
1673 }
1674
1675 void Resolver::syncAliases()
1676 {
1677 if ( !_haveAliases || (_options.outputKind() == Options::kObjectFile) )
1678 return;
1679
1680 // Set attributes of alias to match its found target
1681 for (std::vector<const ld::Atom*>::iterator it = _atoms.begin(); it != _atoms.end(); ++it) {
1682 const ld::Atom* atom = *it;
1683 if ( atom->section().type() == ld::Section::typeTempAlias ) {
1684 assert(atom->fixupsBegin() != atom->fixupsEnd());
1685 for (ld::Fixup::iterator fit = atom->fixupsBegin(); fit != atom->fixupsEnd(); ++fit) {
1686 const ld::Atom* target;
1687 ld::Atom::Scope scope;
1688 assert(fit->kind == ld::Fixup::kindNoneFollowOn);
1689 switch ( fit->binding ) {
1690 case ld::Fixup::bindingByNameUnbound:
1691 break;
1692 case ld::Fixup::bindingsIndirectlyBound:
1693 target = _internal.indirectBindingTable[fit->u.bindingIndex];
1694 assert(target != NULL);
1695 scope = atom->scope();
1696 (const_cast<Atom*>(atom))->setAttributesFromAtom(*target);
1697 // alias has same attributes as target, except for scope
1698 (const_cast<Atom*>(atom))->setScope(scope);
1699 break;
1700 default:
1701 assert(0 && "internal error: unexpected alias binding");
1702 }
1703 }
1704 }
1705 }
1706 }
1707
1708 void Resolver::removeCoalescedAwayAtoms()
1709 {
1710 const bool log = false;
1711 if ( log ) {
1712 fprintf(stderr, "removeCoalescedAwayAtoms() starts with %lu atoms\n", _atoms.size());
1713 }
1714 _atoms.erase(std::remove_if(_atoms.begin(), _atoms.end(), AtomCoalescedAway()), _atoms.end());
1715 if ( log ) {
1716 fprintf(stderr, "removeCoalescedAwayAtoms() after removing coalesced atoms, %lu remain\n", _atoms.size());
1717 for (std::vector<const ld::Atom*>::const_iterator it=_atoms.begin(); it != _atoms.end(); ++it) {
1718 fprintf(stderr, " atom=%p %s\n", *it, (*it)->name());
1719 }
1720 }
1721 }
1722
1723 void Resolver::linkTimeOptimize()
1724 {
1725 // only do work here if some llvm obj files where loaded
1726 if ( ! _haveLLVMObjs )
1727 return;
1728
1729 // <rdar://problem/15314161> LTO: Symbol multiply defined error should specify exactly where the symbol is found
1730 _symbolTable.checkDuplicateSymbols();
1731
1732 // run LLVM lto code-gen
1733 lto::OptimizeOptions optOpt;
1734 optOpt.outputFilePath = _options.outputFilePath();
1735 optOpt.tmpObjectFilePath = _options.tempLtoObjectPath();
1736 optOpt.ltoCachePath = _options.ltoCachePath();
1737 optOpt.ltoPruneInterval = _options.ltoPruneInterval();
1738 optOpt.ltoPruneAfter = _options.ltoPruneAfter();
1739 optOpt.ltoMaxCacheSize = _options.ltoMaxCacheSize();
1740 optOpt.preserveAllGlobals = _options.allGlobalsAreDeadStripRoots() || _options.hasExportRestrictList();
1741 optOpt.verbose = _options.verbose();
1742 optOpt.saveTemps = _options.saveTempFiles();
1743 optOpt.ltoCodegenOnly = _options.ltoCodegenOnly();
1744 optOpt.pie = _options.positionIndependentExecutable();
1745 optOpt.mainExecutable = _options.linkingMainExecutable();;
1746 optOpt.staticExecutable = (_options.outputKind() == Options::kStaticExecutable);
1747 optOpt.relocatable = (_options.outputKind() == Options::kObjectFile);
1748 optOpt.allowTextRelocs = _options.allowTextRelocs();
1749 optOpt.linkerDeadStripping = _options.deadCodeStrip();
1750 optOpt.needsUnwindInfoSection = _options.needsUnwindInfoSection();
1751 optOpt.keepDwarfUnwind = _options.keepDwarfUnwind();
1752 optOpt.verboseOptimizationHints = _options.verboseOptimizationHints();
1753 optOpt.armUsesZeroCostExceptions = _options.armUsesZeroCostExceptions();
1754 optOpt.simulator = _options.targetIOSSimulator();
1755 optOpt.ignoreMismatchPlatform = ((_options.outputKind() == Options::kPreload) || (_options.outputKind() == Options::kStaticExecutable));
1756 optOpt.bitcodeBundle = _options.bundleBitcode();
1757 optOpt.maxDefaultCommonAlignment = _options.maxDefaultCommonAlign();
1758 optOpt.arch = _options.architecture();
1759 optOpt.mcpu = _options.mcpuLTO();
1760 optOpt.platform = _options.platform();
1761 optOpt.minOSVersion = _options.minOSversion();
1762 optOpt.llvmOptions = &_options.llvmOptions();
1763 optOpt.initialUndefines = &_options.initialUndefines();
1764
1765 std::vector<const ld::Atom*> newAtoms;
1766 std::vector<const char*> additionalUndefines;
1767 if ( ! lto::optimize(_atoms, _internal, optOpt, *this, newAtoms, additionalUndefines) )
1768 return; // if nothing done
1769 _ltoCodeGenFinished = true;
1770
1771 // add all newly created atoms to _atoms and update symbol table
1772 for(std::vector<const ld::Atom*>::iterator it = newAtoms.begin(); it != newAtoms.end(); ++it)
1773 this->doAtom(**it);
1774
1775 // some atoms might have been optimized way (marked coalesced), remove them
1776 this->removeCoalescedAwayAtoms();
1777
1778 // run through all atoms again and make sure newly codegened atoms have references bound
1779 for (std::vector<const ld::Atom*>::const_iterator it=_atoms.begin(); it != _atoms.end(); ++it)
1780 this->convertReferencesToIndirect(**it);
1781
1782 // adjust section of any new
1783 for (std::vector<const AliasAtom*>::const_iterator it=_aliasesFromCmdLine.begin(); it != _aliasesFromCmdLine.end(); ++it) {
1784 const AliasAtom* aliasAtom = *it;
1785 // update fields in AliasAtom to match newly constructed mach-o atom
1786 aliasAtom->setFinalAliasOf();
1787 }
1788
1789 // <rdar://problem/14609792> add any auto-link libraries requested by LTO output to dylibs to search
1790 _inputFiles.addLinkerOptionLibraries(_internal, *this);
1791 _inputFiles.createIndirectDylibs();
1792
1793 // resolve new undefines (e.g calls to _malloc and _memcpy that llvm compiler conjures up)
1794 for(std::vector<const char*>::iterator uit = additionalUndefines.begin(); uit != additionalUndefines.end(); ++uit) {
1795 const char *targetName = *uit;
1796 // these symbols may or may not already be in linker's symbol table
1797 if ( ! _symbolTable.hasName(targetName) ) {
1798 _inputFiles.searchLibraries(targetName, true, true, false, *this);
1799 }
1800 }
1801
1802 // if -dead_strip on command line
1803 if ( _options.deadCodeStrip() ) {
1804 // clear liveness bit
1805 for (std::vector<const ld::Atom*>::const_iterator it=_atoms.begin(); it != _atoms.end(); ++it) {
1806 (const_cast<ld::Atom*>(*it))->setLive((*it)->dontDeadStrip());
1807 }
1808 // and re-compute dead code
1809 this->deadStripOptimize(true);
1810 }
1811
1812 // <rdar://problem/12386559> if -exported_symbols_list on command line, re-force scope
1813 if ( _options.hasExportMaskList() ) {
1814 for (std::vector<const ld::Atom*>::const_iterator it=_atoms.begin(); it != _atoms.end(); ++it) {
1815 const ld::Atom* atom = *it;
1816 if ( atom->scope() == ld::Atom::scopeGlobal ) {
1817 if ( !_options.shouldExport(atom->name()) ) {
1818 (const_cast<ld::Atom*>(atom))->setScope(ld::Atom::scopeLinkageUnit);
1819 }
1820 }
1821 }
1822 }
1823
1824 if ( _options.outputKind() == Options::kObjectFile ) {
1825 // if -r mode, add proxies for new undefines (e.g. ___stack_chk_fail)
1826 this->resolveUndefines();
1827 }
1828 else {
1829 // last chance to check for undefines
1830 this->resolveUndefines();
1831 this->checkUndefines(true);
1832
1833 // check new code does not override some dylib
1834 this->checkDylibSymbolCollisions();
1835 }
1836 }
1837
1838
1839 void Resolver::tweakWeakness()
1840 {
1841 // <rdar://problem/7977374> Add command line options to control symbol weak-def bit on exported symbols
1842 if ( _options.hasWeakBitTweaks() ) {
1843 for (std::vector<ld::Internal::FinalSection*>::iterator sit = _internal.sections.begin(); sit != _internal.sections.end(); ++sit) {
1844 ld::Internal::FinalSection* sect = *sit;
1845 for (std::vector<const ld::Atom*>::iterator ait = sect->atoms.begin(); ait != sect->atoms.end(); ++ait) {
1846 const ld::Atom* atom = *ait;
1847 if ( atom->definition() != ld::Atom::definitionRegular )
1848 continue;
1849 const char* name = atom->name();
1850 if ( atom->scope() == ld::Atom::scopeGlobal ) {
1851 if ( atom->combine() == ld::Atom::combineNever ) {
1852 if ( _options.forceWeak(name) )
1853 (const_cast<ld::Atom*>(atom))->setCombine(ld::Atom::combineByName);
1854 }
1855 else if ( atom->combine() == ld::Atom::combineByName ) {
1856 if ( _options.forceNotWeak(name) )
1857 (const_cast<ld::Atom*>(atom))->setCombine(ld::Atom::combineNever);
1858 }
1859 }
1860 else {
1861 if ( _options.forceWeakNonWildCard(name) )
1862 warning("cannot force to be weak, non-external symbol %s", name);
1863 else if ( _options.forceNotWeakNonWildcard(name) )
1864 warning("cannot force to be not-weak, non-external symbol %s", name);
1865 }
1866 }
1867 }
1868 }
1869 }
1870
1871 void Resolver::buildArchivesList()
1872 {
1873 // Determine which archives were linked and update the internal state.
1874 _inputFiles.archives(_internal);
1875 }
1876
1877 void Resolver::dumpAtoms()
1878 {
1879 fprintf(stderr, "Resolver all atoms:\n");
1880 for (std::vector<const ld::Atom*>::const_iterator it=_atoms.begin(); it != _atoms.end(); ++it) {
1881 const ld::Atom* atom = *it;
1882 fprintf(stderr, " %p name=%s, def=%d\n", atom, atom->name(), atom->definition());
1883 }
1884 }
1885
1886 void Resolver::resolve()
1887 {
1888 this->initializeState();
1889 this->buildAtomList();
1890 this->addInitialUndefines();
1891 this->fillInHelpersInInternalState();
1892 this->resolveUndefines();
1893 this->deadStripOptimize();
1894 this->checkUndefines();
1895 this->checkDylibSymbolCollisions();
1896 this->syncAliases();
1897 this->removeCoalescedAwayAtoms();
1898 this->fillInEntryPoint();
1899 this->linkTimeOptimize();
1900 this->fillInInternalState();
1901 this->tweakWeakness();
1902 _symbolTable.checkDuplicateSymbols();
1903 this->buildArchivesList();
1904 }
1905
1906
1907
1908 } // namespace tool
1909 } // namespace ld
1910
1911
1912