2 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-*
4 * Copyright (c) 2009-2011 Apple Inc. All rights reserved.
6 * @APPLE_LICENSE_HEADER_START@
8 * This file contains Original Code and/or Modifications of Original Code
9 * as defined in and that are subject to the Apple Public Source License
10 * Version 2.0 (the 'License'). You may not use this file except in
11 * compliance with the License. Please obtain a copy of the License at
12 * http://www.opensource.apple.com/apsl/ and read it before using this
15 * The Original Code and all software distributed under the License are
16 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
17 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
18 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
20 * Please see the License for the specific language governing rights and
21 * limitations under the License.
23 * @APPLE_LICENSE_HEADER_END@
28 #include <sys/types.h>
31 #include <sys/sysctl.h>
36 #include <mach/mach_time.h>
37 #include <mach/vm_statistics.h>
38 #include <mach/mach_init.h>
39 #include <mach/mach_host.h>
41 #include <mach-o/dyld.h>
42 #include <mach-o/fat.h>
43 #include <sys/sysctl.h>
44 #include <libkern/OSAtomic.h>
54 #include <AvailabilityMacros.h>
58 #include "InputFiles.h"
59 #include "macho_relocatable_file.h"
60 #include "macho_dylib_file.h"
61 #include "archive_file.h"
63 #include "opaque_section_file.h"
64 #include "MachOFileAbstraction.hpp"
67 const bool _s_logPThreads
= false;
72 class IgnoredFile
: public ld::File
{
74 IgnoredFile(const char* pth
, time_t modTime
, Ordinal ord
, Type type
) : ld::File(pth
, modTime
, ord
, type
) {};
75 virtual bool forEachAtom(AtomHandler
&) const { return false; };
76 virtual bool justInTimeforEachAtom(const char* name
, AtomHandler
&) const { return false; };
80 class DSOHandleAtom
: public ld::Atom
{
82 DSOHandleAtom(const char* nm
, ld::Atom::Scope sc
,
83 ld::Atom::SymbolTableInclusion inc
, ld::Section
& sect
=_s_section
)
84 : ld::Atom(sect
, ld::Atom::definitionRegular
,
85 (sect
== _s_section_text
) ? ld::Atom::combineByName
: ld::Atom::combineNever
,
86 // make "weak def" so that link succeeds even if app defines __dso_handle
87 sc
, ld::Atom::typeUnclassified
, inc
, true, false, false,
88 ld::Atom::Alignment(1)), _name(nm
) {}
90 virtual ld::File
* file() const { return NULL
; }
91 virtual const char* name() const { return _name
; }
92 virtual uint64_t size() const { return 0; }
93 virtual uint64_t objectAddress() const { return 0; }
94 virtual void copyRawContent(uint8_t buffer
[]) const
96 virtual void setScope(Scope
) { }
98 virtual ~DSOHandleAtom() {}
100 static ld::Section _s_section
;
101 static ld::Section _s_section_preload
;
102 static ld::Section _s_section_text
;
103 static DSOHandleAtom _s_atomAll
;
104 static DSOHandleAtom _s_atomExecutable
;
105 static DSOHandleAtom _s_atomDylib
;
106 static DSOHandleAtom _s_atomBundle
;
107 static DSOHandleAtom _s_atomDyld
;
108 static DSOHandleAtom _s_atomObjectFile
;
109 static DSOHandleAtom _s_atomPreload
;
110 static DSOHandleAtom _s_atomPreloadDSO
;
114 ld::Section
DSOHandleAtom::_s_section("__TEXT", "__mach_header", ld::Section::typeMachHeader
, true);
115 ld::Section
DSOHandleAtom::_s_section_preload("__HEADER", "__mach_header", ld::Section::typeMachHeader
, true);
116 ld::Section
DSOHandleAtom::_s_section_text("__TEXT", "__text", ld::Section::typeCode
, false);
117 DSOHandleAtom
DSOHandleAtom::_s_atomAll("___dso_handle", ld::Atom::scopeLinkageUnit
, ld::Atom::symbolTableNotIn
);
118 DSOHandleAtom
DSOHandleAtom::_s_atomExecutable("__mh_execute_header", ld::Atom::scopeGlobal
, ld::Atom::symbolTableInAndNeverStrip
);
119 DSOHandleAtom
DSOHandleAtom::_s_atomDylib("__mh_dylib_header", ld::Atom::scopeLinkageUnit
, ld::Atom::symbolTableNotIn
);
120 DSOHandleAtom
DSOHandleAtom::_s_atomBundle("__mh_bundle_header", ld::Atom::scopeLinkageUnit
, ld::Atom::symbolTableNotIn
);
121 DSOHandleAtom
DSOHandleAtom::_s_atomDyld("__mh_dylinker_header", ld::Atom::scopeLinkageUnit
, ld::Atom::symbolTableNotIn
);
122 DSOHandleAtom
DSOHandleAtom::_s_atomObjectFile("__mh_object_header", ld::Atom::scopeLinkageUnit
, ld::Atom::symbolTableNotIn
);
123 DSOHandleAtom
DSOHandleAtom::_s_atomPreload("__mh_preload_header", ld::Atom::scopeLinkageUnit
, ld::Atom::symbolTableNotIn
, _s_section_preload
);
124 DSOHandleAtom
DSOHandleAtom::_s_atomPreloadDSO("___dso_handle", ld::Atom::scopeLinkageUnit
, ld::Atom::symbolTableNotIn
, _s_section_text
);
128 class PageZeroAtom
: public ld::Atom
{
130 PageZeroAtom(uint64_t sz
)
131 : ld::Atom(_s_section
, ld::Atom::definitionRegular
, ld::Atom::combineNever
,
132 ld::Atom::scopeTranslationUnit
, ld::Atom::typeZeroFill
,
133 symbolTableNotIn
, true, false, false, ld::Atom::Alignment(12)),
136 virtual ld::File
* file() const { return NULL
; }
137 virtual const char* name() const { return "page zero"; }
138 virtual uint64_t size() const { return _size
; }
139 virtual uint64_t objectAddress() const { return 0; }
140 virtual void copyRawContent(uint8_t buffer
[]) const
142 virtual void setScope(Scope
) { }
144 virtual ~PageZeroAtom() {}
146 static ld::Section _s_section
;
147 static DSOHandleAtom _s_atomAll
;
151 ld::Section
PageZeroAtom::_s_section("__PAGEZERO", "__pagezero", ld::Section::typePageZero
, true);
154 class CustomStackAtom
: public ld::Atom
{
156 CustomStackAtom(uint64_t sz
)
157 : ld::Atom(_s_section
, ld::Atom::definitionRegular
, ld::Atom::combineNever
,
158 ld::Atom::scopeTranslationUnit
, ld::Atom::typeZeroFill
,
159 symbolTableNotIn
, false, false, false, ld::Atom::Alignment(12)),
162 virtual ld::File
* file() const { return NULL
; }
163 virtual const char* name() const { return "custom stack"; }
164 virtual uint64_t size() const { return _size
; }
165 virtual uint64_t objectAddress() const { return 0; }
166 virtual void copyRawContent(uint8_t buffer
[]) const
168 virtual void setScope(Scope
) { }
170 virtual ~CustomStackAtom() {}
174 static ld::Section _s_section
;
176 ld::Section
CustomStackAtom::_s_section("__UNIXSTACK", "__stack", ld::Section::typeStack
, true);
180 const char* InputFiles::fileArch(const uint8_t* p
, unsigned len
)
182 const char* result
= mach_o::relocatable::archName(p
);
183 if ( result
!= NULL
)
186 result
= mach_o::dylib::archName(p
);
187 if ( result
!= NULL
)
190 result
= lto::archName(p
, len
);
191 if ( result
!= NULL
)
194 if ( strncmp((const char*)p
, "!<arch>\n", 8) == 0 )
197 char *unsupported
= (char *)malloc(128);
198 strcpy(unsupported
, "unsupported file format (");
199 for (unsigned i
=0; i
<len
&& i
< 16; i
++) {
201 sprintf(buf
, " 0x%02X", p
[i
]);
202 strcat(unsupported
, buf
);
204 strcat(unsupported
, " )");
209 ld::File
* InputFiles::makeFile(const Options::FileInfo
& info
, bool indirectDylib
)
212 uint64_t len
= info
.fileLen
;
213 int fd
= ::open(info
.path
, O_RDONLY
, 0);
215 throwf("can't open file, errno=%d", errno
);
216 if ( info
.fileLen
< 20 )
217 throwf("file too small (length=%llu)", info
.fileLen
);
219 uint8_t* p
= (uint8_t*)::mmap(NULL
, info
.fileLen
, PROT_READ
, MAP_FILE
| MAP_PRIVATE
, fd
, 0);
220 if ( p
== (uint8_t*)(-1) )
221 throwf("can't map file, errno=%d", errno
);
223 // if fat file, skip to architecture we want
224 // Note: fat header is always big-endian
225 bool isFatFile
= false;
226 uint32_t sliceToUse
, sliceCount
;
227 const fat_header
* fh
= (fat_header
*)p
;
228 if ( fh
->magic
== OSSwapBigToHostInt32(FAT_MAGIC
) ) {
230 const struct fat_arch
* archs
= (struct fat_arch
*)(p
+ sizeof(struct fat_header
));
231 bool sliceFound
= false;
232 sliceCount
= OSSwapBigToHostInt32(fh
->nfat_arch
);
233 if ( _options
.preferSubArchitecture() ) {
234 // first try to find a slice that match cpu-type and cpu-sub-type
235 for (uint32_t i
=0; i
< sliceCount
; ++i
) {
236 if ( (OSSwapBigToHostInt32(archs
[i
].cputype
) == (uint32_t)_options
.architecture())
237 && (OSSwapBigToHostInt32(archs
[i
].cpusubtype
) == (uint32_t)_options
.subArchitecture()) ) {
245 // look for any slice that matches just cpu-type
246 for (uint32_t i
=0; i
< sliceCount
; ++i
) {
247 if ( OSSwapBigToHostInt32(archs
[i
].cputype
) == (uint32_t)_options
.architecture() ) {
255 uint32_t fileOffset
= OSSwapBigToHostInt32(archs
[sliceToUse
].offset
);
256 len
= OSSwapBigToHostInt32(archs
[sliceToUse
].size
);
257 if ( fileOffset
+len
> info
.fileLen
) {
258 throwf("truncated fat file. Slice from %u to %llu is past end of file with length %llu",
259 fileOffset
, fileOffset
+len
, info
.fileLen
);
261 // if requested architecture is page aligned within fat file, then remap just that portion of file
262 if ( (fileOffset
& 0x00000FFF) == 0 ) {
264 munmap((caddr_t
)p
, info
.fileLen
);
265 // re-map just part we need
266 p
= (uint8_t*)::mmap(NULL
, len
, PROT_READ
, MAP_FILE
| MAP_PRIVATE
, fd
, fileOffset
);
267 if ( p
== (uint8_t*)(-1) )
268 throwf("can't re-map file, errno=%d", errno
);
277 // see if it is an object file
278 mach_o::relocatable::ParserOptions objOpts
;
279 objOpts
.architecture
= _options
.architecture();
280 objOpts
.objSubtypeMustMatch
= !_options
.allowSubArchitectureMismatches();
281 objOpts
.logAllFiles
= _options
.logAllFiles();
282 objOpts
.warnUnwindConversionProblems
= _options
.needsUnwindInfoSection();
283 objOpts
.keepDwarfUnwind
= _options
.keepDwarfUnwind();
284 objOpts
.forceDwarfConversion
= (_options
.outputKind() == Options::kDyld
);
285 objOpts
.neverConvertDwarf
= !_options
.needsUnwindInfoSection();
286 objOpts
.verboseOptimizationHints
= _options
.verboseOptimizationHints();
287 objOpts
.subType
= _options
.subArchitecture();
288 ld::relocatable::File
* objResult
= mach_o::relocatable::parse(p
, len
, info
.path
, info
.modTime
, info
.ordinal
, objOpts
);
289 if ( objResult
!= NULL
) {
290 OSAtomicAdd64(len
, &_totalObjectSize
);
291 OSAtomicIncrement32(&_totalObjectLoaded
);
295 // see if it is an llvm object file
296 objResult
= lto::parse(p
, len
, info
.path
, info
.modTime
, info
.ordinal
, _options
.architecture(), _options
.subArchitecture(), _options
.logAllFiles(), _options
.verboseOptimizationHints());
297 if ( objResult
!= NULL
) {
298 OSAtomicAdd64(len
, &_totalObjectSize
);
299 OSAtomicIncrement32(&_totalObjectLoaded
);
303 // see if it is a dynamic library
304 ld::dylib::File
* dylibResult
= mach_o::dylib::parse(p
, len
, info
.path
, info
.modTime
, _options
, info
.ordinal
, info
.options
.fBundleLoader
, indirectDylib
);
305 if ( dylibResult
!= NULL
) {
309 // see if it is a static library
310 ::archive::ParserOptions archOpts
;
311 archOpts
.objOpts
= objOpts
;
312 archOpts
.forceLoadThisArchive
= info
.options
.fForceLoad
;
313 archOpts
.forceLoadAll
= _options
.fullyLoadArchives();
314 archOpts
.forceLoadObjC
= _options
.loadAllObjcObjectsFromArchives();
315 archOpts
.objcABI2
= _options
.objCABIVersion2POverride();
316 archOpts
.verboseLoad
= _options
.whyLoad();
317 archOpts
.logAllFiles
= _options
.logAllFiles();
318 ld::archive::File
* archiveResult
= ::archive::parse(p
, len
, info
.path
, info
.modTime
, info
.ordinal
, archOpts
);
319 if ( archiveResult
!= NULL
) {
320 OSAtomicAdd64(len
, &_totalArchiveSize
);
321 OSAtomicIncrement32(&_totalArchivesLoaded
);
322 return archiveResult
;
325 // does not seem to be any valid linker input file, check LTO misconfiguration problems
326 if ( lto::archName((uint8_t*)p
, len
) != NULL
) {
327 if ( lto::libLTOisLoaded() ) {
328 throwf("lto file was built for %s which is not the architecture being linked (%s): %s", fileArch(p
, len
), _options
.architectureName(), info
.path
);
331 const char* libLTO
= "libLTO.dylib";
332 char ldPath
[PATH_MAX
];
333 char tmpPath
[PATH_MAX
];
334 char libLTOPath
[PATH_MAX
];
335 uint32_t bufSize
= PATH_MAX
;
336 if ( _options
.overridePathlibLTO() != NULL
) {
337 libLTO
= _options
.overridePathlibLTO();
339 else if ( _NSGetExecutablePath(ldPath
, &bufSize
) != -1 ) {
340 if ( realpath(ldPath
, tmpPath
) != NULL
) {
341 char* lastSlash
= strrchr(tmpPath
, '/');
342 if ( lastSlash
!= NULL
)
343 strcpy(lastSlash
, "/../lib/libLTO.dylib");
345 if ( realpath(tmpPath
, libLTOPath
) != NULL
)
349 throwf("could not process llvm bitcode object file, because %s could not be loaded", libLTO
);
354 if ( ((fat_header
*)p
)->magic
== OSSwapBigToHostInt32(FAT_MAGIC
) ) {
355 throwf("missing required architecture %s in file %s (%u slices)", _options
.architectureName(), info
.path
, sliceCount
);
359 throwf("file is universal (%u slices) but does not contain a(n) %s slice: %s", sliceCount
, _options
.architectureName(), info
.path
);
361 throwf("file was built for %s which is not the architecture being linked (%s): %s", fileArch(p
, len
), _options
.architectureName(), info
.path
);
365 void InputFiles::logDylib(ld::File
* file
, bool indirect
)
367 if ( _options
.traceDylibs() ) {
368 const char* fullPath
= file
->path();
369 char realName
[MAXPATHLEN
];
370 if ( realpath(fullPath
, realName
) != NULL
)
372 const ld::dylib::File
* dylib
= dynamic_cast<const ld::dylib::File
*>(file
);
373 if ( (dylib
!= NULL
) && dylib
->willBeUpwardDylib() ) {
374 // don't log upward dylibs when XBS is computing dependencies
375 logTraceInfo("[Logging for XBS] Used upward dynamic library: %s\n", fullPath
);
379 logTraceInfo("[Logging for XBS] Used indirect dynamic library: %s\n", fullPath
);
381 logTraceInfo("[Logging for XBS] Used dynamic library: %s\n", fullPath
);
385 if ( _options
.dumpDependencyInfo() ) {
386 const ld::dylib::File
* dylib
= dynamic_cast<const ld::dylib::File
*>(file
);
387 if ( file
== _bundleLoader
) {
388 _options
.dumpDependency(Options::depBundleLoader
, file
->path());
390 else if ( (dylib
!= NULL
) && dylib
->willBeUpwardDylib() ) {
392 _options
.dumpDependency(Options::depUpwardIndirectDylib
, file
->path());
394 _options
.dumpDependency(Options::depUpwardDirectDylib
, file
->path());
398 _options
.dumpDependency(Options::depIndirectDylib
, file
->path());
400 _options
.dumpDependency(Options::depDirectDylib
, file
->path());
405 void InputFiles::logArchive(ld::File
* file
) const
407 if ( _options
.traceArchives() && (_archiveFilesLogged
.count(file
) == 0) ) {
408 // <rdar://problem/4947347> LD_TRACE_ARCHIVES should only print out when a .o is actually used from an archive
409 _archiveFilesLogged
.insert(file
);
410 const char* fullPath
= file
->path();
411 char realName
[MAXPATHLEN
];
412 if ( realpath(fullPath
, realName
) != NULL
)
414 logTraceInfo("[Logging for XBS] Used static archive: %s\n", fullPath
);
419 void InputFiles::logTraceInfo(const char* format
, ...) const
421 // one time open() of custom LD_TRACE_FILE
422 static int trace_file
= -1;
423 if ( trace_file
== -1 ) {
424 const char *trace_file_path
= _options
.traceOutputFile();
425 if ( trace_file_path
!= NULL
) {
426 trace_file
= open(trace_file_path
, O_WRONLY
| O_APPEND
| O_CREAT
, 0666);
427 if ( trace_file
== -1 )
428 throwf("Could not open or create trace file (errno=%d): %s", errno
, trace_file_path
);
431 trace_file
= fileno(stderr
);
435 char trace_buffer
[MAXPATHLEN
* 2];
437 va_start(ap
, format
);
438 int length
= vsnprintf(trace_buffer
, sizeof(trace_buffer
), format
, ap
);
440 char* buffer_ptr
= trace_buffer
;
443 ssize_t amount_written
= write(trace_file
, buffer_ptr
, length
);
444 if(amount_written
== -1)
445 /* Failure to write shouldn't fail the build. */
447 buffer_ptr
+= amount_written
;
448 length
-= amount_written
;
453 ld::dylib::File
* InputFiles::findDylib(const char* installPath
, const char* fromPath
)
455 //fprintf(stderr, "findDylib(%s, %s)\n", installPath, fromPath);
456 InstallNameToDylib::iterator pos
= _installPathToDylibs
.find(installPath
);
457 if ( pos
!= _installPathToDylibs
.end() ) {
461 // allow -dylib_path option to override indirect library to use
462 for (std::vector
<Options::DylibOverride
>::const_iterator dit
= _options
.dylibOverrides().begin(); dit
!= _options
.dylibOverrides().end(); ++dit
) {
463 if ( strcmp(dit
->installName
,installPath
) == 0 ) {
465 Options::FileInfo info
= _options
.findFile(dit
->useInstead
);
466 _indirectDylibOrdinal
= _indirectDylibOrdinal
.nextIndirectDylibOrdinal();
467 info
.ordinal
= _indirectDylibOrdinal
;
468 info
.options
.fIndirectDylib
= true;
469 ld::File
* reader
= this->makeFile(info
, true);
470 ld::dylib::File
* dylibReader
= dynamic_cast<ld::dylib::File
*>(reader
);
471 if ( dylibReader
!= NULL
) {
472 addDylib(dylibReader
, info
);
473 //_installPathToDylibs[strdup(installPath)] = dylibReader;
474 this->logDylib(dylibReader
, true);
478 throwf("indirect dylib at %s is not a dylib", dit
->useInstead
);
480 catch (const char* msg
) {
481 warning("ignoring -dylib_file option, %s", msg
);
485 char newPath
[MAXPATHLEN
];
486 // handle @loader_path
487 if ( strncmp(installPath
, "@loader_path/", 13) == 0 ) {
488 strcpy(newPath
, fromPath
);
489 char* addPoint
= strrchr(newPath
,'/');
490 if ( addPoint
!= NULL
)
491 strcpy(&addPoint
[1], &installPath
[13]);
493 strcpy(newPath
, &installPath
[13]);
494 installPath
= newPath
;
496 // note: @executable_path case is handled inside findFileUsingPaths()
497 // search for dylib using -F and -L paths
498 Options::FileInfo info
= _options
.findFileUsingPaths(installPath
);
499 _indirectDylibOrdinal
= _indirectDylibOrdinal
.nextIndirectDylibOrdinal();
500 info
.ordinal
= _indirectDylibOrdinal
;
501 info
.options
.fIndirectDylib
= true;
503 ld::File
* reader
= this->makeFile(info
, true);
504 ld::dylib::File
* dylibReader
= dynamic_cast<ld::dylib::File
*>(reader
);
505 if ( dylibReader
!= NULL
) {
506 //assert(_installPathToDylibs.find(installPath) != _installPathToDylibs.end());
507 //_installPathToDylibs[strdup(installPath)] = dylibReader;
508 addDylib(dylibReader
, info
);
509 this->logDylib(dylibReader
, true);
513 throwf("indirect dylib at %s is not a dylib", info
.path
);
515 catch (const char* msg
) {
516 throwf("in '%s', %s", info
.path
, msg
);
522 // mark all dylibs initially specified as required, and check if they can be used
523 void InputFiles::markExplicitlyLinkedDylibs()
525 for (InstallNameToDylib::iterator it
=_installPathToDylibs
.begin(); it
!= _installPathToDylibs
.end(); it
++) {
526 it
->second
->setExplicitlyLinked();
527 this->checkDylibClientRestrictions(it
->second
);
531 bool InputFiles::libraryAlreadyLoaded(const char* path
)
533 for (std::vector
<ld::File
*>::const_iterator it
= _inputFiles
.begin(); it
!= _inputFiles
.end(); ++it
) {
534 if ( strcmp(path
, (*it
)->path()) == 0 )
541 void InputFiles::addLinkerOptionLibraries(ld::Internal
& state
)
543 if ( _options
.outputKind() == Options::kObjectFile
)
546 // process frameworks specified in .o linker options
547 for (CStringSet::const_iterator it
= state
.linkerOptionFrameworks
.begin(); it
!= state
.linkerOptionFrameworks
.end(); ++it
) {
548 const char* frameworkName
= *it
;
549 Options::FileInfo info
= _options
.findFramework(frameworkName
);
550 if ( ! this->libraryAlreadyLoaded(info
.path
) ) {
551 info
.ordinal
= _linkerOptionOrdinal
.nextLinkerOptionOrdinal();
553 ld::File
* reader
= this->makeFile(info
, true);
554 ld::dylib::File
* dylibReader
= dynamic_cast<ld::dylib::File
*>(reader
);
555 if ( dylibReader
!= NULL
) {
556 if ( ! dylibReader
->installPathVersionSpecific() ) {
557 dylibReader
->setImplicitlyLinked();
558 this->addDylib(dylibReader
, info
);
562 throwf("framework linker option at %s is not a dylib", info
.path
);
565 catch (const char* msg
) {
566 warning("Auto-Linking supplied '%s', %s", info
.path
, msg
);
570 // process libraries specified in .o linker options
571 for (CStringSet::const_iterator it
= state
.linkerOptionLibraries
.begin(); it
!= state
.linkerOptionLibraries
.end(); ++it
) {
572 const char* libName
= *it
;
573 Options::FileInfo info
= _options
.findLibrary(libName
);
574 if ( ! this->libraryAlreadyLoaded(info
.path
) ) {
575 info
.ordinal
= _linkerOptionOrdinal
.nextLinkerOptionOrdinal();
577 ld::File
* reader
= this->makeFile(info
, true);
578 ld::dylib::File
* dylibReader
= dynamic_cast<ld::dylib::File
*>(reader
);
579 ld::archive::File
* archiveReader
= dynamic_cast<ld::archive::File
*>(reader
);
580 if ( dylibReader
!= NULL
) {
581 dylibReader
->setImplicitlyLinked();
582 this->addDylib(dylibReader
, info
);
584 else if ( archiveReader
!= NULL
) {
585 _searchLibraries
.push_back(LibraryInfo(archiveReader
));
586 if ( _options
.dumpDependencyInfo() )
587 _options
.dumpDependency(Options::depArchive
, archiveReader
->path());
590 throwf("linker option dylib at %s is not a dylib", info
.path
);
593 catch (const char* msg
) {
594 warning("Auto-Linking supplied '%s', %s", info
.path
, msg
);
600 void InputFiles::createIndirectDylibs()
602 // keep processing dylibs until no more dylibs are added
603 unsigned long lastMapSize
= 0;
604 std::set
<ld::dylib::File
*> dylibsProcessed
;
605 while ( lastMapSize
!= _allDylibs
.size() ) {
606 lastMapSize
= _allDylibs
.size();
607 // can't iterator _installPathToDylibs while modifying it, so use temp buffer
608 std::vector
<ld::dylib::File
*> unprocessedDylibs
;
609 for (std::set
<ld::dylib::File
*>::iterator it
=_allDylibs
.begin(); it
!= _allDylibs
.end(); it
++) {
610 if ( dylibsProcessed
.count(*it
) == 0 )
611 unprocessedDylibs
.push_back(*it
);
613 for (std::vector
<ld::dylib::File
*>::iterator it
=unprocessedDylibs
.begin(); it
!= unprocessedDylibs
.end(); it
++) {
614 dylibsProcessed
.insert(*it
);
615 (*it
)->processIndirectLibraries(this, _options
.implicitlyLinkIndirectPublicDylibs());
619 // go back over original dylibs and mark sub frameworks as re-exported
620 if ( _options
.outputKind() == Options::kDynamicLibrary
) {
621 const char* myLeaf
= strrchr(_options
.installPath(), '/');
622 if ( myLeaf
!= NULL
) {
623 for (std::vector
<class ld::File
*>::const_iterator it
=_inputFiles
.begin(); it
!= _inputFiles
.end(); it
++) {
624 ld::dylib::File
* dylibReader
= dynamic_cast<ld::dylib::File
*>(*it
);
625 if ( dylibReader
!= NULL
) {
626 const char* childParent
= dylibReader
->parentUmbrella();
627 if ( childParent
!= NULL
) {
628 if ( strcmp(childParent
, &myLeaf
[1]) == 0 ) {
629 // mark that this dylib will be re-exported
630 dylibReader
->setWillBeReExported();
640 void InputFiles::createOpaqueFileSections()
642 // extra command line sections always at end
643 for (Options::ExtraSection::const_iterator it
=_options
.extraSectionsBegin(); it
!= _options
.extraSectionsEnd(); ++it
) {
644 _inputFiles
.push_back(opaque_section::parse(it
->segmentName
, it
->sectionName
, it
->path
, it
->data
, it
->dataLen
));
645 if ( _options
.dumpDependencyInfo() )
646 _options
.dumpDependency(Options::depSection
, it
->path
);
652 void InputFiles::checkDylibClientRestrictions(ld::dylib::File
* dylib
)
654 // Check for any restrictions on who can link with this dylib
655 const char* dylibParentName
= dylib
->parentUmbrella() ;
656 const std::vector
<const char*>* clients
= dylib
->allowableClients();
657 if ( (dylibParentName
!= NULL
) || (clients
!= NULL
) ) {
658 // only dylibs that are in an umbrella or have a client list need verification
659 const char* installName
= _options
.installPath();
660 const char* installNameLastSlash
= strrchr(installName
, '/');
661 bool isParent
= false;
662 bool isSibling
= false;
663 bool isAllowableClient
= false;
664 // There are three cases:
665 if ( (dylibParentName
!= NULL
) && (installNameLastSlash
!= NULL
) ) {
666 // starts after last slash
667 const char* myName
= &installNameLastSlash
[1];
668 unsigned int myNameLen
= strlen(myName
);
669 if ( strncmp(myName
, "lib", 3) == 0 )
672 const char* firstDot
= strchr(myName
, '.');
673 if ( firstDot
!= NULL
)
674 myNameLen
= firstDot
- myName
;
675 // up to first underscore
676 const char* firstUnderscore
= strchr(myName
, '_');
677 if ( (firstUnderscore
!= NULL
) && ((firstUnderscore
- myName
) < (int)myNameLen
) )
678 myNameLen
= firstUnderscore
- myName
;
680 // case 1) The dylib has a parent umbrella, and we are creating the parent umbrella
681 isParent
= ( (strlen(dylibParentName
) == myNameLen
) && (strncmp(myName
, dylibParentName
, myNameLen
) == 0) );
683 // case 2) The dylib has a parent umbrella, and we are creating a sibling with the same parent
684 isSibling
= ( (_options
.umbrellaName() != NULL
) && (strcmp(_options
.umbrellaName(), dylibParentName
) == 0) );
687 if ( !isParent
&& !isSibling
&& (clients
!= NULL
) ) {
688 // case 3) the dylib has a list of allowable clients, and we are creating one of them
689 const char* clientName
= _options
.clientName();
690 int clientNameLen
= 0;
691 if ( clientName
!= NULL
) {
692 // use client name as specified on command line
693 clientNameLen
= strlen(clientName
);
696 // infer client name from output path (e.g. xxx/libfoo_variant.A.dylib --> foo, Bar.framework/Bar_variant --> Bar)
697 clientName
= installName
;
698 clientNameLen
= strlen(clientName
);
699 // starts after last slash
700 if ( installNameLastSlash
!= NULL
)
701 clientName
= &installNameLastSlash
[1];
702 if ( strncmp(clientName
, "lib", 3) == 0 )
703 clientName
= &clientName
[3];
705 const char* firstDot
= strchr(clientName
, '.');
706 if ( firstDot
!= NULL
)
707 clientNameLen
= firstDot
- clientName
;
708 // up to first underscore
709 const char* firstUnderscore
= strchr(clientName
, '_');
710 if ( (firstUnderscore
!= NULL
) && ((firstUnderscore
- clientName
) < clientNameLen
) )
711 clientNameLen
= firstUnderscore
- clientName
;
714 // Use clientName to check if this dylib is able to link against the allowable clients.
715 for (std::vector
<const char*>::const_iterator it
= clients
->begin(); it
!= clients
->end(); it
++) {
716 if ( strncmp(*it
, clientName
, clientNameLen
) == 0 )
717 isAllowableClient
= true;
721 if ( !isParent
&& !isSibling
&& !isAllowableClient
) {
722 if ( dylibParentName
!= NULL
) {
723 throwf("cannot link directly with %s. Link against the umbrella framework '%s.framework' instead.",
724 dylib
->path(), dylibParentName
);
727 throwf("cannot link directly with %s", dylib
->path());
734 void InputFiles::inferArchitecture(Options
& opts
, const char** archName
)
736 _inferredArch
= true;
737 // scan all input files, looking for a thin .o file.
738 // the first one found is presumably the architecture to link
739 uint8_t buffer
[sizeof(mach_header_64
)];
740 const std::vector
<Options::FileInfo
>& files
= opts
.getInputFiles();
741 for (std::vector
<Options::FileInfo
>::const_iterator it
= files
.begin(); it
!= files
.end(); ++it
) {
742 int fd
= ::open(it
->path
, O_RDONLY
, 0);
744 ssize_t amount
= read(fd
, buffer
, sizeof(buffer
));
746 if ( amount
>= (ssize_t
)sizeof(buffer
) ) {
748 cpu_subtype_t subtype
;
749 if ( mach_o::relocatable::isObjectFile(buffer
, &type
, &subtype
) ) {
750 opts
.setArchitecture(type
, subtype
);
751 *archName
= opts
.architectureName();
758 // no thin .o files found, so default to same architecture this tool was built as
759 warning("-arch not specified");
761 opts
.setArchitecture(CPU_TYPE_I386
, CPU_SUBTYPE_X86_ALL
);
763 opts
.setArchitecture(CPU_TYPE_X86_64
, CPU_SUBTYPE_X86_64_ALL
);
765 opts
.setArchitecture(CPU_TYPE_ARM
, CPU_SUBTYPE_ARM_V6
);
767 #error unknown default architecture
769 *archName
= opts
.architectureName();
773 InputFiles::InputFiles(Options
& opts
, const char** archName
)
774 : _totalObjectSize(0), _totalArchiveSize(0),
775 _totalObjectLoaded(0), _totalArchivesLoaded(0), _totalDylibsLoaded(0),
776 _options(opts
), _bundleLoader(NULL
),
777 _inferredArch(false),
779 _indirectDylibOrdinal(ld::File::Ordinal::indirectDylibBase()),
780 _linkerOptionOrdinal(ld::File::Ordinal::linkeOptionBase())
782 // fStartCreateReadersTime = mach_absolute_time();
783 if ( opts
.architecture() == 0 ) {
784 // command line missing -arch, so guess arch
785 inferArchitecture(opts
, archName
);
788 pthread_mutex_init(&_parseLock
, NULL
);
789 pthread_cond_init(&_parseWorkReady
, NULL
);
790 pthread_cond_init(&_newFileAvailable
, NULL
);
792 const std::vector
<Options::FileInfo
>& files
= _options
.getInputFiles();
793 if ( files
.size() == 0 )
794 throw "no object files specified";
796 _inputFiles
.reserve(files
.size());
798 unsigned int inputFileSlot
= 0;
799 _availableInputFiles
= 0;
802 Options::FileInfo
* entry
;
803 for (std::vector
<Options::FileInfo
>::const_iterator it
= files
.begin(); it
!= files
.end(); ++it
) {
804 entry
= (Options::FileInfo
*)&(*it
);
806 // Assign input file slots to all the FileInfos.
807 // Also chain all FileInfos into one big list to set up for worker threads to do parsing.
808 entry
->inputFileSlot
= inputFileSlot
;
809 entry
->readyToParse
= !entry
->fromFileList
|| !_options
.pipelineEnabled();
810 if (entry
->readyToParse
)
811 _availableInputFiles
++;
812 _inputFiles
.push_back(NULL
);
815 // In the non-threaded case just parse the file now.
816 _inputFiles
.push_back(makeFile(*entry
, false));
821 _remainingInputFiles
= files
.size();
823 // initialize info for parsing input files on worker threads
826 size_t len
= sizeof(ncpus
);
829 if (sysctl(mib
, 2, &ncpus
, &len
, NULL
, 0) != 0) {
832 _availableWorkers
= MIN(ncpus
, files
.size()); // max # workers we permit
835 if (_options
.pipelineEnabled()) {
836 // start up a thread to listen for available input files
837 startThread(InputFiles::waitForInputFiles
);
840 // Start up one parser thread. More start on demand as parsed input files get consumed.
841 startThread(InputFiles::parseWorkerThread
);
844 if (_options
.pipelineEnabled()) {
845 throwf("pipelined linking not supported on this platform");
852 void InputFiles::startThread(void (*threadFunc
)(InputFiles
*)) const {
855 pthread_attr_init(&attr
);
856 // set a nice big stack (same as main thread) because some code uses potentially large stack buffers
857 pthread_attr_setstacksize(&attr
, 8 * 1024 * 1024);
858 pthread_create(&thread
, &attr
, (void *(*)(void*))threadFunc
, (void *)this);
859 pthread_detach(thread
);
860 pthread_attr_destroy(&attr
);
863 // Work loop for input file parsing threads
864 void InputFiles::parseWorkerThread() {
866 const char *exception
= NULL
;
867 pthread_mutex_lock(&_parseLock
);
868 const std::vector
<Options::FileInfo
>& files
= _options
.getInputFiles();
869 if (_s_logPThreads
) printf("worker starting\n");
871 if (_availableInputFiles
== 0) {
873 pthread_cond_wait(&_parseWorkReady
, &_parseLock
);
876 int slot
= _parseCursor
;
877 while (slot
< (int)files
.size() && (_inputFiles
[slot
] != NULL
|| !files
[slot
].readyToParse
))
879 assert(slot
< (int)files
.size());
880 Options::FileInfo
& entry
= (Options::FileInfo
&)files
[slot
];
881 _parseCursor
= slot
+1;
882 _availableInputFiles
--;
883 entry
.readyToParse
= false; // to avoid multiple threads finding this file
884 pthread_mutex_unlock(&_parseLock
);
885 if (_s_logPThreads
) printf("parsing index %u\n", slot
);
887 file
= makeFile(entry
, false);
889 catch (const char *msg
) {
890 if ( (strstr(msg
, "architecture") != NULL
) && !_options
.errorOnOtherArchFiles() ) {
891 if ( _options
.ignoreOtherArchInputFiles() ) {
892 // ignore, because this is about an architecture not in use
895 warning("ignoring file %s, %s", entry
.path
, msg
);
899 asprintf((char**)&exception
, "%s file '%s'", msg
, entry
.path
);
901 file
= new IgnoredFile(entry
.path
, entry
.modTime
, entry
.ordinal
, ld::File::Other
);
903 pthread_mutex_lock(&_parseLock
);
904 if (_remainingInputFiles
> 0)
905 _remainingInputFiles
--;
906 if (_s_logPThreads
) printf("done with index %u, %d remaining\n", slot
, _remainingInputFiles
);
908 // We are about to die, so set to zero to stop other threads from doing unneeded work.
909 _remainingInputFiles
= 0;
910 _exception
= exception
;
913 _inputFiles
[slot
] = file
;
914 if (_neededFileSlot
== slot
)
915 pthread_cond_signal(&_newFileAvailable
);
918 } while (_remainingInputFiles
);
919 if (_s_logPThreads
) printf("worker exiting\n");
920 pthread_cond_broadcast(&_parseWorkReady
);
921 pthread_cond_signal(&_newFileAvailable
);
922 pthread_mutex_unlock(&_parseLock
);
926 void InputFiles::parseWorkerThread(InputFiles
*inputFiles
) {
927 inputFiles
->parseWorkerThread();
932 ld::File
* InputFiles::addDylib(ld::dylib::File
* reader
, const Options::FileInfo
& info
)
934 _allDylibs
.insert(reader
);
936 if ( (reader
->installPath() == NULL
) && !info
.options
.fBundleLoader
) {
937 // this is a "blank" stub
938 // silently ignore it
941 // store options about how dylib will be used in dylib itself
942 if ( info
.options
.fWeakImport
)
943 reader
->setForcedWeakLinked();
944 if ( info
.options
.fReExport
)
945 reader
->setWillBeReExported();
946 if ( info
.options
.fUpward
) {
947 if ( _options
.outputKind() == Options::kDynamicLibrary
)
948 reader
->setWillBeUpwardDylib();
950 warning("ignoring upward dylib option for %s\n", info
.path
);
952 if ( info
.options
.fLazyLoad
)
953 reader
->setWillBeLazyLoadedDylb();
955 // add to map of loaded dylibs
956 const char* installPath
= reader
->installPath();
957 if ( installPath
!= NULL
) {
958 InstallNameToDylib::iterator pos
= _installPathToDylibs
.find(installPath
);
959 if ( pos
== _installPathToDylibs
.end() ) {
960 _installPathToDylibs
[strdup(installPath
)] = reader
;
963 bool dylibOnCommandLineTwice
= ( strcmp(pos
->second
->path(), reader
->path()) == 0 );
964 bool isSymlink
= false;
965 // ignore if this is a symlink to a dylib we've already loaded
966 if ( !dylibOnCommandLineTwice
) {
967 char existingDylibPath
[PATH_MAX
];
968 if ( realpath(pos
->second
->path(), existingDylibPath
) != NULL
) {
969 char newDylibPath
[PATH_MAX
];
970 if ( realpath(reader
->path(), newDylibPath
) != NULL
) {
971 isSymlink
= ( strcmp(existingDylibPath
, newDylibPath
) == 0 );
975 // remove warning for <rdar://problem/10860629> Same install name for CoreServices and CFNetwork?
976 //if ( !dylibOnCommandLineTwice && !isSymlink )
977 // warning("dylibs with same install name: %p %s and %p %s", pos->second, pos->second->path(), reader, reader->path());
980 else if ( info
.options
.fBundleLoader
)
981 _bundleLoader
= reader
;
983 // log direct readers
984 if ( ! info
.options
.fIndirectDylib
)
985 this->logDylib(reader
, false);
988 _totalDylibsLoaded
++;
990 // just add direct libraries to search-first list
991 if ( ! info
.options
.fIndirectDylib
)
992 _searchLibraries
.push_back(LibraryInfo(reader
));
999 // Called during pipelined linking to listen for available input files.
1000 // Available files are enqueued for parsing.
1001 void InputFiles::waitForInputFiles()
1003 if (_s_logPThreads
) printf("starting pipeline listener\n");
1005 const char *fifo
= _options
.pipelineFifo();
1007 std::map
<const char *, const Options::FileInfo
*, strcompclass
> fileMap
;
1008 const std::vector
<Options::FileInfo
>& files
= _options
.getInputFiles();
1009 for (std::vector
<Options::FileInfo
>::const_iterator it
= files
.begin(); it
!= files
.end(); ++it
) {
1010 const Options::FileInfo
& entry
= *it
;
1011 if (entry
.fromFileList
) {
1012 fileMap
[entry
.path
] = &entry
;
1015 FILE *fileStream
= fopen(fifo
, "r");
1017 throwf("pipelined linking error - failed to open stream. fopen() returns %s for \"%s\"\n", strerror(errno
), fifo
);
1018 while (fileMap
.size() > 0) {
1019 char path_buf
[PATH_MAX
+1];
1020 if (fgets(path_buf
, PATH_MAX
, fileStream
) == NULL
)
1021 throwf("pipelined linking error - %lu missing input files", fileMap
.size());
1022 int len
= strlen(path_buf
);
1023 if (path_buf
[len
-1] == '\n')
1024 path_buf
[len
-1] = 0;
1025 std::map
<const char *, const Options::FileInfo
*, strcompclass
>::iterator it
= fileMap
.find(path_buf
);
1026 if (it
== fileMap
.end())
1027 throwf("pipelined linking error - not in file list: %s\n", path_buf
);
1028 Options::FileInfo
* inputInfo
= (Options::FileInfo
*)it
->second
;
1029 if (!inputInfo
->checkFileExists(_options
))
1030 throwf("pipelined linking error - file does not exist: %s\n", inputInfo
->path
);
1031 pthread_mutex_lock(&_parseLock
);
1033 pthread_cond_signal(&_parseWorkReady
);
1034 inputInfo
->readyToParse
= true;
1035 if (_parseCursor
> inputInfo
->inputFileSlot
)
1036 _parseCursor
= inputInfo
->inputFileSlot
;
1037 _availableInputFiles
++;
1038 if (_s_logPThreads
) printf("pipeline listener: %s slot=%d, _parseCursor=%d, _availableInputFiles = %d remaining = %ld\n", path_buf
, inputInfo
->inputFileSlot
, _parseCursor
, _availableInputFiles
, fileMap
.size()-1);
1039 pthread_mutex_unlock(&_parseLock
);
1042 } catch (const char *msg
) {
1043 pthread_mutex_lock(&_parseLock
);
1045 pthread_cond_signal(&_newFileAvailable
);
1046 pthread_mutex_unlock(&_parseLock
);
1051 void InputFiles::waitForInputFiles(InputFiles
*inputFiles
) {
1052 inputFiles
->waitForInputFiles();
1057 void InputFiles::forEachInitialAtom(ld::File::AtomHandler
& handler
, ld::Internal
& state
)
1059 // add all direct object, archives, and dylibs
1060 const std::vector
<Options::FileInfo
>& files
= _options
.getInputFiles();
1062 for (fileIndex
=0; fileIndex
<_inputFiles
.size(); fileIndex
++) {
1065 pthread_mutex_lock(&_parseLock
);
1067 // this loop waits for the needed file to be ready (parsed by worker thread)
1068 while (_inputFiles
[fileIndex
] == NULL
&& _exception
== NULL
) {
1069 // We are starved for input. If there are still files to parse and we have
1070 // not maxed out the worker thread count start a new worker thread.
1071 if (_availableInputFiles
> 0 && _availableWorkers
> 0) {
1072 if (_s_logPThreads
) printf("starting worker\n");
1073 startThread(InputFiles::parseWorkerThread
);
1074 _availableWorkers
--;
1076 _neededFileSlot
= fileIndex
;
1077 if (_s_logPThreads
) printf("consumer blocking for %lu: %s\n", fileIndex
, files
[fileIndex
].path
);
1078 pthread_cond_wait(&_newFileAvailable
, &_parseLock
);
1084 // The input file is parsed. Assimilate it and call its atom iterator.
1085 if (_s_logPThreads
) printf("consuming slot %lu\n", fileIndex
);
1086 file
= _inputFiles
[fileIndex
];
1087 pthread_mutex_unlock(&_parseLock
);
1089 file
= _inputFiles
[fileIndex
];
1091 const Options::FileInfo
& info
= files
[fileIndex
];
1092 switch (file
->type()) {
1093 case ld::File::Reloc
:
1095 ld::relocatable::File
* reloc
= (ld::relocatable::File
*)file
;
1096 _options
.snapshot().recordObjectFile(reloc
->path());
1097 if ( _options
.dumpDependencyInfo() )
1098 _options
.dumpDependency(Options::depObjectFile
, reloc
->path());
1101 case ld::File::Dylib
:
1103 ld::dylib::File
* dylib
= (ld::dylib::File
*)file
;
1104 addDylib(dylib
, info
);
1107 case ld::File::Archive
:
1109 ld::archive::File
* archive
= (ld::archive::File
*)file
;
1110 // <rdar://problem/9740166> force loaded archives should be in LD_TRACE
1111 if ( (info
.options
.fForceLoad
|| _options
.fullyLoadArchives()) && _options
.traceArchives() )
1112 logArchive(archive
);
1113 _searchLibraries
.push_back(LibraryInfo(archive
));
1114 if ( _options
.dumpDependencyInfo() )
1115 _options
.dumpDependency(Options::depArchive
, archive
->path());
1118 case ld::File::Other
:
1122 throwf("Unknown file type for %s", file
->path());
1126 file
->forEachAtom(handler
);
1129 markExplicitlyLinkedDylibs();
1130 addLinkerOptionLibraries(state
);
1131 createIndirectDylibs();
1132 createOpaqueFileSections();
1134 while (fileIndex
< _inputFiles
.size()) {
1135 ld::File
*file
= _inputFiles
[fileIndex
];
1136 file
->forEachAtom(handler
);
1140 switch ( _options
.outputKind() ) {
1141 case Options::kStaticExecutable
:
1142 case Options::kDynamicExecutable
:
1143 // add implicit __dso_handle label
1144 handler
.doAtom(DSOHandleAtom::_s_atomExecutable
);
1145 handler
.doAtom(DSOHandleAtom::_s_atomAll
);
1146 if ( _options
.pageZeroSize() != 0 )
1147 handler
.doAtom(*new PageZeroAtom(_options
.pageZeroSize()));
1148 if ( _options
.hasCustomStack() && !_options
.needsEntryPointLoadCommand() )
1149 handler
.doAtom(*new CustomStackAtom(_options
.customStackSize()));
1151 case Options::kDynamicLibrary
:
1152 // add implicit __dso_handle label
1153 handler
.doAtom(DSOHandleAtom::_s_atomDylib
);
1154 handler
.doAtom(DSOHandleAtom::_s_atomAll
);
1156 case Options::kDynamicBundle
:
1157 // add implicit __dso_handle label
1158 handler
.doAtom(DSOHandleAtom::_s_atomBundle
);
1159 handler
.doAtom(DSOHandleAtom::_s_atomAll
);
1161 case Options::kDyld
:
1162 // add implicit __dso_handle label
1163 handler
.doAtom(DSOHandleAtom::_s_atomDyld
);
1164 handler
.doAtom(DSOHandleAtom::_s_atomAll
);
1166 case Options::kPreload
:
1167 // add implicit __mh_preload_header label
1168 handler
.doAtom(DSOHandleAtom::_s_atomPreload
);
1169 // add implicit __dso_handle label, but put it in __text section because
1170 // with -preload the mach_header is no in the address space.
1171 handler
.doAtom(DSOHandleAtom::_s_atomPreloadDSO
);
1173 case Options::kObjectFile
:
1174 handler
.doAtom(DSOHandleAtom::_s_atomObjectFile
);
1176 case Options::kKextBundle
:
1177 // add implicit __dso_handle label
1178 handler
.doAtom(DSOHandleAtom::_s_atomAll
);
1184 bool InputFiles::searchLibraries(const char* name
, bool searchDylibs
, bool searchArchives
, bool dataSymbolOnly
, ld::File::AtomHandler
& handler
) const
1186 // Check each input library.
1187 for (std::vector
<LibraryInfo
>::const_iterator it
=_searchLibraries
.begin(); it
!= _searchLibraries
.end(); ++it
) {
1188 LibraryInfo lib
= *it
;
1189 if (lib
.isDylib()) {
1191 ld::dylib::File
*dylibFile
= lib
.dylib();
1192 //fprintf(stderr, "searchLibraries(%s), looking in linked %s\n", name, dylibFile->path() );
1193 if ( dylibFile
->justInTimeforEachAtom(name
, handler
) ) {
1194 // we found a definition in this dylib
1195 // done, unless it is a weak definition in which case we keep searching
1196 _options
.snapshot().recordDylibSymbol(dylibFile
, name
);
1197 if ( !dylibFile
->hasWeakExternals() || !dylibFile
->hasWeakDefinition(name
)) {
1200 // else continue search for a non-weak definition
1204 if (searchArchives
) {
1205 ld::archive::File
*archiveFile
= lib
.archive();
1206 if ( dataSymbolOnly
) {
1207 if ( archiveFile
->justInTimeDataOnlyforEachAtom(name
, handler
) ) {
1208 if ( _options
.traceArchives() )
1209 logArchive(archiveFile
);
1210 _options
.snapshot().recordArchive(archiveFile
->path());
1211 // found data definition in static library, done
1216 if ( archiveFile
->justInTimeforEachAtom(name
, handler
) ) {
1217 if ( _options
.traceArchives() )
1218 logArchive(archiveFile
);
1219 _options
.snapshot().recordArchive(archiveFile
->path());
1220 // found definition in static library, done
1228 // search indirect dylibs
1229 if ( searchDylibs
) {
1230 for (InstallNameToDylib::const_iterator it
=_installPathToDylibs
.begin(); it
!= _installPathToDylibs
.end(); ++it
) {
1231 ld::dylib::File
* dylibFile
= it
->second
;
1232 bool searchThisDylib
= false;
1233 if ( _options
.nameSpace() == Options::kTwoLevelNameSpace
) {
1234 // for two level namesapce, just check all implicitly linked dylibs
1235 searchThisDylib
= dylibFile
->implicitlyLinked() && !dylibFile
->explicitlyLinked();
1238 // for flat namespace, check all indirect dylibs
1239 searchThisDylib
= ! dylibFile
->explicitlyLinked();
1241 if ( searchThisDylib
) {
1242 //fprintf(stderr, "searchLibraries(%s), looking in implicitly linked %s\n", name, dylibFile->path() );
1243 if ( dylibFile
->justInTimeforEachAtom(name
, handler
) ) {
1244 // we found a definition in this dylib
1245 // done, unless it is a weak definition in which case we keep searching
1246 _options
.snapshot().recordDylibSymbol(dylibFile
, name
);
1247 if ( !dylibFile
->hasWeakExternals() || !dylibFile
->hasWeakDefinition(name
)) {
1250 // else continue search for a non-weak definition
1260 bool InputFiles::searchWeakDefInDylib(const char* name
) const
1262 // search all relevant dylibs to see if any have a weak-def with this name
1263 for (InstallNameToDylib::const_iterator it
=_installPathToDylibs
.begin(); it
!= _installPathToDylibs
.end(); ++it
) {
1264 ld::dylib::File
* dylibFile
= it
->second
;
1265 if ( dylibFile
->implicitlyLinked() || dylibFile
->explicitlyLinked() ) {
1266 if ( dylibFile
->hasWeakExternals() && dylibFile
->hasWeakDefinition(name
) ) {
1274 static bool vectorContains(const std::vector
<ld::dylib::File
*>& vec
, ld::dylib::File
* key
)
1276 return std::find(vec
.begin(), vec
.end(), key
) != vec
.end();
1279 void InputFiles::dylibs(ld::Internal
& state
)
1281 bool dylibsOK
= false;
1282 switch ( _options
.outputKind() ) {
1283 case Options::kDynamicExecutable
:
1284 case Options::kDynamicLibrary
:
1285 case Options::kDynamicBundle
:
1288 case Options::kStaticExecutable
:
1289 case Options::kDyld
:
1290 case Options::kPreload
:
1291 case Options::kObjectFile
:
1292 case Options::kKextBundle
:
1297 // add command line dylibs in order
1298 for (std::vector
<ld::File
*>::const_iterator it
=_inputFiles
.begin(); it
!= _inputFiles
.end(); ++it
) {
1299 ld::dylib::File
* dylibFile
= dynamic_cast<ld::dylib::File
*>(*it
);
1300 // only add dylibs that are not "blank" dylib stubs
1301 if ( (dylibFile
!= NULL
) && ((dylibFile
->installPath() != NULL
) || (dylibFile
== _bundleLoader
)) ) {
1303 if ( ! vectorContains(state
.dylibs
, dylibFile
) ) {
1304 state
.dylibs
.push_back(dylibFile
);
1308 warning("unexpected dylib (%s) on link line", dylibFile
->path());
1311 // add implicitly linked dylibs
1312 if ( _options
.nameSpace() == Options::kTwoLevelNameSpace
) {
1313 for (InstallNameToDylib::const_iterator it
=_installPathToDylibs
.begin(); it
!= _installPathToDylibs
.end(); ++it
) {
1314 ld::dylib::File
* dylibFile
= it
->second
;
1315 if ( dylibFile
->implicitlyLinked() && dylibsOK
) {
1316 if ( ! vectorContains(state
.dylibs
, dylibFile
) ) {
1317 state
.dylibs
.push_back(dylibFile
);
1323 //fprintf(stderr, "all dylibs:\n");
1324 //for(std::vector<ld::dylib::File*>::iterator it=state.dylibs.begin(); it != state.dylibs.end(); ++it) {
1325 // const ld::dylib::File* dylib = *it;
1326 // fprintf(stderr, " %p %s\n", dylib, dylib->path());
1329 // and -bundle_loader
1330 state
.bundleLoader
= _bundleLoader
;
1332 // <rdar://problem/10807040> give an error when -nostdlib is used and libSystem is missing
1333 if ( (state
.dylibs
.size() == 0) && _options
.needsEntryPointLoadCommand() )
1334 throw "dynamic main executables must link with libSystem.dylib";