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 bool isThumb() const { return false; }
91 virtual uint64_t getSize() const { return 0; }
92 virtual std::vector<ObjectFile::Reference*>& getReferences() const { return fgEmptyReferenceList; }
93 virtual bool mustRemainInSection() const { return false; }
94 virtual const char* getSectionName() const { return "._imports"; }
95 virtual Segment& getSegment() const { return fgImportSegment; }
96 virtual ObjectFile::Atom& getFollowOnAtom() const { return *((ObjectFile::Atom*)NULL); }
97 virtual uint32_t getOrdinal() const { return fOrdinal; }
98 virtual std::vector<ObjectFile::LineInfo>* getLineInfo() const { return NULL; }
99 virtual ObjectFile::Alignment getAlignment() const { return ObjectFile::Alignment(0); }
100 virtual void copyRawContent(uint8_t buffer[]) const {}
102 virtual void setScope(Scope) { }
105 friend class Reader<A>;
106 typedef typename A::P P;
108 ExportAtom(ObjectFile::Reader& owner, const char* name, bool weak, uint32_t ordinal)
109 : fOwner(owner), fName(name), fOrdinal(ordinal), fWeakDefinition(weak) {}
110 virtual ~ExportAtom() {}
112 ObjectFile::Reader& fOwner;
115 bool fWeakDefinition;
117 static std::vector<ObjectFile::Reference*> fgEmptyReferenceList;
118 static Segment fgImportSegment;
121 template <typename A>
122 Segment ExportAtom<A>::fgImportSegment("__LINKEDIT");
124 template <typename A>
125 std::vector<ObjectFile::Reference*> ExportAtom<A>::fgEmptyReferenceList;
129 class ImportReference : public ObjectFile::Reference
132 ImportReference(const char* name)
133 : fTarget(NULL), fTargetName(strdup(name)) {}
134 virtual ~ImportReference() {}
137 virtual ObjectFile::Reference::TargetBinding getTargetBinding() const { return (fTarget==NULL) ? ObjectFile::Reference::kUnboundByName : ObjectFile::Reference::kBoundByName; }
138 virtual ObjectFile::Reference::TargetBinding getFromTargetBinding() const{ return ObjectFile::Reference::kDontBind; }
139 virtual uint8_t getKind() const { return 0; }
140 virtual uint64_t getFixUpOffset() const { return 0; }
141 virtual const char* getTargetName() const { return fTargetName; }
142 virtual ObjectFile::Atom& getTarget() const { return *((ObjectFile::Atom*)fTarget); }
143 virtual uint64_t getTargetOffset() const { return 0; }
144 virtual ObjectFile::Atom& getFromTarget() const { return *((ObjectFile::Atom*)NULL); }
145 virtual const char* getFromTargetName() const { return NULL; }
146 virtual uint64_t getFromTargetOffset() const { return 0; }
147 virtual void setTarget(ObjectFile::Atom& atom, uint64_t offset) { fTarget = &atom; }
148 virtual void setFromTarget(ObjectFile::Atom&) { throw "can't set from target"; }
149 virtual const char* getDescription() const { return "dylib import reference"; }
152 const ObjectFile::Atom* fTarget;
153 const char* fTargetName;
158 // An ImportAtom has no content. It exists so that when linking a main executable flat-namespace
159 // the imports of all flat dylibs are checked
161 template <typename A>
162 class ImportAtom : public ObjectFile::Atom
165 virtual ObjectFile::Reader* getFile() const { return &fOwner; }
166 virtual bool getTranslationUnitSource(const char** dir, const char** name) const { return false; }
167 virtual const char* getName() const { return "flat-imports"; }
168 virtual const char* getDisplayName() const { return "flat_namespace undefines"; }
169 virtual Scope getScope() const { return ObjectFile::Atom::scopeTranslationUnit; }
170 virtual DefinitionKind getDefinitionKind() const { return kRegularDefinition; }
171 virtual SymbolTableInclusion getSymbolTableInclusion() const { return ObjectFile::Atom::kSymbolTableNotIn; }
172 virtual bool dontDeadStrip() const { return false; }
173 virtual bool isZeroFill() const { return false; }
174 virtual bool isThumb() const { return false; }
175 virtual uint64_t getSize() const { return 0; }
176 virtual std::vector<ObjectFile::Reference*>& getReferences() const { return (std::vector<ObjectFile::Reference*>&)(fReferences); }
177 virtual bool mustRemainInSection() const { return false; }
178 virtual const char* getSectionName() const { return "._imports"; }
179 virtual Segment& getSegment() const { return fgImportSegment; }
180 virtual ObjectFile::Atom& getFollowOnAtom() const { return *((ObjectFile::Atom*)NULL); }
181 virtual uint32_t getOrdinal() const { return fOrdinal; }
182 virtual std::vector<ObjectFile::LineInfo>* getLineInfo() const { return NULL; }
183 virtual ObjectFile::Alignment getAlignment() const { return ObjectFile::Alignment(0); }
184 virtual void copyRawContent(uint8_t buffer[]) const {}
186 virtual void setScope(Scope) { }
189 friend class Reader<A>;
190 typedef typename A::P P;
192 ImportAtom(ObjectFile::Reader& owner, uint32_t ordinal, std::vector<const char*>& imports)
193 : fOwner(owner), fOrdinal(ordinal) { makeReferences(imports); }
194 virtual ~ImportAtom() {}
195 void makeReferences(std::vector<const char*>& imports) {
196 for (std::vector<const char*>::iterator it=imports.begin(); it != imports.end(); ++it) {
197 fReferences.push_back(new ImportReference(*it));
202 ObjectFile::Reader& fOwner;
204 std::vector<ObjectFile::Reference*> fReferences;
206 static Segment fgImportSegment;
209 template <typename A>
210 Segment ImportAtom<A>::fgImportSegment("__LINKEDIT");
216 // The reader for a dylib extracts all exported symbols names from the memory-mapped
217 // dylib, builds a hash table, then unmaps the file. This is an important memory
218 // savings for large dylibs.
220 template <typename A>
221 class Reader : public ObjectFile::Reader
224 static bool validFile(const uint8_t* fileContent, bool executableOrDylib);
225 Reader(const uint8_t* fileContent, uint64_t fileLength, const char* path,
226 const DynamicLibraryOptions& dylibOptions, const ObjectFile::ReaderOptions& options,
227 uint32_t ordinalBase);
230 virtual const char* getPath() { return fPath; }
231 virtual time_t getModificationTime() { return 0; }
232 virtual DebugInfoKind getDebugInfoKind() { return ObjectFile::Reader::kDebugInfoNone; }
233 virtual std::vector<class ObjectFile::Atom*>& getAtoms();
234 virtual std::vector<class ObjectFile::Atom*>* getJustInTimeAtomsFor(const char* name);
235 virtual std::vector<Stab>* getStabs() { return NULL; }
236 virtual ObjectFile::Reader::ObjcConstraint getObjCConstraint() { return fObjcContraint; }
237 virtual const char* getInstallPath() { return fDylibInstallPath; }
238 virtual uint32_t getTimestamp() { return fDylibTimeStamp; }
239 virtual uint32_t getCurrentVersion() { return fDylibtCurrentVersion; }
240 virtual uint32_t getCompatibilityVersion() { return fDylibCompatibilityVersion; }
241 virtual void processIndirectLibraries(DylibHander* handler);
242 virtual void setExplicitlyLinked() { fExplicitlyLinked = true; }
243 virtual bool explicitlyLinked() { return fExplicitlyLinked; }
244 virtual bool implicitlyLinked() { return fImplicitlyLinked; }
245 virtual bool providedExportAtom() { return fProvidedAtom; }
246 virtual const char* parentUmbrella() { return fParentUmbrella; }
247 virtual std::vector<const char*>* getAllowableClients();
248 virtual bool hasWeakExternals() { return fHasWeakExports; }
249 virtual bool isLazyLoadedDylib() { return fLazyLoaded; }
251 virtual void setImplicitlyLinked() { fImplicitlyLinked = true; }
255 struct ReExportChain { ReExportChain* prev; Reader<A>* reader; };
257 void assertNoReExportCycles(ReExportChain*);
260 typedef typename A::P P;
261 typedef typename A::P::E E;
266 bool operator()(const char* left, const char* right) const { return (strcmp(left, right) == 0); }
268 struct AtomAndWeak { ObjectFile::Atom* atom; bool weak; uint32_t ordinal; };
269 typedef __gnu_cxx::hash_map<const char*, AtomAndWeak, __gnu_cxx::hash<const char*>, CStringEquals> NameToAtomMap;
270 typedef __gnu_cxx::hash_set<const char*, __gnu_cxx::hash<const char*>, CStringEquals> NameSet;
271 typedef typename NameToAtomMap::iterator NameToAtomMapIterator;
273 struct PathAndFlag { const char* path; bool reExport; };
275 bool isPublicLocation(const char* path);
276 void addSymbol(const char* name, bool weak, uint32_t ordinal);
279 const char* fParentUmbrella;
280 std::vector<const char*> fAllowableClients;
281 const char* fDylibInstallPath;
282 uint32_t fDylibTimeStamp;
283 uint32_t fDylibtCurrentVersion;
284 uint32_t fDylibCompatibilityVersion;
285 uint32_t fReExportedOrdinal;
286 std::vector<PathAndFlag> fDependentLibraryPaths;
287 NameToAtomMap fAtoms;
288 NameSet fIgnoreExports;
290 bool fHasWeakExports;
291 const bool fLinkingFlat;
292 const bool fLinkingMainExecutable;
293 bool fExplictReExportFound;
294 bool fExplicitlyLinked;
295 bool fImplicitlyLinked;
297 bool fImplicitlyLinkPublicDylibs;
299 ObjectFile::Reader::ObjcConstraint fObjcContraint;
300 std::vector<ObjectFile::Reader*> fReExportedChildren;
301 const ObjectFile::ReaderOptions::VersionMin fDeploymentVersionMin;
302 std::vector<class ObjectFile::Atom*> fFlatImports;
304 static bool fgLogHashtable;
305 static std::vector<class ObjectFile::Atom*> fgEmptyAtomList;
308 template <typename A>
309 std::vector<class ObjectFile::Atom*> Reader<A>::fgEmptyAtomList;
310 template <typename A>
311 bool Reader<A>::fgLogHashtable = false;
314 template <typename A>
315 Reader<A>::Reader(const uint8_t* fileContent, uint64_t fileLength, const char* path,
316 const DynamicLibraryOptions& dylibOptions,
317 const ObjectFile::ReaderOptions& options, uint32_t ordinalBase)
318 : fParentUmbrella(NULL), fDylibInstallPath(NULL), fDylibTimeStamp(0), fDylibtCurrentVersion(0),
319 fDylibCompatibilityVersion(0), fLinkingFlat(options.fFlatNamespace),
320 fLinkingMainExecutable(options.fLinkingMainExecutable), fExplictReExportFound(false),
321 fExplicitlyLinked(false), fImplicitlyLinked(false), fProvidedAtom(false),
322 fImplicitlyLinkPublicDylibs(options.fImplicitlyLinkPublicDylibs), fLazyLoaded(dylibOptions.fLazyLoad),
323 fObjcContraint(ObjectFile::Reader::kObjcNone),
324 fDeploymentVersionMin(options.fVersionMin)
327 if ( ! validFile(fileContent, dylibOptions.fBundleLoader) )
328 throw "not a valid mach-o object file";
330 fPath = strdup(path);
332 const macho_header<P>* header = (const macho_header<P>*)fileContent;
333 const uint32_t cmd_count = header->ncmds();
334 const macho_load_command<P>* const cmds = (macho_load_command<P>*)((char*)header + sizeof(macho_header<P>));
335 const macho_load_command<P>* const cmdsEnd = (macho_load_command<P>*)((char*)header + sizeof(macho_header<P>) + header->sizeofcmds());
337 // write out path for -whatsloaded option
338 if ( options.fLogAllFiles )
339 printf("%s\n", path);
341 if ( options.fRootSafe && ((header->flags() & MH_ROOT_SAFE) == 0) )
342 warning("using -root_safe but linking against %s which is not root safe", path);
344 if ( options.fSetuidSafe && ((header->flags() & MH_SETUID_SAFE) == 0) )
345 warning("using -setuid_safe but linking against %s which is not setuid safe", path);
347 // a "blank" stub has zero load commands
348 if ( (header->filetype() == MH_DYLIB_STUB) && (cmd_count == 0) ) {
349 // no further processing needed
350 munmap((caddr_t)fileContent, fileLength);
355 // optimize the case where we know there is no reason to look at indirect dylibs
356 fNoRexports = (header->flags() & MH_NO_REEXPORTED_DYLIBS);
357 fHasWeakExports = (header->flags() & MH_WEAK_DEFINES);
358 bool trackDependentLibraries = !fNoRexports || options.fFlatNamespace;
360 // pass 1 builds list of all dependent libraries
361 const macho_load_command<P>* cmd = cmds;
362 if ( trackDependentLibraries ) {
363 for (uint32_t i = 0; i < cmd_count; ++i) {
364 switch (cmd->cmd()) {
365 case LC_REEXPORT_DYLIB:
366 fExplictReExportFound = true;
367 // fall into next case
369 case LC_LOAD_WEAK_DYLIB:
371 entry.path = strdup(((struct macho_dylib_command<P>*)cmd)->name());
372 entry.reExport = (cmd->cmd() == LC_REEXPORT_DYLIB);
373 fDependentLibraryPaths.push_back(entry);
376 cmd = (const macho_load_command<P>*)(((char*)cmd)+cmd->cmdsize());
378 throwf("malformed dylb, load command #%d is outside size of load commands in %s", i, path);
382 // pass 2 determines re-export info
383 const macho_dysymtab_command<P>* dynamicInfo = NULL;
384 const macho_nlist<P>* symbolTable = NULL;
385 const char* strings = NULL;
387 for (uint32_t i = 0; i < cmd_count; ++i) {
388 switch (cmd->cmd()) {
391 const macho_symtab_command<P>* symtab = (macho_symtab_command<P>*)cmd;
392 symbolTable = (const macho_nlist<P>*)((char*)header + symtab->symoff());
393 strings = (char*)header + symtab->stroff();
397 dynamicInfo = (macho_dysymtab_command<P>*)cmd;
401 macho_dylib_command<P>* dylibID = (macho_dylib_command<P>*)cmd;
402 fDylibInstallPath = strdup(dylibID->name());
403 fDylibTimeStamp = dylibID->timestamp();
404 fDylibtCurrentVersion = dylibID->current_version();
405 fDylibCompatibilityVersion = dylibID->compatibility_version();
408 case LC_SUB_UMBRELLA:
409 if ( trackDependentLibraries ) {
410 const char* frameworkLeafName = ((macho_sub_umbrella_command<P>*)cmd)->sub_umbrella();
411 for (typename std::vector<PathAndFlag>::iterator it = fDependentLibraryPaths.begin(); it != fDependentLibraryPaths.end(); it++) {
412 const char* dylibName = it->path;
413 const char* lastSlash = strrchr(dylibName, '/');
414 if ( (lastSlash != NULL) && (strcmp(&lastSlash[1], frameworkLeafName) == 0) )
420 if ( trackDependentLibraries) {
421 const char* dylibBaseName = ((macho_sub_library_command<P>*)cmd)->sub_library();
422 for (typename std::vector<PathAndFlag>::iterator it = fDependentLibraryPaths.begin(); it != fDependentLibraryPaths.end(); it++) {
423 const char* dylibName = it->path;
424 const char* lastSlash = strrchr(dylibName, '/');
425 const char* leafStart = &lastSlash[1];
426 if ( lastSlash == NULL )
427 leafStart = dylibName;
428 const char* firstDot = strchr(leafStart, '.');
429 int len = strlen(leafStart);
430 if ( firstDot != NULL )
431 len = firstDot - leafStart;
432 if ( strncmp(leafStart, dylibBaseName, len) == 0 )
437 case LC_SUB_FRAMEWORK:
438 fParentUmbrella = strdup(((macho_sub_framework_command<P>*)cmd)->umbrella());
440 case macho_segment_command<P>::CMD:
441 // check for Objective-C info
442 if ( strcmp(((macho_segment_command<P>*)cmd)->segname(), "__OBJC") == 0 ) {
443 const macho_segment_command<P>* segment = (macho_segment_command<P>*)cmd;
444 const macho_section<P>* const sectionsStart = (macho_section<P>*)((char*)segment + sizeof(macho_segment_command<P>));
445 const macho_section<P>* const sectionsEnd = §ionsStart[segment->nsects()];
446 for (const macho_section<P>* sect=sectionsStart; sect < sectionsEnd; ++sect) {
447 if ( strcmp(sect->sectname(), "__image_info") == 0 ) {
448 // struct objc_image_info {
449 // uint32_t version; // initially 0
452 // #define OBJC_IMAGE_SUPPORTS_GC 2
453 // #define OBJC_IMAGE_GC_ONLY 4
455 const uint32_t* contents = (uint32_t*)(&fileContent[sect->offset()]);
456 if ( (sect->size() >= 8) && (contents[0] == 0) ) {
457 uint32_t flags = E::get32(contents[1]);
458 if ( (flags & 4) == 4 )
459 fObjcContraint = ObjectFile::Reader::kObjcGC;
460 else if ( (flags & 2) == 2 )
461 fObjcContraint = ObjectFile::Reader::kObjcRetainReleaseOrGC;
463 fObjcContraint = ObjectFile::Reader::kObjcRetainRelease;
465 else if ( sect->size() > 0 ) {
466 warning("can't parse __OBJC/__image_info section in %s", fPath);
473 cmd = (const macho_load_command<P>*)(((char*)cmd)+cmd->cmdsize());
475 throwf("malformed dylb, load command #%d is outside size of load commands in %s", i, path);
478 // Process the rest of the commands here.
480 for (uint32_t i = 0; i < cmd_count; ++i) {
481 switch (cmd->cmd()) {
483 const char *temp = strdup(((macho_sub_client_command<P>*)cmd)->client());
484 fAllowableClients.push_back(temp);
487 cmd = (const macho_load_command<P>*)(((char*)cmd)+cmd->cmdsize());
490 // validate minimal load commands
491 if ( (fDylibInstallPath == NULL) && ((header->filetype() == MH_DYLIB) || (header->filetype() == MH_DYLIB_STUB)) )
492 throwf("dylib %s missing LC_ID_DYLIB load command", path);
493 if ( symbolTable == NULL )
494 throw "binary missing LC_SYMTAB load command";
495 if ( dynamicInfo == NULL )
496 throw "binary missing LC_DYSYMTAB load command";
498 // if linking flat and this is a flat dylib, create one atom that references all imported symbols
499 if ( fLinkingFlat && fLinkingMainExecutable && ((header->flags() & MH_TWOLEVEL) == 0) ) {
500 std::vector<const char*> importNames;
501 importNames.reserve(dynamicInfo->nundefsym());
502 const macho_nlist<P>* start = &symbolTable[dynamicInfo->iundefsym()];
503 const macho_nlist<P>* end = &start[dynamicInfo->nundefsym()];
504 for (const macho_nlist<P>* sym=start; sym < end; ++sym) {
505 importNames.push_back(&strings[sym->n_strx()]);
507 fFlatImports.push_back(new ImportAtom<A>(*this, ordinalBase++, importNames));
511 if ( dynamicInfo->tocoff() == 0 ) {
512 if ( fgLogHashtable ) fprintf(stderr, "ld: building hashtable of %u toc entries for %s\n", dynamicInfo->nextdefsym(), path);
513 const macho_nlist<P>* start = &symbolTable[dynamicInfo->iextdefsym()];
514 const macho_nlist<P>* end = &start[dynamicInfo->nextdefsym()];
515 fAtoms.resize(dynamicInfo->nextdefsym()); // set initial bucket count
516 uint32_t index = ordinalBase;
517 for (const macho_nlist<P>* sym=start; sym < end; ++sym, ++index) {
518 this->addSymbol(&strings[sym->n_strx()], (sym->n_desc() & N_WEAK_DEF) != 0, index);
520 fReExportedOrdinal = index;
523 int32_t count = dynamicInfo->ntoc();
524 fAtoms.resize(count); // set initial bucket count
525 if ( fgLogHashtable ) fprintf(stderr, "ld: building hashtable of %u entries for %s\n", count, path);
526 const struct dylib_table_of_contents* toc = (dylib_table_of_contents*)((char*)header + dynamicInfo->tocoff());
527 for (int32_t i = 0; i < count; ++i) {
528 const uint32_t index = E::get32(toc[i].symbol_index);
529 const macho_nlist<P>* sym = &symbolTable[index];
530 this->addSymbol(&strings[sym->n_strx()], (sym->n_desc() & N_WEAK_DEF) != 0, ordinalBase+i);
532 fReExportedOrdinal = ordinalBase + count;
537 munmap((caddr_t)fileContent, fileLength);
542 template <typename A>
543 void Reader<A>::addSymbol(const char* name, bool weak, uint32_t ordinal)
545 // symbols that start with $ld$ are meta-data to the static linker
546 // <rdar://problem/5182537> need way for ld and dyld to see different exported symbols in a dylib
547 if ( strncmp(name, "$ld$", 4) == 0 ) {
548 // $ld$ <action> $ <condition> $ <symbol-name>
549 const char* symAction = &name[4];
550 const char* symCond = strchr(symAction, '$');
551 if ( symCond != NULL ) {
552 ObjectFile::ReaderOptions::VersionMin symVersionCondition = ObjectFile::ReaderOptions::kMinUnset;
553 if ( (strncmp(symCond, "$os10.", 6) == 0) && isdigit(symCond[6]) && (symCond[7] == '$') ) {
554 switch ( symCond[6] - '0' ) {
557 symVersionCondition = ObjectFile::ReaderOptions::k10_1;
560 symVersionCondition = ObjectFile::ReaderOptions::k10_2;
563 symVersionCondition = ObjectFile::ReaderOptions::k10_3;
566 symVersionCondition = ObjectFile::ReaderOptions::k10_4;
569 symVersionCondition = ObjectFile::ReaderOptions::k10_5;
572 symVersionCondition = ObjectFile::ReaderOptions::k10_6;
575 const char* symName = strchr(&symCond[1], '$');
576 if ( symName != NULL ) {
578 if ( fDeploymentVersionMin == symVersionCondition ) {
579 if ( strncmp(symAction, "hide$", 5) == 0 ) {
580 if ( fgLogHashtable ) fprintf(stderr, " adding %s to ignore set for %s\n", symName, this->getPath());
581 fIgnoreExports.insert(strdup(symName));
584 else if ( strncmp(symAction, "add$", 4) == 0 ) {
585 this->addSymbol(symName, weak, ordinal);
589 warning("bad symbol action: %s in dylib %s", name, this->getPath());
594 warning("bad symbol name: %s in dylib %s", name, this->getPath());
598 warning("bad symbol version: %s in dylib %s", name, this->getPath());
602 warning("bad symbol condition: %s in dylib %s", name, this->getPath());
606 // add symbol as possible export if we are not supposed to ignore it
607 if ( fIgnoreExports.count(name) == 0 ) {
611 bucket.ordinal = ordinal;
612 if ( fgLogHashtable ) fprintf(stderr, " adding %s to hash table for %s\n", name, this->getPath());
613 fAtoms[strdup(name)] = bucket;
618 template <typename A>
619 std::vector<class ObjectFile::Atom*>& Reader<A>::getAtoms()
625 template <typename A>
626 std::vector<class ObjectFile::Atom*>* Reader<A>::getJustInTimeAtomsFor(const char* name)
628 std::vector<class ObjectFile::Atom*>* atoms = NULL;
630 NameToAtomMapIterator pos = fAtoms.find(name);
631 if ( pos != fAtoms.end() ) {
632 if ( pos->second.atom == NULL ) {
633 // instantiate atom and update hash table
634 pos->second.atom = new ExportAtom<A>(*this, name, pos->second.weak, pos->second.ordinal);
635 fProvidedAtom = true;
636 if ( fgLogHashtable ) fprintf(stderr, "getJustInTimeAtomsFor: %s found in %s\n", name, this->getPath());
638 // return a vector of one atom
639 atoms = new std::vector<class ObjectFile::Atom*>;
640 atoms->push_back(pos->second.atom);
643 if ( fgLogHashtable ) fprintf(stderr, "getJustInTimeAtomsFor: %s NOT found in %s\n", name, this->getPath());
644 // if not supposed to ignore this export, see if I have it
645 if ( fIgnoreExports.count(name) == 0 ) {
646 // look in children that I re-export
647 for (std::vector<ObjectFile::Reader*>::iterator it = fReExportedChildren.begin(); it != fReExportedChildren.end(); it++) {
648 //fprintf(stderr, "getJustInTimeAtomsFor: %s NOT found in %s, looking in child %s\n", name, this->getPath(), (*it)->getInstallPath());
649 std::vector<class ObjectFile::Atom*>* childAtoms = (*it)->getJustInTimeAtomsFor(name);
650 if ( childAtoms != NULL ) {
651 // make a new atom that says this reader is the owner
652 bool isWeakDef = (childAtoms->at(0)->getDefinitionKind() == ObjectFile::Atom::kExternalWeakDefinition);
653 // return a vector of one atom
654 ExportAtom<A>* newAtom = new ExportAtom<A>(*this, name, isWeakDef, fReExportedOrdinal++);
655 fProvidedAtom = true;
656 atoms = new std::vector<class ObjectFile::Atom*>;
657 atoms->push_back(newAtom);
669 template <typename A>
670 bool Reader<A>::isPublicLocation(const char* path)
672 // -no_implicit_dylibs disables this optimization
673 if ( ! fImplicitlyLinkPublicDylibs )
676 // /usr/lib is a public location
677 if ( (strncmp(path, "/usr/lib/", 9) == 0) && (strchr(&path[9], '/') == NULL) )
680 // /System/Library/Frameworks/ is a public location
681 if ( strncmp(path, "/System/Library/Frameworks/", 27) == 0 ) {
682 const char* frameworkDot = strchr(&path[27], '.');
683 // but only top level framework
684 // /System/Library/Frameworks/Foo.framework/Versions/A/Foo ==> true
685 // /System/Library/Frameworks/Foo.framework/Resources/libBar.dylib ==> false
686 // /System/Library/Frameworks/Foo.framework/Frameworks/Bar.framework/Bar ==> false
687 // /System/Library/Frameworks/Foo.framework/Frameworks/Xfoo.framework/XFoo ==> false
688 if ( frameworkDot != NULL ) {
689 int frameworkNameLen = frameworkDot - &path[27];
690 if ( strncmp(&path[strlen(path)-frameworkNameLen-1], &path[26], frameworkNameLen+1) == 0 )
698 template <typename A>
699 void Reader<A>::processIndirectLibraries(DylibHander* handler)
701 if ( fLinkingFlat ) {
702 for (typename std::vector<PathAndFlag>::iterator it = fDependentLibraryPaths.begin(); it != fDependentLibraryPaths.end(); it++) {
703 handler->findDylib(it->path, this->getPath());
706 else if ( fNoRexports ) {
707 // MH_NO_REEXPORTED_DYLIBS bit set, then nothing to do
710 // two-level, might have re-exports
711 for (typename std::vector<PathAndFlag>::iterator it = fDependentLibraryPaths.begin(); it != fDependentLibraryPaths.end(); it++) {
712 if ( it->reExport ) {
713 //fprintf(stderr, "processIndirectLibraries() parent=%s, child=%s\n", this->getInstallPath(), it->path);
714 // a LC_REEXPORT_DYLIB, LC_SUB_UMBRELLA or LC_SUB_LIBRARY says we re-export this child
715 ObjectFile::Reader* child = handler->findDylib(it->path, this->getPath());
716 if ( isPublicLocation(child->getInstallPath()) ) {
717 // promote this child to be automatically added as a direct dependent if this already is
718 if ( this->explicitlyLinked() || this->implicitlyLinked() ) {
719 //fprintf(stderr, "processIndirectLibraries() implicitly linking %s\n", child->getInstallPath());
720 ((Reader<A>*)child)->setImplicitlyLinked();
723 fReExportedChildren.push_back(child);
726 // add all child's symbols to me
727 fReExportedChildren.push_back(child);
728 //fprintf(stderr, "processIndirectLibraries() parent=%s will re-export child=%s\n", this->getInstallPath(), it->path);
731 else if ( !fExplictReExportFound ) {
732 // see if child contains LC_SUB_FRAMEWORK with my name
733 ObjectFile::Reader* child = handler->findDylib(it->path, this->getPath());
734 const char* parentUmbrellaName = ((Reader<A>*)child)->parentUmbrella();
735 if ( parentUmbrellaName != NULL ) {
736 const char* parentName = this->getPath();
737 const char* lastSlash = strrchr(parentName, '/');
738 if ( (lastSlash != NULL) && (strcmp(&lastSlash[1], parentUmbrellaName) == 0) ) {
739 // add all child's symbols to me
740 fReExportedChildren.push_back(child);
741 //fprintf(stderr, "processIndirectLibraries() umbrella=%s will re-export child=%s\n", this->getInstallPath(), it->path);
748 // check for re-export cycles
752 this->assertNoReExportCycles(&chain);
755 template <typename A>
756 void Reader<A>::assertNoReExportCycles(ReExportChain* prev)
758 // recursively check my re-exported dylibs
762 for (std::vector<ObjectFile::Reader*>::iterator it = fReExportedChildren.begin(); it != fReExportedChildren.end(); it++) {
763 ObjectFile::Reader* child = *it;
764 // check child is not already in chain
765 for (ReExportChain* p = prev; p != NULL; p = p->prev) {
766 if ( p->reader == child ) {
767 throwf("cycle in dylib re-exports with %s", child->getPath());
770 ((Reader<A>*)(*it))->assertNoReExportCycles(&chain);
775 template <typename A>
776 std::vector<const char*>* Reader<A>::getAllowableClients()
778 std::vector<const char*>* result = new std::vector<const char*>;
779 for (typename std::vector<const char*>::iterator it = fAllowableClients.begin();
780 it != fAllowableClients.end();
782 result->push_back(*it);
784 return (fAllowableClients.size() != 0 ? result : NULL);
788 bool Reader<ppc>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle)
790 const macho_header<P>* header = (const macho_header<P>*)fileContent;
791 if ( header->magic() != MH_MAGIC )
793 if ( header->cputype() != CPU_TYPE_POWERPC )
795 switch ( header->filetype() ) {
800 if ( executableOrDyliborBundle )
803 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
805 if ( executableOrDyliborBundle )
808 throw "can't link with a main executable";
815 bool Reader<ppc64>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle)
817 const macho_header<P>* header = (const macho_header<P>*)fileContent;
818 if ( header->magic() != MH_MAGIC_64 )
820 if ( header->cputype() != CPU_TYPE_POWERPC64 )
822 switch ( header->filetype() ) {
827 if ( executableOrDyliborBundle )
830 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
832 if ( executableOrDyliborBundle )
835 throw "can't link with a main executable";
842 bool Reader<x86>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle)
844 const macho_header<P>* header = (const macho_header<P>*)fileContent;
845 if ( header->magic() != MH_MAGIC )
847 if ( header->cputype() != CPU_TYPE_I386 )
849 switch ( header->filetype() ) {
854 if ( executableOrDyliborBundle )
857 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
859 if ( executableOrDyliborBundle )
862 throw "can't link with a main executable";
869 bool Reader<x86_64>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle)
871 const macho_header<P>* header = (const macho_header<P>*)fileContent;
872 if ( header->magic() != MH_MAGIC_64 )
874 if ( header->cputype() != CPU_TYPE_X86_64 )
876 switch ( header->filetype() ) {
881 if ( executableOrDyliborBundle )
884 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
886 if ( executableOrDyliborBundle )
889 throw "can't link with a main executable";
896 bool Reader<arm>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle)
898 const macho_header<P>* header = (const macho_header<P>*)fileContent;
899 if ( header->magic() != MH_MAGIC )
901 if ( header->cputype() != CPU_TYPE_ARM )
903 switch ( header->filetype() ) {
908 if ( executableOrDyliborBundle )
911 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
913 if ( executableOrDyliborBundle )
916 throw "can't link with a main executable";
922 }; // namespace dylib
923 }; // namespace mach_o
926 #endif // __OBJECT_FILE_DYLIB_MACH_O__