1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
3 * Copyright (c) 2005-2007 Apple Inc. All rights reserved.
5 * @APPLE_LICENSE_HEADER_START@
7 * This file contains Original Code and/or Modifications of Original Code
8 * as defined in and that are subject to the Apple Public Source License
9 * Version 2.0 (the 'License'). You may not use this file except in
10 * compliance with the License. Please obtain a copy of the License at
11 * http://www.opensource.apple.com/apsl/ and read it before using this
14 * The Original Code and all software distributed under the License are
15 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
19 * Please see the License for the specific language governing rights and
20 * limitations under the License.
22 * @APPLE_LICENSE_HEADER_END@
25 #ifndef __OBJECT_FILE_DYLIB_MACH_O__
26 #define __OBJECT_FILE_DYLIB_MACH_O__
31 #include <sys/param.h>
37 #include <ext/hash_map>
39 #include "MachOFileAbstraction.hpp"
40 #include "ObjectFile.h"
44 // To implement architecture xxx, you must write template specializations for the following method:
45 // Reader<xxx>::validFile()
57 template <typename A> class Reader;
60 class Segment : public ObjectFile::Segment
63 Segment(const char* name) { fName = name; }
64 virtual const char* getName() const { return fName; }
65 virtual bool isContentReadable() const { return true; }
66 virtual bool isContentWritable() const { return false; }
67 virtual bool isContentExecutable() const { return false; }
74 // An ExportAtom has no content. It exists so that the linker can track which imported
75 // symbols came from which dynamic libraries.
78 class ExportAtom : public ObjectFile::Atom
81 virtual ObjectFile::Reader* getFile() const { return &fOwner; }
82 virtual bool getTranslationUnitSource(const char** dir, const char** name) const { return false; }
83 virtual const char* getName() const { return fName; }
84 virtual const char* getDisplayName() const { return fName; }
85 virtual Scope getScope() const { return ObjectFile::Atom::scopeGlobal; }
86 virtual DefinitionKind getDefinitionKind() const { return fWeakDefinition ? kExternalWeakDefinition : kExternalDefinition; }
87 virtual SymbolTableInclusion getSymbolTableInclusion() const { return ObjectFile::Atom::kSymbolTableIn; }
88 virtual bool dontDeadStrip() const { return false; }
89 virtual bool isZeroFill() const { return false; }
90 virtual uint64_t getSize() const { return 0; }
91 virtual std::vector<ObjectFile::Reference*>& getReferences() const { return fgEmptyReferenceList; }
92 virtual bool mustRemainInSection() const { return false; }
93 virtual const char* getSectionName() const { return "._imports"; }
94 virtual Segment& getSegment() const { return fgImportSegment; }
95 virtual ObjectFile::Atom& getFollowOnAtom() const { return *((ObjectFile::Atom*)NULL); }
96 virtual uint32_t getOrdinal() const { return fOrdinal; }
97 virtual std::vector<ObjectFile::LineInfo>* getLineInfo() const { return NULL; }
98 virtual ObjectFile::Alignment getAlignment() const { return ObjectFile::Alignment(0); }
99 virtual void copyRawContent(uint8_t buffer[]) const {}
101 virtual void setScope(Scope) { }
104 friend class Reader<A>;
105 typedef typename A::P P;
107 ExportAtom(ObjectFile::Reader& owner, const char* name, bool weak, uint32_t ordinal)
108 : fOwner(owner), fName(name), fOrdinal(ordinal), fWeakDefinition(weak) {}
109 virtual ~ExportAtom() {}
111 ObjectFile::Reader& fOwner;
114 bool fWeakDefinition;
116 static std::vector<ObjectFile::Reference*> fgEmptyReferenceList;
117 static Segment fgImportSegment;
120 template <typename A>
121 Segment ExportAtom<A>::fgImportSegment("__LINKEDIT");
123 template <typename A>
124 std::vector<ObjectFile::Reference*> ExportAtom<A>::fgEmptyReferenceList;
128 class ImportReference : public ObjectFile::Reference
131 ImportReference(const char* name)
132 : fTarget(NULL), fTargetName(strdup(name)) {}
133 virtual ~ImportReference() {}
136 virtual ObjectFile::Reference::TargetBinding getTargetBinding() const { return (fTarget==NULL) ? ObjectFile::Reference::kUnboundByName : ObjectFile::Reference::kBoundByName; }
137 virtual ObjectFile::Reference::TargetBinding getFromTargetBinding() const{ return ObjectFile::Reference::kDontBind; }
138 virtual uint8_t getKind() const { return 0; }
139 virtual uint64_t getFixUpOffset() const { return 0; }
140 virtual const char* getTargetName() const { return fTargetName; }
141 virtual ObjectFile::Atom& getTarget() const { return *((ObjectFile::Atom*)fTarget); }
142 virtual uint64_t getTargetOffset() const { return 0; }
143 virtual ObjectFile::Atom& getFromTarget() const { return *((ObjectFile::Atom*)NULL); }
144 virtual const char* getFromTargetName() const { return NULL; }
145 virtual uint64_t getFromTargetOffset() const { return 0; }
146 virtual void setTarget(ObjectFile::Atom& atom, uint64_t offset) { fTarget = &atom; }
147 virtual void setFromTarget(ObjectFile::Atom&) { throw "can't set from target"; }
148 virtual const char* getDescription() const { return "dylib import reference"; }
151 const ObjectFile::Atom* fTarget;
152 const char* fTargetName;
157 // An ImportAtom has no content. It exists so that when linking a main executable flat-namespace
158 // the imports of all flat dylibs are checked
160 template <typename A>
161 class ImportAtom : public ObjectFile::Atom
164 virtual ObjectFile::Reader* getFile() const { return &fOwner; }
165 virtual bool getTranslationUnitSource(const char** dir, const char** name) const { return false; }
166 virtual const char* getName() const { return "flat-imports"; }
167 virtual const char* getDisplayName() const { return "flat_namespace undefines"; }
168 virtual Scope getScope() const { return ObjectFile::Atom::scopeTranslationUnit; }
169 virtual DefinitionKind getDefinitionKind() const { return kRegularDefinition; }
170 virtual SymbolTableInclusion getSymbolTableInclusion() const { return ObjectFile::Atom::kSymbolTableNotIn; }
171 virtual bool dontDeadStrip() const { return false; }
172 virtual bool isZeroFill() const { return false; }
173 virtual uint64_t getSize() const { return 0; }
174 virtual std::vector<ObjectFile::Reference*>& getReferences() const { return (std::vector<ObjectFile::Reference*>&)(fReferences); }
175 virtual bool mustRemainInSection() const { return false; }
176 virtual const char* getSectionName() const { return "._imports"; }
177 virtual Segment& getSegment() const { return fgImportSegment; }
178 virtual ObjectFile::Atom& getFollowOnAtom() const { return *((ObjectFile::Atom*)NULL); }
179 virtual uint32_t getOrdinal() const { return fOrdinal; }
180 virtual std::vector<ObjectFile::LineInfo>* getLineInfo() const { return NULL; }
181 virtual ObjectFile::Alignment getAlignment() const { return ObjectFile::Alignment(0); }
182 virtual void copyRawContent(uint8_t buffer[]) const {}
184 virtual void setScope(Scope) { }
187 friend class Reader<A>;
188 typedef typename A::P P;
190 ImportAtom(ObjectFile::Reader& owner, uint32_t ordinal, std::vector<const char*>& imports)
191 : fOwner(owner), fOrdinal(ordinal) { makeReferences(imports); }
192 virtual ~ImportAtom() {}
193 void makeReferences(std::vector<const char*>& imports) {
194 for (std::vector<const char*>::iterator it=imports.begin(); it != imports.end(); ++it) {
195 fReferences.push_back(new ImportReference(*it));
200 ObjectFile::Reader& fOwner;
202 std::vector<ObjectFile::Reference*> fReferences;
204 static Segment fgImportSegment;
207 template <typename A>
208 Segment ImportAtom<A>::fgImportSegment("__LINKEDIT");
214 // The reader for a dylib extracts all exported symbols names from the memory-mapped
215 // dylib, builds a hash table, then unmaps the file. This is an important memory
216 // savings for large dylibs.
218 template <typename A>
219 class Reader : public ObjectFile::Reader
222 static bool validFile(const uint8_t* fileContent, bool executableOrDylib);
223 Reader(const uint8_t* fileContent, uint64_t fileLength, const char* path,
224 bool executableOrDylib, const ObjectFile::ReaderOptions& options,
225 uint32_t ordinalBase);
228 virtual const char* getPath() { return fPath; }
229 virtual time_t getModificationTime() { return 0; }
230 virtual DebugInfoKind getDebugInfoKind() { return ObjectFile::Reader::kDebugInfoNone; }
231 virtual std::vector<class ObjectFile::Atom*>& getAtoms();
232 virtual std::vector<class ObjectFile::Atom*>* getJustInTimeAtomsFor(const char* name);
233 virtual std::vector<Stab>* getStabs() { return NULL; }
234 virtual ObjectFile::Reader::ObjcConstraint getObjCConstraint() { return fObjcContraint; }
235 virtual const char* getInstallPath() { return fDylibInstallPath; }
236 virtual uint32_t getTimestamp() { return fDylibTimeStamp; }
237 virtual uint32_t getCurrentVersion() { return fDylibtCurrentVersion; }
238 virtual uint32_t getCompatibilityVersion() { return fDylibCompatibilityVersion; }
239 virtual void processIndirectLibraries(DylibHander* handler);
240 virtual void setExplicitlyLinked() { fExplicitlyLinked = true; }
241 virtual bool explicitlyLinked() { return fExplicitlyLinked; }
242 virtual bool implicitlyLinked() { return fImplicitlyLinked; }
243 virtual bool providedExportAtom() { return fProvidedAtom; }
244 virtual const char* parentUmbrella() { return fParentUmbrella; }
245 virtual std::vector<const char*>* getAllowableClients();
247 virtual void setImplicitlyLinked() { fImplicitlyLinked = true; }
251 struct ReExportChain { ReExportChain* prev; Reader<A>* reader; };
253 void assertNoReExportCycles(std::set<ObjectFile::Reader*>& chainedReExportReaders, ReExportChain*);
256 typedef typename A::P P;
257 typedef typename A::P::E E;
262 bool operator()(const char* left, const char* right) const { return (strcmp(left, right) == 0); }
264 struct AtomAndWeak { ObjectFile::Atom* atom; bool weak; uint32_t ordinal; };
265 typedef __gnu_cxx::hash_map<const char*, AtomAndWeak, __gnu_cxx::hash<const char*>, CStringEquals> NameToAtomMap;
266 typedef __gnu_cxx::hash_set<const char*, __gnu_cxx::hash<const char*>, CStringEquals> NameSet;
267 typedef typename NameToAtomMap::iterator NameToAtomMapIterator;
269 struct PathAndFlag { const char* path; bool reExport; };
271 bool isPublicLocation(const char* path);
272 void addSymbol(const char* name, bool weak, uint32_t ordinal);
275 const char* fParentUmbrella;
276 std::vector<const char*> fAllowableClients;
277 const char* fDylibInstallPath;
278 uint32_t fDylibTimeStamp;
279 uint32_t fDylibtCurrentVersion;
280 uint32_t fDylibCompatibilityVersion;
281 uint32_t fReExportedOrdinal;
282 std::vector<PathAndFlag> fDependentLibraryPaths;
283 NameToAtomMap fAtoms;
284 NameSet fIgnoreExports;
286 const bool fLinkingFlat;
287 const bool fLinkingMainExecutable;
288 bool fExplictReExportFound;
289 bool fExplicitlyLinked;
290 bool fImplicitlyLinked;
292 ObjectFile::Reader::ObjcConstraint fObjcContraint;
293 std::vector<ObjectFile::Reader*> fReExportedChildren;
294 const ObjectFile::ReaderOptions::VersionMin fDeploymentVersionMin;
295 std::vector<class ObjectFile::Atom*> fFlatImports;
297 static bool fgLogHashtable;
298 static std::vector<class ObjectFile::Atom*> fgEmptyAtomList;
301 template <typename A>
302 std::vector<class ObjectFile::Atom*> Reader<A>::fgEmptyAtomList;
303 template <typename A>
304 bool Reader<A>::fgLogHashtable = false;
307 template <typename A>
308 Reader<A>::Reader(const uint8_t* fileContent, uint64_t fileLength, const char* path, bool executableOrDylib,
309 const ObjectFile::ReaderOptions& options, uint32_t ordinalBase)
310 : fParentUmbrella(NULL), fDylibInstallPath(NULL), fDylibTimeStamp(0), fDylibtCurrentVersion(0),
311 fDylibCompatibilityVersion(0), fLinkingFlat(options.fFlatNamespace),
312 fLinkingMainExecutable(options.fLinkingMainExecutable), fExplictReExportFound(false),
313 fExplicitlyLinked(false), fImplicitlyLinked(false), fProvidedAtom(false), fObjcContraint(ObjectFile::Reader::kObjcNone),
314 fDeploymentVersionMin(options.fVersionMin)
317 if ( ! validFile(fileContent, executableOrDylib) )
318 throw "not a valid mach-o object file";
320 fPath = strdup(path);
322 const macho_header<P>* header = (const macho_header<P>*)fileContent;
323 const uint32_t cmd_count = header->ncmds();
324 const macho_load_command<P>* const cmds = (macho_load_command<P>*)((char*)header + sizeof(macho_header<P>));
326 // write out path for -whatsloaded option
327 if ( options.fLogAllFiles )
328 printf("%s\n", path);
330 if ( options.fRootSafe && ((header->flags() & MH_ROOT_SAFE) == 0) )
331 fprintf(stderr, "ld: warning using -root_safe but linking against %s which is not root safe\n", path);
333 if ( options.fSetuidSafe && ((header->flags() & MH_SETUID_SAFE) == 0) )
334 fprintf(stderr, "ld: warning using -setuid_safe but linking against %s which is not setuid safe\n", path);
336 // a "blank" stub has zero load commands
337 if ( (header->filetype() == MH_DYLIB_STUB) && (cmd_count == 0) ) {
338 // no further processing needed
339 munmap((caddr_t)fileContent, fileLength);
344 // optimize the case where we know there is no reason to look at indirect dylibs
345 fNoRexports = (header->flags() & MH_NO_REEXPORTED_DYLIBS);
346 bool trackDependentLibraries = !fNoRexports || options.fFlatNamespace;
348 // pass 1 builds list of all dependent libraries
349 const macho_load_command<P>* cmd = cmds;
350 if ( trackDependentLibraries ) {
351 for (uint32_t i = 0; i < cmd_count; ++i) {
352 switch (cmd->cmd()) {
353 case LC_REEXPORT_DYLIB:
354 fExplictReExportFound = true;
355 // fall into next case
357 case LC_LOAD_WEAK_DYLIB:
359 entry.path = strdup(((struct macho_dylib_command<P>*)cmd)->name());
360 entry.reExport = (cmd->cmd() == LC_REEXPORT_DYLIB);
361 fDependentLibraryPaths.push_back(entry);
364 cmd = (const macho_load_command<P>*)(((char*)cmd)+cmd->cmdsize());
368 // pass 2 determines re-export info
369 const macho_dysymtab_command<P>* dynamicInfo = NULL;
370 const macho_nlist<P>* symbolTable = NULL;
371 const char* strings = NULL;
373 for (uint32_t i = 0; i < cmd_count; ++i) {
374 switch (cmd->cmd()) {
377 const macho_symtab_command<P>* symtab = (macho_symtab_command<P>*)cmd;
378 symbolTable = (const macho_nlist<P>*)((char*)header + symtab->symoff());
379 strings = (char*)header + symtab->stroff();
383 dynamicInfo = (macho_dysymtab_command<P>*)cmd;
387 macho_dylib_command<P>* dylibID = (macho_dylib_command<P>*)cmd;
388 fDylibInstallPath = strdup(dylibID->name());
389 fDylibTimeStamp = dylibID->timestamp();
390 fDylibtCurrentVersion = dylibID->current_version();
391 fDylibCompatibilityVersion = dylibID->compatibility_version();
394 case LC_SUB_UMBRELLA:
395 if ( trackDependentLibraries ) {
396 const char* frameworkLeafName = ((macho_sub_umbrella_command<P>*)cmd)->sub_umbrella();
397 for (typename std::vector<PathAndFlag>::iterator it = fDependentLibraryPaths.begin(); it != fDependentLibraryPaths.end(); it++) {
398 const char* dylibName = it->path;
399 const char* lastSlash = strrchr(dylibName, '/');
400 if ( (lastSlash != NULL) && (strcmp(&lastSlash[1], frameworkLeafName) == 0) )
406 if ( trackDependentLibraries) {
407 const char* dylibBaseName = ((macho_sub_library_command<P>*)cmd)->sub_library();
408 for (typename std::vector<PathAndFlag>::iterator it = fDependentLibraryPaths.begin(); it != fDependentLibraryPaths.end(); it++) {
409 const char* dylibName = it->path;
410 const char* lastSlash = strrchr(dylibName, '/');
411 const char* leafStart = &lastSlash[1];
412 if ( lastSlash == NULL )
413 leafStart = dylibName;
414 const char* firstDot = strchr(leafStart, '.');
415 int len = strlen(leafStart);
416 if ( firstDot != NULL )
417 len = firstDot - leafStart;
418 if ( strncmp(leafStart, dylibBaseName, len) == 0 )
423 case LC_SUB_FRAMEWORK:
424 fParentUmbrella = strdup(((macho_sub_framework_command<P>*)cmd)->umbrella());
426 case macho_segment_command<P>::CMD:
427 // check for Objective-C info
428 if ( strcmp(((macho_segment_command<P>*)cmd)->segname(), "__OBJC") == 0 ) {
429 const macho_segment_command<P>* segment = (macho_segment_command<P>*)cmd;
430 const macho_section<P>* const sectionsStart = (macho_section<P>*)((char*)segment + sizeof(macho_segment_command<P>));
431 const macho_section<P>* const sectionsEnd = §ionsStart[segment->nsects()];
432 for (const macho_section<P>* sect=sectionsStart; sect < sectionsEnd; ++sect) {
433 if ( strcmp(sect->sectname(), "__image_info") == 0 ) {
434 // struct objc_image_info {
435 // uint32_t version; // initially 0
438 // #define OBJC_IMAGE_SUPPORTS_GC 2
439 // #define OBJC_IMAGE_GC_ONLY 4
441 const uint32_t* contents = (uint32_t*)(&fileContent[sect->offset()]);
442 if ( (sect->size() >= 8) && (contents[0] == 0) ) {
443 uint32_t flags = E::get32(contents[1]);
444 if ( (flags & 4) == 4 )
445 fObjcContraint = ObjectFile::Reader::kObjcGC;
446 else if ( (flags & 2) == 2 )
447 fObjcContraint = ObjectFile::Reader::kObjcRetainReleaseOrGC;
449 fObjcContraint = ObjectFile::Reader::kObjcRetainRelease;
451 else if ( sect->size() > 0 ) {
452 fprintf(stderr, "ld: warning, can't parse __OBJC/__image_info section in %s\n", fPath);
459 cmd = (const macho_load_command<P>*)(((char*)cmd)+cmd->cmdsize());
462 // Process the rest of the commands here.
464 for (uint32_t i = 0; i < cmd_count; ++i) {
465 switch (cmd->cmd()) {
467 const char *temp = strdup(((macho_sub_client_command<P>*)cmd)->client());
468 fAllowableClients.push_back(temp);
471 cmd = (const macho_load_command<P>*)(((char*)cmd)+cmd->cmdsize());
474 // validate minimal load commands
475 if ( (fDylibInstallPath == NULL) && (header->filetype() != MH_EXECUTE) )
476 throw "dylib missing LC_ID_DYLIB load command";
477 if ( symbolTable == NULL )
478 throw "dylib missing LC_SYMTAB load command";
479 if ( dynamicInfo == NULL )
480 throw "dylib missing LC_DYSYMTAB load command";
482 // if linking flat and this is a flat dylib, create one atom that references all imported symbols
483 if ( fLinkingFlat && fLinkingMainExecutable && ((header->flags() & MH_TWOLEVEL) == 0) ) {
484 std::vector<const char*> importNames;
485 importNames.reserve(dynamicInfo->nundefsym());
486 const macho_nlist<P>* start = &symbolTable[dynamicInfo->iundefsym()];
487 const macho_nlist<P>* end = &start[dynamicInfo->nundefsym()];
488 for (const macho_nlist<P>* sym=start; sym < end; ++sym) {
489 importNames.push_back(&strings[sym->n_strx()]);
491 fFlatImports.push_back(new ImportAtom<A>(*this, ordinalBase++, importNames));
495 if ( dynamicInfo->tocoff() == 0 ) {
496 if ( fgLogHashtable ) fprintf(stderr, "ld: building hashtable of %u toc entries for %s\n", dynamicInfo->nextdefsym(), path);
497 const macho_nlist<P>* start = &symbolTable[dynamicInfo->iextdefsym()];
498 const macho_nlist<P>* end = &start[dynamicInfo->nextdefsym()];
499 fAtoms.resize(dynamicInfo->nextdefsym()); // set initial bucket count
500 uint32_t index = ordinalBase;
501 for (const macho_nlist<P>* sym=start; sym < end; ++sym, ++index) {
502 this->addSymbol(&strings[sym->n_strx()], (sym->n_desc() & N_WEAK_DEF) != 0, index);
504 fReExportedOrdinal = index;
507 int32_t count = dynamicInfo->ntoc();
508 fAtoms.resize(count); // set initial bucket count
509 if ( fgLogHashtable ) fprintf(stderr, "ld: building hashtable of %u entries for %s\n", count, path);
510 const struct dylib_table_of_contents* toc = (dylib_table_of_contents*)((char*)header + dynamicInfo->tocoff());
511 for (int32_t i = 0; i < count; ++i) {
512 const uint32_t index = E::get32(toc[i].symbol_index);
513 const macho_nlist<P>* sym = &symbolTable[index];
514 this->addSymbol(&strings[sym->n_strx()], (sym->n_desc() & N_WEAK_DEF) != 0, ordinalBase+i);
516 fReExportedOrdinal = ordinalBase + count;
521 munmap((caddr_t)fileContent, fileLength);
526 template <typename A>
527 void Reader<A>::addSymbol(const char* name, bool weak, uint32_t ordinal)
529 // symbols that start with $ld$ are meta-data to the static linker
530 // <rdar://problem/5182537> need way for ld and dyld to see different exported symbols in a dylib
531 if ( strncmp(name, "$ld$", 4) == 0 ) {
532 // $ld$ <action> $ <condition> $ <symbol-name>
533 const char* symAction = &name[4];
534 const char* symCond = strchr(symAction, '$');
535 if ( symCond != NULL ) {
536 ObjectFile::ReaderOptions::VersionMin symVersionCondition = ObjectFile::ReaderOptions::kMinUnset;
537 if ( (strncmp(symCond, "$os10.", 6) == 0) && isdigit(symCond[6]) && (symCond[7] == '$') ) {
538 switch ( symCond[6] - '0' ) {
541 symVersionCondition = ObjectFile::ReaderOptions::k10_1;
544 symVersionCondition = ObjectFile::ReaderOptions::k10_2;
547 symVersionCondition = ObjectFile::ReaderOptions::k10_3;
550 symVersionCondition = ObjectFile::ReaderOptions::k10_4;
553 symVersionCondition = ObjectFile::ReaderOptions::k10_5;
556 const char* symName = strchr(&symCond[1], '$');
557 if ( symName != NULL ) {
559 if ( fDeploymentVersionMin == symVersionCondition ) {
560 if ( strncmp(symAction, "hide$", 5) == 0 ) {
561 if ( fgLogHashtable ) fprintf(stderr, " adding %s to ignore set for %s\n", symName, this->getPath());
562 fIgnoreExports.insert(strdup(symName));
565 else if ( strncmp(symAction, "add$", 4) == 0 ) {
566 this->addSymbol(symName, weak, ordinal);
570 fprintf(stderr, "ld: warning bad symbol action: %s in dylib %s\n", name, this->getPath());
575 fprintf(stderr, "ld: warning bad symbol name: %s in dylib %s\n", name, this->getPath());
579 fprintf(stderr, "ld: warning bad symbol version: %s in dylib %s\n", name, this->getPath());
583 fprintf(stderr, "ld: warning bad symbol condition: %s in dylib %s\n", name, this->getPath());
587 // add symbol as possible export if we are not supposed to ignore it
588 if ( fIgnoreExports.count(name) == 0 ) {
592 bucket.ordinal = ordinal;
593 if ( fgLogHashtable ) fprintf(stderr, " adding %s to hash table for %s\n", name, this->getPath());
594 fAtoms[strdup(name)] = bucket;
599 template <typename A>
600 std::vector<class ObjectFile::Atom*>& Reader<A>::getAtoms()
606 template <typename A>
607 std::vector<class ObjectFile::Atom*>* Reader<A>::getJustInTimeAtomsFor(const char* name)
609 std::vector<class ObjectFile::Atom*>* atoms = NULL;
611 NameToAtomMapIterator pos = fAtoms.find(name);
612 if ( pos != fAtoms.end() ) {
613 if ( pos->second.atom == NULL ) {
614 // instantiate atom and update hash table
615 pos->second.atom = new ExportAtom<A>(*this, name, pos->second.weak, pos->second.ordinal);
616 fProvidedAtom = true;
617 if ( fgLogHashtable ) fprintf(stderr, "getJustInTimeAtomsFor: %s found in %s\n", name, this->getPath());
619 // return a vector of one atom
620 atoms = new std::vector<class ObjectFile::Atom*>;
621 atoms->push_back(pos->second.atom);
624 if ( fgLogHashtable ) fprintf(stderr, "getJustInTimeAtomsFor: %s NOT found in %s\n", name, this->getPath());
625 // if not supposed to ignore this export, see if I have it
626 if ( fIgnoreExports.count(name) == 0 ) {
627 // look in children that I re-export
628 for (std::vector<ObjectFile::Reader*>::iterator it = fReExportedChildren.begin(); it != fReExportedChildren.end(); it++) {
629 //fprintf(stderr, "getJustInTimeAtomsFor: %s NOT found in %s, looking in child %s\n", name, this->getPath(), (*it)->getInstallPath());
630 std::vector<class ObjectFile::Atom*>* childAtoms = (*it)->getJustInTimeAtomsFor(name);
631 if ( childAtoms != NULL ) {
632 // make a new atom that says this reader is the owner
633 bool isWeakDef = (childAtoms->at(0)->getDefinitionKind() == ObjectFile::Atom::kExternalWeakDefinition);
634 // return a vector of one atom
635 ExportAtom<A>* newAtom = new ExportAtom<A>(*this, name, isWeakDef, fReExportedOrdinal++);
636 fProvidedAtom = true;
637 atoms = new std::vector<class ObjectFile::Atom*>;
638 atoms->push_back(newAtom);
650 template <typename A>
651 bool Reader<A>::isPublicLocation(const char* path)
653 // /usr/lib is a public location
654 if ( (strncmp(path, "/usr/lib/", 9) == 0) && (strchr(&path[9], '/') == NULL) )
657 // /System/Library/Frameworks/ is a public location
658 if ( strncmp(path, "/System/Library/Frameworks/", 27) == 0 ) {
659 const char* frameworkDot = strchr(&path[27], '.');
660 // but only top level framework
661 // /System/Library/Frameworks/Foo.framework/Versions/A/Foo ==> true
662 // /System/Library/Frameworks/Foo.framework/Resources/libBar.dylib ==> false
663 // /System/Library/Frameworks/Foo.framework/Frameworks/Bar.framework/Bar ==> false
664 // /System/Library/Frameworks/Foo.framework/Frameworks/Xfoo.framework/XFoo ==> false
665 if ( frameworkDot != NULL ) {
666 int frameworkNameLen = frameworkDot - &path[27];
667 if ( strncmp(&path[strlen(path)-frameworkNameLen-1], &path[26], frameworkNameLen+1) == 0 )
675 template <typename A>
676 void Reader<A>::processIndirectLibraries(DylibHander* handler)
678 if ( fLinkingFlat ) {
679 for (typename std::vector<PathAndFlag>::iterator it = fDependentLibraryPaths.begin(); it != fDependentLibraryPaths.end(); it++) {
680 handler->findDylib(it->path, this->getPath());
683 else if ( fNoRexports ) {
684 // MH_NO_REEXPORTED_DYLIBS bit set, then nothing to do
687 // two-level, might have re-exports
688 for (typename std::vector<PathAndFlag>::iterator it = fDependentLibraryPaths.begin(); it != fDependentLibraryPaths.end(); it++) {
689 if ( it->reExport ) {
690 //fprintf(stderr, "processIndirectLibraries() parent=%s, child=%s\n", this->getInstallPath(), it->path);
691 // a LC_REEXPORT_DYLIB, LC_SUB_UMBRELLA or LC_SUB_LIBRARY says we re-export this child
692 ObjectFile::Reader* child = handler->findDylib(it->path, this->getPath());
693 if ( isPublicLocation(child->getInstallPath()) ) {
694 // promote this child to be automatically added as a direct dependent if this already is
695 if ( this->explicitlyLinked() || this->implicitlyLinked() ) {
696 //fprintf(stderr, "processIndirectLibraries() implicitly linking %s\n", child->getInstallPath());
697 ((Reader<A>*)child)->setImplicitlyLinked();
700 fReExportedChildren.push_back(child);
703 // add all child's symbols to me
704 fReExportedChildren.push_back(child);
705 //fprintf(stderr, "processIndirectLibraries() parent=%s will re-export child=%s\n", this->getInstallPath(), it->path);
708 else if ( !fExplictReExportFound ) {
709 // see if child contains LC_SUB_FRAMEWORK with my name
710 ObjectFile::Reader* child = handler->findDylib(it->path, this->getPath());
711 const char* parentUmbrellaName = ((Reader<A>*)child)->parentUmbrella();
712 if ( parentUmbrellaName != NULL ) {
713 const char* parentName = this->getPath();
714 const char* lastSlash = strrchr(parentName, '/');
715 if ( (lastSlash != NULL) && (strcmp(&lastSlash[1], parentUmbrellaName) == 0) ) {
716 // add all child's symbols to me
717 fReExportedChildren.push_back(child);
718 //fprintf(stderr, "processIndirectLibraries() umbrella=%s will re-export child=%s\n", this->getInstallPath(), it->path);
725 // check for re-export cycles
726 std::set<ObjectFile::Reader*> chainedReExportReaders;
730 this->assertNoReExportCycles(chainedReExportReaders, &chain);
733 template <typename A>
734 void Reader<A>::assertNoReExportCycles(std::set<ObjectFile::Reader*>& chainedReExportReaders, ReExportChain* prev)
736 // check none of my re-exported dylibs are already in set
737 for (std::vector<ObjectFile::Reader*>::iterator it = fReExportedChildren.begin(); it != fReExportedChildren.end(); it++) {
738 if ( chainedReExportReaders.count(*it) != 0 ) {
739 // we may want to print out the chain of dylibs causing the cylce...
740 throwf("cycle in dylib re-exports with %s", this->getPath());
743 // recursively check my re-exportted dylibs
744 chainedReExportReaders.insert(this);
748 for (std::vector<ObjectFile::Reader*>::iterator it = fReExportedChildren.begin(); it != fReExportedChildren.end(); it++) {
749 ((Reader<A>*)(*it))->assertNoReExportCycles(chainedReExportReaders, &chain);
754 template <typename A>
755 std::vector<const char*>* Reader<A>::getAllowableClients()
757 std::vector<const char*>* result = new std::vector<const char*>;
758 for (typename std::vector<const char*>::iterator it = fAllowableClients.begin();
759 it != fAllowableClients.end();
761 result->push_back(*it);
763 return (fAllowableClients.size() != 0 ? result : NULL);
767 bool Reader<ppc>::validFile(const uint8_t* fileContent, bool executableOrDylib)
769 const macho_header<P>* header = (const macho_header<P>*)fileContent;
770 if ( header->magic() != MH_MAGIC )
772 if ( header->cputype() != CPU_TYPE_POWERPC )
774 switch ( header->filetype() ) {
779 return executableOrDylib;
786 bool Reader<ppc64>::validFile(const uint8_t* fileContent, bool executableOrDylib)
788 const macho_header<P>* header = (const macho_header<P>*)fileContent;
789 if ( header->magic() != MH_MAGIC_64 )
791 if ( header->cputype() != CPU_TYPE_POWERPC64 )
793 switch ( header->filetype() ) {
798 return executableOrDylib;
805 bool Reader<x86>::validFile(const uint8_t* fileContent, bool executableOrDylib)
807 const macho_header<P>* header = (const macho_header<P>*)fileContent;
808 if ( header->magic() != MH_MAGIC )
810 if ( header->cputype() != CPU_TYPE_I386 )
812 switch ( header->filetype() ) {
817 return executableOrDylib;
824 bool Reader<x86_64>::validFile(const uint8_t* fileContent, bool executableOrDylib)
826 const macho_header<P>* header = (const macho_header<P>*)fileContent;
827 if ( header->magic() != MH_MAGIC_64 )
829 if ( header->cputype() != CPU_TYPE_X86_64 )
831 switch ( header->filetype() ) {
836 return executableOrDylib;
845 }; // namespace dylib
846 }; // namespace mach_o
849 #endif // __OBJECT_FILE_DYLIB_MACH_O__