]> git.saurik.com Git - apple/ld64.git/blob - src/ld/InputFiles.cpp
c0b5cdb0d359d0a48dadc2bf99ac5d1021be6b27
[apple/ld64.git] / src / ld / InputFiles.cpp
1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-*
2 *
3 * Copyright (c) 2009-2011 Apple Inc. All rights reserved.
4 *
5 * @APPLE_LICENSE_HEADER_START@
6 *
7 * This file contains Original Code and/or Modifications of Original Code
8 * as defined in and that are subject to the Apple Public Source License
9 * Version 2.0 (the 'License'). You may not use this file except in
10 * compliance with the License. Please obtain a copy of the License at
11 * http://www.opensource.apple.com/apsl/ and read it before using this
12 * file.
13 *
14 * The Original Code and all software distributed under the License are
15 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
19 * Please see the License for the specific language governing rights and
20 * limitations under the License.
21 *
22 * @APPLE_LICENSE_HEADER_END@
23 */
24
25
26 #include <stdlib.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <sys/mman.h>
30 #include <sys/sysctl.h>
31 #include <fcntl.h>
32 #include <errno.h>
33 #include <limits.h>
34 #include <unistd.h>
35 #include <mach/mach_time.h>
36 #include <mach/vm_statistics.h>
37 #include <mach/mach_init.h>
38 #include <mach/mach_host.h>
39 #include <dlfcn.h>
40 #include <mach-o/dyld.h>
41 #include <mach-o/fat.h>
42 #include <sys/sysctl.h>
43 #include <libkern/OSAtomic.h>
44
45 #include <string>
46 #include <map>
47 #include <set>
48 #include <string>
49 #include <vector>
50 #include <list>
51 #include <algorithm>
52 #include <ext/hash_map>
53 #include <ext/hash_set>
54 #include <dlfcn.h>
55 #include <AvailabilityMacros.h>
56
57 #include "Options.h"
58
59 #include "InputFiles.h"
60 #include "macho_relocatable_file.h"
61 #include "macho_dylib_file.h"
62 #include "archive_file.h"
63 #include "lto_file.h"
64 #include "opaque_section_file.h"
65 #include "Snapshot.h"
66
67 const bool _s_logPThreads = false;
68
69 namespace ld {
70 namespace tool {
71
72 class IgnoredFile : public ld::File {
73 public:
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; };
77 };
78
79
80 class DSOHandleAtom : public ld::Atom {
81 public:
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) {}
89
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
95 { }
96 virtual void setScope(Scope) { }
97
98 virtual ~DSOHandleAtom() {}
99
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;
111 private:
112 const char* _name;
113 };
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);
125
126
127
128 class PageZeroAtom : public ld::Atom {
129 public:
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)),
134 _size(sz) {}
135
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
141 { }
142 virtual void setScope(Scope) { }
143
144 virtual ~PageZeroAtom() {}
145
146 static ld::Section _s_section;
147 static DSOHandleAtom _s_atomAll;
148 private:
149 uint64_t _size;
150 };
151 ld::Section PageZeroAtom::_s_section("__PAGEZERO", "__pagezero", ld::Section::typePageZero, true);
152
153
154 class CustomStackAtom : public ld::Atom {
155 public:
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)),
160 _size(sz) {}
161
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
167 { }
168 virtual void setScope(Scope) { }
169
170 virtual ~CustomStackAtom() {}
171
172 private:
173 uint64_t _size;
174 static ld::Section _s_section;
175 };
176 ld::Section CustomStackAtom::_s_section("__UNIXSTACK", "__stack", ld::Section::typeStack, true);
177
178
179
180 const char* InputFiles::fileArch(const uint8_t* p, unsigned len)
181 {
182 const char* result = mach_o::relocatable::archName(p);
183 if ( result != NULL )
184 return result;
185
186 result = lto::archName(p, len);
187 if ( result != NULL )
188 return result;
189
190 if ( strncmp((const char*)p, "!<arch>\n", 8) == 0 )
191 return "archive";
192
193 char *unsupported = (char *)malloc(128);
194 strcpy(unsupported, "unsupported file format (");
195 for (unsigned i=0; i<len && i < 16; i++) {
196 char buf[8];
197 sprintf(buf, " 0x%2x", p[i]);
198 strcat(unsupported, buf);
199 }
200 strcat(unsupported, " )");
201 return unsupported;
202 }
203
204
205 ld::File* InputFiles::makeFile(const Options::FileInfo& info, bool indirectDylib)
206 {
207 // map in whole file
208 uint64_t len = info.fileLen;
209 int fd = ::open(info.path, O_RDONLY, 0);
210 if ( fd == -1 )
211 throwf("can't open file, errno=%d", errno);
212 if ( info.fileLen < 20 )
213 throw "file too small";
214
215 uint8_t* p = (uint8_t*)::mmap(NULL, info.fileLen, PROT_READ, MAP_FILE | MAP_PRIVATE, fd, 0);
216 if ( p == (uint8_t*)(-1) )
217 throwf("can't map file, errno=%d", errno);
218
219 // if fat file, skip to architecture we want
220 // Note: fat header is always big-endian
221 bool isFatFile = false;
222 uint32_t sliceToUse, sliceCount;
223 const fat_header* fh = (fat_header*)p;
224 if ( fh->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
225 isFatFile = true;
226 const struct fat_arch* archs = (struct fat_arch*)(p + sizeof(struct fat_header));
227 bool sliceFound = false;
228 sliceCount = OSSwapBigToHostInt32(fh->nfat_arch);
229 if ( _options.preferSubArchitecture() ) {
230 // first try to find a slice that match cpu-type and cpu-sub-type
231 for (uint32_t i=0; i < sliceCount; ++i) {
232 if ( (OSSwapBigToHostInt32(archs[i].cputype) == (uint32_t)_options.architecture())
233 && (OSSwapBigToHostInt32(archs[i].cpusubtype) == (uint32_t)_options.subArchitecture()) ) {
234 sliceToUse = i;
235 sliceFound = true;
236 break;
237 }
238 }
239 }
240 if ( !sliceFound ) {
241 // look for any slice that matches just cpu-type
242 for (uint32_t i=0; i < sliceCount; ++i) {
243 if ( OSSwapBigToHostInt32(archs[i].cputype) == (uint32_t)_options.architecture() ) {
244 sliceToUse = i;
245 sliceFound = true;
246 break;
247 }
248 }
249 }
250 if ( sliceFound ) {
251 uint32_t fileOffset = OSSwapBigToHostInt32(archs[sliceToUse].offset);
252 len = OSSwapBigToHostInt32(archs[sliceToUse].size);
253 if ( fileOffset+len > info.fileLen ) {
254 throwf("truncated fat file. Slice from %u to %llu is past end of file with length %llu",
255 fileOffset, fileOffset+len, info.fileLen);
256 }
257 // if requested architecture is page aligned within fat file, then remap just that portion of file
258 if ( (fileOffset & 0x00000FFF) == 0 ) {
259 // unmap whole file
260 munmap((caddr_t)p, info.fileLen);
261 // re-map just part we need
262 p = (uint8_t*)::mmap(NULL, len, PROT_READ, MAP_FILE | MAP_PRIVATE, fd, fileOffset);
263 if ( p == (uint8_t*)(-1) )
264 throwf("can't re-map file, errno=%d", errno);
265 }
266 else {
267 p = &p[fileOffset];
268 }
269 }
270 }
271 ::close(fd);
272
273 // see if it is an object file
274 mach_o::relocatable::ParserOptions objOpts;
275 objOpts.architecture = _options.architecture();
276 objOpts.objSubtypeMustMatch = !_options.allowSubArchitectureMismatches();
277 objOpts.logAllFiles = _options.logAllFiles();
278 objOpts.convertUnwindInfo = _options.needsUnwindInfoSection();
279 objOpts.subType = _options.subArchitecture();
280 ld::relocatable::File* objResult = mach_o::relocatable::parse(p, len, info.path, info.modTime, info.ordinal, objOpts);
281 if ( objResult != NULL ) {
282 OSAtomicAdd64(len, &_totalObjectSize);
283 OSAtomicIncrement32(&_totalObjectLoaded);
284 return objResult;
285 }
286
287 // see if it is an llvm object file
288 objResult = lto::parse(p, len, info.path, info.modTime, info.ordinal, _options.architecture(), _options.subArchitecture(), _options.logAllFiles());
289 if ( objResult != NULL ) {
290 OSAtomicAdd64(len, &_totalObjectSize);
291 OSAtomicIncrement32(&_totalObjectLoaded);
292 return objResult;
293 }
294
295 // see if it is a dynamic library
296 ld::dylib::File* dylibResult = mach_o::dylib::parse(p, len, info.path, info.modTime, _options, info.ordinal, info.options.fBundleLoader, indirectDylib);
297 if ( dylibResult != NULL ) {
298 return dylibResult;
299 }
300
301 // see if it is a static library
302 ::archive::ParserOptions archOpts;
303 archOpts.objOpts = objOpts;
304 archOpts.forceLoadThisArchive = info.options.fForceLoad;
305 archOpts.forceLoadAll = _options.fullyLoadArchives();
306 archOpts.forceLoadObjC = _options.loadAllObjcObjectsFromArchives();
307 archOpts.objcABI2 = _options.objCABIVersion2POverride();
308 archOpts.verboseLoad = _options.whyLoad();
309 archOpts.logAllFiles = _options.logAllFiles();
310 ld::archive::File* archiveResult = ::archive::parse(p, len, info.path, info.modTime, info.ordinal, archOpts);
311 if ( archiveResult != NULL ) {
312 OSAtomicAdd64(len, &_totalArchiveSize);
313 OSAtomicIncrement32(&_totalArchivesLoaded);
314 return archiveResult;
315 }
316
317 // does not seem to be any valid linker input file, check LTO misconfiguration problems
318 if ( lto::archName((uint8_t*)p, len) != NULL ) {
319 if ( lto::libLTOisLoaded() ) {
320 throwf("lto file was built for %s which is not the architecture being linked (%s): %s", fileArch(p, len), _options.architectureName(), info.path);
321 }
322 else {
323 const char* libLTO = "libLTO.dylib";
324 char ldPath[PATH_MAX];
325 char tmpPath[PATH_MAX];
326 char libLTOPath[PATH_MAX];
327 uint32_t bufSize = PATH_MAX;
328 if ( _options.overridePathlibLTO() != NULL ) {
329 libLTO = _options.overridePathlibLTO();
330 }
331 else if ( _NSGetExecutablePath(ldPath, &bufSize) != -1 ) {
332 if ( realpath(ldPath, tmpPath) != NULL ) {
333 char* lastSlash = strrchr(tmpPath, '/');
334 if ( lastSlash != NULL )
335 strcpy(lastSlash, "/../lib/libLTO.dylib");
336 libLTO = tmpPath;
337 if ( realpath(tmpPath, libLTOPath) != NULL )
338 libLTO = libLTOPath;
339 }
340 }
341 throwf("could not process llvm bitcode object file, because %s could not be loaded", libLTO);
342 }
343 }
344
345 // error handling
346 if ( ((fat_header*)p)->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
347 throwf("missing required architecture %s in file %s (%u slices)", _options.architectureName(), info.path, sliceCount);
348 }
349 else {
350 if ( isFatFile )
351 throwf("file is universal (%u slices) but does not contain a(n) %s slice: %s", sliceCount, _options.architectureName(), info.path);
352 else
353 throwf("file was built for %s which is not the architecture being linked (%s): %s", fileArch(p, len), _options.architectureName(), info.path);
354 }
355 }
356
357 void InputFiles::logDylib(ld::File* file, bool indirect)
358 {
359 if ( _options.traceDylibs() ) {
360 const char* fullPath = file->path();
361 char realName[MAXPATHLEN];
362 if ( realpath(fullPath, realName) != NULL )
363 fullPath = realName;
364 const ld::dylib::File* dylib = dynamic_cast<const ld::dylib::File*>(file);
365 if ( (dylib != NULL ) && dylib->willBeUpwardDylib() ) {
366 // don't log upward dylibs when XBS is computing dependencies
367 logTraceInfo("[Logging for XBS] Used upward dynamic library: %s\n", fullPath);
368 }
369 else {
370 if ( indirect )
371 logTraceInfo("[Logging for XBS] Used indirect dynamic library: %s\n", fullPath);
372 else
373 logTraceInfo("[Logging for XBS] Used dynamic library: %s\n", fullPath);
374 }
375 }
376 }
377
378 void InputFiles::logArchive(ld::File* file) const
379 {
380 if ( _options.traceArchives() && (_archiveFilesLogged.count(file) == 0) ) {
381 // <rdar://problem/4947347> LD_TRACE_ARCHIVES should only print out when a .o is actually used from an archive
382 _archiveFilesLogged.insert(file);
383 const char* fullPath = file->path();
384 char realName[MAXPATHLEN];
385 if ( realpath(fullPath, realName) != NULL )
386 fullPath = realName;
387 logTraceInfo("[Logging for XBS] Used static archive: %s\n", fullPath);
388 }
389 }
390
391
392 void InputFiles::logTraceInfo(const char* format, ...) const
393 {
394 // one time open() of custom LD_TRACE_FILE
395 static int trace_file = -1;
396 if ( trace_file == -1 ) {
397 const char *trace_file_path = _options.traceOutputFile();
398 if ( trace_file_path != NULL ) {
399 trace_file = open(trace_file_path, O_WRONLY | O_APPEND | O_CREAT, 0666);
400 if ( trace_file == -1 )
401 throwf("Could not open or create trace file: %s", trace_file_path);
402 }
403 else {
404 trace_file = fileno(stderr);
405 }
406 }
407
408 char trace_buffer[MAXPATHLEN * 2];
409 va_list ap;
410 va_start(ap, format);
411 int length = vsnprintf(trace_buffer, sizeof(trace_buffer), format, ap);
412 va_end(ap);
413 char* buffer_ptr = trace_buffer;
414
415 while (length > 0) {
416 ssize_t amount_written = write(trace_file, buffer_ptr, length);
417 if(amount_written == -1)
418 /* Failure to write shouldn't fail the build. */
419 return;
420 buffer_ptr += amount_written;
421 length -= amount_written;
422 }
423 }
424
425 ld::dylib::File* InputFiles::findDylib(const char* installPath, const char* fromPath)
426 {
427 //fprintf(stderr, "findDylib(%s, %s)\n", installPath, fromPath);
428 InstallNameToDylib::iterator pos = _installPathToDylibs.find(installPath);
429 if ( pos != _installPathToDylibs.end() ) {
430 return pos->second;
431 }
432 else {
433 // allow -dylib_path option to override indirect library to use
434 for (std::vector<Options::DylibOverride>::const_iterator dit = _options.dylibOverrides().begin(); dit != _options.dylibOverrides().end(); ++dit) {
435 if ( strcmp(dit->installName,installPath) == 0 ) {
436 try {
437 Options::FileInfo info = _options.findFile(dit->useInstead);
438 _indirectDylibOrdinal = _indirectDylibOrdinal.nextIndirectDylibOrdinal();
439 info.ordinal = _indirectDylibOrdinal;
440 ld::File* reader = this->makeFile(info, true);
441 ld::dylib::File* dylibReader = dynamic_cast<ld::dylib::File*>(reader);
442 if ( dylibReader != NULL ) {
443 addDylib(dylibReader, info);
444 //_installPathToDylibs[strdup(installPath)] = dylibReader;
445 this->logDylib(dylibReader, true);
446 return dylibReader;
447 }
448 else
449 throwf("indirect dylib at %s is not a dylib", dit->useInstead);
450 }
451 catch (const char* msg) {
452 warning("ignoring -dylib_file option, %s", msg);
453 }
454 }
455 }
456 char newPath[MAXPATHLEN];
457 // handle @loader_path
458 if ( strncmp(installPath, "@loader_path/", 13) == 0 ) {
459 strcpy(newPath, fromPath);
460 char* addPoint = strrchr(newPath,'/');
461 if ( addPoint != NULL )
462 strcpy(&addPoint[1], &installPath[13]);
463 else
464 strcpy(newPath, &installPath[13]);
465 installPath = newPath;
466 }
467 // note: @executable_path case is handled inside findFileUsingPaths()
468 // search for dylib using -F and -L paths
469 Options::FileInfo info = _options.findFileUsingPaths(installPath);
470 _indirectDylibOrdinal = _indirectDylibOrdinal.nextIndirectDylibOrdinal();
471 info.ordinal = _indirectDylibOrdinal;
472 try {
473 ld::File* reader = this->makeFile(info, true);
474 ld::dylib::File* dylibReader = dynamic_cast<ld::dylib::File*>(reader);
475 if ( dylibReader != NULL ) {
476 //assert(_installPathToDylibs.find(installPath) != _installPathToDylibs.end());
477 //_installPathToDylibs[strdup(installPath)] = dylibReader;
478 addDylib(dylibReader, info);
479 this->logDylib(dylibReader, true);
480 return dylibReader;
481 }
482 else
483 throwf("indirect dylib at %s is not a dylib", info.path);
484 }
485 catch (const char* msg) {
486 throwf("in %s, %s", info.path, msg);
487 }
488 }
489 }
490
491
492
493 void InputFiles::createIndirectDylibs()
494 {
495 _allDirectDylibsLoaded = true;
496 _indirectDylibOrdinal = ld::File::Ordinal::indirectDylibBase();
497
498 // mark all dylibs initially specified as required and check if they can be used
499 for (InstallNameToDylib::iterator it=_installPathToDylibs.begin(); it != _installPathToDylibs.end(); it++) {
500 it->second->setExplicitlyLinked();
501 this->checkDylibClientRestrictions(it->second);
502 }
503
504 // keep processing dylibs until no more dylibs are added
505 unsigned long lastMapSize = 0;
506 std::set<ld::dylib::File*> dylibsProcessed;
507 while ( lastMapSize != _allDylibs.size() ) {
508 lastMapSize = _allDylibs.size();
509 // can't iterator _installPathToDylibs while modifying it, so use temp buffer
510 std::vector<ld::dylib::File*> unprocessedDylibs;
511 for (std::set<ld::dylib::File*>::iterator it=_allDylibs.begin(); it != _allDylibs.end(); it++) {
512 if ( dylibsProcessed.count(*it) == 0 )
513 unprocessedDylibs.push_back(*it);
514 }
515 for (std::vector<ld::dylib::File*>::iterator it=unprocessedDylibs.begin(); it != unprocessedDylibs.end(); it++) {
516 dylibsProcessed.insert(*it);
517 (*it)->processIndirectLibraries(this, _options.implicitlyLinkIndirectPublicDylibs());
518 }
519 }
520
521 // go back over original dylibs and mark sub frameworks as re-exported
522 if ( _options.outputKind() == Options::kDynamicLibrary ) {
523 const char* myLeaf = strrchr(_options.installPath(), '/');
524 if ( myLeaf != NULL ) {
525 for (std::vector<class ld::File*>::const_iterator it=_inputFiles.begin(); it != _inputFiles.end(); it++) {
526 ld::dylib::File* dylibReader = dynamic_cast<ld::dylib::File*>(*it);
527 if ( dylibReader != NULL ) {
528 const char* childParent = dylibReader->parentUmbrella();
529 if ( childParent != NULL ) {
530 if ( strcmp(childParent, &myLeaf[1]) == 0 ) {
531 // mark that this dylib will be re-exported
532 dylibReader->setWillBeReExported();
533 }
534 }
535 }
536 }
537 }
538 }
539
540 }
541
542 void InputFiles::createOpaqueFileSections()
543 {
544 // extra command line section always at end
545 for (Options::ExtraSection::const_iterator it=_options.extraSectionsBegin(); it != _options.extraSectionsEnd(); ++it) {
546 _inputFiles.push_back(opaque_section::parse(it->segmentName, it->sectionName, it->path, it->data, it->dataLen));
547 }
548
549 }
550
551
552 void InputFiles::checkDylibClientRestrictions(ld::dylib::File* dylib)
553 {
554 // Check for any restrictions on who can link with this dylib
555 const char* dylibParentName = dylib->parentUmbrella() ;
556 const std::vector<const char*>* clients = dylib->allowableClients();
557 if ( (dylibParentName != NULL) || (clients != NULL) ) {
558 // only dylibs that are in an umbrella or have a client list need verification
559 const char* installName = _options.installPath();
560 const char* installNameLastSlash = strrchr(installName, '/');
561 bool isParent = false;
562 bool isSibling = false;
563 bool isAllowableClient = false;
564 // There are three cases:
565 if ( (dylibParentName != NULL) && (installNameLastSlash != NULL) ) {
566 // starts after last slash
567 const char* myName = &installNameLastSlash[1];
568 unsigned int myNameLen = strlen(myName);
569 if ( strncmp(myName, "lib", 3) == 0 )
570 myName = &myName[3];
571 // up to first dot
572 const char* firstDot = strchr(myName, '.');
573 if ( firstDot != NULL )
574 myNameLen = firstDot - myName;
575 // up to first underscore
576 const char* firstUnderscore = strchr(myName, '_');
577 if ( (firstUnderscore != NULL) && ((firstUnderscore - myName) < (int)myNameLen) )
578 myNameLen = firstUnderscore - myName;
579
580 // case 1) The dylib has a parent umbrella, and we are creating the parent umbrella
581 isParent = ( (strlen(dylibParentName) == myNameLen) && (strncmp(myName, dylibParentName, myNameLen) == 0) );
582
583 // case 2) The dylib has a parent umbrella, and we are creating a sibling with the same parent
584 isSibling = ( (_options.umbrellaName() != NULL) && (strcmp(_options.umbrellaName(), dylibParentName) == 0) );
585 }
586
587 if ( !isParent && !isSibling && (clients != NULL) ) {
588 // case 3) the dylib has a list of allowable clients, and we are creating one of them
589 const char* clientName = _options.clientName();
590 int clientNameLen = 0;
591 if ( clientName != NULL ) {
592 // use client name as specified on command line
593 clientNameLen = strlen(clientName);
594 }
595 else {
596 // infer client name from output path (e.g. xxx/libfoo_variant.A.dylib --> foo, Bar.framework/Bar_variant --> Bar)
597 clientName = installName;
598 clientNameLen = strlen(clientName);
599 // starts after last slash
600 if ( installNameLastSlash != NULL )
601 clientName = &installNameLastSlash[1];
602 if ( strncmp(clientName, "lib", 3) == 0 )
603 clientName = &clientName[3];
604 // up to first dot
605 const char* firstDot = strchr(clientName, '.');
606 if ( firstDot != NULL )
607 clientNameLen = firstDot - clientName;
608 // up to first underscore
609 const char* firstUnderscore = strchr(clientName, '_');
610 if ( (firstUnderscore != NULL) && ((firstUnderscore - clientName) < clientNameLen) )
611 clientNameLen = firstUnderscore - clientName;
612 }
613
614 // Use clientName to check if this dylib is able to link against the allowable clients.
615 for (std::vector<const char*>::const_iterator it = clients->begin(); it != clients->end(); it++) {
616 if ( strncmp(*it, clientName, clientNameLen) == 0 )
617 isAllowableClient = true;
618 }
619 }
620
621 if ( !isParent && !isSibling && !isAllowableClient ) {
622 if ( dylibParentName != NULL ) {
623 throwf("cannot link directly with %s. Link against the umbrella framework '%s.framework' instead.",
624 dylib->path(), dylibParentName);
625 }
626 else {
627 throwf("cannot link directly with %s", dylib->path());
628 }
629 }
630 }
631 }
632
633
634 void InputFiles::inferArchitecture(Options& opts, const char** archName)
635 {
636 _inferredArch = true;
637 // scan all input files, looking for a thin .o file.
638 // the first one found is presumably the architecture to link
639 uint8_t buffer[sizeof(mach_header_64)];
640 const std::vector<Options::FileInfo>& files = opts.getInputFiles();
641 for (std::vector<Options::FileInfo>::const_iterator it = files.begin(); it != files.end(); ++it) {
642 int fd = ::open(it->path, O_RDONLY, 0);
643 if ( fd != -1 ) {
644 ssize_t amount = read(fd, buffer, sizeof(buffer));
645 ::close(fd);
646 if ( amount >= (ssize_t)sizeof(buffer) ) {
647 cpu_type_t type;
648 cpu_subtype_t subtype;
649 if ( mach_o::relocatable::isObjectFile(buffer, &type, &subtype) ) {
650 opts.setArchitecture(type, subtype);
651 *archName = opts.architectureName();
652 return;
653 }
654 }
655 }
656 }
657
658 // no thin .o files found, so default to same architecture this tool was built as
659 warning("-arch not specified");
660 #if __i386__
661 opts.setArchitecture(CPU_TYPE_I386, CPU_SUBTYPE_X86_ALL);
662 #elif __x86_64__
663 opts.setArchitecture(CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_ALL);
664 #elif __arm__
665 opts.setArchitecture(CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V6);
666 #else
667 #error unknown default architecture
668 #endif
669 *archName = opts.architectureName();
670 }
671
672
673 InputFiles::InputFiles(Options& opts, const char** archName)
674 : _totalObjectSize(0), _totalArchiveSize(0),
675 _totalObjectLoaded(0), _totalArchivesLoaded(0), _totalDylibsLoaded(0),
676 _options(opts), _bundleLoader(NULL),
677 _allDirectDylibsLoaded(false), _inferredArch(false), _fileMonitor(-1),
678 _exception(NULL)
679 {
680 // fStartCreateReadersTime = mach_absolute_time();
681 if ( opts.architecture() == 0 ) {
682 // command line missing -arch, so guess arch
683 inferArchitecture(opts, archName);
684 }
685 #if HAVE_PTHREADS
686 pthread_mutex_init(&_parseLock, NULL);
687 pthread_cond_init(&_parseWorkReady, NULL);
688 pthread_cond_init(&_newFileAvailable, NULL);
689 #endif
690 const std::vector<Options::FileInfo>& files = _options.getInputFiles();
691 if ( files.size() == 0 )
692 throw "no object files specified";
693
694 _inputFiles.reserve(files.size());
695 #if HAVE_PTHREADS
696 unsigned int inputFileSlot = 0;
697 _availableInputFiles = 0;
698 _parseCursor = 0;
699 #endif
700 Options::FileInfo* entry;
701 for (std::vector<Options::FileInfo>::const_iterator it = files.begin(); it != files.end(); ++it) {
702 entry = (Options::FileInfo*)&(*it);
703 #if HAVE_PTHREADS
704 // Assign input file slots to all the FileInfos.
705 // Also chain all FileInfos into one big list to set up for worker threads to do parsing.
706 entry->inputFileSlot = inputFileSlot;
707 entry->readyToParse = !entry->fromFileList || !_options.pipelineEnabled();
708 if (entry->readyToParse)
709 _availableInputFiles++;
710 _inputFiles.push_back(NULL);
711 inputFileSlot++;
712 #else
713 // In the non-threaded case just parse the file now.
714 _inputFiles.push_back(makeFile(*entry, false));
715 #endif
716 }
717
718 #if HAVE_PTHREADS
719 _remainingInputFiles = files.size();
720
721 // initialize info for parsing input files on worker threads
722 unsigned int ncpus;
723 int mib[2];
724 size_t len = sizeof(ncpus);
725 mib[0] = CTL_HW;
726 mib[1] = HW_NCPU;
727 if (sysctl(mib, 2, &ncpus, &len, NULL, 0) != 0) {
728 ncpus = 1;
729 }
730 _availableWorkers = MIN(ncpus, files.size()); // max # workers we permit
731 _idleWorkers = 0;
732
733 if (_options.pipelineEnabled()) {
734 // start up a thread to listen for available input files
735 startThread(InputFiles::waitForInputFiles);
736 }
737
738 // Start up one parser thread. More start on demand as parsed input files get consumed.
739 startThread(InputFiles::parseWorkerThread);
740 _availableWorkers--;
741 #else
742 if (_options.pipelineEnabled()) {
743 throwf("pipelined linking not supported on this platform");
744 }
745 #endif
746 }
747
748
749 #if HAVE_PTHREADS
750 void InputFiles::startThread(void (*threadFunc)(InputFiles *)) const {
751 pthread_t thread;
752 pthread_attr_t attr;
753 pthread_attr_init(&attr);
754 // set a nice big stack (same as main thread) because some code uses potentially large stack buffers
755 pthread_attr_setstacksize(&attr, 8 * 1024 * 1024);
756 pthread_create(&thread, &attr, (void *(*)(void*))threadFunc, (void *)this);
757 pthread_detach(thread);
758 pthread_attr_destroy(&attr);
759 }
760
761 // Work loop for input file parsing threads
762 void InputFiles::parseWorkerThread() {
763 ld::File *file;
764 const char *exception = NULL;
765 pthread_mutex_lock(&_parseLock);
766 const std::vector<Options::FileInfo>& files = _options.getInputFiles();
767 if (_s_logPThreads) printf("worker starting\n");
768 do {
769 if (_availableInputFiles == 0) {
770 _idleWorkers++;
771 pthread_cond_wait(&_parseWorkReady, &_parseLock);
772 _idleWorkers--;
773 } else {
774 int slot = _parseCursor;
775 while (slot < (int)files.size() && (_inputFiles[slot] != NULL || !files[slot].readyToParse))
776 slot++;
777 assert(slot < (int)files.size());
778 Options::FileInfo& entry = (Options::FileInfo&)files[slot];
779 _parseCursor = slot+1;
780 _availableInputFiles--;
781 entry.readyToParse = false; // to avoid multiple threads finding this file
782 pthread_mutex_unlock(&_parseLock);
783 if (_s_logPThreads) printf("parsing index %u\n", slot);
784 try {
785 file = makeFile(entry, false);
786 } catch (const char *msg) {
787 if ( (strstr(msg, "architecture") != NULL) && !_options.errorOnOtherArchFiles() ) {
788 if ( _options.ignoreOtherArchInputFiles() ) {
789 // ignore, because this is about an architecture not in use
790 }
791 else {
792 warning("ignoring file %s, %s", entry.path, msg);
793 }
794 } else {
795 exception = msg;
796 }
797 file = new IgnoredFile(entry.path, entry.modTime, entry.ordinal, ld::File::Other);
798 }
799 pthread_mutex_lock(&_parseLock);
800 if (_remainingInputFiles > 0)
801 _remainingInputFiles--;
802 if (_s_logPThreads) printf("done with index %u, %d remaining\n", slot, _remainingInputFiles);
803 if (exception) {
804 // We are about to die, so set to zero to stop other threads from doing unneeded work.
805 _remainingInputFiles = 0;
806 _exception = exception;
807 } else {
808 _inputFiles[slot] = file;
809 if (_neededFileSlot == slot)
810 pthread_cond_signal(&_newFileAvailable);
811 }
812 }
813 } while (_remainingInputFiles);
814 if (_s_logPThreads) printf("worker exiting\n");
815 pthread_cond_broadcast(&_parseWorkReady);
816 pthread_cond_signal(&_newFileAvailable);
817 pthread_mutex_unlock(&_parseLock);
818 }
819
820
821 void InputFiles::parseWorkerThread(InputFiles *inputFiles) {
822 inputFiles->parseWorkerThread();
823 }
824 #endif
825
826
827 ld::File* InputFiles::addDylib(ld::dylib::File* reader, const Options::FileInfo& info)
828 {
829 _allDylibs.insert(reader);
830
831 if ( (reader->installPath() == NULL) && !info.options.fBundleLoader ) {
832 // this is a "blank" stub
833 // silently ignore it
834 return reader;
835 }
836 // store options about how dylib will be used in dylib itself
837 if ( info.options.fWeakImport )
838 reader->setForcedWeakLinked();
839 if ( info.options.fReExport )
840 reader->setWillBeReExported();
841 if ( info.options.fUpward ) {
842 if ( _options.outputKind() == Options::kDynamicLibrary )
843 reader->setWillBeUpwardDylib();
844 else
845 warning("ignoring upward dylib option for %s\n", info.path);
846 }
847 if ( info.options.fLazyLoad )
848 reader->setWillBeLazyLoadedDylb();
849
850 // add to map of loaded dylibs
851 const char* installPath = reader->installPath();
852 if ( installPath != NULL ) {
853 InstallNameToDylib::iterator pos = _installPathToDylibs.find(installPath);
854 if ( pos == _installPathToDylibs.end() ) {
855 _installPathToDylibs[strdup(installPath)] = reader;
856 }
857 else {
858 bool dylibOnCommandLineTwice = ( strcmp(pos->second->path(), reader->path()) == 0 );
859 bool isSymlink = false;
860 // ignore if this is a symlink to a dylib we've already loaded
861 if ( !dylibOnCommandLineTwice ) {
862 char existingDylibPath[PATH_MAX];
863 if ( realpath(pos->second->path(), existingDylibPath) != NULL ) {
864 char newDylibPath[PATH_MAX];
865 if ( realpath(reader->path(), newDylibPath) != NULL ) {
866 isSymlink = ( strcmp(existingDylibPath, newDylibPath) == 0 );
867 }
868 }
869 }
870 // remove warning for <rdar://problem/10860629> Same install name for CoreServices and CFNetwork?
871 //if ( !dylibOnCommandLineTwice && !isSymlink )
872 // warning("dylibs with same install name: %s and %s", pos->second->path(), reader->path());
873 }
874 }
875 else if ( info.options.fBundleLoader )
876 _bundleLoader = reader;
877
878 // log direct readers
879 if ( !_allDirectDylibsLoaded )
880 this->logDylib(reader, false);
881
882 // update stats
883 _totalDylibsLoaded++;
884
885 _searchLibraries.push_back(LibraryInfo(reader));
886 return reader;
887 }
888
889
890 #if HAVE_PTHREADS
891 // Called during pipelined linking to listen for available input files.
892 // Available files are enqueued for parsing.
893 void InputFiles::waitForInputFiles()
894 {
895 if (_s_logPThreads) printf("starting pipeline listener\n");
896 try {
897 const char *fifo = _options.pipelineFifo();
898 assert(fifo);
899 std::map<const char *, const Options::FileInfo*, strcompclass> fileMap;
900 const std::vector<Options::FileInfo>& files = _options.getInputFiles();
901 for (std::vector<Options::FileInfo>::const_iterator it = files.begin(); it != files.end(); ++it) {
902 const Options::FileInfo& entry = *it;
903 if (entry.fromFileList) {
904 fileMap[entry.path] = &entry;
905 }
906 }
907 FILE *fileStream = fopen(fifo, "r");
908 if (!fileStream)
909 throwf("pipelined linking error - failed to open stream. fopen() returns %s for \"%s\"\n", strerror(errno), fifo);
910 while (fileMap.size() > 0) {
911 char path_buf[PATH_MAX+1];
912 if (fgets(path_buf, PATH_MAX, fileStream) == NULL)
913 throwf("pipelined linking error - %lu missing input files", fileMap.size());
914 int len = strlen(path_buf);
915 if (path_buf[len-1] == '\n')
916 path_buf[len-1] = 0;
917 std::map<const char *, const Options::FileInfo*, strcompclass>::iterator it = fileMap.find(path_buf);
918 if (it == fileMap.end())
919 throwf("pipelined linking error - not in file list: %s\n", path_buf);
920 Options::FileInfo* inputInfo = (Options::FileInfo*)it->second;
921 if (!inputInfo->checkFileExists())
922 throwf("pipelined linking error - file does not exist: %s\n", inputInfo->path);
923 pthread_mutex_lock(&_parseLock);
924 if (_idleWorkers)
925 pthread_cond_signal(&_parseWorkReady);
926 inputInfo->readyToParse = true;
927 if (_parseCursor > inputInfo->inputFileSlot)
928 _parseCursor = inputInfo->inputFileSlot;
929 _availableInputFiles++;
930 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);
931 pthread_mutex_unlock(&_parseLock);
932 fileMap.erase(it);
933 }
934 } catch (const char *msg) {
935 pthread_mutex_lock(&_parseLock);
936 _exception = msg;
937 pthread_cond_signal(&_newFileAvailable);
938 pthread_mutex_unlock(&_parseLock);
939 }
940 }
941
942
943 void InputFiles::waitForInputFiles(InputFiles *inputFiles) {
944 inputFiles->waitForInputFiles();
945 }
946 #endif
947
948
949 void InputFiles::forEachInitialAtom(ld::File::AtomHandler& handler)
950 {
951 // add all direct object, archives, and dylibs
952 const std::vector<Options::FileInfo>& files = _options.getInputFiles();
953 size_t fileIndex;
954 for (fileIndex=0; fileIndex<_inputFiles.size(); fileIndex++) {
955 ld::File *file;
956 #if HAVE_PTHREADS
957 pthread_mutex_lock(&_parseLock);
958
959 // this loop waits for the needed file to be ready (parsed by worker thread)
960 while (_inputFiles[fileIndex] == NULL && _exception == NULL) {
961 // We are starved for input. If there are still files to parse and we have
962 // not maxed out the worker thread count start a new worker thread.
963 if (_availableInputFiles > 0 && _availableWorkers > 0) {
964 if (_s_logPThreads) printf("starting worker\n");
965 startThread(InputFiles::parseWorkerThread);
966 _availableWorkers--;
967 }
968 _neededFileSlot = fileIndex;
969 if (_s_logPThreads) printf("consumer blocking for %lu: %s\n", fileIndex, files[fileIndex].path);
970 pthread_cond_wait(&_newFileAvailable, &_parseLock);
971 }
972
973 if (_exception)
974 throw _exception;
975
976 // The input file is parsed. Assimilate it and call its atom iterator.
977 if (_s_logPThreads) printf("consuming slot %lu\n", fileIndex);
978 file = _inputFiles[fileIndex];
979 pthread_mutex_unlock(&_parseLock);
980 #else
981 file = _inputFiles[fileIndex];
982 #endif
983 const Options::FileInfo& info = files[fileIndex];
984 switch (file->type()) {
985 case ld::File::Reloc:
986 {
987 ld::relocatable::File* reloc = (ld::relocatable::File*)file;
988 _options.snapshot().recordObjectFile(reloc->path());
989 }
990 break;
991 case ld::File::Dylib:
992 {
993 ld::dylib::File* dylib = (ld::dylib::File*)file;
994 addDylib(dylib, info);
995 }
996 break;
997 case ld::File::Archive:
998 {
999 ld::archive::File* archive = (ld::archive::File*)file;
1000 // <rdar://problem/9740166> force loaded archives should be in LD_TRACE
1001 if ( (info.options.fForceLoad || _options.fullyLoadArchives()) && _options.traceArchives() )
1002 logArchive(archive);
1003 _searchLibraries.push_back(LibraryInfo(archive));
1004 }
1005 break;
1006 case ld::File::Other:
1007 break;
1008 default:
1009 {
1010 throwf("Unknown file type for %s", file->path());
1011 }
1012 break;
1013 }
1014 file->forEachAtom(handler);
1015 }
1016
1017 createIndirectDylibs();
1018 createOpaqueFileSections();
1019
1020 while (fileIndex < _inputFiles.size()) {
1021 ld::File *file = _inputFiles[fileIndex];
1022 file->forEachAtom(handler);
1023 fileIndex++;
1024 }
1025
1026 switch ( _options.outputKind() ) {
1027 case Options::kStaticExecutable:
1028 case Options::kDynamicExecutable:
1029 // add implicit __dso_handle label
1030 handler.doAtom(DSOHandleAtom::_s_atomExecutable);
1031 handler.doAtom(DSOHandleAtom::_s_atomAll);
1032 if ( _options.pageZeroSize() != 0 )
1033 handler.doAtom(*new PageZeroAtom(_options.pageZeroSize()));
1034 if ( _options.hasCustomStack() && !_options.needsEntryPointLoadCommand() )
1035 handler.doAtom(*new CustomStackAtom(_options.customStackSize()));
1036 break;
1037 case Options::kDynamicLibrary:
1038 // add implicit __dso_handle label
1039 handler.doAtom(DSOHandleAtom::_s_atomDylib);
1040 handler.doAtom(DSOHandleAtom::_s_atomAll);
1041 break;
1042 case Options::kDynamicBundle:
1043 // add implicit __dso_handle label
1044 handler.doAtom(DSOHandleAtom::_s_atomBundle);
1045 handler.doAtom(DSOHandleAtom::_s_atomAll);
1046 break;
1047 case Options::kDyld:
1048 // add implicit __dso_handle label
1049 handler.doAtom(DSOHandleAtom::_s_atomDyld);
1050 handler.doAtom(DSOHandleAtom::_s_atomAll);
1051 break;
1052 case Options::kPreload:
1053 // add implicit __mh_preload_header label
1054 handler.doAtom(DSOHandleAtom::_s_atomPreload);
1055 // add implicit __dso_handle label, but put it in __text section because
1056 // with -preload the mach_header is no in the address space.
1057 handler.doAtom(DSOHandleAtom::_s_atomPreloadDSO);
1058 break;
1059 case Options::kObjectFile:
1060 handler.doAtom(DSOHandleAtom::_s_atomObjectFile);
1061 break;
1062 case Options::kKextBundle:
1063 // add implicit __dso_handle label
1064 handler.doAtom(DSOHandleAtom::_s_atomAll);
1065 break;
1066 }
1067 }
1068
1069
1070 bool InputFiles::searchLibraries(const char* name, bool searchDylibs, bool searchArchives, bool dataSymbolOnly, ld::File::AtomHandler& handler) const
1071 {
1072 // Check each input library.
1073 std::vector<LibraryInfo>::const_iterator libIterator = _searchLibraries.begin();
1074
1075
1076 while (libIterator != _searchLibraries.end()) {
1077 LibraryInfo lib = *libIterator;
1078 if (lib.isDylib()) {
1079 if (searchDylibs) {
1080 ld::dylib::File *dylibFile = lib.dylib();
1081 //fprintf(stderr, "searchLibraries(%s), looking in linked %s\n", name, dylibFile->path() );
1082 if ( dylibFile->justInTimeforEachAtom(name, handler) ) {
1083 // we found a definition in this dylib
1084 // done, unless it is a weak definition in which case we keep searching
1085 _options.snapshot().recordDylibSymbol(dylibFile, name);
1086 if ( !dylibFile->hasWeakExternals() || !dylibFile->hasWeakDefinition(name)) {
1087 return true;
1088 }
1089 // else continue search for a non-weak definition
1090 }
1091 }
1092 } else {
1093 if (searchArchives) {
1094 ld::archive::File *archiveFile = lib.archive();
1095 if ( dataSymbolOnly ) {
1096 if ( archiveFile->justInTimeDataOnlyforEachAtom(name, handler) ) {
1097 if ( _options.traceArchives() )
1098 logArchive(archiveFile);
1099 _options.snapshot().recordArchive(archiveFile->path());
1100 // found data definition in static library, done
1101 return true;
1102 }
1103 }
1104 else {
1105 if ( archiveFile->justInTimeforEachAtom(name, handler) ) {
1106 if ( _options.traceArchives() )
1107 logArchive(archiveFile);
1108 _options.snapshot().recordArchive(archiveFile->path());
1109 // found definition in static library, done
1110 return true;
1111 }
1112 }
1113 }
1114 }
1115 libIterator++;
1116 }
1117
1118 // search indirect dylibs
1119 if ( searchDylibs ) {
1120 for (InstallNameToDylib::const_iterator it=_installPathToDylibs.begin(); it != _installPathToDylibs.end(); ++it) {
1121 ld::dylib::File* dylibFile = it->second;
1122 bool searchThisDylib = false;
1123 if ( _options.nameSpace() == Options::kTwoLevelNameSpace ) {
1124 // for two level namesapce, just check all implicitly linked dylibs
1125 searchThisDylib = dylibFile->implicitlyLinked() && !dylibFile->explicitlyLinked();
1126 }
1127 else {
1128 // for flat namespace, check all indirect dylibs
1129 searchThisDylib = ! dylibFile->explicitlyLinked();
1130 }
1131 if ( searchThisDylib ) {
1132 //fprintf(stderr, "searchLibraries(%s), looking in implicitly linked %s\n", name, dylibFile->path() );
1133 if ( dylibFile->justInTimeforEachAtom(name, handler) ) {
1134 // we found a definition in this dylib
1135 // done, unless it is a weak definition in which case we keep searching
1136 _options.snapshot().recordDylibSymbol(dylibFile, name);
1137 if ( !dylibFile->hasWeakExternals() || !dylibFile->hasWeakDefinition(name)) {
1138 return true;
1139 }
1140 // else continue search for a non-weak definition
1141 }
1142 }
1143 }
1144 }
1145
1146 return false;
1147 }
1148
1149
1150 bool InputFiles::searchWeakDefInDylib(const char* name) const
1151 {
1152 // search all relevant dylibs to see if any of a weak-def with this name
1153 for (InstallNameToDylib::const_iterator it=_installPathToDylibs.begin(); it != _installPathToDylibs.end(); ++it) {
1154 ld::dylib::File* dylibFile = it->second;
1155 if ( dylibFile->implicitlyLinked() || dylibFile->explicitlyLinked() ) {
1156 if ( dylibFile->hasWeakExternals() && dylibFile->hasWeakDefinition(name) ) {
1157 return true;
1158 }
1159 }
1160 }
1161 return false;
1162 }
1163
1164 static bool vectorContains(const std::vector<ld::dylib::File*>& vec, ld::dylib::File* key)
1165 {
1166 return std::find(vec.begin(), vec.end(), key) != vec.end();
1167 }
1168
1169 void InputFiles::dylibs(ld::Internal& state)
1170 {
1171 bool dylibsOK = false;
1172 switch ( _options.outputKind() ) {
1173 case Options::kDynamicExecutable:
1174 case Options::kDynamicLibrary:
1175 case Options::kDynamicBundle:
1176 dylibsOK = true;
1177 break;
1178 case Options::kStaticExecutable:
1179 case Options::kDyld:
1180 case Options::kPreload:
1181 case Options::kObjectFile:
1182 case Options::kKextBundle:
1183 dylibsOK = false;
1184 break;
1185 }
1186
1187 // add command line dylibs in order
1188 for (std::vector<ld::File*>::const_iterator it=_inputFiles.begin(); it != _inputFiles.end(); ++it) {
1189 ld::dylib::File* dylibFile = dynamic_cast<ld::dylib::File*>(*it);
1190 // only add dylibs that are not "blank" dylib stubs
1191 if ( (dylibFile != NULL) && ((dylibFile->installPath() != NULL) || (dylibFile == _bundleLoader)) ) {
1192 if ( dylibsOK ) {
1193 if ( ! vectorContains(state.dylibs, dylibFile) ) {
1194 state.dylibs.push_back(dylibFile);
1195 }
1196 }
1197 else
1198 warning("unexpected dylib (%s) on link line", dylibFile->path());
1199 }
1200 }
1201 // add implicitly linked dylibs
1202 if ( _options.nameSpace() == Options::kTwoLevelNameSpace ) {
1203 for (InstallNameToDylib::const_iterator it=_installPathToDylibs.begin(); it != _installPathToDylibs.end(); ++it) {
1204 ld::dylib::File* dylibFile = it->second;
1205 if ( dylibFile->implicitlyLinked() && dylibsOK ) {
1206 if ( ! vectorContains(state.dylibs, dylibFile) ) {
1207 state.dylibs.push_back(dylibFile);
1208 }
1209 }
1210 }
1211 }
1212
1213 //fprintf(stderr, "all dylibs:\n");
1214 //for(std::vector<ld::dylib::File*>::iterator it=state.dylibs.begin(); it != state.dylibs.end(); ++it) {
1215 // const ld::dylib::File* dylib = *it;
1216 // fprintf(stderr, " %p %s\n", dylib, dylib->path());
1217 //}
1218
1219 // and -bundle_loader
1220 state.bundleLoader = _bundleLoader;
1221
1222 // <rdar://problem/10807040> give an error when -nostdlib is used and libSystem is missing
1223 if ( (state.dylibs.size() == 0) && _options.needsEntryPointLoadCommand() )
1224 throw "dynamic main executables must link with libSystem.dylib";
1225 }
1226
1227
1228 } // namespace tool
1229 } // namespace ld
1230
1231