1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
3 * Copyright (c) 2005-2006 Apple Computer, Inc. All rights reserved.
5 * @APPLE_LICENSE_HEADER_START@
7 * This file contains Original Code and/or Modifications of Original Code
8 * as defined in and that are subject to the Apple Public Source License
9 * Version 2.0 (the 'License'). You may not use this file except in
10 * compliance with the License. Please obtain a copy of the License at
11 * http://www.opensource.apple.com/apsl/ and read it before using this
14 * The Original Code and all software distributed under the License are
15 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
19 * Please see the License for the specific language governing rights and
20 * limitations under the License.
22 * @APPLE_LICENSE_HEADER_END@
25 #ifndef __OBJECT_FILE_MACH_O__
26 #define __OBJECT_FILE_MACH_O__
31 #include <sys/param.h>
32 #include <mach-o/ppc/reloc.h>
33 #include <mach-o/stab.h>
34 #include <mach-o/x86_64/reloc.h>
36 #define S_ATTR_DEBUG 0x02000000
43 #include "MachOFileAbstraction.hpp"
44 #include "Architectures.hpp"
45 #include "ObjectFile.h"
47 #include "debugline.h"
52 // To implement architecture xxx, you must write template specializations for the following six methods:
53 // Reader<xxx>::validFile()
54 // Reader<xxx>::validSectionType()
55 // Reader<xxx>::addRelocReference()
56 // Reference<xxx>::getDescription()
62 extern __attribute__((noreturn)) void throwf(const char* format, ...);
65 namespace relocatable {
70 template <typename A> class Reader;
71 template <typename A> class SymbolAtomSorter;
75 AtomAndOffset(ObjectFile::Atom* a=NULL) : atom(a), offset(0) {}
76 AtomAndOffset(ObjectFile::Atom* a, uint32_t off) : atom(a), offset(off) {}
77 ObjectFile::Atom* atom;
83 class Reference : public ObjectFile::Reference
86 typedef typename A::P P;
87 typedef typename A::P::uint_t pint_t;
88 typedef typename A::ReferenceKinds Kinds;
90 Reference(Kinds kind, const AtomAndOffset& at, const AtomAndOffset& toTarget);
91 Reference(Kinds kind, const AtomAndOffset& at, const AtomAndOffset& fromTarget, const AtomAndOffset& toTarget);
92 Reference(Kinds kind, const AtomAndOffset& at, const char* toName, uint32_t toOffset);
94 virtual ~Reference() {}
97 virtual bool isTargetUnbound() const { return ( fToTarget.atom == NULL ); }
98 virtual bool isFromTargetUnbound() const { return ( fFromTarget.atom == NULL ); }
99 virtual uint8_t getKind() const { return (uint8_t)fKind; }
100 virtual uint64_t getFixUpOffset() const { return fFixUpOffsetInSrc; }
101 virtual const char* getTargetName() const { return (fToTargetName != NULL) ? fToTargetName : fToTarget.atom->getName(); }
102 virtual ObjectFile::Atom& getTarget() const { return *fToTarget.atom; }
103 virtual uint64_t getTargetOffset() const { return (int64_t)((int32_t)fToTarget.offset); }
104 virtual bool hasFromTarget() const { return ( (fFromTarget.atom != NULL) || (fFromTargetName != NULL) ); }
105 virtual ObjectFile::Atom& getFromTarget() const { return *fFromTarget.atom; }
106 virtual const char* getFromTargetName() const { return (fFromTargetName != NULL) ? fFromTargetName : fFromTarget.atom->getName(); }
107 virtual void setTarget(ObjectFile::Atom& target, uint64_t offset) { fToTarget.atom = ⌖ fToTarget.offset = offset; }
108 virtual void setToTargetOffset(uint64_t offset) { fToTarget.offset = offset; }
109 virtual void setFromTarget(ObjectFile::Atom& target) { fFromTarget.atom = ⌖ }
110 virtual void setFromTargetName(const char* name) { fFromTargetName = name; }
111 virtual void setFromTargetOffset(uint64_t offset) { fFromTarget.offset = offset; }
112 virtual const char* getDescription() const;
113 virtual uint64_t getFromTargetOffset() const { return fFromTarget.offset; }
117 pint_t fFixUpOffsetInSrc;
118 AtomAndOffset fToTarget;
119 AtomAndOffset fFromTarget;
120 const char* fToTargetName;
121 const char* fFromTargetName;
126 template <typename A>
127 Reference<A>::Reference(Kinds kind, const AtomAndOffset& at, const AtomAndOffset& toTarget)
128 : fFixUpOffsetInSrc(at.offset), fToTarget(toTarget), fToTargetName(NULL), fFromTargetName(NULL),
131 // make reference a by-name unless:
132 // - the reference type is only used with direct references
133 // - the target is translation unit scoped
134 if ( (kind != A::kNoFixUp) && (kind != A::kFollowOn)
135 && (toTarget.atom->getScope() != ObjectFile::Atom::scopeTranslationUnit) ) {
136 //fprintf(stderr, "Reference(): changing to by-name %p %s, target scope=%d\n", toTarget.atom, fToTargetName, toTarget.atom->getScope());
137 fToTargetName = toTarget.atom->getName();
138 fToTarget.atom = NULL;
140 ((class BaseAtom*)at.atom)->addReference(this);
141 //fprintf(stderr, "Reference(): %p fToTarget<%s, %08X>\n", this, (fToTarget.atom != NULL) ? fToTarget.atom->getDisplayName() : fToTargetName , fToTarget.offset);
144 template <typename A>
145 Reference<A>::Reference(Kinds kind, const AtomAndOffset& at, const AtomAndOffset& fromTarget, const AtomAndOffset& toTarget)
146 : fFixUpOffsetInSrc(at.offset), fToTarget(toTarget), fFromTarget(fromTarget),
147 fToTargetName(NULL), fFromTargetName(NULL), fKind(kind)
149 // make reference a by-name where needed
150 if ( (kind != A::kNoFixUp) && (kind != A::kFollowOn)
151 && (toTarget.atom->getScope() != ObjectFile::Atom::scopeTranslationUnit)
152 && (toTarget.atom != at.atom) ) {
153 fToTargetName = toTarget.atom->getName();
154 fToTarget.atom = NULL;
156 ((class BaseAtom*)at.atom)->addReference(this);
157 //fprintf(stderr, "Reference(): %p kind=%d, fToTarget<%s, %08X>, fromTarget<%s, %08X>\n", this, kind,
158 // this->getTargetName(), fToTarget.offset, this->getFromTargetName(), fromTarget.offset);
161 template <typename A>
162 Reference<A>::Reference(Kinds kind, const AtomAndOffset& at, const char* toName, uint32_t toOffset)
163 : fFixUpOffsetInSrc(at.offset),
164 fToTargetName(toName), fFromTargetName(NULL), fKind(kind)
166 fToTarget.offset = toOffset;
167 ((class BaseAtom*)at.atom)->addReference(this);
171 template <typename A>
172 class Segment : public ObjectFile::Segment
175 Segment(const macho_section<typename A::P>* sect);
176 virtual const char* getName() const { return fSection->segname(); }
177 virtual bool isContentReadable() const { return true; }
178 virtual bool isContentWritable() const { return fWritable; }
179 virtual bool isContentExecutable() const { return fExecutable; }
181 const macho_section<typename A::P>* fSection;
186 template <typename A>
187 Segment<A>::Segment(const macho_section<typename A::P>* sect)
188 : fSection(sect), fWritable(true), fExecutable(false)
190 if ( strcmp(fSection->segname(), "__TEXT") == 0 ) {
194 else if ( strcmp(fSection->segname(), "__IMPORT") == 0 ) {
201 class DataSegment : public ObjectFile::Segment
204 virtual const char* getName() const { return "__DATA"; }
205 virtual bool isContentReadable() const { return true; }
206 virtual bool isContentWritable() const { return true; }
207 virtual bool isContentExecutable() const { return false; }
209 static DataSegment fgSingleton;
212 DataSegment DataSegment::fgSingleton;
215 class BaseAtom : public ObjectFile::Atom
218 BaseAtom() : fStabsStartIndex(0), fStabsCount(0) {}
220 virtual void setSize(uint64_t size) = 0;
221 virtual void addReference(ObjectFile::Reference* ref) = 0;
222 virtual void addLineInfo(const ObjectFile::LineInfo& info) = 0;
223 virtual void alignAtLeast(uint8_t align) = 0;
225 uint32_t fStabsStartIndex;
226 uint32_t fStabsCount;
231 // A SymbolAtom represents a chunk of a mach-o object file that has a symbol table entry
232 // pointing to it. A C function or global variable is represented by one of these atoms.
235 template <typename A>
236 class SymbolAtom : public BaseAtom
239 virtual ObjectFile::Reader* getFile() const { return &fOwner; }
240 virtual bool getTranslationUnitSource(const char** dir, const char** name) const
241 { return fOwner.getTranslationUnitSource(dir, name); }
242 virtual const char* getName() const { return &fOwner.fStrings[fSymbol->n_strx()]; }
243 virtual const char* getDisplayName() const { return getName(); }
244 virtual ObjectFile::Atom::Scope getScope() const { return fScope; }
245 virtual ObjectFile::Atom::DefinitionKind getDefinitionKind() const { return ((fSymbol->n_desc() & N_WEAK_DEF) != 0)
246 ? ObjectFile::Atom::kWeakDefinition : ObjectFile::Atom::kRegularDefinition; }
247 virtual SymbolTableInclusion getSymbolTableInclusion() const { return fSymbolTableInclusion; }
248 virtual bool dontDeadStrip() const { return ((fSymbol->n_desc() & (N_NO_DEAD_STRIP|REFERENCED_DYNAMICALLY)) != 0); }
249 virtual bool isZeroFill() const { return ((fSection->flags() & SECTION_TYPE) == S_ZEROFILL); }
250 virtual uint64_t getSize() const { return fSize; }
251 virtual std::vector<ObjectFile::Reference*>& getReferences() const { return (std::vector<ObjectFile::Reference*>&)(fReferences); }
252 virtual bool mustRemainInSection() const { return true; }
253 virtual const char* getSectionName() const;
254 virtual Segment<A>& getSegment() const { return *fSegment; }
255 virtual bool requiresFollowOnAtom() const;
256 virtual ObjectFile::Atom& getFollowOnAtom() const;
257 virtual std::vector<ObjectFile::LineInfo>* getLineInfo() const { return (std::vector<ObjectFile::LineInfo>*)&fLineInfo; }
258 virtual uint8_t getAlignment() const { return fAlignment; }
259 virtual void copyRawContent(uint8_t buffer[]) const;
260 virtual void setScope(ObjectFile::Atom::Scope newScope) { fScope = newScope; }
261 virtual void setSize(uint64_t size);
262 virtual void addReference(ObjectFile::Reference* ref) { fReferences.insert(fReferences.begin(), (Reference<A>*)ref); }
263 virtual void addLineInfo(const ObjectFile::LineInfo& info) { fLineInfo.push_back(info); }
264 virtual void alignAtLeast(uint8_t align) { fAlignment = std::max(align, fAlignment); }
267 typedef typename A::P P;
268 typedef typename A::P::E E;
269 typedef typename A::P::uint_t pint_t;
270 typedef typename A::ReferenceKinds Kinds;
271 typedef typename std::vector<Reference<A>*> ReferenceVector;
272 typedef typename ReferenceVector::iterator ReferenceVectorIterator; // seems to help C++ parser
273 typedef typename ReferenceVector::const_iterator ReferenceVectorConstIterator; // seems to help C++ parser
274 friend class Reader<A>;
275 friend class SymbolAtomSorter<A>;
277 SymbolAtom(Reader<A>&, const macho_nlist<P>*, const macho_section<P>*);
278 virtual ~SymbolAtom() {}
281 const macho_nlist<P>* fSymbol;
284 const macho_section<P>* fSection;
285 Segment<A>* fSegment;
286 ReferenceVector fReferences;
287 std::vector<ObjectFile::LineInfo> fLineInfo;
288 ObjectFile::Atom::Scope fScope;
289 SymbolTableInclusion fSymbolTableInclusion;
294 template <typename A>
295 SymbolAtom<A>::SymbolAtom(Reader<A>& owner, const macho_nlist<P>* symbol, const macho_section<P>* section)
296 : fOwner(owner), fSymbol(symbol), fAddress(0), fSize(0), fSection(section), fSegment(NULL), fAlignment(0)
298 uint8_t type = symbol->n_type();
299 if ( (type & N_EXT) == 0 )
300 fScope = ObjectFile::Atom::scopeTranslationUnit;
301 else if ( (type & N_PEXT) != 0 )
302 fScope = ObjectFile::Atom::scopeLinkageUnit;
304 fScope = ObjectFile::Atom::scopeGlobal;
305 if ( (type & N_TYPE) == N_SECT ) {
307 fSegment = new Segment<A>(fSection);
308 fAddress = fSymbol->n_value();
311 printf("unknown symbol type: %d\n", type);
313 //fprintf(stderr, "SymbolAtom(%p) %s fAddress=0x%X\n", this, this->getDisplayName(), (uint32_t)fAddress);
314 // support for .o files built with old ld64
315 if ( (fSymbol->n_desc() & N_WEAK_DEF) && (strcmp(fSection->sectname(),"__picsymbolstub1__TEXT") == 0) ) {
316 const char* name = this->getName();
317 const int nameLen = strlen(name);
318 if ( (nameLen > 6) && strcmp(&name[nameLen-5], "$stub") == 0 ) {
319 // switch symbol to point at name that does not have trailing $stub
320 char correctName[nameLen];
321 strncpy(correctName, name, nameLen-5);
322 correctName[nameLen-5] = '\0';
323 const macho_nlist<P>* symbolsStart = fOwner.fSymbols;
324 const macho_nlist<P>* symbolsEnd = &symbolsStart[fOwner.fSymbolCount];
325 for(const macho_nlist<P>* s = symbolsStart; s < symbolsEnd; ++s) {
326 if ( strcmp(&fOwner.fStrings[s->n_strx()], correctName) == 0 ) {
333 // support for labeled stubs
334 switch ( section->flags() & SECTION_TYPE ) {
336 setSize(section->reserved2());
338 case S_LAZY_SYMBOL_POINTERS:
339 case S_NON_LAZY_SYMBOL_POINTERS:
340 setSize(sizeof(pint_t));
342 case S_4BYTE_LITERALS:
345 case S_8BYTE_LITERALS:
348 case S_16BYTE_LITERALS:
351 case S_CSTRING_LITERALS:
352 setSize(strlen((char*)(fOwner.fHeader) + section->offset() + fAddress - section->addr()) + 1);
357 // size calculate later after next atom is found
361 // compute whether this atom needs to be in symbol table
362 if ( (fSymbol->n_desc() & REFERENCED_DYNAMICALLY) != 0) {
363 fSymbolTableInclusion = ObjectFile::Atom::kSymbolTableInAndNeverStrip;
365 else if ( fOwner.fOptions.fForFinalLinkedImage
366 && ((section->flags() & SECTION_TYPE) == S_COALESCED)
367 && ((section->flags() & S_ATTR_NO_TOC) == S_ATTR_NO_TOC)
368 && ((section->flags() & S_ATTR_STRIP_STATIC_SYMS) == S_ATTR_STRIP_STATIC_SYMS)
369 && (strcmp(section->sectname(), "__eh_frame") == 0) ) {
370 // .eh symbols exist so the linker can associate them with functions
371 // removing them from final linked images is a big space savings rdar://problem/4180168
372 fSymbolTableInclusion = ObjectFile::Atom::kSymbolTableNotIn;
374 else if ( fOwner.fOptions.fForFinalLinkedImage
375 && ((section->flags() & SECTION_TYPE) == S_REGULAR)
376 && (strncmp(section->sectname(), "__gcc_except_tab", 16) == 0)
377 && (strncmp(this->getName(), "GCC_except_table", 16) == 0) ) {
378 // GCC_except_table* symbols don't need to exist in final linked image
379 fSymbolTableInclusion = ObjectFile::Atom::kSymbolTableNotIn;
382 fSymbolTableInclusion = ObjectFile::Atom::kSymbolTableIn;
387 template <typename A>
388 void SymbolAtom<A>::setSize(uint64_t size)
392 if ( fSection->flags() & S_ATTR_SOME_INSTRUCTIONS ) {
393 // For code, the aligment is based just on the section alignment and code address
395 fAlignment = fSection->align();
397 fAlignment = std::min((uint8_t)__builtin_ctz(fAddress), (uint8_t)fSection->align());
400 // For data, compute the alignment base on the address aligned at in object file and the size
401 uint8_t sizeAlign = __builtin_ctz(fSize);
402 uint8_t sizeAndSectAlign = std::min((uint8_t)fSection->align(), sizeAlign);
403 // If address is zero, can't figure out better alignment than section alignment and size
405 fAlignment = sizeAndSectAlign;
407 fAlignment = std::min((uint8_t)__builtin_ctz(fAddress), sizeAndSectAlign);
412 template <typename A>
413 const char* SymbolAtom<A>::getSectionName() const
415 if ( strlen(fSection->sectname()) > 15 ) {
416 static char temp[18];
417 strncpy(temp, fSection->sectname(), 16);
421 return fSection->sectname();
424 template <typename A>
425 bool SymbolAtom<A>::requiresFollowOnAtom() const
427 // requires follow-on if built with old compiler and not the last atom
428 if ( (fOwner.fHeader->flags() & MH_SUBSECTIONS_VIA_SYMBOLS) == 0) {
429 for (ReferenceVectorConstIterator it=fReferences.begin(); it != fReferences.end(); it++) {
430 Reference<A>* ref = *it;
431 if ( ref->getKind() == A::kFollowOn )
438 template <typename A>
439 ObjectFile::Atom& SymbolAtom<A>::getFollowOnAtom() const
441 for (ReferenceVectorConstIterator it=fReferences.begin(); it != fReferences.end(); it++) {
442 Reference<A>* ref = *it;
443 if ( ref->getKind() == A::kFollowOn )
444 return ref->getTarget();
446 return *((ObjectFile::Atom*)NULL);
452 template <typename A>
453 void SymbolAtom<A>::copyRawContent(uint8_t buffer[]) const
457 bzero(buffer, fSize);
459 uint32_t fileOffset = fSection->offset() - fSection->addr() + fAddress;
460 memcpy(buffer, (char*)(fOwner.fHeader)+fileOffset, fSize);
465 template <typename A>
466 class SymbolAtomSorter
469 SymbolAtomSorter(std::map<uint32_t, BaseAtom*>& map) : fMap(map) {}
471 typedef typename A::P::uint_t pint_t;
473 bool operator()(ObjectFile::Atom* left, ObjectFile::Atom* right)
475 pint_t leftAddr = ((SymbolAtom<A>*)left)->fAddress;
476 pint_t rightAddr = ((SymbolAtom<A>*)right)->fAddress;
477 if ( leftAddr == rightAddr ) {
478 // two atoms with same address, must have been a function with multiple labels
479 // make sure we sort these so the one with real content (in map) is last
480 std::map<uint32_t, BaseAtom*>::iterator pos = fMap.find(leftAddr);
481 if ( pos != fMap.end() ) {
482 return ( pos->second == right );
487 return ( leftAddr < rightAddr );
491 std::map<uint32_t, BaseAtom*>& fMap;
496 // A TentativeAtom represents a C "common" or "tentative" defintion of data.
497 // For instance, "int foo;" is neither a declaration or a definition and
498 // is represented by a TentativeAtom.
500 template <typename A>
501 class TentativeAtom : public BaseAtom
504 virtual ObjectFile::Reader* getFile() const { return &fOwner; }
505 virtual bool getTranslationUnitSource(const char** dir, const char** name) const
506 { return fOwner.getTranslationUnitSource(dir, name); }
507 virtual const char* getName() const { return &fOwner.fStrings[fSymbol->n_strx()]; }
508 virtual const char* getDisplayName() const { return getName(); }
509 virtual ObjectFile::Atom::Scope getScope() const { return fScope; }
510 virtual ObjectFile::Atom::DefinitionKind getDefinitionKind() const { return ObjectFile::Atom::kTentativeDefinition; }
511 virtual bool isZeroFill() const { return true; }
512 virtual SymbolTableInclusion getSymbolTableInclusion() const { return ((fSymbol->n_desc() & REFERENCED_DYNAMICALLY) != 0)
513 ? ObjectFile::Atom::kSymbolTableInAndNeverStrip : ObjectFile::Atom::kSymbolTableIn; }
514 virtual bool dontDeadStrip() const { return ((fSymbol->n_desc() & (N_NO_DEAD_STRIP|REFERENCED_DYNAMICALLY)) != 0); }
515 virtual uint64_t getSize() const { return fSymbol->n_value(); }
516 virtual std::vector<ObjectFile::Reference*>& getReferences() const { return fgNoReferences; }
517 virtual bool mustRemainInSection() const { return true; }
518 virtual const char* getSectionName() const { return "__common"; }
519 virtual ObjectFile::Segment& getSegment() const { return DataSegment::fgSingleton; }
520 virtual bool requiresFollowOnAtom() const { return false; }
521 virtual ObjectFile::Atom& getFollowOnAtom() const { return *(ObjectFile::Atom*)NULL; }
522 virtual std::vector<ObjectFile::LineInfo>* getLineInfo() const { return NULL; }
523 virtual uint8_t getAlignment() const;
524 virtual void copyRawContent(uint8_t buffer[]) const;
525 virtual void setScope(ObjectFile::Atom::Scope newScope) { fScope = newScope; }
526 virtual void setSize(uint64_t size) { }
527 virtual void addReference(ObjectFile::Reference* ref) { throw "ld64: can't add references"; }
528 virtual void addLineInfo(const ObjectFile::LineInfo& info) { throw "ld64: can't add line info to tentative definition"; }
529 virtual void alignAtLeast(uint8_t align) { }
532 typedef typename A::P P;
533 typedef typename A::P::E E;
534 typedef typename A::P::uint_t pint_t;
535 typedef typename A::ReferenceKinds Kinds;
536 friend class Reader<A>;
538 TentativeAtom(Reader<A>&, const macho_nlist<P>*);
539 virtual ~TentativeAtom() {}
542 const macho_nlist<P>* fSymbol;
543 ObjectFile::Atom::Scope fScope;
544 static std::vector<ObjectFile::Reference*> fgNoReferences;
547 template <typename A>
548 std::vector<ObjectFile::Reference*> TentativeAtom<A>::fgNoReferences;
550 template <typename A>
551 TentativeAtom<A>::TentativeAtom(Reader<A>& owner, const macho_nlist<P>* symbol)
552 : fOwner(owner), fSymbol(symbol)
554 uint8_t type = symbol->n_type();
555 if ( (type & N_EXT) == 0 )
556 fScope = ObjectFile::Atom::scopeTranslationUnit;
557 else if ( (type & N_PEXT) != 0 )
558 fScope = ObjectFile::Atom::scopeLinkageUnit;
560 fScope = ObjectFile::Atom::scopeGlobal;
561 if ( ((type & N_TYPE) == N_UNDF) && (symbol->n_value() != 0) ) {
562 // tentative definition
565 printf("unknown symbol type: %d\n", type);
567 //fprintf(stderr, "TentativeAtom(%p) %s\n", this, this->getDisplayName());
571 template <typename A>
572 uint8_t TentativeAtom<A>::getAlignment() const
574 // common symbols align to their size
575 // that is, a 4-byte common aligns to 4-bytes
576 // to be safe, odd size commons align to the next power-of-2 size
577 uint8_t alignment = (uint8_t)ceil(log2(this->getSize()));
578 // limit alignment of extremely large commons to 2^15 bytes (8-page)
579 if ( alignment < 15 )
585 template <typename A>
586 void TentativeAtom<A>::copyRawContent(uint8_t buffer[]) const
588 bzero(buffer, getSize());
593 // An AnonymousAtom represents compiler generated data that has no name.
594 // For instance, a literal C-string or a 64-bit floating point constant
595 // is represented by an AnonymousAtom.
597 template <typename A>
598 class AnonymousAtom : public BaseAtom
601 virtual ObjectFile::Reader* getFile() const { return &fOwner; }
602 virtual bool getTranslationUnitSource(const char** dir, const char** name) const { return false; }
603 virtual const char* getName() const { return fSynthesizedName; }
604 virtual const char* getDisplayName() const;
605 virtual ObjectFile::Atom::Scope getScope() const;
606 virtual ObjectFile::Atom::DefinitionKind getDefinitionKind() const;
607 virtual ObjectFile::Atom::SymbolTableInclusion getSymbolTableInclusion() const { return fSymbolTableInclusion; }
608 virtual bool dontDeadStrip() const { return fDontDeadStrip; }
609 virtual bool isZeroFill() const;
610 virtual uint64_t getSize() const { return fSize; }
611 virtual std::vector<ObjectFile::Reference*>& getReferences() const { return (std::vector<ObjectFile::Reference*>&)(fReferences); }
612 virtual bool mustRemainInSection() const { return true; }
613 virtual const char* getSectionName() const;
614 virtual Segment<A>& getSegment() const { return *fSegment; }
615 virtual bool requiresFollowOnAtom() const;
616 virtual ObjectFile::Atom& getFollowOnAtom() const;
617 virtual std::vector<ObjectFile::LineInfo>* getLineInfo() const { return NULL; }
618 virtual uint8_t getAlignment() const;
619 virtual void copyRawContent(uint8_t buffer[]) const;
620 virtual void setScope(ObjectFile::Atom::Scope newScope) { fScope = newScope; }
621 virtual void setSize(uint64_t size) { fSize = size; }
622 virtual void addReference(ObjectFile::Reference* ref) { fReferences.insert(fReferences.begin(), (Reference<A>*)ref); }
623 virtual void addLineInfo(const ObjectFile::LineInfo& info) { fprintf(stderr, "ld64: can't add line info to anonymous symbol %s from %s\n", this->getDisplayName(), this->getFile()->getPath()); }
624 virtual void alignAtLeast(uint8_t align) { }
625 BaseAtom* redirectTo() { return fRedirect; }
626 bool isWeakImportStub() { return fWeakImportStub; }
629 typedef typename A::P P;
630 typedef typename A::P::E E;
631 typedef typename A::P::uint_t pint_t;
632 typedef typename A::ReferenceKinds Kinds;
633 typedef typename std::vector<Reference<A>*> ReferenceVector;
634 typedef typename ReferenceVector::iterator ReferenceVectorIterator; // seems to help C++ parser
635 typedef typename ReferenceVector::const_iterator ReferenceVectorConstIterator; // seems to help C++ parser
636 friend class Reader<A>;
638 AnonymousAtom(Reader<A>&, const macho_section<P>*, uint32_t addr, uint32_t size);
639 virtual ~AnonymousAtom() {}
642 const char* fSynthesizedName;
643 const macho_section<P>* fSection;
646 Segment<A>* fSegment;
647 ReferenceVector fReferences;
650 bool fWeakImportStub;
651 bool fReallyNonLazyPointer; // HACK until compiler stops emitting anonymous non-lazy pointers
652 ObjectFile::Atom::SymbolTableInclusion fSymbolTableInclusion;
653 ObjectFile::Atom::Scope fScope;
656 template <typename A>
657 AnonymousAtom<A>::AnonymousAtom(Reader<A>& owner, const macho_section<P>* section, uint32_t addr, uint32_t size)
658 : fOwner(owner), fSynthesizedName(NULL), fSection(section), fAddress(addr), fSize(size), fSegment(NULL), fDontDeadStrip(true),
659 fWeakImportStub(false), fReallyNonLazyPointer(false), fSymbolTableInclusion(ObjectFile::Atom::kSymbolTableNotIn),
660 fScope(ObjectFile::Atom::scopeTranslationUnit)
662 fSegment = new Segment<A>(fSection);
664 uint8_t type = fSection->flags() & SECTION_TYPE;
668 asprintf((char**)&fSynthesizedName, "zero-fill-at-0x%08X", addr);
672 if ( (strcmp(section->sectname(), "__class") == 0) && (strcmp(section->segname(), "__OBJC") == 0) && owner.fAppleObjc ) {
673 // special case ObjC classes to synthesize .objc_class_name_* symbols, for Apple runtime only
674 uint32_t classNameAddr = P::getP(*(pint_t*)(((uint8_t*)owner.fHeader) + section->offset() + addr + 2*sizeof(pint_t) - section->addr()));
675 const char* str = (char*)(owner.fHeader) + section->offset() + classNameAddr - section->addr();
676 asprintf((char**)&fSynthesizedName, ".objc_class_name_%s", str);
677 if ( fOwner.fOptions.fForFinalLinkedImage )
678 fSymbolTableInclusion = ObjectFile::Atom::kSymbolTableIn;
680 fSymbolTableInclusion = ObjectFile::Atom::kSymbolTableInAsAbsolute;
681 fScope = ObjectFile::Atom::scopeGlobal;
683 else if ( strcmp(fSection->sectname(), "__cstring") == 0 ) {
684 // handle .o files created by old ld64 -r that are missing cstring section type
685 const char* str = (char*)(owner.fHeader) + section->offset() + addr - section->addr();
686 asprintf((char**)&fSynthesizedName, "cstring=%s", str);
689 case S_CSTRING_LITERALS:
691 const char* str = (char*)(owner.fHeader) + section->offset() + addr - section->addr();
692 asprintf((char**)&fSynthesizedName, "cstring=%s", str);
693 fScope = ObjectFile::Atom::scopeLinkageUnit;
694 fDontDeadStrip = false;
697 case S_4BYTE_LITERALS:
699 uint32_t value = E::get32(*(uint32_t*)(((uint8_t*)owner.fHeader) + section->offset() + addr - section->addr()));
700 asprintf((char**)&fSynthesizedName, "4-byte-literal=0x%08X", value);
701 fScope = ObjectFile::Atom::scopeLinkageUnit;
702 fDontDeadStrip = false;
705 case S_8BYTE_LITERALS:
707 uint64_t value = E::get64(*(uint64_t*)(((uint8_t*)owner.fHeader) + section->offset() + addr - section->addr()));
708 asprintf((char**)&fSynthesizedName, "8-byte-literal=0x%016llX", value);
709 fScope = ObjectFile::Atom::scopeLinkageUnit;
710 fDontDeadStrip = false;
713 case S_16BYTE_LITERALS:
715 uint64_t value1 = E::get64(*(uint64_t*)(((uint8_t*)owner.fHeader) + section->offset() + addr - section->addr()));
716 uint64_t value2 = E::get64(*(uint64_t*)(((uint8_t*)owner.fHeader) + section->offset() + addr + 8 - section->addr()));
717 asprintf((char**)&fSynthesizedName, "16-byte-literal=0x%016llX,%016llX", value1, value2);
718 fScope = ObjectFile::Atom::scopeLinkageUnit;
719 fDontDeadStrip = false;
722 case S_LITERAL_POINTERS:
724 uint32_t literalNameAddr = P::getP(*(pint_t*)(((uint8_t*)owner.fHeader) + section->offset() + addr - section->addr()));
725 const char* str = (char*)(owner.fHeader) + section->offset() + literalNameAddr - section->addr();
726 asprintf((char**)&fSynthesizedName, "literal-pointer@%s@%s@%s", section->segname(), section->sectname(), str);
727 fScope = ObjectFile::Atom::scopeLinkageUnit;
730 case S_MOD_INIT_FUNC_POINTERS:
731 asprintf((char**)&fSynthesizedName, "initializer$%d", (addr - (uint32_t)fSection->addr())/sizeof(pint_t));
733 case S_MOD_TERM_FUNC_POINTERS:
734 asprintf((char**)&fSynthesizedName, "terminator$%d", (addr - (uint32_t)fSection->addr())/sizeof(pint_t));
738 uint32_t index = (fAddress - fSection->addr()) / fSection->reserved2();
739 index += fSection->reserved1();
740 uint32_t symbolIndex = E::get32(fOwner.fIndirectTable[index]);
741 const macho_nlist<P>* sym = &fOwner.fSymbols[symbolIndex];
742 uint32_t strOffset = sym->n_strx();
743 // want name to not have $stub suffix, this is what automatic stub generation expects
744 fSynthesizedName = &fOwner.fStrings[strOffset];
745 // check for weak import
746 fWeakImportStub = fOwner.isWeakImportSymbol(sym);
747 // sometimes the compiler gets confused and generates a stub to a static function
748 // if so, we should redirect any call to the stub to be calls to the real static function atom
749 if ( ((sym->n_type() & N_TYPE) != N_UNDF) && ((sym->n_desc() & N_WEAK_DEF) == 0) ) {
750 BaseAtom* staticAtom = fOwner.findAtomByName(fSynthesizedName);
751 if ( staticAtom != NULL )
752 fRedirect = staticAtom;
754 fScope = ObjectFile::Atom::scopeLinkageUnit;
757 case S_LAZY_SYMBOL_POINTERS:
758 case S_NON_LAZY_SYMBOL_POINTERS:
760 fDontDeadStrip = false;
761 fScope = ObjectFile::Atom::scopeLinkageUnit;
762 uint32_t index = (fAddress - fSection->addr()) / sizeof(pint_t);
763 index += fSection->reserved1();
764 uint32_t symbolIndex = E::get32(fOwner.fIndirectTable[index]);
765 if ( symbolIndex == INDIRECT_SYMBOL_LOCAL ) {
766 // Silly codegen with non-lazy pointer to a local symbol
767 uint32_t fileOffset = fSection->offset() - fSection->addr() + fAddress;
768 pint_t nonLazyPtrValue = P::getP(*((pint_t*)((char*)(fOwner.fHeader)+fileOffset)));
769 // All atoms not created yet, so we need to scan symbol table
770 const macho_nlist<P>* end = &fOwner.fSymbols[fOwner.fSymbolCount];
771 for (const macho_nlist<P>* sym = fOwner.fSymbols; sym < end; ++sym) {
772 if ( ((sym->n_type() & N_TYPE) == N_SECT)
773 && ((sym->n_type() & N_STAB) == 0)
774 && (sym->n_value() == nonLazyPtrValue) ) {
775 const char* name = &fOwner.fStrings[sym->n_strx()];
776 char* str = new char[strlen(name)+16];
778 strcat(str, "$non_lazy_ptr");
779 fSynthesizedName = str;
780 // add direct reference to target later, because its atom may not be constructed yet
781 fOwner.fLocalNonLazys.push_back(this);
782 fScope = ObjectFile::Atom::scopeTranslationUnit;
786 throwf("malformed .o file: non-lazy-pointer at address 0x%08X with value 0x%0llX missing symbol", addr, (uint64_t)nonLazyPtrValue);
788 const macho_nlist<P>* targetSymbol = &fOwner.fSymbols[symbolIndex];
789 const char* name = &fOwner.fStrings[targetSymbol->n_strx()];
790 char* str = new char[strlen(name)+16];
792 if ( type == S_LAZY_SYMBOL_POINTERS )
793 strcat(str, "$lazy_ptr");
795 strcat(str, "$non_lazy_ptr");
796 fSynthesizedName = str;
798 if ( (targetSymbol->n_type() & N_EXT) == 0 ) {
799 // target is translation unit scoped, so add direct reference to target
800 //fOwner.makeReference(A::kPointer, addr, targetSymbol->n_value());
801 new Reference<A>(A::kPointer, AtomAndOffset(this), fOwner.findAtomAndOffset(targetSymbol->n_value()));
804 if ( fOwner.isWeakImportSymbol(targetSymbol) )
805 new Reference<A>(A::kPointerWeakImport, AtomAndOffset(this), name, 0);
807 new Reference<A>(A::kPointer, AtomAndOffset(this), name, 0);
812 throwf("section type %d not supported with address=0x%08X", type, addr);
814 //fprintf(stderr, "AnonymousAtom(%p) %s \n", this, this->getDisplayName());
818 template <typename A>
819 const char* AnonymousAtom<A>::getDisplayName() const
821 if ( fSynthesizedName != NULL )
822 return fSynthesizedName;
824 static char temp[512];
825 if ( (fSection->flags() & SECTION_TYPE) == S_CSTRING_LITERALS ) {
826 uint32_t fileOffset = fSection->offset() - fSection->addr() + fAddress;
827 sprintf(temp, "atom string literal: \"%s\"", (char*)(fOwner.fHeader)+fileOffset);
830 sprintf(temp, "%s@%d", fSection->sectname(), fAddress - (uint32_t)fSection->addr() );
835 template <typename A>
836 ObjectFile::Atom::Scope AnonymousAtom<A>::getScope() const
838 if ( fReallyNonLazyPointer )
839 return ObjectFile::Atom::scopeTranslationUnit;
844 template <typename A>
845 ObjectFile::Atom::DefinitionKind AnonymousAtom<A>::getDefinitionKind() const
847 if ( fReallyNonLazyPointer )
848 return ObjectFile::Atom::kRegularDefinition;
849 // in order for literals to be coalesced they must be weak
850 switch ( fSection->flags() & SECTION_TYPE ) {
851 case S_CSTRING_LITERALS:
852 case S_4BYTE_LITERALS:
853 case S_8BYTE_LITERALS:
854 case S_16BYTE_LITERALS:
855 case S_NON_LAZY_SYMBOL_POINTERS:
856 case S_LITERAL_POINTERS:
857 return ObjectFile::Atom::kWeakDefinition;
859 return ObjectFile::Atom::kRegularDefinition;
863 template <typename A>
864 bool AnonymousAtom<A>::isZeroFill() const
866 return ( (fSection->flags() & SECTION_TYPE) == S_ZEROFILL );
870 template <typename A>
871 const char* AnonymousAtom<A>::getSectionName() const
873 if ( strlen(fSection->sectname()) > 15 ) {
874 static char temp[18];
875 strncpy(temp, fSection->sectname(), 16);
879 return fSection->sectname();
882 template <typename A>
883 uint8_t AnonymousAtom<A>::getAlignment() const
885 if ( fReallyNonLazyPointer )
886 return (uint8_t)log2(sizeof(pint_t));
887 switch ( fSection->flags() & SECTION_TYPE ) {
888 case S_4BYTE_LITERALS:
890 case S_8BYTE_LITERALS:
892 case S_16BYTE_LITERALS:
894 case S_NON_LAZY_SYMBOL_POINTERS:
895 return (uint8_t)log2(sizeof(pint_t));
897 return fSection->align();
901 template <typename A>
902 bool AnonymousAtom<A>::requiresFollowOnAtom() const
904 // requires follow-on if built with old compiler and not the last atom
905 if ( (fOwner.fHeader->flags() & MH_SUBSECTIONS_VIA_SYMBOLS) == 0) {
906 for (ReferenceVectorConstIterator it=fReferences.begin(); it != fReferences.end(); it++) {
907 Reference<A>* ref = *it;
908 if ( ref->getKind() == A::kFollowOn )
915 template <typename A>
916 ObjectFile::Atom& AnonymousAtom<A>::getFollowOnAtom() const
918 for (ReferenceVectorConstIterator it=fReferences.begin(); it != fReferences.end(); it++) {
919 Reference<A>* ref = *it;
920 if ( ref->getKind() == A::kFollowOn )
921 return ref->getTarget();
923 return *((ObjectFile::Atom*)NULL);
926 template <typename A>
927 void AnonymousAtom<A>::copyRawContent(uint8_t buffer[]) const
931 bzero(buffer, fSize);
933 uint32_t fileOffset = fSection->offset() - fSection->addr() + fAddress;
934 memcpy(buffer, (char*)(fOwner.fHeader)+fileOffset, fSize);
941 template <typename A>
942 class Reader : public ObjectFile::Reader
945 static bool validFile(const uint8_t* fileContent);
946 static Reader<A>* make(const uint8_t* fileContent, const char* path, time_t modTime,
947 const ObjectFile::ReaderOptions& options)
948 { return new Reader<A>(fileContent, path, modTime, options); }
951 virtual const char* getPath() { return fPath; }
952 virtual time_t getModificationTime() { return fModTime; }
953 virtual ObjectFile::Reader::DebugInfoKind getDebugInfoKind() { return fDebugInfo; }
954 virtual std::vector<class ObjectFile::Atom*>& getAtoms() { return (std::vector<class ObjectFile::Atom*>&)(fAtoms); }
955 virtual std::vector<class ObjectFile::Atom*>* getJustInTimeAtomsFor(const char* name) { return NULL; }
956 virtual std::vector<Stab>* getStabs() { return &fStabs; }
958 bool getTranslationUnitSource(const char** dir, const char** name) const;
961 typedef typename A::P P;
962 typedef typename A::P::E E;
963 typedef typename A::P::uint_t pint_t;
964 //typedef typename std::vector<Atom<A>*> AtomVector;
965 //typedef typename AtomVector::iterator AtomVectorIterator; // seems to help C++ parser
966 typedef typename A::ReferenceKinds Kinds;
967 friend class AnonymousAtom<A>;
968 friend class TentativeAtom<A>;
969 friend class SymbolAtom<A>;
970 Reader(const uint8_t* fileContent, const char* path, time_t modTime, const ObjectFile::ReaderOptions& options);
971 bool addRelocReference(const macho_section<P>* sect, const macho_relocation_info<P>* reloc);
972 bool addRelocReference_powerpc(const macho_section<P>* sect, const macho_relocation_info<P>* reloc);
973 Kinds pointerDiffKindForLength_powerpc(uint8_t r_length);
974 bool read_comp_unit(const char ** name, const char ** comp_dir, uint64_t *stmt_list);
975 static bool isWeakImportSymbol(const macho_nlist<P>* sym);
976 static bool skip_form(const uint8_t ** offset, const uint8_t * end, uint64_t form, uint8_t addr_size, bool dwarf64);
977 static const char* assureFullPath(const char* path);
978 AtomAndOffset findAtomAndOffset(uint32_t addr);
979 AtomAndOffset findAtomAndOffset(uint32_t baseAddr, uint32_t realAddr);
980 Reference<A>* makeReference(Kinds kind, uint32_t atAddr, uint32_t toAddr);
981 Reference<A>* makeReference(Kinds kind, uint32_t atAddr, uint32_t fromAddr, uint32_t toAddr);
982 Reference<A>* makeReferenceWithToBase(Kinds kind, uint32_t atAddr, uint32_t toAddr, uint32_t toBaseAddr);
983 Reference<A>* makeReferenceWithToBase(Kinds kind, uint32_t atAddr, uint32_t fromAddr, uint32_t toAddr, uint32_t toBaseAddr);
984 Reference<A>* makeByNameReference(Kinds kind, uint32_t atAddr, const char* toName, uint32_t toOffset);
985 Reference<A>* makeReferenceToEH(const char* ehName, pint_t ehAtomAddress, const macho_section<P>* ehSect);
986 Reference<A>* makeReferenceToSymbol(Kinds kind, uint32_t atAddr, const macho_nlist<P>* toSymbol, uint32_t toOffset);
987 void validSectionType(uint8_t type);
988 void handleAnonymousNonLazyPointers(const macho_section<P>* sect);
990 BaseAtom* findAtomByName(const char*);
994 const ObjectFile::ReaderOptions& fOptions;
995 const macho_header<P>* fHeader;
996 const char* fStrings;
997 const macho_nlist<P>* fSymbols;
998 uint32_t fSymbolCount;
999 const macho_segment_command<P>* fSegment;
1000 const uint32_t* fIndirectTable;
1001 std::vector<ObjectFile::Atom*> fAtoms;
1002 std::map<uint32_t, BaseAtom*> fAddrToAtom;
1003 std::vector<class AnonymousAtom<A>*> fLocalNonLazys;
1004 ObjectFile::Reader::DebugInfoKind fDebugInfo;
1006 const macho_section<P>* fDwarfDebugInfoSect;
1007 const macho_section<P>* fDwarfDebugAbbrevSect;
1008 const macho_section<P>* fDwarfDebugLineSect;
1009 const char* fDwarfTranslationUnitDir;
1010 const char* fDwarfTranslationUnitFile;
1011 std::map<uint32_t,const char*> fDwarfIndexToFile;
1012 std::vector<Stab> fStabs;
1016 // usually do nothing
1017 template <typename A> void Reader<A>::handleAnonymousNonLazyPointers(const macho_section<P>* sect) { }
1019 // HACK for ppc64, need to split of anonymous non-lazy-pointers because they must be 8-byte aligned to work with ld instruction
1021 Reader<ppc64>::handleAnonymousNonLazyPointers(const macho_section<P>* dataSect) {
1022 if ( (dataSect->size() >= sizeof(pint_t))
1023 && (dataSect->align() >= log2(sizeof(pint_t)))
1024 && (strcmp(dataSect->sectname(), "__data") == 0)
1025 && (strcmp(dataSect->segname(), "__DATA") == 0) ) {
1026 std::set<uint32_t> lo14targets;
1027 const macho_section<P>* const sectionsStart = (macho_section<P>*)((char*)fSegment + sizeof(macho_segment_command<P>));
1028 const macho_section<P>* const sectionsEnd = §ionsStart[fSegment->nsects()];
1029 for (const macho_section<P>* sect=sectionsStart; sect < sectionsEnd; ++sect) {
1030 if ( strncmp(sect->sectname(), "__text", 6) == 0 ) {
1031 const macho_relocation_info<P>* relocs = (macho_relocation_info<P>*)((char*)(fHeader) + sect->reloff());
1032 const macho_relocation_info<P>* relocsEnd = &relocs[sect->nreloc()];
1033 for (const macho_relocation_info<P>* r = relocs; r < relocsEnd; ++r) {
1034 if ( (r->r_address() & R_SCATTERED) != 0 ) {
1035 const macho_scattered_relocation_info<P>* sreloc = (macho_scattered_relocation_info<P>*)r;
1036 if ( sreloc->r_type() == PPC_RELOC_LO14_SECTDIFF ) {
1037 lo14targets.insert(sreloc->r_value());
1043 // walk backwards so that newly created anonymous atoms do not mask misalignmented
1044 for (std::set<uint32_t>::reverse_iterator it=lo14targets.rbegin(); it != lo14targets.rend(); it++) {
1045 uint32_t targetOfLO14 = *it;
1046 AtomAndOffset found = this->findAtomAndOffset(targetOfLO14);
1047 if ( (found.offset & 0x7) != 0 ) {
1048 AnonymousAtom<ppc64>* newAtom = new AnonymousAtom<ppc64>(*this, dataSect, targetOfLO14, sizeof(pint_t));
1049 newAtom->fReallyNonLazyPointer = true;
1050 fAtoms.push_back(newAtom);
1051 fAddrToAtom[targetOfLO14] = newAtom;
1057 template <typename A>
1058 Reader<A>::Reader(const uint8_t* fileContent, const char* path, time_t modTime, const ObjectFile::ReaderOptions& options)
1059 : fPath(strdup(path)), fModTime(modTime), fOptions(options), fHeader((const macho_header<P>*)fileContent),
1060 fStrings(NULL), fSymbols(NULL), fSymbolCount(0), fSegment(NULL), fIndirectTable(NULL),
1061 fDebugInfo(kDebugInfoNone), fHasUUID(false), fDwarfDebugInfoSect(NULL), fDwarfDebugAbbrevSect(NULL),
1062 fDwarfTranslationUnitDir(NULL), fDwarfTranslationUnitFile(NULL), fAppleObjc(false)
1065 if ( ! validFile(fileContent) )
1066 throw "not a valid mach-o object file";
1068 // cache intersting pointers
1069 const macho_header<P>* header = (const macho_header<P>*)fileContent;
1070 const uint32_t cmd_count = header->ncmds();
1071 const macho_load_command<P>* const cmds = (macho_load_command<P>*)((char*)header + sizeof(macho_header<P>));
1072 const macho_load_command<P>* cmd = cmds;
1073 uint32_t undefinedStartIndex = 0;
1074 uint32_t undefinedEndIndex = 0;
1075 for (uint32_t i = 0; i < cmd_count; ++i) {
1076 switch (cmd->cmd()) {
1079 const macho_symtab_command<P>* symtab = (macho_symtab_command<P>*)cmd;
1080 fSymbolCount = symtab->nsyms();
1081 fSymbols = (const macho_nlist<P>*)((char*)header + symtab->symoff());
1082 fStrings = (char*)header + symtab->stroff();
1087 const macho_dysymtab_command<P>* dsymtab = (struct macho_dysymtab_command<P>*)cmd;
1088 fIndirectTable = (uint32_t*)((char*)fHeader + dsymtab->indirectsymoff());
1089 undefinedStartIndex = dsymtab->iundefsym();
1090 undefinedEndIndex = undefinedStartIndex + dsymtab->nundefsym();
1098 if ( cmd->cmd() == macho_segment_command<P>::CMD ) {
1099 fSegment = (macho_segment_command<P>*)cmd;
1103 cmd = (const macho_load_command<P>*)(((char*)cmd)+cmd->cmdsize());
1105 const macho_section<P>* const sectionsStart = (macho_section<P>*)((char*)fSegment + sizeof(macho_segment_command<P>));
1106 const macho_section<P>* const sectionsEnd = §ionsStart[fSegment->nsects()];
1108 // inital guess for number of atoms
1109 fAtoms.reserve(fSymbolCount);
1111 // add all atoms that have entries in symbol table
1112 const macho_section<P>* sections = (macho_section<P>*)((char*)fSegment + sizeof(macho_segment_command<P>));
1113 for (uint32_t i=0; i < fSymbolCount; ++i) {
1114 const macho_nlist<P>& sym = fSymbols[i];
1115 if ( (sym.n_type() & N_STAB) == 0 ) {
1116 uint8_t type = (sym.n_type() & N_TYPE);
1117 if ( type == N_SECT ) {
1118 const macho_section<P>* section = §ions[sym.n_sect()-1];
1119 bool suppress = false;
1120 // ignore atoms in debugger sections
1121 if ( (section->flags() & S_ATTR_DEBUG) == 0 ) {
1122 // ignore labels for atoms in other sections
1123 switch ( section->flags() & SECTION_TYPE ) {
1125 if ( (sym.n_desc() & N_WEAK_DEF) && strcmp(section->sectname(), "__picsymbolstub1__TEXT") == 0 )
1126 suppress = true; // ignore stubs in crt1.o built by old ld64 that was missing S_SYMBOL_STUBS
1129 case S_4BYTE_LITERALS:
1130 case S_8BYTE_LITERALS:
1131 case S_16BYTE_LITERALS:
1132 case S_CSTRING_LITERALS:
1134 BaseAtom* newAtom = new SymbolAtom<A>(*this, &sym, section);
1135 std::map<uint32_t, BaseAtom*>::iterator pos = fAddrToAtom.find(sym.n_value());
1136 if ( pos != fAddrToAtom.end() ) {
1137 // another label to an existing address
1138 // make this one be the real one and followed by the previous
1139 BaseAtom* existingAtom = pos->second;
1140 //fprintf(stderr, "new atom %s has same address as existing atom %s\n", newAtom->getDisplayName(), existingAtom->getDisplayName());
1141 new Reference<A>(A::kFollowOn, AtomAndOffset(newAtom), AtomAndOffset(existingAtom));
1142 newAtom->setSize(0);
1145 fAddrToAtom[sym.n_value()] = newAtom;
1148 fAtoms.push_back(newAtom);
1151 case S_SYMBOL_STUBS:
1152 case S_LAZY_SYMBOL_POINTERS:
1153 case S_NON_LAZY_SYMBOL_POINTERS:
1154 // ignore symboled stubs produces by old ld64
1157 fprintf(stderr, "ld64 warning: symbol %s found in unsupported section in %s\n",
1158 &fStrings[sym.n_strx()], this->getPath());
1162 else if ( (type == N_UNDF) && (sym.n_value() != 0) ) {
1163 fAtoms.push_back(new TentativeAtom<A>(*this, &sym));
1165 else if ( (type == N_ABS) && (strncmp(&fStrings[sym.n_strx()], ".objc_class_name_", 16) == 0) ) {
1171 // sort SymbolAtoms by address
1172 std::sort(fAtoms.begin(), fAtoms.end(), SymbolAtomSorter<A>(fAddrToAtom));
1174 // add all fixed size anonymous atoms from special sections
1175 for (const macho_section<P>* sect=sectionsStart; sect < sectionsEnd; ++sect) {
1176 uint32_t atomSize = 0;
1177 uint8_t type (sect->flags() & SECTION_TYPE);
1178 validSectionType(type);
1179 bool suppress = false;
1181 case S_SYMBOL_STUBS:
1183 atomSize = sect->reserved2();
1185 case S_LAZY_SYMBOL_POINTERS:
1187 atomSize = sizeof(pint_t);
1189 case S_NON_LAZY_SYMBOL_POINTERS:
1190 case S_LITERAL_POINTERS:
1191 case S_MOD_INIT_FUNC_POINTERS:
1192 case S_MOD_TERM_FUNC_POINTERS:
1193 atomSize = sizeof(pint_t);
1196 atomSize = sizeof(pint_t)*2;
1198 case S_4BYTE_LITERALS:
1201 case S_8BYTE_LITERALS:
1204 case S_16BYTE_LITERALS:
1208 // special case ObjC classes to synthesize .objc_class_name_* symbols
1209 if ( (strcmp(sect->sectname(), "__class") == 0) && (strcmp(sect->segname(), "__OBJC") == 0) && fAppleObjc ) {
1210 // gcc sometimes over aligns class structure
1211 uint32_t align = 1 << sect->align();
1212 atomSize = ((12 * sizeof(pint_t)) + align-1) & (-align);
1216 if ( atomSize != 0 ) {
1217 for(uint32_t sectOffset=0; sectOffset < sect->size(); sectOffset += atomSize) {
1218 uint32_t atomAddr = sect->addr() + sectOffset;
1219 // add if not already an atom at that address
1220 if ( fAddrToAtom.find(atomAddr) == fAddrToAtom.end() ) {
1221 AnonymousAtom<A>* newAtom = new AnonymousAtom<A>(*this, sect, atomAddr, atomSize);
1223 fAtoms.push_back(newAtom);
1224 fAddrToAtom[atomAddr] = newAtom->redirectTo();
1230 // add all c-string anonymous atoms
1231 for (const macho_section<P>* sect=sectionsStart; sect < sectionsEnd; ++sect) {
1232 if ( ((sect->flags() & SECTION_TYPE) == S_CSTRING_LITERALS) || strcmp(sect->sectname(), "__cstring") == 0 ) {
1234 uint32_t stringAddr;
1235 BaseAtom* firstEmptyString = NULL;
1236 for(uint32_t sectOffset=0; sectOffset < sect->size(); sectOffset += stringLen) {
1237 stringAddr = sect->addr() + sectOffset;
1238 stringLen = strlen((char*)(fHeader) + sect->offset() + sectOffset) + 1;
1239 // add if not already an atom at that address
1240 if ( fAddrToAtom.find(stringAddr) == fAddrToAtom.end() ) {
1241 BaseAtom* newAtom = new AnonymousAtom<A>(*this, sect, stringAddr, stringLen);
1242 if ( stringLen == 1 ) {
1243 // because of padding it may look like there are lots of empty strings
1244 // map them all to the first empty string
1245 if ( firstEmptyString == NULL ) {
1246 firstEmptyString = newAtom;
1247 fAtoms.push_back(firstEmptyString);
1249 fAddrToAtom[stringAddr] = firstEmptyString;
1252 fAtoms.push_back(newAtom);
1253 fAddrToAtom[stringAddr] = newAtom;
1260 // create atoms to cover any non-debug ranges not handled above
1261 for (const macho_section<P>* sect=sectionsStart; sect < sectionsEnd; ++sect) {
1262 pint_t sectionStartAddr = sect->addr();
1263 pint_t sectionEndAddr = sect->addr() + sect->size();
1264 const bool setFollowOnAtom = ((fHeader->flags() & MH_SUBSECTIONS_VIA_SYMBOLS) == 0);
1265 if ( sect->size() != 0 ) {
1266 // ignore dwarf sections. If ld every supports processing dwarf, this logic will need to change
1267 if ( (sect->flags() & S_ATTR_DEBUG) != 0 ) {
1268 fDebugInfo = kDebugInfoDwarf;
1269 if ( strcmp(sect->sectname(), "__debug_info") == 0 )
1270 fDwarfDebugInfoSect = sect;
1271 else if ( strcmp(sect->sectname(), "__debug_abbrev") == 0 )
1272 fDwarfDebugAbbrevSect = sect;
1273 else if ( strcmp(sect->sectname(), "__debug_line") == 0 )
1274 fDwarfDebugLineSect = sect;
1277 if ( strcmp(sect->segname(), "__DWARFA") == 0 ) {
1278 throw "object file contains old DWARF debug info - rebuild with newer compiler";
1280 uint8_t type (sect->flags() & SECTION_TYPE);
1285 // HACK until compiler stops generated anonymous non-lazy pointers rdar://problem/4513414
1286 handleAnonymousNonLazyPointers(sect);
1287 // if there is not an atom already at the start of this section, add an anonymous one
1288 uint32_t previousAtomAddr = 0;
1289 BaseAtom* previousAtom = NULL;
1290 if ( fAddrToAtom.find(sectionStartAddr) == fAddrToAtom.end() ) {
1291 BaseAtom* newAtom = new AnonymousAtom<A>(*this, sect, sect->addr(), 0);
1292 fAtoms.push_back(newAtom);
1293 fAddrToAtom[sect->addr()] = newAtom;
1294 previousAtomAddr = sectionStartAddr;
1295 previousAtom = newAtom;
1297 // calculate size of all atoms in this section and add follow-on references
1298 for (std::map<uint32_t, BaseAtom*>::iterator it=fAddrToAtom.begin(); it != fAddrToAtom.end(); it++) {
1299 // note: this algorithm depends on the map iterator returning entries in address order
1300 if ( (it->first >= sectionStartAddr) && (it->first < sectionEndAddr) ) {
1301 //fprintf(stderr, " atom %s in section\n", it->second->getDisplayName());
1302 if ( previousAtom != NULL ) {
1303 previousAtom->setSize(it->first - previousAtomAddr);
1304 // FIX FIX: this setting of followOn atoms does not work when there are multiple
1305 // labels for the same atom
1306 if ( setFollowOnAtom && (it->second != previousAtom) )
1307 makeReference(A::kFollowOn, previousAtomAddr, it->first);
1309 previousAtomAddr = it->first;
1310 previousAtom = it->second;
1313 if ( previousAtom != NULL ) {
1314 // set last atom in section
1315 previousAtom->setSize(sectionEndAddr - previousAtomAddr);
1323 // add relocation based references
1324 for (const macho_section<P>* sect=sectionsStart; sect < sectionsEnd; ++sect) {
1325 // ignore dwarf sections. If ld every supports processing dwarf, this logic will need to change
1326 if ( (sect->flags() & S_ATTR_DEBUG) == 0 ) {
1327 switch ( sect->flags() & SECTION_TYPE ) {
1328 case S_SYMBOL_STUBS:
1329 case S_LAZY_SYMBOL_POINTERS:
1330 // we ignore compiler generated stubs, so ignore those relocs too
1333 const macho_relocation_info<P>* relocs = (macho_relocation_info<P>*)((char*)(fHeader) + sect->reloff());
1334 const uint32_t relocCount = sect->nreloc();
1335 //fprintf(stderr, "relocCount = %d in section %s\n", relocCount, sect->sectname());
1336 for (uint32_t r = 0; r < relocCount; ++r) {
1338 if ( addRelocReference(sect, &relocs[r]) )
1341 catch (const char* msg) {
1342 throwf("in section %s,%s reloc %u: %s\n", sect->segname(), sect->sectname(), r, msg);
1349 // check of object file that defines no classes, but uses classes
1350 if ( !fAppleObjc ) {
1351 for (uint32_t i=undefinedStartIndex; i < undefinedEndIndex; ++i) {
1352 const macho_nlist<P>& sym = fSymbols[i];
1353 if ( (sym.n_type() & N_STAB) == 0 ) {
1354 if ( ((sym.n_type() & N_TYPE) == N_UNDF) && (strncmp(&fStrings[sym.n_strx()], ".objc_class_name_", 16) == 0) ) {
1362 // add objective-c references
1364 for (const macho_section<P>* sect=sectionsStart; sect < sectionsEnd; ++sect) {
1365 // ignore dwarf sections. If ld every supports processing dwarf, this logic will need to change
1366 if ( (strcmp(sect->sectname(), "__class") == 0) && (strcmp(sect->segname(), "__OBJC") == 0) ) {
1367 // gcc sometimes over aligns class structure
1368 uint32_t align = 1 << sect->align();
1369 uint32_t classSize = ((12 * sizeof(pint_t)) + align-1) & (-align);
1370 for (uint32_t offset = 0; offset < sect->size(); offset += classSize) {
1371 // add by-name reference to super class
1372 uint32_t superClassNameAddr = P::getP(*(pint_t*)(((uint8_t*)fHeader) + sect->offset() + offset + sizeof(pint_t)));
1373 const char* superStr = (char*)(fHeader) + sect->offset() + superClassNameAddr - sect->addr();
1374 const char* superClassName;
1375 asprintf((char**)&superClassName, ".objc_class_name_%s", superStr);
1376 makeByNameReference(A::kNoFixUp, sect->addr()+offset+sizeof(pint_t), superClassName, 0);
1379 else if ( (strcmp(sect->sectname(), "__cls_refs") == 0) && (strcmp(sect->segname(), "__OBJC") == 0) ) {
1380 for (uint32_t offset = 0; offset < sect->size(); offset += sizeof(pint_t)) {
1381 // scan through __cls_refs and add by-name reference for each required class
1382 uint32_t classNameAddr = P::getP(*(pint_t*)(((uint8_t*)fHeader) + sect->offset() + offset));
1383 const char* classStr = (char*)(fHeader) + sect->offset() + classNameAddr - sect->addr();
1384 const char* className;
1385 asprintf((char**)&className, ".objc_class_name_%s", classStr);
1386 makeByNameReference(A::kNoFixUp, sect->addr()+offset, className, 0);
1392 // add direct references to local non-lazy-pointers, can do this now that all atoms are constructed
1393 for (typename std::vector<AnonymousAtom<A>*>::iterator it=fLocalNonLazys.begin(); it != fLocalNonLazys.end(); it++) {
1394 AnonymousAtom<A>* localNonLazy = *it;
1395 uint32_t fileOffset = localNonLazy->fSection->offset() - localNonLazy->fSection->addr() + localNonLazy->fAddress;
1396 pint_t nonLazyPtrValue = P::getP(*((pint_t*)((char*)(fHeader)+fileOffset)));
1397 makeReference(A::kPointer, localNonLazy->fAddress, nonLazyPtrValue);
1400 // add implicit direct reference from each C++ function to its eh info
1401 for (const macho_section<P>* sect=sectionsStart; sect < sectionsEnd; ++sect) {
1402 if ( ((sect->flags() & SECTION_TYPE) == S_COALESCED) && (strcmp(sect->sectname(), "__eh_frame") == 0) ) {
1403 for (std::map<uint32_t, BaseAtom*>::iterator it=fAddrToAtom.begin(); it != fAddrToAtom.end(); it++) {
1404 // note: this algorithm depens on the map iterator returning entries in address order
1405 if ( (it->first >= sect->addr()) && (it->first < sect->addr()+sect->size()) ) {
1406 uint32_t ehAtomAddress = it->first;
1407 BaseAtom* ehAtom = it->second;
1408 const char* ehName = ehAtom->getName();
1409 if ( (ehName != NULL) && (strcmp(&ehName[strlen(ehName)-3], ".eh") == 0) )
1410 makeReferenceToEH(ehName, ehAtomAddress, sect);
1417 //for (std::map<uint32_t, BaseAtom*>::iterator it=fAddrToAtom.begin(); it != fAddrToAtom.end(); it++) {
1418 // fprintf(stderr, "[0x%0X -> 0x%0llX) : %s\n", it->first, it->first+it->second->getSize(), it->second->getDisplayName());
1421 // add translation unit info from dwarf
1423 if ( (fDebugInfo == kDebugInfoDwarf) && (fOptions.fDebugInfoStripping != ObjectFile::ReaderOptions::kDebugInfoNone) ) {
1424 // compiler sometimes emits emtpty dwarf sections when there is no debug info, skip those
1425 if ( (fDwarfDebugInfoSect != NULL) && (fDwarfDebugInfoSect->size() != 0) ) {
1426 if ( !read_comp_unit(&fDwarfTranslationUnitFile, &fDwarfTranslationUnitDir, &stmtList) ) {
1427 // if can't parse dwarf, warn and give up
1428 fDwarfTranslationUnitFile = NULL;
1429 fDwarfTranslationUnitDir = NULL;
1430 fprintf(stderr, "ld64: warning can't parse dwarf compilation unit info in %s\n", this->getPath());
1431 fDebugInfo = kDebugInfoNone;
1436 // add line number info to atoms from dwarf
1437 if ( (fDebugInfo == kDebugInfoDwarf) && (fOptions.fDebugInfoStripping != ObjectFile::ReaderOptions::kDebugInfoNone) ) {
1438 // file with just data will have no __debug_line info
1439 if ( (fDwarfDebugLineSect != NULL) && (fDwarfDebugLineSect->size() != 0) && (fAddrToAtom.size() != 0) ) {
1440 // validate stmt_list
1441 if ( (stmtList != (uint64_t)-1) && (stmtList < fDwarfDebugLineSect->size()) ) {
1442 const uint8_t* debug_line = (uint8_t*)(fHeader) + fDwarfDebugLineSect->offset();
1443 if ( debug_line != NULL ) {
1444 struct line_reader_data* lines = line_open(&debug_line[stmtList],
1445 fDwarfDebugLineSect->size() - stmtList, E::little_endian);
1446 struct line_info result;
1447 ObjectFile::Atom* curAtom = NULL;
1448 uint32_t curAtomOffset = 0;
1449 uint32_t curAtomAddress = 0;
1450 uint32_t curAtomSize = 0;
1451 while ( line_next (lines, &result, line_stop_pc) ) {
1452 // for performance, see if in next pc is in current atom
1453 if ( (curAtom != NULL) && (curAtomAddress <= result.pc) && (result.pc < (curAtomAddress+curAtomSize)) ) {
1454 curAtomOffset = result.pc - curAtomAddress;
1456 // or pc at end of current atom
1457 else if ( result.end_of_sequence && (curAtom != NULL) && (result.pc == (curAtomAddress+curAtomSize)) ) {
1458 curAtomOffset = result.pc - curAtomAddress;
1461 // do slow look up of atom by address
1462 AtomAndOffset ao = this->findAtomAndOffset(result.pc);
1464 if ( curAtom == NULL )
1465 break; // file has line info but no functions
1466 curAtomOffset = ao.offset;
1467 curAtomAddress = result.pc - ao.offset;
1468 curAtomSize = curAtom->getSize();
1470 const char* filename;
1471 std::map<uint32_t,const char*>::iterator pos = fDwarfIndexToFile.find(result.file);
1472 if ( pos == fDwarfIndexToFile.end() ) {
1473 filename = line_file(lines, result.file);
1474 fDwarfIndexToFile[result.file] = filename;
1477 filename = pos->second;
1479 ObjectFile::LineInfo info;
1480 info.atomOffset = curAtomOffset;
1481 info.fileName = filename;
1482 info.lineNumber = result.line;
1483 //fprintf(stderr, "addr=0x%08llX, line=%lld, file=%s, atom=%s, atom.size=0x%X, end=%d\n",
1484 // result.pc, result.line, filename, curAtom->getDisplayName(), curAtomSize, result.end_of_sequence);
1485 ((BaseAtom*)curAtom)->addLineInfo(info);
1486 if ( result.end_of_sequence ) {
1493 fprintf(stderr, "ld64: warning could not parse dwarf line number info in %s\n", this->getPath());
1499 // if no dwarf, try processing stabs debugging info
1500 if ( (fDebugInfo == kDebugInfoNone) && (fOptions.fDebugInfoStripping != ObjectFile::ReaderOptions::kDebugInfoNone) ) {
1501 // scan symbol table for stabs entries
1502 fStabs.reserve(fSymbolCount); // reduce re-allocations
1503 BaseAtom* currentAtom = NULL;
1504 pint_t currentAtomAddress = 0;
1505 enum { start, inBeginEnd, inFun } state = start;
1506 for (uint32_t symbolIndex = 0; symbolIndex < fSymbolCount; ++symbolIndex ) {
1507 const macho_nlist<P>* sym = &fSymbols[symbolIndex];
1508 bool useStab = true;
1509 uint8_t type = sym->n_type();
1510 const char* symString = (sym->n_strx() != 0) ? &fStrings[sym->n_strx()] : NULL;
1511 if ( (type & N_STAB) != 0 ) {
1512 fDebugInfo = (fHasUUID ? kDebugInfoStabsUUID : kDebugInfoStabs);
1516 stab.other = sym->n_sect();
1517 stab.desc = sym->n_desc();
1518 stab.value = sym->n_value();
1524 // beginning of function block
1526 // fall into case to lookup atom by addresss
1529 currentAtomAddress = sym->n_value();
1530 currentAtom = (BaseAtom*)this->findAtomAndOffset(currentAtomAddress).atom;
1531 if ( currentAtom != NULL ) {
1532 stab.atom = currentAtom;
1533 stab.string = symString;
1536 fprintf(stderr, "can't find atom for stabs BNSYM at %08llX in %s\n",
1537 (uint64_t)sym->n_value(), path);
1544 // not associated with an atom, just copy
1545 stab.string = symString;
1548 // n_value field is NOT atom address ;-(
1549 // need to find atom by name match
1550 const char* colon = strchr(symString, ':');
1551 if ( colon != NULL ) {
1552 // build underscore leading name
1553 int nameLen = colon - symString;
1554 char symName[nameLen+2];
1555 strlcpy(&symName[1], symString, nameLen+1);
1557 symName[nameLen+1] = '\0';
1558 currentAtom = findAtomByName(symName);
1559 if ( currentAtom != NULL ) {
1560 stab.atom = currentAtom;
1561 stab.string = symString;
1564 if ( stab.atom == NULL ) {
1565 fprintf(stderr, "can't find atom for N_GSYM stabs %s in %s\n", symString, path);
1570 // old style stabs without BNSYM
1572 currentAtomAddress = sym->n_value();
1573 currentAtom = (BaseAtom*)this->findAtomAndOffset(currentAtomAddress).atom;
1574 if ( currentAtom != NULL ) {
1575 stab.atom = currentAtom;
1576 stab.string = symString;
1579 fprintf(stderr, "can't find atom for stabs FUN at %08llX in %s\n",
1580 (uint64_t)currentAtomAddress, path);
1585 stab.string = symString;
1591 stab.string = symString;
1592 // -gfull built .o file
1595 fprintf(stderr, "unknown stabs type 0x%X in %s\n", type, path);
1599 stab.atom = currentAtom;
1607 BaseAtom* nestedAtom = (BaseAtom*)this->findAtomAndOffset(sym->n_value()).atom;
1608 if ( nestedAtom != NULL ) {
1609 stab.atom = nestedAtom;
1610 stab.string = symString;
1613 fprintf(stderr, "can't find atom for stabs 0x%X at %08llX in %s\n",
1614 type, (uint64_t)sym->n_value(), path);
1620 // adjust value to be offset in atom
1621 stab.value -= currentAtomAddress;
1623 stab.string = symString;
1630 if ( sym->n_sect() != 0 ) {
1631 // found another start stab, must be really old stabs...
1632 currentAtomAddress = sym->n_value();
1633 currentAtom = (BaseAtom*)this->findAtomAndOffset(currentAtomAddress).atom;
1634 if ( currentAtom != NULL ) {
1635 stab.atom = currentAtom;
1636 stab.string = symString;
1639 fprintf(stderr, "can't find atom for stabs FUN at %08llX in %s\n",
1640 (uint64_t)currentAtomAddress, path);
1644 // found ending stab, switch back to start state
1645 stab.string = symString;
1646 stab.atom = currentAtom;
1654 // adjust value to be offset in atom
1655 stab.value -= currentAtomAddress;
1656 stab.atom = currentAtom;
1659 stab.string = symString;
1663 stab.atom = currentAtom;
1664 stab.string = symString;
1669 // add to list of stabs for this .o file
1671 fStabs.push_back(stab);
1678 // special case precompiled header .o file (which has no content) to have one empty atom
1679 if ( fAtoms.size() == 0 ) {
1680 int pathLen = strlen(path);
1681 if ( (pathLen > 6) && (strcmp(&path[pathLen-6], ".gch.o")==0) ) {
1682 ObjectFile::Atom* phony = new AnonymousAtom<A>(*this, (uint32_t)0);
1683 //phony->fSynthesizedName = ".gch.o";
1684 fAtoms.push_back(phony);
1691 void Reader<x86_64>::validSectionType(uint8_t type)
1694 case S_SYMBOL_STUBS:
1695 throw "symbol_stub sections not valid in x86_64 object files";
1696 case S_LAZY_SYMBOL_POINTERS:
1697 throw "lazy pointer sections not valid in x86_64 object files";
1698 case S_NON_LAZY_SYMBOL_POINTERS:
1699 throw "non lazy pointer sections not valid in x86_64 object files";
1703 template <typename A>
1704 void Reader<A>::validSectionType(uint8_t type)
1708 template <typename A>
1709 bool Reader<A>::getTranslationUnitSource(const char** dir, const char** name) const
1711 if ( fDebugInfo == kDebugInfoDwarf ) {
1712 *dir = fDwarfTranslationUnitDir;
1713 *name = fDwarfTranslationUnitFile;
1719 template <typename A>
1720 BaseAtom* Reader<A>::findAtomByName(const char* name)
1722 // first search the more important atoms
1723 for (std::map<uint32_t, BaseAtom*>::iterator it=fAddrToAtom.begin(); it != fAddrToAtom.end(); it++) {
1724 const char* atomName = it->second->getName();
1725 if ( (atomName != NULL) && (strcmp(atomName, name) == 0) ) {
1729 // try all atoms, because this might have been a tentative definition
1730 for (std::vector<ObjectFile::Atom*>::iterator it=fAtoms.begin(); it != fAtoms.end(); it++) {
1731 BaseAtom* atom = (BaseAtom*)(*it);
1732 const char* atomName = atom->getName();
1733 if ( (atomName != NULL) && (strcmp(atomName, name) == 0) ) {
1740 template <typename A>
1741 Reference<A>* Reader<A>::makeReference(Kinds kind, uint32_t atAddr, uint32_t toAddr)
1743 return new Reference<A>(kind, findAtomAndOffset(atAddr), findAtomAndOffset(toAddr));
1746 template <typename A>
1747 Reference<A>* Reader<A>::makeReference(Kinds kind, uint32_t atAddr, uint32_t fromAddr, uint32_t toAddr)
1749 return new Reference<A>(kind, findAtomAndOffset(atAddr), findAtomAndOffset(fromAddr), findAtomAndOffset(toAddr));
1752 template <typename A>
1753 Reference<A>* Reader<A>::makeReferenceWithToBase(Kinds kind, uint32_t atAddr, uint32_t toAddr, uint32_t toBaseAddr)
1755 return new Reference<A>(kind, findAtomAndOffset(atAddr), findAtomAndOffset(toBaseAddr, toAddr));
1758 template <typename A>
1759 Reference<A>* Reader<A>::makeReferenceWithToBase(Kinds kind, uint32_t atAddr, uint32_t fromAddr, uint32_t toAddr, uint32_t toBaseAddr)
1761 return new Reference<A>(kind, findAtomAndOffset(atAddr), findAtomAndOffset(fromAddr), findAtomAndOffset(toBaseAddr, toAddr));
1764 template <typename A>
1765 Reference<A>* Reader<A>::makeByNameReference(Kinds kind, uint32_t atAddr, const char* toName, uint32_t toOffset)
1767 return new Reference<A>(kind, findAtomAndOffset(atAddr), toName, toOffset);
1770 template <typename A>
1771 Reference<A>* Reader<A>::makeReferenceToEH(const char* ehName, pint_t ehAtomAddress, const macho_section<P>* ehSect)
1773 // add a direct reference from function atom to its eh frame atom
1774 const uint8_t* ehContent = (const uint8_t*)(fHeader) + ehAtomAddress - ehSect->addr() + ehSect->offset();
1775 int32_t deltaMinus8 = P::getP(*(pint_t*)(&ehContent[8])); // offset 8 in eh info is delta to function
1776 uint32_t funcAddr = ehAtomAddress + deltaMinus8 + 8;
1777 return makeReference(A::kNoFixUp, funcAddr, ehAtomAddress);
1782 Reference<x86_64>* Reader<x86_64>::makeByNameReference(Kinds kind, uint32_t atAddr, const char* toName, uint32_t toOffset)
1784 // x86_64 uses external relocations everywhere, so external relocations do not imply by-name references
1785 // instead check scope of target
1786 BaseAtom* target = findAtomByName(toName);
1787 if ( (target != NULL) && (target->getScope() == ObjectFile::Atom::scopeTranslationUnit) )
1788 return new Reference<x86_64>(kind, findAtomAndOffset(atAddr), AtomAndOffset(target, toOffset));
1790 return new Reference<x86_64>(kind, findAtomAndOffset(atAddr), toName, toOffset);
1794 Reference<x86_64>* Reader<x86_64>::makeReferenceToSymbol(Kinds kind, uint32_t atAddr, const macho_nlist<P>* toSymbol, uint32_t toOffset)
1796 // x86_64 uses external relocations everywhere, so external relocations do not imply by-name references
1797 // instead check scope of target
1798 if ( ((toSymbol->n_type() & N_TYPE) == N_SECT) && ((toSymbol->n_type() & N_EXT) == 0) )
1799 return new Reference<x86_64>(kind, findAtomAndOffset(atAddr), findAtomAndOffset(toSymbol->n_value(), toSymbol->n_value()+toOffset));
1801 return new Reference<x86_64>(kind, findAtomAndOffset(atAddr), &fStrings[toSymbol->n_strx()], toOffset);
1806 Reference<x86_64>* Reader<x86_64>::makeReferenceToEH(const char* ehName, pint_t ehAtomAddress, const macho_section<P>* ehSect)
1808 // add a direct reference from function atom to its eh frame atom
1809 // for x86_64 the __eh_frame section contains the addends, so need to use relocs to find target
1810 uint32_t ehAtomDeltaSectionOffset = ehAtomAddress + 8 - ehSect->addr(); // offset 8 in eh info is delta to function
1811 const macho_relocation_info<P>* relocs = (macho_relocation_info<P>*)((char*)(fHeader) + ehSect->reloff());
1812 const macho_relocation_info<P>* relocsEnd = &relocs[ehSect->nreloc()];
1813 for (const macho_relocation_info<P>* reloc = relocs; reloc < relocsEnd; ++reloc) {
1814 if ( (reloc->r_address() == ehAtomDeltaSectionOffset) && (reloc->r_type() == X86_64_RELOC_UNSIGNED) ) {
1815 uint32_t funcAddr = fSymbols[reloc->r_symbolnum()].n_value();
1816 return makeReference(x86_64::kNoFixUp, funcAddr, ehAtomAddress);
1819 fprintf(stderr, "ld64: warning, can't find matching function for eh symbol %s\n", ehName);
1823 template <typename A>
1824 AtomAndOffset Reader<A>::findAtomAndOffset(uint32_t addr)
1826 // STL has no built-in for "find largest key that is same or less than"
1827 std::map<uint32_t, BaseAtom*>::iterator it = fAddrToAtom.upper_bound(addr);
1828 --it; // upper_bound gets us next key, so we back up one
1829 AtomAndOffset result;
1830 result.atom = it->second;
1831 result.offset = addr - it->first;
1832 //fprintf(stderr, "findAtomAndOffset(0x%0X) ==> %s (0x%0X -> 0x%0llX)\n",
1833 // addr, result.atom->getDisplayName(), it->first, it->first+result.atom->getSize());
1837 // "scattered" relocations enable you to offset into an atom past the end of it
1838 // baseAddr is the address of the target atom,
1839 // realAddr is the points into it
1840 template <typename A>
1841 AtomAndOffset Reader<A>::findAtomAndOffset(uint32_t baseAddr, uint32_t realAddr)
1843 std::map<uint32_t, BaseAtom*>::iterator it = fAddrToAtom.find(baseAddr);
1844 if ( it != fAddrToAtom.end() ) {
1845 AtomAndOffset result;
1846 result.atom = it->second;
1847 result.offset = realAddr - it->first;
1848 //fprintf(stderr, "findAtomAndOffset(0x%08X, 0x%08X) => %s + 0x%08X\n", baseAddr, realAddr, result.atom->getDisplayName(), result.offset);
1851 // getting here means we have a scattered relocation to an address without a label
1852 // we should never get here...
1853 // one case we do get here is because sometimes the compiler generates non-lazy pointers in the __data section
1854 return findAtomAndOffset(realAddr);
1858 /* Skip over a LEB128 value (signed or unsigned). */
1860 skip_leb128 (const uint8_t ** offset, const uint8_t * end)
1862 while (*offset != end && **offset >= 0x80)
1868 /* Read a ULEB128 into a 64-bit word. Return (uint64_t)-1 on overflow
1869 or error. On overflow, skip past the rest of the uleb128. */
1871 read_uleb128 (const uint8_t ** offset, const uint8_t * end)
1873 uint64_t result = 0;
1880 return (uint64_t) -1;
1882 b = **offset & 0x7f;
1884 if (bit >= 64 || b << bit >> bit != b)
1885 result = (uint64_t) -1;
1887 result |= b << bit, bit += 7;
1888 } while (*(*offset)++ >= 0x80);
1893 /* Skip over a DWARF attribute of form FORM. */
1894 template <typename A>
1895 bool Reader<A>::skip_form(const uint8_t ** offset, const uint8_t * end, uint64_t form,
1896 uint8_t addr_size, bool dwarf64)
1906 case DW_FORM_block2:
1907 if (end - *offset < 2)
1909 sz = 2 + A::P::E::get16(*(uint16_t*)offset);
1912 case DW_FORM_block4:
1913 if (end - *offset < 4)
1915 sz = 2 + A::P::E::get32(*(uint32_t*)offset);
1933 case DW_FORM_string:
1934 while (*offset != end && **offset)
1943 sz = read_uleb128 (offset, end);
1946 case DW_FORM_block1:
1954 case DW_FORM_ref_udata:
1955 skip_leb128 (offset, end);
1959 case DW_FORM_ref_addr:
1960 sz = dwarf64 ? 8 : 4;
1966 if (end - *offset < sz)
1972 // Look at the compilation unit DIE and determine
1973 // its NAME, compilation directory (in COMP_DIR) and its
1974 // line number information offset (in STMT_LIST). NAME and COMP_DIR
1975 // may be NULL (especially COMP_DIR) if they are not in the .o file;
1976 // STMT_LIST will be (uint64_t) -1.
1978 // At present this assumes that there's only one compilation unit DIE.
1980 template <typename A>
1981 bool Reader<A>::read_comp_unit(const char ** name, const char ** comp_dir,
1982 uint64_t *stmt_list)
1984 const uint8_t * debug_info;
1985 const uint8_t * debug_abbrev;
1988 const uint8_t * end;
1989 const uint8_t * enda;
1992 uint64_t abbrev_base;
1994 uint8_t address_size;
1999 *stmt_list = (uint64_t) -1;
2001 if ( (fDwarfDebugInfoSect == NULL) || (fDwarfDebugAbbrevSect == NULL) )
2004 debug_info = (uint8_t*)(fHeader) + fDwarfDebugInfoSect->offset();
2005 debug_abbrev = (uint8_t*)(fHeader) + fDwarfDebugAbbrevSect->offset();
2008 if (fDwarfDebugInfoSect->size() < 12)
2009 /* Too small to be a real debug_info section. */
2011 sz = A::P::E::get32(*(uint32_t*)di);
2013 dwarf64 = sz == 0xffffffff;
2015 sz = A::P::E::get64(*(uint64_t*)di), di += 8;
2016 else if (sz > 0xffffff00)
2017 /* Unknown dwarf format. */
2020 /* Verify claimed size. */
2021 if (sz + (di - debug_info) > fDwarfDebugInfoSect->size() || sz <= (dwarf64 ? 23 : 11))
2024 vers = A::P::E::get16(*(uint16_t*)di);
2025 if (vers < 2 || vers > 3)
2026 /* DWARF version wrong for this code.
2027 Chances are we could continue anyway, but we don't know for sure. */
2031 /* Find the debug_abbrev section. */
2032 abbrev_base = dwarf64 ? A::P::E::get64(*(uint64_t*)di) : A::P::E::get32(*(uint32_t*)di);
2033 di += dwarf64 ? 8 : 4;
2035 if (abbrev_base > fDwarfDebugAbbrevSect->size())
2037 da = debug_abbrev + abbrev_base;
2038 enda = debug_abbrev + fDwarfDebugAbbrevSect->size();
2040 address_size = *di++;
2042 /* Find the abbrev number we're looking for. */
2044 abbrev = read_uleb128 (&di, end);
2045 if (abbrev == (uint64_t) -1)
2048 /* Skip through the debug_abbrev section looking for that abbrev. */
2051 uint64_t this_abbrev = read_uleb128 (&da, enda);
2054 if (this_abbrev == abbrev)
2055 /* This is almost always taken. */
2057 skip_leb128 (&da, enda); /* Skip the tag. */
2060 da++; /* Skip the DW_CHILDREN_* value. */
2063 attr = read_uleb128 (&da, enda);
2064 skip_leb128 (&da, enda);
2065 } while (attr != 0 && attr != (uint64_t) -1);
2070 /* Check that the abbrev is one for a DW_TAG_compile_unit. */
2071 if (read_uleb128 (&da, enda) != DW_TAG_compile_unit)
2075 da++; /* Skip the DW_CHILDREN_* value. */
2077 /* Now, go through the DIE looking for DW_AT_name,
2078 DW_AT_comp_dir, and DW_AT_stmt_list. */
2081 uint64_t attr = read_uleb128 (&da, enda);
2082 uint64_t form = read_uleb128 (&da, enda);
2084 if (attr == (uint64_t) -1)
2089 if (form == DW_FORM_indirect)
2090 form = read_uleb128 (&di, end);
2092 if (attr == DW_AT_name && form == DW_FORM_string)
2093 *name = (const char *) di;
2094 else if (attr == DW_AT_comp_dir && form == DW_FORM_string)
2095 *comp_dir = (const char *) di;
2096 /* Really we should support DW_FORM_strp here, too, but
2097 there's usually no reason for the producer to use that form
2098 for the DW_AT_name and DW_AT_comp_dir attributes. */
2099 else if (attr == DW_AT_stmt_list && form == DW_FORM_data4)
2100 *stmt_list = A::P::E::get32(*(uint32_t*)di);
2101 else if (attr == DW_AT_stmt_list && form == DW_FORM_data8)
2102 *stmt_list = A::P::E::get64(*(uint64_t*)di);
2103 if (! skip_form (&di, end, form, address_size, dwarf64))
2108 template <typename A>
2109 const char* Reader<A>::assureFullPath(const char* path)
2111 if ( path[0] == '/' )
2113 char cwdbuff[MAXPATHLEN];
2114 if ( getcwd(cwdbuff, MAXPATHLEN) != NULL ) {
2116 asprintf(&result, "%s/%s", cwdbuff, path);
2117 if ( result != NULL )
2126 // To implement architecture xxx, you must write template specializations for the following six methods:
2127 // Reader<xxx>::validFile()
2128 // Reader<xxx>::addRelocReference()
2129 // Reference<xxx>::getDescription()
2135 bool Reader<ppc>::validFile(const uint8_t* fileContent)
2137 const macho_header<P>* header = (const macho_header<P>*)fileContent;
2138 if ( header->magic() != MH_MAGIC )
2140 if ( header->cputype() != CPU_TYPE_POWERPC )
2142 if ( header->filetype() != MH_OBJECT )
2148 bool Reader<ppc64>::validFile(const uint8_t* fileContent)
2150 const macho_header<P>* header = (const macho_header<P>*)fileContent;
2151 if ( header->magic() != MH_MAGIC_64 )
2153 if ( header->cputype() != CPU_TYPE_POWERPC64 )
2155 if ( header->filetype() != MH_OBJECT )
2161 bool Reader<x86>::validFile(const uint8_t* fileContent)
2163 const macho_header<P>* header = (const macho_header<P>*)fileContent;
2164 if ( header->magic() != MH_MAGIC )
2166 if ( header->cputype() != CPU_TYPE_I386 )
2168 if ( header->filetype() != MH_OBJECT )
2174 bool Reader<x86_64>::validFile(const uint8_t* fileContent)
2176 const macho_header<P>* header = (const macho_header<P>*)fileContent;
2177 if ( header->magic() != MH_MAGIC_64 )
2179 if ( header->cputype() != CPU_TYPE_X86_64 )
2181 if ( header->filetype() != MH_OBJECT )
2187 template <typename A>
2188 bool Reader<A>::isWeakImportSymbol(const macho_nlist<P>* sym)
2190 return ( ((sym->n_type() & N_TYPE) == N_UNDF) && ((sym->n_desc() & N_WEAK_REF) != 0) );
2194 bool Reader<ppc64>::addRelocReference(const macho_section<ppc64::P>* sect, const macho_relocation_info<ppc64::P>* reloc)
2196 return addRelocReference_powerpc(sect, reloc);
2200 bool Reader<ppc>::addRelocReference(const macho_section<ppc::P>* sect, const macho_relocation_info<ppc::P>* reloc)
2202 return addRelocReference_powerpc(sect, reloc);
2207 // ppc and ppc64 both use the same relocations, so process them in one common routine
2209 template <typename A>
2210 bool Reader<A>::addRelocReference_powerpc(const macho_section<typename A::P>* sect,
2211 const macho_relocation_info<typename A::P>* reloc)
2216 int32_t displacement = 0;
2217 uint32_t instruction = 0;
2218 uint32_t offsetInTarget;
2220 bool result = false;
2221 if ( (reloc->r_address() & R_SCATTERED) == 0 ) {
2222 const macho_relocation_info<P>* nextReloc = &reloc[1];
2223 const char* targetName = NULL;
2224 bool weakImport = false;
2225 fixUpPtr = (uint32_t*)((char*)(fHeader) + sect->offset() + reloc->r_address());
2226 if ( reloc->r_type() != PPC_RELOC_PAIR )
2227 instruction = BigEndian::get32(*fixUpPtr);
2228 srcAddr = sect->addr() + reloc->r_address();
2229 if ( reloc->r_extern() ) {
2230 const macho_nlist<P>* targetSymbol = &fSymbols[reloc->r_symbolnum()];
2231 targetName = &fStrings[targetSymbol->n_strx()];
2232 weakImport = this->isWeakImportSymbol(targetSymbol);
2234 switch ( reloc->r_type() ) {
2235 case PPC_RELOC_BR24:
2237 if ( (instruction & 0x4C000000) == 0x48000000 ) {
2238 displacement = (instruction & 0x03FFFFFC);
2239 if ( (displacement & 0x02000000) != 0 )
2240 displacement |= 0xFC000000;
2243 printf("bad instruction for BR24 reloc");
2245 if ( reloc->r_extern() ) {
2246 offsetInTarget = srcAddr + displacement;
2248 makeByNameReference(A::kBranch24WeakImport, srcAddr, targetName, offsetInTarget);
2250 makeByNameReference(A::kBranch24, srcAddr, targetName, offsetInTarget);
2253 dstAddr = srcAddr + displacement;
2254 // if this is a branch to a stub, we need to see if the stub is for a weak imported symbol
2255 ObjectFile::Atom* atom = findAtomAndOffset(dstAddr).atom;
2256 if ( (atom->getSymbolTableInclusion() == ObjectFile::Atom::kSymbolTableNotIn)
2257 && ((AnonymousAtom<A>*)atom)->isWeakImportStub() )
2258 makeReference(A::kBranch24WeakImport, srcAddr, dstAddr);
2260 makeReference(A::kBranch24, srcAddr, dstAddr);
2264 case PPC_RELOC_BR14:
2266 displacement = (instruction & 0x0000FFFC);
2267 if ( (displacement & 0x00008000) != 0 )
2268 displacement |= 0xFFFF0000;
2269 if ( reloc->r_extern() ) {
2270 offsetInTarget = srcAddr + displacement;
2271 makeByNameReference(A::kBranch14, srcAddr, targetName, offsetInTarget);
2274 dstAddr = srcAddr + displacement;
2275 makeReference(A::kBranch14, srcAddr, dstAddr);
2279 case PPC_RELOC_PAIR:
2280 // skip, processed by a previous look ahead
2282 case PPC_RELOC_LO16:
2284 if ( nextReloc->r_type() != PPC_RELOC_PAIR ) {
2285 printf("PPC_RELOC_LO16 missing following pair\n");
2289 lowBits = (instruction & 0xFFFF);
2290 if ( reloc->r_extern() ) {
2291 offsetInTarget = (nextReloc->r_address() << 16) | ((uint32_t)lowBits & 0x0000FFFF);
2292 makeByNameReference(A::kAbsLow16, srcAddr, targetName, offsetInTarget);
2295 dstAddr = (nextReloc->r_address() << 16) + ((uint32_t)lowBits & 0x0000FFFF);
2296 makeReference(A::kAbsLow16, srcAddr, dstAddr);
2300 case PPC_RELOC_LO14:
2302 if ( nextReloc->r_type() != PPC_RELOC_PAIR ) {
2303 printf("PPC_RELOC_LO14 missing following pair\n");
2307 lowBits = (instruction & 0xFFFC);
2308 if ( reloc->r_extern() ) {
2309 offsetInTarget = (nextReloc->r_address() << 16) | ((uint32_t)lowBits & 0x0000FFFF);
2310 makeByNameReference(A::kAbsLow14, srcAddr, targetName, offsetInTarget);
2313 dstAddr = (nextReloc->r_address() << 16) | ((uint32_t)lowBits & 0x0000FFFF);
2314 Reference<A>* ref = makeReference(A::kAbsLow14, srcAddr, dstAddr);
2315 BaseAtom* target = ((BaseAtom*)&(ref->getTarget()));
2316 if ( target != NULL )
2317 target->alignAtLeast(3);
2321 case PPC_RELOC_HI16:
2323 if ( nextReloc->r_type() != PPC_RELOC_PAIR ) {
2324 printf("PPC_RELOC_HI16 missing following pair\n");
2328 if ( reloc->r_extern() ) {
2329 offsetInTarget = ((instruction & 0x0000FFFF) << 16) | (nextReloc->r_address() & 0x0000FFFF);
2330 makeByNameReference(A::kAbsHigh16, srcAddr, targetName, offsetInTarget);
2333 dstAddr = ((instruction & 0x0000FFFF) << 16) | (nextReloc->r_address() & 0x0000FFFF);
2334 makeReference(A::kAbsHigh16, srcAddr, dstAddr);
2338 case PPC_RELOC_HA16:
2340 if ( nextReloc->r_type() != PPC_RELOC_PAIR ) {
2341 printf("PPC_RELOC_HA16 missing following pair\n");
2345 lowBits = (nextReloc->r_address() & 0x0000FFFF);
2346 if ( reloc->r_extern() ) {
2347 offsetInTarget = ((instruction & 0x0000FFFF) << 16) + (int32_t)lowBits;
2348 makeByNameReference(A::kAbsHigh16AddLow, srcAddr, targetName, offsetInTarget);
2351 dstAddr = ((instruction & 0x0000FFFF) << 16) + (int32_t)lowBits;
2352 makeReference(A::kAbsHigh16AddLow, srcAddr, dstAddr);
2356 case PPC_RELOC_VANILLA:
2358 pint_t pointerValue = P::getP(*((pint_t*)fixUpPtr));
2359 if ( reloc->r_extern() ) {
2361 makeByNameReference(A::kPointerWeakImport, srcAddr, targetName, pointerValue);
2363 makeByNameReference(A::kPointer, srcAddr, targetName, pointerValue);
2366 makeReference(A::kPointer, srcAddr, pointerValue);
2370 case PPC_RELOC_JBSR:
2371 // this is from -mlong-branch codegen. We ignore the jump island
2372 if ( nextReloc->r_type() != PPC_RELOC_PAIR ) {
2373 printf("PPC_RELOC_JBSR missing following pair\n");
2377 makeReference(A::kBranch24, srcAddr, nextReloc->r_address());
2380 printf("unknown relocation type %d\n", reloc->r_type());
2384 const macho_scattered_relocation_info<P>* sreloc = (macho_scattered_relocation_info<P>*)reloc;
2385 srcAddr = sect->addr() + sreloc->r_address();
2386 dstAddr = sreloc->r_value();
2387 uint32_t betterDstAddr;
2388 fixUpPtr = (uint32_t*)((char*)(fHeader) + sect->offset() + sreloc->r_address());
2389 const macho_scattered_relocation_info<P>* nextSReloc = &sreloc[1];
2390 const macho_relocation_info<P>* nextReloc = &reloc[1];
2391 // file format allows pair to be scattered or not
2392 bool nextRelocIsPair = false;
2393 uint32_t nextRelocAddress = 0;
2394 uint32_t nextRelocValue = 0;
2395 if ( (nextReloc->r_address() & R_SCATTERED) == 0 ) {
2396 if ( nextReloc->r_type() == PPC_RELOC_PAIR ) {
2397 nextRelocIsPair = true;
2398 nextRelocAddress = nextReloc->r_address();
2403 if ( nextSReloc->r_type() == PPC_RELOC_PAIR ) {
2404 nextRelocIsPair = true;
2405 nextRelocAddress = nextSReloc->r_address();
2406 nextRelocValue = nextSReloc->r_value();
2410 switch (sreloc->r_type()) {
2411 case PPC_RELOC_VANILLA:
2413 betterDstAddr = P::getP(*(pint_t*)fixUpPtr);
2414 //fprintf(stderr, "scattered pointer reloc: srcAddr=0x%08X, dstAddr=0x%08X, pointer=0x%08X\n", srcAddr, dstAddr, betterDstAddr);
2415 // with a scattered relocation we get both the target (sreloc->r_value()) and the target+offset (*fixUpPtr)
2416 makeReferenceWithToBase(A::kPointer, srcAddr, betterDstAddr, dstAddr);
2419 case PPC_RELOC_BR14:
2421 instruction = BigEndian::get32(*fixUpPtr);
2422 displacement = (instruction & 0x0000FFFC);
2423 if ( (displacement & 0x00008000) != 0 )
2424 displacement |= 0xFFFF0000;
2425 betterDstAddr = srcAddr+displacement;
2426 //fprintf(stderr, "betterDstAddr=0x%08X, srcAddr=0x%08X, displacement=0x%08X\n", betterDstAddr, srcAddr, displacement);
2427 makeReferenceWithToBase(A::kBranch14, srcAddr, betterDstAddr, dstAddr);
2430 case PPC_RELOC_BR24:
2432 instruction = BigEndian::get32(*fixUpPtr);
2433 if ( (instruction & 0x4C000000) == 0x48000000 ) {
2434 displacement = (instruction & 0x03FFFFFC);
2435 if ( (displacement & 0x02000000) != 0 )
2436 displacement |= 0xFC000000;
2437 betterDstAddr = srcAddr+displacement;
2438 makeReferenceWithToBase(A::kBranch24, srcAddr, betterDstAddr, dstAddr);
2442 case PPC_RELOC_LO16_SECTDIFF:
2444 if ( ! nextRelocIsPair ) {
2445 printf("PPC_RELOC_LO16_SECTDIFF missing following PAIR\n");
2448 instruction = BigEndian::get32(*fixUpPtr);
2449 lowBits = (instruction & 0xFFFF);
2450 displacement = (nextRelocAddress << 16) | ((uint32_t)lowBits & 0x0000FFFF);
2451 makeReferenceWithToBase(A::kPICBaseLow16, srcAddr, nextRelocValue, nextRelocValue + displacement, dstAddr);
2454 case PPC_RELOC_LO14_SECTDIFF:
2456 if ( ! nextRelocIsPair ) {
2457 printf("PPC_RELOC_LO14_SECTDIFF missing following PAIR\n");
2460 instruction = BigEndian::get32(*fixUpPtr);
2461 lowBits = (instruction & 0xFFFC);
2462 displacement = (nextRelocAddress << 16) | ((uint32_t)lowBits & 0x0000FFFF);
2463 Reference<A>* ref = makeReferenceWithToBase(A::kPICBaseLow14, srcAddr, nextRelocValue, nextRelocValue + displacement, dstAddr);
2464 BaseAtom* target = ((BaseAtom*)&(ref->getTarget()));
2465 if ( target != NULL ) // can be NULL if target is turned into by-name reference
2466 target->alignAtLeast(3);
2469 case PPC_RELOC_HA16_SECTDIFF:
2471 if ( ! nextRelocIsPair ) {
2472 printf("PPC_RELOC_HA16_SECTDIFF missing following PAIR\n");
2475 instruction = BigEndian::get32(*fixUpPtr);
2476 lowBits = (nextRelocAddress & 0x0000FFFF);
2477 displacement = ((instruction & 0x0000FFFF) << 16) + (int32_t)lowBits;
2478 makeReferenceWithToBase(A::kPICBaseHigh16, srcAddr, nextRelocValue, nextRelocValue + displacement, dstAddr);
2481 case PPC_RELOC_LO14:
2483 if ( ! nextRelocIsPair ) {
2484 printf("PPC_RELOC_LO14 missing following PAIR\n");
2487 instruction = BigEndian::get32(*fixUpPtr);
2488 lowBits = (instruction & 0xFFFC);
2489 betterDstAddr = (nextRelocAddress << 16) + ((uint32_t)lowBits & 0x0000FFFF);
2490 makeReferenceWithToBase(A::kAbsLow14, srcAddr, betterDstAddr, dstAddr);
2493 case PPC_RELOC_LO16:
2495 if ( ! nextRelocIsPair ) {
2496 printf("PPC_RELOC_LO16 missing following PAIR\n");
2499 instruction = BigEndian::get32(*fixUpPtr);
2500 lowBits = (instruction & 0xFFFF);
2501 betterDstAddr = (nextRelocAddress << 16) + ((uint32_t)lowBits & 0x0000FFFF);
2502 makeReferenceWithToBase(A::kAbsLow16, srcAddr, betterDstAddr, dstAddr);
2505 case PPC_RELOC_HA16:
2507 if ( ! nextRelocIsPair ) {
2508 printf("PPC_RELOC_HA16 missing following PAIR\n");
2511 instruction = BigEndian::get32(*fixUpPtr);
2512 lowBits = (nextRelocAddress & 0xFFFF);
2513 betterDstAddr = ((instruction & 0xFFFF) << 16) + (int32_t)lowBits;
2514 makeReferenceWithToBase(A::kAbsHigh16AddLow, srcAddr, betterDstAddr, dstAddr);
2517 case PPC_RELOC_SECTDIFF:
2518 case PPC_RELOC_LOCAL_SECTDIFF:
2520 if ( ! nextRelocIsPair ) {
2521 printf("PPC_RELOC_SECTDIFF missing following pair\n");
2524 makeReference(pointerDiffKindForLength_powerpc(sreloc->r_length()), srcAddr, nextRelocValue, dstAddr);
2527 case PPC_RELOC_PAIR:
2529 case PPC_RELOC_HI16_SECTDIFF:
2530 printf("unexpected scattered relocation type PPC_RELOC_HI16_SECTDIFF\n");
2533 printf("unknown scattered relocation type %d\n", sreloc->r_type());
2540 ppc::ReferenceKinds Reader<ppc>::pointerDiffKindForLength_powerpc(uint8_t r_length)
2542 if ( r_length == 2 )
2543 return ppc::kPointerDiff32;
2545 throw "bad diff relocations r_length for ppc architecture";
2549 ppc64::ReferenceKinds Reader<ppc64>::pointerDiffKindForLength_powerpc(uint8_t r_length)
2551 if ( r_length == 2 )
2552 return ppc64::kPointerDiff32;
2553 else if ( r_length == 3 )
2554 return ppc64::kPointerDiff64;
2556 throw "bad diff relocations r_length for ppc64 architecture";
2560 bool Reader<x86>::addRelocReference(const macho_section<x86::P>* sect, const macho_relocation_info<x86::P>* reloc)
2565 bool result = false;
2566 if ( (reloc->r_address() & R_SCATTERED) == 0 ) {
2567 srcAddr = sect->addr() + reloc->r_address();
2568 fixUpPtr = (uint32_t*)((char*)(fHeader) + sect->offset() + reloc->r_address());
2569 switch ( reloc->r_type() ) {
2570 case GENERIC_RELOC_VANILLA:
2572 if ( reloc->r_length() != 2 )
2573 throw "bad vanilla relocation length";
2574 x86::ReferenceKinds kind;
2575 uint32_t pointerValue = E::get32(*fixUpPtr);
2576 if ( reloc->r_pcrel() ) {
2577 kind = x86::kPCRel32;
2578 pointerValue += srcAddr + sizeof(uint32_t);
2580 else if ( strcmp(sect->segname(), "__TEXT") == 0 ) {
2581 kind = x86::kAbsolute32;
2584 kind = x86::kPointer;
2586 if ( reloc->r_extern() ) {
2587 const macho_nlist<P>* targetSymbol = &fSymbols[reloc->r_symbolnum()];
2588 if ( this->isWeakImportSymbol(targetSymbol) )
2589 kind = x86::kPointerWeakImport;
2590 const char* targetName = &fStrings[targetSymbol->n_strx()];
2591 makeByNameReference(kind, srcAddr, targetName, pointerValue);
2594 // if this is a branch to a stub, we need to see if the stub is for a weak imported symbol
2595 ObjectFile::Atom* atom = findAtomAndOffset(pointerValue).atom;
2596 if ( reloc->r_pcrel() && (atom->getSymbolTableInclusion() == ObjectFile::Atom::kSymbolTableNotIn)
2597 && ((AnonymousAtom<x86>*)atom)->isWeakImportStub() )
2598 makeReference(x86::kPCRel32WeakImport, srcAddr, pointerValue);
2600 makeReference(kind, srcAddr, pointerValue);
2605 printf("unknown relocation type %d\n", reloc->r_type());
2609 const macho_scattered_relocation_info<P>* sreloc = (macho_scattered_relocation_info<P>*)reloc;
2610 srcAddr = sect->addr() + sreloc->r_address();
2611 dstAddr = sreloc->r_value();
2612 fixUpPtr = (uint32_t*)((char*)(fHeader) + sect->offset() + sreloc->r_address());
2613 const macho_scattered_relocation_info<P>* nextSReloc = &sreloc[1];
2614 const macho_relocation_info<P>* nextReloc = &reloc[1];
2615 pint_t betterDstAddr;
2616 // file format allows pair to be scattered or not
2617 bool nextRelocIsPair = false;
2618 uint32_t nextRelocAddress = 0;
2619 uint32_t nextRelocValue = 0;
2620 if ( (nextReloc->r_address() & R_SCATTERED) == 0 ) {
2621 if ( nextReloc->r_type() == PPC_RELOC_PAIR ) {
2622 nextRelocIsPair = true;
2623 nextRelocAddress = nextReloc->r_address();
2628 if ( nextSReloc->r_type() == PPC_RELOC_PAIR ) {
2629 nextRelocIsPair = true;
2630 nextRelocAddress = nextSReloc->r_address();
2631 nextRelocValue = nextSReloc->r_value();
2634 switch (sreloc->r_type()) {
2635 case GENERIC_RELOC_VANILLA:
2636 betterDstAddr = LittleEndian::get32(*fixUpPtr);
2637 //fprintf(stderr, "pointer reloc: srcAddr=0x%08X, dstAddr=0x%08X, pointer=0x%08lX\n", srcAddr, dstAddr, betterDstAddr);
2638 // with a scattered relocation we get both the target (sreloc->r_value()) and the target+offset (*fixUpPtr)
2639 if ( sreloc->r_pcrel() ) {
2640 betterDstAddr += srcAddr + 4;
2641 makeReferenceWithToBase(x86::kPCRel32, srcAddr, betterDstAddr, dstAddr);
2644 if ( strcmp(sect->segname(), "__TEXT") == 0 )
2645 makeReferenceWithToBase(x86::kAbsolute32, srcAddr, betterDstAddr, dstAddr);
2647 makeReferenceWithToBase(x86::kPointer, srcAddr, betterDstAddr, dstAddr);
2650 case GENERIC_RELOC_SECTDIFF:
2651 case GENERIC_RELOC_LOCAL_SECTDIFF:
2653 if ( !nextRelocIsPair ) {
2654 printf("GENERIC_RELOC_SECTDIFF missing following pair\n");
2657 if ( sreloc->r_length() != 2 )
2658 throw "bad length for GENERIC_RELOC_SECTDIFF";
2659 betterDstAddr = LittleEndian::get32(*fixUpPtr);
2660 makeReferenceWithToBase(x86::kPointerDiff, srcAddr, nextRelocValue, betterDstAddr+nextRelocValue, dstAddr);
2663 case GENERIC_RELOC_PAIR:
2664 // do nothing, already used via a look ahead
2667 printf("unknown scattered relocation type %d\n", sreloc->r_type());
2674 bool Reader<x86_64>::addRelocReference(const macho_section<x86_64::P>* sect, const macho_relocation_info<x86_64::P>* reloc)
2677 uint64_t dstAddr = 0;
2680 x86_64::ReferenceKinds kind;
2681 bool result = false;
2682 const macho_nlist<P>* targetSymbol = NULL;
2683 const char* targetName = NULL;
2684 srcAddr = sect->addr() + reloc->r_address();
2685 fixUpPtr = (uint32_t*)((char*)(fHeader) + sect->offset() + reloc->r_address());
2686 //fprintf(stderr, "addReloc type=%d\n", reloc->r_type());
2687 if ( reloc->r_extern() ) {
2688 targetSymbol = &fSymbols[reloc->r_symbolnum()];
2689 targetName = &fStrings[targetSymbol->n_strx()];
2691 switch ( reloc->r_type() ) {
2692 case X86_64_RELOC_UNSIGNED:
2693 if ( reloc->r_pcrel() )
2694 throw "pcrel and X86_64_RELOC_UNSIGNED not supported";
2695 if ( reloc->r_length() != 3 )
2696 throw "length < 3 and X86_64_RELOC_UNSIGNED not supported";
2697 dstAddr = E::get64(*((uint64_t*)fixUpPtr));
2698 if ( reloc->r_extern() )
2699 makeReferenceToSymbol(x86_64::kPointer, srcAddr, targetSymbol, dstAddr);
2701 makeReference(x86_64::kPointer, srcAddr, dstAddr);
2703 case X86_64_RELOC_SIGNED:
2704 if ( ! reloc->r_pcrel() )
2705 throw "not pcrel and X86_64_RELOC_SIGNED not supported";
2706 if ( reloc->r_length() != 2 )
2707 throw "length != 2 and X86_64_RELOC_SIGNED not supported";
2708 kind = x86_64::kPCRel32;
2709 dstAddr = (int64_t)((int32_t)(E::get32(*fixUpPtr)));
2710 if ( dstAddr == (uint64_t)(-1) ) {
2712 kind = x86_64::kPCRel32_1;
2714 else if ( dstAddr == (uint64_t)(-2) ) {
2716 kind = x86_64::kPCRel32_2;
2718 else if ( dstAddr == (uint64_t)(-4) ) {
2720 kind = x86_64::kPCRel32_4;
2722 if ( reloc->r_extern() )
2723 makeReferenceToSymbol(kind, srcAddr, targetSymbol, dstAddr);
2725 makeReference(kind, srcAddr, srcAddr+4+dstAddr);
2728 case X86_64_RELOC_BRANCH:
2729 if ( ! reloc->r_pcrel() )
2730 throw "not pcrel and X86_64_RELOC_BRANCH not supported";
2731 if ( reloc->r_length() != 2 )
2732 throw "length != 2 and X86_64_RELOC_BRANCH not supported";
2733 dstAddr = (int64_t)((int32_t)(E::get32(*fixUpPtr)));
2734 if ( reloc->r_extern() ) {
2735 if ( isWeakImportSymbol(targetSymbol) )
2736 makeReferenceToSymbol(x86_64::kBranchPCRel32WeakImport, srcAddr, targetSymbol, dstAddr);
2738 makeReferenceToSymbol(x86_64::kBranchPCRel32, srcAddr, targetSymbol, dstAddr);
2741 makeReference(x86_64::kBranchPCRel32, srcAddr, srcAddr+4+dstAddr);
2744 case X86_64_RELOC_GOT:
2745 if ( ! reloc->r_extern() )
2746 throw "not extern and X86_64_RELOC_GOT not supported";
2747 if ( ! reloc->r_pcrel() )
2748 throw "not pcrel and X86_64_RELOC_GOT not supported";
2749 if ( reloc->r_length() != 2 )
2750 throw "length != 2 and X86_64_RELOC_GOT not supported";
2751 addend = (int64_t)((int32_t)(E::get32(*fixUpPtr)));
2752 if ( isWeakImportSymbol(targetSymbol) )
2753 makeReferenceToSymbol(x86_64::kPCRel32GOTWeakImport, srcAddr, targetSymbol, addend);
2755 makeReferenceToSymbol(x86_64::kPCRel32GOT, srcAddr, targetSymbol, addend);
2757 case X86_64_RELOC_GOT_LOAD:
2758 if ( ! reloc->r_extern() )
2759 throw "not extern and X86_64_RELOC_GOT_LOAD not supported";
2760 if ( ! reloc->r_pcrel() )
2761 throw "not pcrel and X86_64_RELOC_GOT_LOAD not supported";
2762 if ( reloc->r_length() != 2 )
2763 throw "length != 2 and X86_64_RELOC_GOT_LOAD not supported";
2764 addend = (int64_t)((int32_t)(E::get32(*fixUpPtr)));
2765 if ( isWeakImportSymbol(targetSymbol) )
2766 makeReferenceToSymbol(x86_64::kPCRel32GOTLoadWeakImport, srcAddr, targetSymbol, addend);
2768 makeReferenceToSymbol(x86_64::kPCRel32GOTLoad, srcAddr, targetSymbol, addend);
2770 case X86_64_RELOC_SUBTRACTOR:
2771 if ( reloc->r_pcrel() )
2772 throw "X86_64_RELOC_SUBTRACTOR cannot be pc-relative";
2773 if ( reloc->r_length() < 2 )
2774 throw "X86_64_RELOC_SUBTRACTOR must have r_length of 2 or 3";
2775 if ( !reloc->r_extern() )
2776 throw "X86_64_RELOC_SUBTRACTOR must have r_extern=1";
2777 const macho_relocation_info<x86_64::P>* nextReloc = &reloc[1];
2778 if ( nextReloc->r_type() != X86_64_RELOC_UNSIGNED )
2779 throw "X86_64_RELOC_SUBTRACTOR must be followed by X86_64_RELOC_UNSIGNED";
2781 if ( nextReloc->r_pcrel() )
2782 throw "X86_64_RELOC_UNSIGNED following a X86_64_RELOC_SUBTRACTOR cannot be pc-relative";
2783 if ( nextReloc->r_length() != reloc->r_length() )
2784 throw "X86_64_RELOC_UNSIGNED following a X86_64_RELOC_SUBTRACTOR must have same r_length";
2785 Reference<x86_64>* ref;
2786 bool negativeAddend;
2787 if ( reloc->r_length() == 2 ) {
2788 kind = x86_64::kPointerDiff32;
2789 dstAddr = E::get32(*fixUpPtr); // addend is in content
2790 negativeAddend = ((dstAddr & 0x80000000) != 0);
2793 kind = x86_64::kPointerDiff;
2794 dstAddr = E::get64(*((uint64_t*)fixUpPtr)); // addend is in content
2795 negativeAddend = ((dstAddr & 0x8000000000000000ULL) != 0);
2797 ObjectFile::Atom* inAtom = this->findAtomAndOffset(srcAddr).atom;
2798 // create reference with "to" target
2799 if ( nextReloc->r_extern() ) {
2800 const macho_nlist<P>* targetSymbol = &fSymbols[nextReloc->r_symbolnum()];
2801 const char* targetName = &fStrings[targetSymbol->n_strx()];
2802 ref = makeReferenceToSymbol(kind, srcAddr, targetSymbol, 0);
2803 // if "to" is in this atom, change by-name to a direct reference
2804 if ( strcmp(targetName, inAtom->getName()) == 0 )
2805 ref->setTarget(*inAtom, 0);
2808 ref = makeReference(kind, srcAddr, dstAddr);
2810 // add in "from" target
2811 if ( reloc->r_extern() ) {
2812 const macho_nlist<P>* targetFromSymbol = &fSymbols[reloc->r_symbolnum()];
2813 const char* fromTargetName = &fStrings[targetFromSymbol->n_strx()];
2814 if ( (targetFromSymbol->n_type() & N_EXT) == 0 ) {
2815 // from target is translation unit scoped, so use a direct reference
2816 ref->setFromTarget(*(findAtomAndOffset(targetSymbol->n_value()).atom));
2818 else if ( strcmp(fromTargetName, inAtom->getName()) == 0 ) {
2819 // if "from" is in this atom, change by-name to a direct reference
2820 ref->setFromTarget(*inAtom);
2823 // some non-static other atom
2824 ref->setFromTargetName(fromTargetName);
2827 // addend goes in from side iff negative
2828 if ( negativeAddend )
2829 ref->setFromTargetOffset(-dstAddr);
2831 ref->setToTargetOffset(dstAddr);
2834 fprintf(stderr, "unknown relocation type %d\n", reloc->r_type());
2841 const char* Reference<x86>::getDescription() const
2843 static char temp[2048];
2846 sprintf(temp, "reference to ");
2848 case x86::kFollowOn:
2849 sprintf(temp, "followed by ");
2851 case x86::kPointerWeakImport:
2852 sprintf(temp, "offset 0x%04X, weak import pointer to ", fFixUpOffsetInSrc);
2855 sprintf(temp, "offset 0x%04X, pointer to ", fFixUpOffsetInSrc);
2857 case x86::kPointerDiff:
2859 // by-name references have quoted names
2860 const char* targetQuotes = (&(this->getTarget()) == NULL) ? "\"" : "";
2861 const char* fromQuotes = (&(this->getFromTarget()) == NULL) ? "\"" : "";
2862 sprintf(temp, "offset 0x%04X, 32-bit pointer difference: (&%s%s%s + 0x%08X) - (&%s%s%s + 0x%08X)",
2863 fFixUpOffsetInSrc, targetQuotes, this->getTargetName(), targetQuotes, fToTarget.offset,
2864 fromQuotes, this->getFromTargetName(), fromQuotes, fFromTarget.offset );
2868 case x86::kPCRel32WeakImport:
2869 sprintf(temp, "offset 0x%04X, rel32 reference to weak imported ", fFixUpOffsetInSrc);
2872 sprintf(temp, "offset 0x%04X, rel32 reference to ", fFixUpOffsetInSrc);
2874 case x86::kAbsolute32:
2875 sprintf(temp, "offset 0x%04X, absolute32 reference to ", fFixUpOffsetInSrc);
2878 // always quote by-name references
2879 if ( fToTargetName != NULL ) {
2881 strcat(temp, fToTargetName);
2884 else if ( fToTarget.atom != NULL ) {
2885 strcat(temp, fToTarget.atom->getDisplayName());
2888 strcat(temp, "NULL target");
2890 if ( fToTarget.offset != 0 )
2891 sprintf(&temp[strlen(temp)], " plus 0x%08X", fToTarget.offset);
2898 const char* Reference<ppc>::getDescription() const
2900 static char temp[2048];
2903 sprintf(temp, "reference to ");
2905 case ppc::kFollowOn:
2906 sprintf(temp, "followed by ");
2908 case ppc::kPointerWeakImport:
2909 sprintf(temp, "offset 0x%04X, weak import pointer to ", fFixUpOffsetInSrc);
2912 sprintf(temp, "offset 0x%04X, pointer to ", fFixUpOffsetInSrc);
2914 case ppc::kPointerDiff32:
2916 // by-name references have quoted names
2917 const char* targetQuotes = (&(this->getTarget()) == NULL) ? "\"" : "";
2918 const char* fromQuotes = (&(this->getFromTarget()) == NULL) ? "\"" : "";
2919 sprintf(temp, "offset 0x%04X, 32-bit pointer difference: (&%s%s%s + %d) - (&%s%s%s + %d)",
2920 fFixUpOffsetInSrc, targetQuotes, this->getTargetName(), targetQuotes, fToTarget.offset,
2921 fromQuotes, this->getFromTargetName(), fromQuotes, fFromTarget.offset );
2924 case ppc::kPointerDiff64:
2925 throw "unsupported refrence kind";
2927 case ppc::kBranch24WeakImport:
2928 sprintf(temp, "offset 0x%04X, pc-rel branch fixup to weak imported ", fFixUpOffsetInSrc);
2930 case ppc::kBranch24:
2931 case ppc::kBranch14:
2932 sprintf(temp, "offset 0x%04X, pc-rel branch fixup to ", fFixUpOffsetInSrc);
2934 case ppc::kPICBaseLow16:
2935 sprintf(temp, "offset 0x%04X, low 16 fixup from pic-base offset 0x%04X to ", fFixUpOffsetInSrc, fFromTarget.offset);
2937 case ppc::kPICBaseLow14:
2938 sprintf(temp, "offset 0x%04X, low 14 fixup from pic-base offset 0x%04X to ", fFixUpOffsetInSrc, fFromTarget.offset);
2940 case ppc::kPICBaseHigh16:
2941 sprintf(temp, "offset 0x%04X, high 16 fixup from pic-base offset 0x%04X to ", fFixUpOffsetInSrc, fFromTarget.offset);
2943 case ppc::kAbsLow16:
2944 sprintf(temp, "offset 0x%04X, low 16 fixup to absolute address of ", fFixUpOffsetInSrc);
2946 case ppc::kAbsLow14:
2947 sprintf(temp, "offset 0x%04X, low 14 fixup to absolute address of ", fFixUpOffsetInSrc);
2949 case ppc::kAbsHigh16:
2950 sprintf(temp, "offset 0x%04X, high 16 fixup to absolute address of ", fFixUpOffsetInSrc);
2952 case ppc::kAbsHigh16AddLow:
2953 sprintf(temp, "offset 0x%04X, high 16 fixup to absolute address of ", fFixUpOffsetInSrc);
2956 // always quote by-name references
2957 if ( fToTargetName != NULL ) {
2959 strcat(temp, fToTargetName);
2962 else if ( fToTarget.atom != NULL ) {
2963 strcat(temp, fToTarget.atom->getDisplayName());
2966 strcat(temp, "NULL target");
2968 if ( fToTarget.offset != 0 )
2969 sprintf(&temp[strlen(temp)], " plus 0x%08X", fToTarget.offset);
2975 const char* Reference<ppc64>::getDescription() const
2977 static char temp[2048];
2979 case ppc64::kNoFixUp:
2980 sprintf(temp, "reference to ");
2982 case ppc64::kFollowOn:
2983 sprintf(temp, "followed by ");
2985 case ppc64::kPointerWeakImport:
2986 sprintf(temp, "offset 0x%04llX, weak import pointer to ", fFixUpOffsetInSrc);
2988 case ppc64::kPointer:
2989 sprintf(temp, "offset 0x%04llX, pointer to ", fFixUpOffsetInSrc);
2991 case ppc64::kPointerDiff64:
2993 // by-name references have quoted names
2994 const char* targetQuotes = (&(this->getTarget()) == NULL) ? "\"" : "";
2995 const char* fromQuotes = (&(this->getFromTarget()) == NULL) ? "\"" : "";
2996 sprintf(temp, "offset 0x%04llX, 64-bit pointer difference: (&%s%s%s + %u) - (&%s%s%s + %u)",
2997 fFixUpOffsetInSrc, targetQuotes, this->getTargetName(), targetQuotes, fToTarget.offset,
2998 fromQuotes, this->getFromTargetName(), fromQuotes, fFromTarget.offset );
3001 case ppc64::kPointerDiff32:
3003 // by-name references have quoted names
3004 const char* targetQuotes = (&(this->getTarget()) == NULL) ? "\"" : "";
3005 const char* fromQuotes = (&(this->getFromTarget()) == NULL) ? "\"" : "";
3006 sprintf(temp, "offset 0x%04llX, 32-bit pointer difference: (&%s%s%s + %u) - (&%s%s%s + %u)",
3007 fFixUpOffsetInSrc, targetQuotes, this->getTargetName(), targetQuotes, fToTarget.offset,
3008 fromQuotes, this->getFromTargetName(), fromQuotes, fFromTarget.offset );
3011 case ppc64::kBranch24WeakImport:
3012 sprintf(temp, "offset 0x%04llX, pc-rel branch fixup to weak imported ", fFixUpOffsetInSrc);
3014 case ppc64::kBranch24:
3015 case ppc64::kBranch14:
3016 sprintf(temp, "offset 0x%04llX, pc-rel branch fixup to ", fFixUpOffsetInSrc);
3018 case ppc64::kPICBaseLow16:
3019 sprintf(temp, "offset 0x%04llX, low 16 fixup from pic-base offset 0x%04X to ", fFixUpOffsetInSrc, fFromTarget.offset);
3021 case ppc64::kPICBaseLow14:
3022 sprintf(temp, "offset 0x%04llX, low 14 fixup from pic-base offset 0x%04X to ", fFixUpOffsetInSrc, fFromTarget.offset);
3024 case ppc64::kPICBaseHigh16:
3025 sprintf(temp, "offset 0x%04llX, high 16 fixup from pic-base offset 0x%04X to ", fFixUpOffsetInSrc, fFromTarget.offset);
3027 case ppc64::kAbsLow16:
3028 sprintf(temp, "offset 0x%04llX, low 16 fixup to absolute address of ", fFixUpOffsetInSrc);
3030 case ppc64::kAbsLow14:
3031 sprintf(temp, "offset 0x%04llX, low 14 fixup to absolute address of ", fFixUpOffsetInSrc);
3033 case ppc64::kAbsHigh16:
3034 sprintf(temp, "offset 0x%04llX, high 16 fixup to absolute address of ", fFixUpOffsetInSrc);
3036 case ppc64::kAbsHigh16AddLow:
3037 sprintf(temp, "offset 0x%04llX, high 16 fixup to absolute address of ", fFixUpOffsetInSrc);
3040 // always quote by-name references
3041 if ( fToTargetName != NULL ) {
3043 strcat(temp, fToTargetName);
3046 else if ( fToTarget.atom != NULL ) {
3047 strcat(temp, fToTarget.atom->getDisplayName());
3050 strcat(temp, "NULL target");
3052 if ( fToTarget.offset != 0 )
3053 sprintf(&temp[strlen(temp)], " plus 0x%llX", this->getTargetOffset());
3060 const char* Reference<x86_64>::getDescription() const
3062 static char temp[2048];
3064 case x86_64::kNoFixUp:
3065 sprintf(temp, "reference to ");
3067 case x86_64::kFollowOn:
3068 sprintf(temp, "followed by ");
3070 case x86_64::kPointerWeakImport:
3071 sprintf(temp, "offset 0x%04llX, weak import pointer to ", fFixUpOffsetInSrc);
3073 case x86_64::kPointer:
3074 sprintf(temp, "offset 0x%04llX, pointer to ", fFixUpOffsetInSrc);
3076 case x86_64::kPointerDiff32:
3077 case x86_64::kPointerDiff:
3079 // by-name references have quoted names
3080 const char* targetQuotes = (&(this->getTarget()) == NULL) ? "\"" : "";
3081 const char* fromQuotes = (&(this->getFromTarget()) == NULL) ? "\"" : "";
3082 const char* size = (fKind == x86_64::kPointerDiff32) ? "32-bit" : "64-bit";
3083 sprintf(temp, "offset 0x%04llX, %s pointer difference: (&%s%s%s + 0x%08X) - (&%s%s%s + 0x%08X)",
3084 fFixUpOffsetInSrc, size, targetQuotes, this->getTargetName(), targetQuotes, fToTarget.offset,
3085 fromQuotes, this->getFromTargetName(), fromQuotes, fFromTarget.offset );
3089 case x86_64::kPCRel32:
3090 sprintf(temp, "offset 0x%04llX, rel32 reference to ", fFixUpOffsetInSrc);
3092 case x86_64::kPCRel32_1:
3093 sprintf(temp, "offset 0x%04llX, rel32-1 reference to ", fFixUpOffsetInSrc);
3095 case x86_64::kPCRel32_2:
3096 sprintf(temp, "offset 0x%04llX, rel32-2 reference to ", fFixUpOffsetInSrc);
3098 case x86_64::kPCRel32_4:
3099 sprintf(temp, "offset 0x%04llX, rel32-4 reference to ", fFixUpOffsetInSrc);
3101 case x86_64::kBranchPCRel32:
3102 sprintf(temp, "offset 0x%04llX, branch rel32 reference to ", fFixUpOffsetInSrc);
3104 case x86_64::kBranchPCRel32WeakImport:
3105 sprintf(temp, "offset 0x%04llX, branch rel32 reference to weak imported ", fFixUpOffsetInSrc);
3107 case x86_64::kPCRel32GOT:
3108 sprintf(temp, "offset 0x%04llX, rel32 reference to GOT entry for ", fFixUpOffsetInSrc);
3110 case x86_64::kPCRel32GOTWeakImport:
3111 sprintf(temp, "offset 0x%04llX, rel32 reference to GOT entry for weak imported ", fFixUpOffsetInSrc);
3113 case x86_64::kPCRel32GOTLoad:
3114 sprintf(temp, "offset 0x%04llX, rel32 reference to GOT entry for ", fFixUpOffsetInSrc);
3116 case x86_64::kPCRel32GOTLoadWeakImport:
3117 sprintf(temp, "offset 0x%04llX, rel32 reference to GOT entry for weak imported ", fFixUpOffsetInSrc);
3120 // always quote by-name references
3121 if ( fToTargetName != NULL ) {
3123 strcat(temp, fToTargetName);
3126 else if ( fToTarget.atom != NULL ) {
3127 strcat(temp, fToTarget.atom->getDisplayName());
3130 strcat(temp, "NULL target");
3132 if ( fToTarget.offset != 0 )
3133 sprintf(&temp[strlen(temp)], " plus 0x%llX", this->getTargetOffset());
3139 }; // namespace relocatable
3140 }; // namespace mach_o
3142 #endif // __OBJECT_FILE_MACH_O__