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