]> git.saurik.com Git - apple/ld64.git/blame - src/MachOReaderDylib.hpp
ld64-85.2.2.tar.gz
[apple/ld64.git] / src / 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"
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
52namespace mach_o {
53namespace dylib {
54
55
56// forward reference
57template <typename A> class Reader;
58
59
60class Segment : public ObjectFile::Segment
61{
62public:
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; }
68private:
69 const char* fName;
70};
71
72
73//
74// An ExportAtom has no content. It exists so that the linker can track which imported
a61fdf0a 75// symbols came from which dynamic libraries.
d696c285
A
76//
77template <typename A>
78class ExportAtom : public ObjectFile::Atom
79{
80public:
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; }
69a49097 88 virtual bool dontDeadStrip() const { return false; }
d696c285 89 virtual bool isZeroFill() const { return false; }
2f2f92e4 90 virtual bool isThumb() const { return false; }
d696c285
A
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; }
d696c285 96 virtual ObjectFile::Atom& getFollowOnAtom() const { return *((ObjectFile::Atom*)NULL); }
a61fdf0a 97 virtual uint32_t getOrdinal() const { return fOrdinal; }
d696c285 98 virtual std::vector<ObjectFile::LineInfo>* getLineInfo() const { return NULL; }
74cfe461 99 virtual ObjectFile::Alignment getAlignment() const { return ObjectFile::Alignment(0); }
d696c285
A
100 virtual void copyRawContent(uint8_t buffer[]) const {}
101
102 virtual void setScope(Scope) { }
103
104protected:
105 friend class Reader<A>;
106 typedef typename A::P P;
107
a61fdf0a
A
108 ExportAtom(ObjectFile::Reader& owner, const char* name, bool weak, uint32_t ordinal)
109 : fOwner(owner), fName(name), fOrdinal(ordinal), fWeakDefinition(weak) {}
d696c285
A
110 virtual ~ExportAtom() {}
111
112 ObjectFile::Reader& fOwner;
113 const char* fName;
a61fdf0a 114 uint32_t fOrdinal;
d696c285
A
115 bool fWeakDefinition;
116
117 static std::vector<ObjectFile::Reference*> fgEmptyReferenceList;
118 static Segment fgImportSegment;
119};
120
121template <typename A>
122Segment ExportAtom<A>::fgImportSegment("__LINKEDIT");
123
124template <typename A>
125std::vector<ObjectFile::Reference*> ExportAtom<A>::fgEmptyReferenceList;
126
127
a61fdf0a
A
128
129class ImportReference : public ObjectFile::Reference
130{
131public:
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
151private:
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//
161template <typename A>
162class ImportAtom : public ObjectFile::Atom
163{
164public:
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; }
2f2f92e4 174 virtual bool isThumb() const { return false; }
a61fdf0a
A
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
188protected:
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
209template <typename A>
210Segment ImportAtom<A>::fgImportSegment("__LINKEDIT");
211
212
213
214
d696c285
A
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//
220template <typename A>
221class Reader : public ObjectFile::Reader
222{
223public:
69a49097 224 static bool validFile(const uint8_t* fileContent, bool executableOrDylib);
a61fdf0a 225 Reader(const uint8_t* fileContent, uint64_t fileLength, const char* path,
2f2f92e4 226 const DynamicLibraryOptions& dylibOptions, const ObjectFile::ReaderOptions& options,
a61fdf0a 227 uint32_t ordinalBase);
69a49097 228 virtual ~Reader() {}
d696c285
A
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; }
a61fdf0a 236 virtual ObjectFile::Reader::ObjcConstraint getObjCConstraint() { return fObjcContraint; }
d696c285
A
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; }
a61fdf0a
A
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; }
d696c285 247 virtual std::vector<const char*>* getAllowableClients();
2f2f92e4
A
248 virtual bool hasWeakExternals() { return fHasWeakExports; }
249 virtual bool isLazyLoadedDylib() { return fLazyLoaded; }
d696c285 250
a61fdf0a
A
251 virtual void setImplicitlyLinked() { fImplicitlyLinked = true; }
252
d696c285 253protected:
a61fdf0a
A
254
255 struct ReExportChain { ReExportChain* prev; Reader<A>* reader; };
256
2f2f92e4 257 void assertNoReExportCycles(ReExportChain*);
d696c285
A
258
259private:
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 };
a61fdf0a 268 struct AtomAndWeak { ObjectFile::Atom* atom; bool weak; uint32_t ordinal; };
d696c285 269 typedef __gnu_cxx::hash_map<const char*, AtomAndWeak, __gnu_cxx::hash<const char*>, CStringEquals> NameToAtomMap;
a61fdf0a 270 typedef __gnu_cxx::hash_set<const char*, __gnu_cxx::hash<const char*>, CStringEquals> NameSet;
d696c285
A
271 typedef typename NameToAtomMap::iterator NameToAtomMapIterator;
272
273 struct PathAndFlag { const char* path; bool reExport; };
274
a61fdf0a
A
275 bool isPublicLocation(const char* path);
276 void addSymbol(const char* name, bool weak, uint32_t ordinal);
d696c285
A
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;
a61fdf0a 285 uint32_t fReExportedOrdinal;
d696c285
A
286 std::vector<PathAndFlag> fDependentLibraryPaths;
287 NameToAtomMap fAtoms;
a61fdf0a
A
288 NameSet fIgnoreExports;
289 bool fNoRexports;
2f2f92e4 290 bool fHasWeakExports;
a61fdf0a
A
291 const bool fLinkingFlat;
292 const bool fLinkingMainExecutable;
293 bool fExplictReExportFound;
294 bool fExplicitlyLinked;
295 bool fImplicitlyLinked;
296 bool fProvidedAtom;
2f2f92e4
A
297 bool fImplicitlyLinkPublicDylibs;
298 bool fLazyLoaded;
a61fdf0a
A
299 ObjectFile::Reader::ObjcConstraint fObjcContraint;
300 std::vector<ObjectFile::Reader*> fReExportedChildren;
301 const ObjectFile::ReaderOptions::VersionMin fDeploymentVersionMin;
302 std::vector<class ObjectFile::Atom*> fFlatImports;
d696c285
A
303
304 static bool fgLogHashtable;
305 static std::vector<class ObjectFile::Atom*> fgEmptyAtomList;
306};
307
308template <typename A>
309std::vector<class ObjectFile::Atom*> Reader<A>::fgEmptyAtomList;
310template <typename A>
311bool Reader<A>::fgLogHashtable = false;
312
313
314template <typename A>
2f2f92e4
A
315Reader<A>::Reader(const uint8_t* fileContent, uint64_t fileLength, const char* path,
316 const DynamicLibraryOptions& dylibOptions,
a61fdf0a
A
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),
2f2f92e4
A
321 fExplicitlyLinked(false), fImplicitlyLinked(false), fProvidedAtom(false),
322 fImplicitlyLinkPublicDylibs(options.fImplicitlyLinkPublicDylibs), fLazyLoaded(dylibOptions.fLazyLoad),
323 fObjcContraint(ObjectFile::Reader::kObjcNone),
a61fdf0a 324 fDeploymentVersionMin(options.fVersionMin)
d696c285
A
325{
326 // sanity check
2f2f92e4 327 if ( ! validFile(fileContent, dylibOptions.fBundleLoader) )
d696c285
A
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>));
2f2f92e4 335 const macho_load_command<P>* const cmdsEnd = (macho_load_command<P>*)((char*)header + sizeof(macho_header<P>) + header->sizeofcmds());
d696c285 336
a61fdf0a
A
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) )
2f2f92e4 342 warning("using -root_safe but linking against %s which is not root safe", path);
a61fdf0a
A
343
344 if ( options.fSetuidSafe && ((header->flags() & MH_SETUID_SAFE) == 0) )
2f2f92e4 345 warning("using -setuid_safe but linking against %s which is not setuid safe", path);
a61fdf0a 346
d696c285
A
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
a61fdf0a
A
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);
2f2f92e4 357 fHasWeakExports = (header->flags() & MH_WEAK_DEFINES);
a61fdf0a
A
358 bool trackDependentLibraries = !fNoRexports || options.fFlatNamespace;
359
d696c285
A
360 // pass 1 builds list of all dependent libraries
361 const macho_load_command<P>* cmd = cmds;
a61fdf0a
A
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());
2f2f92e4
A
377 if ( cmd > cmdsEnd )
378 throwf("malformed dylb, load command #%d is outside size of load commands in %s", i, path);
d696c285 379 }
d696c285 380 }
a61fdf0a 381
d696c285
A
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:
a61fdf0a 400 {
d696c285
A
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();
a61fdf0a 406 }
d696c285
A
407 break;
408 case LC_SUB_UMBRELLA:
a61fdf0a 409 if ( trackDependentLibraries ) {
d696c285
A
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:
a61fdf0a 420 if ( trackDependentLibraries) {
d696c285
A
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;
a61fdf0a
A
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 ) {
2f2f92e4 466 warning("can't parse __OBJC/__image_info section in %s", fPath);
a61fdf0a
A
467 }
468 }
469 }
470 }
d696c285
A
471 }
472
473 cmd = (const macho_load_command<P>*)(((char*)cmd)+cmd->cmdsize());
2f2f92e4
A
474 if ( cmd > cmdsEnd )
475 throwf("malformed dylb, load command #%d is outside size of load commands in %s", i, path);
d696c285 476 }
a61fdf0a 477
d696c285
A
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());
d696c285
A
484 fAllowableClients.push_back(temp);
485 break;
486 }
d696c285
A
487 cmd = (const macho_load_command<P>*)(((char*)cmd)+cmd->cmdsize());
488 }
489
490 // validate minimal load commands
2f2f92e4
A
491 if ( (fDylibInstallPath == NULL) && ((header->filetype() == MH_DYLIB) || (header->filetype() == MH_DYLIB_STUB)) )
492 throwf("dylib %s missing LC_ID_DYLIB load command", path);
d696c285 493 if ( symbolTable == NULL )
2f2f92e4 494 throw "binary missing LC_SYMTAB load command";
d696c285 495 if ( dynamicInfo == NULL )
2f2f92e4 496 throw "binary missing LC_DYSYMTAB load command";
d696c285 497
a61fdf0a
A
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
d696c285
A
510 // build hash table
511 if ( dynamicInfo->tocoff() == 0 ) {
a61fdf0a 512 if ( fgLogHashtable ) fprintf(stderr, "ld: building hashtable of %u toc entries for %s\n", dynamicInfo->nextdefsym(), path);
d696c285
A
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
a61fdf0a
A
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);
d696c285 519 }
a61fdf0a 520 fReExportedOrdinal = index;
d696c285
A
521 }
522 else {
523 int32_t count = dynamicInfo->ntoc();
524 fAtoms.resize(count); // set initial bucket count
a61fdf0a 525 if ( fgLogHashtable ) fprintf(stderr, "ld: building hashtable of %u entries for %s\n", count, path);
d696c285
A
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];
a61fdf0a 530 this->addSymbol(&strings[sym->n_strx()], (sym->n_desc() & N_WEAK_DEF) != 0, ordinalBase+i);
d696c285 531 }
a61fdf0a 532 fReExportedOrdinal = ordinalBase + count;
d696c285
A
533 }
534
a61fdf0a 535
d696c285
A
536 // unmap file
537 munmap((caddr_t)fileContent, fileLength);
538}
539
a61fdf0a
A
540
541
542template <typename A>
543void 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;
2f2f92e4
A
571 case 6:
572 symVersionCondition = ObjectFile::ReaderOptions::k10_6;
573 break;
a61fdf0a
A
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 {
2f2f92e4 589 warning("bad symbol action: %s in dylib %s", name, this->getPath());
a61fdf0a
A
590 }
591 }
592 }
593 else {
2f2f92e4 594 warning("bad symbol name: %s in dylib %s", name, this->getPath());
a61fdf0a
A
595 }
596 }
597 else {
2f2f92e4 598 warning("bad symbol version: %s in dylib %s", name, this->getPath());
a61fdf0a
A
599 }
600 }
601 else {
2f2f92e4 602 warning("bad symbol condition: %s in dylib %s", name, this->getPath());
a61fdf0a
A
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
d696c285
A
618template <typename A>
619std::vector<class ObjectFile::Atom*>& Reader<A>::getAtoms()
620{
a61fdf0a 621 return fFlatImports;
d696c285
A
622}
623
624
625template <typename A>
626std::vector<class ObjectFile::Atom*>* Reader<A>::getJustInTimeAtomsFor(const char* name)
627{
628 std::vector<class ObjectFile::Atom*>* atoms = NULL;
a61fdf0a 629
d696c285
A
630 NameToAtomMapIterator pos = fAtoms.find(name);
631 if ( pos != fAtoms.end() ) {
632 if ( pos->second.atom == NULL ) {
633 // instantiate atom and update hash table
a61fdf0a
A
634 pos->second.atom = new ExportAtom<A>(*this, name, pos->second.weak, pos->second.ordinal);
635 fProvidedAtom = true;
d696c285
A
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());
a61fdf0a
A
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 }
d696c285
A
663 }
664 return atoms;
665}
666
667
668
669template <typename A>
a61fdf0a 670bool Reader<A>::isPublicLocation(const char* path)
d696c285 671{
2f2f92e4
A
672 // -no_implicit_dylibs disables this optimization
673 if ( ! fImplicitlyLinkPublicDylibs )
674 return false;
675
a61fdf0a
A
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 }
d696c285 693 }
a61fdf0a
A
694
695 return false;
d696c285
A
696}
697
698template <typename A>
a61fdf0a 699void Reader<A>::processIndirectLibraries(DylibHander* handler)
d696c285 700{
a61fdf0a
A
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 }
d696c285 705 }
a61fdf0a
A
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
a61fdf0a
A
749 ReExportChain chain;
750 chain.prev = NULL;
751 chain.reader = this;
2f2f92e4 752 this->assertNoReExportCycles(&chain);
d696c285
A
753}
754
755template <typename A>
2f2f92e4 756void Reader<A>::assertNoReExportCycles(ReExportChain* prev)
d696c285 757{
2f2f92e4 758 // recursively check my re-exported dylibs
a61fdf0a
A
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++) {
2f2f92e4
A
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);
d696c285 771 }
a61fdf0a 772}
d696c285 773
a61fdf0a
A
774
775template <typename A>
776std::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);
d696c285
A
785}
786
787template <>
2f2f92e4 788bool Reader<ppc>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle)
d696c285
A
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;
69a49097
A
795 switch ( header->filetype() ) {
796 case MH_DYLIB:
797 case MH_DYLIB_STUB:
798 return true;
2f2f92e4
A
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)";
69a49097 804 case MH_EXECUTE:
2f2f92e4
A
805 if ( executableOrDyliborBundle )
806 return true;
807 else
808 throw "can't link with a main executable";
69a49097
A
809 default:
810 return false;
811 }
d696c285
A
812}
813
814template <>
2f2f92e4 815bool Reader<ppc64>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle)
d696c285
A
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;
69a49097
A
822 switch ( header->filetype() ) {
823 case MH_DYLIB:
824 case MH_DYLIB_STUB:
825 return true;
2f2f92e4
A
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)";
69a49097 831 case MH_EXECUTE:
2f2f92e4
A
832 if ( executableOrDyliborBundle )
833 return true;
834 else
835 throw "can't link with a main executable";
69a49097
A
836 default:
837 return false;
838 }
d696c285
A
839}
840
841template <>
2f2f92e4 842bool Reader<x86>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle)
d696c285
A
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;
69a49097
A
849 switch ( header->filetype() ) {
850 case MH_DYLIB:
851 case MH_DYLIB_STUB:
852 return true;
2f2f92e4
A
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)";
69a49097 858 case MH_EXECUTE:
2f2f92e4
A
859 if ( executableOrDyliborBundle )
860 return true;
861 else
862 throw "can't link with a main executable";
69a49097
A
863 default:
864 return false;
865 }
d696c285
A
866}
867
69a49097 868template <>
2f2f92e4 869bool Reader<x86_64>::validFile(const uint8_t* fileContent, bool executableOrDyliborBundle)
69a49097
A
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;
2f2f92e4
A
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)";
69a49097 885 case MH_EXECUTE:
2f2f92e4
A
886 if ( executableOrDyliborBundle )
887 return true;
888 else
889 throw "can't link with a main executable";
69a49097
A
890 default:
891 return false;
892 }
893}
d696c285 894
2f2f92e4
A
895template <>
896bool 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}
86b84c30 921
d696c285
A
922}; // namespace dylib
923}; // namespace mach_o
924
925
926#endif // __OBJECT_FILE_DYLIB_MACH_O__