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 "MachOTrie.hpp"
41 #include "ObjectFile.h"
45 // To implement architecture xxx, you must write template specializations for the following method:
46 // Reader<xxx>::validFile()
58 template <typename A> class Reader;
61 class Segment : public ObjectFile::Segment
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; }
75 // An ExportAtom has no content. It exists so that the linker can track which imported
76 // symbols came from which dynamic libraries.
79 class ExportAtom : public ObjectFile::Atom
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 {}
103 virtual void setScope(Scope) { }
106 friend class Reader<A>;
107 typedef typename A::P P;
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() {}
113 ObjectFile::Reader& fOwner;
116 bool fWeakDefinition;
118 static std::vector<ObjectFile::Reference*> fgEmptyReferenceList;
119 static Segment fgImportSegment;
122 template <typename A>
123 Segment ExportAtom<A>::fgImportSegment("__LINKEDIT");
125 template <typename A>
126 std::vector<ObjectFile::Reference*> ExportAtom<A>::fgEmptyReferenceList;
130 class ImportReference : public ObjectFile::Reference
133 ImportReference(const char* name)
134 : fTarget(NULL), fTargetName(strdup(name)) {}
135 virtual ~ImportReference() {}
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"; }
153 const ObjectFile::Atom* fTarget;
154 const char* fTargetName;
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
162 template <typename A>
163 class ImportAtom : public ObjectFile::Atom
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 {}
187 virtual void setScope(Scope) { }
190 friend class Reader<A>;
191 typedef typename A::P P;
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));
203 ObjectFile::Reader& fOwner;
205 std::vector<ObjectFile::Reference*> fReferences;
207 static Segment fgImportSegment;
210 template <typename A>
211 Segment ImportAtom<A>::fgImportSegment("__LINKEDIT");
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.
221 template <typename A>
222 class Reader : public ObjectFile::Reader
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);
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; }
253 virtual void setImplicitlyLinked() { fImplicitlyLinked = true; }
257 struct ReExportChain { ReExportChain* prev; Reader<A>* reader; };
259 void assertNoReExportCycles(ReExportChain*);
262 typedef typename A::P P;
263 typedef typename A::P::E E;
268 bool operator()(const char* left, const char* right) const { return (strcmp(left, right) == 0); }
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;
275 struct PathAndFlag { const char* path; bool reExport; };
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);
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;
298 bool fHasWeakExports;
299 bool fDeadStrippable;
300 const bool fLinkingFlat;
301 const bool fLinkingMainExecutable;
302 bool fExplictReExportFound;
303 bool fExplicitlyLinked;
304 bool fImplicitlyLinked;
306 bool fImplicitlyLinkPublicDylibs;
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;
314 static bool fgLogHashtable;
315 static std::vector<class ObjectFile::Atom*> fgEmptyAtomList;
318 template <typename A>
319 std::vector<class ObjectFile::Atom*> Reader<A>::fgEmptyAtomList;
320 template <typename A>
321 bool Reader<A>::fgLogHashtable = false;
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)
338 if ( ! validFile(fileContent, dylibOptions.fBundleLoader) )
339 throw "not a valid mach-o object file";
341 fPath = strdup(path);
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());
348 // write out path for -whatsloaded option
349 if ( options.fLogAllFiles )
350 printf("%s\n", path);
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);
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);
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);
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;
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
381 case LC_LOAD_WEAK_DYLIB:
383 entry.path = strdup(((struct macho_dylib_command<P>*)cmd)->name());
384 entry.reExport = (cmd->cmd() == LC_REEXPORT_DYLIB);
385 fDependentLibraryPaths.push_back(entry);
388 cmd = (const macho_load_command<P>*)(((char*)cmd)+cmd->cmdsize());
390 throwf("malformed dylb, load command #%d is outside size of load commands in %s", i, path);
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;
400 for (uint32_t i = 0; i < cmd_count; ++i) {
401 switch (cmd->cmd()) {
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();
410 dynamicInfo = (macho_dysymtab_command<P>*)cmd;
413 case LC_DYLD_INFO_ONLY:
414 dyldInfo = (macho_dyld_info_command<P>*)cmd;
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();
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) )
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 )
454 case LC_SUB_FRAMEWORK:
455 fParentUmbrella = strdup(((macho_sub_framework_command<P>*)cmd)->umbrella());
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 = §ionsStart[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
469 // #define OBJC_IMAGE_SUPPORTS_GC 2
470 // #define OBJC_IMAGE_GC_ONLY 4
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;
480 fObjcContraint = ObjectFile::Reader::kObjcRetainRelease;
482 else if ( sect->size() > 0 ) {
483 warning("can't parse __OBJC/__image_info section in %s", fPath);
490 cmd = (const macho_load_command<P>*)(((char*)cmd)+cmd->cmdsize());
492 throwf("malformed dylb, load command #%d is outside size of load commands in %s", i, path);
495 // Process the rest of the commands here.
497 for (uint32_t i = 0; i < cmd_count; ++i) {
498 switch (cmd->cmd()) {
500 const char *temp = strdup(((macho_sub_client_command<P>*)cmd)->client());
501 fAllowableClients.push_back(temp);
504 cmd = (const macho_load_command<P>*)(((char*)cmd)+cmd->cmdsize());
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";
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()]);
524 fFlatImports.push_back(new ImportAtom<A>(*this, fReExportedOrdinal++, importNames));
528 if ( dyldInfo != NULL )
529 buildExportHashTableFromExportInfo(dyldInfo, fileContent);
531 buildExportHashTableFromSymbolTable(dynamicInfo, symbolTable, strings, fileContent);
533 // special case libSystem
534 if ( (fDylibInstallPath != NULL) && (strcmp(fDylibInstallPath, "/usr/lib/libSystem.B.dylib") == 0) )
538 munmap((caddr_t)fileContent, fileLength);
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)
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);
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);
570 template <typename A>
571 void Reader<A>::buildExportHashTableFromExportInfo(const macho_dyld_info_command<P>* dyldInfo,
572 const uint8_t* fileContent)
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);
587 void Reader<x86_64>::addDyldFastStub()
589 addSymbol("dyld_stub_binder", false);
593 void Reader<x86>::addDyldFastStub()
595 addSymbol("dyld_stub_binder", false);
598 // hack for bring up of iPhoneOS builds on SnowLeopard
600 void Reader<arm>::addDyldFastStub()
602 addSymbol("dyld_stub_binder", false);
605 template <typename A>
606 void Reader<A>::addDyldFastStub()
611 template <typename A>
612 void Reader<A>::addSymbol(const char* name, bool weakDef)
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' ) {
629 symVersionCondition = ObjectFile::ReaderOptions::k10_1;
632 symVersionCondition = ObjectFile::ReaderOptions::k10_2;
635 symVersionCondition = ObjectFile::ReaderOptions::k10_3;
638 symVersionCondition = ObjectFile::ReaderOptions::k10_4;
641 symVersionCondition = ObjectFile::ReaderOptions::k10_5;
644 symVersionCondition = ObjectFile::ReaderOptions::k10_6;
647 const char* symName = strchr(&symCond[1], '$');
648 if ( symName != NULL ) {
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));
656 else if ( strncmp(symAction, "add$", 4) == 0 ) {
657 this->addSymbol(symName, weakDef);
661 warning("bad symbol action: %s in dylib %s", name, this->getPath());
666 warning("bad symbol name: %s in dylib %s", name, this->getPath());
670 warning("bad symbol version: %s in dylib %s", name, this->getPath());
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 ) {
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));
700 else if ( strncmp(symAction, "add$", 4) == 0 ) {
701 this->addSymbol(symName, weakDef);
705 warning("bad symbol action: %s in dylib %s", name, this->getPath());
710 warning("bad symbol name: %s in dylib %s", name, this->getPath());
714 warning("bad symbol version: %s in dylib %s, symCond=%s", name, this->getPath(), symCond);
719 warning("bad symbol condition: %s in dylib %s", name, this->getPath());
723 // add symbol as possible export if we are not supposed to ignore it
724 if ( fIgnoreExports.count(name) == 0 ) {
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;
735 template <typename A>
736 std::vector<class ObjectFile::Atom*>& Reader<A>::getAtoms()
742 template <typename A>
743 std::vector<class ObjectFile::Atom*>* Reader<A>::getJustInTimeAtomsFor(const char* name)
745 // if supposed to ignore this export, then pretend I don't have it
746 if ( fIgnoreExports.count(name) != 0 )
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());
758 // return a vector of one atom
759 atoms = new std::vector<class ObjectFile::Atom*>;
760 atoms->push_back(pos->second.atom);
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);
786 template <typename A>
787 bool Reader<A>::isPublicLocation(const char* path)
789 // -no_implicit_dylibs disables this optimization
790 if ( ! fImplicitlyLinkPublicDylibs )
793 // /usr/lib is a public location
794 if ( (strncmp(path, "/usr/lib/", 9) == 0) && (strchr(&path[9], '/') == NULL) )
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 )
815 template <typename A>
816 void Reader<A>::processIndirectLibraries(DylibHander* handler)
818 if ( fLinkingFlat ) {
819 for (typename std::vector<PathAndFlag>::iterator it = fDependentLibraryPaths.begin(); it != fDependentLibraryPaths.end(); it++) {
820 handler->findDylib(it->path, this->getPath());
823 else if ( fNoRexports ) {
824 // MH_NO_REEXPORTED_DYLIBS bit set, then nothing to do
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();
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");
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);
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);
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);
870 // check for re-export cycles
874 this->assertNoReExportCycles(&chain);
877 template <typename A>
878 void Reader<A>::assertNoReExportCycles(ReExportChain* prev)
880 // recursively check my re-exported dylibs
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());
892 ((Reader<A>*)(*it))->assertNoReExportCycles(&chain);
897 template <typename A>
898 std::vector<const char*>* Reader<A>::getAllowableClients()
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();
904 result->push_back(*it);
906 return (fAllowableClients.size() != 0 ? result : NULL);
910 bool Reader<ppc>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle)
912 const macho_header<P>* header = (const macho_header<P>*)fileContent;
913 if ( header->magic() != MH_MAGIC )
915 if ( header->cputype() != CPU_TYPE_POWERPC )
917 switch ( header->filetype() ) {
922 if ( executableOrDyliborBundle )
925 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
927 if ( executableOrDyliborBundle )
930 throw "can't link with a main executable";
937 bool Reader<ppc64>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle)
939 const macho_header<P>* header = (const macho_header<P>*)fileContent;
940 if ( header->magic() != MH_MAGIC_64 )
942 if ( header->cputype() != CPU_TYPE_POWERPC64 )
944 switch ( header->filetype() ) {
949 if ( executableOrDyliborBundle )
952 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
954 if ( executableOrDyliborBundle )
957 throw "can't link with a main executable";
964 bool Reader<x86>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle)
966 const macho_header<P>* header = (const macho_header<P>*)fileContent;
967 if ( header->magic() != MH_MAGIC )
969 if ( header->cputype() != CPU_TYPE_I386 )
971 switch ( header->filetype() ) {
976 if ( executableOrDyliborBundle )
979 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
981 if ( executableOrDyliborBundle )
984 throw "can't link with a main executable";
991 bool Reader<x86_64>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle)
993 const macho_header<P>* header = (const macho_header<P>*)fileContent;
994 if ( header->magic() != MH_MAGIC_64 )
996 if ( header->cputype() != CPU_TYPE_X86_64 )
998 switch ( header->filetype() ) {
1003 if ( executableOrDyliborBundle )
1006 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
1008 if ( executableOrDyliborBundle )
1011 throw "can't link with a main executable";
1018 bool Reader<arm>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle)
1020 const macho_header<P>* header = (const macho_header<P>*)fileContent;
1021 if ( header->magic() != MH_MAGIC )
1023 if ( header->cputype() != CPU_TYPE_ARM )
1025 switch ( header->filetype() ) {
1030 if ( executableOrDyliborBundle )
1033 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
1035 if ( executableOrDyliborBundle )
1038 throw "can't link with a main executable";
1044 }; // namespace dylib
1045 }; // namespace mach_o
1048 #endif // __OBJECT_FILE_DYLIB_MACH_O__