]> git.saurik.com Git - apple/ld64.git/blob - src/ld/MachOReaderDylib.hpp
ld64-97.17.tar.gz
[apple/ld64.git] / src / ld / MachOReaderDylib.hpp
1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
2 *
3 * Copyright (c) 2005-2007 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 #ifndef __OBJECT_FILE_DYLIB_MACH_O__
26 #define __OBJECT_FILE_DYLIB_MACH_O__
27
28 #include <stdint.h>
29 #include <math.h>
30 #include <unistd.h>
31 #include <sys/param.h>
32
33
34 #include <vector>
35 #include <set>
36 #include <algorithm>
37 #include <ext/hash_map>
38
39 #include "MachOFileAbstraction.hpp"
40 #include "MachOTrie.hpp"
41 #include "ObjectFile.h"
42
43 //
44 //
45 // To implement architecture xxx, you must write template specializations for the following method:
46 // Reader<xxx>::validFile()
47 //
48 //
49
50
51
52
53 namespace mach_o {
54 namespace dylib {
55
56
57 // forward reference
58 template <typename A> class Reader;
59
60
61 class Segment : public ObjectFile::Segment
62 {
63 public:
64 Segment(const char* name) { fName = name; }
65 virtual const char* getName() const { return fName; }
66 virtual bool isContentReadable() const { return true; }
67 virtual bool isContentWritable() const { return false; }
68 virtual bool isContentExecutable() const { return false; }
69 private:
70 const char* fName;
71 };
72
73
74 //
75 // An ExportAtom has no content. It exists so that the linker can track which imported
76 // symbols came from which dynamic libraries.
77 //
78 template <typename A>
79 class ExportAtom : public ObjectFile::Atom
80 {
81 public:
82 virtual ObjectFile::Reader* getFile() const { return &fOwner; }
83 virtual bool getTranslationUnitSource(const char** dir, const char** name) const { return false; }
84 virtual const char* getName() const { return fName; }
85 virtual const char* getDisplayName() const { return fName; }
86 virtual Scope getScope() const { return ObjectFile::Atom::scopeGlobal; }
87 virtual DefinitionKind getDefinitionKind() const { return fWeakDefinition ? kExternalWeakDefinition : kExternalDefinition; }
88 virtual SymbolTableInclusion getSymbolTableInclusion() const { return ObjectFile::Atom::kSymbolTableIn; }
89 virtual bool dontDeadStrip() const { return false; }
90 virtual bool isZeroFill() const { return false; }
91 virtual bool isThumb() const { return false; }
92 virtual uint64_t getSize() const { return 0; }
93 virtual std::vector<ObjectFile::Reference*>& getReferences() const { return fgEmptyReferenceList; }
94 virtual bool mustRemainInSection() const { return false; }
95 virtual const char* getSectionName() const { return "._imports"; }
96 virtual Segment& getSegment() const { return fgImportSegment; }
97 virtual ObjectFile::Atom& getFollowOnAtom() const { return *((ObjectFile::Atom*)NULL); }
98 virtual uint32_t getOrdinal() const { return fOrdinal; }
99 virtual std::vector<ObjectFile::LineInfo>* getLineInfo() const { return NULL; }
100 virtual ObjectFile::Alignment getAlignment() const { return ObjectFile::Alignment(0); }
101 virtual void copyRawContent(uint8_t buffer[]) const {}
102
103 virtual void setScope(Scope) { }
104
105 protected:
106 friend class Reader<A>;
107 typedef typename A::P P;
108
109 ExportAtom(ObjectFile::Reader& owner, const char* name, bool weak, uint32_t ordinal)
110 : fOwner(owner), fName(name), fOrdinal(ordinal), fWeakDefinition(weak) {}
111 virtual ~ExportAtom() {}
112
113 ObjectFile::Reader& fOwner;
114 const char* fName;
115 uint32_t fOrdinal;
116 bool fWeakDefinition;
117
118 static std::vector<ObjectFile::Reference*> fgEmptyReferenceList;
119 static Segment fgImportSegment;
120 };
121
122 template <typename A>
123 Segment ExportAtom<A>::fgImportSegment("__LINKEDIT");
124
125 template <typename A>
126 std::vector<ObjectFile::Reference*> ExportAtom<A>::fgEmptyReferenceList;
127
128
129
130 class ImportReference : public ObjectFile::Reference
131 {
132 public:
133 ImportReference(const char* name)
134 : fTarget(NULL), fTargetName(strdup(name)) {}
135 virtual ~ImportReference() {}
136
137
138 virtual ObjectFile::Reference::TargetBinding getTargetBinding() const { return (fTarget==NULL) ? ObjectFile::Reference::kUnboundByName : ObjectFile::Reference::kBoundByName; }
139 virtual ObjectFile::Reference::TargetBinding getFromTargetBinding() const{ return ObjectFile::Reference::kDontBind; }
140 virtual uint8_t getKind() const { return 0; }
141 virtual uint64_t getFixUpOffset() const { return 0; }
142 virtual const char* getTargetName() const { return fTargetName; }
143 virtual ObjectFile::Atom& getTarget() const { return *((ObjectFile::Atom*)fTarget); }
144 virtual uint64_t getTargetOffset() const { return 0; }
145 virtual ObjectFile::Atom& getFromTarget() const { return *((ObjectFile::Atom*)NULL); }
146 virtual const char* getFromTargetName() const { return NULL; }
147 virtual uint64_t getFromTargetOffset() const { return 0; }
148 virtual void setTarget(ObjectFile::Atom& atom, uint64_t offset) { fTarget = &atom; }
149 virtual void setFromTarget(ObjectFile::Atom&) { throw "can't set from target"; }
150 virtual const char* getDescription() const { return "dylib import reference"; }
151
152 private:
153 const ObjectFile::Atom* fTarget;
154 const char* fTargetName;
155 };
156
157
158 //
159 // An ImportAtom has no content. It exists so that when linking a main executable flat-namespace
160 // the imports of all flat dylibs are checked
161 //
162 template <typename A>
163 class ImportAtom : public ObjectFile::Atom
164 {
165 public:
166 virtual ObjectFile::Reader* getFile() const { return &fOwner; }
167 virtual bool getTranslationUnitSource(const char** dir, const char** name) const { return false; }
168 virtual const char* getName() const { return "flat-imports"; }
169 virtual const char* getDisplayName() const { return "flat_namespace undefines"; }
170 virtual Scope getScope() const { return ObjectFile::Atom::scopeTranslationUnit; }
171 virtual DefinitionKind getDefinitionKind() const { return kRegularDefinition; }
172 virtual SymbolTableInclusion getSymbolTableInclusion() const { return ObjectFile::Atom::kSymbolTableNotIn; }
173 virtual bool dontDeadStrip() const { return false; }
174 virtual bool isZeroFill() const { return false; }
175 virtual bool isThumb() const { return false; }
176 virtual uint64_t getSize() const { return 0; }
177 virtual std::vector<ObjectFile::Reference*>& getReferences() const { return (std::vector<ObjectFile::Reference*>&)(fReferences); }
178 virtual bool mustRemainInSection() const { return false; }
179 virtual const char* getSectionName() const { return "._imports"; }
180 virtual Segment& getSegment() const { return fgImportSegment; }
181 virtual ObjectFile::Atom& getFollowOnAtom() const { return *((ObjectFile::Atom*)NULL); }
182 virtual uint32_t getOrdinal() const { return fOrdinal; }
183 virtual std::vector<ObjectFile::LineInfo>* getLineInfo() const { return NULL; }
184 virtual ObjectFile::Alignment getAlignment() const { return ObjectFile::Alignment(0); }
185 virtual void copyRawContent(uint8_t buffer[]) const {}
186
187 virtual void setScope(Scope) { }
188
189 protected:
190 friend class Reader<A>;
191 typedef typename A::P P;
192
193 ImportAtom(ObjectFile::Reader& owner, uint32_t ordinal, std::vector<const char*>& imports)
194 : fOwner(owner), fOrdinal(ordinal) { makeReferences(imports); }
195 virtual ~ImportAtom() {}
196 void makeReferences(std::vector<const char*>& imports) {
197 for (std::vector<const char*>::iterator it=imports.begin(); it != imports.end(); ++it) {
198 fReferences.push_back(new ImportReference(*it));
199 }
200 }
201
202
203 ObjectFile::Reader& fOwner;
204 uint32_t fOrdinal;
205 std::vector<ObjectFile::Reference*> fReferences;
206
207 static Segment fgImportSegment;
208 };
209
210 template <typename A>
211 Segment ImportAtom<A>::fgImportSegment("__LINKEDIT");
212
213
214
215
216 //
217 // The reader for a dylib extracts all exported symbols names from the memory-mapped
218 // dylib, builds a hash table, then unmaps the file. This is an important memory
219 // savings for large dylibs.
220 //
221 template <typename A>
222 class Reader : public ObjectFile::Reader
223 {
224 public:
225 static bool validFile(const uint8_t* fileContent, bool executableOrDylib);
226 Reader(const uint8_t* fileContent, uint64_t fileLength, const char* path,
227 const LibraryOptions& dylibOptions, const ObjectFile::ReaderOptions& options,
228 uint32_t ordinalBase);
229 virtual ~Reader() {}
230
231 virtual const char* getPath() { return fPath; }
232 virtual time_t getModificationTime() { return 0; }
233 virtual DebugInfoKind getDebugInfoKind() { return ObjectFile::Reader::kDebugInfoNone; }
234 virtual std::vector<class ObjectFile::Atom*>& getAtoms();
235 virtual std::vector<class ObjectFile::Atom*>* getJustInTimeAtomsFor(const char* name);
236 virtual std::vector<Stab>* getStabs() { return NULL; }
237 virtual ObjectFile::Reader::ObjcConstraint getObjCConstraint() { return fObjcContraint; }
238 virtual const char* getInstallPath() { return fDylibInstallPath; }
239 virtual uint32_t getTimestamp() { return fDylibTimeStamp; }
240 virtual uint32_t getCurrentVersion() { return fDylibtCurrentVersion; }
241 virtual uint32_t getCompatibilityVersion() { return fDylibCompatibilityVersion; }
242 virtual void processIndirectLibraries(DylibHander* handler);
243 virtual void setExplicitlyLinked() { fExplicitlyLinked = true; }
244 virtual bool explicitlyLinked() { return fExplicitlyLinked; }
245 virtual bool implicitlyLinked() { return fImplicitlyLinked; }
246 virtual bool providedExportAtom() { return fProvidedAtom; }
247 virtual const char* parentUmbrella() { return fParentUmbrella; }
248 virtual std::vector<const char*>* getAllowableClients();
249 virtual bool hasWeakExternals() { return fHasWeakExports; }
250 virtual bool deadStrippable() { return fDeadStrippable; }
251 virtual bool isLazyLoadedDylib() { return fLazyLoaded; }
252
253 virtual void setImplicitlyLinked() { fImplicitlyLinked = true; }
254
255 protected:
256
257 struct ReExportChain { ReExportChain* prev; Reader<A>* reader; };
258
259 void assertNoReExportCycles(ReExportChain*);
260
261 private:
262 typedef typename A::P P;
263 typedef typename A::P::E E;
264
265 class CStringEquals
266 {
267 public:
268 bool operator()(const char* left, const char* right) const { return (strcmp(left, right) == 0); }
269 };
270 struct AtomAndWeak { ObjectFile::Atom* atom; bool weak; uint32_t ordinal; };
271 typedef __gnu_cxx::hash_map<const char*, AtomAndWeak, __gnu_cxx::hash<const char*>, CStringEquals> NameToAtomMap;
272 typedef __gnu_cxx::hash_set<const char*, __gnu_cxx::hash<const char*>, CStringEquals> NameSet;
273 typedef typename NameToAtomMap::iterator NameToAtomMapIterator;
274
275 struct PathAndFlag { const char* path; bool reExport; };
276
277 bool isPublicLocation(const char* path);
278 void addSymbol(const char* name, bool weak);
279 void addDyldFastStub();
280 void buildExportHashTableFromExportInfo(const macho_dyld_info_command<P>* dyldInfo,
281 const uint8_t* fileContent);
282 void buildExportHashTableFromSymbolTable(const macho_dysymtab_command<P>* dynamicInfo,
283 const macho_nlist<P>* symbolTable, const char* strings,
284 const uint8_t* fileContent);
285
286 const char* fPath;
287 const char* fParentUmbrella;
288 std::vector<const char*> fAllowableClients;
289 const char* fDylibInstallPath;
290 uint32_t fDylibTimeStamp;
291 uint32_t fDylibtCurrentVersion;
292 uint32_t fDylibCompatibilityVersion;
293 uint32_t fReExportedOrdinal;
294 std::vector<PathAndFlag> fDependentLibraryPaths;
295 NameToAtomMap fAtoms;
296 NameSet fIgnoreExports;
297 bool fNoRexports;
298 bool fHasWeakExports;
299 bool fDeadStrippable;
300 const bool fLinkingFlat;
301 const bool fLinkingMainExecutable;
302 bool fExplictReExportFound;
303 bool fExplicitlyLinked;
304 bool fImplicitlyLinked;
305 bool fProvidedAtom;
306 bool fImplicitlyLinkPublicDylibs;
307 bool fLazyLoaded;
308 ObjectFile::Reader::ObjcConstraint fObjcContraint;
309 std::vector<ObjectFile::Reader*> fReExportedChildren;
310 const ObjectFile::ReaderOptions::MacVersionMin fMacDeploymentVersionMin;
311 const ObjectFile::ReaderOptions::IPhoneVersionMin fIPhoneDeploymentVersionMin;
312 std::vector<class ObjectFile::Atom*> fFlatImports;
313
314 static bool fgLogHashtable;
315 static std::vector<class ObjectFile::Atom*> fgEmptyAtomList;
316 };
317
318 template <typename A>
319 std::vector<class ObjectFile::Atom*> Reader<A>::fgEmptyAtomList;
320 template <typename A>
321 bool Reader<A>::fgLogHashtable = false;
322
323
324 template <typename A>
325 Reader<A>::Reader(const uint8_t* fileContent, uint64_t fileLength, const char* path,
326 const LibraryOptions& dylibOptions,
327 const ObjectFile::ReaderOptions& options, uint32_t ordinalBase)
328 : fParentUmbrella(NULL), fDylibInstallPath(NULL), fDylibTimeStamp(0), fDylibtCurrentVersion(0),
329 fDylibCompatibilityVersion(0), fReExportedOrdinal(ordinalBase), fLinkingFlat(options.fFlatNamespace),
330 fLinkingMainExecutable(options.fLinkingMainExecutable), fExplictReExportFound(false),
331 fExplicitlyLinked(false), fImplicitlyLinked(false), fProvidedAtom(false),
332 fImplicitlyLinkPublicDylibs(options.fImplicitlyLinkPublicDylibs), fLazyLoaded(dylibOptions.fLazyLoad),
333 fObjcContraint(ObjectFile::Reader::kObjcNone),
334 fMacDeploymentVersionMin(options.fMacVersionMin),
335 fIPhoneDeploymentVersionMin(options.fIPhoneVersionMin)
336 {
337 // sanity check
338 if ( ! validFile(fileContent, dylibOptions.fBundleLoader) )
339 throw "not a valid mach-o object file";
340
341 fPath = strdup(path);
342
343 const macho_header<P>* header = (const macho_header<P>*)fileContent;
344 const uint32_t cmd_count = header->ncmds();
345 const macho_load_command<P>* const cmds = (macho_load_command<P>*)((char*)header + sizeof(macho_header<P>));
346 const macho_load_command<P>* const cmdsEnd = (macho_load_command<P>*)((char*)header + sizeof(macho_header<P>) + header->sizeofcmds());
347
348 // write out path for -whatsloaded option
349 if ( options.fLogAllFiles )
350 printf("%s\n", path);
351
352 if ( options.fRootSafe && ((header->flags() & MH_ROOT_SAFE) == 0) )
353 warning("using -root_safe but linking against %s which is not root safe", path);
354
355 if ( options.fSetuidSafe && ((header->flags() & MH_SETUID_SAFE) == 0) )
356 warning("using -setuid_safe but linking against %s which is not setuid safe", path);
357
358 // a "blank" stub has zero load commands
359 if ( (header->filetype() == MH_DYLIB_STUB) && (cmd_count == 0) ) {
360 // no further processing needed
361 munmap((caddr_t)fileContent, fileLength);
362 return;
363 }
364
365
366 // optimize the case where we know there is no reason to look at indirect dylibs
367 fNoRexports = (header->flags() & MH_NO_REEXPORTED_DYLIBS);
368 fHasWeakExports = (header->flags() & MH_WEAK_DEFINES);
369 fDeadStrippable = (header->flags() & MH_DEAD_STRIPPABLE_DYLIB);
370 bool trackDependentLibraries = !fNoRexports || options.fFlatNamespace;
371
372 // pass 1 builds list of all dependent libraries
373 const macho_load_command<P>* cmd = cmds;
374 if ( trackDependentLibraries ) {
375 for (uint32_t i = 0; i < cmd_count; ++i) {
376 switch (cmd->cmd()) {
377 case LC_REEXPORT_DYLIB:
378 fExplictReExportFound = true;
379 // fall into next case
380 case LC_LOAD_DYLIB:
381 case LC_LOAD_WEAK_DYLIB:
382 PathAndFlag entry;
383 entry.path = strdup(((struct macho_dylib_command<P>*)cmd)->name());
384 entry.reExport = (cmd->cmd() == LC_REEXPORT_DYLIB);
385 fDependentLibraryPaths.push_back(entry);
386 break;
387 }
388 cmd = (const macho_load_command<P>*)(((char*)cmd)+cmd->cmdsize());
389 if ( cmd > cmdsEnd )
390 throwf("malformed dylb, load command #%d is outside size of load commands in %s", i, path);
391 }
392 }
393
394 // pass 2 determines re-export info
395 const macho_dysymtab_command<P>* dynamicInfo = NULL;
396 const macho_dyld_info_command<P>* dyldInfo = NULL;
397 const macho_nlist<P>* symbolTable = NULL;
398 const char* strings = NULL;
399 cmd = cmds;
400 for (uint32_t i = 0; i < cmd_count; ++i) {
401 switch (cmd->cmd()) {
402 case LC_SYMTAB:
403 {
404 const macho_symtab_command<P>* symtab = (macho_symtab_command<P>*)cmd;
405 symbolTable = (const macho_nlist<P>*)((char*)header + symtab->symoff());
406 strings = (char*)header + symtab->stroff();
407 }
408 break;
409 case LC_DYSYMTAB:
410 dynamicInfo = (macho_dysymtab_command<P>*)cmd;
411 break;
412 case LC_DYLD_INFO:
413 case LC_DYLD_INFO_ONLY:
414 dyldInfo = (macho_dyld_info_command<P>*)cmd;
415 break;
416 case LC_ID_DYLIB:
417 {
418 macho_dylib_command<P>* dylibID = (macho_dylib_command<P>*)cmd;
419 fDylibInstallPath = strdup(dylibID->name());
420 fDylibTimeStamp = dylibID->timestamp();
421 fDylibtCurrentVersion = dylibID->current_version();
422 fDylibCompatibilityVersion = dylibID->compatibility_version();
423 }
424 break;
425 case LC_SUB_UMBRELLA:
426 if ( trackDependentLibraries ) {
427 const char* frameworkLeafName = ((macho_sub_umbrella_command<P>*)cmd)->sub_umbrella();
428 for (typename std::vector<PathAndFlag>::iterator it = fDependentLibraryPaths.begin(); it != fDependentLibraryPaths.end(); it++) {
429 const char* dylibName = it->path;
430 const char* lastSlash = strrchr(dylibName, '/');
431 if ( (lastSlash != NULL) && (strcmp(&lastSlash[1], frameworkLeafName) == 0) )
432 it->reExport = true;
433 }
434 }
435 break;
436 case LC_SUB_LIBRARY:
437 if ( trackDependentLibraries) {
438 const char* dylibBaseName = ((macho_sub_library_command<P>*)cmd)->sub_library();
439 for (typename std::vector<PathAndFlag>::iterator it = fDependentLibraryPaths.begin(); it != fDependentLibraryPaths.end(); it++) {
440 const char* dylibName = it->path;
441 const char* lastSlash = strrchr(dylibName, '/');
442 const char* leafStart = &lastSlash[1];
443 if ( lastSlash == NULL )
444 leafStart = dylibName;
445 const char* firstDot = strchr(leafStart, '.');
446 int len = strlen(leafStart);
447 if ( firstDot != NULL )
448 len = firstDot - leafStart;
449 if ( strncmp(leafStart, dylibBaseName, len) == 0 )
450 it->reExport = true;
451 }
452 }
453 break;
454 case LC_SUB_FRAMEWORK:
455 fParentUmbrella = strdup(((macho_sub_framework_command<P>*)cmd)->umbrella());
456 break;
457 case macho_segment_command<P>::CMD:
458 // check for Objective-C info
459 if ( strcmp(((macho_segment_command<P>*)cmd)->segname(), "__OBJC") == 0 ) {
460 const macho_segment_command<P>* segment = (macho_segment_command<P>*)cmd;
461 const macho_section<P>* const sectionsStart = (macho_section<P>*)((char*)segment + sizeof(macho_segment_command<P>));
462 const macho_section<P>* const sectionsEnd = &sectionsStart[segment->nsects()];
463 for (const macho_section<P>* sect=sectionsStart; sect < sectionsEnd; ++sect) {
464 if ( strcmp(sect->sectname(), "__image_info") == 0 ) {
465 // struct objc_image_info {
466 // uint32_t version; // initially 0
467 // uint32_t flags;
468 // };
469 // #define OBJC_IMAGE_SUPPORTS_GC 2
470 // #define OBJC_IMAGE_GC_ONLY 4
471 //
472 const uint32_t* contents = (uint32_t*)(&fileContent[sect->offset()]);
473 if ( (sect->size() >= 8) && (contents[0] == 0) ) {
474 uint32_t flags = E::get32(contents[1]);
475 if ( (flags & 4) == 4 )
476 fObjcContraint = ObjectFile::Reader::kObjcGC;
477 else if ( (flags & 2) == 2 )
478 fObjcContraint = ObjectFile::Reader::kObjcRetainReleaseOrGC;
479 else
480 fObjcContraint = ObjectFile::Reader::kObjcRetainRelease;
481 }
482 else if ( sect->size() > 0 ) {
483 warning("can't parse __OBJC/__image_info section in %s", fPath);
484 }
485 }
486 }
487 }
488 }
489
490 cmd = (const macho_load_command<P>*)(((char*)cmd)+cmd->cmdsize());
491 if ( cmd > cmdsEnd )
492 throwf("malformed dylb, load command #%d is outside size of load commands in %s", i, path);
493 }
494
495 // Process the rest of the commands here.
496 cmd = cmds;
497 for (uint32_t i = 0; i < cmd_count; ++i) {
498 switch (cmd->cmd()) {
499 case LC_SUB_CLIENT:
500 const char *temp = strdup(((macho_sub_client_command<P>*)cmd)->client());
501 fAllowableClients.push_back(temp);
502 break;
503 }
504 cmd = (const macho_load_command<P>*)(((char*)cmd)+cmd->cmdsize());
505 }
506
507 // validate minimal load commands
508 if ( (fDylibInstallPath == NULL) && ((header->filetype() == MH_DYLIB) || (header->filetype() == MH_DYLIB_STUB)) )
509 throwf("dylib %s missing LC_ID_DYLIB load command", path);
510 if ( symbolTable == NULL )
511 throw "binary missing LC_SYMTAB load command";
512 if ( dynamicInfo == NULL )
513 throw "binary missing LC_DYSYMTAB load command";
514
515 // if linking flat and this is a flat dylib, create one atom that references all imported symbols
516 if ( fLinkingFlat && fLinkingMainExecutable && ((header->flags() & MH_TWOLEVEL) == 0) ) {
517 std::vector<const char*> importNames;
518 importNames.reserve(dynamicInfo->nundefsym());
519 const macho_nlist<P>* start = &symbolTable[dynamicInfo->iundefsym()];
520 const macho_nlist<P>* end = &start[dynamicInfo->nundefsym()];
521 for (const macho_nlist<P>* sym=start; sym < end; ++sym) {
522 importNames.push_back(&strings[sym->n_strx()]);
523 }
524 fFlatImports.push_back(new ImportAtom<A>(*this, fReExportedOrdinal++, importNames));
525 }
526
527 // build hash table
528 if ( dyldInfo != NULL )
529 buildExportHashTableFromExportInfo(dyldInfo, fileContent);
530 else
531 buildExportHashTableFromSymbolTable(dynamicInfo, symbolTable, strings, fileContent);
532
533 // special case libSystem
534 if ( (fDylibInstallPath != NULL) && (strcmp(fDylibInstallPath, "/usr/lib/libSystem.B.dylib") == 0) )
535 addDyldFastStub();
536
537 // unmap file
538 munmap((caddr_t)fileContent, fileLength);
539 }
540
541
542 template <typename A>
543 void Reader<A>::buildExportHashTableFromSymbolTable(const macho_dysymtab_command<P>* dynamicInfo,
544 const macho_nlist<P>* symbolTable, const char* strings,
545 const uint8_t* fileContent)
546 {
547 if ( dynamicInfo->tocoff() == 0 ) {
548 if ( fgLogHashtable ) fprintf(stderr, "ld: building hashtable of %u toc entries for %s\n", dynamicInfo->nextdefsym(), this->getPath());
549 const macho_nlist<P>* start = &symbolTable[dynamicInfo->iextdefsym()];
550 const macho_nlist<P>* end = &start[dynamicInfo->nextdefsym()];
551 fAtoms.resize(dynamicInfo->nextdefsym()); // set initial bucket count
552 for (const macho_nlist<P>* sym=start; sym < end; ++sym) {
553 this->addSymbol(&strings[sym->n_strx()], (sym->n_desc() & N_WEAK_DEF) != 0);
554 }
555 }
556 else {
557 int32_t count = dynamicInfo->ntoc();
558 fAtoms.resize(count); // set initial bucket count
559 if ( fgLogHashtable ) fprintf(stderr, "ld: building hashtable of %u entries for %s\n", count, this->getPath());
560 const struct dylib_table_of_contents* toc = (dylib_table_of_contents*)(fileContent + dynamicInfo->tocoff());
561 for (int32_t i = 0; i < count; ++i) {
562 const uint32_t index = E::get32(toc[i].symbol_index);
563 const macho_nlist<P>* sym = &symbolTable[index];
564 this->addSymbol(&strings[sym->n_strx()], (sym->n_desc() & N_WEAK_DEF) != 0);
565 }
566 }
567 }
568
569
570 template <typename A>
571 void Reader<A>::buildExportHashTableFromExportInfo(const macho_dyld_info_command<P>* dyldInfo,
572 const uint8_t* fileContent)
573 {
574 if ( fgLogHashtable ) fprintf(stderr, "ld: building hashtable from export info in %s\n", this->getPath());
575 if ( dyldInfo->export_size() > 0 ) {
576 const uint8_t* start = fileContent + dyldInfo->export_off();
577 const uint8_t* end = &start[dyldInfo->export_size()];
578 std::vector<mach_o::trie::Entry> list;
579 parseTrie(start, end, list);
580 for (std::vector<mach_o::trie::Entry>::iterator it=list.begin(); it != list.end(); ++it)
581 this->addSymbol(it->name, it->flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
582 }
583 }
584
585
586 template <>
587 void Reader<x86_64>::addDyldFastStub()
588 {
589 addSymbol("dyld_stub_binder", false);
590 }
591
592 template <>
593 void Reader<x86>::addDyldFastStub()
594 {
595 addSymbol("dyld_stub_binder", false);
596 }
597
598 // hack for bring up of iPhoneOS builds on SnowLeopard
599 template <>
600 void Reader<arm>::addDyldFastStub()
601 {
602 addSymbol("dyld_stub_binder", false);
603 }
604
605 template <typename A>
606 void Reader<A>::addDyldFastStub()
607 {
608 // do nothing
609 }
610
611 template <typename A>
612 void Reader<A>::addSymbol(const char* name, bool weakDef)
613 {
614 //fprintf(stderr, "addSymbol() %s\n", name);
615 // symbols that start with $ld$ are meta-data to the static linker
616 // <rdar://problem/5182537> need way for ld and dyld to see different exported symbols in a dylib
617 if ( strncmp(name, "$ld$", 4) == 0 ) {
618 // $ld$ <action> $ <condition> $ <symbol-name>
619 const char* symAction = &name[4];
620 const char* symCond = strchr(symAction, '$');
621 if ( symCond != NULL ) {
622 if ( fMacDeploymentVersionMin != ObjectFile::ReaderOptions::kMinMacVersionUnset ) {
623 ObjectFile::ReaderOptions::MacVersionMin symVersionCondition = ObjectFile::ReaderOptions::kMinMacVersionUnset;
624 // ex: $ld$add$os10.6$_foo
625 if ( (strncmp(symCond, "$os10.", 6) == 0) && isdigit(symCond[6]) && (symCond[7] == '$') ) {
626 switch ( symCond[6] - '0' ) {
627 case 0:
628 case 1:
629 symVersionCondition = ObjectFile::ReaderOptions::k10_1;
630 break;
631 case 2:
632 symVersionCondition = ObjectFile::ReaderOptions::k10_2;
633 break;
634 case 3:
635 symVersionCondition = ObjectFile::ReaderOptions::k10_3;
636 break;
637 case 4:
638 symVersionCondition = ObjectFile::ReaderOptions::k10_4;
639 break;
640 case 5:
641 symVersionCondition = ObjectFile::ReaderOptions::k10_5;
642 break;
643 case 6:
644 symVersionCondition = ObjectFile::ReaderOptions::k10_6;
645 break;
646 }
647 const char* symName = strchr(&symCond[1], '$');
648 if ( symName != NULL ) {
649 ++symName;
650 if ( fMacDeploymentVersionMin == symVersionCondition ) {
651 if ( strncmp(symAction, "hide$", 5) == 0 ) {
652 if ( fgLogHashtable ) fprintf(stderr, " adding %s to ignore set for %s\n", symName, this->getPath());
653 fIgnoreExports.insert(strdup(symName));
654 return;
655 }
656 else if ( strncmp(symAction, "add$", 4) == 0 ) {
657 this->addSymbol(symName, weakDef);
658 return;
659 }
660 else {
661 warning("bad symbol action: %s in dylib %s", name, this->getPath());
662 }
663 }
664 }
665 else {
666 warning("bad symbol name: %s in dylib %s", name, this->getPath());
667 }
668 }
669 else {
670 warning("bad symbol version: %s in dylib %s", name, this->getPath());
671 }
672 }
673 else if ( fIPhoneDeploymentVersionMin != ObjectFile::ReaderOptions::kMinIPhoneVersionUnset ) {
674 ObjectFile::ReaderOptions::IPhoneVersionMin symVersionCondition = ObjectFile::ReaderOptions::kMinIPhoneVersionUnset;
675 // ex: $ld$add$os3.1$_foo
676 if ( (strncmp(symCond, "$os", 3) == 0) && isdigit(symCond[3]) && (symCond[4] == '.') ) {
677 if ( (symCond[3] == '2') && (symCond[5] == '0') )
678 symVersionCondition = ObjectFile::ReaderOptions::k2_0;
679 else if ( (symCond[3] == '2') && (symCond[5] == '1') )
680 symVersionCondition = ObjectFile::ReaderOptions::k2_1;
681 else if ( (symCond[3] == '2') && (symCond[5] >= '2') )
682 symVersionCondition = ObjectFile::ReaderOptions::k2_2;
683 else if ( (symCond[3] == '3') && (symCond[5] == '0') )
684 symVersionCondition = ObjectFile::ReaderOptions::k3_0;
685 else if ( (symCond[3] == '3') && (symCond[5] == '1') )
686 symVersionCondition = ObjectFile::ReaderOptions::k3_1;
687 else if ( (symCond[3] == '3') && (symCond[5] >= '2') )
688 symVersionCondition = ObjectFile::ReaderOptions::k3_2;
689 else if ( (symCond[3] >= '4') )
690 symVersionCondition = ObjectFile::ReaderOptions::k4_0;
691 const char* symName = strchr(&symCond[1], '$');
692 if ( symName != NULL ) {
693 ++symName;
694 if ( fIPhoneDeploymentVersionMin == symVersionCondition ) {
695 if ( strncmp(symAction, "hide$", 5) == 0 ) {
696 if ( fgLogHashtable ) fprintf(stderr, " adding %s to ignore set for %s\n", symName, this->getPath());
697 fIgnoreExports.insert(strdup(symName));
698 return;
699 }
700 else if ( strncmp(symAction, "add$", 4) == 0 ) {
701 this->addSymbol(symName, weakDef);
702 return;
703 }
704 else {
705 warning("bad symbol action: %s in dylib %s", name, this->getPath());
706 }
707 }
708 }
709 else {
710 warning("bad symbol name: %s in dylib %s", name, this->getPath());
711 }
712 }
713 else {
714 warning("bad symbol version: %s in dylib %s, symCond=%s", name, this->getPath(), symCond);
715 }
716 }
717 }
718 else {
719 warning("bad symbol condition: %s in dylib %s", name, this->getPath());
720 }
721 }
722
723 // add symbol as possible export if we are not supposed to ignore it
724 if ( fIgnoreExports.count(name) == 0 ) {
725 AtomAndWeak bucket;
726 bucket.atom = NULL;
727 bucket.weak = weakDef;
728 bucket.ordinal = fReExportedOrdinal++;
729 if ( fgLogHashtable ) fprintf(stderr, " adding %s to hash table for %s\n", name, this->getPath());
730 fAtoms[strdup(name)] = bucket;
731 }
732 }
733
734
735 template <typename A>
736 std::vector<class ObjectFile::Atom*>& Reader<A>::getAtoms()
737 {
738 return fFlatImports;
739 }
740
741
742 template <typename A>
743 std::vector<class ObjectFile::Atom*>* Reader<A>::getJustInTimeAtomsFor(const char* name)
744 {
745 // if supposed to ignore this export, then pretend I don't have it
746 if ( fIgnoreExports.count(name) != 0 )
747 return NULL;
748
749 std::vector<class ObjectFile::Atom*>* atoms = NULL;
750 NameToAtomMapIterator pos = fAtoms.find(name);
751 if ( pos != fAtoms.end() ) {
752 if ( pos->second.atom == NULL ) {
753 // instantiate atom and update hash table
754 pos->second.atom = new ExportAtom<A>(*this, name, pos->second.weak, pos->second.ordinal);
755 fProvidedAtom = true;
756 if ( fgLogHashtable ) fprintf(stderr, "getJustInTimeAtomsFor: %s found in %s\n", name, this->getPath());
757 }
758 // return a vector of one atom
759 atoms = new std::vector<class ObjectFile::Atom*>;
760 atoms->push_back(pos->second.atom);
761 }
762 else {
763 if ( fgLogHashtable ) fprintf(stderr, "getJustInTimeAtomsFor: %s NOT found in %s\n", name, this->getPath());
764 // look in children that I re-export
765 for (std::vector<ObjectFile::Reader*>::iterator it = fReExportedChildren.begin(); it != fReExportedChildren.end(); it++) {
766 //fprintf(stderr, "getJustInTimeAtomsFor: %s NOT found in %s, looking in child %s\n", name, this->getPath(), (*it)->getInstallPath());
767 std::vector<class ObjectFile::Atom*>* childAtoms = (*it)->getJustInTimeAtomsFor(name);
768 if ( childAtoms != NULL ) {
769 // make a new atom that says this reader is the owner
770 bool isWeakDef = (childAtoms->at(0)->getDefinitionKind() == ObjectFile::Atom::kExternalWeakDefinition);
771 // return a vector of one atom
772 ExportAtom<A>* newAtom = new ExportAtom<A>(*this, name, isWeakDef, fReExportedOrdinal++);
773 fProvidedAtom = true;
774 atoms = new std::vector<class ObjectFile::Atom*>;
775 atoms->push_back(newAtom);
776 delete childAtoms;
777 return atoms;
778 }
779 }
780 }
781 return atoms;
782 }
783
784
785
786 template <typename A>
787 bool Reader<A>::isPublicLocation(const char* path)
788 {
789 // -no_implicit_dylibs disables this optimization
790 if ( ! fImplicitlyLinkPublicDylibs )
791 return false;
792
793 // /usr/lib is a public location
794 if ( (strncmp(path, "/usr/lib/", 9) == 0) && (strchr(&path[9], '/') == NULL) )
795 return true;
796
797 // /System/Library/Frameworks/ is a public location
798 if ( strncmp(path, "/System/Library/Frameworks/", 27) == 0 ) {
799 const char* frameworkDot = strchr(&path[27], '.');
800 // but only top level framework
801 // /System/Library/Frameworks/Foo.framework/Versions/A/Foo ==> true
802 // /System/Library/Frameworks/Foo.framework/Resources/libBar.dylib ==> false
803 // /System/Library/Frameworks/Foo.framework/Frameworks/Bar.framework/Bar ==> false
804 // /System/Library/Frameworks/Foo.framework/Frameworks/Xfoo.framework/XFoo ==> false
805 if ( frameworkDot != NULL ) {
806 int frameworkNameLen = frameworkDot - &path[27];
807 if ( strncmp(&path[strlen(path)-frameworkNameLen-1], &path[26], frameworkNameLen+1) == 0 )
808 return true;
809 }
810 }
811
812 return false;
813 }
814
815 template <typename A>
816 void Reader<A>::processIndirectLibraries(DylibHander* handler)
817 {
818 if ( fLinkingFlat ) {
819 for (typename std::vector<PathAndFlag>::iterator it = fDependentLibraryPaths.begin(); it != fDependentLibraryPaths.end(); it++) {
820 handler->findDylib(it->path, this->getPath());
821 }
822 }
823 else if ( fNoRexports ) {
824 // MH_NO_REEXPORTED_DYLIBS bit set, then nothing to do
825 }
826 else {
827 // two-level, might have re-exports
828 for (typename std::vector<PathAndFlag>::iterator it = fDependentLibraryPaths.begin(); it != fDependentLibraryPaths.end(); it++) {
829 if ( it->reExport ) {
830 //fprintf(stderr, "processIndirectLibraries() parent=%s, child=%s\n", this->getInstallPath(), it->path);
831 // a LC_REEXPORT_DYLIB, LC_SUB_UMBRELLA or LC_SUB_LIBRARY says we re-export this child
832 ObjectFile::Reader* child = handler->findDylib(it->path, this->getPath());
833 if ( isPublicLocation(child->getInstallPath()) ) {
834 // promote this child to be automatically added as a direct dependent if this already is
835 if ( (this->explicitlyLinked() || this->implicitlyLinked()) && (strcmp(it->path,child->getInstallPath()) == 0) ) {
836 //fprintf(stderr, "processIndirectLibraries() implicitly linking %s\n", child->getInstallPath());
837 ((Reader<A>*)child)->setImplicitlyLinked();
838 }
839 else if ( child->explicitlyLinked() || child->implicitlyLinked() ) {
840 //fprintf(stderr, "processIndirectLibraries() parent is not directly linked, but child is, so no need to re-export child\n");
841 }
842 else {
843 fReExportedChildren.push_back(child);
844 //fprintf(stderr, "processIndirectLibraries() parent is not directly linked, so parent=%s will re-export child=%s\n", this->getInstallPath(), it->path);
845 }
846 }
847 else {
848 // add all child's symbols to me
849 fReExportedChildren.push_back(child);
850 //fprintf(stderr, "processIndirectLibraries() child is not public, so parent=%s will re-export child=%s\n", this->getInstallPath(), it->path);
851 }
852 }
853 else if ( !fExplictReExportFound ) {
854 // see if child contains LC_SUB_FRAMEWORK with my name
855 ObjectFile::Reader* child = handler->findDylib(it->path, this->getPath());
856 const char* parentUmbrellaName = ((Reader<A>*)child)->parentUmbrella();
857 if ( parentUmbrellaName != NULL ) {
858 const char* parentName = this->getPath();
859 const char* lastSlash = strrchr(parentName, '/');
860 if ( (lastSlash != NULL) && (strcmp(&lastSlash[1], parentUmbrellaName) == 0) ) {
861 // add all child's symbols to me
862 fReExportedChildren.push_back(child);
863 //fprintf(stderr, "processIndirectLibraries() umbrella=%s will re-export child=%s\n", this->getInstallPath(), it->path);
864 }
865 }
866 }
867 }
868 }
869
870 // check for re-export cycles
871 ReExportChain chain;
872 chain.prev = NULL;
873 chain.reader = this;
874 this->assertNoReExportCycles(&chain);
875 }
876
877 template <typename A>
878 void Reader<A>::assertNoReExportCycles(ReExportChain* prev)
879 {
880 // recursively check my re-exported dylibs
881 ReExportChain chain;
882 chain.prev = prev;
883 chain.reader = this;
884 for (std::vector<ObjectFile::Reader*>::iterator it = fReExportedChildren.begin(); it != fReExportedChildren.end(); it++) {
885 ObjectFile::Reader* child = *it;
886 // check child is not already in chain
887 for (ReExportChain* p = prev; p != NULL; p = p->prev) {
888 if ( p->reader == child ) {
889 throwf("cycle in dylib re-exports with %s", child->getPath());
890 }
891 }
892 ((Reader<A>*)(*it))->assertNoReExportCycles(&chain);
893 }
894 }
895
896
897 template <typename A>
898 std::vector<const char*>* Reader<A>::getAllowableClients()
899 {
900 std::vector<const char*>* result = new std::vector<const char*>;
901 for (typename std::vector<const char*>::iterator it = fAllowableClients.begin();
902 it != fAllowableClients.end();
903 it++) {
904 result->push_back(*it);
905 }
906 return (fAllowableClients.size() != 0 ? result : NULL);
907 }
908
909 template <>
910 bool Reader<ppc>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle)
911 {
912 const macho_header<P>* header = (const macho_header<P>*)fileContent;
913 if ( header->magic() != MH_MAGIC )
914 return false;
915 if ( header->cputype() != CPU_TYPE_POWERPC )
916 return false;
917 switch ( header->filetype() ) {
918 case MH_DYLIB:
919 case MH_DYLIB_STUB:
920 return true;
921 case MH_BUNDLE:
922 if ( executableOrDyliborBundle )
923 return true;
924 else
925 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
926 case MH_EXECUTE:
927 if ( executableOrDyliborBundle )
928 return true;
929 else
930 throw "can't link with a main executable";
931 default:
932 return false;
933 }
934 }
935
936 template <>
937 bool Reader<ppc64>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle)
938 {
939 const macho_header<P>* header = (const macho_header<P>*)fileContent;
940 if ( header->magic() != MH_MAGIC_64 )
941 return false;
942 if ( header->cputype() != CPU_TYPE_POWERPC64 )
943 return false;
944 switch ( header->filetype() ) {
945 case MH_DYLIB:
946 case MH_DYLIB_STUB:
947 return true;
948 case MH_BUNDLE:
949 if ( executableOrDyliborBundle )
950 return true;
951 else
952 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
953 case MH_EXECUTE:
954 if ( executableOrDyliborBundle )
955 return true;
956 else
957 throw "can't link with a main executable";
958 default:
959 return false;
960 }
961 }
962
963 template <>
964 bool Reader<x86>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle)
965 {
966 const macho_header<P>* header = (const macho_header<P>*)fileContent;
967 if ( header->magic() != MH_MAGIC )
968 return false;
969 if ( header->cputype() != CPU_TYPE_I386 )
970 return false;
971 switch ( header->filetype() ) {
972 case MH_DYLIB:
973 case MH_DYLIB_STUB:
974 return true;
975 case MH_BUNDLE:
976 if ( executableOrDyliborBundle )
977 return true;
978 else
979 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
980 case MH_EXECUTE:
981 if ( executableOrDyliborBundle )
982 return true;
983 else
984 throw "can't link with a main executable";
985 default:
986 return false;
987 }
988 }
989
990 template <>
991 bool Reader<x86_64>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle)
992 {
993 const macho_header<P>* header = (const macho_header<P>*)fileContent;
994 if ( header->magic() != MH_MAGIC_64 )
995 return false;
996 if ( header->cputype() != CPU_TYPE_X86_64 )
997 return false;
998 switch ( header->filetype() ) {
999 case MH_DYLIB:
1000 case MH_DYLIB_STUB:
1001 return true;
1002 case MH_BUNDLE:
1003 if ( executableOrDyliborBundle )
1004 return true;
1005 else
1006 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
1007 case MH_EXECUTE:
1008 if ( executableOrDyliborBundle )
1009 return true;
1010 else
1011 throw "can't link with a main executable";
1012 default:
1013 return false;
1014 }
1015 }
1016
1017 template <>
1018 bool Reader<arm>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle)
1019 {
1020 const macho_header<P>* header = (const macho_header<P>*)fileContent;
1021 if ( header->magic() != MH_MAGIC )
1022 return false;
1023 if ( header->cputype() != CPU_TYPE_ARM )
1024 return false;
1025 switch ( header->filetype() ) {
1026 case MH_DYLIB:
1027 case MH_DYLIB_STUB:
1028 return true;
1029 case MH_BUNDLE:
1030 if ( executableOrDyliborBundle )
1031 return true;
1032 else
1033 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
1034 case MH_EXECUTE:
1035 if ( executableOrDyliborBundle )
1036 return true;
1037 else
1038 throw "can't link with a main executable";
1039 default:
1040 return false;
1041 }
1042 }
1043
1044 }; // namespace dylib
1045 }; // namespace mach_o
1046
1047
1048 #endif // __OBJECT_FILE_DYLIB_MACH_O__