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