1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-*
3 * Copyright (c) 2009-2010 Apple Inc. All rights reserved.
5 * @APPLE_LICENSE_HEADER_START@
7 * This file contains Original Code and/or Modifications of Original Code
8 * as defined in and that are subject to the Apple Public Source License
9 * Version 2.0 (the 'License'). You may not use this file except in
10 * compliance with the License. Please obtain a copy of the License at
11 * http://www.opensource.apple.com/apsl/ and read it before using this
14 * The Original Code and all software distributed under the License are
15 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
19 * Please see the License for the specific language governing rights and
20 * limitations under the License.
22 * @APPLE_LICENSE_HEADER_END@
27 #include <sys/types.h>
30 #include <sys/sysctl.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>
40 #include <mach-o/dyld.h>
41 #include <mach-o/fat.h>
51 #include <AvailabilityMacros.h>
56 #include "Bitcode.hpp"
57 #include "InputFiles.h"
58 #include "SymbolTable.h"
60 #include "parsers/lto_file.h"
68 // An ExportAtom has no content. It exists so that the linker can track which imported
69 // symbols came from which dynamic libraries.
71 class UndefinedProxyAtom
: public ld::Atom
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)),
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
) { }
90 virtual ~UndefinedProxyAtom() {}
94 static ld::Section _s_section
;
97 ld::Section
UndefinedProxyAtom::_s_section("__TEXT", "__import", ld::Section::typeImportProxies
, true);
102 class AliasAtom
: public ld::Atom
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()),
112 _fixup(0, ld::Fixup::k1of1
, ld::Fixup::kindNoneFollowOn
, &target
) { }
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
; }
134 void setFinalAliasOf() const {
135 (const_cast<AliasAtom
*>(this))->setAttributesFromAtom(_aliasOf
);
136 (const_cast<AliasAtom
*>(this))->setScope(ld::Atom::scopeGlobal
);
141 const ld::Atom
& _aliasOf
;
147 class SectionBoundaryAtom
: public ld::Atom
150 static SectionBoundaryAtom
* makeSectionBoundaryAtom(const char* name
, bool start
, const char* segSectName
);
151 static SectionBoundaryAtom
* makeOldSectionBoundaryAtom(const char* name
, bool start
);
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; }
163 SectionBoundaryAtom(const char* nm
, const ld::Section
& sect
,
164 ld::Atom::ContentType cont
) :
166 ld::Atom::definitionRegular
,
167 ld::Atom::combineNever
,
168 ld::Atom::scopeLinkageUnit
,
170 ld::Atom::symbolTableNotIn
,
171 false, false, true, ld::Atom::Alignment(0)),
177 SectionBoundaryAtom
* SectionBoundaryAtom::makeSectionBoundaryAtom(const char* name
, bool start
, const char* segSectName
)
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
);
188 strlcpy(segName
, segSectName
, segNameLen
+1);
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
));
194 SectionBoundaryAtom
* SectionBoundaryAtom::makeOldSectionBoundaryAtom(const char* name
, bool start
)
196 // e.g. __DATA__bss__begin
198 strlcpy(segName
, name
, 7);
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
));
211 class SegmentBoundaryAtom
: public ld::Atom
214 static SegmentBoundaryAtom
* makeSegmentBoundaryAtom(const char* name
, bool start
, const char* segName
);
215 static SegmentBoundaryAtom
* makeOldSegmentBoundaryAtom(const char* name
, bool start
);
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; }
227 SegmentBoundaryAtom(const char* nm
, const ld::Section
& sect
,
228 ld::Atom::ContentType cont
) :
230 ld::Atom::definitionRegular
,
231 ld::Atom::combineNever
,
232 ld::Atom::scopeLinkageUnit
,
234 ld::Atom::symbolTableNotIn
,
235 false, false, true, ld::Atom::Alignment(0)),
241 SegmentBoundaryAtom
* SegmentBoundaryAtom::makeSegmentBoundaryAtom(const char* name
, bool start
, const char* segName
)
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
);
249 const ld::Section
* section
= new ld::Section(segName
, "__start", ld::Section::typeFirstSection
, true);
250 return new SegmentBoundaryAtom(name
, *section
, ld::Atom::typeSectionStart
);
253 const ld::Section
* section
= new ld::Section(segName
, "__end", ld::Section::typeLastSection
, true);
254 return new SegmentBoundaryAtom(name
, *section
, ld::Atom::typeSectionEnd
);
258 SegmentBoundaryAtom
* SegmentBoundaryAtom::makeOldSegmentBoundaryAtom(const char* name
, bool start
)
260 // e.g. __DATA__begin
262 strlcpy(temp
, name
, 7);
263 char* segName
= strdup(temp
);
265 warning("grandfathering in old symbol '%s' as alias for 'segment$%s$%s'", name
, start
? "start" : "end", segName
);
268 const ld::Section
* section
= new ld::Section(segName
, "__start", ld::Section::typeFirstSection
, true);
269 return new SegmentBoundaryAtom(name
, *section
, ld::Atom::typeSectionStart
);
272 const ld::Section
* section
= new ld::Section(segName
, "__end", ld::Section::typeLastSection
, true);
273 return new SegmentBoundaryAtom(name
, *section
, ld::Atom::typeSectionEnd
);
277 void Resolver::initializeState()
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
;
285 _internal
.cpuSubType
= _options
.subArchitecture();
286 _internal
.minOSVersion
= _options
.minOSversion();
287 _internal
.derivedPlatformLoadCommand
= 0;
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");
298 void Resolver::buildAtomList()
300 // each input files contributes initial atoms
301 _atoms
.reserve(1024);
302 _inputFiles
.forEachInitialAtom(*this, _internal
);
304 _completedInitialObjectFiles
= true;
306 //_symbolTable.printStatistics();
310 void Resolver::doLinkerOption(const std::vector
<const char*>& linkerOption
, const char* fileName
)
312 if ( linkerOption
.size() == 1 ) {
313 const char* lo1
= linkerOption
.front();
314 if ( strncmp(lo1
, "-l", 2) == 0 ) {
315 _internal
.linkerOptionLibraries
.insert(&lo1
[2]);
318 warning("unknown linker option from object file ignored: '%s' in %s", lo1
, fileName
);
321 else if ( linkerOption
.size() == 2 ) {
322 const char* lo2a
= linkerOption
[0];
323 const char* lo2b
= linkerOption
[1];
324 if ( strcmp(lo2a
, "-framework") == 0 ) {
325 _internal
.linkerOptionFrameworks
.insert(lo2b
);
328 warning("unknown linker option from object file ignored: '%s' '%s' from %s", lo2a
, lo2b
, fileName
);
332 warning("unknown linker option from object file ignored, starting with: '%s' from %s", linkerOption
.front(), fileName
);
336 static void userReadableSwiftVersion(uint8_t value
, char versionString
[64])
340 strcpy(versionString
, "1.0");
343 strcpy(versionString
, "1.1");
346 strcpy(versionString
, "2.0");
349 sprintf(versionString
, "unknown ABI version 0x%02X", value
);
353 void Resolver::doFile(const ld::File
& file
)
355 const ld::relocatable::File
* objFile
= dynamic_cast<const ld::relocatable::File
*>(&file
);
356 const ld::dylib::File
* dylibFile
= dynamic_cast<const ld::dylib::File
*>(&file
);
358 if ( objFile
!= NULL
) {
359 // if file has linker options, process them
360 ld::relocatable::File::LinkerOptionsList
* lo
= objFile
->linkerOptions();
361 if ( lo
!= NULL
&& !_options
.ignoreAutoLink() ) {
362 for (relocatable::File::LinkerOptionsList::const_iterator it
=lo
->begin(); it
!= lo
->end(); ++it
) {
363 this->doLinkerOption(*it
, file
.path());
366 // Resolve bitcode section in the object file
367 if ( _options
.bundleBitcode() ) {
368 if ( objFile
->getBitcode() == NULL
) {
369 // No bitcode section, figure out if the object file comes from LTO/compiler static library
370 if (objFile
->sourceKind() != ld::relocatable::File::kSourceLTO
&&
371 objFile
->sourceKind() != ld::relocatable::File::kSourceCompilerArchive
) {
372 switch ( _options
.platform() ) {
373 case Options::kPlatformOSX
:
374 case Options::kPlatformUnknown
:
375 warning("all bitcode will be dropped because '%s' was built without bitcode. "
376 "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());
377 _internal
.filesWithBitcode
.clear();
378 _internal
.dropAllBitcode
= true;
380 case Options::kPlatformiOS
:
381 throwf("'%s' does not contain bitcode. "
382 "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());
384 case Options::kPlatformWatchOS
:
386 case Options::kPlatform_tvOS
:
388 throwf("'%s' does not contain bitcode. "
389 "You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE) or obtain an updated library from the vendor", file
.path());
394 // contains bitcode, check if it is just a marker
395 if ( objFile
->getBitcode()->isMarker() ) {
396 // if -bitcode_verify_bundle is used, check if all the object files participate in the linking have full bitcode embedded.
397 // error on any marker encountered.
398 if ( _options
.verifyBitcode() )
399 throwf("bitcode bundle could not be generated because '%s' was built without full bitcode. "
400 "All object files and libraries for bitcode must be generated from Xcode Archive or Install build",
402 // update the internal state that marker is encountered.
403 _internal
.embedMarkerOnly
= true;
404 _internal
.filesWithBitcode
.clear();
405 _internal
.dropAllBitcode
= true;
406 } else if ( !_internal
.dropAllBitcode
)
407 _internal
.filesWithBitcode
.push_back(objFile
);
411 // update which form of ObjC is being used
412 switch ( file
.objCConstraint() ) {
413 case ld::File::objcConstraintNone
:
415 case ld::File::objcConstraintRetainRelease
:
416 if ( _internal
.objcObjectConstraint
== ld::File::objcConstraintGC
)
417 throwf("%s built with incompatible Garbage Collection settings to link with previous .o files", file
.path());
418 if ( _options
.objcGcOnly() )
419 throwf("command line specified -objc_gc_only, but file is retain/release based: %s", file
.path());
420 if ( _options
.objcGc() )
421 throwf("command line specified -objc_gc, but file is retain/release based: %s", file
.path());
422 if ( !_options
.targetIOSSimulator() && (_internal
.objcObjectConstraint
!= ld::File::objcConstraintRetainReleaseForSimulator
) )
423 _internal
.objcObjectConstraint
= ld::File::objcConstraintRetainRelease
;
425 case ld::File::objcConstraintRetainReleaseOrGC
:
426 if ( _internal
.objcObjectConstraint
== ld::File::objcConstraintNone
)
427 _internal
.objcObjectConstraint
= ld::File::objcConstraintRetainReleaseOrGC
;
428 if ( _options
.targetIOSSimulator() )
429 warning("linking ObjC for iOS Simulator, but object file (%s) was compiled for MacOSX", file
.path());
431 case ld::File::objcConstraintGC
:
432 if ( _internal
.objcObjectConstraint
== ld::File::objcConstraintRetainRelease
)
433 throwf("%s built with incompatible Garbage Collection settings to link with previous .o files", file
.path());
434 _internal
.objcObjectConstraint
= ld::File::objcConstraintGC
;
435 if ( _options
.targetIOSSimulator() )
436 warning("linking ObjC for iOS Simulator, but object file (%s) was compiled for MacOSX", file
.path());
438 case ld::File::objcConstraintRetainReleaseForSimulator
:
439 if ( _internal
.objcObjectConstraint
== ld::File::objcConstraintNone
) {
440 if ( !_options
.targetIOSSimulator() && (_options
.outputKind() != Options::kObjectFile
) )
441 warning("ObjC object file (%s) was compiled for iOS Simulator, but linking for MacOSX", file
.path());
442 _internal
.objcObjectConstraint
= ld::File::objcConstraintRetainReleaseForSimulator
;
444 else if ( _internal
.objcObjectConstraint
!= ld::File::objcConstraintRetainReleaseForSimulator
) {
445 _internal
.objcObjectConstraint
= ld::File::objcConstraintRetainReleaseForSimulator
;
450 // verify all files use same version of Swift language
451 if ( file
.swiftVersion() != 0 ) {
452 if ( _internal
.swiftVersion
== 0 ) {
453 _internal
.swiftVersion
= file
.swiftVersion();
455 else if ( file
.swiftVersion() != _internal
.swiftVersion
) {
456 char fileVersion
[64];
457 char otherVersion
[64];
458 userReadableSwiftVersion(file
.swiftVersion(), fileVersion
);
459 userReadableSwiftVersion(_internal
.swiftVersion
, otherVersion
);
460 if ( file
.swiftVersion() > _internal
.swiftVersion
) {
461 throwf("%s compiled with newer version of Swift language (%s) than previous files (%s)",
462 file
.path(), fileVersion
, otherVersion
);
465 throwf("%s compiled with older version of Swift language (%s) than previous files (%s)",
466 file
.path(), fileVersion
, otherVersion
);
471 // in -r mode, if any .o files have dwarf then add UUID to output .o file
472 if ( objFile
->debugInfo() == ld::relocatable::File::kDebugInfoDwarf
)
473 _internal
.someObjectFileHasDwarf
= true;
475 // remember if any .o file did not have MH_SUBSECTIONS_VIA_SYMBOLS bit set
476 if ( ! objFile
->canScatterAtoms() )
477 _internal
.allObjectFilesScatterable
= false;
479 // update minOSVersion off all .o files
480 uint32_t objMinOS
= objFile
->minOSVersion();
482 _internal
.objectFileFoundWithNoVersion
= true;
484 uint32_t objPlatformLC
= objFile
->platformLoadCommand();
485 if ( (objPlatformLC
!= 0) && (_internal
.derivedPlatformLoadCommand
== 0) && (_options
.outputKind() == Options::kObjectFile
) )
486 _internal
.derivedPlatformLoadCommand
= objPlatformLC
;
488 if ( (_options
.outputKind() == Options::kObjectFile
) && (objMinOS
> _internal
.minOSVersion
) )
489 _internal
.minOSVersion
= objMinOS
;
491 // update cpu-sub-type
492 cpu_subtype_t nextObjectSubType
= file
.cpuSubType();
493 switch ( _options
.architecture() ) {
495 if ( _options
.subArchitecture() != nextObjectSubType
) {
496 if ( (_options
.subArchitecture() == CPU_SUBTYPE_ARM_ALL
) && _options
.forceCpuSubtypeAll() ) {
497 // hack to support gcc multillib build that tries to make sub-type-all slice
499 else if ( nextObjectSubType
== CPU_SUBTYPE_ARM_ALL
) {
500 warning("CPU_SUBTYPE_ARM_ALL subtype is deprecated: %s", file
.path());
502 else if ( _options
.allowSubArchitectureMismatches() ) {
503 //warning("object file %s was built for different arm sub-type (%d) than link command line (%d)",
504 // file.path(), nextObjectSubType, _options.subArchitecture());
507 throwf("object file %s was built for different arm sub-type (%d) than link command line (%d)",
508 file
.path(), nextObjectSubType
, _options
.subArchitecture());
514 _internal
.cpuSubType
= CPU_SUBTYPE_I386_ALL
;
517 case CPU_TYPE_X86_64
:
518 if ( _options
.subArchitecture() != nextObjectSubType
) {
519 if ( _options
.allowSubArchitectureMismatches() ) {
520 warning("object file %s was built for different x86_64 sub-type (%d) than link command line (%d)",
521 file
.path(), nextObjectSubType
, _options
.subArchitecture());
524 throwf("object file %s was built for different x86_64 sub-type (%d) than link command line (%d)",
525 file
.path(), nextObjectSubType
, _options
.subArchitecture());
531 if ( dylibFile
!= NULL
) {
532 // Check dylib for bitcode, if the library install path is relative path or @rpath, it has to contain bitcode
533 if ( _options
.bundleBitcode() ) {
534 bool isSystemFramework
= ( dylibFile
->installPath() != NULL
) && ( dylibFile
->installPath()[0] == '/' );
535 if ( dylibFile
->getBitcode() == NULL
&& !isSystemFramework
) {
536 // Check if the dylib is from toolchain by checking the path
537 char tcLibPath
[PATH_MAX
];
538 char ldPath
[PATH_MAX
];
539 char tempPath
[PATH_MAX
];
540 uint32_t bufSize
= PATH_MAX
;
541 // toolchain library path should pointed to *.xctoolchain/usr/lib
542 if ( _NSGetExecutablePath(ldPath
, &bufSize
) != -1 ) {
543 if ( realpath(ldPath
, tempPath
) != NULL
) {
544 char* lastSlash
= strrchr(tempPath
, '/');
545 if ( lastSlash
!= NULL
)
546 strcpy(lastSlash
, "/../lib");
549 // Compare toolchain library path to the dylib path
550 if ( realpath(tempPath
, tcLibPath
) == NULL
||
551 realpath(dylibFile
->path(), tempPath
) == NULL
||
552 strncmp(tcLibPath
, tempPath
, strlen(tcLibPath
)) != 0 ) {
553 switch ( _options
.platform() ) {
554 case Options::kPlatformOSX
:
555 case Options::kPlatformUnknown
:
556 warning("all bitcode will be dropped because '%s' was built without bitcode. "
557 "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());
558 _internal
.filesWithBitcode
.clear();
559 _internal
.dropAllBitcode
= true;
561 case Options::kPlatformiOS
:
562 throwf("'%s' does not contain bitcode. "
563 "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());
565 case Options::kPlatformWatchOS
:
567 case Options::kPlatform_tvOS
:
569 throwf("'%s' does not contain bitcode. "
570 "You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE) or obtain an updated library from the vendor", file
.path());
575 // Error on bitcode marker in non-system frameworks if -bitcode_verify is used
576 if ( _options
.verifyBitcode() && !isSystemFramework
&&
577 dylibFile
->getBitcode() != NULL
&& dylibFile
->getBitcode()->isMarker() )
578 throwf("bitcode bundle could not be generated because '%s' was built without full bitcode. "
579 "All frameworks and dylibs for bitcode must be generated from Xcode Archive or Install build",
583 // update which form of ObjC dylibs are being linked
584 switch ( dylibFile
->objCConstraint() ) {
585 case ld::File::objcConstraintNone
:
587 case ld::File::objcConstraintRetainRelease
:
588 if ( _internal
.objcDylibConstraint
== ld::File::objcConstraintGC
)
589 throwf("%s built with incompatible Garbage Collection settings to link with previous dylibs", file
.path());
590 if ( _options
.objcGcOnly() )
591 throwf("command line specified -objc_gc_only, but dylib is retain/release based: %s", file
.path());
592 if ( _options
.objcGc() )
593 throwf("command line specified -objc_gc, but dylib is retain/release based: %s", file
.path());
594 if ( _options
.targetIOSSimulator() )
595 warning("linking ObjC for iOS Simulator, but dylib (%s) was compiled for MacOSX", file
.path());
596 _internal
.objcDylibConstraint
= ld::File::objcConstraintRetainRelease
;
598 case ld::File::objcConstraintRetainReleaseOrGC
:
599 if ( _internal
.objcDylibConstraint
== ld::File::objcConstraintNone
)
600 _internal
.objcDylibConstraint
= ld::File::objcConstraintRetainReleaseOrGC
;
601 if ( _options
.targetIOSSimulator() )
602 warning("linking ObjC for iOS Simulator, but dylib (%s) was compiled for MacOSX", file
.path());
604 case ld::File::objcConstraintGC
:
605 if ( _internal
.objcDylibConstraint
== ld::File::objcConstraintRetainRelease
)
606 throwf("%s built with incompatible Garbage Collection settings to link with previous dylibs", file
.path());
607 if ( _options
.targetIOSSimulator() )
608 warning("linking ObjC for iOS Simulator, but dylib (%s) was compiled for MacOSX", file
.path());
609 _internal
.objcDylibConstraint
= ld::File::objcConstraintGC
;
611 case ld::File::objcConstraintRetainReleaseForSimulator
:
612 if ( _internal
.objcDylibConstraint
== ld::File::objcConstraintNone
)
613 _internal
.objcDylibConstraint
= ld::File::objcConstraintRetainReleaseForSimulator
;
614 else if ( _internal
.objcDylibConstraint
!= ld::File::objcConstraintRetainReleaseForSimulator
) {
615 warning("ObjC dylib (%s) was compiled for iOS Simulator, but dylibs others were compiled for MacOSX", file
.path());
616 _internal
.objcDylibConstraint
= ld::File::objcConstraintRetainReleaseForSimulator
;
620 if ( _options
.checkDylibsAreAppExtensionSafe() && !dylibFile
->appExtensionSafe() ) {
621 warning("linking against dylib not safe for use in application extensions: %s", file
.path());
623 const char* depInstallName
= dylibFile
->installPath();
624 // <rdar://problem/17229513> embedded frameworks are only supported on iOS 8 and later
625 if ( (depInstallName
!= NULL
) && (depInstallName
[0] != '/') ) {
626 if ( (_options
.iOSVersionMin() != iOSVersionUnset
) && (_options
.iOSVersionMin() < iOS_8_0
) ) {
627 // <rdar://problem/17598404> only warn about linking against embedded dylib if it is built for iOS 8 or later
628 if ( dylibFile
->minOSVersion() >= iOS_8_0
)
629 throwf("embedded dylibs/frameworks are only supported on iOS 8.0 and later (%s)", depInstallName
);
632 if ( _options
.sharedRegionEligible() ) {
633 assert(depInstallName
!= NULL
);
634 if ( depInstallName
[0] == '@' ) {
635 warning("invalid -install_name (%s) in dependent dylib (%s). Dylibs/frameworks which might go in dyld shared cache "
636 "cannot link with dylib that uses @rpath, @loader_path, etc.", depInstallName
, dylibFile
->path());
637 } else if ( (strncmp(depInstallName
, "/usr/lib/", 9) != 0) && (strncmp(depInstallName
, "/System/Library/", 16) != 0) ) {
638 warning("invalid -install_name (%s) in dependent dylib (%s). Dylibs/frameworks which might go in dyld shared cache "
639 "cannot link with dylibs that won't be in the shared cache", depInstallName
, dylibFile
->path());
646 void Resolver::doAtom(const ld::Atom
& atom
)
648 //fprintf(stderr, "Resolver::doAtom(%p), name=%s, sect=%s, scope=%d\n", &atom, atom.name(), atom.section().sectionName(), atom.scope());
649 if ( _ltoCodeGenFinished
&& (atom
.contentType() == ld::Atom::typeLTOtemporary
) && (atom
.scope() != ld::Atom::scopeTranslationUnit
) )
650 warning("'%s' is implemented in bitcode, but it was loaded too late", atom
.name());
652 // add to list of known atoms
653 _atoms
.push_back(&atom
);
656 if ( _options
.hasExportRestrictList() || _options
.hasReExportList() ) {
657 const char* name
= atom
.name();
658 switch ( atom
.scope() ) {
659 case ld::Atom::scopeTranslationUnit
:
661 case ld::Atom::scopeLinkageUnit
:
662 if ( _options
.hasExportMaskList() && _options
.shouldExport(name
) ) {
663 // <rdar://problem/5062685> ld does not report error when -r is used and exported symbols are not defined.
664 if ( _options
.outputKind() == Options::kObjectFile
)
665 throwf("cannot export hidden symbol %s", name
);
666 // .objc_class_name_* symbols are special
667 if ( atom
.section().type() != ld::Section::typeObjC1Classes
) {
668 if ( atom
.definition() == ld::Atom::definitionProxy
) {
669 // .exp file says to export a symbol, but that symbol is in some dylib being linked
670 if ( _options
.canReExportSymbols() ) {
671 // marking proxy atom as global triggers the re-export
672 (const_cast<ld::Atom
*>(&atom
))->setScope(ld::Atom::scopeGlobal
);
674 else if ( _options
.outputKind() == Options::kDynamicLibrary
) {
675 if ( atom
.file() != NULL
)
676 warning("target OS does not support re-exporting symbol %s from %s\n", _options
.demangleSymbol(name
), atom
.file()->path());
678 warning("target OS does not support re-exporting symbol %s\n", _options
.demangleSymbol(name
));
682 if ( atom
.file() != NULL
)
683 warning("cannot export hidden symbol %s from %s", _options
.demangleSymbol(name
), atom
.file()->path());
685 warning("cannot export hidden symbol %s", _options
.demangleSymbol(name
));
689 else if ( _options
.shouldReExport(name
) && _options
.canReExportSymbols() ) {
690 if ( atom
.definition() == ld::Atom::definitionProxy
) {
691 // marking proxy atom as global triggers the re-export
692 (const_cast<ld::Atom
*>(&atom
))->setScope(ld::Atom::scopeGlobal
);
695 throwf("requested re-export symbol %s is not from a dylib, but from %s\n", _options
.demangleSymbol(name
), atom
.file()->path());
699 case ld::Atom::scopeGlobal
:
700 // check for globals that are downgraded to hidden
701 if ( ! _options
.shouldExport(name
) ) {
702 (const_cast<ld::Atom
*>(&atom
))->setScope(ld::Atom::scopeLinkageUnit
);
703 //fprintf(stderr, "demote %s to hidden\n", name);
705 if ( _options
.canReExportSymbols() && _options
.shouldReExport(name
) ) {
706 throwf("requested re-export symbol %s is not from a dylib, but from %s\n", _options
.demangleSymbol(name
), atom
.file()->path());
712 // work around for kernel that uses 'l' labels in assembly code
713 if ( (atom
.symbolTableInclusion() == ld::Atom::symbolTableNotInFinalLinkedImages
)
714 && (atom
.name()[0] == 'l') && (_options
.outputKind() == Options::kStaticExecutable
)
715 && (strncmp(atom
.name(), "ltmp", 4) != 0) )
716 (const_cast<ld::Atom
*>(&atom
))->setSymbolTableInclusion(ld::Atom::symbolTableIn
);
719 // tell symbol table about non-static atoms
720 if ( atom
.scope() != ld::Atom::scopeTranslationUnit
) {
721 _symbolTable
.add(atom
, _options
.deadCodeStrip() && (_completedInitialObjectFiles
|| _options
.allowDeadDuplicates()));
723 // add symbol aliases defined on the command line
724 if ( _options
.haveCmdLineAliases() ) {
725 const std::vector
<Options::AliasPair
>& aliases
= _options
.cmdLineAliases();
726 for (std::vector
<Options::AliasPair
>::const_iterator it
=aliases
.begin(); it
!= aliases
.end(); ++it
) {
727 if ( strcmp(it
->realName
, atom
.name()) == 0 ) {
728 const AliasAtom
* alias
= new AliasAtom(atom
, it
->alias
);
729 _aliasesFromCmdLine
.push_back(alias
);
730 this->doAtom(*alias
);
736 // convert references by-name or by-content to by-slot
737 this->convertReferencesToIndirect(atom
);
739 // remember if any atoms are proxies that require LTO
740 if ( atom
.contentType() == ld::Atom::typeLTOtemporary
)
741 _haveLLVMObjs
= true;
743 // remember if any atoms are aliases
744 if ( atom
.section().type() == ld::Section::typeTempAlias
)
747 if ( _options
.deadCodeStrip() ) {
748 // add to set of dead-strip-roots, all symbols that the compiler marks as don't strip
749 if ( atom
.dontDeadStrip() )
750 _deadStripRoots
.insert(&atom
);
751 else if ( atom
.dontDeadStripIfReferencesLive() )
752 _dontDeadStripIfReferencesLive
.push_back(&atom
);
754 if ( atom
.scope() == ld::Atom::scopeGlobal
) {
755 // <rdar://problem/5524973> -exported_symbols_list that has wildcards and -dead_strip
756 // in dylibs, every global atom in initial .o files is a root
757 if ( _options
.hasWildCardExportRestrictList() || _options
.allGlobalsAreDeadStripRoots() ) {
758 if ( _options
.shouldExport(atom
.name()) )
759 _deadStripRoots
.insert(&atom
);
765 bool Resolver::isDtraceProbe(ld::Fixup::Kind kind
)
768 case ld::Fixup::kindStoreX86DtraceCallSiteNop
:
769 case ld::Fixup::kindStoreX86DtraceIsEnableSiteClear
:
770 case ld::Fixup::kindStoreARMDtraceCallSiteNop
:
771 case ld::Fixup::kindStoreARMDtraceIsEnableSiteClear
:
772 case ld::Fixup::kindStoreARM64DtraceCallSiteNop
:
773 case ld::Fixup::kindStoreARM64DtraceIsEnableSiteClear
:
774 case ld::Fixup::kindStoreThumbDtraceCallSiteNop
:
775 case ld::Fixup::kindStoreThumbDtraceIsEnableSiteClear
:
776 case ld::Fixup::kindDtraceExtra
:
784 void Resolver::convertReferencesToIndirect(const ld::Atom
& atom
)
786 // convert references by-name or by-content to by-slot
787 SymbolTable::IndirectBindingSlot slot
;
788 const ld::Atom
* dummy
;
789 ld::Fixup::iterator end
= atom
.fixupsEnd();
790 for (ld::Fixup::iterator fit
=atom
.fixupsBegin(); fit
!= end
; ++fit
) {
791 if ( fit
->kind
== ld::Fixup::kindLinkerOptimizationHint
)
792 _internal
.someObjectHasOptimizationHints
= true;
793 switch ( fit
->binding
) {
794 case ld::Fixup::bindingByNameUnbound
:
795 if ( isDtraceProbe(fit
->kind
) && (_options
.outputKind() != Options::kObjectFile
) ) {
796 // in final linked images, remove reference
797 fit
->binding
= ld::Fixup::bindingNone
;
800 slot
= _symbolTable
.findSlotForName(fit
->u
.name
);
801 fit
->binding
= ld::Fixup::bindingsIndirectlyBound
;
802 fit
->u
.bindingIndex
= slot
;
805 case ld::Fixup::bindingByContentBound
:
806 switch ( fit
->u
.target
->combine() ) {
807 case ld::Atom::combineNever
:
808 case ld::Atom::combineByName
:
809 assert(0 && "wrong combine type for bind by content");
811 case ld::Atom::combineByNameAndContent
:
812 slot
= _symbolTable
.findSlotForContent(fit
->u
.target
, &dummy
);
813 fit
->binding
= ld::Fixup::bindingsIndirectlyBound
;
814 fit
->u
.bindingIndex
= slot
;
816 case ld::Atom::combineByNameAndReferences
:
817 slot
= _symbolTable
.findSlotForReferences(fit
->u
.target
, &dummy
);
818 fit
->binding
= ld::Fixup::bindingsIndirectlyBound
;
819 fit
->u
.bindingIndex
= slot
;
823 case ld::Fixup::bindingNone
:
824 case ld::Fixup::bindingDirectlyBound
:
825 case ld::Fixup::bindingsIndirectlyBound
:
832 void Resolver::addInitialUndefines()
834 // add initial undefines from -u option
835 for (Options::UndefinesIterator it
=_options
.initialUndefinesBegin(); it
!= _options
.initialUndefinesEnd(); ++it
) {
836 _symbolTable
.findSlotForName(*it
);
840 void Resolver::resolveUndefines()
842 // keep looping until no more undefines were added in last loop
843 unsigned int undefineGenCount
= 0xFFFFFFFF;
844 while ( undefineGenCount
!= _symbolTable
.updateCount() ) {
845 undefineGenCount
= _symbolTable
.updateCount();
846 std::vector
<const char*> undefineNames
;
847 _symbolTable
.undefines(undefineNames
);
848 for(std::vector
<const char*>::iterator it
= undefineNames
.begin(); it
!= undefineNames
.end(); ++it
) {
849 const char* undef
= *it
;
850 // load for previous undefine may also have loaded this undefine, so check again
851 if ( ! _symbolTable
.hasName(undef
) ) {
852 _inputFiles
.searchLibraries(undef
, true, true, false, *this);
853 if ( !_symbolTable
.hasName(undef
) && (_options
.outputKind() != Options::kObjectFile
) ) {
854 if ( strncmp(undef
, "section$", 8) == 0 ) {
855 if ( strncmp(undef
, "section$start$", 14) == 0 ) {
856 this->doAtom(*SectionBoundaryAtom::makeSectionBoundaryAtom(undef
, true, &undef
[14]));
858 else if ( strncmp(undef
, "section$end$", 12) == 0 ) {
859 this->doAtom(*SectionBoundaryAtom::makeSectionBoundaryAtom(undef
, false, &undef
[12]));
862 else if ( strncmp(undef
, "segment$", 8) == 0 ) {
863 if ( strncmp(undef
, "segment$start$", 14) == 0 ) {
864 this->doAtom(*SegmentBoundaryAtom::makeSegmentBoundaryAtom(undef
, true, &undef
[14]));
866 else if ( strncmp(undef
, "segment$end$", 12) == 0 ) {
867 this->doAtom(*SegmentBoundaryAtom::makeSegmentBoundaryAtom(undef
, false, &undef
[12]));
870 else if ( _options
.outputKind() == Options::kPreload
) {
871 // for iBoot grandfather in old style section labels
872 int undefLen
= strlen(undef
);
873 if ( strcmp(&undef
[undefLen
-7], "__begin") == 0 ) {
875 this->doAtom(*SectionBoundaryAtom::makeOldSectionBoundaryAtom(undef
, true));
877 this->doAtom(*SegmentBoundaryAtom::makeOldSegmentBoundaryAtom(undef
, true));
879 else if ( strcmp(&undef
[undefLen
-5], "__end") == 0 ) {
881 this->doAtom(*SectionBoundaryAtom::makeOldSectionBoundaryAtom(undef
, false));
883 this->doAtom(*SegmentBoundaryAtom::makeOldSegmentBoundaryAtom(undef
, false));
889 // <rdar://problem/5894163> need to search archives for overrides of common symbols
890 if ( _symbolTable
.hasExternalTentativeDefinitions() ) {
891 bool searchDylibs
= (_options
.commonsMode() == Options::kCommonsOverriddenByDylibs
);
892 std::vector
<const char*> tents
;
893 _symbolTable
.tentativeDefs(tents
);
894 for(std::vector
<const char*>::iterator it
= tents
.begin(); it
!= tents
.end(); ++it
) {
895 // load for previous tentative may also have loaded this tentative, so check again
896 const ld::Atom
* curAtom
= _symbolTable
.atomForSlot(_symbolTable
.findSlotForName(*it
));
897 assert(curAtom
!= NULL
);
898 if ( curAtom
->definition() == ld::Atom::definitionTentative
) {
899 _inputFiles
.searchLibraries(*it
, searchDylibs
, true, true, *this);
905 // Use linker options to resolve any remaining undefined symbols
906 if ( !_internal
.linkerOptionLibraries
.empty() || !_internal
.linkerOptionFrameworks
.empty() ) {
907 std::vector
<const char*> undefineNames
;
908 _symbolTable
.undefines(undefineNames
);
909 if ( undefineNames
.size() != 0 ) {
910 for (std::vector
<const char*>::iterator it
= undefineNames
.begin(); it
!= undefineNames
.end(); ++it
) {
911 const char* undef
= *it
;
912 if ( ! _symbolTable
.hasName(undef
) ) {
913 _inputFiles
.searchLibraries(undef
, true, true, false, *this);
919 // create proxies as needed for undefined symbols
920 if ( (_options
.undefinedTreatment() != Options::kUndefinedError
) || (_options
.outputKind() == Options::kObjectFile
) ) {
921 std::vector
<const char*> undefineNames
;
922 _symbolTable
.undefines(undefineNames
);
923 for(std::vector
<const char*>::iterator it
= undefineNames
.begin(); it
!= undefineNames
.end(); ++it
) {
924 const char* undefName
= *it
;
925 // <rdar://problem/14547001> "ld -r -exported_symbol _foo" has wrong error message if _foo is undefined
926 bool makeProxy
= true;
927 if ( (_options
.outputKind() == Options::kObjectFile
) && _options
.hasExportMaskList() && _options
.shouldExport(undefName
) )
931 this->doAtom(*new UndefinedProxyAtom(undefName
));
936 if ( _options
.someAllowedUndefines() ) {
937 std::vector
<const char*> undefineNames
;
938 _symbolTable
.undefines(undefineNames
);
939 for(std::vector
<const char*>::iterator it
= undefineNames
.begin(); it
!= undefineNames
.end(); ++it
) {
940 if ( _options
.allowedUndefined(*it
) ) {
942 this->doAtom(*new UndefinedProxyAtom(*it
));
950 void Resolver::markLive(const ld::Atom
& atom
, WhyLiveBackChain
* previous
)
952 //fprintf(stderr, "markLive(%p) %s\n", &atom, atom.name());
953 // if -why_live cares about this symbol, then dump chain
954 if ( (previous
->referer
!= NULL
) && _options
.printWhyLive(atom
.name()) ) {
955 fprintf(stderr
, "%s from %s\n", atom
.name(), atom
.file()->path());
957 for(WhyLiveBackChain
* p
= previous
; p
!= NULL
; p
= p
->previous
, ++depth
) {
958 for(int i
=depth
; i
> 0; --i
)
959 fprintf(stderr
, " ");
960 fprintf(stderr
, "%s from %s\n", p
->referer
->name(), p
->referer
->file()->path());
964 // if already marked live, then done (stop recursion)
968 // mark this atom is live
969 (const_cast<ld::Atom
*>(&atom
))->setLive();
971 // mark all atoms it references as live
972 WhyLiveBackChain thisChain
;
973 thisChain
.previous
= previous
;
974 thisChain
.referer
= &atom
;
975 for (ld::Fixup::iterator fit
= atom
.fixupsBegin(), end
=atom
.fixupsEnd(); fit
!= end
; ++fit
) {
976 const ld::Atom
* target
;
977 switch ( fit
->kind
) {
978 case ld::Fixup::kindNone
:
979 case ld::Fixup::kindNoneFollowOn
:
980 case ld::Fixup::kindNoneGroupSubordinate
:
981 case ld::Fixup::kindNoneGroupSubordinateFDE
:
982 case ld::Fixup::kindNoneGroupSubordinateLSDA
:
983 case ld::Fixup::kindNoneGroupSubordinatePersonality
:
984 case ld::Fixup::kindSetTargetAddress
:
985 case ld::Fixup::kindSubtractTargetAddress
:
986 case ld::Fixup::kindStoreTargetAddressLittleEndian32
:
987 case ld::Fixup::kindStoreTargetAddressLittleEndian64
:
988 case ld::Fixup::kindStoreTargetAddressBigEndian32
:
989 case ld::Fixup::kindStoreTargetAddressBigEndian64
:
990 case ld::Fixup::kindStoreTargetAddressX86PCRel32
:
991 case ld::Fixup::kindStoreTargetAddressX86BranchPCRel32
:
992 case ld::Fixup::kindStoreTargetAddressX86PCRel32GOTLoad
:
993 case ld::Fixup::kindStoreTargetAddressX86PCRel32GOTLoadNowLEA
:
994 case ld::Fixup::kindStoreTargetAddressX86PCRel32TLVLoad
:
995 case ld::Fixup::kindStoreTargetAddressX86PCRel32TLVLoadNowLEA
:
996 case ld::Fixup::kindStoreTargetAddressX86Abs32TLVLoad
:
997 case ld::Fixup::kindStoreTargetAddressX86Abs32TLVLoadNowLEA
:
998 case ld::Fixup::kindStoreTargetAddressARMBranch24
:
999 case ld::Fixup::kindStoreTargetAddressThumbBranch22
:
1000 #if SUPPORT_ARCH_arm64
1001 case ld::Fixup::kindStoreTargetAddressARM64Branch26
:
1002 case ld::Fixup::kindStoreTargetAddressARM64Page21
:
1003 case ld::Fixup::kindStoreTargetAddressARM64GOTLoadPage21
:
1004 case ld::Fixup::kindStoreTargetAddressARM64GOTLeaPage21
:
1005 case ld::Fixup::kindStoreTargetAddressARM64TLVPLoadPage21
:
1006 case ld::Fixup::kindStoreTargetAddressARM64TLVPLoadNowLeaPage21
:
1008 if ( fit
->binding
== ld::Fixup::bindingByContentBound
) {
1009 // normally this was done in convertReferencesToIndirect()
1010 // but a archive loaded .o file may have a forward reference
1011 SymbolTable::IndirectBindingSlot slot
;
1012 const ld::Atom
* dummy
;
1013 switch ( fit
->u
.target
->combine() ) {
1014 case ld::Atom::combineNever
:
1015 case ld::Atom::combineByName
:
1016 assert(0 && "wrong combine type for bind by content");
1018 case ld::Atom::combineByNameAndContent
:
1019 slot
= _symbolTable
.findSlotForContent(fit
->u
.target
, &dummy
);
1020 fit
->binding
= ld::Fixup::bindingsIndirectlyBound
;
1021 fit
->u
.bindingIndex
= slot
;
1023 case ld::Atom::combineByNameAndReferences
:
1024 slot
= _symbolTable
.findSlotForReferences(fit
->u
.target
, &dummy
);
1025 fit
->binding
= ld::Fixup::bindingsIndirectlyBound
;
1026 fit
->u
.bindingIndex
= slot
;
1030 switch ( fit
->binding
) {
1031 case ld::Fixup::bindingDirectlyBound
:
1032 markLive(*(fit
->u
.target
), &thisChain
);
1034 case ld::Fixup::bindingByNameUnbound
:
1035 // doAtom() did not convert to indirect in dead-strip mode, so that now
1036 fit
->u
.bindingIndex
= _symbolTable
.findSlotForName(fit
->u
.name
);
1037 fit
->binding
= ld::Fixup::bindingsIndirectlyBound
;
1038 // fall into next case
1039 case ld::Fixup::bindingsIndirectlyBound
:
1040 target
= _internal
.indirectBindingTable
[fit
->u
.bindingIndex
];
1041 if ( target
== NULL
) {
1042 const char* targetName
= _symbolTable
.indirectName(fit
->u
.bindingIndex
);
1043 _inputFiles
.searchLibraries(targetName
, true, true, false, *this);
1044 target
= _internal
.indirectBindingTable
[fit
->u
.bindingIndex
];
1046 if ( target
!= NULL
) {
1047 if ( target
->definition() == ld::Atom::definitionTentative
) {
1048 // <rdar://problem/5894163> need to search archives for overrides of common symbols
1049 bool searchDylibs
= (_options
.commonsMode() == Options::kCommonsOverriddenByDylibs
);
1050 _inputFiles
.searchLibraries(target
->name(), searchDylibs
, true, true, *this);
1051 // recompute target since it may have been overridden by searchLibraries()
1052 target
= _internal
.indirectBindingTable
[fit
->u
.bindingIndex
];
1054 this->markLive(*target
, &thisChain
);
1057 _atomsWithUnresolvedReferences
.push_back(&atom
);
1061 assert(0 && "bad binding during dead stripping");
1073 bool operator()(const ld::Atom
* atom
) const {
1074 if (atom
->live() || atom
->dontDeadStrip() )
1076 // don't kill combinable atoms in first pass
1077 switch ( atom
->combine() ) {
1078 case ld::Atom::combineByNameAndContent
:
1079 case ld::Atom::combineByNameAndReferences
:
1087 void Resolver::deadStripOptimize(bool force
)
1089 // only do this optimization with -dead_strip
1090 if ( ! _options
.deadCodeStrip() )
1093 // add entry point (main) to live roots
1094 const ld::Atom
* entry
= this->entryPoint(true);
1095 if ( entry
!= NULL
)
1096 _deadStripRoots
.insert(entry
);
1098 // add -exported_symbols_list, -init, and -u entries to live roots
1099 for (Options::UndefinesIterator uit
=_options
.initialUndefinesBegin(); uit
!= _options
.initialUndefinesEnd(); ++uit
) {
1100 SymbolTable::IndirectBindingSlot slot
= _symbolTable
.findSlotForName(*uit
);
1101 if ( _internal
.indirectBindingTable
[slot
] == NULL
) {
1102 _inputFiles
.searchLibraries(*uit
, false, true, false, *this);
1104 if ( _internal
.indirectBindingTable
[slot
] != NULL
)
1105 _deadStripRoots
.insert(_internal
.indirectBindingTable
[slot
]);
1108 // this helper is only referenced by synthesize stubs, assume it will be used
1109 if ( _internal
.classicBindingHelper
!= NULL
)
1110 _deadStripRoots
.insert(_internal
.classicBindingHelper
);
1112 // this helper is only referenced by synthesize stubs, assume it will be used
1113 if ( _internal
.compressedFastBinderProxy
!= NULL
)
1114 _deadStripRoots
.insert(_internal
.compressedFastBinderProxy
);
1116 // this helper is only referenced by synthesized lazy stubs, assume it will be used
1117 if ( _internal
.lazyBindingHelper
!= NULL
)
1118 _deadStripRoots
.insert(_internal
.lazyBindingHelper
);
1120 // add all dont-dead-strip atoms as roots
1121 for (std::vector
<const ld::Atom
*>::const_iterator it
=_atoms
.begin(); it
!= _atoms
.end(); ++it
) {
1122 const ld::Atom
* atom
= *it
;
1123 if ( atom
->dontDeadStrip() ) {
1124 //fprintf(stderr, "dont dead strip: %p %s %s\n", atom, atom->section().sectionName(), atom->name());
1125 _deadStripRoots
.insert(atom
);
1126 // unset liveness, so markLive() will recurse
1127 (const_cast<ld::Atom
*>(atom
))->setLive(0);
1131 // mark all roots as live, and all atoms they reference
1132 for (std::set
<const ld::Atom
*>::iterator it
=_deadStripRoots
.begin(); it
!= _deadStripRoots
.end(); ++it
) {
1133 WhyLiveBackChain rootChain
;
1134 rootChain
.previous
= NULL
;
1135 rootChain
.referer
= *it
;
1136 this->markLive(**it
, &rootChain
);
1139 // special case atoms that need to be live if they reference something live
1140 if ( ! _dontDeadStripIfReferencesLive
.empty() ) {
1141 for (std::vector
<const ld::Atom
*>::iterator it
=_dontDeadStripIfReferencesLive
.begin(); it
!= _dontDeadStripIfReferencesLive
.end(); ++it
) {
1142 const Atom
* liveIfRefLiveAtom
= *it
;
1143 //fprintf(stderr, "live-if-live atom: %s\n", liveIfRefLiveAtom->name());
1144 if ( liveIfRefLiveAtom
->live() )
1146 bool hasLiveRef
= false;
1147 for (ld::Fixup::iterator fit
=liveIfRefLiveAtom
->fixupsBegin(); fit
!= liveIfRefLiveAtom
->fixupsEnd(); ++fit
) {
1148 const Atom
* target
= NULL
;
1149 switch ( fit
->binding
) {
1150 case ld::Fixup::bindingDirectlyBound
:
1151 target
= fit
->u
.target
;
1153 case ld::Fixup::bindingsIndirectlyBound
:
1154 target
= _internal
.indirectBindingTable
[fit
->u
.bindingIndex
];
1159 if ( (target
!= NULL
) && target
->live() )
1163 WhyLiveBackChain rootChain
;
1164 rootChain
.previous
= NULL
;
1165 rootChain
.referer
= liveIfRefLiveAtom
;
1166 this->markLive(*liveIfRefLiveAtom
, &rootChain
);
1171 // now remove all non-live atoms from _atoms
1172 const bool log
= false;
1174 fprintf(stderr
, "deadStripOptimize() all %ld atoms with liveness:\n", _atoms
.size());
1175 for (std::vector
<const ld::Atom
*>::const_iterator it
=_atoms
.begin(); it
!= _atoms
.end(); ++it
) {
1176 const ld::File
* file
= (*it
)->file();
1177 fprintf(stderr
, " live=%d atom=%p name=%s from=%s\n", (*it
)->live(), *it
, (*it
)->name(), (file
? file
->path() : "<internal>"));
1181 if ( _haveLLVMObjs
&& !force
) {
1182 // <rdar://problem/9777977> don't remove combinable atoms, they may come back in lto output
1183 _atoms
.erase(std::remove_if(_atoms
.begin(), _atoms
.end(), NotLiveLTO()), _atoms
.end());
1184 _symbolTable
.removeDeadAtoms();
1187 _atoms
.erase(std::remove_if(_atoms
.begin(), _atoms
.end(), NotLive()), _atoms
.end());
1191 fprintf(stderr
, "deadStripOptimize() %ld remaining atoms\n", _atoms
.size());
1192 for (std::vector
<const ld::Atom
*>::const_iterator it
=_atoms
.begin(); it
!= _atoms
.end(); ++it
) {
1193 fprintf(stderr
, " live=%d atom=%p name=%s\n", (*it
)->live(), *it
, (*it
)->name());
1199 // This is called when LTO is used but -dead_strip is not used.
1200 // Some undefines were eliminated by LTO, but others were not.
1201 void Resolver::remainingUndefines(std::vector
<const char*>& undefs
)
1204 // search all atoms for references that are unbound
1205 for (std::vector
<const ld::Atom
*>::const_iterator it
=_atoms
.begin(); it
!= _atoms
.end(); ++it
) {
1206 const ld::Atom
* atom
= *it
;
1207 for (ld::Fixup::iterator fit
=atom
->fixupsBegin(); fit
!= atom
->fixupsEnd(); ++fit
) {
1208 switch ( (ld::Fixup::TargetBinding
)fit
->binding
) {
1209 case ld::Fixup::bindingByNameUnbound
:
1210 assert(0 && "should not be by-name this late");
1211 undefSet
.insert(fit
->u
.name
);
1213 case ld::Fixup::bindingsIndirectlyBound
:
1214 if ( _internal
.indirectBindingTable
[fit
->u
.bindingIndex
] == NULL
) {
1215 undefSet
.insert(_symbolTable
.indirectName(fit
->u
.bindingIndex
));
1218 case ld::Fixup::bindingByContentBound
:
1219 case ld::Fixup::bindingNone
:
1220 case ld::Fixup::bindingDirectlyBound
:
1225 // look for any initial undefines that are still undefined
1226 for (Options::UndefinesIterator uit
=_options
.initialUndefinesBegin(); uit
!= _options
.initialUndefinesEnd(); ++uit
) {
1227 if ( ! _symbolTable
.hasName(*uit
) ) {
1228 undefSet
.insert(*uit
);
1232 // copy set to vector
1233 for (StringSet::const_iterator it
=undefSet
.begin(); it
!= undefSet
.end(); ++it
) {
1234 fprintf(stderr
, "undef: %s\n", *it
);
1235 undefs
.push_back(*it
);
1239 void Resolver::liveUndefines(std::vector
<const char*>& undefs
)
1242 // search all live atoms for references that are unbound
1243 for (std::vector
<const ld::Atom
*>::const_iterator it
=_atoms
.begin(); it
!= _atoms
.end(); ++it
) {
1244 const ld::Atom
* atom
= *it
;
1245 if ( ! atom
->live() )
1247 for (ld::Fixup::iterator fit
=atom
->fixupsBegin(); fit
!= atom
->fixupsEnd(); ++fit
) {
1248 switch ( (ld::Fixup::TargetBinding
)fit
->binding
) {
1249 case ld::Fixup::bindingByNameUnbound
:
1250 assert(0 && "should not be by-name this late");
1251 undefSet
.insert(fit
->u
.name
);
1253 case ld::Fixup::bindingsIndirectlyBound
:
1254 if ( _internal
.indirectBindingTable
[fit
->u
.bindingIndex
] == NULL
) {
1255 undefSet
.insert(_symbolTable
.indirectName(fit
->u
.bindingIndex
));
1258 case ld::Fixup::bindingByContentBound
:
1259 case ld::Fixup::bindingNone
:
1260 case ld::Fixup::bindingDirectlyBound
:
1265 // look for any initial undefines that are still undefined
1266 for (Options::UndefinesIterator uit
=_options
.initialUndefinesBegin(); uit
!= _options
.initialUndefinesEnd(); ++uit
) {
1267 if ( ! _symbolTable
.hasName(*uit
) ) {
1268 undefSet
.insert(*uit
);
1272 // copy set to vector
1273 for (StringSet::const_iterator it
=undefSet
.begin(); it
!= undefSet
.end(); ++it
) {
1274 undefs
.push_back(*it
);
1280 // <rdar://problem/8252819> warn when .objc_class_name_* symbol missing
1281 class ExportedObjcClass
1284 ExportedObjcClass(const Options
& opt
) : _options(opt
) {}
1286 bool operator()(const char* name
) const {
1287 if ( (strncmp(name
, ".objc_class_name_", 17) == 0) && _options
.shouldExport(name
) ) {
1288 warning("ignoring undefined symbol %s from -exported_symbols_list", name
);
1291 const char* s
= strstr(name
, "CLASS_$_");
1293 char temp
[strlen(name
)+16];
1294 strcpy(temp
, ".objc_class_name_");
1295 strcat(temp
, &s
[8]);
1296 if ( _options
.wasRemovedExport(temp
) ) {
1297 warning("ignoring undefined symbol %s from -exported_symbols_list", temp
);
1304 const Options
& _options
;
1308 // temp hack for undefined aliases
1309 class UndefinedAlias
1312 UndefinedAlias(const Options
& opt
) : _aliases(opt
.cmdLineAliases()) {}
1314 bool operator()(const char* name
) const {
1315 for (std::vector
<Options::AliasPair
>::const_iterator it
=_aliases
.begin(); it
!= _aliases
.end(); ++it
) {
1316 if ( strcmp(it
->realName
, name
) == 0 ) {
1317 warning("undefined base symbol '%s' for alias '%s'", name
, it
->alias
);
1324 const std::vector
<Options::AliasPair
>& _aliases
;
1329 static const char* pathLeafName(const char* path
)
1331 const char* shortPath
= strrchr(path
, '/');
1332 if ( shortPath
== NULL
)
1335 return &shortPath
[1];
1338 bool Resolver::printReferencedBy(const char* name
, SymbolTable::IndirectBindingSlot slot
)
1340 unsigned foundReferenceCount
= 0;
1341 for (std::vector
<const ld::Atom
*>::const_iterator it
=_atoms
.begin(); it
!= _atoms
.end(); ++it
) {
1342 const ld::Atom
* atom
= *it
;
1343 for (ld::Fixup::iterator fit
=atom
->fixupsBegin(); fit
!= atom
->fixupsEnd(); ++fit
) {
1344 if ( fit
->binding
== ld::Fixup::bindingsIndirectlyBound
) {
1345 if ( fit
->u
.bindingIndex
== slot
) {
1346 if ( atom
->contentType() == ld::Atom::typeNonLazyPointer
) {
1347 const ld::Atom
* existingAtom
;
1348 unsigned int nlSlot
= _symbolTable
.findSlotForReferences(atom
, &existingAtom
);
1349 if ( printReferencedBy(name
, nlSlot
) )
1350 ++foundReferenceCount
;
1352 else if ( atom
->contentType() == ld::Atom::typeCFI
) {
1353 fprintf(stderr
, " Dwarf Exception Unwind Info (__eh_frame) in %s\n", pathLeafName(atom
->file()->path()));
1354 ++foundReferenceCount
;
1357 fprintf(stderr
, " %s in %s\n", _options
.demangleSymbol(atom
->name()), pathLeafName(atom
->file()->path()));
1358 ++foundReferenceCount
;
1359 break; // if undefined used twice in a function, only show first
1364 if ( foundReferenceCount
> 6 ) {
1365 fprintf(stderr
, " ...\n");
1366 break; // only show first six uses of undefined symbol
1369 return (foundReferenceCount
!= 0);
1372 void Resolver::checkUndefines(bool force
)
1374 // when using LTO, undefines are checked after bitcode is optimized
1375 if ( _haveLLVMObjs
&& !force
)
1378 // error out on any remaining undefines
1379 bool doPrint
= true;
1380 bool doError
= true;
1381 switch ( _options
.undefinedTreatment() ) {
1382 case Options::kUndefinedError
:
1384 case Options::kUndefinedDynamicLookup
:
1387 case Options::kUndefinedWarning
:
1390 case Options::kUndefinedSuppress
:
1395 std::vector
<const char*> unresolvableUndefines
;
1396 if ( _options
.deadCodeStrip() )
1397 this->liveUndefines(unresolvableUndefines
);
1398 else if( _haveLLVMObjs
)
1399 this->remainingUndefines(unresolvableUndefines
); // <rdar://problem/10052396> LTO may have eliminated need for some undefines
1401 _symbolTable
.undefines(unresolvableUndefines
);
1403 // <rdar://problem/8252819> assert when .objc_class_name_* symbol missing
1404 if ( _options
.hasExportMaskList() ) {
1405 unresolvableUndefines
.erase(std::remove_if(unresolvableUndefines
.begin(), unresolvableUndefines
.end(), ExportedObjcClass(_options
)), unresolvableUndefines
.end());
1408 // hack to temporarily make missing aliases a warning
1409 if ( _options
.haveCmdLineAliases() ) {
1410 unresolvableUndefines
.erase(std::remove_if(unresolvableUndefines
.begin(), unresolvableUndefines
.end(), UndefinedAlias(_options
)), unresolvableUndefines
.end());
1413 const int unresolvableCount
= unresolvableUndefines
.size();
1414 int unresolvableExportsCount
= 0;
1415 if ( unresolvableCount
!= 0 ) {
1417 if ( _options
.printArchPrefix() )
1418 fprintf(stderr
, "Undefined symbols for architecture %s:\n", _options
.architectureName());
1420 fprintf(stderr
, "Undefined symbols:\n");
1421 for (int i
=0; i
< unresolvableCount
; ++i
) {
1422 const char* name
= unresolvableUndefines
[i
];
1423 unsigned int slot
= _symbolTable
.findSlotForName(name
);
1424 fprintf(stderr
, " \"%s\", referenced from:\n", _options
.demangleSymbol(name
));
1425 // scan all atoms for references
1426 bool foundAtomReference
= printReferencedBy(name
, slot
);
1427 // scan command line options
1428 if ( !foundAtomReference
) {
1429 // might be from -init command line option
1430 if ( (_options
.initFunctionName() != NULL
) && (strcmp(name
, _options
.initFunctionName()) == 0) ) {
1431 fprintf(stderr
, " -init command line option\n");
1433 // or might be from exported symbol option
1434 else if ( _options
.hasExportMaskList() && _options
.shouldExport(name
) ) {
1435 fprintf(stderr
, " -exported_symbol[s_list] command line option\n");
1437 // or might be from re-exported symbol option
1438 else if ( _options
.hasReExportList() && _options
.shouldReExport(name
) ) {
1439 fprintf(stderr
, " -reexported_symbols_list command line option\n");
1441 else if ( (_options
.outputKind() == Options::kDynamicExecutable
)
1442 && (_options
.entryName() != NULL
) && (strcmp(name
, _options
.entryName()) == 0) ) {
1443 fprintf(stderr
, " implicit entry/start for main executable\n");
1446 bool isInitialUndefine
= false;
1447 for (Options::UndefinesIterator uit
=_options
.initialUndefinesBegin(); uit
!= _options
.initialUndefinesEnd(); ++uit
) {
1448 if ( strcmp(*uit
, name
) == 0 ) {
1449 isInitialUndefine
= true;
1453 if ( isInitialUndefine
)
1454 fprintf(stderr
, " -u command line option\n");
1456 ++unresolvableExportsCount
;
1458 // be helpful and check for typos
1459 bool printedStart
= false;
1460 for (SymbolTable::byNameIterator sit
=_symbolTable
.begin(); sit
!= _symbolTable
.end(); sit
++) {
1461 const ld::Atom
* atom
= *sit
;
1462 if ( (atom
!= NULL
) && (atom
->symbolTableInclusion() == ld::Atom::symbolTableIn
) && (strstr(atom
->name(), name
) != NULL
) ) {
1463 if ( ! printedStart
) {
1464 fprintf(stderr
, " (maybe you meant: %s", atom
->name());
1465 printedStart
= true;
1468 fprintf(stderr
, ", %s ", atom
->name());
1473 fprintf(stderr
, ")\n");
1474 // <rdar://problem/8989530> Add comment to error message when __ZTV symbols are undefined
1475 if ( strncmp(name
, "__ZTV", 5) == 0 ) {
1476 fprintf(stderr
, " NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.\n");
1481 throw "symbol(s) not found";
1488 void Resolver::checkDylibSymbolCollisions()
1490 for (SymbolTable::byNameIterator it
=_symbolTable
.begin(); it
!= _symbolTable
.end(); it
++) {
1491 const ld::Atom
* atom
= *it
;
1494 if ( atom
->scope() == ld::Atom::scopeGlobal
) {
1495 // <rdar://problem/5048861> No warning about tentative definition conflicting with dylib definition
1496 // for each tentative definition in symbol table look for dylib that exports same symbol name
1497 if ( atom
->definition() == ld::Atom::definitionTentative
) {
1498 _inputFiles
.searchLibraries(atom
->name(), true, false, false, *this);
1500 // record any overrides of weak symbols in any linked dylib
1501 if ( (atom
->definition() == ld::Atom::definitionRegular
) && (atom
->symbolTableInclusion() == ld::Atom::symbolTableIn
) ) {
1502 if ( _inputFiles
.searchWeakDefInDylib(atom
->name()) )
1503 (const_cast<ld::Atom
*>(atom
))->setOverridesDylibsWeakDef();
1510 const ld::Atom
* Resolver::entryPoint(bool searchArchives
)
1512 const char* symbolName
= NULL
;
1513 bool makingDylib
= false;
1514 switch ( _options
.outputKind() ) {
1515 case Options::kDynamicExecutable
:
1516 case Options::kStaticExecutable
:
1517 case Options::kDyld
:
1518 case Options::kPreload
:
1519 symbolName
= _options
.entryName();
1521 case Options::kDynamicLibrary
:
1522 symbolName
= _options
.initFunctionName();
1525 case Options::kObjectFile
:
1526 case Options::kDynamicBundle
:
1527 case Options::kKextBundle
:
1531 if ( symbolName
!= NULL
) {
1532 SymbolTable::IndirectBindingSlot slot
= _symbolTable
.findSlotForName(symbolName
);
1533 if ( (_internal
.indirectBindingTable
[slot
] == NULL
) && searchArchives
) {
1534 // <rdar://problem/7043256> ld64 can not find a -e entry point from an archive
1535 _inputFiles
.searchLibraries(symbolName
, false, true, false, *this);
1537 if ( _internal
.indirectBindingTable
[slot
] == NULL
) {
1538 if ( strcmp(symbolName
, "start") == 0 )
1539 throwf("entry point (%s) undefined. Usually in crt1.o", symbolName
);
1541 throwf("entry point (%s) undefined.", symbolName
);
1543 else if ( _internal
.indirectBindingTable
[slot
]->definition() == ld::Atom::definitionProxy
) {
1545 throwf("-init function (%s) found in linked dylib, must be in dylib being linked", symbolName
);
1547 return _internal
.indirectBindingTable
[slot
];
1553 void Resolver::fillInHelpersInInternalState()
1555 // look up well known atoms
1556 bool needsStubHelper
= true;
1557 switch ( _options
.outputKind() ) {
1558 case Options::kDynamicExecutable
:
1559 case Options::kDynamicLibrary
:
1560 case Options::kDynamicBundle
:
1561 needsStubHelper
= true;
1563 case Options::kDyld
:
1564 case Options::kKextBundle
:
1565 case Options::kObjectFile
:
1566 case Options::kStaticExecutable
:
1567 case Options::kPreload
:
1568 needsStubHelper
= false;
1572 _internal
.classicBindingHelper
= NULL
;
1573 if ( needsStubHelper
&& !_options
.makeCompressedDyldInfo() ) {
1574 // "dyld_stub_binding_helper" comes from .o file, so should already exist in symbol table
1575 if ( _symbolTable
.hasName("dyld_stub_binding_helper") ) {
1576 SymbolTable::IndirectBindingSlot slot
= _symbolTable
.findSlotForName("dyld_stub_binding_helper");
1577 _internal
.classicBindingHelper
= _internal
.indirectBindingTable
[slot
];
1581 _internal
.lazyBindingHelper
= NULL
;
1582 if ( _options
.usingLazyDylibLinking() ) {
1583 // "dyld_lazy_dylib_stub_binding_helper" comes from lazydylib1.o file, so should already exist in symbol table
1584 if ( _symbolTable
.hasName("dyld_lazy_dylib_stub_binding_helper") ) {
1585 SymbolTable::IndirectBindingSlot slot
= _symbolTable
.findSlotForName("dyld_lazy_dylib_stub_binding_helper");
1586 _internal
.lazyBindingHelper
= _internal
.indirectBindingTable
[slot
];
1588 if ( _internal
.lazyBindingHelper
== NULL
)
1589 throw "symbol dyld_lazy_dylib_stub_binding_helper not defined (usually in lazydylib1.o)";
1592 _internal
.compressedFastBinderProxy
= NULL
;
1593 if ( needsStubHelper
&& _options
.makeCompressedDyldInfo() ) {
1594 // "dyld_stub_binder" comes from libSystem.dylib so will need to manually resolve
1595 if ( !_symbolTable
.hasName("dyld_stub_binder") ) {
1596 _inputFiles
.searchLibraries("dyld_stub_binder", true, false, false, *this);
1598 if ( _symbolTable
.hasName("dyld_stub_binder") ) {
1599 SymbolTable::IndirectBindingSlot slot
= _symbolTable
.findSlotForName("dyld_stub_binder");
1600 _internal
.compressedFastBinderProxy
= _internal
.indirectBindingTable
[slot
];
1602 if ( _internal
.compressedFastBinderProxy
== NULL
) {
1603 if ( _options
.undefinedTreatment() != Options::kUndefinedError
) {
1605 _internal
.compressedFastBinderProxy
= new UndefinedProxyAtom("dyld_stub_binder");
1606 this->doAtom(*_internal
.compressedFastBinderProxy
);
1613 void Resolver::fillInInternalState()
1615 // store atoms into their final section
1616 for (std::vector
<const ld::Atom
*>::iterator it
= _atoms
.begin(); it
!= _atoms
.end(); ++it
) {
1617 _internal
.addAtom(**it
);
1620 // <rdar://problem/7783918> make sure there is a __text section so that codesigning works
1621 if ( (_options
.outputKind() == Options::kDynamicLibrary
) || (_options
.outputKind() == Options::kDynamicBundle
) )
1622 _internal
.getFinalSection(*new ld::Section("__TEXT", "__text", ld::Section::typeCode
));
1625 void Resolver::fillInEntryPoint()
1627 _internal
.entryPoint
= this->entryPoint(true);
1630 void Resolver::syncAliases()
1632 if ( !_haveAliases
|| (_options
.outputKind() == Options::kObjectFile
) )
1635 // Set attributes of alias to match its found target
1636 for (std::vector
<const ld::Atom
*>::iterator it
= _atoms
.begin(); it
!= _atoms
.end(); ++it
) {
1637 const ld::Atom
* atom
= *it
;
1638 if ( atom
->section().type() == ld::Section::typeTempAlias
) {
1639 assert(atom
->fixupsBegin() != atom
->fixupsEnd());
1640 for (ld::Fixup::iterator fit
= atom
->fixupsBegin(); fit
!= atom
->fixupsEnd(); ++fit
) {
1641 const ld::Atom
* target
;
1642 ld::Atom::Scope scope
;
1643 assert(fit
->kind
== ld::Fixup::kindNoneFollowOn
);
1644 switch ( fit
->binding
) {
1645 case ld::Fixup::bindingByNameUnbound
:
1647 case ld::Fixup::bindingsIndirectlyBound
:
1648 target
= _internal
.indirectBindingTable
[fit
->u
.bindingIndex
];
1649 assert(target
!= NULL
);
1650 scope
= atom
->scope();
1651 (const_cast<Atom
*>(atom
))->setAttributesFromAtom(*target
);
1652 // alias has same attributes as target, except for scope
1653 (const_cast<Atom
*>(atom
))->setScope(scope
);
1656 assert(0 && "internal error: unexpected alias binding");
1663 void Resolver::removeCoalescedAwayAtoms()
1665 const bool log
= false;
1667 fprintf(stderr
, "removeCoalescedAwayAtoms() starts with %lu atoms\n", _atoms
.size());
1669 _atoms
.erase(std::remove_if(_atoms
.begin(), _atoms
.end(), AtomCoalescedAway()), _atoms
.end());
1671 fprintf(stderr
, "removeCoalescedAwayAtoms() after removing coalesced atoms, %lu remain\n", _atoms
.size());
1672 for (std::vector
<const ld::Atom
*>::const_iterator it
=_atoms
.begin(); it
!= _atoms
.end(); ++it
) {
1673 fprintf(stderr
, " atom=%p %s\n", *it
, (*it
)->name());
1678 void Resolver::linkTimeOptimize()
1680 // only do work here if some llvm obj files where loaded
1681 if ( ! _haveLLVMObjs
)
1684 // <rdar://problem/15314161> LTO: Symbol multiply defined error should specify exactly where the symbol is found
1685 _symbolTable
.checkDuplicateSymbols();
1687 // run LLVM lto code-gen
1688 lto::OptimizeOptions optOpt
;
1689 optOpt
.outputFilePath
= _options
.outputFilePath();
1690 optOpt
.tmpObjectFilePath
= _options
.tempLtoObjectPath();
1691 optOpt
.preserveAllGlobals
= _options
.allGlobalsAreDeadStripRoots() || _options
.hasExportRestrictList();
1692 optOpt
.verbose
= _options
.verbose();
1693 optOpt
.saveTemps
= _options
.saveTempFiles();
1694 optOpt
.ltoCodegenOnly
= _options
.ltoCodegenOnly();
1695 optOpt
.pie
= _options
.positionIndependentExecutable();
1696 optOpt
.mainExecutable
= _options
.linkingMainExecutable();;
1697 optOpt
.staticExecutable
= (_options
.outputKind() == Options::kStaticExecutable
);
1698 optOpt
.relocatable
= (_options
.outputKind() == Options::kObjectFile
);
1699 optOpt
.allowTextRelocs
= _options
.allowTextRelocs();
1700 optOpt
.linkerDeadStripping
= _options
.deadCodeStrip();
1701 optOpt
.needsUnwindInfoSection
= _options
.needsUnwindInfoSection();
1702 optOpt
.keepDwarfUnwind
= _options
.keepDwarfUnwind();
1703 optOpt
.verboseOptimizationHints
= _options
.verboseOptimizationHints();
1704 optOpt
.armUsesZeroCostExceptions
= _options
.armUsesZeroCostExceptions();
1705 optOpt
.simulator
= _options
.targetIOSSimulator();
1706 optOpt
.ignoreMismatchPlatform
= ((_options
.outputKind() == Options::kPreload
) || (_options
.outputKind() == Options::kStaticExecutable
));
1707 optOpt
.bitcodeBundle
= _options
.bundleBitcode();
1708 optOpt
.arch
= _options
.architecture();
1709 optOpt
.mcpu
= _options
.mcpuLTO();
1710 optOpt
.platform
= _options
.platform();
1711 optOpt
.llvmOptions
= &_options
.llvmOptions();
1712 optOpt
.initialUndefines
= &_options
.initialUndefines();
1714 std::vector
<const ld::Atom
*> newAtoms
;
1715 std::vector
<const char*> additionalUndefines
;
1716 if ( ! lto::optimize(_atoms
, _internal
, optOpt
, *this, newAtoms
, additionalUndefines
) )
1717 return; // if nothing done
1718 _ltoCodeGenFinished
= true;
1720 // add all newly created atoms to _atoms and update symbol table
1721 for(std::vector
<const ld::Atom
*>::iterator it
= newAtoms
.begin(); it
!= newAtoms
.end(); ++it
)
1724 // some atoms might have been optimized way (marked coalesced), remove them
1725 this->removeCoalescedAwayAtoms();
1727 // run through all atoms again and make sure newly codegened atoms have references bound
1728 for (std::vector
<const ld::Atom
*>::const_iterator it
=_atoms
.begin(); it
!= _atoms
.end(); ++it
)
1729 this->convertReferencesToIndirect(**it
);
1731 // adjust section of any new
1732 for (std::vector
<const AliasAtom
*>::const_iterator it
=_aliasesFromCmdLine
.begin(); it
!= _aliasesFromCmdLine
.end(); ++it
) {
1733 const AliasAtom
* aliasAtom
= *it
;
1734 // update fields in AliasAtom to match newly constructed mach-o atom
1735 aliasAtom
->setFinalAliasOf();
1738 // <rdar://problem/14609792> add any auto-link libraries requested by LTO output to dylibs to search
1739 _inputFiles
.addLinkerOptionLibraries(_internal
, *this);
1740 _inputFiles
.createIndirectDylibs();
1742 // resolve new undefines (e.g calls to _malloc and _memcpy that llvm compiler conjures up)
1743 for(std::vector
<const char*>::iterator uit
= additionalUndefines
.begin(); uit
!= additionalUndefines
.end(); ++uit
) {
1744 const char *targetName
= *uit
;
1745 // these symbols may or may not already be in linker's symbol table
1746 if ( ! _symbolTable
.hasName(targetName
) ) {
1747 _inputFiles
.searchLibraries(targetName
, true, true, false, *this);
1751 // if -dead_strip on command line
1752 if ( _options
.deadCodeStrip() ) {
1753 // clear liveness bit
1754 for (std::vector
<const ld::Atom
*>::const_iterator it
=_atoms
.begin(); it
!= _atoms
.end(); ++it
) {
1755 (const_cast<ld::Atom
*>(*it
))->setLive((*it
)->dontDeadStrip());
1757 // and re-compute dead code
1758 this->deadStripOptimize(true);
1761 // <rdar://problem/12386559> if -exported_symbols_list on command line, re-force scope
1762 if ( _options
.hasExportMaskList() ) {
1763 for (std::vector
<const ld::Atom
*>::const_iterator it
=_atoms
.begin(); it
!= _atoms
.end(); ++it
) {
1764 const ld::Atom
* atom
= *it
;
1765 if ( atom
->scope() == ld::Atom::scopeGlobal
) {
1766 if ( !_options
.shouldExport(atom
->name()) ) {
1767 (const_cast<ld::Atom
*>(atom
))->setScope(ld::Atom::scopeLinkageUnit
);
1773 if ( _options
.outputKind() == Options::kObjectFile
) {
1774 // if -r mode, add proxies for new undefines (e.g. ___stack_chk_fail)
1775 this->resolveUndefines();
1778 // last chance to check for undefines
1779 this->resolveUndefines();
1780 this->checkUndefines(true);
1782 // check new code does not override some dylib
1783 this->checkDylibSymbolCollisions();
1788 void Resolver::tweakWeakness()
1790 // <rdar://problem/7977374> Add command line options to control symbol weak-def bit on exported symbols
1791 if ( _options
.hasWeakBitTweaks() ) {
1792 for (std::vector
<ld::Internal::FinalSection
*>::iterator sit
= _internal
.sections
.begin(); sit
!= _internal
.sections
.end(); ++sit
) {
1793 ld::Internal::FinalSection
* sect
= *sit
;
1794 for (std::vector
<const ld::Atom
*>::iterator ait
= sect
->atoms
.begin(); ait
!= sect
->atoms
.end(); ++ait
) {
1795 const ld::Atom
* atom
= *ait
;
1796 if ( atom
->definition() != ld::Atom::definitionRegular
)
1798 const char* name
= atom
->name();
1799 if ( atom
->scope() == ld::Atom::scopeGlobal
) {
1800 if ( atom
->combine() == ld::Atom::combineNever
) {
1801 if ( _options
.forceWeak(name
) )
1802 (const_cast<ld::Atom
*>(atom
))->setCombine(ld::Atom::combineByName
);
1804 else if ( atom
->combine() == ld::Atom::combineByName
) {
1805 if ( _options
.forceNotWeak(name
) )
1806 (const_cast<ld::Atom
*>(atom
))->setCombine(ld::Atom::combineNever
);
1810 if ( _options
.forceWeakNonWildCard(name
) )
1811 warning("cannot force to be weak, non-external symbol %s", name
);
1812 else if ( _options
.forceNotWeakNonWildcard(name
) )
1813 warning("cannot force to be not-weak, non-external symbol %s", name
);
1820 void Resolver::dumpAtoms()
1822 fprintf(stderr
, "Resolver all atoms:\n");
1823 for (std::vector
<const ld::Atom
*>::const_iterator it
=_atoms
.begin(); it
!= _atoms
.end(); ++it
) {
1824 const ld::Atom
* atom
= *it
;
1825 fprintf(stderr
, " %p name=%s, def=%d\n", atom
, atom
->name(), atom
->definition());
1829 void Resolver::resolve()
1831 this->initializeState();
1832 this->buildAtomList();
1833 this->addInitialUndefines();
1834 this->fillInHelpersInInternalState();
1835 this->resolveUndefines();
1836 this->deadStripOptimize();
1837 this->checkUndefines();
1838 this->checkDylibSymbolCollisions();
1839 this->syncAliases();
1840 this->removeCoalescedAwayAtoms();
1841 this->fillInEntryPoint();
1842 this->linkTimeOptimize();
1843 this->fillInInternalState();
1844 this->tweakWeakness();
1845 _symbolTable
.checkDuplicateSymbols();