]> git.saurik.com Git - apple/ld64.git/blob - FireOpal/src/MachOReaderDylib.hpp
eb8e844392723c69e7c6512de416474c76507436
[apple/ld64.git] / FireOpal / src / MachOReaderDylib.hpp
1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
2 *
3 * Copyright (c) 2005-2007 Apple Inc. All rights reserved.
4 *
5 * @APPLE_LICENSE_HEADER_START@
6 *
7 * This file contains Original Code and/or Modifications of Original Code
8 * as defined in and that are subject to the Apple Public Source License
9 * Version 2.0 (the 'License'). You may not use this file except in
10 * compliance with the License. Please obtain a copy of the License at
11 * http://www.opensource.apple.com/apsl/ and read it before using this
12 * file.
13 *
14 * The Original Code and all software distributed under the License are
15 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
19 * Please see the License for the specific language governing rights and
20 * limitations under the License.
21 *
22 * @APPLE_LICENSE_HEADER_END@
23 */
24
25 #ifndef __OBJECT_FILE_DYLIB_MACH_O__
26 #define __OBJECT_FILE_DYLIB_MACH_O__
27
28 #include <stdint.h>
29 #include <math.h>
30 #include <unistd.h>
31 #include <sys/param.h>
32
33
34 #include <vector>
35 #include <set>
36 #include <algorithm>
37 #include <ext/hash_map>
38
39 #include "MachOFileAbstraction.hpp"
40 #include "ObjectFile.h"
41
42 //
43 //
44 // To implement architecture xxx, you must write template specializations for the following method:
45 // Reader<xxx>::validFile()
46 //
47 //
48
49
50
51
52 namespace mach_o {
53 namespace dylib {
54
55
56 // forward reference
57 template <typename A> class Reader;
58
59
60 class Segment : public ObjectFile::Segment
61 {
62 public:
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; }
68 private:
69 const char* fName;
70 };
71
72
73 //
74 // An ExportAtom has no content. It exists so that the linker can track which imported
75 // symbols came from which dynamic libraries.
76 //
77 template <typename A>
78 class ExportAtom : public ObjectFile::Atom
79 {
80 public:
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 {}
101
102 virtual void setScope(Scope) { }
103
104 protected:
105 friend class Reader<A>;
106 typedef typename A::P P;
107
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() {}
111
112 ObjectFile::Reader& fOwner;
113 const char* fName;
114 uint32_t fOrdinal;
115 bool fWeakDefinition;
116
117 static std::vector<ObjectFile::Reference*> fgEmptyReferenceList;
118 static Segment fgImportSegment;
119 };
120
121 template <typename A>
122 Segment ExportAtom<A>::fgImportSegment("__LINKEDIT");
123
124 template <typename A>
125 std::vector<ObjectFile::Reference*> ExportAtom<A>::fgEmptyReferenceList;
126
127
128
129 class ImportReference : public ObjectFile::Reference
130 {
131 public:
132 ImportReference(const char* name)
133 : fTarget(NULL), fTargetName(strdup(name)) {}
134 virtual ~ImportReference() {}
135
136
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"; }
150
151 private:
152 const ObjectFile::Atom* fTarget;
153 const char* fTargetName;
154 };
155
156
157 //
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
160 //
161 template <typename A>
162 class ImportAtom : public ObjectFile::Atom
163 {
164 public:
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 {}
185
186 virtual void setScope(Scope) { }
187
188 protected:
189 friend class Reader<A>;
190 typedef typename A::P P;
191
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));
198 }
199 }
200
201
202 ObjectFile::Reader& fOwner;
203 uint32_t fOrdinal;
204 std::vector<ObjectFile::Reference*> fReferences;
205
206 static Segment fgImportSegment;
207 };
208
209 template <typename A>
210 Segment ImportAtom<A>::fgImportSegment("__LINKEDIT");
211
212
213
214
215 //
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.
219 //
220 template <typename A>
221 class Reader : public ObjectFile::Reader
222 {
223 public:
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);
228 virtual ~Reader() {}
229
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; }
250
251 virtual void setImplicitlyLinked() { fImplicitlyLinked = true; }
252
253 protected:
254
255 struct ReExportChain { ReExportChain* prev; Reader<A>* reader; };
256
257 void assertNoReExportCycles(ReExportChain*);
258
259 private:
260 typedef typename A::P P;
261 typedef typename A::P::E E;
262
263 class CStringEquals
264 {
265 public:
266 bool operator()(const char* left, const char* right) const { return (strcmp(left, right) == 0); }
267 };
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;
272
273 struct PathAndFlag { const char* path; bool reExport; };
274
275 bool isPublicLocation(const char* path);
276 void addSymbol(const char* name, bool weak, uint32_t ordinal);
277
278 const char* fPath;
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;
289 bool fNoRexports;
290 bool fHasWeakExports;
291 const bool fLinkingFlat;
292 const bool fLinkingMainExecutable;
293 bool fExplictReExportFound;
294 bool fExplicitlyLinked;
295 bool fImplicitlyLinked;
296 bool fProvidedAtom;
297 bool fImplicitlyLinkPublicDylibs;
298 bool fLazyLoaded;
299 ObjectFile::Reader::ObjcConstraint fObjcContraint;
300 std::vector<ObjectFile::Reader*> fReExportedChildren;
301 const ObjectFile::ReaderOptions::VersionMin fDeploymentVersionMin;
302 std::vector<class ObjectFile::Atom*> fFlatImports;
303
304 static bool fgLogHashtable;
305 static std::vector<class ObjectFile::Atom*> fgEmptyAtomList;
306 };
307
308 template <typename A>
309 std::vector<class ObjectFile::Atom*> Reader<A>::fgEmptyAtomList;
310 template <typename A>
311 bool Reader<A>::fgLogHashtable = false;
312
313
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)
325 {
326 // sanity check
327 if ( ! validFile(fileContent, dylibOptions.fBundleLoader) )
328 throw "not a valid mach-o object file";
329
330 fPath = strdup(path);
331
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());
336
337 // write out path for -whatsloaded option
338 if ( options.fLogAllFiles )
339 printf("%s\n", path);
340
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);
343
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);
346
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);
351 return;
352 }
353
354
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;
359
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
368 case LC_LOAD_DYLIB:
369 case LC_LOAD_WEAK_DYLIB:
370 PathAndFlag entry;
371 entry.path = strdup(((struct macho_dylib_command<P>*)cmd)->name());
372 entry.reExport = (cmd->cmd() == LC_REEXPORT_DYLIB);
373 fDependentLibraryPaths.push_back(entry);
374 break;
375 }
376 cmd = (const macho_load_command<P>*)(((char*)cmd)+cmd->cmdsize());
377 if ( cmd > cmdsEnd )
378 throwf("malformed dylb, load command #%d is outside size of load commands in %s", i, path);
379 }
380 }
381
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;
386 cmd = cmds;
387 for (uint32_t i = 0; i < cmd_count; ++i) {
388 switch (cmd->cmd()) {
389 case LC_SYMTAB:
390 {
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();
394 }
395 break;
396 case LC_DYSYMTAB:
397 dynamicInfo = (macho_dysymtab_command<P>*)cmd;
398 break;
399 case LC_ID_DYLIB:
400 {
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();
406 }
407 break;
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) )
415 it->reExport = true;
416 }
417 }
418 break;
419 case LC_SUB_LIBRARY:
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 )
433 it->reExport = true;
434 }
435 }
436 break;
437 case LC_SUB_FRAMEWORK:
438 fParentUmbrella = strdup(((macho_sub_framework_command<P>*)cmd)->umbrella());
439 break;
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 = &sectionsStart[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
450 // uint32_t flags;
451 // };
452 // #define OBJC_IMAGE_SUPPORTS_GC 2
453 // #define OBJC_IMAGE_GC_ONLY 4
454 //
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;
462 else
463 fObjcContraint = ObjectFile::Reader::kObjcRetainRelease;
464 }
465 else if ( sect->size() > 0 ) {
466 warning("can't parse __OBJC/__image_info section in %s", fPath);
467 }
468 }
469 }
470 }
471 }
472
473 cmd = (const macho_load_command<P>*)(((char*)cmd)+cmd->cmdsize());
474 if ( cmd > cmdsEnd )
475 throwf("malformed dylb, load command #%d is outside size of load commands in %s", i, path);
476 }
477
478 // Process the rest of the commands here.
479 cmd = cmds;
480 for (uint32_t i = 0; i < cmd_count; ++i) {
481 switch (cmd->cmd()) {
482 case LC_SUB_CLIENT:
483 const char *temp = strdup(((macho_sub_client_command<P>*)cmd)->client());
484 fAllowableClients.push_back(temp);
485 break;
486 }
487 cmd = (const macho_load_command<P>*)(((char*)cmd)+cmd->cmdsize());
488 }
489
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";
497
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()]);
506 }
507 fFlatImports.push_back(new ImportAtom<A>(*this, ordinalBase++, importNames));
508 }
509
510 // build hash table
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);
519 }
520 fReExportedOrdinal = index;
521 }
522 else {
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);
531 }
532 fReExportedOrdinal = ordinalBase + count;
533 }
534
535
536 // unmap file
537 munmap((caddr_t)fileContent, fileLength);
538 }
539
540
541
542 template <typename A>
543 void Reader<A>::addSymbol(const char* name, bool weak, uint32_t ordinal)
544 {
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' ) {
555 case 0:
556 case 1:
557 symVersionCondition = ObjectFile::ReaderOptions::k10_1;
558 break;
559 case 2:
560 symVersionCondition = ObjectFile::ReaderOptions::k10_2;
561 break;
562 case 3:
563 symVersionCondition = ObjectFile::ReaderOptions::k10_3;
564 break;
565 case 4:
566 symVersionCondition = ObjectFile::ReaderOptions::k10_4;
567 break;
568 case 5:
569 symVersionCondition = ObjectFile::ReaderOptions::k10_5;
570 break;
571 case 6:
572 symVersionCondition = ObjectFile::ReaderOptions::k10_6;
573 break;
574 }
575 const char* symName = strchr(&symCond[1], '$');
576 if ( symName != NULL ) {
577 ++symName;
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));
582 return;
583 }
584 else if ( strncmp(symAction, "add$", 4) == 0 ) {
585 this->addSymbol(symName, weak, ordinal);
586 return;
587 }
588 else {
589 warning("bad symbol action: %s in dylib %s", name, this->getPath());
590 }
591 }
592 }
593 else {
594 warning("bad symbol name: %s in dylib %s", name, this->getPath());
595 }
596 }
597 else {
598 warning("bad symbol version: %s in dylib %s", name, this->getPath());
599 }
600 }
601 else {
602 warning("bad symbol condition: %s in dylib %s", name, this->getPath());
603 }
604 }
605
606 // add symbol as possible export if we are not supposed to ignore it
607 if ( fIgnoreExports.count(name) == 0 ) {
608 AtomAndWeak bucket;
609 bucket.atom = NULL;
610 bucket.weak = weak;
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;
614 }
615 }
616
617
618 template <typename A>
619 std::vector<class ObjectFile::Atom*>& Reader<A>::getAtoms()
620 {
621 return fFlatImports;
622 }
623
624
625 template <typename A>
626 std::vector<class ObjectFile::Atom*>* Reader<A>::getJustInTimeAtomsFor(const char* name)
627 {
628 std::vector<class ObjectFile::Atom*>* atoms = NULL;
629
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());
637 }
638 // return a vector of one atom
639 atoms = new std::vector<class ObjectFile::Atom*>;
640 atoms->push_back(pos->second.atom);
641 }
642 else {
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);
658 delete childAtoms;
659 return atoms;
660 }
661 }
662 }
663 }
664 return atoms;
665 }
666
667
668
669 template <typename A>
670 bool Reader<A>::isPublicLocation(const char* path)
671 {
672 // -no_implicit_dylibs disables this optimization
673 if ( ! fImplicitlyLinkPublicDylibs )
674 return false;
675
676 // /usr/lib is a public location
677 if ( (strncmp(path, "/usr/lib/", 9) == 0) && (strchr(&path[9], '/') == NULL) )
678 return true;
679
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 )
691 return true;
692 }
693 }
694
695 return false;
696 }
697
698 template <typename A>
699 void Reader<A>::processIndirectLibraries(DylibHander* handler)
700 {
701 if ( fLinkingFlat ) {
702 for (typename std::vector<PathAndFlag>::iterator it = fDependentLibraryPaths.begin(); it != fDependentLibraryPaths.end(); it++) {
703 handler->findDylib(it->path, this->getPath());
704 }
705 }
706 else if ( fNoRexports ) {
707 // MH_NO_REEXPORTED_DYLIBS bit set, then nothing to do
708 }
709 else {
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();
721 }
722 else
723 fReExportedChildren.push_back(child);
724 }
725 else {
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);
729 }
730 }
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);
742 }
743 }
744 }
745 }
746 }
747
748 // check for re-export cycles
749 ReExportChain chain;
750 chain.prev = NULL;
751 chain.reader = this;
752 this->assertNoReExportCycles(&chain);
753 }
754
755 template <typename A>
756 void Reader<A>::assertNoReExportCycles(ReExportChain* prev)
757 {
758 // recursively check my re-exported dylibs
759 ReExportChain chain;
760 chain.prev = prev;
761 chain.reader = this;
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());
768 }
769 }
770 ((Reader<A>*)(*it))->assertNoReExportCycles(&chain);
771 }
772 }
773
774
775 template <typename A>
776 std::vector<const char*>* Reader<A>::getAllowableClients()
777 {
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();
781 it++) {
782 result->push_back(*it);
783 }
784 return (fAllowableClients.size() != 0 ? result : NULL);
785 }
786
787 template <>
788 bool Reader<ppc>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle)
789 {
790 const macho_header<P>* header = (const macho_header<P>*)fileContent;
791 if ( header->magic() != MH_MAGIC )
792 return false;
793 if ( header->cputype() != CPU_TYPE_POWERPC )
794 return false;
795 switch ( header->filetype() ) {
796 case MH_DYLIB:
797 case MH_DYLIB_STUB:
798 return true;
799 case MH_BUNDLE:
800 if ( executableOrDyliborBundle )
801 return true;
802 else
803 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
804 case MH_EXECUTE:
805 if ( executableOrDyliborBundle )
806 return true;
807 else
808 throw "can't link with a main executable";
809 default:
810 return false;
811 }
812 }
813
814 template <>
815 bool Reader<ppc64>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle)
816 {
817 const macho_header<P>* header = (const macho_header<P>*)fileContent;
818 if ( header->magic() != MH_MAGIC_64 )
819 return false;
820 if ( header->cputype() != CPU_TYPE_POWERPC64 )
821 return false;
822 switch ( header->filetype() ) {
823 case MH_DYLIB:
824 case MH_DYLIB_STUB:
825 return true;
826 case MH_BUNDLE:
827 if ( executableOrDyliborBundle )
828 return true;
829 else
830 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
831 case MH_EXECUTE:
832 if ( executableOrDyliborBundle )
833 return true;
834 else
835 throw "can't link with a main executable";
836 default:
837 return false;
838 }
839 }
840
841 template <>
842 bool Reader<x86>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle)
843 {
844 const macho_header<P>* header = (const macho_header<P>*)fileContent;
845 if ( header->magic() != MH_MAGIC )
846 return false;
847 if ( header->cputype() != CPU_TYPE_I386 )
848 return false;
849 switch ( header->filetype() ) {
850 case MH_DYLIB:
851 case MH_DYLIB_STUB:
852 return true;
853 case MH_BUNDLE:
854 if ( executableOrDyliborBundle )
855 return true;
856 else
857 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
858 case MH_EXECUTE:
859 if ( executableOrDyliborBundle )
860 return true;
861 else
862 throw "can't link with a main executable";
863 default:
864 return false;
865 }
866 }
867
868 template <>
869 bool Reader<x86_64>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle)
870 {
871 const macho_header<P>* header = (const macho_header<P>*)fileContent;
872 if ( header->magic() != MH_MAGIC_64 )
873 return false;
874 if ( header->cputype() != CPU_TYPE_X86_64 )
875 return false;
876 switch ( header->filetype() ) {
877 case MH_DYLIB:
878 case MH_DYLIB_STUB:
879 return true;
880 case MH_BUNDLE:
881 if ( executableOrDyliborBundle )
882 return true;
883 else
884 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
885 case MH_EXECUTE:
886 if ( executableOrDyliborBundle )
887 return true;
888 else
889 throw "can't link with a main executable";
890 default:
891 return false;
892 }
893 }
894
895 template <>
896 bool Reader<arm>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle)
897 {
898 const macho_header<P>* header = (const macho_header<P>*)fileContent;
899 if ( header->magic() != MH_MAGIC )
900 return false;
901 if ( header->cputype() != CPU_TYPE_ARM )
902 return false;
903 switch ( header->filetype() ) {
904 case MH_DYLIB:
905 case MH_DYLIB_STUB:
906 return true;
907 case MH_BUNDLE:
908 if ( executableOrDyliborBundle )
909 return true;
910 else
911 throw "can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)";
912 case MH_EXECUTE:
913 if ( executableOrDyliborBundle )
914 return true;
915 else
916 throw "can't link with a main executable";
917 default:
918 return false;
919 }
920 }
921
922 }; // namespace dylib
923 }; // namespace mach_o
924
925
926 #endif // __OBJECT_FILE_DYLIB_MACH_O__