1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
3 * Copyright (c) 2009-2010 Apple Inc. All rights reserved.
5 * @APPLE_LICENSE_HEADER_START@
7 * This file contains Original Code and/or Modifications of Original Code
8 * as defined in and that are subject to the Apple Public Source License
9 * Version 2.0 (the 'License'). You may not use this file except in
10 * compliance with the License. Please obtain a copy of the License at
11 * http://www.opensource.apple.com/apsl/ and read it before using this
14 * The Original Code and all software distributed under the License are
15 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
19 * Please see the License for the specific language governing rights and
20 * limitations under the License.
22 * @APPLE_LICENSE_HEADER_END@
31 #include <sys/param.h>
35 #include "MachOFileAbstraction.hpp"
37 #include "libunwind/DwarfInstructions.hpp"
38 #include "libunwind/AddressSpace.hpp"
39 #include "libunwind/Registers.hpp"
47 #include "debugline.h"
49 #include "Architectures.hpp"
51 #include "macho_relocatable_file.h"
55 extern void throwf(const char* format
, ...) __attribute__ ((noreturn
,format(printf
, 1, 2)));
56 extern void warning(const char* format
, ...) __attribute__((format(printf
, 1, 2)));
59 namespace relocatable
{
63 template <typename A
> class Parser
;
64 template <typename A
> class Atom
;
65 template <typename A
> class Section
;
66 template <typename A
> class CFISection
;
67 template <typename A
> class CUSection
;
70 class File
: public ld::relocatable::File
73 File(const char* p
, time_t mTime
, const uint8_t* content
, ld::File::Ordinal ord
) :
74 ld::relocatable::File(p
,mTime
,ord
), _fileContent(content
),
75 _sectionsArray(NULL
), _atomsArray(NULL
),
76 _sectionsArrayCount(0), _atomsArrayCount(0),
77 _debugInfoKind(ld::relocatable::File::kDebugInfoNone
),
78 _dwarfTranslationUnitPath(NULL
),
79 _dwarfDebugInfoSect(NULL
), _dwarfDebugAbbrevSect(NULL
),
80 _dwarfDebugLineSect(NULL
), _dwarfDebugStringSect(NULL
),
81 _objConstraint(ld::File::objcConstraintNone
),
84 _canScatterAtoms(false) {}
87 // overrides of ld::File
88 virtual bool forEachAtom(ld::File::AtomHandler
&) const;
89 virtual bool justInTimeforEachAtom(const char* name
, ld::File::AtomHandler
&) const
92 // overrides of ld::relocatable::File
93 virtual ObjcConstraint
objCConstraint() const { return _objConstraint
; }
94 virtual uint32_t cpuSubType() const { return _cpuSubType
; }
95 virtual DebugInfoKind
debugInfo() const { return _debugInfoKind
; }
96 virtual const std::vector
<ld::relocatable::File::Stab
>* stabs() const { return &_stabs
; }
97 virtual bool canScatterAtoms() const { return _canScatterAtoms
; }
98 virtual const char* translationUnitSource() const;
99 virtual LinkerOptionsList
* linkerOptions() const { return &_linkerOptions
; }
100 virtual uint8_t swiftVersion() const { return _swiftVersion
; }
102 const uint8_t* fileContent() { return _fileContent
; }
104 friend class Atom
<A
>;
105 friend class Section
<A
>;
106 friend class Parser
<A
>;
107 friend class CFISection
<A
>::OAS
;
109 typedef typename
A::P P
;
111 const uint8_t* _fileContent
;
112 Section
<A
>** _sectionsArray
;
113 uint8_t* _atomsArray
;
114 uint8_t* _aliasAtomsArray
;
115 uint32_t _sectionsArrayCount
;
116 uint32_t _atomsArrayCount
;
117 uint32_t _aliasAtomsArrayCount
;
118 std::vector
<ld::Fixup
> _fixups
;
119 std::vector
<ld::Atom::UnwindInfo
> _unwindInfos
;
120 std::vector
<ld::Atom::LineInfo
> _lineInfos
;
121 std::vector
<ld::relocatable::File::Stab
>_stabs
;
122 ld::relocatable::File::DebugInfoKind _debugInfoKind
;
123 const char* _dwarfTranslationUnitPath
;
124 const macho_section
<P
>* _dwarfDebugInfoSect
;
125 const macho_section
<P
>* _dwarfDebugAbbrevSect
;
126 const macho_section
<P
>* _dwarfDebugLineSect
;
127 const macho_section
<P
>* _dwarfDebugStringSect
;
128 ld::File::ObjcConstraint _objConstraint
;
129 uint8_t _swiftVersion
;
130 uint32_t _cpuSubType
;
131 bool _canScatterAtoms
;
132 std::vector
<std::vector
<const char*> > _linkerOptions
;
136 template <typename A
>
137 class Section
: public ld::Section
140 typedef typename
A::P::uint_t pint_t
;
141 typedef typename
A::P P
;
142 typedef typename
A::P::E E
;
144 virtual ~Section() { }
145 class File
<A
>& file() const { return _file
; }
146 const macho_section
<P
>* machoSection() const { return _machOSection
; }
147 uint32_t sectionNum(class Parser
<A
>&) const;
148 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
);
149 virtual ld::Atom::ContentType
contentType() { return ld::Atom::typeUnclassified
; }
150 virtual bool dontDeadStrip() { return (this->_machOSection
->flags() & S_ATTR_NO_DEAD_STRIP
); }
151 virtual Atom
<A
>* findAtomByAddress(pint_t addr
) { return this->findContentAtomByAddress(addr
, this->_beginAtoms
, this->_endAtoms
); }
152 virtual bool addFollowOnFixups() const { return ! _file
.canScatterAtoms(); }
153 virtual uint32_t appendAtoms(class Parser
<A
>& parser
, uint8_t* buffer
,
154 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
155 const struct Parser
<A
>::CFI_CU_InfoArrays
&) = 0;
156 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
,
157 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
158 const struct Parser
<A
>::CFI_CU_InfoArrays
&) = 0;
159 virtual void makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
160 virtual bool addRelocFixup(class Parser
<A
>& parser
, const macho_relocation_info
<P
>*);
161 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const { return 0; }
162 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
163 const ld::IndirectBindingTable
& ind
) const { return false; }
164 virtual bool ignoreLabel(const char* label
) const { return false; }
165 static const char* makeSectionName(const macho_section
<typename
A::P
>* s
);
168 Section(File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
169 : ld::Section(makeSegmentName(s
), makeSectionName(s
), sectionType(s
)),
170 _file(f
), _machOSection(s
), _beginAtoms(NULL
), _endAtoms(NULL
), _hasAliases(false) { }
171 Section(File
<A
>& f
, const char* segName
, const char* sectName
, ld::Section::Type t
, bool hidden
=false)
172 : ld::Section(segName
, sectName
, t
, hidden
), _file(f
), _machOSection(NULL
),
173 _beginAtoms(NULL
), _endAtoms(NULL
), _hasAliases(false) { }
176 Atom
<A
>* findContentAtomByAddress(pint_t addr
, class Atom
<A
>* start
, class Atom
<A
>* end
);
177 uint32_t x86_64PcRelOffset(uint8_t r_type
);
178 void addLOH(class Parser
<A
>& parser
, int kind
, int count
, const uint64_t addrs
[]);
179 static const char* makeSegmentName(const macho_section
<typename
A::P
>* s
);
180 static bool readable(const macho_section
<typename
A::P
>* s
);
181 static bool writable(const macho_section
<typename
A::P
>* s
);
182 static bool exectuable(const macho_section
<typename
A::P
>* s
);
183 static ld::Section::Type
sectionType(const macho_section
<typename
A::P
>* s
);
186 const macho_section
<P
>* _machOSection
;
187 class Atom
<A
>* _beginAtoms
;
188 class Atom
<A
>* _endAtoms
;
190 std::set
<const class Atom
<A
>*> _altEntries
;
194 template <typename A
>
195 class CFISection
: public Section
<A
>
198 CFISection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
199 : Section
<A
>(f
, s
) { }
200 uint32_t cfiCount(Parser
<A
>& parser
);
202 virtual ld::Atom::ContentType
contentType() { return ld::Atom::typeCFI
; }
203 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
204 virtual uint32_t appendAtoms(class Parser
<A
>& parser
, uint8_t* buffer
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
205 virtual void makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
206 virtual bool addFollowOnFixups() const { return false; }
210 /// ObjectFileAddressSpace is used as a template parameter to UnwindCursor for parsing
211 /// dwarf CFI information in an object file.
216 typedef typename
A::P::uint_t pint_t
;
217 typedef typename
A::P P
;
218 typedef typename
A::P::E E
;
219 typedef typename
A::P::uint_t sint_t
;
221 OAS(CFISection
<A
>& ehFrameSection
, const uint8_t* ehFrameBuffer
) :
222 _ehFrameSection(ehFrameSection
),
223 _ehFrameContent(ehFrameBuffer
),
224 _ehFrameStartAddr(ehFrameSection
.machoSection()->addr()),
225 _ehFrameEndAddr(ehFrameSection
.machoSection()->addr()+ehFrameSection
.machoSection()->size()) {}
227 uint8_t get8(pint_t addr
) { return *((uint8_t*)mappedAddress(addr
)); }
228 uint16_t get16(pint_t addr
) { return E::get16(*((uint16_t*)mappedAddress(addr
))); }
229 uint32_t get32(pint_t addr
) { return E::get32(*((uint32_t*)mappedAddress(addr
))); }
230 uint64_t get64(pint_t addr
) { return E::get64(*((uint64_t*)mappedAddress(addr
))); }
231 pint_t
getP(pint_t addr
) { return P::getP(*((pint_t
*)mappedAddress(addr
))); }
232 uint64_t getULEB128(pint_t
& addr
, pint_t end
);
233 int64_t getSLEB128(pint_t
& addr
, pint_t end
);
234 pint_t
getEncodedP(pint_t
& addr
, pint_t end
, uint8_t encoding
);
236 const void* mappedAddress(pint_t addr
);
238 CFISection
<A
>& _ehFrameSection
;
239 const uint8_t* _ehFrameContent
;
240 pint_t _ehFrameStartAddr
;
241 pint_t _ehFrameEndAddr
;
245 typedef typename
A::P::uint_t pint_t
;
246 typedef libunwind::CFI_Atom_Info
<OAS
> CFI_Atom_Info
;
248 void cfiParse(class Parser
<A
>& parser
, uint8_t* buffer
, CFI_Atom_Info cfiArray
[], uint32_t& cfiCount
, const pint_t cuStarts
[], uint32_t cuCount
);
249 bool needsRelocating();
251 static bool bigEndian();
253 void addCiePersonalityFixups(class Parser
<A
>& parser
, const CFI_Atom_Info
* cieInfo
);
254 static void warnFunc(void* ref
, uint64_t funcAddr
, const char* msg
);
258 template <typename A
>
259 class CUSection
: public Section
<A
>
262 CUSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
263 : Section
<A
>(f
, s
) { }
265 typedef typename
A::P::uint_t pint_t
;
266 typedef typename
A::P P
;
267 typedef typename
A::P::E E
;
269 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, const struct Parser
<A
>::CFI_CU_InfoArrays
&) { return 0; }
270 virtual uint32_t appendAtoms(class Parser
<A
>& parser
, uint8_t* buffer
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, const struct Parser
<A
>::CFI_CU_InfoArrays
&) { return 0; }
271 virtual void makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
272 virtual bool addFollowOnFixups() const { return false; }
275 pint_t functionStartAddress
;
276 uint32_t functionSymbolIndex
;
277 uint32_t rangeLength
;
278 uint32_t compactUnwindInfo
;
279 const char* personality
;
286 void parse(class Parser
<A
>& parser
, uint32_t cnt
, Info array
[]);
287 static bool encodingMeansUseDwarf(compact_unwind_encoding_t enc
);
292 const char* personalityName(class Parser
<A
>& parser
, const macho_relocation_info
<P
>* reloc
);
294 static int infoSorter(const void* l
, const void* r
);
299 template <typename A
>
300 class TentativeDefinitionSection
: public Section
<A
>
303 TentativeDefinitionSection(Parser
<A
>& parser
, File
<A
>& f
)
304 : Section
<A
>(f
, "__DATA", "__comm/tent", ld::Section::typeTentativeDefs
) {}
306 virtual ld::Atom::ContentType
contentType() { return ld::Atom::typeZeroFill
; }
307 virtual bool addFollowOnFixups() const { return false; }
308 virtual Atom
<A
>* findAtomByAddress(typename
A::P::uint_t addr
) { throw "TentativeDefinitionSection::findAtomByAddress() should never be called"; }
309 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
310 const struct Parser
<A
>::CFI_CU_InfoArrays
&);
311 virtual uint32_t appendAtoms(class Parser
<A
>& parser
, uint8_t* buffer
,
312 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
313 const struct Parser
<A
>::CFI_CU_InfoArrays
&);
314 virtual void makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&) {}
316 typedef typename
A::P::uint_t pint_t
;
317 typedef typename
A::P P
;
321 template <typename A
>
322 class AbsoluteSymbolSection
: public Section
<A
>
325 AbsoluteSymbolSection(Parser
<A
>& parser
, File
<A
>& f
)
326 : Section
<A
>(f
, "__DATA", "__abs", ld::Section::typeAbsoluteSymbols
, true) {}
328 virtual ld::Atom::ContentType
contentType() { return ld::Atom::typeUnclassified
; }
329 virtual bool dontDeadStrip() { return false; }
330 virtual ld::Atom::Alignment
alignmentForAddress(typename
A::P::uint_t addr
) { return ld::Atom::Alignment(0); }
331 virtual bool addFollowOnFixups() const { return false; }
332 virtual Atom
<A
>* findAtomByAddress(typename
A::P::uint_t addr
) { throw "AbsoluteSymbolSection::findAtomByAddress() should never be called"; }
333 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
334 const struct Parser
<A
>::CFI_CU_InfoArrays
&);
335 virtual uint32_t appendAtoms(class Parser
<A
>& parser
, uint8_t* buffer
,
336 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
337 const struct Parser
<A
>::CFI_CU_InfoArrays
&);
338 virtual void makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&) {}
339 virtual Atom
<A
>* findAbsAtomForValue(typename
A::P::uint_t
);
342 typedef typename
A::P::uint_t pint_t
;
343 typedef typename
A::P P
;
347 template <typename A
>
348 class SymboledSection
: public Section
<A
>
351 SymboledSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
);
352 virtual ld::Atom::ContentType
contentType() { return _type
; }
353 virtual bool dontDeadStrip();
354 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
355 const struct Parser
<A
>::CFI_CU_InfoArrays
&);
356 virtual uint32_t appendAtoms(class Parser
<A
>& parser
, uint8_t* buffer
,
357 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
358 const struct Parser
<A
>::CFI_CU_InfoArrays
&);
360 typedef typename
A::P::uint_t pint_t
;
361 typedef typename
A::P P
;
363 ld::Atom::ContentType _type
;
367 template <typename A
>
368 class TLVDefsSection
: public SymboledSection
<A
>
371 TLVDefsSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
) :
372 SymboledSection
<A
>(parser
, f
, s
) { }
379 template <typename A
>
380 class ImplicitSizeSection
: public Section
<A
>
383 ImplicitSizeSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
384 : Section
<A
>(f
, s
) { }
385 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
386 virtual uint32_t appendAtoms(class Parser
<A
>& parser
, uint8_t* buffer
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
388 typedef typename
A::P::uint_t pint_t
;
389 typedef typename
A::P P
;
391 virtual bool addFollowOnFixups() const { return false; }
392 virtual const char* unlabeledAtomName(Parser
<A
>& parser
, pint_t addr
) = 0;
393 virtual ld::Atom::SymbolTableInclusion
symbolTableInclusion();
394 virtual pint_t
elementSizeAtAddress(pint_t addr
) = 0;
395 virtual ld::Atom::Scope
scopeAtAddress(Parser
<A
>& parser
, pint_t addr
) { return ld::Atom::scopeLinkageUnit
; }
396 virtual bool useElementAt(Parser
<A
>& parser
,
397 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, pint_t addr
) = 0;
398 virtual ld::Atom::Definition
definition() { return ld::Atom::definitionRegular
; }
399 virtual ld::Atom::Combine
combine(Parser
<A
>& parser
, pint_t addr
) = 0;
400 virtual bool ignoreLabel(const char* label
) const { return (label
[0] == 'L'); }
404 template <typename A
>
405 class FixedSizeSection
: public ImplicitSizeSection
<A
>
408 FixedSizeSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
409 : ImplicitSizeSection
<A
>(parser
, f
, s
) { }
411 typedef typename
A::P::uint_t pint_t
;
412 typedef typename
A::P P
;
413 typedef typename
A::P::E E
;
415 virtual bool useElementAt(Parser
<A
>& parser
,
416 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, pint_t addr
)
421 template <typename A
>
422 class Literal4Section
: public FixedSizeSection
<A
>
425 Literal4Section(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
426 : FixedSizeSection
<A
>(parser
, f
, s
) {}
428 typedef typename
A::P::uint_t pint_t
;
429 typedef typename
A::P P
;
431 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(2); }
432 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "4-byte-literal"; }
433 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return 4; }
434 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndContent
; }
435 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
436 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
437 const ld::IndirectBindingTable
& ind
) const;
440 template <typename A
>
441 class Literal8Section
: public FixedSizeSection
<A
>
444 Literal8Section(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
445 : FixedSizeSection
<A
>(parser
, f
, s
) {}
447 typedef typename
A::P::uint_t pint_t
;
448 typedef typename
A::P P
;
450 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(3); }
451 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "8-byte-literal"; }
452 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return 8; }
453 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndContent
; }
454 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
455 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
456 const ld::IndirectBindingTable
& ind
) const;
459 template <typename A
>
460 class Literal16Section
: public FixedSizeSection
<A
>
463 Literal16Section(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
464 : FixedSizeSection
<A
>(parser
, f
, s
) {}
466 typedef typename
A::P::uint_t pint_t
;
467 typedef typename
A::P P
;
469 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(4); }
470 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "16-byte-literal"; }
471 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return 16; }
472 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndContent
; }
473 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
474 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
475 const ld::IndirectBindingTable
& ind
) const;
479 template <typename A
>
480 class NonLazyPointerSection
: public FixedSizeSection
<A
>
483 NonLazyPointerSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
484 : FixedSizeSection
<A
>(parser
, f
, s
) {}
486 typedef typename
A::P::uint_t pint_t
;
487 typedef typename
A::P P
;
489 virtual void makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
490 virtual ld::Atom::ContentType
contentType() { return ld::Atom::typeNonLazyPointer
; }
491 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(log2(sizeof(pint_t
))); }
492 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "non_lazy_ptr"; }
493 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return sizeof(pint_t
); }
494 virtual ld::Atom::Scope
scopeAtAddress(Parser
<A
>& parser
, pint_t addr
);
495 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
);
496 virtual bool ignoreLabel(const char* label
) const { return true; }
497 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
498 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
499 const ld::IndirectBindingTable
& ind
) const;
502 static const char* targetName(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
);
503 static ld::Fixup::Kind
fixupKind();
507 template <typename A
>
508 class CFStringSection
: public FixedSizeSection
<A
>
511 CFStringSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
512 : FixedSizeSection
<A
>(parser
, f
, s
) {}
514 typedef typename
A::P::uint_t pint_t
;
516 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(log2(sizeof(pint_t
))); }
517 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "CFString"; }
518 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return 4*sizeof(pint_t
); }
519 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndReferences
; }
520 virtual bool ignoreLabel(const char* label
) const { return true; }
521 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
522 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
523 const ld::IndirectBindingTable
& ind
) const;
525 enum ContentType
{ contentUTF8
, contentUTF16
, contentUnknown
};
526 static const uint8_t* targetContent(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
,
527 ContentType
* ct
, unsigned int* count
);
531 template <typename A
>
532 class ObjC1ClassSection
: public FixedSizeSection
<A
>
535 ObjC1ClassSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
536 : FixedSizeSection
<A
>(parser
, f
, s
) {}
538 typedef typename
A::P::uint_t pint_t
;
539 typedef typename
A::P P
;
540 typedef typename
A::P::E E
;
542 virtual ld::Atom::Scope
scopeAtAddress(Parser
<A
>& , pint_t
) { return ld::Atom::scopeGlobal
; }
543 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(2); }
544 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
);
545 virtual ld::Atom::SymbolTableInclusion
symbolTableInclusion() { return ld::Atom::symbolTableIn
; }
546 virtual pint_t
elementSizeAtAddress(pint_t addr
);
547 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineNever
; }
548 virtual bool ignoreLabel(const char* label
) const { return true; }
549 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
551 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
552 const ld::IndirectBindingTable
& ind
) const { return false; }
553 virtual bool addRelocFixup(class Parser
<A
>& parser
, const macho_relocation_info
<P
>*);
557 template <typename A
>
558 class ObjC2ClassRefsSection
: public FixedSizeSection
<A
>
561 ObjC2ClassRefsSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
562 : FixedSizeSection
<A
>(parser
, f
, s
) {}
564 typedef typename
A::P::uint_t pint_t
;
566 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(log2(sizeof(pint_t
))); }
567 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "objc-class-ref"; }
568 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return sizeof(pint_t
); }
569 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndReferences
; }
570 virtual bool ignoreLabel(const char* label
) const { return true; }
571 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
572 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
573 const ld::IndirectBindingTable
& ind
) const;
575 const char* targetClassName(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
579 template <typename A
>
580 class ObjC2CategoryListSection
: public FixedSizeSection
<A
>
583 ObjC2CategoryListSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
584 : FixedSizeSection
<A
>(parser
, f
, s
) {}
586 typedef typename
A::P::uint_t pint_t
;
588 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(log2(sizeof(pint_t
))); }
589 virtual ld::Atom::Scope
scopeAtAddress(Parser
<A
>& parser
, pint_t addr
) { return ld::Atom::scopeTranslationUnit
; }
590 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "objc-cat-list"; }
591 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return sizeof(pint_t
); }
592 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineNever
; }
593 virtual bool ignoreLabel(const char* label
) const { return true; }
595 const char* targetClassName(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
599 template <typename A
>
600 class PointerToCStringSection
: public FixedSizeSection
<A
>
603 PointerToCStringSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
604 : FixedSizeSection
<A
>(parser
, f
, s
) {}
606 typedef typename
A::P::uint_t pint_t
;
608 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(log2(sizeof(pint_t
))); }
609 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "pointer-to-literal-cstring"; }
610 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return sizeof(pint_t
); }
611 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndReferences
; }
612 virtual bool ignoreLabel(const char* label
) const { return true; }
613 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
614 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
615 const ld::IndirectBindingTable
& ind
) const;
616 virtual const char* targetCString(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
620 template <typename A
>
621 class Objc1ClassReferences
: public PointerToCStringSection
<A
>
624 Objc1ClassReferences(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
625 : PointerToCStringSection
<A
>(parser
, f
, s
) {}
627 typedef typename
A::P::uint_t pint_t
;
628 typedef typename
A::P P
;
630 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "pointer-to-literal-objc-class-name"; }
631 virtual bool addRelocFixup(class Parser
<A
>& parser
, const macho_relocation_info
<P
>*);
632 virtual const char* targetCString(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
636 template <typename A
>
637 class CStringSection
: public ImplicitSizeSection
<A
>
640 CStringSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
641 : ImplicitSizeSection
<A
>(parser
, f
, s
) {}
643 typedef typename
A::P::uint_t pint_t
;
644 typedef typename
A::P P
;
646 virtual ld::Atom::ContentType
contentType() { return ld::Atom::typeCString
; }
647 virtual Atom
<A
>* findAtomByAddress(pint_t addr
);
648 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "cstring"; }
649 virtual pint_t
elementSizeAtAddress(pint_t addr
);
650 virtual bool ignoreLabel(const char* label
) const;
651 virtual bool useElementAt(Parser
<A
>& parser
,
652 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, pint_t addr
);
653 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndContent
; }
654 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
655 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
656 const ld::IndirectBindingTable
& ind
) const;
661 template <typename A
>
662 class UTF16StringSection
: public SymboledSection
<A
>
665 UTF16StringSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
666 : SymboledSection
<A
>(parser
, f
, s
) {}
668 typedef typename
A::P::uint_t pint_t
;
669 typedef typename
A::P P
;
671 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndContent
; }
672 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
673 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
674 const ld::IndirectBindingTable
& ind
) const;
679 // Atoms in mach-o files
681 template <typename A
>
682 class Atom
: public ld::Atom
685 // overrides of ld::Atom
686 virtual const ld::File
* file() const;
687 virtual const char* translationUnitSource() const
688 { return sect().file().translationUnitSource(); }
689 virtual const char* name() const { return _name
; }
690 virtual uint64_t size() const { return _size
; }
691 virtual uint64_t objectAddress() const { return _objAddress
; }
692 virtual void copyRawContent(uint8_t buffer
[]) const;
693 virtual const uint8_t* rawContentPointer() const { return contentPointer(); }
694 virtual unsigned long contentHash(const ld::IndirectBindingTable
& ind
) const
695 { if ( _hash
== 0 ) _hash
= sect().contentHash(this, ind
); return _hash
; }
696 virtual bool canCoalesceWith(const ld::Atom
& rhs
, const ld::IndirectBindingTable
& ind
) const
697 { return sect().canCoalesceWith(this, rhs
, ind
); }
698 virtual ld::Fixup::iterator
fixupsBegin() const { return &machofile()._fixups
[_fixupsStartIndex
]; }
699 virtual ld::Fixup::iterator
fixupsEnd() const { return &machofile()._fixups
[_fixupsStartIndex
+_fixupsCount
]; }
700 virtual ld::Atom::UnwindInfo::iterator
beginUnwind() const { return &machofile()._unwindInfos
[_unwindInfoStartIndex
]; }
701 virtual ld::Atom::UnwindInfo::iterator
endUnwind() const { return &machofile()._unwindInfos
[_unwindInfoStartIndex
+_unwindInfoCount
]; }
702 virtual ld::Atom::LineInfo::iterator
beginLineInfo() const{ return &machofile()._lineInfos
[_lineInfoStartIndex
]; }
703 virtual ld::Atom::LineInfo::iterator
endLineInfo() const { return &machofile()._lineInfos
[_lineInfoStartIndex
+_lineInfoCount
]; }
704 virtual void setFile(const ld::File
* f
);
708 enum { kFixupStartIndexBits
= 32,
709 kLineInfoStartIndexBits
= 32,
710 kUnwindInfoStartIndexBits
= 24,
711 kFixupCountBits
= 24,
712 kLineInfoCountBits
= 12,
713 kUnwindInfoCountBits
= 4
714 }; // must sum to 128
717 // methods for all atoms from mach-o object file
718 Section
<A
>& sect() const { return (Section
<A
>&)section(); }
719 File
<A
>& machofile() const { return ((Section
<A
>*)(this->_section
))->file(); }
720 void setFixupsRange(uint32_t s
, uint32_t c
);
721 void setUnwindInfoRange(uint32_t s
, uint32_t c
);
722 void extendUnwindInfoRange();
723 void setLineInfoRange(uint32_t s
, uint32_t c
);
724 bool roomForMoreLineInfoCount() { return (_lineInfoCount
< ((1<<kLineInfoCountBits
)-1)); }
725 void incrementLineInfoCount() { assert(roomForMoreLineInfoCount()); ++_lineInfoCount
; }
726 void incrementFixupCount() { if (_fixupsCount
== ((1 << kFixupCountBits
)-1))
727 throwf("too may fixups in %s", name()); ++_fixupsCount
; }
728 const uint8_t* contentPointer() const;
729 uint32_t fixupCount() const { return _fixupsCount
; }
730 void verifyAlignment(const macho_section
<typename
A::P
>&) const;
732 typedef typename
A::P P
;
733 typedef typename
A::P::E E
;
734 typedef typename
A::P::uint_t pint_t
;
735 // constuct via all attributes
736 Atom(Section
<A
>& sct
, const char* nm
, pint_t addr
, uint64_t sz
,
737 ld::Atom::Definition d
, ld::Atom::Combine c
, ld::Atom::Scope s
,
738 ld::Atom::ContentType ct
, ld::Atom::SymbolTableInclusion i
,
739 bool dds
, bool thumb
, bool al
, ld::Atom::Alignment a
)
740 : ld::Atom((ld::Section
&)sct
, d
, c
, s
, ct
, i
, dds
, thumb
, al
, a
),
741 _size(sz
), _objAddress(addr
), _name(nm
), _hash(0),
742 _fixupsStartIndex(0), _lineInfoStartIndex(0),
743 _unwindInfoStartIndex(0), _fixupsCount(0),
744 _lineInfoCount(0), _unwindInfoCount(0) { }
745 // construct via symbol table entry
746 Atom(Section
<A
>& sct
, Parser
<A
>& parser
, const macho_nlist
<P
>& sym
,
747 uint64_t sz
, bool alias
=false)
748 : ld::Atom((ld::Section
&)sct
, parser
.definitionFromSymbol(sym
),
749 parser
.combineFromSymbol(sym
), parser
.scopeFromSymbol(sym
),
750 parser
.resolverFromSymbol(sym
) ? ld::Atom::typeResolver
: sct
.contentType(),
751 parser
.inclusionFromSymbol(sym
),
752 parser
.dontDeadStripFromSymbol(sym
) || sct
.dontDeadStrip(),
753 parser
.isThumbFromSymbol(sym
), alias
,
754 sct
.alignmentForAddress(sym
.n_value())),
755 _size(sz
), _objAddress(sym
.n_value()),
756 _name(parser
.nameFromSymbol(sym
)), _hash(0),
757 _fixupsStartIndex(0), _lineInfoStartIndex(0),
758 _unwindInfoStartIndex(0), _fixupsCount(0),
759 _lineInfoCount(0), _unwindInfoCount(0) {
760 // <rdar://problem/6783167> support auto-hidden weak symbols
761 if ( _scope
== ld::Atom::scopeGlobal
&&
762 (sym
.n_desc() & (N_WEAK_DEF
|N_WEAK_REF
)) == (N_WEAK_DEF
|N_WEAK_REF
) )
764 this->verifyAlignment(*sct
.machoSection());
768 friend class Parser
<A
>;
769 friend class Section
<A
>;
770 friend class CStringSection
<A
>;
771 friend class AbsoluteSymbolSection
<A
>;
776 mutable unsigned long _hash
;
778 uint64_t _fixupsStartIndex
: kFixupStartIndexBits
,
779 _lineInfoStartIndex
: kLineInfoStartIndexBits
,
780 _unwindInfoStartIndex
: kUnwindInfoStartIndexBits
,
781 _fixupsCount
: kFixupCountBits
,
782 _lineInfoCount
: kLineInfoCountBits
,
783 _unwindInfoCount
: kUnwindInfoCountBits
;
785 static std::map
<const ld::Atom
*, const ld::File
*> _s_fileOverride
;
788 template <typename A
>
789 std::map
<const ld::Atom
*, const ld::File
*> Atom
<A
>::_s_fileOverride
;
791 template <typename A
>
792 void Atom
<A
>::setFile(const ld::File
* f
) {
793 _s_fileOverride
[this] = f
;
796 template <typename A
>
797 const ld::File
* Atom
<A
>::file() const
799 std::map
<const ld::Atom
*, const ld::File
*>::iterator pos
= _s_fileOverride
.find(this);
800 if ( pos
!= _s_fileOverride
.end() )
803 return §().file();
806 template <typename A
>
807 void Atom
<A
>::setFixupsRange(uint32_t startIndex
, uint32_t count
)
809 if ( count
>= (1 << kFixupCountBits
) )
810 throwf("too many fixups in function %s", this->name());
811 if ( startIndex
>= (1 << kFixupStartIndexBits
) )
812 throwf("too many fixups in file");
813 assert(((startIndex
+count
) <= sect().file()._fixups
.size()) && "fixup index out of range");
814 _fixupsStartIndex
= startIndex
;
815 _fixupsCount
= count
;
818 template <typename A
>
819 void Atom
<A
>::setUnwindInfoRange(uint32_t startIndex
, uint32_t count
)
821 if ( count
>= (1 << kUnwindInfoCountBits
) )
822 throwf("too many compact unwind infos in function %s", this->name());
823 if ( startIndex
>= (1 << kUnwindInfoStartIndexBits
) )
824 throwf("too many compact unwind infos (%d) in file", startIndex
);
825 assert((startIndex
+count
) <= sect().file()._unwindInfos
.size() && "unwindinfo index out of range");
826 _unwindInfoStartIndex
= startIndex
;
827 _unwindInfoCount
= count
;
830 template <typename A
>
831 void Atom
<A
>::extendUnwindInfoRange()
833 if ( _unwindInfoCount
+1 >= (1 << kUnwindInfoCountBits
) )
834 throwf("too many compact unwind infos in function %s", this->name());
835 _unwindInfoCount
+= 1;
838 template <typename A
>
839 void Atom
<A
>::setLineInfoRange(uint32_t startIndex
, uint32_t count
)
841 assert((count
< (1 << kLineInfoCountBits
)) && "too many line infos");
842 assert((startIndex
+count
) < sect().file()._lineInfos
.size() && "line info index out of range");
843 _lineInfoStartIndex
= startIndex
;
844 _lineInfoCount
= count
;
847 template <typename A
>
848 const uint8_t* Atom
<A
>::contentPointer() const
850 const macho_section
<P
>* sct
= this->sect().machoSection();
851 if ( this->_objAddress
> sct
->addr() + sct
->size() )
852 throwf("malformed .o file, symbol has address 0x%0llX which is outside range of its section", (uint64_t)this->_objAddress
);
853 uint32_t fileOffset
= sct
->offset() - sct
->addr() + this->_objAddress
;
854 return this->sect().file().fileContent()+fileOffset
;
858 template <typename A
>
859 void Atom
<A
>::copyRawContent(uint8_t buffer
[]) const
862 if ( this->contentType() == ld::Atom::typeZeroFill
) {
863 bzero(buffer
, _size
);
865 else if ( _size
!= 0 ) {
866 memcpy(buffer
, this->contentPointer(), _size
);
871 void Atom
<arm
>::verifyAlignment(const macho_section
<P
>&) const
873 if ( (this->section().type() == ld::Section::typeCode
) && ! isThumb() ) {
874 if ( ((_objAddress
% 4) != 0) || (this->alignment().powerOf2
< 2) )
875 warning("ARM function not 4-byte aligned: %s from %s", this->name(), this->file()->path());
879 #if SUPPORT_ARCH_arm64
881 void Atom
<arm64
>::verifyAlignment(const macho_section
<P
>& sect
) const
883 if ( (this->section().type() == ld::Section::typeCode
) && (sect
.size() != 0) ) {
884 if ( ((_objAddress
% 4) != 0) || (this->alignment().powerOf2
< 2) )
885 warning("arm64 function not 4-byte aligned: %s from %s", this->name(), this->file()->path());
890 template <typename A
>
891 void Atom
<A
>::verifyAlignment(const macho_section
<P
>&) const
896 class AliasAtom
: public ld::Atom
899 AliasAtom(const char* name
, bool hidden
, const ld::File
* file
, const char* aliasOfName
) :
900 ld::Atom(_s_section
, ld::Atom::definitionRegular
, ld::Atom::combineNever
,
901 (hidden
? ld::Atom::scopeLinkageUnit
: ld::Atom::scopeGlobal
),
902 ld::Atom::typeUnclassified
, ld::Atom::symbolTableIn
,
903 false, false, true, 0),
906 _fixup(0, ld::Fixup::k1of1
, ld::Fixup::kindNoneFollowOn
, ld::Fixup::bindingByNameUnbound
, aliasOfName
) { }
908 virtual const ld::File
* file() const { return _file
; }
909 virtual const char* translationUnitSource() const
911 virtual const char* name() const { return _name
; }
912 virtual uint64_t size() const { return 0; }
913 virtual uint64_t objectAddress() const { return 0; }
914 virtual void copyRawContent(uint8_t buffer
[]) const { }
915 virtual ld::Fixup::iterator
fixupsBegin() const { return &((ld::Fixup
*)&_fixup
)[0]; }
916 virtual ld::Fixup::iterator
fixupsEnd() const { return &((ld::Fixup
*)&_fixup
)[1]; }
919 static ld::Section _s_section
;
921 const ld::File
* _file
;
926 ld::Section
AliasAtom::_s_section("__LD", "__aliases", ld::Section::typeTempAlias
, true);
929 template <typename A
>
933 static bool validFile(const uint8_t* fileContent
, bool subtypeMustMatch
=false,
934 cpu_subtype_t subtype
=0);
935 static const char* fileKind(const uint8_t* fileContent
);
936 static bool hasObjC2Categories(const uint8_t* fileContent
);
937 static bool hasObjC1Categories(const uint8_t* fileContent
);
938 static ld::relocatable::File
* parse(const uint8_t* fileContent
, uint64_t fileLength
,
939 const char* path
, time_t modTime
, ld::File::Ordinal ordinal
,
940 const ParserOptions
& opts
) {
941 Parser
p(fileContent
, fileLength
, path
, modTime
,
942 ordinal
, opts
.warnUnwindConversionProblems
,
943 opts
.keepDwarfUnwind
, opts
.forceDwarfConversion
,
944 opts
.neverConvertDwarf
, opts
.verboseOptimizationHints
);
945 return p
.parse(opts
);
948 typedef typename
A::P P
;
949 typedef typename
A::P::E E
;
950 typedef typename
A::P::uint_t pint_t
;
952 struct SourceLocation
{
954 SourceLocation(Atom
<A
>* a
, uint32_t o
) : atom(a
), offsetInAtom(o
) {}
956 uint32_t offsetInAtom
;
961 const char* name
; // only used if targetAtom is NULL
963 bool weakImport
; // only used if targetAtom is NULL
967 FixupInAtom(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, Atom
<A
>* target
) :
968 fixup(src
.offsetInAtom
, c
, k
, target
), atom(src
.atom
) { src
.atom
->incrementFixupCount(); }
970 FixupInAtom(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, ld::Fixup::TargetBinding b
, Atom
<A
>* target
) :
971 fixup(src
.offsetInAtom
, c
, k
, b
, target
), atom(src
.atom
) { src
.atom
->incrementFixupCount(); }
973 FixupInAtom(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, bool wi
, const char* name
) :
974 fixup(src
.offsetInAtom
, c
, k
, wi
, name
), atom(src
.atom
) { src
.atom
->incrementFixupCount(); }
976 FixupInAtom(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, ld::Fixup::TargetBinding b
, const char* name
) :
977 fixup(src
.offsetInAtom
, c
, k
, b
, name
), atom(src
.atom
) { src
.atom
->incrementFixupCount(); }
979 FixupInAtom(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, uint64_t addend
) :
980 fixup(src
.offsetInAtom
, c
, k
, addend
), atom(src
.atom
) { src
.atom
->incrementFixupCount(); }
982 FixupInAtom(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
) :
983 fixup(src
.offsetInAtom
, c
, k
, (uint64_t)0), atom(src
.atom
) { src
.atom
->incrementFixupCount(); }
989 void addFixup(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, Atom
<A
>* target
) {
990 _allFixups
.push_back(FixupInAtom(src
, c
, k
, target
));
993 void addFixup(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, ld::Fixup::TargetBinding b
, Atom
<A
>* target
) {
994 _allFixups
.push_back(FixupInAtom(src
, c
, k
, b
, target
));
997 void addFixup(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, bool wi
, const char* name
) {
998 _allFixups
.push_back(FixupInAtom(src
, c
, k
, wi
, name
));
1001 void addFixup(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, ld::Fixup::TargetBinding b
, const char* name
) {
1002 _allFixups
.push_back(FixupInAtom(src
, c
, k
, b
, name
));
1005 void addFixup(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, uint64_t addend
) {
1006 _allFixups
.push_back(FixupInAtom(src
, c
, k
, addend
));
1009 void addFixup(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
) {
1010 _allFixups
.push_back(FixupInAtom(src
, c
, k
));
1013 const char* path() { return _path
; }
1014 uint32_t symbolCount() { return _symbolCount
; }
1015 uint32_t indirectSymbol(uint32_t indirectIndex
);
1016 const macho_nlist
<P
>& symbolFromIndex(uint32_t index
);
1017 const char* nameFromSymbol(const macho_nlist
<P
>& sym
);
1018 ld::Atom::Scope
scopeFromSymbol(const macho_nlist
<P
>& sym
);
1019 static ld::Atom::Definition
definitionFromSymbol(const macho_nlist
<P
>& sym
);
1020 static ld::Atom::Combine
combineFromSymbol(const macho_nlist
<P
>& sym
);
1021 ld::Atom::SymbolTableInclusion
inclusionFromSymbol(const macho_nlist
<P
>& sym
);
1022 static bool dontDeadStripFromSymbol(const macho_nlist
<P
>& sym
);
1023 static bool isThumbFromSymbol(const macho_nlist
<P
>& sym
);
1024 static bool weakImportFromSymbol(const macho_nlist
<P
>& sym
);
1025 static bool resolverFromSymbol(const macho_nlist
<P
>& sym
);
1026 static bool altEntryFromSymbol(const macho_nlist
<P
>& sym
);
1027 uint32_t symbolIndexFromIndirectSectionAddress(pint_t
,const macho_section
<P
>*);
1028 const macho_section
<P
>* firstMachOSection() { return _sectionsStart
; }
1029 const macho_section
<P
>* machOSectionFromSectionIndex(uint32_t index
);
1030 uint32_t machOSectionCount() { return _machOSectionsCount
; }
1031 uint32_t undefinedStartIndex() { return _undefinedStartIndex
; }
1032 uint32_t undefinedEndIndex() { return _undefinedEndIndex
; }
1033 void addFixup(FixupInAtom f
) { _allFixups
.push_back(f
); }
1034 Section
<A
>* sectionForNum(unsigned int sectNum
);
1035 Section
<A
>* sectionForAddress(pint_t addr
);
1036 Atom
<A
>* findAtomByAddress(pint_t addr
);
1037 Atom
<A
>* findAtomByAddressOrNullIfStub(pint_t addr
);
1038 Atom
<A
>* findAtomByAddressOrLocalTargetOfStub(pint_t addr
, uint32_t* offsetInAtom
);
1039 Atom
<A
>* findAtomByName(const char* name
); // slow!
1040 void findTargetFromAddress(pint_t addr
, TargetDesc
& target
);
1041 void findTargetFromAddress(pint_t baseAddr
, pint_t addr
, TargetDesc
& target
);
1042 void findTargetFromAddressAndSectionNum(pint_t addr
, unsigned int sectNum
,
1043 TargetDesc
& target
);
1044 uint32_t tentativeDefinitionCount() { return _tentativeDefinitionCount
; }
1045 uint32_t absoluteSymbolCount() { return _absoluteSymbolCount
; }
1047 bool hasStubsSection() { return (_stubsSectionNum
!= 0); }
1048 unsigned int stubsSectionNum() { return _stubsSectionNum
; }
1049 void addDtraceExtraInfos(const SourceLocation
& src
, const char* provider
);
1050 const char* scanSymbolTableForAddress(uint64_t addr
);
1051 bool warnUnwindConversionProblems() { return _warnUnwindConversionProblems
; }
1052 bool hasDataInCodeLabels() { return _hasDataInCodeLabels
; }
1053 bool keepDwarfUnwind() { return _keepDwarfUnwind
; }
1054 bool forceDwarfConversion() { return _forceDwarfConversion
; }
1055 bool verboseOptimizationHints() { return _verboseOptimizationHints
; }
1056 bool neverConvertDwarf() { return _neverConvertDwarf
; }
1058 macho_data_in_code_entry
<P
>* dataInCodeStart() { return _dataInCodeStart
; }
1059 macho_data_in_code_entry
<P
>* dataInCodeEnd() { return _dataInCodeEnd
; }
1060 const uint8_t* optimizationHintsStart() { return _lohStart
; }
1061 const uint8_t* optimizationHintsEnd() { return _lohEnd
; }
1062 bool hasOptimizationHints() { return _lohStart
!= _lohEnd
; }
1065 void addFixups(const SourceLocation
& src
, ld::Fixup::Kind kind
, const TargetDesc
& target
);
1066 void addFixups(const SourceLocation
& src
, ld::Fixup::Kind kind
, const TargetDesc
& target
, const TargetDesc
& picBase
);
1070 struct LabelAndCFIBreakIterator
{
1071 typedef typename CFISection
<A
>::CFI_Atom_Info CFI_Atom_Info
;
1072 LabelAndCFIBreakIterator(const uint32_t* ssa
, uint32_t ssc
, const pint_t
* cfisa
,
1073 uint32_t cfisc
, bool ols
)
1074 : sortedSymbolIndexes(ssa
), sortedSymbolCount(ssc
), cfiStartsArray(cfisa
),
1075 cfiStartsCount(cfisc
), fileHasOverlappingSymbols(ols
),
1076 newSection(false), cfiIndex(0), symIndex(0) {}
1077 bool next(Parser
<A
>& parser
, const Section
<A
>& sect
, uint32_t sectNum
, pint_t startAddr
, pint_t endAddr
,
1078 pint_t
* addr
, pint_t
* size
, const macho_nlist
<P
>** sym
);
1079 pint_t
peek(Parser
<A
>& parser
, pint_t startAddr
, pint_t endAddr
);
1080 void beginSection() { newSection
= true; symIndex
= 0; }
1082 const uint32_t* const sortedSymbolIndexes
;
1083 const uint32_t sortedSymbolCount
;
1084 const pint_t
* cfiStartsArray
;
1085 const uint32_t cfiStartsCount
;
1086 const bool fileHasOverlappingSymbols
;
1092 struct CFI_CU_InfoArrays
{
1093 typedef typename CFISection
<A
>::CFI_Atom_Info CFI_Atom_Info
;
1094 typedef typename CUSection
<A
>::Info CU_Info
;
1095 CFI_CU_InfoArrays(const CFI_Atom_Info
* cfiAr
, uint32_t cfiC
, CU_Info
* cuAr
, uint32_t cuC
)
1096 : cfiArray(cfiAr
), cuArray(cuAr
), cfiCount(cfiC
), cuCount(cuC
) {}
1097 const CFI_Atom_Info
* const cfiArray
;
1098 CU_Info
* const cuArray
;
1099 const uint32_t cfiCount
;
1100 const uint32_t cuCount
;
1106 friend class Section
<A
>;
1108 enum SectionType
{ sectionTypeIgnore
, sectionTypeLiteral4
, sectionTypeLiteral8
, sectionTypeLiteral16
,
1109 sectionTypeNonLazy
, sectionTypeCFI
, sectionTypeCString
, sectionTypeCStringPointer
,
1110 sectionTypeUTF16Strings
, sectionTypeCFString
, sectionTypeObjC2ClassRefs
, typeObjC2CategoryList
,
1111 sectionTypeObjC1Classes
, sectionTypeSymboled
, sectionTypeObjC1ClassRefs
,
1112 sectionTypeTentativeDefinitions
, sectionTypeAbsoluteSymbols
, sectionTypeTLVDefs
,
1113 sectionTypeCompactUnwind
};
1115 template <typename P
>
1116 struct MachOSectionAndSectionClass
1118 const macho_section
<P
>* sect
;
1121 static int sorter(const void* l
, const void* r
) {
1122 const MachOSectionAndSectionClass
<P
>* left
= (MachOSectionAndSectionClass
<P
>*)l
;
1123 const MachOSectionAndSectionClass
<P
>* right
= (MachOSectionAndSectionClass
<P
>*)r
;
1124 int64_t diff
= left
->sect
->addr() - right
->sect
->addr();
1134 struct ParserAndSectionsArray
{ Parser
* parser
; const uint32_t* sortedSectionsArray
; };
1137 Parser(const uint8_t* fileContent
, uint64_t fileLength
,
1138 const char* path
, time_t modTime
, ld::File::Ordinal ordinal
,
1139 bool warnUnwindConversionProblems
, bool keepDwarfUnwind
,
1140 bool forceDwarfConversion
, bool neverConvertDwarf
, bool verboseOptimizationHints
);
1141 ld::relocatable::File
* parse(const ParserOptions
& opts
);
1142 uint8_t loadCommandSizeMask();
1143 bool parseLoadCommands();
1144 void makeSections();
1145 void prescanSymbolTable();
1146 void makeSortedSymbolsArray(uint32_t symArray
[], const uint32_t sectionArray
[]);
1147 void makeSortedSectionsArray(uint32_t array
[]);
1148 static int pointerSorter(const void* l
, const void* r
);
1149 static int symbolIndexSorter(void* extra
, const void* l
, const void* r
);
1150 static int sectionIndexSorter(void* extra
, const void* l
, const void* r
);
1152 void parseDebugInfo();
1154 void appendAliasAtoms(uint8_t* atomBuffer
);
1155 static bool isConstFunStabs(const char *stabStr
);
1156 bool read_comp_unit(const char ** name
, const char ** comp_dir
,
1157 uint64_t *stmt_list
);
1158 pint_t
realAddr(pint_t addr
);
1159 const char* getDwarfString(uint64_t form
, const uint8_t*& p
);
1160 uint64_t getDwarfOffset(uint64_t form
, const uint8_t*& di
, bool dwarf64
);
1161 bool skip_form(const uint8_t ** offset
, const uint8_t * end
,
1162 uint64_t form
, uint8_t addr_size
, bool dwarf64
);
1165 // filled in by constructor
1166 const uint8_t* _fileContent
;
1167 uint32_t _fileLength
;
1170 ld::File::Ordinal _ordinal
;
1172 // filled in by parseLoadCommands()
1174 const macho_nlist
<P
>* _symbols
;
1175 uint32_t _symbolCount
;
1176 uint32_t _indirectSymbolCount
;
1177 const char* _strings
;
1178 uint32_t _stringsSize
;
1179 const uint32_t* _indirectTable
;
1180 uint32_t _indirectTableCount
;
1181 uint32_t _undefinedStartIndex
;
1182 uint32_t _undefinedEndIndex
;
1183 const macho_section
<P
>* _sectionsStart
;
1184 uint32_t _machOSectionsCount
;
1186 macho_data_in_code_entry
<P
>* _dataInCodeStart
;
1187 macho_data_in_code_entry
<P
>* _dataInCodeEnd
;
1188 const uint8_t* _lohStart
;
1189 const uint8_t* _lohEnd
;
1191 // filled in by parse()
1192 CFISection
<A
>* _EHFrameSection
;
1193 CUSection
<A
>* _compactUnwindSection
;
1194 AbsoluteSymbolSection
<A
>* _absoluteSection
;
1195 uint32_t _tentativeDefinitionCount
;
1196 uint32_t _absoluteSymbolCount
;
1197 uint32_t _symbolsInSections
;
1198 bool _hasLongBranchStubs
;
1199 bool _AppleObjc
; // FSF has objc that uses different data layout
1200 bool _overlappingSymbols
;
1201 bool _warnUnwindConversionProblems
;
1202 bool _hasDataInCodeLabels
;
1203 bool _keepDwarfUnwind
;
1204 bool _forceDwarfConversion
;
1205 bool _neverConvertDwarf
;
1206 bool _verboseOptimizationHints
;
1207 unsigned int _stubsSectionNum
;
1208 const macho_section
<P
>* _stubsMachOSection
;
1209 std::vector
<const char*> _dtraceProviderInfo
;
1210 std::vector
<FixupInAtom
> _allFixups
;
1215 template <typename A
>
1216 Parser
<A
>::Parser(const uint8_t* fileContent
, uint64_t fileLength
, const char* path
, time_t modTime
,
1217 ld::File::Ordinal ordinal
, bool convertDUI
, bool keepDwarfUnwind
, bool forceDwarfConversion
,
1218 bool neverConvertDwarf
, bool verboseOptimizationHints
)
1219 : _fileContent(fileContent
), _fileLength(fileLength
), _path(path
), _modTime(modTime
),
1220 _ordinal(ordinal
), _file(NULL
),
1221 _symbols(NULL
), _symbolCount(0), _indirectSymbolCount(0), _strings(NULL
), _stringsSize(0),
1222 _indirectTable(NULL
), _indirectTableCount(0),
1223 _undefinedStartIndex(0), _undefinedEndIndex(0),
1224 _sectionsStart(NULL
), _machOSectionsCount(0), _hasUUID(false),
1225 _dataInCodeStart(NULL
), _dataInCodeEnd(NULL
),
1226 _lohStart(NULL
), _lohEnd(NULL
),
1227 _EHFrameSection(NULL
), _compactUnwindSection(NULL
), _absoluteSection(NULL
),
1228 _tentativeDefinitionCount(0), _absoluteSymbolCount(0),
1229 _symbolsInSections(0), _hasLongBranchStubs(false), _AppleObjc(false),
1230 _overlappingSymbols(false), _warnUnwindConversionProblems(convertDUI
), _hasDataInCodeLabels(false),
1231 _keepDwarfUnwind(keepDwarfUnwind
), _forceDwarfConversion(forceDwarfConversion
),
1232 _neverConvertDwarf(neverConvertDwarf
),
1233 _verboseOptimizationHints(verboseOptimizationHints
),
1234 _stubsSectionNum(0), _stubsMachOSection(NULL
)
1240 bool Parser
<x86
>::validFile(const uint8_t* fileContent
, bool, cpu_subtype_t
)
1242 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1243 if ( header
->magic() != MH_MAGIC
)
1245 if ( header
->cputype() != CPU_TYPE_I386
)
1247 if ( header
->filetype() != MH_OBJECT
)
1253 bool Parser
<x86_64
>::validFile(const uint8_t* fileContent
, bool, cpu_subtype_t
)
1255 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1256 if ( header
->magic() != MH_MAGIC_64
)
1258 if ( header
->cputype() != CPU_TYPE_X86_64
)
1260 if ( header
->filetype() != MH_OBJECT
)
1266 bool Parser
<arm
>::validFile(const uint8_t* fileContent
, bool subtypeMustMatch
, cpu_subtype_t subtype
)
1268 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1269 if ( header
->magic() != MH_MAGIC
)
1271 if ( header
->cputype() != CPU_TYPE_ARM
)
1273 if ( header
->filetype() != MH_OBJECT
)
1275 if ( subtypeMustMatch
) {
1276 if ( (cpu_subtype_t
)header
->cpusubtype() == subtype
)
1278 // hack until libcc_kext.a is made fat
1279 if ( header
->cpusubtype() == CPU_SUBTYPE_ARM_ALL
)
1288 bool Parser
<arm64
>::validFile(const uint8_t* fileContent
, bool subtypeMustMatch
, cpu_subtype_t subtype
)
1290 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1291 if ( header
->magic() != MH_MAGIC_64
)
1293 if ( header
->cputype() != CPU_TYPE_ARM64
)
1295 if ( header
->filetype() != MH_OBJECT
)
1302 const char* Parser
<x86
>::fileKind(const uint8_t* fileContent
)
1304 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1305 if ( header
->magic() != MH_MAGIC
)
1307 if ( header
->cputype() != CPU_TYPE_I386
)
1313 const char* Parser
<x86_64
>::fileKind(const uint8_t* fileContent
)
1315 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1316 if ( header
->magic() != MH_MAGIC
)
1318 if ( header
->cputype() != CPU_TYPE_X86_64
)
1324 const char* Parser
<arm
>::fileKind(const uint8_t* fileContent
)
1326 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1327 if ( header
->magic() != MH_MAGIC
)
1329 if ( header
->cputype() != CPU_TYPE_ARM
)
1331 for (const ArchInfo
* t
=archInfoArray
; t
->archName
!= NULL
; ++t
) {
1332 if ( (t
->cpuType
== CPU_TYPE_ARM
) && ((cpu_subtype_t
)header
->cpusubtype() == t
->cpuSubType
) ) {
1339 #if SUPPORT_ARCH_arm64
1341 const char* Parser
<arm64
>::fileKind(const uint8_t* fileContent
)
1343 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1344 if ( header
->magic() != MH_MAGIC
)
1346 if ( header
->cputype() != CPU_TYPE_ARM64
)
1352 template <typename A
>
1353 bool Parser
<A
>::hasObjC2Categories(const uint8_t* fileContent
)
1355 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1356 const uint32_t cmd_count
= header
->ncmds();
1357 const macho_load_command
<P
>* const cmds
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>));
1358 const macho_load_command
<P
>* const cmdsEnd
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>) + header
->sizeofcmds());
1359 const macho_load_command
<P
>* cmd
= cmds
;
1360 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1361 if ( cmd
->cmd() == macho_segment_command
<P
>::CMD
) {
1362 const macho_segment_command
<P
>* segment
= (macho_segment_command
<P
>*)cmd
;
1363 const macho_section
<P
>* sectionsStart
= (macho_section
<P
>*)((char*)segment
+ sizeof(macho_segment_command
<P
>));
1364 for (uint32_t si
=0; si
< segment
->nsects(); ++si
) {
1365 const macho_section
<P
>* sect
= §ionsStart
[si
];
1366 if ( (sect
->size() > 0)
1367 && (strcmp(sect
->sectname(), "__objc_catlist") == 0)
1368 && (strcmp(sect
->segname(), "__DATA") == 0) ) {
1373 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
1374 if ( cmd
> cmdsEnd
)
1375 throwf("malformed mach-o file, load command #%d is outside size of load commands", i
);
1381 template <typename A
>
1382 bool Parser
<A
>::hasObjC1Categories(const uint8_t* fileContent
)
1384 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1385 const uint32_t cmd_count
= header
->ncmds();
1386 const macho_load_command
<P
>* const cmds
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>));
1387 const macho_load_command
<P
>* const cmdsEnd
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>) + header
->sizeofcmds());
1388 const macho_load_command
<P
>* cmd
= cmds
;
1389 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1390 if ( cmd
->cmd() == macho_segment_command
<P
>::CMD
) {
1391 const macho_segment_command
<P
>* segment
= (macho_segment_command
<P
>*)cmd
;
1392 const macho_section
<P
>* sectionsStart
= (macho_section
<P
>*)((char*)segment
+ sizeof(macho_segment_command
<P
>));
1393 for (uint32_t si
=0; si
< segment
->nsects(); ++si
) {
1394 const macho_section
<P
>* sect
= §ionsStart
[si
];
1395 if ( (sect
->size() > 0)
1396 && (strcmp(sect
->sectname(), "__category") == 0)
1397 && (strcmp(sect
->segname(), "__OBJC") == 0) ) {
1402 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
1403 if ( cmd
> cmdsEnd
)
1404 throwf("malformed mach-o file, load command #%d is outside size of load commands", i
);
1409 template <typename A
>
1410 int Parser
<A
>::pointerSorter(const void* l
, const void* r
)
1412 // sort references by address
1413 const pint_t
* left
= (pint_t
*)l
;
1414 const pint_t
* right
= (pint_t
*)r
;
1415 return (*left
- *right
);
1418 template <typename A
>
1419 typename
A::P::uint_t Parser
<A
>::LabelAndCFIBreakIterator::peek(Parser
<A
>& parser
, pint_t startAddr
, pint_t endAddr
)
1422 if ( symIndex
< sortedSymbolCount
)
1423 symbolAddr
= parser
.symbolFromIndex(sortedSymbolIndexes
[symIndex
]).n_value();
1425 symbolAddr
= endAddr
;
1427 if ( cfiIndex
< cfiStartsCount
)
1428 cfiAddr
= cfiStartsArray
[cfiIndex
];
1431 if ( (cfiAddr
< symbolAddr
) && (cfiAddr
>= startAddr
) ) {
1432 if ( cfiAddr
< endAddr
)
1438 if ( symbolAddr
< endAddr
)
1446 // Parses up a section into chunks based on labels and CFI information.
1447 // Each call returns the next chunk address and size, and (if the break
1448 // was becuase of a label, the symbol). Returns false when no more chunks.
1450 template <typename A
>
1451 bool Parser
<A
>::LabelAndCFIBreakIterator::next(Parser
<A
>& parser
, const Section
<A
>& sect
, uint32_t sectNum
, pint_t startAddr
, pint_t endAddr
,
1452 pint_t
* addr
, pint_t
* size
, const macho_nlist
<P
>** symbol
)
1454 // may not be a label on start of section, but need atom demarcation there
1457 // advance symIndex until we get to the first label at or past the start of this section
1458 while ( symIndex
< sortedSymbolCount
) {
1459 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(sortedSymbolIndexes
[symIndex
]);
1460 if ( ! sect
.ignoreLabel(parser
.nameFromSymbol(sym
)) ) {
1461 pint_t nextSymbolAddr
= sym
.n_value();
1462 //fprintf(stderr, "sectNum=%d, nextSymbolAddr=0x%08llX, name=%s\n", sectNum, (uint64_t)nextSymbolAddr, parser.nameFromSymbol(sym));
1463 if ( (nextSymbolAddr
> startAddr
) || ((nextSymbolAddr
== startAddr
) && (sym
.n_sect() == sectNum
)) )
1468 if ( symIndex
< sortedSymbolCount
) {
1469 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(sortedSymbolIndexes
[symIndex
]);
1470 pint_t nextSymbolAddr
= sym
.n_value();
1471 // if next symbol found is not in this section
1472 if ( sym
.n_sect() != sectNum
) {
1473 // check for CFI break instead of symbol break
1474 if ( cfiIndex
< cfiStartsCount
) {
1475 pint_t nextCfiAddr
= cfiStartsArray
[cfiIndex
];
1476 if ( nextCfiAddr
< endAddr
) {
1479 *addr
= nextCfiAddr
;
1480 *size
= peek(parser
, startAddr
, endAddr
) - nextCfiAddr
;
1486 *size
= endAddr
- startAddr
;
1488 if ( startAddr
== endAddr
)
1489 return false; // zero size section
1491 return true; // whole section is one atom with no label
1493 // if also CFI break here, eat it
1494 if ( cfiIndex
< cfiStartsCount
) {
1495 if ( cfiStartsArray
[cfiIndex
] == nextSymbolAddr
)
1498 if ( nextSymbolAddr
== startAddr
) {
1499 // label at start of section, return it as chunk
1502 *size
= peek(parser
, startAddr
, endAddr
) - startAddr
;
1506 // return chunk before first symbol
1508 *size
= nextSymbolAddr
- startAddr
;
1512 // no symbols in section, check CFI
1513 if ( cfiIndex
< cfiStartsCount
) {
1514 pint_t nextCfiAddr
= cfiStartsArray
[cfiIndex
];
1515 if ( nextCfiAddr
< endAddr
) {
1518 *addr
= nextCfiAddr
;
1519 *size
= peek(parser
, startAddr
, endAddr
) - nextCfiAddr
;
1524 // no cfi, so whole section is one chunk
1526 *size
= endAddr
- startAddr
;
1528 if ( startAddr
== endAddr
)
1529 return false; // zero size section
1531 return true; // whole section is one atom with no label
1534 while ( (symIndex
< sortedSymbolCount
) && (cfiIndex
< cfiStartsCount
) ) {
1535 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(sortedSymbolIndexes
[symIndex
]);
1536 pint_t nextSymbolAddr
= sym
.n_value();
1537 pint_t nextCfiAddr
= cfiStartsArray
[cfiIndex
];
1538 if ( nextSymbolAddr
< nextCfiAddr
) {
1539 if ( nextSymbolAddr
>= endAddr
)
1542 if ( nextSymbolAddr
< startAddr
)
1544 *addr
= nextSymbolAddr
;
1545 *size
= peek(parser
, startAddr
, endAddr
) - nextSymbolAddr
;
1549 else if ( nextCfiAddr
< nextSymbolAddr
) {
1550 if ( nextCfiAddr
>= endAddr
)
1553 if ( nextCfiAddr
< startAddr
)
1555 *addr
= nextCfiAddr
;
1556 *size
= peek(parser
, startAddr
, endAddr
) - nextCfiAddr
;
1561 if ( nextCfiAddr
>= endAddr
)
1565 if ( nextCfiAddr
< startAddr
)
1567 *addr
= nextCfiAddr
;
1568 *size
= peek(parser
, startAddr
, endAddr
) - nextCfiAddr
;
1573 while ( symIndex
< sortedSymbolCount
) {
1574 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(sortedSymbolIndexes
[symIndex
]);
1575 pint_t nextSymbolAddr
= sym
.n_value();
1576 // if next symbol found is not in this section, then done with iteration
1577 if ( sym
.n_sect() != sectNum
)
1580 if ( nextSymbolAddr
< startAddr
)
1582 *addr
= nextSymbolAddr
;
1583 *size
= peek(parser
, startAddr
, endAddr
) - nextSymbolAddr
;
1587 while ( cfiIndex
< cfiStartsCount
) {
1588 pint_t nextCfiAddr
= cfiStartsArray
[cfiIndex
];
1589 if ( nextCfiAddr
>= endAddr
)
1592 if ( nextCfiAddr
< startAddr
)
1594 *addr
= nextCfiAddr
;
1595 *size
= peek(parser
, startAddr
, endAddr
) - nextCfiAddr
;
1603 typename
arm::P::uint_t Parser
<arm
>::realAddr(typename
arm::P::uint_t addr
)
1608 template <typename A
>
1609 typename
A::P::uint_t Parser
<A
>::realAddr(typename
A::P::uint_t addr
)
1614 #define STACK_ALLOC_IF_SMALL(_type, _name, _actual_count, _maxCount) \
1615 _type* _name = NULL; \
1616 uint32_t _name##_count = 1; \
1617 if ( _actual_count > _maxCount ) \
1618 _name = (_type*)malloc(sizeof(_type) * _actual_count); \
1620 _name##_count = _actual_count; \
1621 _type _name##_buffer[_name##_count]; \
1622 if ( _name == NULL ) \
1623 _name = _name##_buffer;
1626 template <typename A
>
1627 ld::relocatable::File
* Parser
<A
>::parse(const ParserOptions
& opts
)
1629 // create file object
1630 _file
= new File
<A
>(_path
, _modTime
, _fileContent
, _ordinal
);
1632 // respond to -t option
1633 if ( opts
.logAllFiles
)
1634 printf("%s\n", _path
);
1636 // parse start of mach-o file
1637 if ( ! parseLoadCommands() )
1641 uint32_t sortedSectionIndexes
[_machOSectionsCount
];
1642 this->makeSortedSectionsArray(sortedSectionIndexes
);
1644 // make symbol table sorted by address
1645 this->prescanSymbolTable();
1646 uint32_t sortedSymbolIndexes
[_symbolsInSections
];
1647 this->makeSortedSymbolsArray(sortedSymbolIndexes
, sortedSectionIndexes
);
1649 // allocate Section<A> object for each mach-o section
1652 // if it exists, do special early parsing of __compact_unwind section
1653 uint32_t countOfCUs
= 0;
1654 if ( _compactUnwindSection
!= NULL
)
1655 countOfCUs
= _compactUnwindSection
->count();
1656 // stack allocate (if not too large) cuInfoBuffer
1657 STACK_ALLOC_IF_SMALL(typename CUSection
<A
>::Info
, cuInfoArray
, countOfCUs
, 1024);
1658 if ( countOfCUs
!= 0 )
1659 _compactUnwindSection
->parse(*this, countOfCUs
, cuInfoArray
);
1661 // create lists of address that already have compact unwind and thus don't need the dwarf parsed
1662 unsigned cuLsdaCount
= 0;
1663 pint_t cuStarts
[countOfCUs
];
1664 for (uint32_t i
=0; i
< countOfCUs
; ++i
) {
1665 if ( CUSection
<A
>::encodingMeansUseDwarf(cuInfoArray
[i
].compactUnwindInfo
) )
1668 cuStarts
[i
] = cuInfoArray
[i
].functionStartAddress
;
1669 if ( cuInfoArray
[i
].lsdaAddress
!= 0 )
1674 // if it exists, do special early parsing of __eh_frame section
1675 // stack allocate (if not too large) array of CFI_Atom_Info
1676 uint32_t countOfCFIs
= 0;
1677 if ( _EHFrameSection
!= NULL
)
1678 countOfCFIs
= _EHFrameSection
->cfiCount(*this);
1679 STACK_ALLOC_IF_SMALL(typename CFISection
<A
>::CFI_Atom_Info
, cfiArray
, countOfCFIs
, 1024);
1681 // stack allocate (if not too large) a copy of __eh_frame to apply relocations to
1682 uint32_t sectSize
= 4;
1683 if ( (countOfCFIs
!= 0) && _EHFrameSection
->needsRelocating() )
1684 sectSize
= _EHFrameSection
->machoSection()->size()+4;
1685 STACK_ALLOC_IF_SMALL(uint8_t, ehBuffer
, sectSize
, 50*1024);
1686 uint32_t cfiStartsCount
= 0;
1687 if ( countOfCFIs
!= 0 ) {
1688 _EHFrameSection
->cfiParse(*this, ehBuffer
, cfiArray
, countOfCFIs
, cuStarts
, countOfCUs
);
1689 // count functions and lsdas
1690 for(uint32_t i
=0; i
< countOfCFIs
; ++i
) {
1691 if ( cfiArray
[i
].isCIE
)
1693 //fprintf(stderr, "cfiArray[i].func = 0x%08llX, cfiArray[i].lsda = 0x%08llX, encoding=0x%08X\n",
1694 // (uint64_t)cfiArray[i].u.fdeInfo.function.targetAddress,
1695 // (uint64_t)cfiArray[i].u.fdeInfo.lsda.targetAddress,
1696 // cfiArray[i].u.fdeInfo.compactUnwindInfo);
1697 if ( cfiArray
[i
].u
.fdeInfo
.function
.targetAddress
!= CFI_INVALID_ADDRESS
)
1699 if ( cfiArray
[i
].u
.fdeInfo
.lsda
.targetAddress
!= CFI_INVALID_ADDRESS
)
1703 CFI_CU_InfoArrays
cfis(cfiArray
, countOfCFIs
, cuInfoArray
, countOfCUs
);
1705 // create sorted array of function starts and lsda starts
1706 pint_t cfiStartsArray
[cfiStartsCount
+cuLsdaCount
];
1707 uint32_t countOfFDEs
= 0;
1708 uint32_t cfiStartsArrayCount
= 0;
1709 if ( countOfCFIs
!= 0 ) {
1710 for(uint32_t i
=0; i
< countOfCFIs
; ++i
) {
1711 if ( cfiArray
[i
].isCIE
)
1713 if ( cfiArray
[i
].u
.fdeInfo
.function
.targetAddress
!= CFI_INVALID_ADDRESS
)
1714 cfiStartsArray
[cfiStartsArrayCount
++] = realAddr(cfiArray
[i
].u
.fdeInfo
.function
.targetAddress
);
1715 if ( cfiArray
[i
].u
.fdeInfo
.lsda
.targetAddress
!= CFI_INVALID_ADDRESS
)
1716 cfiStartsArray
[cfiStartsArrayCount
++] = cfiArray
[i
].u
.fdeInfo
.lsda
.targetAddress
;
1720 if ( cuLsdaCount
!= 0 ) {
1721 // merge in an lsda info from compact unwind
1722 for (uint32_t i
=0; i
< countOfCUs
; ++i
) {
1723 if ( cuInfoArray
[i
].lsdaAddress
== 0 )
1725 // append to cfiStartsArray if not already in that list
1727 for(uint32_t j
=0; j
< cfiStartsArrayCount
; ++j
) {
1728 if ( cfiStartsArray
[j
] == cuInfoArray
[i
].lsdaAddress
)
1732 cfiStartsArray
[cfiStartsArrayCount
++] = cuInfoArray
[i
].lsdaAddress
;
1736 if ( cfiStartsArrayCount
!= 0 ) {
1737 ::qsort(cfiStartsArray
, cfiStartsArrayCount
, sizeof(pint_t
), pointerSorter
);
1739 // scan for FDEs claming the same function
1740 for(uint32_t i
=1; i
< cfiStartsArrayCount
; ++i
) {
1741 assert( cfiStartsArray
[i
] != cfiStartsArray
[i
-1] );
1746 Section
<A
>** sections
= _file
->_sectionsArray
;
1747 uint32_t sectionsCount
= _file
->_sectionsArrayCount
;
1749 // figure out how many atoms will be allocated and allocate
1750 LabelAndCFIBreakIterator
breakIterator(sortedSymbolIndexes
, _symbolsInSections
, cfiStartsArray
,
1751 cfiStartsArrayCount
, _overlappingSymbols
);
1752 uint32_t computedAtomCount
= 0;
1753 for (uint32_t i
=0; i
< sectionsCount
; ++i
) {
1754 breakIterator
.beginSection();
1755 uint32_t count
= sections
[i
]->computeAtomCount(*this, breakIterator
, cfis
);
1756 //const macho_section<P>* sect = sections[i]->machoSection();
1757 //fprintf(stderr, "computed count=%u for section %s size=%llu\n", count, sect->sectname(), (sect != NULL) ? sect->size() : 0);
1758 computedAtomCount
+= count
;
1760 //fprintf(stderr, "allocating %d atoms * sizeof(Atom<A>)=%ld, sizeof(ld::Atom)=%ld\n", computedAtomCount, sizeof(Atom<A>), sizeof(ld::Atom));
1761 _file
->_atomsArray
= new uint8_t[computedAtomCount
*sizeof(Atom
<A
>)];
1762 _file
->_atomsArrayCount
= 0;
1764 // have each section append atoms to _atomsArray
1765 LabelAndCFIBreakIterator
breakIterator2(sortedSymbolIndexes
, _symbolsInSections
, cfiStartsArray
,
1766 cfiStartsArrayCount
, _overlappingSymbols
);
1767 for (uint32_t i
=0; i
< sectionsCount
; ++i
) {
1768 uint8_t* atoms
= _file
->_atomsArray
+ _file
->_atomsArrayCount
*sizeof(Atom
<A
>);
1769 breakIterator2
.beginSection();
1770 uint32_t count
= sections
[i
]->appendAtoms(*this, atoms
, breakIterator2
, cfis
);
1771 //fprintf(stderr, "append count=%u for section %s/%s\n", count, sections[i]->machoSection()->segname(), sections[i]->machoSection()->sectname());
1772 _file
->_atomsArrayCount
+= count
;
1774 assert( _file
->_atomsArrayCount
== computedAtomCount
&& "more atoms allocated than expected");
1777 // have each section add all fix-ups for its atoms
1778 _allFixups
.reserve(computedAtomCount
*5);
1779 for (uint32_t i
=0; i
< sectionsCount
; ++i
)
1780 sections
[i
]->makeFixups(*this, cfis
);
1782 // assign fixups start offset for each atom
1783 uint8_t* p
= _file
->_atomsArray
;
1784 uint32_t fixupOffset
= 0;
1785 for(int i
=_file
->_atomsArrayCount
; i
> 0; --i
) {
1786 Atom
<A
>* atom
= (Atom
<A
>*)p
;
1787 atom
->_fixupsStartIndex
= fixupOffset
;
1788 fixupOffset
+= atom
->_fixupsCount
;
1789 atom
->_fixupsCount
= 0;
1790 p
+= sizeof(Atom
<A
>);
1792 assert(fixupOffset
== _allFixups
.size());
1793 _file
->_fixups
.reserve(fixupOffset
);
1795 // copy each fixup for each atom
1796 for(typename
std::vector
<FixupInAtom
>::iterator it
=_allFixups
.begin(); it
!= _allFixups
.end(); ++it
) {
1797 uint32_t slot
= it
->atom
->_fixupsStartIndex
+ it
->atom
->_fixupsCount
;
1798 _file
->_fixups
[slot
] = it
->fixup
;
1799 it
->atom
->_fixupsCount
++;
1802 // done with temp vector
1806 _file
->_unwindInfos
.reserve(countOfFDEs
+countOfCUs
);
1807 for(uint32_t i
=0; i
< countOfCFIs
; ++i
) {
1808 if ( cfiArray
[i
].isCIE
)
1810 if ( cfiArray
[i
].u
.fdeInfo
.function
.targetAddress
!= CFI_INVALID_ADDRESS
) {
1811 ld::Atom::UnwindInfo info
;
1812 info
.startOffset
= 0;
1813 info
.unwindInfo
= cfiArray
[i
].u
.fdeInfo
.compactUnwindInfo
;
1814 _file
->_unwindInfos
.push_back(info
);
1815 Atom
<A
>* func
= findAtomByAddress(cfiArray
[i
].u
.fdeInfo
.function
.targetAddress
);
1816 func
->setUnwindInfoRange(_file
->_unwindInfos
.size()-1, 1);
1817 //fprintf(stderr, "cu from dwarf =0x%08X, atom=%s\n", info.unwindInfo, func->name());
1820 // apply compact infos in __LD,__compact_unwind section to each function
1821 // if function also has dwarf unwind, CU will override it
1822 Atom
<A
>* lastFunc
= NULL
;
1823 uint32_t lastEnd
= 0;
1824 for(uint32_t i
=0; i
< countOfCUs
; ++i
) {
1825 typename CUSection
<A
>::Info
* info
= &cuInfoArray
[i
];
1826 assert(info
->function
!= NULL
);
1827 ld::Atom::UnwindInfo ui
;
1828 ui
.startOffset
= info
->functionStartAddress
- info
->function
->objectAddress();
1829 ui
.unwindInfo
= info
->compactUnwindInfo
;
1830 _file
->_unwindInfos
.push_back(ui
);
1831 // don't override with converted cu with "use dwarf" cu, if forcing dwarf conversion
1832 if ( !_forceDwarfConversion
|| !CUSection
<A
>::encodingMeansUseDwarf(info
->compactUnwindInfo
) ) {
1833 //fprintf(stderr, "cu=0x%08X, atom=%s\n", ui.unwindInfo, info->function->name());
1834 // if previous is for same function, extend range
1835 if ( info
->function
== lastFunc
) {
1836 if ( lastEnd
!= ui
.startOffset
) {
1837 if ( lastEnd
< ui
.startOffset
)
1838 warning("__LD,__compact_unwind entries for %s have a gap at offset 0x%0X", info
->function
->name(), lastEnd
);
1840 warning("__LD,__compact_unwind entries for %s overlap at offset 0x%0X", info
->function
->name(), lastEnd
);
1842 lastFunc
->extendUnwindInfoRange();
1845 info
->function
->setUnwindInfoRange(_file
->_unwindInfos
.size()-1, 1);
1846 lastFunc
= info
->function
;
1847 lastEnd
= ui
.startOffset
+ info
->rangeLength
;
1851 // process indirect symbols which become AliasAtoms
1852 _file
->_aliasAtomsArray
= NULL
;
1853 _file
->_aliasAtomsArrayCount
= 0;
1854 if ( _indirectSymbolCount
!= 0 ) {
1855 _file
->_aliasAtomsArrayCount
= _indirectSymbolCount
;
1856 _file
->_aliasAtomsArray
= new uint8_t[_file
->_aliasAtomsArrayCount
*sizeof(AliasAtom
)];
1857 this->appendAliasAtoms(_file
->_aliasAtomsArray
);
1861 // parse dwarf debug info to get line info
1862 this->parseDebugInfo();
1868 template <> uint8_t Parser
<x86
>::loadCommandSizeMask() { return 0x03; }
1869 template <> uint8_t Parser
<x86_64
>::loadCommandSizeMask() { return 0x07; }
1870 template <> uint8_t Parser
<arm
>::loadCommandSizeMask() { return 0x03; }
1871 template <> uint8_t Parser
<arm64
>::loadCommandSizeMask() { return 0x07; }
1873 template <typename A
>
1874 bool Parser
<A
>::parseLoadCommands()
1876 const macho_header
<P
>* header
= (const macho_header
<P
>*)_fileContent
;
1878 // set File attributes
1879 _file
->_canScatterAtoms
= (header
->flags() & MH_SUBSECTIONS_VIA_SYMBOLS
);
1880 _file
->_cpuSubType
= header
->cpusubtype();
1882 const macho_segment_command
<P
>* segment
= NULL
;
1883 const uint8_t* const endOfFile
= _fileContent
+ _fileLength
;
1884 const uint32_t cmd_count
= header
->ncmds();
1885 // <rdar://problem/5394172> an empty .o file with zero load commands will crash linker
1886 if ( cmd_count
== 0 )
1888 const macho_load_command
<P
>* const cmds
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>));
1889 const macho_load_command
<P
>* const cmdsEnd
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>) + header
->sizeofcmds());
1890 const macho_load_command
<P
>* cmd
= cmds
;
1891 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1892 uint32_t size
= cmd
->cmdsize();
1893 if ( (size
& this->loadCommandSizeMask()) != 0 )
1894 throwf("load command #%d has a unaligned size", i
);
1895 const uint8_t* endOfCmd
= ((uint8_t*)cmd
)+cmd
->cmdsize();
1896 if ( endOfCmd
> (uint8_t*)cmdsEnd
)
1897 throwf("load command #%d extends beyond the end of the load commands", i
);
1898 if ( endOfCmd
> endOfFile
)
1899 throwf("load command #%d extends beyond the end of the file", i
);
1900 switch (cmd
->cmd()) {
1903 const macho_symtab_command
<P
>* symtab
= (macho_symtab_command
<P
>*)cmd
;
1904 _symbolCount
= symtab
->nsyms();
1905 _symbols
= (const macho_nlist
<P
>*)(_fileContent
+ symtab
->symoff());
1906 _strings
= (char*)_fileContent
+ symtab
->stroff();
1907 _stringsSize
= symtab
->strsize();
1908 if ( (symtab
->symoff() + _symbolCount
*sizeof(macho_nlist
<P
>)) > _fileLength
)
1909 throw "mach-o symbol table extends beyond end of file";
1910 if ( (_strings
+ _stringsSize
) > (char*)endOfFile
)
1911 throw "mach-o string pool extends beyond end of file";
1912 if ( _indirectTable
== NULL
) {
1913 if ( _undefinedEndIndex
== 0 ) {
1914 _undefinedStartIndex
= 0;
1915 _undefinedEndIndex
= symtab
->nsyms();
1922 const macho_dysymtab_command
<P
>* dsymtab
= (macho_dysymtab_command
<P
>*)cmd
;
1923 _indirectTable
= (uint32_t*)(_fileContent
+ dsymtab
->indirectsymoff());
1924 _indirectTableCount
= dsymtab
->nindirectsyms();
1925 if ( &_indirectTable
[_indirectTableCount
] > (uint32_t*)endOfFile
)
1926 throw "indirect symbol table extends beyond end of file";
1927 _undefinedStartIndex
= dsymtab
->iundefsym();
1928 _undefinedEndIndex
= _undefinedStartIndex
+ dsymtab
->nundefsym();
1934 case LC_DATA_IN_CODE
:
1936 const macho_linkedit_data_command
<P
>* dc
= (macho_linkedit_data_command
<P
>*)cmd
;
1937 _dataInCodeStart
= (macho_data_in_code_entry
<P
>*)(_fileContent
+ dc
->dataoff());
1938 _dataInCodeEnd
= (macho_data_in_code_entry
<P
>*)(_fileContent
+ dc
->dataoff() + dc
->datasize());
1939 if ( _dataInCodeEnd
> (macho_data_in_code_entry
<P
>*)endOfFile
)
1940 throw "LC_DATA_IN_CODE table extends beyond end of file";
1943 case LC_LINKER_OPTION
:
1945 const macho_linker_option_command
<P
>* loc
= (macho_linker_option_command
<P
>*)cmd
;
1946 const char* buffer
= loc
->buffer();
1947 _file
->_linkerOptions
.resize(_file
->_linkerOptions
.size() + 1);
1948 std::vector
<const char*>& vec
= _file
->_linkerOptions
.back();
1949 for (uint32_t j
=0; j
< loc
->count(); ++j
) {
1950 vec
.push_back(buffer
);
1951 buffer
+= strlen(buffer
) + 1;
1953 if ( buffer
> ((char*)cmd
+ loc
->cmdsize()) )
1954 throw "malformed LC_LINKER_OPTION";
1957 case LC_LINKER_OPTIMIZATION_HINTS
:
1959 const macho_linkedit_data_command
<P
>* loh
= (macho_linkedit_data_command
<P
>*)cmd
;
1960 _lohStart
= _fileContent
+ loh
->dataoff();
1961 _lohEnd
= _fileContent
+ loh
->dataoff() + loh
->datasize();
1962 if ( _lohEnd
> endOfFile
)
1963 throw "LC_LINKER_OPTIMIZATION_HINTS table extends beyond end of file";
1967 if ( cmd
->cmd() == macho_segment_command
<P
>::CMD
) {
1968 if ( segment
!= NULL
)
1969 throw "more than one LC_SEGMENT found in object file";
1970 segment
= (macho_segment_command
<P
>*)cmd
;
1974 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
1975 if ( cmd
> cmdsEnd
)
1976 throwf("malformed mach-o file, load command #%d is outside size of load commands", i
);
1979 // record range of sections
1980 if ( segment
== NULL
)
1981 throw "missing LC_SEGMENT";
1982 _sectionsStart
= (macho_section
<P
>*)((char*)segment
+ sizeof(macho_segment_command
<P
>));
1983 _machOSectionsCount
= segment
->nsects();
1989 template <typename A
>
1990 void Parser
<A
>::prescanSymbolTable()
1992 _tentativeDefinitionCount
= 0;
1993 _absoluteSymbolCount
= 0;
1994 _symbolsInSections
= 0;
1995 _hasDataInCodeLabels
= false;
1996 for (uint32_t i
=0; i
< this->_symbolCount
; ++i
) {
1997 const macho_nlist
<P
>& sym
= symbolFromIndex(i
);
1999 if ( (sym
.n_type() & N_STAB
) != 0 )
2002 // look at undefines
2003 const char* symbolName
= this->nameFromSymbol(sym
);
2004 if ( (sym
.n_type() & N_TYPE
) == N_UNDF
) {
2005 if ( sym
.n_value() != 0 ) {
2006 // count tentative definitions
2007 ++_tentativeDefinitionCount
;
2009 else if ( strncmp(symbolName
, "___dtrace_", 10) == 0 ) {
2010 // any undefined starting with __dtrace_*$ that is not ___dtrace_probe$* or ___dtrace_isenabled$*
2011 // is extra provider info
2012 if ( (strncmp(&symbolName
[10], "probe$", 6) != 0) && (strncmp(&symbolName
[10], "isenabled$", 10) != 0) ) {
2013 _dtraceProviderInfo
.push_back(symbolName
);
2018 else if ( ((sym
.n_type() & N_TYPE
) == N_INDR
) && ((sym
.n_type() & N_EXT
) != 0) ) {
2019 _indirectSymbolCount
++;
2023 // count absolute symbols
2024 if ( (sym
.n_type() & N_TYPE
) == N_ABS
) {
2025 const char* absName
= this->nameFromSymbol(sym
);
2026 // ignore .objc_class_name_* symbols
2027 if ( strncmp(absName
, ".objc_class_name_", 17) == 0 ) {
2031 // ignore .objc_class_name_* symbols
2032 if ( strncmp(absName
, ".objc_category_name_", 20) == 0 )
2034 // ignore empty *.eh symbols
2035 if ( strcmp(&absName
[strlen(absName
)-3], ".eh") == 0 )
2037 ++_absoluteSymbolCount
;
2040 // only look at definitions
2041 if ( (sym
.n_type() & N_TYPE
) != N_SECT
)
2044 // 'L' labels do not denote atom breaks
2045 if ( symbolName
[0] == 'L' ) {
2046 // <rdar://problem/9218847> Formalize data in code with L$start$ labels
2047 if ( strncmp(symbolName
, "L$start$", 8) == 0 )
2048 _hasDataInCodeLabels
= true;
2051 // how many def syms in each section
2052 if ( sym
.n_sect() > _machOSectionsCount
)
2053 throw "bad n_sect in symbol table";
2055 _symbolsInSections
++;
2059 template <typename A
>
2060 void Parser
<A
>::appendAliasAtoms(uint8_t* p
)
2062 for (uint32_t i
=0; i
< this->_symbolCount
; ++i
) {
2063 const macho_nlist
<P
>& sym
= symbolFromIndex(i
);
2065 if ( (sym
.n_type() & N_STAB
) != 0 )
2068 // only look at N_INDR symbols
2069 if ( (sym
.n_type() & N_TYPE
) != N_INDR
)
2072 // skip non-external aliases
2073 if ( (sym
.n_type() & N_EXT
) == 0 )
2076 const char* symbolName
= this->nameFromSymbol(sym
);
2077 const char* aliasOfName
= &_strings
[sym
.n_value()];
2078 bool isHiddenVisibility
= (sym
.n_type() & N_PEXT
);
2079 AliasAtom
* allocatedSpace
= (AliasAtom
*)p
;
2080 new (allocatedSpace
) AliasAtom(symbolName
, isHiddenVisibility
, _file
, aliasOfName
);
2081 p
+= sizeof(AliasAtom
);
2087 template <typename A
>
2088 int Parser
<A
>::sectionIndexSorter(void* extra
, const void* l
, const void* r
)
2090 Parser
<A
>* parser
= (Parser
<A
>*)extra
;
2091 const uint32_t* left
= (uint32_t*)l
;
2092 const uint32_t* right
= (uint32_t*)r
;
2093 const macho_section
<P
>* leftSect
= parser
->machOSectionFromSectionIndex(*left
);
2094 const macho_section
<P
>* rightSect
= parser
->machOSectionFromSectionIndex(*right
);
2096 // can't just return difference because 64-bit diff does not fit in 32-bit return type
2097 int64_t result
= leftSect
->addr() - rightSect
->addr();
2098 if ( result
== 0 ) {
2099 // two sections with same start address
2100 // one with zero size goes first
2101 bool leftEmpty
= ( leftSect
->size() == 0 );
2102 bool rightEmpty
= ( rightSect
->size() == 0 );
2103 if ( leftEmpty
!= rightEmpty
) {
2104 return ( rightEmpty
? 1 : -1 );
2106 if ( !leftEmpty
&& !rightEmpty
)
2107 throwf("overlapping sections");
2108 // both empty, so chose file order
2109 return ( rightSect
- leftSect
);
2111 else if ( result
< 0 )
2117 template <typename A
>
2118 void Parser
<A
>::makeSortedSectionsArray(uint32_t array
[])
2120 const bool log
= false;
2123 fprintf(stderr
, "unsorted sections:\n");
2124 for(unsigned int i
=0; i
< _machOSectionsCount
; ++i
)
2125 fprintf(stderr
, "0x%08llX %s %s\n", _sectionsStart
[i
].addr(), _sectionsStart
[i
].segname(), _sectionsStart
[i
].sectname());
2128 // sort by symbol table address
2129 for (uint32_t i
=0; i
< _machOSectionsCount
; ++i
)
2131 ::qsort_r(array
, _machOSectionsCount
, sizeof(uint32_t), this, §ionIndexSorter
);
2134 fprintf(stderr
, "sorted sections:\n");
2135 for(unsigned int i
=0; i
< _machOSectionsCount
; ++i
)
2136 fprintf(stderr
, "0x%08llX %s %s\n", _sectionsStart
[array
[i
]].addr(), _sectionsStart
[array
[i
]].segname(), _sectionsStart
[array
[i
]].sectname());
2142 template <typename A
>
2143 int Parser
<A
>::symbolIndexSorter(void* extra
, const void* l
, const void* r
)
2145 ParserAndSectionsArray
* extraInfo
= (ParserAndSectionsArray
*)extra
;
2146 Parser
<A
>* parser
= extraInfo
->parser
;
2147 const uint32_t* sortedSectionsArray
= extraInfo
->sortedSectionsArray
;
2148 const uint32_t* left
= (uint32_t*)l
;
2149 const uint32_t* right
= (uint32_t*)r
;
2150 const macho_nlist
<P
>& leftSym
= parser
->symbolFromIndex(*left
);
2151 const macho_nlist
<P
>& rightSym
= parser
->symbolFromIndex(*right
);
2152 // can't just return difference because 64-bit diff does not fit in 32-bit return type
2153 int64_t result
= leftSym
.n_value() - rightSym
.n_value();
2154 if ( result
== 0 ) {
2155 // two symbols with same address
2156 // if in different sections, sort earlier section first
2157 if ( leftSym
.n_sect() != rightSym
.n_sect() ) {
2158 for (uint32_t i
=0; i
< parser
->machOSectionCount(); ++i
) {
2159 if ( sortedSectionsArray
[i
]+1 == leftSym
.n_sect() )
2161 if ( sortedSectionsArray
[i
]+1 == rightSym
.n_sect() )
2165 // two symbols in same section, means one is an alias
2166 // if one is ltmp*, make it an alias (sort first)
2167 const char* leftName
= parser
->nameFromSymbol(leftSym
);
2168 const char* rightName
= parser
->nameFromSymbol(rightSym
);
2169 bool leftIsTmp
= strncmp(leftName
, "ltmp", 4);
2170 bool rightIsTmp
= strncmp(rightName
, "ltmp", 4);
2171 if ( leftIsTmp
!= rightIsTmp
) {
2172 return (rightIsTmp
? -1 : 1);
2175 // if only one is global, make the other an alias (sort first)
2176 if ( (leftSym
.n_type() & N_EXT
) != (rightSym
.n_type() & N_EXT
) ) {
2177 if ( (rightSym
.n_type() & N_EXT
) != 0 )
2182 // if both are global, sort alphabetically. earlier one will be the alias
2183 return ( strcmp(rightName
, leftName
) );
2185 else if ( result
< 0 )
2192 template <typename A
>
2193 void Parser
<A
>::makeSortedSymbolsArray(uint32_t array
[], const uint32_t sectionArray
[])
2195 const bool log
= false;
2197 uint32_t* p
= array
;
2198 for (uint32_t i
=0; i
< this->_symbolCount
; ++i
) {
2199 const macho_nlist
<P
>& sym
= symbolFromIndex(i
);
2201 if ( (sym
.n_type() & N_STAB
) != 0 )
2204 // only look at definitions
2205 if ( (sym
.n_type() & N_TYPE
) != N_SECT
)
2208 // 'L' labels do not denote atom breaks
2209 const char* symbolName
= this->nameFromSymbol(sym
);
2210 if ( symbolName
[0] == 'L' )
2213 // how many def syms in each section
2214 if ( sym
.n_sect() > _machOSectionsCount
)
2215 throw "bad n_sect in symbol table";
2220 assert(p
== &array
[_symbolsInSections
] && "second pass over symbol table yield a different number of symbols");
2222 // sort by symbol table address
2223 ParserAndSectionsArray extra
= { this, sectionArray
};
2224 ::qsort_r(array
, _symbolsInSections
, sizeof(uint32_t), &extra
, &symbolIndexSorter
);
2227 // look for two symbols at same address
2228 _overlappingSymbols
= false;
2229 for (unsigned int i
=1; i
< _symbolsInSections
; ++i
) {
2230 if ( symbolFromIndex(array
[i
-1]).n_value() == symbolFromIndex(array
[i
]).n_value() ) {
2231 //fprintf(stderr, "overlapping symbols at 0x%08llX\n", symbolFromIndex(array[i-1]).n_value());
2232 _overlappingSymbols
= true;
2238 fprintf(stderr
, "sorted symbols:\n");
2239 for(unsigned int i
=0; i
< _symbolsInSections
; ++i
)
2240 fprintf(stderr
, "0x%09llX symIndex=%d sectNum=%2d, %s\n", symbolFromIndex(array
[i
]).n_value(), array
[i
], symbolFromIndex(array
[i
]).n_sect(), nameFromSymbol(symbolFromIndex(array
[i
])) );
2244 template <typename A
>
2245 void Parser
<A
>::makeSections()
2247 // classify each section by type
2248 // compute how many Section objects will be needed and total size for all
2249 unsigned int totalSectionsSize
= 0;
2250 uint8_t machOSectsStorage
[sizeof(MachOSectionAndSectionClass
<P
>)*(_machOSectionsCount
+2)]; // also room for tentative-defs and absolute symbols
2251 // allocate raw storage for all section objects on stack
2252 MachOSectionAndSectionClass
<P
>* machOSects
= (MachOSectionAndSectionClass
<P
>*)machOSectsStorage
;
2253 unsigned int count
= 0;
2254 for (uint32_t i
=0; i
< _machOSectionsCount
; ++i
) {
2255 const macho_section
<P
>* sect
= &_sectionsStart
[i
];
2256 if ( (sect
->flags() & S_ATTR_DEBUG
) != 0 ) {
2257 if ( strcmp(sect
->segname(), "__DWARF") == 0 ) {
2258 // note that .o file has dwarf
2259 _file
->_debugInfoKind
= ld::relocatable::File::kDebugInfoDwarf
;
2260 // save off iteresting dwarf sections
2261 if ( strcmp(sect
->sectname(), "__debug_info") == 0 )
2262 _file
->_dwarfDebugInfoSect
= sect
;
2263 else if ( strcmp(sect
->sectname(), "__debug_abbrev") == 0 )
2264 _file
->_dwarfDebugAbbrevSect
= sect
;
2265 else if ( strcmp(sect
->sectname(), "__debug_line") == 0 )
2266 _file
->_dwarfDebugLineSect
= sect
;
2267 else if ( strcmp(sect
->sectname(), "__debug_str") == 0 )
2268 _file
->_dwarfDebugStringSect
= sect
;
2269 // linker does not propagate dwarf sections to output file
2272 else if ( strcmp(sect
->segname(), "__LD") == 0 ) {
2273 if ( strncmp(sect
->sectname(), "__compact_unwind", 16) == 0 ) {
2274 machOSects
[count
].sect
= sect
;
2275 totalSectionsSize
+= sizeof(CUSection
<A
>);
2276 machOSects
[count
++].type
= sectionTypeCompactUnwind
;
2281 // ignore empty __OBJC sections
2282 if ( (sect
->size() == 0) && (strcmp(sect
->segname(), "__OBJC") == 0) )
2284 // objc image info section is really attributes and not content
2285 if ( ((strcmp(sect
->sectname(), "__image_info") == 0) && (strcmp(sect
->segname(), "__OBJC") == 0))
2286 || ((strncmp(sect
->sectname(), "__objc_imageinfo", 16) == 0) && (strcmp(sect
->segname(), "__DATA") == 0)) ) {
2287 // struct objc_image_info {
2288 // uint32_t version; // initially 0
2291 // #define OBJC_IMAGE_SUPPORTS_GC 2
2292 // #define OBJC_IMAGE_GC_ONLY 4
2293 // #define OBJC_IMAGE_IS_SIMULATED 32
2295 const uint32_t* contents
= (uint32_t*)(_file
->fileContent()+sect
->offset());
2296 if ( (sect
->size() >= 8) && (contents
[0] == 0) ) {
2297 uint32_t flags
= E::get32(contents
[1]);
2298 if ( (flags
& 4) == 4 )
2299 _file
->_objConstraint
= ld::File::objcConstraintGC
;
2300 else if ( (flags
& 2) == 2 )
2301 _file
->_objConstraint
= ld::File::objcConstraintRetainReleaseOrGC
;
2302 else if ( (flags
& 32) == 32 )
2303 _file
->_objConstraint
= ld::File::objcConstraintRetainReleaseForSimulator
;
2305 _file
->_objConstraint
= ld::File::objcConstraintRetainRelease
;
2306 _file
->_swiftVersion
= ((flags
>> 8) & 0xFF);
2307 if ( sect
->size() > 8 ) {
2308 warning("section %s/%s has unexpectedly large size %llu in %s",
2309 sect
->segname(), Section
<A
>::makeSectionName(sect
), sect
->size(), _file
->path());
2313 warning("can't parse %s/%s section in %s", sect
->segname(), Section
<A
>::makeSectionName(sect
), _file
->path());
2317 machOSects
[count
].sect
= sect
;
2318 switch ( sect
->flags() & SECTION_TYPE
) {
2319 case S_SYMBOL_STUBS
:
2320 if ( _stubsSectionNum
== 0 ) {
2321 _stubsSectionNum
= i
+1;
2322 _stubsMachOSection
= sect
;
2325 assert(1 && "multiple S_SYMBOL_STUBS sections");
2326 case S_LAZY_SYMBOL_POINTERS
:
2328 case S_4BYTE_LITERALS
:
2329 totalSectionsSize
+= sizeof(Literal4Section
<A
>);
2330 machOSects
[count
++].type
= sectionTypeLiteral4
;
2332 case S_8BYTE_LITERALS
:
2333 totalSectionsSize
+= sizeof(Literal8Section
<A
>);
2334 machOSects
[count
++].type
= sectionTypeLiteral8
;
2336 case S_16BYTE_LITERALS
:
2337 totalSectionsSize
+= sizeof(Literal16Section
<A
>);
2338 machOSects
[count
++].type
= sectionTypeLiteral16
;
2340 case S_NON_LAZY_SYMBOL_POINTERS
:
2341 totalSectionsSize
+= sizeof(NonLazyPointerSection
<A
>);
2342 machOSects
[count
++].type
= sectionTypeNonLazy
;
2344 case S_LITERAL_POINTERS
:
2345 if ( (strcmp(sect
->segname(), "__OBJC") == 0) && (strcmp(sect
->sectname(), "__cls_refs") == 0) ) {
2346 totalSectionsSize
+= sizeof(Objc1ClassReferences
<A
>);
2347 machOSects
[count
++].type
= sectionTypeObjC1ClassRefs
;
2350 totalSectionsSize
+= sizeof(PointerToCStringSection
<A
>);
2351 machOSects
[count
++].type
= sectionTypeCStringPointer
;
2354 case S_CSTRING_LITERALS
:
2355 totalSectionsSize
+= sizeof(CStringSection
<A
>);
2356 machOSects
[count
++].type
= sectionTypeCString
;
2358 case S_MOD_INIT_FUNC_POINTERS
:
2359 case S_MOD_TERM_FUNC_POINTERS
:
2360 case S_THREAD_LOCAL_INIT_FUNCTION_POINTERS
:
2365 case S_THREAD_LOCAL_REGULAR
:
2366 case S_THREAD_LOCAL_ZEROFILL
:
2367 if ( (strcmp(sect
->segname(), "__TEXT") == 0) && (strcmp(sect
->sectname(), "__eh_frame") == 0) ) {
2368 totalSectionsSize
+= sizeof(CFISection
<A
>);
2369 machOSects
[count
++].type
= sectionTypeCFI
;
2371 else if ( (strcmp(sect
->segname(), "__DATA") == 0) && (strcmp(sect
->sectname(), "__cfstring") == 0) ) {
2372 totalSectionsSize
+= sizeof(CFStringSection
<A
>);
2373 machOSects
[count
++].type
= sectionTypeCFString
;
2375 else if ( (strcmp(sect
->segname(), "__TEXT") == 0) && (strcmp(sect
->sectname(), "__ustring") == 0) ) {
2376 totalSectionsSize
+= sizeof(UTF16StringSection
<A
>);
2377 machOSects
[count
++].type
= sectionTypeUTF16Strings
;
2379 else if ( (strcmp(sect
->segname(), "__DATA") == 0) && (strncmp(sect
->sectname(), "__objc_classrefs", 16) == 0) ) {
2380 totalSectionsSize
+= sizeof(ObjC2ClassRefsSection
<A
>);
2381 machOSects
[count
++].type
= sectionTypeObjC2ClassRefs
;
2383 else if ( (strcmp(sect
->segname(), "__DATA") == 0) && (strcmp(sect
->sectname(), "__objc_catlist") == 0) ) {
2384 totalSectionsSize
+= sizeof(ObjC2CategoryListSection
<A
>);
2385 machOSects
[count
++].type
= typeObjC2CategoryList
;
2387 else if ( _AppleObjc
&& (strcmp(sect
->segname(), "__OBJC") == 0) && (strcmp(sect
->sectname(), "__class") == 0) ) {
2388 totalSectionsSize
+= sizeof(ObjC1ClassSection
<A
>);
2389 machOSects
[count
++].type
= sectionTypeObjC1Classes
;
2392 totalSectionsSize
+= sizeof(SymboledSection
<A
>);
2393 machOSects
[count
++].type
= sectionTypeSymboled
;
2396 case S_THREAD_LOCAL_VARIABLES
:
2397 totalSectionsSize
+= sizeof(TLVDefsSection
<A
>);
2398 machOSects
[count
++].type
= sectionTypeTLVDefs
;
2400 case S_THREAD_LOCAL_VARIABLE_POINTERS
:
2402 throwf("unknown section type %d", sect
->flags() & SECTION_TYPE
);
2406 // sort by address (mach-o object files don't aways have sections sorted)
2407 ::qsort(machOSects
, count
, sizeof(MachOSectionAndSectionClass
<P
>), MachOSectionAndSectionClass
<P
>::sorter
);
2409 // we will synthesize a dummy Section<A> object for tentative definitions
2410 if ( _tentativeDefinitionCount
> 0 ) {
2411 totalSectionsSize
+= sizeof(TentativeDefinitionSection
<A
>);
2412 machOSects
[count
++].type
= sectionTypeTentativeDefinitions
;
2415 // we will synthesize a dummy Section<A> object for Absolute symbols
2416 if ( _absoluteSymbolCount
> 0 ) {
2417 totalSectionsSize
+= sizeof(AbsoluteSymbolSection
<A
>);
2418 machOSects
[count
++].type
= sectionTypeAbsoluteSymbols
;
2421 // allocate one block for all Section objects as well as pointers to each
2422 uint8_t* space
= new uint8_t[totalSectionsSize
+count
*sizeof(Section
<A
>*)];
2423 _file
->_sectionsArray
= (Section
<A
>**)space
;
2424 _file
->_sectionsArrayCount
= count
;
2425 Section
<A
>** objects
= _file
->_sectionsArray
;
2426 space
+= count
*sizeof(Section
<A
>*);
2427 for (uint32_t i
=0; i
< count
; ++i
) {
2428 switch ( machOSects
[i
].type
) {
2429 case sectionTypeIgnore
:
2431 case sectionTypeLiteral4
:
2432 *objects
++ = new (space
) Literal4Section
<A
>(*this, *_file
, machOSects
[i
].sect
);
2433 space
+= sizeof(Literal4Section
<A
>);
2435 case sectionTypeLiteral8
:
2436 *objects
++ = new (space
) Literal8Section
<A
>(*this, *_file
, machOSects
[i
].sect
);
2437 space
+= sizeof(Literal8Section
<A
>);
2439 case sectionTypeLiteral16
:
2440 *objects
++ = new (space
) Literal16Section
<A
>(*this, *_file
, machOSects
[i
].sect
);
2441 space
+= sizeof(Literal16Section
<A
>);
2443 case sectionTypeNonLazy
:
2444 *objects
++ = new (space
) NonLazyPointerSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2445 space
+= sizeof(NonLazyPointerSection
<A
>);
2447 case sectionTypeCFI
:
2448 _EHFrameSection
= new (space
) CFISection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2449 *objects
++ = _EHFrameSection
;
2450 space
+= sizeof(CFISection
<A
>);
2452 case sectionTypeCString
:
2453 *objects
++ = new (space
) CStringSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2454 space
+= sizeof(CStringSection
<A
>);
2456 case sectionTypeCStringPointer
:
2457 *objects
++ = new (space
) PointerToCStringSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2458 space
+= sizeof(PointerToCStringSection
<A
>);
2460 case sectionTypeObjC1ClassRefs
:
2461 *objects
++ = new (space
) Objc1ClassReferences
<A
>(*this, *_file
, machOSects
[i
].sect
);
2462 space
+= sizeof(Objc1ClassReferences
<A
>);
2464 case sectionTypeUTF16Strings
:
2465 *objects
++ = new (space
) UTF16StringSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2466 space
+= sizeof(UTF16StringSection
<A
>);
2468 case sectionTypeCFString
:
2469 *objects
++ = new (space
) CFStringSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2470 space
+= sizeof(CFStringSection
<A
>);
2472 case sectionTypeObjC2ClassRefs
:
2473 *objects
++ = new (space
) ObjC2ClassRefsSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2474 space
+= sizeof(ObjC2ClassRefsSection
<A
>);
2476 case typeObjC2CategoryList
:
2477 *objects
++ = new (space
) ObjC2CategoryListSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2478 space
+= sizeof(ObjC2CategoryListSection
<A
>);
2480 case sectionTypeObjC1Classes
:
2481 *objects
++ = new (space
) ObjC1ClassSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2482 space
+= sizeof(ObjC1ClassSection
<A
>);
2484 case sectionTypeSymboled
:
2485 *objects
++ = new (space
) SymboledSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2486 space
+= sizeof(SymboledSection
<A
>);
2488 case sectionTypeTLVDefs
:
2489 *objects
++ = new (space
) TLVDefsSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2490 space
+= sizeof(TLVDefsSection
<A
>);
2492 case sectionTypeCompactUnwind
:
2493 _compactUnwindSection
= new (space
) CUSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2494 *objects
++ = _compactUnwindSection
;
2495 space
+= sizeof(CUSection
<A
>);
2497 case sectionTypeTentativeDefinitions
:
2498 *objects
++ = new (space
) TentativeDefinitionSection
<A
>(*this, *_file
);
2499 space
+= sizeof(TentativeDefinitionSection
<A
>);
2501 case sectionTypeAbsoluteSymbols
:
2502 _absoluteSection
= new (space
) AbsoluteSymbolSection
<A
>(*this, *_file
);
2503 *objects
++ = _absoluteSection
;
2504 space
+= sizeof(AbsoluteSymbolSection
<A
>);
2507 throw "internal error uknown SectionType";
2513 template <typename A
>
2514 Section
<A
>* Parser
<A
>::sectionForAddress(typename
A::P::uint_t addr
)
2516 for (uint32_t i
=0; i
< _file
->_sectionsArrayCount
; ++i
) {
2517 const macho_section
<typename
A::P
>* sect
= _file
->_sectionsArray
[i
]->machoSection();
2518 // TentativeDefinitionSection and AbsoluteSymbolSection have no mach-o section
2519 if ( sect
!= NULL
) {
2520 if ( (sect
->addr() <= addr
) && (addr
< (sect
->addr()+sect
->size())) ) {
2521 return _file
->_sectionsArray
[i
];
2525 // not strictly in any section
2526 // may be in a zero length section
2527 for (uint32_t i
=0; i
< _file
->_sectionsArrayCount
; ++i
) {
2528 const macho_section
<typename
A::P
>* sect
= _file
->_sectionsArray
[i
]->machoSection();
2529 // TentativeDefinitionSection and AbsoluteSymbolSection have no mach-o section
2530 if ( sect
!= NULL
) {
2531 if ( (sect
->addr() == addr
) && (sect
->size() == 0) ) {
2532 return _file
->_sectionsArray
[i
];
2537 throwf("sectionForAddress(0x%llX) address not in any section", (uint64_t)addr
);
2540 template <typename A
>
2541 Section
<A
>* Parser
<A
>::sectionForNum(unsigned int num
)
2543 for (uint32_t i
=0; i
< _file
->_sectionsArrayCount
; ++i
) {
2544 const macho_section
<typename
A::P
>* sect
= _file
->_sectionsArray
[i
]->machoSection();
2545 // TentativeDefinitionSection and AbsoluteSymbolSection have no mach-o section
2546 if ( sect
!= NULL
) {
2547 if ( num
== (unsigned int)((sect
- _sectionsStart
)+1) )
2548 return _file
->_sectionsArray
[i
];
2551 throwf("sectionForNum(%u) section number not for any section", num
);
2554 template <typename A
>
2555 Atom
<A
>* Parser
<A
>::findAtomByAddress(pint_t addr
)
2557 Section
<A
>* section
= this->sectionForAddress(addr
);
2558 return section
->findAtomByAddress(addr
);
2561 template <typename A
>
2562 Atom
<A
>* Parser
<A
>::findAtomByAddressOrNullIfStub(pint_t addr
)
2564 if ( hasStubsSection() && (_stubsMachOSection
->addr() <= addr
) && (addr
< (_stubsMachOSection
->addr()+_stubsMachOSection
->size())) )
2566 return findAtomByAddress(addr
);
2569 template <typename A
>
2570 Atom
<A
>* Parser
<A
>::findAtomByAddressOrLocalTargetOfStub(pint_t addr
, uint32_t* offsetInAtom
)
2572 if ( hasStubsSection() && (_stubsMachOSection
->addr() <= addr
) && (addr
< (_stubsMachOSection
->addr()+_stubsMachOSection
->size())) ) {
2573 // target is a stub, remove indirection
2574 uint32_t symbolIndex
= this->symbolIndexFromIndirectSectionAddress(addr
, _stubsMachOSection
);
2575 assert(symbolIndex
!= INDIRECT_SYMBOL_LOCAL
);
2576 const macho_nlist
<P
>& sym
= this->symbolFromIndex(symbolIndex
);
2577 // can't be to external weak symbol
2578 assert( (this->combineFromSymbol(sym
) != ld::Atom::combineByName
) || (this->scopeFromSymbol(sym
) != ld::Atom::scopeGlobal
) );
2580 return this->findAtomByName(this->nameFromSymbol(sym
));
2582 Atom
<A
>* target
= this->findAtomByAddress(addr
);
2583 *offsetInAtom
= addr
- target
->_objAddress
;
2587 template <typename A
>
2588 Atom
<A
>* Parser
<A
>::findAtomByName(const char* name
)
2590 uint8_t* p
= _file
->_atomsArray
;
2591 for(int i
=_file
->_atomsArrayCount
; i
> 0; --i
) {
2592 Atom
<A
>* atom
= (Atom
<A
>*)p
;
2593 if ( strcmp(name
, atom
->name()) == 0 )
2595 p
+= sizeof(Atom
<A
>);
2600 template <typename A
>
2601 void Parser
<A
>::findTargetFromAddress(pint_t addr
, TargetDesc
& target
)
2603 if ( hasStubsSection() && (_stubsMachOSection
->addr() <= addr
) && (addr
< (_stubsMachOSection
->addr()+_stubsMachOSection
->size())) ) {
2604 // target is a stub, remove indirection
2605 uint32_t symbolIndex
= this->symbolIndexFromIndirectSectionAddress(addr
, _stubsMachOSection
);
2606 assert(symbolIndex
!= INDIRECT_SYMBOL_LOCAL
);
2607 const macho_nlist
<P
>& sym
= this->symbolFromIndex(symbolIndex
);
2609 target
.name
= this->nameFromSymbol(sym
);
2610 target
.weakImport
= this->weakImportFromSymbol(sym
);
2614 Section
<A
>* section
= this->sectionForAddress(addr
);
2615 target
.atom
= section
->findAtomByAddress(addr
);
2616 target
.addend
= addr
- target
.atom
->_objAddress
;
2617 target
.weakImport
= false;
2621 template <typename A
>
2622 void Parser
<A
>::findTargetFromAddress(pint_t baseAddr
, pint_t addr
, TargetDesc
& target
)
2624 findTargetFromAddress(baseAddr
, target
);
2625 target
.addend
= addr
- target
.atom
->_objAddress
;
2628 template <typename A
>
2629 void Parser
<A
>::findTargetFromAddressAndSectionNum(pint_t addr
, unsigned int sectNum
, TargetDesc
& target
)
2631 if ( sectNum
== R_ABS
) {
2632 // target is absolute symbol that corresponds to addr
2633 if ( _absoluteSection
!= NULL
) {
2634 target
.atom
= _absoluteSection
->findAbsAtomForValue(addr
);
2635 if ( target
.atom
!= NULL
) {
2637 target
.weakImport
= false;
2642 throwf("R_ABS reloc but no absolute symbol at target address");
2645 if ( hasStubsSection() && (stubsSectionNum() == sectNum
) ) {
2646 // target is a stub, remove indirection
2647 uint32_t symbolIndex
= this->symbolIndexFromIndirectSectionAddress(addr
, _stubsMachOSection
);
2648 assert(symbolIndex
!= INDIRECT_SYMBOL_LOCAL
);
2649 const macho_nlist
<P
>& sym
= this->symbolFromIndex(symbolIndex
);
2650 // use direct reference when stub is to a static function
2651 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && (((sym
.n_type() & N_EXT
) == 0) || (this->nameFromSymbol(sym
)[0] == 'L')) ) {
2652 this->findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
2656 target
.name
= this->nameFromSymbol(sym
);
2657 target
.weakImport
= this->weakImportFromSymbol(sym
);
2662 Section
<A
>* section
= this->sectionForNum(sectNum
);
2663 target
.atom
= section
->findAtomByAddress(addr
);
2664 if ( target
.atom
== NULL
) {
2665 typedef typename
A::P::sint_t sint_t
;
2666 sint_t a
= (sint_t
)addr
;
2667 sint_t sectStart
= (sint_t
)(section
->machoSection()->addr());
2668 sint_t sectEnd
= sectStart
+ section
->machoSection()->size();
2669 if ( a
< sectStart
) {
2670 // target address is before start of section, so must be negative addend
2671 target
.atom
= section
->findAtomByAddress(sectStart
);
2672 target
.addend
= a
- sectStart
;
2673 target
.weakImport
= false;
2677 else if ( a
>= sectEnd
) {
2678 target
.atom
= section
->findAtomByAddress(sectEnd
-1);
2679 target
.addend
= a
- sectEnd
;
2680 target
.weakImport
= false;
2685 assert(target
.atom
!= NULL
);
2686 target
.addend
= addr
- target
.atom
->_objAddress
;
2687 target
.weakImport
= false;
2691 template <typename A
>
2692 void Parser
<A
>::addDtraceExtraInfos(const SourceLocation
& src
, const char* providerName
)
2694 // for every ___dtrace_stability$* and ___dtrace_typedefs$* undefine with
2695 // a matching provider name, add a by-name kDtraceTypeReference at probe site
2696 const char* dollar
= strchr(providerName
, '$');
2697 if ( dollar
!= NULL
) {
2698 int providerNameLen
= dollar
-providerName
+1;
2699 for ( std::vector
<const char*>::iterator it
= _dtraceProviderInfo
.begin(); it
!= _dtraceProviderInfo
.end(); ++it
) {
2700 const char* typeDollar
= strchr(*it
, '$');
2701 if ( typeDollar
!= NULL
) {
2702 if ( strncmp(typeDollar
+1, providerName
, providerNameLen
) == 0 ) {
2703 addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindDtraceExtra
,false, *it
);
2710 template <typename A
>
2711 const char* Parser
<A
>::scanSymbolTableForAddress(uint64_t addr
)
2713 uint64_t closestSymAddr
= 0;
2714 const char* closestSymName
= NULL
;
2715 for (uint32_t i
=0; i
< this->_symbolCount
; ++i
) {
2716 const macho_nlist
<P
>& sym
= symbolFromIndex(i
);
2718 if ( (sym
.n_type() & N_STAB
) != 0 )
2721 // only look at definitions
2722 if ( (sym
.n_type() & N_TYPE
) != N_SECT
)
2725 // return with exact match
2726 if ( sym
.n_value() == addr
) {
2727 const char* name
= nameFromSymbol(sym
);
2728 if ( strncmp(name
, "ltmp", 4) != 0 )
2730 // treat 'ltmp*' labels as close match
2731 closestSymAddr
= sym
.n_value();
2732 closestSymName
= name
;
2735 // record closest seen so far
2736 if ( (sym
.n_value() < addr
) && ((sym
.n_value() > closestSymAddr
) || (closestSymName
== NULL
)) )
2737 closestSymName
= nameFromSymbol(sym
);
2740 return (closestSymName
!= NULL
) ? closestSymName
: "unknown";
2744 template <typename A
>
2745 void Parser
<A
>::addFixups(const SourceLocation
& src
, ld::Fixup::Kind setKind
, const TargetDesc
& target
)
2747 // some fixup pairs can be combined
2748 ld::Fixup::Cluster cl
= ld::Fixup::k1of3
;
2749 ld::Fixup::Kind firstKind
= ld::Fixup::kindSetTargetAddress
;
2750 bool combined
= false;
2751 if ( target
.addend
== 0 ) {
2752 cl
= ld::Fixup::k1of1
;
2754 switch ( setKind
) {
2755 case ld::Fixup::kindStoreLittleEndian32
:
2756 firstKind
= ld::Fixup::kindStoreTargetAddressLittleEndian32
;
2758 case ld::Fixup::kindStoreLittleEndian64
:
2759 firstKind
= ld::Fixup::kindStoreTargetAddressLittleEndian64
;
2761 case ld::Fixup::kindStoreBigEndian32
:
2762 firstKind
= ld::Fixup::kindStoreTargetAddressBigEndian32
;
2764 case ld::Fixup::kindStoreBigEndian64
:
2765 firstKind
= ld::Fixup::kindStoreTargetAddressBigEndian64
;
2767 case ld::Fixup::kindStoreX86BranchPCRel32
:
2768 firstKind
= ld::Fixup::kindStoreTargetAddressX86BranchPCRel32
;
2770 case ld::Fixup::kindStoreX86PCRel32
:
2771 firstKind
= ld::Fixup::kindStoreTargetAddressX86PCRel32
;
2773 case ld::Fixup::kindStoreX86PCRel32GOTLoad
:
2774 firstKind
= ld::Fixup::kindStoreTargetAddressX86PCRel32GOTLoad
;
2776 case ld::Fixup::kindStoreX86PCRel32TLVLoad
:
2777 firstKind
= ld::Fixup::kindStoreTargetAddressX86PCRel32TLVLoad
;
2779 case ld::Fixup::kindStoreX86Abs32TLVLoad
:
2780 firstKind
= ld::Fixup::kindStoreTargetAddressX86Abs32TLVLoad
;
2782 case ld::Fixup::kindStoreARMBranch24
:
2783 firstKind
= ld::Fixup::kindStoreTargetAddressARMBranch24
;
2785 case ld::Fixup::kindStoreThumbBranch22
:
2786 firstKind
= ld::Fixup::kindStoreTargetAddressThumbBranch22
;
2788 #if SUPPORT_ARCH_arm64
2789 case ld::Fixup::kindStoreARM64Branch26
:
2790 firstKind
= ld::Fixup::kindStoreTargetAddressARM64Branch26
;
2792 case ld::Fixup::kindStoreARM64Page21
:
2793 firstKind
= ld::Fixup::kindStoreTargetAddressARM64Page21
;
2795 case ld::Fixup::kindStoreARM64PageOff12
:
2796 firstKind
= ld::Fixup::kindStoreTargetAddressARM64PageOff12
;
2798 case ld::Fixup::kindStoreARM64GOTLoadPage21
:
2799 firstKind
= ld::Fixup::kindStoreTargetAddressARM64GOTLoadPage21
;
2801 case ld::Fixup::kindStoreARM64GOTLoadPageOff12
:
2802 firstKind
= ld::Fixup::kindStoreTargetAddressARM64GOTLoadPageOff12
;
2804 case ld::Fixup::kindStoreARM64TLVPLoadPage21
:
2805 firstKind
= ld::Fixup::kindStoreTargetAddressARM64TLVPLoadPage21
;
2807 case ld::Fixup::kindStoreARM64TLVPLoadPageOff12
:
2808 firstKind
= ld::Fixup::kindStoreTargetAddressARM64TLVPLoadPageOff12
;
2813 cl
= ld::Fixup::k1of2
;
2818 if ( target
.atom
!= NULL
) {
2819 if ( target
.atom
->scope() == ld::Atom::scopeTranslationUnit
) {
2820 addFixup(src
, cl
, firstKind
, target
.atom
);
2822 else if ( (target
.atom
->combine() == ld::Atom::combineByNameAndContent
) || (target
.atom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
2823 addFixup(src
, cl
, firstKind
, ld::Fixup::bindingByContentBound
, target
.atom
);
2825 else if ( (src
.atom
->section().type() == ld::Section::typeCFString
) && (src
.offsetInAtom
!= 0) ) {
2826 // backing string in CFStrings should always be direct
2827 addFixup(src
, cl
, firstKind
, target
.atom
);
2829 else if ( (src
.atom
== target
.atom
) && (target
.atom
->combine() == ld::Atom::combineByName
) ) {
2830 // reference to self should always be direct
2831 addFixup(src
, cl
, firstKind
, target
.atom
);
2834 // change direct fixup to by-name fixup
2835 addFixup(src
, cl
, firstKind
, false, target
.atom
->name());
2839 addFixup(src
, cl
, firstKind
, target
.weakImport
, target
.name
);
2841 if ( target
.addend
== 0 ) {
2843 addFixup(src
, ld::Fixup::k2of2
, setKind
);
2846 addFixup(src
, ld::Fixup::k2of3
, ld::Fixup::kindAddAddend
, target
.addend
);
2847 addFixup(src
, ld::Fixup::k3of3
, setKind
);
2851 template <typename A
>
2852 void Parser
<A
>::addFixups(const SourceLocation
& src
, ld::Fixup::Kind kind
, const TargetDesc
& target
, const TargetDesc
& picBase
)
2854 ld::Fixup::Cluster cl
= (target
.addend
== 0) ? ld::Fixup::k1of4
: ld::Fixup::k1of5
;
2855 if ( target
.atom
!= NULL
) {
2856 if ( target
.atom
->scope() == ld::Atom::scopeTranslationUnit
) {
2857 addFixup(src
, cl
, ld::Fixup::kindSetTargetAddress
, target
.atom
);
2859 else if ( (target
.atom
->combine() == ld::Atom::combineByNameAndContent
) || (target
.atom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
2860 addFixup(src
, cl
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, target
.atom
);
2863 addFixup(src
, cl
, ld::Fixup::kindSetTargetAddress
, false, target
.atom
->name());
2867 addFixup(src
, cl
, ld::Fixup::kindSetTargetAddress
, target
.weakImport
, target
.name
);
2869 if ( target
.addend
== 0 ) {
2870 assert(picBase
.atom
!= NULL
);
2871 addFixup(src
, ld::Fixup::k2of4
, ld::Fixup::kindSubtractTargetAddress
, picBase
.atom
);
2872 addFixup(src
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractAddend
, picBase
.addend
);
2873 addFixup(src
, ld::Fixup::k4of4
, kind
);
2876 addFixup(src
, ld::Fixup::k2of5
, ld::Fixup::kindAddAddend
, target
.addend
);
2877 addFixup(src
, ld::Fixup::k3of5
, ld::Fixup::kindSubtractTargetAddress
, picBase
.atom
);
2878 addFixup(src
, ld::Fixup::k4of5
, ld::Fixup::kindSubtractAddend
, picBase
.addend
);
2879 addFixup(src
, ld::Fixup::k5of5
, kind
);
2885 template <typename A
>
2886 uint32_t TentativeDefinitionSection
<A
>::computeAtomCount(class Parser
<A
>& parser
,
2887 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
2888 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
2890 return parser
.tentativeDefinitionCount();
2893 template <typename A
>
2894 uint32_t TentativeDefinitionSection
<A
>::appendAtoms(class Parser
<A
>& parser
, uint8_t* p
,
2895 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
2896 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
2898 this->_beginAtoms
= (Atom
<A
>*)p
;
2900 for (uint32_t i
=parser
.undefinedStartIndex(); i
< parser
.undefinedEndIndex(); ++i
) {
2901 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(i
);
2902 if ( ((sym
.n_type() & N_TYPE
) == N_UNDF
) && (sym
.n_value() != 0) ) {
2903 uint64_t size
= sym
.n_value();
2904 uint8_t alignP2
= GET_COMM_ALIGN(sym
.n_desc());
2905 if ( alignP2
== 0 ) {
2906 // common symbols align to their size
2907 // that is, a 4-byte common aligns to 4-bytes
2908 // if this size is not a power of two,
2909 // then round up to the next power of two
2910 alignP2
= 63 - (uint8_t)__builtin_clzll(size
);
2911 if ( size
!= (1ULL << alignP2
) )
2914 // limit alignment of extremely large commons to 2^15 bytes (8-page)
2917 Atom
<A
>* allocatedSpace
= (Atom
<A
>*)p
;
2918 new (allocatedSpace
) Atom
<A
>(*this, parser
.nameFromSymbol(sym
), (pint_t
)ULLONG_MAX
, size
,
2919 ld::Atom::definitionTentative
, ld::Atom::combineByName
,
2920 parser
.scopeFromSymbol(sym
), ld::Atom::typeZeroFill
, ld::Atom::symbolTableIn
,
2921 parser
.dontDeadStripFromSymbol(sym
), false, false, ld::Atom::Alignment(alignP2
) );
2922 p
+= sizeof(Atom
<A
>);
2926 this->_endAtoms
= (Atom
<A
>*)p
;
2931 template <typename A
>
2932 uint32_t AbsoluteSymbolSection
<A
>::computeAtomCount(class Parser
<A
>& parser
,
2933 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
2934 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
2936 return parser
.absoluteSymbolCount();
2939 template <typename A
>
2940 uint32_t AbsoluteSymbolSection
<A
>::appendAtoms(class Parser
<A
>& parser
, uint8_t* p
,
2941 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
2942 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
2944 this->_beginAtoms
= (Atom
<A
>*)p
;
2946 for (uint32_t i
=0; i
< parser
.symbolCount(); ++i
) {
2947 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(i
);
2948 if ( (sym
.n_type() & N_TYPE
) != N_ABS
)
2950 const char* absName
= parser
.nameFromSymbol(sym
);
2951 // ignore .objc_class_name_* symbols
2952 if ( strncmp(absName
, ".objc_class_name_", 17) == 0 )
2954 // ignore .objc_class_name_* symbols
2955 if ( strncmp(absName
, ".objc_category_name_", 20) == 0 )
2957 // ignore empty *.eh symbols
2958 if ( strcmp(&absName
[strlen(absName
)-3], ".eh") == 0 )
2961 Atom
<A
>* allocatedSpace
= (Atom
<A
>*)p
;
2962 new (allocatedSpace
) Atom
<A
>(*this, parser
, sym
, 0);
2963 p
+= sizeof(Atom
<A
>);
2966 this->_endAtoms
= (Atom
<A
>*)p
;
2970 template <typename A
>
2971 Atom
<A
>* AbsoluteSymbolSection
<A
>::findAbsAtomForValue(typename
A::P::uint_t value
)
2973 Atom
<A
>* end
= this->_endAtoms
;
2974 for(Atom
<A
>* p
= this->_beginAtoms
; p
< end
; ++p
) {
2975 if ( p
->_objAddress
== value
)
2982 template <typename A
>
2983 uint32_t Parser
<A
>::indirectSymbol(uint32_t indirectIndex
)
2985 if ( indirectIndex
>= _indirectTableCount
)
2986 throw "indirect symbol index out of range";
2987 return E::get32(_indirectTable
[indirectIndex
]);
2990 template <typename A
>
2991 const macho_nlist
<typename
A::P
>& Parser
<A
>::symbolFromIndex(uint32_t index
)
2993 if ( index
> _symbolCount
)
2994 throw "symbol index out of range";
2995 return _symbols
[index
];
2998 template <typename A
>
2999 const macho_section
<typename
A::P
>* Parser
<A
>::machOSectionFromSectionIndex(uint32_t index
)
3001 if ( index
>= _machOSectionsCount
)
3002 throw "section index out of range";
3003 return &_sectionsStart
[index
];
3006 template <typename A
>
3007 uint32_t Parser
<A
>::symbolIndexFromIndirectSectionAddress(pint_t addr
, const macho_section
<P
>* sect
)
3009 uint32_t elementSize
= 0;
3010 switch ( sect
->flags() & SECTION_TYPE
) {
3011 case S_SYMBOL_STUBS
:
3012 elementSize
= sect
->reserved2();
3014 case S_LAZY_SYMBOL_POINTERS
:
3015 case S_NON_LAZY_SYMBOL_POINTERS
:
3016 elementSize
= sizeof(pint_t
);
3019 throw "section does not use inirect symbol table";
3021 uint32_t indexInSection
= (addr
- sect
->addr()) / elementSize
;
3022 uint32_t indexIntoIndirectTable
= sect
->reserved1() + indexInSection
;
3023 return this->indirectSymbol(indexIntoIndirectTable
);
3028 template <typename A
>
3029 const char* Parser
<A
>::nameFromSymbol(const macho_nlist
<P
>& sym
)
3031 return &_strings
[sym
.n_strx()];
3034 template <typename A
>
3035 ld::Atom::Scope Parser
<A
>::scopeFromSymbol(const macho_nlist
<P
>& sym
)
3037 if ( (sym
.n_type() & N_EXT
) == 0 )
3038 return ld::Atom::scopeTranslationUnit
;
3039 else if ( (sym
.n_type() & N_PEXT
) != 0 )
3040 return ld::Atom::scopeLinkageUnit
;
3041 else if ( this->nameFromSymbol(sym
)[0] == 'l' ) // since all 'l' symbols will be remove, don't make them global
3042 return ld::Atom::scopeLinkageUnit
;
3044 return ld::Atom::scopeGlobal
;
3047 template <typename A
>
3048 ld::Atom::Definition Parser
<A
>::definitionFromSymbol(const macho_nlist
<P
>& sym
)
3050 switch ( sym
.n_type() & N_TYPE
) {
3052 return ld::Atom::definitionAbsolute
;
3054 return ld::Atom::definitionRegular
;
3056 if ( sym
.n_value() != 0 )
3057 return ld::Atom::definitionTentative
;
3059 throw "definitionFromSymbol() bad symbol";
3062 template <typename A
>
3063 ld::Atom::Combine Parser
<A
>::combineFromSymbol(const macho_nlist
<P
>& sym
)
3065 if ( sym
.n_desc() & N_WEAK_DEF
)
3066 return ld::Atom::combineByName
;
3068 return ld::Atom::combineNever
;
3072 template <typename A
>
3073 ld::Atom::SymbolTableInclusion Parser
<A
>::inclusionFromSymbol(const macho_nlist
<P
>& sym
)
3075 const char* symbolName
= nameFromSymbol(sym
);
3076 // labels beginning with 'l' (lowercase ell) are automatically removed in final linked images <rdar://problem/4571042>
3077 // labels beginning with 'L' should have been stripped by the assembler, so are stripped now
3078 if ( sym
.n_desc() & REFERENCED_DYNAMICALLY
)
3079 return ld::Atom::symbolTableInAndNeverStrip
;
3080 else if ( symbolName
[0] == 'l' )
3081 return ld::Atom::symbolTableNotInFinalLinkedImages
;
3082 else if ( symbolName
[0] == 'L' )
3083 return ld::Atom::symbolTableNotIn
;
3085 return ld::Atom::symbolTableIn
;
3088 template <typename A
>
3089 bool Parser
<A
>::dontDeadStripFromSymbol(const macho_nlist
<P
>& sym
)
3091 return ( (sym
.n_desc() & (N_NO_DEAD_STRIP
|REFERENCED_DYNAMICALLY
)) != 0 );
3094 template <typename A
>
3095 bool Parser
<A
>::isThumbFromSymbol(const macho_nlist
<P
>& sym
)
3097 return ( sym
.n_desc() & N_ARM_THUMB_DEF
);
3100 template <typename A
>
3101 bool Parser
<A
>::weakImportFromSymbol(const macho_nlist
<P
>& sym
)
3103 return ( ((sym
.n_type() & N_TYPE
) == N_UNDF
) && ((sym
.n_desc() & N_WEAK_REF
) != 0) );
3106 template <typename A
>
3107 bool Parser
<A
>::resolverFromSymbol(const macho_nlist
<P
>& sym
)
3109 return ( sym
.n_desc() & N_SYMBOL_RESOLVER
);
3112 template <typename A
>
3113 bool Parser
<A
>::altEntryFromSymbol(const macho_nlist
<P
>& sym
)
3115 return ( sym
.n_desc() & N_ALT_ENTRY
);
3119 /* Skip over a LEB128 value (signed or unsigned). */
3121 skip_leb128 (const uint8_t ** offset
, const uint8_t * end
)
3123 while (*offset
!= end
&& **offset
>= 0x80)
3129 /* Read a ULEB128 into a 64-bit word. Return (uint64_t)-1 on overflow
3130 or error. On overflow, skip past the rest of the uleb128. */
3132 read_uleb128 (const uint8_t ** offset
, const uint8_t * end
)
3134 uint64_t result
= 0;
3141 return (uint64_t) -1;
3143 b
= **offset
& 0x7f;
3145 if (bit
>= 64 || b
<< bit
>> bit
!= b
)
3146 result
= (uint64_t) -1;
3148 result
|= b
<< bit
, bit
+= 7;
3149 } while (*(*offset
)++ >= 0x80);
3154 /* Skip over a DWARF attribute of form FORM. */
3155 template <typename A
>
3156 bool Parser
<A
>::skip_form(const uint8_t ** offset
, const uint8_t * end
, uint64_t form
,
3157 uint8_t addr_size
, bool dwarf64
)
3167 case DW_FORM_block2
:
3168 if (end
- *offset
< 2)
3170 sz
= 2 + A::P::E::get16(*(uint16_t*)offset
);
3173 case DW_FORM_block4
:
3174 if (end
- *offset
< 4)
3176 sz
= 2 + A::P::E::get32(*(uint32_t*)offset
);
3194 case DW_FORM_string
:
3195 while (*offset
!= end
&& **offset
)
3204 sz
= read_uleb128 (offset
, end
);
3207 case DW_FORM_block1
:
3215 case DW_FORM_ref_udata
:
3216 skip_leb128 (offset
, end
);
3220 case DW_FORM_ref_addr
:
3224 case DW_FORM_sec_offset
:
3225 sz
= sizeof(typename
A::P::uint_t
);
3228 case DW_FORM_exprloc
:
3229 sz
= read_uleb128 (offset
, end
);
3232 case DW_FORM_flag_present
:
3236 case DW_FORM_ref_sig8
:
3243 if (end
- *offset
< sz
)
3250 template <typename A
>
3251 const char* Parser
<A
>::getDwarfString(uint64_t form
, const uint8_t*& di
)
3254 const char* dwarfStrings
;
3255 const char* result
= NULL
;
3257 case DW_FORM_string
:
3258 result
= (const char*)di
;
3259 di
+= strlen(result
) + 1;
3262 offset
= E::get32(*((uint32_t*)di
));
3263 dwarfStrings
= (char*)_file
->fileContent() + _file
->_dwarfDebugStringSect
->offset();
3264 if ( offset
< _file
->_dwarfDebugStringSect
->size() )
3265 result
= &dwarfStrings
[offset
];
3267 warning("dwarf DW_FORM_strp (offset=0x%08X) is too big in %s", offset
, this->_path
);
3271 warning("unknown dwarf string encoding (form=%lld) in %s", form
, this->_path
);
3277 template <typename A
>
3278 uint64_t Parser
<A
>::getDwarfOffset(uint64_t form
, const uint8_t*& di
, bool dwarf64
)
3280 if ( form
== DW_FORM_sec_offset
)
3281 form
= (dwarf64
? DW_FORM_data8
: DW_FORM_data4
);
3282 uint64_t result
= -1;
3285 result
= A::P::E::get32(*(uint32_t*)di
);
3289 result
= A::P::E::get64(*(uint64_t*)di
);
3293 warning("unknown dwarf DW_FORM_ for DW_AT_stmt_list in %s", this->_path
);
3299 template <typename A
>
3300 struct AtomAndLineInfo
{
3302 ld::Atom::LineInfo info
;
3306 // <rdar://problem/5591394> Add support to ld64 for N_FUN stabs when used for symbolic constants
3307 // Returns whether a stabStr belonging to an N_FUN stab represents a
3308 // symbolic constant rather than a function
3309 template <typename A
>
3310 bool Parser
<A
>::isConstFunStabs(const char *stabStr
)
3313 // N_FUN can be used for both constants and for functions. In case it's a constant,
3314 // the format of the stabs string is "symname:c=<value>;"
3315 // ':' cannot appear in the symbol name, except if it's an Objective-C method
3316 // (in which case the symbol name starts with + or -, and then it's definitely
3318 return (stabStr
!= NULL
) && (stabStr
[0] != '+') && (stabStr
[0] != '-')
3319 && ((colon
= strchr(stabStr
, ':')) != NULL
)
3320 && (colon
[1] == 'c') && (colon
[2] == '=');
3324 template <typename A
>
3325 void Parser
<A
>::parseDebugInfo()
3327 // check for dwarf __debug_info section
3328 if ( _file
->_dwarfDebugInfoSect
== NULL
) {
3329 // if no DWARF debug info, look for stabs
3333 if ( _file
->_dwarfDebugInfoSect
->size() == 0 )
3339 if ( !read_comp_unit(&tuName
, &tuDir
, &stmtList
) ) {
3340 // if can't parse dwarf, warn and give up
3341 _file
->_dwarfTranslationUnitPath
= NULL
;
3342 warning("can't parse dwarf compilation unit info in %s", _path
);
3343 _file
->_debugInfoKind
= ld::relocatable::File::kDebugInfoNone
;
3346 if ( (tuName
!= NULL
) && (tuName
[0] == '/') ) {
3347 _file
->_dwarfTranslationUnitPath
= tuName
;
3349 else if ( (tuDir
!= NULL
) && (tuName
!= NULL
) ) {
3350 asprintf((char**)&(_file
->_dwarfTranslationUnitPath
), "%s/%s", tuDir
, tuName
);
3352 else if ( tuDir
== NULL
) {
3353 _file
->_dwarfTranslationUnitPath
= tuName
;
3356 _file
->_dwarfTranslationUnitPath
= NULL
;
3359 // add line number info to atoms from dwarf
3360 std::vector
<AtomAndLineInfo
<A
> > entries
;
3361 entries
.reserve(64);
3362 if ( _file
->_debugInfoKind
== ld::relocatable::File::kDebugInfoDwarf
) {
3363 // file with just data will have no __debug_line info
3364 if ( (_file
->_dwarfDebugLineSect
!= NULL
) && (_file
->_dwarfDebugLineSect
->size() != 0) ) {
3365 // validate stmt_list
3366 if ( (stmtList
!= (uint64_t)-1) && (stmtList
< _file
->_dwarfDebugLineSect
->size()) ) {
3367 const uint8_t* debug_line
= (uint8_t*)_file
->fileContent() + _file
->_dwarfDebugLineSect
->offset();
3368 struct line_reader_data
* lines
= line_open(&debug_line
[stmtList
],
3369 _file
->_dwarfDebugLineSect
->size() - stmtList
, E::little_endian
);
3370 struct line_info result
;
3371 Atom
<A
>* curAtom
= NULL
;
3372 uint32_t curAtomOffset
= 0;
3373 uint32_t curAtomAddress
= 0;
3374 uint32_t curAtomSize
= 0;
3375 std::map
<uint32_t,const char*> dwarfIndexToFile
;
3376 if ( lines
!= NULL
) {
3377 while ( line_next(lines
, &result
, line_stop_pc
) ) {
3378 //fprintf(stderr, "curAtom=%p, result.pc=0x%llX, result.line=%llu, result.end_of_sequence=%d,"
3379 // " curAtomAddress=0x%X, curAtomSize=0x%X\n",
3380 // curAtom, result.pc, result.line, result.end_of_sequence, curAtomAddress, curAtomSize);
3381 // work around weird debug line table compiler generates if no functions in __text section
3382 if ( (curAtom
== NULL
) && (result
.pc
== 0) && result
.end_of_sequence
&& (result
.file
== 1))
3384 // for performance, see if in next pc is in current atom
3385 if ( (curAtom
!= NULL
) && (curAtomAddress
<= result
.pc
) && (result
.pc
< (curAtomAddress
+curAtomSize
)) ) {
3386 curAtomOffset
= result
.pc
- curAtomAddress
;
3388 // or pc at end of current atom
3389 else if ( result
.end_of_sequence
&& (curAtom
!= NULL
) && (result
.pc
== (curAtomAddress
+curAtomSize
)) ) {
3390 curAtomOffset
= result
.pc
- curAtomAddress
;
3392 // or only one function that is a one line function
3393 else if ( result
.end_of_sequence
&& (curAtom
== NULL
) && (this->findAtomByAddress(0) != NULL
) && (result
.pc
== this->findAtomByAddress(0)->size()) ) {
3394 curAtom
= this->findAtomByAddress(0);
3395 curAtomOffset
= result
.pc
- curAtom
->objectAddress();
3396 curAtomAddress
= curAtom
->objectAddress();
3397 curAtomSize
= curAtom
->size();
3400 // do slow look up of atom by address
3402 curAtom
= this->findAtomByAddress(result
.pc
);
3405 // in case of bug in debug info, don't abort link, just limp on
3408 if ( curAtom
== NULL
)
3409 break; // file has line info but no functions
3410 if ( result
.end_of_sequence
&& (curAtomAddress
+curAtomSize
< result
.pc
) ) {
3411 // a one line function can be returned by line_next() as one entry with pc at end of blob
3412 // look for alt atom starting at end of previous atom
3413 uint32_t previousEnd
= curAtomAddress
+curAtomSize
;
3414 Atom
<A
>* alt
= this->findAtomByAddressOrNullIfStub(previousEnd
);
3416 continue; // ignore spurious debug info for stubs
3417 if ( result
.pc
<= alt
->objectAddress() + alt
->size() ) {
3419 curAtomOffset
= result
.pc
- alt
->objectAddress();
3420 curAtomAddress
= alt
->objectAddress();
3421 curAtomSize
= alt
->size();
3424 curAtomOffset
= result
.pc
- curAtom
->objectAddress();
3425 curAtomAddress
= curAtom
->objectAddress();
3426 curAtomSize
= curAtom
->size();
3430 curAtomOffset
= result
.pc
- curAtom
->objectAddress();
3431 curAtomAddress
= curAtom
->objectAddress();
3432 curAtomSize
= curAtom
->size();
3435 const char* filename
;
3436 std::map
<uint32_t,const char*>::iterator pos
= dwarfIndexToFile
.find(result
.file
);
3437 if ( pos
== dwarfIndexToFile
.end() ) {
3438 filename
= line_file(lines
, result
.file
);
3439 dwarfIndexToFile
[result
.file
] = filename
;
3442 filename
= pos
->second
;
3444 // only record for ~8000 line info records per function
3445 if ( curAtom
->roomForMoreLineInfoCount() ) {
3446 AtomAndLineInfo
<A
> entry
;
3447 entry
.atom
= curAtom
;
3448 entry
.info
.atomOffset
= curAtomOffset
;
3449 entry
.info
.fileName
= filename
;
3450 entry
.info
.lineNumber
= result
.line
;
3451 //fprintf(stderr, "addr=0x%08llX, line=%lld, file=%s, atom=%s, atom.size=0x%X, end=%d\n",
3452 // result.pc, result.line, filename, curAtom->name(), curAtomSize, result.end_of_sequence);
3453 entries
.push_back(entry
);
3454 curAtom
->incrementLineInfoCount();
3456 if ( result
.end_of_sequence
) {
3466 // assign line info start offset for each atom
3467 uint8_t* p
= _file
->_atomsArray
;
3468 uint32_t liOffset
= 0;
3469 for(int i
=_file
->_atomsArrayCount
; i
> 0; --i
) {
3470 Atom
<A
>* atom
= (Atom
<A
>*)p
;
3471 atom
->_lineInfoStartIndex
= liOffset
;
3472 liOffset
+= atom
->_lineInfoCount
;
3473 atom
->_lineInfoCount
= 0;
3474 p
+= sizeof(Atom
<A
>);
3476 assert(liOffset
== entries
.size());
3477 _file
->_lineInfos
.reserve(liOffset
);
3479 // copy each line info for each atom
3480 for (typename
std::vector
<AtomAndLineInfo
<A
> >::iterator it
= entries
.begin(); it
!= entries
.end(); ++it
) {
3481 uint32_t slot
= it
->atom
->_lineInfoStartIndex
+ it
->atom
->_lineInfoCount
;
3482 _file
->_lineInfos
[slot
] = it
->info
;
3483 it
->atom
->_lineInfoCount
++;
3486 // done with temp vector
3490 template <typename A
>
3491 void Parser
<A
>::parseStabs()
3493 // scan symbol table for stabs entries
3494 Atom
<A
>* currentAtom
= NULL
;
3495 pint_t currentAtomAddress
= 0;
3496 enum { start
, inBeginEnd
, inFun
} state
= start
;
3497 for (uint32_t symbolIndex
= 0; symbolIndex
< _symbolCount
; ++symbolIndex
) {
3498 const macho_nlist
<P
>& sym
= this->symbolFromIndex(symbolIndex
);
3499 bool useStab
= true;
3500 uint8_t type
= sym
.n_type();
3501 const char* symString
= (sym
.n_strx() != 0) ? this->nameFromSymbol(sym
) : NULL
;
3502 if ( (type
& N_STAB
) != 0 ) {
3503 _file
->_debugInfoKind
= (_hasUUID
? ld::relocatable::File::kDebugInfoStabsUUID
: ld::relocatable::File::kDebugInfoStabs
);
3504 ld::relocatable::File::Stab stab
;
3507 stab
.other
= sym
.n_sect();
3508 stab
.desc
= sym
.n_desc();
3509 stab
.value
= sym
.n_value();
3515 // beginning of function block
3517 // fall into case to lookup atom by addresss
3520 currentAtomAddress
= sym
.n_value();
3521 currentAtom
= this->findAtomByAddress(currentAtomAddress
);
3522 if ( currentAtom
!= NULL
) {
3523 stab
.atom
= currentAtom
;
3524 stab
.string
= symString
;
3527 fprintf(stderr
, "can't find atom for stabs BNSYM at %08llX in %s",
3528 (uint64_t)sym
.n_value(), _path
);
3538 // not associated with an atom, just copy
3539 stab
.string
= symString
;
3543 // n_value field is NOT atom address ;-(
3544 // need to find atom by name match
3545 const char* colon
= strchr(symString
, ':');
3546 if ( colon
!= NULL
) {
3547 // build underscore leading name
3548 int nameLen
= colon
- symString
;
3549 char symName
[nameLen
+2];
3550 strlcpy(&symName
[1], symString
, nameLen
+1);
3552 symName
[nameLen
+1] = '\0';
3553 currentAtom
= this->findAtomByName(symName
);
3554 if ( currentAtom
!= NULL
) {
3555 stab
.atom
= currentAtom
;
3556 stab
.string
= symString
;
3560 // might be a debug-note without trailing :G()
3561 currentAtom
= this->findAtomByName(symString
);
3562 if ( currentAtom
!= NULL
) {
3563 stab
.atom
= currentAtom
;
3564 stab
.string
= symString
;
3567 if ( stab
.atom
== NULL
) {
3568 // ld_classic added bogus GSYM stabs for old style dtrace probes
3569 if ( (strncmp(symString
, "__dtrace_probe$", 15) != 0) )
3570 warning("can't find atom for N_GSYM stabs %s in %s", symString
, _path
);
3576 if ( isConstFunStabs(symString
) ) {
3577 // constant not associated with a function
3578 stab
.string
= symString
;
3581 // old style stabs without BNSYM
3583 currentAtomAddress
= sym
.n_value();
3584 currentAtom
= this->findAtomByAddress(currentAtomAddress
);
3585 if ( currentAtom
!= NULL
) {
3586 stab
.atom
= currentAtom
;
3587 stab
.string
= symString
;
3590 warning("can't find atom for stabs FUN at %08llX in %s",
3591 (uint64_t)currentAtomAddress
, _path
);
3597 stab
.string
= symString
;
3603 stab
.string
= symString
;
3604 // -gfull built .o file
3607 warning("unknown stabs type 0x%X in %s", type
, _path
);
3611 stab
.atom
= currentAtom
;
3620 Atom
<A
>* nestedAtom
= this->findAtomByAddress(sym
.n_value());
3621 if ( nestedAtom
!= NULL
) {
3622 stab
.atom
= nestedAtom
;
3623 stab
.string
= symString
;
3626 warning("can't find atom for stabs 0x%X at %08llX in %s",
3627 type
, (uint64_t)sym
.n_value(), _path
);
3634 // adjust value to be offset in atom
3635 stab
.value
-= currentAtomAddress
;
3637 stab
.string
= symString
;
3644 if ( isConstFunStabs(symString
) ) {
3645 stab
.atom
= currentAtom
;
3646 stab
.string
= symString
;
3649 if ( sym
.n_sect() != 0 ) {
3650 // found another start stab, must be really old stabs...
3651 currentAtomAddress
= sym
.n_value();
3652 currentAtom
= this->findAtomByAddress(currentAtomAddress
);
3653 if ( currentAtom
!= NULL
) {
3654 stab
.atom
= currentAtom
;
3655 stab
.string
= symString
;
3658 warning("can't find atom for stabs FUN at %08llX in %s",
3659 (uint64_t)currentAtomAddress
, _path
);
3663 // found ending stab, switch back to start state
3664 stab
.string
= symString
;
3665 stab
.atom
= currentAtom
;
3674 // adjust value to be offset in atom
3675 stab
.value
-= currentAtomAddress
;
3676 stab
.atom
= currentAtom
;
3679 stab
.string
= symString
;
3683 stab
.atom
= currentAtom
;
3684 stab
.string
= symString
;
3689 // add to list of stabs for this .o file
3691 _file
->_stabs
.push_back(stab
);
3698 // Look at the compilation unit DIE and determine
3699 // its NAME, compilation directory (in COMP_DIR) and its
3700 // line number information offset (in STMT_LIST). NAME and COMP_DIR
3701 // may be NULL (especially COMP_DIR) if they are not in the .o file;
3702 // STMT_LIST will be (uint64_t) -1.
3704 // At present this assumes that there's only one compilation unit DIE.
3706 template <typename A
>
3707 bool Parser
<A
>::read_comp_unit(const char ** name
, const char ** comp_dir
,
3708 uint64_t *stmt_list
)
3710 const uint8_t * debug_info
;
3711 const uint8_t * debug_abbrev
;
3714 const uint8_t * end
;
3715 const uint8_t * enda
;
3718 uint64_t abbrev_base
;
3720 uint8_t address_size
;
3725 *stmt_list
= (uint64_t) -1;
3727 if ( (_file
->_dwarfDebugInfoSect
== NULL
) || (_file
->_dwarfDebugAbbrevSect
== NULL
) )
3730 debug_info
= (uint8_t*)_file
->fileContent() + _file
->_dwarfDebugInfoSect
->offset();
3731 debug_abbrev
= (uint8_t*)_file
->fileContent() + _file
->_dwarfDebugAbbrevSect
->offset();
3734 if (_file
->_dwarfDebugInfoSect
->size() < 12)
3735 /* Too small to be a real debug_info section. */
3737 sz
= A::P::E::get32(*(uint32_t*)di
);
3739 dwarf64
= sz
== 0xffffffff;
3741 sz
= A::P::E::get64(*(uint64_t*)di
), di
+= 8;
3742 else if (sz
> 0xffffff00)
3743 /* Unknown dwarf format. */
3746 /* Verify claimed size. */
3747 if (sz
+ (di
- debug_info
) > _file
->_dwarfDebugInfoSect
->size() || sz
<= (dwarf64
? 23 : 11))
3750 vers
= A::P::E::get16(*(uint16_t*)di
);
3751 if (vers
< 2 || vers
> 4)
3752 /* DWARF version wrong for this code.
3753 Chances are we could continue anyway, but we don't know for sure. */
3757 /* Find the debug_abbrev section. */
3758 abbrev_base
= dwarf64
? A::P::E::get64(*(uint64_t*)di
) : A::P::E::get32(*(uint32_t*)di
);
3759 di
+= dwarf64
? 8 : 4;
3761 if (abbrev_base
> _file
->_dwarfDebugAbbrevSect
->size())
3763 da
= debug_abbrev
+ abbrev_base
;
3764 enda
= debug_abbrev
+ _file
->_dwarfDebugAbbrevSect
->size();
3766 address_size
= *di
++;
3768 /* Find the abbrev number we're looking for. */
3770 abbrev
= read_uleb128 (&di
, end
);
3771 if (abbrev
== (uint64_t) -1)
3774 /* Skip through the debug_abbrev section looking for that abbrev. */
3777 uint64_t this_abbrev
= read_uleb128 (&da
, enda
);
3780 if (this_abbrev
== abbrev
)
3781 /* This is almost always taken. */
3783 skip_leb128 (&da
, enda
); /* Skip the tag. */
3786 da
++; /* Skip the DW_CHILDREN_* value. */
3789 attr
= read_uleb128 (&da
, enda
);
3790 skip_leb128 (&da
, enda
);
3791 } while (attr
!= 0 && attr
!= (uint64_t) -1);
3796 /* Check that the abbrev is one for a DW_TAG_compile_unit. */
3797 if (read_uleb128 (&da
, enda
) != DW_TAG_compile_unit
)
3801 da
++; /* Skip the DW_CHILDREN_* value. */
3803 /* Now, go through the DIE looking for DW_AT_name,
3804 DW_AT_comp_dir, and DW_AT_stmt_list. */
3807 uint64_t attr
= read_uleb128 (&da
, enda
);
3808 uint64_t form
= read_uleb128 (&da
, enda
);
3810 if (attr
== (uint64_t) -1)
3814 if (form
== DW_FORM_indirect
)
3815 form
= read_uleb128 (&di
, end
);
3819 *name
= getDwarfString(form
, di
);
3821 case DW_AT_comp_dir
:
3822 *comp_dir
= getDwarfString(form
, di
);
3824 case DW_AT_stmt_list
:
3825 *stmt_list
= getDwarfOffset(form
, di
, dwarf64
);
3828 if (! skip_form (&di
, end
, form
, address_size
, dwarf64
))
3836 template <typename A
>
3839 free(_sectionsArray
);
3843 template <typename A
>
3844 const char* File
<A
>::translationUnitSource() const
3846 return _dwarfTranslationUnitPath
;
3851 template <typename A
>
3852 bool File
<A
>::forEachAtom(ld::File::AtomHandler
& handler
) const
3854 handler
.doFile(*this);
3855 uint8_t* p
= _atomsArray
;
3856 for(int i
=_atomsArrayCount
; i
> 0; --i
) {
3857 handler
.doAtom(*((Atom
<A
>*)p
));
3858 p
+= sizeof(Atom
<A
>);
3860 p
= _aliasAtomsArray
;
3861 for(int i
=_aliasAtomsArrayCount
; i
> 0; --i
) {
3862 handler
.doAtom(*((AliasAtom
*)p
));
3863 p
+= sizeof(AliasAtom
);
3866 return (_atomsArrayCount
!= 0) || (_aliasAtomsArrayCount
!= 0);
3869 template <typename A
>
3870 const char* Section
<A
>::makeSegmentName(const macho_section
<typename
A::P
>* sect
)
3872 // mach-o section record only has room for 16-byte seg/sect names
3873 // so a 16-byte name has no trailing zero
3874 const char* name
= sect
->segname();
3875 if ( strlen(name
) < 16 )
3877 char* tmp
= new char[17];
3878 strlcpy(tmp
, name
, 17);
3882 template <typename A
>
3883 const char* Section
<A
>::makeSectionName(const macho_section
<typename
A::P
>* sect
)
3885 const char* name
= sect
->sectname();
3886 if ( strlen(name
) < 16 )
3889 // special case common long section names so we don't have to malloc
3890 if ( strncmp(sect
->sectname(), "__objc_classrefs", 16) == 0 )
3891 return "__objc_classrefs";
3892 if ( strncmp(sect
->sectname(), "__objc_classlist", 16) == 0 )
3893 return "__objc_classlist";
3894 if ( strncmp(sect
->sectname(), "__objc_nlclslist", 16) == 0 )
3895 return "__objc_nlclslist";
3896 if ( strncmp(sect
->sectname(), "__objc_nlcatlist", 16) == 0 )
3897 return "__objc_nlcatlist";
3898 if ( strncmp(sect
->sectname(), "__objc_protolist", 16) == 0 )
3899 return "__objc_protolist";
3900 if ( strncmp(sect
->sectname(), "__objc_protorefs", 16) == 0 )
3901 return "__objc_protorefs";
3902 if ( strncmp(sect
->sectname(), "__objc_superrefs", 16) == 0 )
3903 return "__objc_superrefs";
3904 if ( strncmp(sect
->sectname(), "__objc_imageinfo", 16) == 0 )
3905 return "__objc_imageinfo";
3906 if ( strncmp(sect
->sectname(), "__objc_stringobj", 16) == 0 )
3907 return "__objc_stringobj";
3908 if ( strncmp(sect
->sectname(), "__gcc_except_tab", 16) == 0 )
3909 return "__gcc_except_tab";
3911 char* tmp
= new char[17];
3912 strlcpy(tmp
, name
, 17);
3916 template <typename A
>
3917 bool Section
<A
>::readable(const macho_section
<typename
A::P
>* sect
)
3922 template <typename A
>
3923 bool Section
<A
>::writable(const macho_section
<typename
A::P
>* sect
)
3925 // mach-o .o files do not contain segment permissions
3926 // we just know TEXT is special
3927 return ( strcmp(sect
->segname(), "__TEXT") != 0 );
3930 template <typename A
>
3931 bool Section
<A
>::exectuable(const macho_section
<typename
A::P
>* sect
)
3933 // mach-o .o files do not contain segment permissions
3934 // we just know TEXT is special
3935 return ( strcmp(sect
->segname(), "__TEXT") == 0 );
3939 template <typename A
>
3940 ld::Section::Type Section
<A
>::sectionType(const macho_section
<typename
A::P
>* sect
)
3942 switch ( sect
->flags() & SECTION_TYPE
) {
3944 return ld::Section::typeZeroFill
;
3945 case S_CSTRING_LITERALS
:
3946 if ( (strcmp(sect
->sectname(), "__cstring") == 0) && (strcmp(sect
->segname(), "__TEXT") == 0) )
3947 return ld::Section::typeCString
;
3949 return ld::Section::typeNonStdCString
;
3950 case S_4BYTE_LITERALS
:
3951 return ld::Section::typeLiteral4
;
3952 case S_8BYTE_LITERALS
:
3953 return ld::Section::typeLiteral8
;
3954 case S_LITERAL_POINTERS
:
3955 return ld::Section::typeCStringPointer
;
3956 case S_NON_LAZY_SYMBOL_POINTERS
:
3957 return ld::Section::typeNonLazyPointer
;
3958 case S_LAZY_SYMBOL_POINTERS
:
3959 return ld::Section::typeLazyPointer
;
3960 case S_SYMBOL_STUBS
:
3961 return ld::Section::typeStub
;
3962 case S_MOD_INIT_FUNC_POINTERS
:
3963 return ld::Section::typeInitializerPointers
;
3964 case S_MOD_TERM_FUNC_POINTERS
:
3965 return ld::Section::typeTerminatorPointers
;
3967 return ld::Section::typeUnclassified
;
3968 case S_16BYTE_LITERALS
:
3969 return ld::Section::typeLiteral16
;
3972 if ( sect
->flags() & S_ATTR_PURE_INSTRUCTIONS
) {
3973 return ld::Section::typeCode
;
3975 else if ( strcmp(sect
->segname(), "__TEXT") == 0 ) {
3976 if ( strcmp(sect
->sectname(), "__eh_frame") == 0 )
3977 return ld::Section::typeCFI
;
3978 else if ( strcmp(sect
->sectname(), "__ustring") == 0 )
3979 return ld::Section::typeUTF16Strings
;
3980 else if ( strcmp(sect
->sectname(), "__textcoal_nt") == 0 )
3981 return ld::Section::typeCode
;
3982 else if ( strcmp(sect
->sectname(), "__StaticInit") == 0 )
3983 return ld::Section::typeCode
;
3984 else if ( strcmp(sect
->sectname(), "__constructor") == 0 )
3985 return ld::Section::typeInitializerPointers
;
3987 else if ( strcmp(sect
->segname(), "__DATA") == 0 ) {
3988 if ( strcmp(sect
->sectname(), "__cfstring") == 0 )
3989 return ld::Section::typeCFString
;
3990 else if ( strcmp(sect
->sectname(), "__dyld") == 0 )
3991 return ld::Section::typeDyldInfo
;
3992 else if ( strcmp(sect
->sectname(), "__program_vars") == 0 )
3993 return ld::Section::typeDyldInfo
;
3994 else if ( strncmp(sect
->sectname(), "__objc_classrefs", 16) == 0 )
3995 return ld::Section::typeObjCClassRefs
;
3996 else if ( strcmp(sect
->sectname(), "__objc_catlist") == 0 )
3997 return ld::Section::typeObjC2CategoryList
;
3999 else if ( strcmp(sect
->segname(), "__OBJC") == 0 ) {
4000 if ( strcmp(sect
->sectname(), "__class") == 0 )
4001 return ld::Section::typeObjC1Classes
;
4004 case S_THREAD_LOCAL_REGULAR
:
4005 return ld::Section::typeTLVInitialValues
;
4006 case S_THREAD_LOCAL_ZEROFILL
:
4007 return ld::Section::typeTLVZeroFill
;
4008 case S_THREAD_LOCAL_VARIABLES
:
4009 return ld::Section::typeTLVDefs
;
4010 case S_THREAD_LOCAL_INIT_FUNCTION_POINTERS
:
4011 return ld::Section::typeTLVInitializerPointers
;
4013 return ld::Section::typeUnclassified
;
4017 template <typename A
>
4018 Atom
<A
>* Section
<A
>::findContentAtomByAddress(pint_t addr
, class Atom
<A
>* start
, class Atom
<A
>* end
)
4020 // do a binary search of atom array
4021 uint32_t atomCount
= end
- start
;
4022 Atom
<A
>* base
= start
;
4023 for (uint32_t n
= atomCount
; n
> 0; n
/= 2) {
4024 Atom
<A
>* pivot
= &base
[n
/2];
4025 pint_t atomStartAddr
= pivot
->_objAddress
;
4026 pint_t atomEndAddr
= atomStartAddr
+ pivot
->_size
;
4027 if ( atomStartAddr
<= addr
) {
4028 // address in normal atom
4029 if (addr
< atomEndAddr
)
4031 // address in "end" label (but not in alias)
4032 if ( (pivot
->_size
== 0) && (addr
== atomEndAddr
) && !pivot
->isAlias() )
4035 if ( addr
>= atomEndAddr
) {
4037 // move base to atom after pivot
4049 template <typename A
>
4050 ld::Atom::Alignment Section
<A
>::alignmentForAddress(pint_t addr
)
4052 const uint32_t sectionAlignment
= this->_machOSection
->align();
4053 uint32_t modulus
= (addr
% (1 << sectionAlignment
));
4054 if ( modulus
> 0xFFFF )
4055 warning("alignment for symbol at address 0x%08llX in %s exceeds 2^16", (uint64_t)addr
, this->file().path());
4056 return ld::Atom::Alignment(sectionAlignment
, modulus
);
4059 template <typename A
>
4060 uint32_t Section
<A
>::sectionNum(class Parser
<A
>& parser
) const
4062 if ( _machOSection
== NULL
)
4065 return 1 + (this->_machOSection
- parser
.firstMachOSection());
4068 // arm does not have zero cost exceptions
4070 uint32_t CFISection
<arm
>::cfiCount(Parser
<arm
>& parser
)
4075 template <typename A
>
4076 uint32_t CFISection
<A
>::cfiCount(Parser
<A
>& parser
)
4078 // create ObjectAddressSpace object for use by libunwind
4079 OAS
oas(*this, (uint8_t*)this->file().fileContent()+this->_machOSection
->offset());
4080 return libunwind::CFI_Parser
<OAS
>::getCFICount(oas
,
4081 this->_machOSection
->addr(), this->_machOSection
->size());
4084 template <typename A
>
4085 void CFISection
<A
>::warnFunc(void* ref
, uint64_t funcAddr
, const char* msg
)
4087 Parser
<A
>* parser
= (Parser
<A
>*)ref
;
4088 if ( ! parser
->warnUnwindConversionProblems() )
4090 if ( funcAddr
!= CFI_INVALID_ADDRESS
) {
4091 // atoms are not constructed yet, so scan symbol table for labels
4092 const char* name
= parser
->scanSymbolTableForAddress(funcAddr
);
4093 warning("could not create compact unwind for %s: %s", name
, msg
);
4096 warning("could not create compact unwind: %s", msg
);
4101 bool CFISection
<x86_64
>::needsRelocating()
4107 bool CFISection
<arm64
>::needsRelocating()
4112 template <typename A
>
4113 bool CFISection
<A
>::needsRelocating()
4119 void CFISection
<x86_64
>::cfiParse(class Parser
<x86_64
>& parser
, uint8_t* buffer
,
4120 libunwind::CFI_Atom_Info
<CFISection
<x86_64
>::OAS
>::CFI_Atom_Info cfiArray
[],
4121 uint32_t& count
, const pint_t cuStarts
[], uint32_t cuCount
)
4123 // copy __eh_frame data to buffer
4124 memcpy(buffer
, file().fileContent() + this->_machOSection
->offset(), this->_machOSection
->size());
4126 // and apply relocations
4127 const macho_relocation_info
<P
>* relocs
= (macho_relocation_info
<P
>*)(file().fileContent() + this->_machOSection
->reloff());
4128 const macho_relocation_info
<P
>* relocsEnd
= &relocs
[this->_machOSection
->nreloc()];
4129 for (const macho_relocation_info
<P
>* reloc
= relocs
; reloc
< relocsEnd
; ++reloc
) {
4131 switch ( reloc
->r_type() ) {
4132 case X86_64_RELOC_SUBTRACTOR
:
4133 value
= 0 - parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
4135 if ( reloc
->r_extern() )
4136 value
+= parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
4138 case X86_64_RELOC_UNSIGNED
:
4139 value
= parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
4141 case X86_64_RELOC_GOT
:
4142 // this is used for the reference to the personality function in CIEs
4143 // store the symbol number of the personality function for later use as a Fixup
4144 value
= reloc
->r_symbolnum();
4147 fprintf(stderr
, "CFISection::cfiParse() unexpected relocation type at r_address=0x%08X\n", reloc
->r_address());
4152 switch ( reloc
->r_length() ) {
4154 p64
= (uint64_t*)&buffer
[reloc
->r_address()];
4155 E::set64(*p64
, value
+ E::get64(*p64
));
4158 p32
= (uint32_t*)&buffer
[reloc
->r_address()];
4159 E::set32(*p32
, value
+ E::get32(*p32
));
4162 fprintf(stderr
, "CFISection::cfiParse() unexpected relocation size at r_address=0x%08X\n", reloc
->r_address());
4167 // create ObjectAddressSpace object for use by libunwind
4168 OAS
oas(*this, buffer
);
4170 // use libuwind to parse __eh_frame data into array of CFI_Atom_Info
4172 msg
= libunwind::DwarfInstructions
<OAS
, libunwind::Registers_x86_64
>::parseCFIs(
4173 oas
, this->_machOSection
->addr(), this->_machOSection
->size(),
4174 cuStarts
, cuCount
, parser
.keepDwarfUnwind(), parser
.forceDwarfConversion(), parser
.neverConvertDwarf(),
4175 cfiArray
, count
, (void*)&parser
, warnFunc
);
4177 throwf("malformed __eh_frame section: %s", msg
);
4181 void CFISection
<x86
>::cfiParse(class Parser
<x86
>& parser
, uint8_t* buffer
,
4182 libunwind::CFI_Atom_Info
<CFISection
<x86
>::OAS
>::CFI_Atom_Info cfiArray
[],
4183 uint32_t& count
, const pint_t cuStarts
[], uint32_t cuCount
)
4185 // create ObjectAddressSpace object for use by libunwind
4186 OAS
oas(*this, (uint8_t*)this->file().fileContent()+this->_machOSection
->offset());
4188 // use libuwind to parse __eh_frame data into array of CFI_Atom_Info
4190 msg
= libunwind::DwarfInstructions
<OAS
, libunwind::Registers_x86
>::parseCFIs(
4191 oas
, this->_machOSection
->addr(), this->_machOSection
->size(),
4192 cuStarts
, cuCount
, parser
.keepDwarfUnwind(), parser
.forceDwarfConversion(), parser
.neverConvertDwarf(),
4193 cfiArray
, count
, (void*)&parser
, warnFunc
);
4195 throwf("malformed __eh_frame section: %s", msg
);
4202 void CFISection
<arm
>::cfiParse(class Parser
<arm
>& parser
, uint8_t* buffer
,
4203 libunwind::CFI_Atom_Info
<CFISection
<arm
>::OAS
>::CFI_Atom_Info cfiArray
[],
4204 uint32_t& count
, const pint_t cuStarts
[], uint32_t cuCount
)
4206 // arm does not use zero cost exceptions
4214 void CFISection
<arm64
>::cfiParse(class Parser
<arm64
>& parser
, uint8_t* buffer
,
4215 libunwind::CFI_Atom_Info
<CFISection
<arm64
>::OAS
>::CFI_Atom_Info cfiArray
[],
4216 uint32_t& count
, const pint_t cuStarts
[], uint32_t cuCount
)
4218 // copy __eh_frame data to buffer
4219 memcpy(buffer
, file().fileContent() + this->_machOSection
->offset(), this->_machOSection
->size());
4221 // and apply relocations
4222 const macho_relocation_info
<P
>* relocs
= (macho_relocation_info
<P
>*)(file().fileContent() + this->_machOSection
->reloff());
4223 const macho_relocation_info
<P
>* relocsEnd
= &relocs
[this->_machOSection
->nreloc()];
4224 for (const macho_relocation_info
<P
>* reloc
= relocs
; reloc
< relocsEnd
; ++reloc
) {
4225 uint64_t* p64
= (uint64_t*)&buffer
[reloc
->r_address()];
4226 uint32_t* p32
= (uint32_t*)&buffer
[reloc
->r_address()];
4227 uint32_t addend32
= E::get32(*p32
);
4228 uint64_t addend64
= E::get64(*p64
);
4230 switch ( reloc
->r_type() ) {
4231 case ARM64_RELOC_SUBTRACTOR
:
4232 value
= 0 - parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
4234 if ( reloc
->r_extern() )
4235 value
+= parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
4237 case ARM64_RELOC_UNSIGNED
:
4238 value
= parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
4240 case ARM64_RELOC_POINTER_TO_GOT
:
4241 // this is used for the reference to the personality function in CIEs
4242 // store the symbol number of the personality function for later use as a Fixup
4243 value
= reloc
->r_symbolnum();
4248 fprintf(stderr
, "CFISection::cfiParse() unexpected relocation type at r_address=0x%08X\n", reloc
->r_address());
4251 switch ( reloc
->r_length() ) {
4253 E::set64(*p64
, value
+ addend64
);
4256 E::set32(*p32
, value
+ addend32
);
4259 fprintf(stderr
, "CFISection::cfiParse() unexpected relocation size at r_address=0x%08X\n", reloc
->r_address());
4265 // create ObjectAddressSpace object for use by libunwind
4266 OAS
oas(*this, buffer
);
4268 // use libuwind to parse __eh_frame data into array of CFI_Atom_Info
4270 msg
= libunwind::DwarfInstructions
<OAS
, libunwind::Registers_arm64
>::parseCFIs(
4271 oas
, this->_machOSection
->addr(), this->_machOSection
->size(),
4272 cuStarts
, cuCount
, parser
.keepDwarfUnwind(), parser
.forceDwarfConversion(), parser
.neverConvertDwarf(),
4273 cfiArray
, count
, (void*)&parser
, warnFunc
);
4275 throwf("malformed __eh_frame section: %s", msg
);
4279 template <typename A
>
4280 uint32_t CFISection
<A
>::computeAtomCount(class Parser
<A
>& parser
,
4281 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
4282 const struct Parser
<A
>::CFI_CU_InfoArrays
& cfis
)
4284 return cfis
.cfiCount
;
4289 template <typename A
>
4290 uint32_t CFISection
<A
>::appendAtoms(class Parser
<A
>& parser
, uint8_t* p
,
4291 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
4292 const struct Parser
<A
>::CFI_CU_InfoArrays
& cfis
)
4294 this->_beginAtoms
= (Atom
<A
>*)p
;
4295 // walk CFI_Atom_Info array and create atom for each entry
4296 const CFI_Atom_Info
* start
= &cfis
.cfiArray
[0];
4297 const CFI_Atom_Info
* end
= &cfis
.cfiArray
[cfis
.cfiCount
];
4298 for(const CFI_Atom_Info
* a
=start
; a
< end
; ++a
) {
4299 Atom
<A
>* space
= (Atom
<A
>*)p
;
4300 new (space
) Atom
<A
>(*this, (a
->isCIE
? "CIE" : "FDE"), a
->address
, a
->size
,
4301 ld::Atom::definitionRegular
, ld::Atom::combineNever
, ld::Atom::scopeTranslationUnit
,
4302 ld::Atom::typeCFI
, ld::Atom::symbolTableNotInFinalLinkedImages
,
4303 false, false, false, ld::Atom::Alignment(0));
4304 p
+= sizeof(Atom
<A
>);
4306 this->_endAtoms
= (Atom
<A
>*)p
;
4307 return cfis
.cfiCount
;
4311 template <> bool CFISection
<x86_64
>::bigEndian() { return false; }
4312 template <> bool CFISection
<x86
>::bigEndian() { return false; }
4313 template <> bool CFISection
<arm
>::bigEndian() { return false; }
4314 template <> bool CFISection
<arm64
>::bigEndian() { return false; }
4318 void CFISection
<x86_64
>::addCiePersonalityFixups(class Parser
<x86_64
>& parser
, const CFI_Atom_Info
* cieInfo
)
4320 uint8_t personalityEncoding
= cieInfo
->u
.cieInfo
.personality
.encodingOfTargetAddress
;
4321 if ( personalityEncoding
== 0x9B ) {
4322 // compiler always produces X86_64_RELOC_GOT with addend of 4 to personality function
4323 // CFISection<x86_64>::cfiParse() set targetAddress to be symbolIndex + 4 + addressInCIE
4324 uint32_t symbolIndex
= cieInfo
->u
.cieInfo
.personality
.targetAddress
- 4
4325 - cieInfo
->address
- cieInfo
->u
.cieInfo
.personality
.offsetInCFI
;
4326 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(symbolIndex
);
4327 const char* personalityName
= parser
.nameFromSymbol(sym
);
4329 Atom
<x86_64
>* cieAtom
= this->findAtomByAddress(cieInfo
->address
);
4330 Parser
<x86_64
>::SourceLocation
src(cieAtom
, cieInfo
->u
.cieInfo
.personality
.offsetInCFI
);
4331 parser
.addFixup(src
, ld::Fixup::k1of3
, ld::Fixup::kindSetTargetAddress
, false, personalityName
);
4332 parser
.addFixup(src
, ld::Fixup::k2of3
, ld::Fixup::kindAddAddend
, 4);
4333 parser
.addFixup(src
, ld::Fixup::k3of3
, ld::Fixup::kindStoreX86PCRel32GOT
);
4335 else if ( personalityEncoding
!= 0 ) {
4336 throwf("unsupported address encoding (%02X) of personality function in CIE",
4337 personalityEncoding
);
4342 void CFISection
<x86
>::addCiePersonalityFixups(class Parser
<x86
>& parser
, const CFI_Atom_Info
* cieInfo
)
4344 uint8_t personalityEncoding
= cieInfo
->u
.cieInfo
.personality
.encodingOfTargetAddress
;
4345 if ( (personalityEncoding
== 0x9B) || (personalityEncoding
== 0x90) ) {
4346 uint32_t offsetInCFI
= cieInfo
->u
.cieInfo
.personality
.offsetInCFI
;
4347 uint32_t nlpAddr
= cieInfo
->u
.cieInfo
.personality
.targetAddress
;
4348 Atom
<x86
>* cieAtom
= this->findAtomByAddress(cieInfo
->address
);
4349 Atom
<x86
>* nlpAtom
= parser
.findAtomByAddress(nlpAddr
);
4350 assert(nlpAtom
->contentType() == ld::Atom::typeNonLazyPointer
);
4351 Parser
<x86
>::SourceLocation
src(cieAtom
, cieInfo
->u
.cieInfo
.personality
.offsetInCFI
);
4353 parser
.addFixup(src
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, nlpAtom
);
4354 parser
.addFixup(src
, ld::Fixup::k2of4
, ld::Fixup::kindSubtractTargetAddress
, cieAtom
);
4355 parser
.addFixup(src
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractAddend
, offsetInCFI
);
4356 parser
.addFixup(src
, ld::Fixup::k4of4
, ld::Fixup::kindStoreLittleEndian32
);
4358 else if ( personalityEncoding
!= 0 ) {
4359 throwf("unsupported address encoding (%02X) of personality function in CIE", personalityEncoding
);
4363 #if SUPPORT_ARCH_arm64
4365 void CFISection
<arm64
>::addCiePersonalityFixups(class Parser
<arm64
>& parser
, const CFI_Atom_Info
* cieInfo
)
4367 uint8_t personalityEncoding
= cieInfo
->u
.cieInfo
.personality
.encodingOfTargetAddress
;
4368 if ( personalityEncoding
== 0x9B ) {
4369 // compiler always produces ARM64_RELOC_GOT r_pcrel=1 to personality function
4370 // CFISection<arm64>::cfiParse() set targetAddress to be symbolIndex + addressInCIE
4371 uint32_t symbolIndex
= cieInfo
->u
.cieInfo
.personality
.targetAddress
4372 - cieInfo
->address
- cieInfo
->u
.cieInfo
.personality
.offsetInCFI
;
4373 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(symbolIndex
);
4374 const char* personalityName
= parser
.nameFromSymbol(sym
);
4376 Atom
<arm64
>* cieAtom
= this->findAtomByAddress(cieInfo
->address
);
4377 Parser
<arm64
>::SourceLocation
src(cieAtom
, cieInfo
->u
.cieInfo
.personality
.offsetInCFI
);
4378 parser
.addFixup(src
, ld::Fixup::k1of2
, ld::Fixup::kindSetTargetAddress
, false, personalityName
);
4379 parser
.addFixup(src
, ld::Fixup::k2of2
, ld::Fixup::kindStoreARM64PCRelToGOT
);
4381 else if ( personalityEncoding
!= 0 ) {
4382 throwf("unsupported address encoding (%02X) of personality function in CIE",
4383 personalityEncoding
);
4389 template <typename A
>
4390 void CFISection
<A
>::addCiePersonalityFixups(class Parser
<A
>& parser
, const CFI_Atom_Info
* cieInfo
)
4392 assert(0 && "addCiePersonalityFixups() not implemented for arch");
4395 template <typename A
>
4396 void CFISection
<A
>::makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
& cfis
)
4398 ld::Fixup::Kind store32
= bigEndian() ? ld::Fixup::kindStoreBigEndian32
: ld::Fixup::kindStoreLittleEndian32
;
4399 ld::Fixup::Kind store64
= bigEndian() ? ld::Fixup::kindStoreBigEndian64
: ld::Fixup::kindStoreLittleEndian64
;
4401 // add all references for FDEs, including implicit group references
4402 const CFI_Atom_Info
* end
= &cfis
.cfiArray
[cfis
.cfiCount
];
4403 for(const CFI_Atom_Info
* p
= &cfis
.cfiArray
[0]; p
< end
; ++p
) {
4405 // add reference to personality function if used
4406 if ( p
->u
.cieInfo
.personality
.targetAddress
!= CFI_INVALID_ADDRESS
) {
4407 this->addCiePersonalityFixups(parser
, p
);
4412 Atom
<A
>* fdeAtom
= this->findAtomByAddress(p
->address
);
4413 // find function Atom
4414 Atom
<A
>* functionAtom
= parser
.findAtomByAddress(p
->u
.fdeInfo
.function
.targetAddress
);
4416 Atom
<A
>* cieAtom
= this->findAtomByAddress(p
->u
.fdeInfo
.cie
.targetAddress
);
4418 Atom
<A
>* lsdaAtom
= NULL
;
4419 if ( p
->u
.fdeInfo
.lsda
.targetAddress
!= CFI_INVALID_ADDRESS
) {
4420 lsdaAtom
= parser
.findAtomByAddress(p
->u
.fdeInfo
.lsda
.targetAddress
);
4422 // add reference from FDE to CIE (always 32-bit pc-rel)
4423 typename Parser
<A
>::SourceLocation
fdeToCieSrc(fdeAtom
, p
->u
.fdeInfo
.cie
.offsetInCFI
);
4424 parser
.addFixup(fdeToCieSrc
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, fdeAtom
);
4425 parser
.addFixup(fdeToCieSrc
, ld::Fixup::k2of4
, ld::Fixup::kindAddAddend
, p
->u
.fdeInfo
.cie
.offsetInCFI
);
4426 parser
.addFixup(fdeToCieSrc
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractTargetAddress
, cieAtom
);
4427 parser
.addFixup(fdeToCieSrc
, ld::Fixup::k4of4
, store32
, cieAtom
);
4429 // add reference from FDE to function
4430 typename Parser
<A
>::SourceLocation
fdeToFuncSrc(fdeAtom
, p
->u
.fdeInfo
.function
.offsetInCFI
);
4431 switch (p
->u
.fdeInfo
.function
.encodingOfTargetAddress
) {
4432 case DW_EH_PE_pcrel
|DW_EH_PE_ptr
:
4433 if ( sizeof(typename
A::P::uint_t
) == 8 ) {
4434 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, functionAtom
);
4435 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k2of4
, ld::Fixup::kindSubtractTargetAddress
, fdeAtom
);
4436 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractAddend
, p
->u
.fdeInfo
.function
.offsetInCFI
);
4437 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k4of4
, store64
);
4440 // else fall into 32-bit case
4441 case DW_EH_PE_pcrel
|DW_EH_PE_sdata4
:
4442 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, functionAtom
);
4443 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k2of4
, ld::Fixup::kindSubtractTargetAddress
, fdeAtom
);
4444 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractAddend
, p
->u
.fdeInfo
.function
.offsetInCFI
);
4445 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k4of4
, store32
);
4448 throw "unsupported encoding in FDE of pointer to function";
4451 // add reference from FDE to LSDA
4452 typename Parser
<A
>::SourceLocation
fdeToLsdaSrc(fdeAtom
, p
->u
.fdeInfo
.lsda
.offsetInCFI
);
4453 if ( lsdaAtom
!= NULL
) {
4454 switch (p
->u
.fdeInfo
.lsda
.encodingOfTargetAddress
) {
4455 case DW_EH_PE_pcrel
|DW_EH_PE_ptr
:
4456 if ( sizeof(typename
A::P::uint_t
) == 8 ) {
4457 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, lsdaAtom
);
4458 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k2of4
, ld::Fixup::kindSubtractTargetAddress
, fdeAtom
);
4459 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractAddend
, p
->u
.fdeInfo
.lsda
.offsetInCFI
);
4460 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k4of4
, store64
);
4463 // else fall into 32-bit case
4464 case DW_EH_PE_pcrel
|DW_EH_PE_sdata4
:
4465 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, lsdaAtom
);
4466 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k2of4
, ld::Fixup::kindSubtractTargetAddress
, fdeAtom
);
4467 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractAddend
, p
->u
.fdeInfo
.lsda
.offsetInCFI
);
4468 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k4of4
, store32
);
4471 throw "unsupported encoding in FDE of pointer to LSDA";
4475 // FDE is in group lead by function atom
4476 typename Parser
<A
>::SourceLocation
fdeSrc(functionAtom
,0);
4477 parser
.addFixup(fdeSrc
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinateFDE
, fdeAtom
);
4479 // LSDA is in group lead by function atom
4480 if ( lsdaAtom
!= NULL
) {
4481 parser
.addFixup(fdeSrc
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinateLSDA
, lsdaAtom
);
4490 template <typename A
>
4491 const void* CFISection
<A
>::OAS::mappedAddress(pint_t addr
)
4493 if ( (_ehFrameStartAddr
<= addr
) && (addr
< _ehFrameEndAddr
) )
4494 return &_ehFrameContent
[addr
-_ehFrameStartAddr
];
4496 // requested bytes are not in __eh_frame section
4497 // this can occur when examining the instruction bytes in the __text
4498 File
<A
>& file
= _ehFrameSection
.file();
4499 for (uint32_t i
=0; i
< file
._sectionsArrayCount
; ++i
) {
4500 const macho_section
<typename
A::P
>* sect
= file
._sectionsArray
[i
]->machoSection();
4501 // TentativeDefinitionSection and AbsoluteSymbolSection have no mach-o section
4502 if ( sect
!= NULL
) {
4503 if ( (sect
->addr() <= addr
) && (addr
< (sect
->addr()+sect
->size())) ) {
4504 return file
.fileContent() + sect
->offset() + addr
- sect
->addr();
4508 throwf("__eh_frame parsing problem. Can't find target of reference to address 0x%08llX", (uint64_t)addr
);
4513 template <typename A
>
4514 uint64_t CFISection
<A
>::OAS::getULEB128(pint_t
& logicalAddr
, pint_t end
)
4516 uintptr_t size
= (end
- logicalAddr
);
4517 libunwind::LocalAddressSpace::pint_t laddr
= (libunwind::LocalAddressSpace::pint_t
)mappedAddress(logicalAddr
);
4518 libunwind::LocalAddressSpace::pint_t sladdr
= laddr
;
4519 uint64_t result
= libunwind::LocalAddressSpace::getULEB128(laddr
, laddr
+size
);
4520 logicalAddr
+= (laddr
-sladdr
);
4524 template <typename A
>
4525 int64_t CFISection
<A
>::OAS::getSLEB128(pint_t
& logicalAddr
, pint_t end
)
4527 uintptr_t size
= (end
- logicalAddr
);
4528 libunwind::LocalAddressSpace::pint_t laddr
= (libunwind::LocalAddressSpace::pint_t
)mappedAddress(logicalAddr
);
4529 libunwind::LocalAddressSpace::pint_t sladdr
= laddr
;
4530 int64_t result
= libunwind::LocalAddressSpace::getSLEB128(laddr
, laddr
+size
);
4531 logicalAddr
+= (laddr
-sladdr
);
4535 template <typename A
>
4536 typename
A::P::uint_t CFISection
<A
>::OAS::getEncodedP(pint_t
& addr
, pint_t end
, uint8_t encoding
)
4538 pint_t startAddr
= addr
;
4543 switch (encoding
& 0x0F) {
4545 result
= getP(addr
);
4546 p
+= sizeof(pint_t
);
4549 case DW_EH_PE_uleb128
:
4550 result
= getULEB128(addr
, end
);
4552 case DW_EH_PE_udata2
:
4553 result
= get16(addr
);
4557 case DW_EH_PE_udata4
:
4558 result
= get32(addr
);
4562 case DW_EH_PE_udata8
:
4563 result
= get64(addr
);
4567 case DW_EH_PE_sleb128
:
4568 result
= getSLEB128(addr
, end
);
4570 case DW_EH_PE_sdata2
:
4571 result
= (int16_t)get16(addr
);
4575 case DW_EH_PE_sdata4
:
4576 result
= (int32_t)get32(addr
);
4580 case DW_EH_PE_sdata8
:
4581 result
= get64(addr
);
4586 throwf("ObjectFileAddressSpace<A>::getEncodedP() encoding 0x%08X not supported", encoding
);
4589 // then add relative offset
4590 switch ( encoding
& 0x70 ) {
4591 case DW_EH_PE_absptr
:
4594 case DW_EH_PE_pcrel
:
4595 result
+= startAddr
;
4597 case DW_EH_PE_textrel
:
4598 throw "DW_EH_PE_textrel pointer encoding not supported";
4600 case DW_EH_PE_datarel
:
4601 throw "DW_EH_PE_datarel pointer encoding not supported";
4603 case DW_EH_PE_funcrel
:
4604 throw "DW_EH_PE_funcrel pointer encoding not supported";
4606 case DW_EH_PE_aligned
:
4607 throw "DW_EH_PE_aligned pointer encoding not supported";
4610 throwf("ObjectFileAddressSpace<A>::getEncodedP() encoding 0x%08X not supported", encoding
);
4614 // Note: DW_EH_PE_indirect is only used in CIEs to refernce the personality pointer
4615 // When parsing .o files that pointer contains zero, so we don't to return that.
4616 // Instead we skip the dereference and return the address of the pointer.
4617 // if ( encoding & DW_EH_PE_indirect )
4618 // result = getP(result);
4624 const char* CUSection
<x86_64
>::personalityName(class Parser
<x86_64
>& parser
, const macho_relocation_info
<x86_64::P
>* reloc
)
4626 if ( reloc
->r_extern() ) {
4627 assert((reloc
->r_type() == X86_64_RELOC_UNSIGNED
) && "wrong reloc type on personality column in __compact_unwind section");
4628 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
4629 return parser
.nameFromSymbol(sym
);
4632 const pint_t
* content
= (pint_t
*)(this->file().fileContent() + this->_machOSection
->offset() + reloc
->r_address());
4633 pint_t personalityAddr
= *content
;
4634 assert((parser
.sectionForAddress(personalityAddr
)->type() == ld::Section::typeCode
) && "personality column in __compact_unwind section is not pointer to function");
4635 // atoms may not be constructed yet, so scan symbol table for labels
4636 const char* name
= parser
.scanSymbolTableForAddress(personalityAddr
);
4642 const char* CUSection
<x86
>::personalityName(class Parser
<x86
>& parser
, const macho_relocation_info
<x86::P
>* reloc
)
4644 if ( reloc
->r_extern() ) {
4645 assert((reloc
->r_type() == GENERIC_RELOC_VANILLA
) && "wrong reloc type on personality column in __compact_unwind section");
4646 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
4647 return parser
.nameFromSymbol(sym
);
4650 // support __LD, __compact_unwind personality entries which are pointer to personality non-lazy pointer
4651 const pint_t
* content
= (pint_t
*)(this->file().fileContent() + this->_machOSection
->offset() + reloc
->r_address());
4652 pint_t nlPointerAddr
= *content
;
4653 Section
<x86
>* nlSection
= parser
.sectionForAddress(nlPointerAddr
);
4654 if ( nlSection
->type() == ld::Section::typeCode
) {
4655 // personality function is defined in this .o file, so this is a direct reference to it
4656 // atoms may not be constructed yet, so scan symbol table for labels
4657 const char* name
= parser
.scanSymbolTableForAddress(nlPointerAddr
);
4661 uint32_t symIndex
= parser
.symbolIndexFromIndirectSectionAddress(nlPointerAddr
, nlSection
->machoSection());
4662 const macho_nlist
<P
>& nlSymbol
= parser
.symbolFromIndex(symIndex
);
4663 return parser
.nameFromSymbol(nlSymbol
);
4668 #if SUPPORT_ARCH_arm64
4670 const char* CUSection
<arm64
>::personalityName(class Parser
<arm64
>& parser
, const macho_relocation_info
<arm64::P
>* reloc
)
4672 if ( reloc
->r_extern() ) {
4673 assert((reloc
->r_type() == ARM64_RELOC_UNSIGNED
) && "wrong reloc type on personality column in __compact_unwind section");
4674 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
4675 return parser
.nameFromSymbol(sym
);
4678 const pint_t
* content
= (pint_t
*)(this->file().fileContent() + this->_machOSection
->offset() + reloc
->r_address());
4679 pint_t personalityAddr
= *content
;
4680 Section
<arm64
>* personalitySection
= parser
.sectionForAddress(personalityAddr
);
4681 assert((personalitySection
->type() == ld::Section::typeCode
) && "personality column in __compact_unwind section is not pointer to function");
4682 // atoms may not be constructed yet, so scan symbol table for labels
4683 const char* name
= parser
.scanSymbolTableForAddress(personalityAddr
);
4690 template <typename A
>
4691 const char* CUSection
<A
>::personalityName(class Parser
<A
>& parser
, const macho_relocation_info
<P
>* reloc
)
4697 bool CUSection
<x86
>::encodingMeansUseDwarf(compact_unwind_encoding_t enc
)
4699 return ((enc
& UNWIND_X86_MODE_MASK
) == UNWIND_X86_MODE_DWARF
);
4703 bool CUSection
<x86_64
>::encodingMeansUseDwarf(compact_unwind_encoding_t enc
)
4705 return ((enc
& UNWIND_X86_64_MODE_MASK
) == UNWIND_X86_64_MODE_DWARF
);
4708 #if SUPPORT_ARCH_arm_any
4710 bool CUSection
<arm
>::encodingMeansUseDwarf(compact_unwind_encoding_t enc
)
4716 #if SUPPORT_ARCH_arm64
4718 bool CUSection
<arm64
>::encodingMeansUseDwarf(compact_unwind_encoding_t enc
)
4720 return ((enc
& UNWIND_ARM64_MODE_MASK
) == UNWIND_ARM64_MODE_DWARF
);
4724 template <typename A
>
4725 int CUSection
<A
>::infoSorter(const void* l
, const void* r
)
4727 // sort references by symbol index, then address
4728 const Info
* left
= (Info
*)l
;
4729 const Info
* right
= (Info
*)r
;
4730 if ( left
->functionSymbolIndex
== right
->functionSymbolIndex
)
4731 return (left
->functionStartAddress
- right
->functionStartAddress
);
4733 return (left
->functionSymbolIndex
- right
->functionSymbolIndex
);
4736 template <typename A
>
4737 void CUSection
<A
>::parse(class Parser
<A
>& parser
, uint32_t cnt
, Info array
[])
4739 // walk section content and copy to Info array
4740 const macho_compact_unwind_entry
<P
>* const entries
= (macho_compact_unwind_entry
<P
>*)(this->file().fileContent() + this->_machOSection
->offset());
4741 for (uint32_t i
=0; i
< cnt
; ++i
) {
4742 Info
* info
= &array
[i
];
4743 const macho_compact_unwind_entry
<P
>* entry
= &entries
[i
];
4744 info
->functionStartAddress
= entry
->codeStart();
4745 info
->functionSymbolIndex
= 0xFFFFFFFF;
4746 info
->rangeLength
= entry
->codeLen();
4747 info
->compactUnwindInfo
= entry
->compactUnwindInfo();
4748 info
->personality
= NULL
;
4749 info
->lsdaAddress
= entry
->lsda();
4750 info
->function
= NULL
;
4752 if ( (info
->compactUnwindInfo
& UNWIND_PERSONALITY_MASK
) != 0 )
4753 warning("no bits should be set in UNWIND_PERSONALITY_MASK of compact unwind encoding in __LD,__compact_unwind section");
4754 if ( info
->lsdaAddress
!= 0 ) {
4755 info
->compactUnwindInfo
|= UNWIND_HAS_LSDA
;
4759 // scan relocs, extern relocs are needed for personality references (possibly for function/lsda refs??)
4760 const macho_relocation_info
<P
>* relocs
= (macho_relocation_info
<P
>*)(this->file().fileContent() + this->_machOSection
->reloff());
4761 const macho_relocation_info
<P
>* relocsEnd
= &relocs
[this->_machOSection
->nreloc()];
4762 for (const macho_relocation_info
<P
>* reloc
= relocs
; reloc
< relocsEnd
; ++reloc
) {
4763 if ( reloc
->r_extern() ) {
4764 // only expect external relocs on some colummns
4765 if ( (reloc
->r_address() % sizeof(macho_compact_unwind_entry
<P
>)) == macho_compact_unwind_entry
<P
>::personalityFieldOffset() ) {
4766 uint32_t entryIndex
= reloc
->r_address() / sizeof(macho_compact_unwind_entry
<P
>);
4767 array
[entryIndex
].personality
= this->personalityName(parser
, reloc
);
4769 else if ( (reloc
->r_address() % sizeof(macho_compact_unwind_entry
<P
>)) == macho_compact_unwind_entry
<P
>::lsdaFieldOffset() ) {
4770 uint32_t entryIndex
= reloc
->r_address() / sizeof(macho_compact_unwind_entry
<P
>);
4771 const macho_nlist
<P
>& lsdaSym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
4772 if ( (lsdaSym
.n_type() & N_TYPE
) == N_SECT
)
4773 array
[entryIndex
].lsdaAddress
= lsdaSym
.n_value();
4775 warning("unexpected extern relocation to lsda in __compact_unwind section");
4777 else if ( (reloc
->r_address() % sizeof(macho_compact_unwind_entry
<P
>)) == macho_compact_unwind_entry
<P
>::codeStartFieldOffset() ) {
4778 uint32_t entryIndex
= reloc
->r_address() / sizeof(macho_compact_unwind_entry
<P
>);
4779 array
[entryIndex
].functionSymbolIndex
= reloc
->r_symbolnum();
4780 array
[entryIndex
].functionStartAddress
+= parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
4783 warning("unexpected extern relocation in __compact_unwind section");
4787 if ( (reloc
->r_address() % sizeof(macho_compact_unwind_entry
<P
>)) == macho_compact_unwind_entry
<P
>::personalityFieldOffset() ) {
4788 uint32_t entryIndex
= reloc
->r_address() / sizeof(macho_compact_unwind_entry
<P
>);
4789 array
[entryIndex
].personality
= this->personalityName(parser
, reloc
);
4794 // sort array by function start address so unwind infos will be contiguous for a given function
4795 ::qsort(array
, cnt
, sizeof(Info
), infoSorter
);
4798 template <typename A
>
4799 uint32_t CUSection
<A
>::count()
4801 const macho_section
<P
>* machoSect
= this->machoSection();
4802 if ( (machoSect
->size() % sizeof(macho_compact_unwind_entry
<P
>)) != 0 )
4803 throw "malformed __LD,__compact_unwind section, bad length";
4805 return machoSect
->size() / sizeof(macho_compact_unwind_entry
<P
>);
4808 template <typename A
>
4809 void CUSection
<A
>::makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
& cus
)
4811 Info
* const arrayStart
= cus
.cuArray
;
4812 Info
* const arrayEnd
= &cus
.cuArray
[cus
.cuCount
];
4813 for (Info
* info
=arrayStart
; info
< arrayEnd
; ++info
) {
4814 // find function atom from address
4815 info
->function
= parser
.findAtomByAddress(info
->functionStartAddress
);
4816 // find lsda atom from address
4817 if ( info
->lsdaAddress
!= 0 ) {
4818 info
->lsda
= parser
.findAtomByAddress(info
->lsdaAddress
);
4819 // add lsda subordinate
4820 typename Parser
<A
>::SourceLocation
src(info
->function
, info
->functionStartAddress
- info
->function
->objectAddress());
4821 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinateLSDA
, info
->lsda
);
4823 if ( info
->personality
!= NULL
) {
4824 // add personality subordinate
4825 typename Parser
<A
>::SourceLocation
src(info
->function
, info
->functionStartAddress
- info
->function
->objectAddress());
4826 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinatePersonality
, false, info
->personality
);
4832 template <typename A
>
4833 SymboledSection
<A
>::SymboledSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
4834 : Section
<A
>(f
, s
), _type(ld::Atom::typeUnclassified
)
4836 switch ( s
->flags() & SECTION_TYPE
) {
4838 _type
= ld::Atom::typeZeroFill
;
4840 case S_MOD_INIT_FUNC_POINTERS
:
4841 _type
= ld::Atom::typeInitializerPointers
;
4843 case S_MOD_TERM_FUNC_POINTERS
:
4844 _type
= ld::Atom::typeTerminatorPointers
;
4846 case S_THREAD_LOCAL_VARIABLES
:
4847 _type
= ld::Atom::typeTLV
;
4849 case S_THREAD_LOCAL_ZEROFILL
:
4850 _type
= ld::Atom::typeTLVZeroFill
;
4852 case S_THREAD_LOCAL_REGULAR
:
4853 _type
= ld::Atom::typeTLVInitialValue
;
4855 case S_THREAD_LOCAL_INIT_FUNCTION_POINTERS
:
4856 _type
= ld::Atom::typeTLVInitializerPointers
;
4859 if ( strncmp(s
->sectname(), "__gcc_except_tab", 16) == 0 )
4860 _type
= ld::Atom::typeLSDA
;
4861 else if ( this->type() == ld::Section::typeInitializerPointers
)
4862 _type
= ld::Atom::typeInitializerPointers
;
4868 template <typename A
>
4869 bool SymboledSection
<A
>::dontDeadStrip()
4872 case ld::Atom::typeInitializerPointers
:
4873 case ld::Atom::typeTerminatorPointers
:
4876 // model an object file without MH_SUBSECTIONS_VIA_SYMBOLS as one in which nothing can be dead stripped
4877 if ( ! this->_file
.canScatterAtoms() )
4880 return Section
<A
>::dontDeadStrip();
4886 template <typename A
>
4887 uint32_t SymboledSection
<A
>::computeAtomCount(class Parser
<A
>& parser
,
4888 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
4889 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
4891 const pint_t startAddr
= this->_machOSection
->addr();
4892 const pint_t endAddr
= startAddr
+ this->_machOSection
->size();
4893 const uint32_t sectNum
= this->sectionNum(parser
);
4898 const macho_nlist
<P
>* sym
;
4899 while ( it
.next(parser
, *this, sectNum
, startAddr
, endAddr
, &addr
, &size
, &sym
) ) {
4902 //fprintf(stderr, "computeAtomCount(%s,%s) => %d\n", this->segmentName(), this->sectionName(), count);
4906 template <typename A
>
4907 uint32_t SymboledSection
<A
>::appendAtoms(class Parser
<A
>& parser
, uint8_t* p
,
4908 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
4909 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
4911 this->_beginAtoms
= (Atom
<A
>*)p
;
4913 //fprintf(stderr, "SymboledSection::appendAtoms() in section %s\n", this->_machOSection->sectname());
4914 const pint_t startAddr
= this->_machOSection
->addr();
4915 const pint_t endAddr
= startAddr
+ this->_machOSection
->size();
4916 const uint32_t sectNum
= this->sectionNum(parser
);
4921 const macho_nlist
<P
>* label
;
4922 while ( it
.next(parser
, *this, sectNum
, startAddr
, endAddr
, &addr
, &size
, &label
) ) {
4923 Atom
<A
>* allocatedSpace
= (Atom
<A
>*)p
;
4924 // is break because of label or CFI?
4925 if ( label
!= NULL
) {
4926 // The size is computed based on the address of the next label (or the end of the section for the last label)
4927 // If there are two labels at the same address, we want them one to be an alias of the other.
4928 // If the label is at the end of a section, it is has zero size, but is not an alias
4929 const bool isAlias
= ( (size
== 0) && (addr
< endAddr
) );
4930 new (allocatedSpace
) Atom
<A
>(*this, parser
, *label
, size
, isAlias
);
4932 this->_hasAliases
= true;
4933 if ( parser
.altEntryFromSymbol(*label
) )
4934 this->_altEntries
.insert(allocatedSpace
);
4937 ld::Atom::SymbolTableInclusion inclusion
= ld::Atom::symbolTableNotIn
;
4938 ld::Atom::ContentType ctype
= this->contentType();
4939 if ( ctype
== ld::Atom::typeLSDA
)
4940 inclusion
= ld::Atom::symbolTableInWithRandomAutoStripLabel
;
4941 new (allocatedSpace
) Atom
<A
>(*this, "anon", addr
, size
, ld::Atom::definitionRegular
, ld::Atom::combineNever
,
4942 ld::Atom::scopeTranslationUnit
, ctype
, inclusion
,
4943 this->dontDeadStrip(), false, false, this->alignmentForAddress(addr
));
4945 p
+= sizeof(Atom
<A
>);
4949 this->_endAtoms
= (Atom
<A
>*)p
;
4955 ld::Atom::SymbolTableInclusion ImplicitSizeSection
<arm64
>::symbolTableInclusion()
4957 return ld::Atom::symbolTableInWithRandomAutoStripLabel
;
4960 template <typename A
>
4961 ld::Atom::SymbolTableInclusion ImplicitSizeSection
<A
>::symbolTableInclusion()
4963 return ld::Atom::symbolTableNotIn
;
4967 template <typename A
>
4968 uint32_t ImplicitSizeSection
<A
>::computeAtomCount(class Parser
<A
>& parser
,
4969 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
4970 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
4973 const macho_section
<P
>* sect
= this->machoSection();
4974 const pint_t startAddr
= sect
->addr();
4975 const pint_t endAddr
= startAddr
+ sect
->size();
4976 for (pint_t addr
= startAddr
; addr
< endAddr
; addr
+= elementSizeAtAddress(addr
) ) {
4977 if ( useElementAt(parser
, it
, addr
) )
4980 if ( it
.fileHasOverlappingSymbols
&& (sect
->size() != 0) && (this->combine(parser
, startAddr
) == ld::Atom::combineByNameAndContent
) ) {
4981 // if there are multiple labels in this section for the same address, then clone them into multi atoms
4982 pint_t prevSymbolAddr
= (pint_t
)(-1);
4983 uint8_t prevSymbolSectNum
= 0;
4984 bool prevIgnore
= false;
4985 for(uint32_t i
=0; i
< it
.sortedSymbolCount
; ++i
) {
4986 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(it
.sortedSymbolIndexes
[i
]);
4987 const pint_t symbolAddr
= sym
.n_value();
4988 const uint8_t symbolSectNum
= sym
.n_sect();
4989 const bool ignore
= this->ignoreLabel(parser
.nameFromSymbol(sym
));
4990 if ( !ignore
&& !prevIgnore
&& (symbolAddr
== prevSymbolAddr
) && (prevSymbolSectNum
== symbolSectNum
) && (symbolSectNum
== this->sectionNum(parser
)) ) {
4993 prevSymbolAddr
= symbolAddr
;
4994 prevSymbolSectNum
= symbolSectNum
;
4995 prevIgnore
= ignore
;
5001 template <typename A
>
5002 uint32_t ImplicitSizeSection
<A
>::appendAtoms(class Parser
<A
>& parser
, uint8_t* p
,
5003 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
5004 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
5006 this->_beginAtoms
= (Atom
<A
>*)p
;
5008 const macho_section
<P
>* sect
= this->machoSection();
5009 const pint_t startAddr
= sect
->addr();
5010 const pint_t endAddr
= startAddr
+ sect
->size();
5011 const uint32_t sectNum
= this->sectionNum(parser
);
5012 //fprintf(stderr, "ImplicitSizeSection::appendAtoms() in section %s\n", sect->sectname());
5016 const macho_nlist
<P
>* foundLabel
;
5017 Atom
<A
>* allocatedSpace
;
5018 while ( it
.next(parser
, *this, sectNum
, startAddr
, endAddr
, &foundAddr
, &size
, &foundLabel
) ) {
5019 if ( foundLabel
!= NULL
) {
5021 pint_t labeledAtomSize
= this->elementSizeAtAddress(foundAddr
);
5022 allocatedSpace
= (Atom
<A
>*)p
;
5023 if ( this->ignoreLabel(parser
.nameFromSymbol(*foundLabel
)) ) {
5025 // <rdar://problem/10018737>
5026 // a size of zero means there is another label at same location
5027 // and we are supposed to ignore this label
5031 //fprintf(stderr, " 0x%08llX make annon, size=%lld\n", (uint64_t)foundAddr, (uint64_t)size);
5032 new (allocatedSpace
) Atom
<A
>(*this, this->unlabeledAtomName(parser
, foundAddr
), foundAddr
,
5033 this->elementSizeAtAddress(foundAddr
), this->definition(),
5034 this->combine(parser
, foundAddr
), this->scopeAtAddress(parser
, foundAddr
),
5035 this->contentType(), this->symbolTableInclusion(),
5036 this->dontDeadStrip(), false, false, this->alignmentForAddress(foundAddr
));
5040 // make named atom for label
5041 //fprintf(stderr, " 0x%08llX make labeled\n", (uint64_t)foundAddr);
5042 new (allocatedSpace
) Atom
<A
>(*this, parser
, *foundLabel
, labeledAtomSize
);
5046 p
+= sizeof(Atom
<A
>);
5047 foundAddr
+= labeledAtomSize
;
5048 size
-= labeledAtomSize
;
5051 // some number of anonymous atoms
5052 for (pint_t addr
= foundAddr
; addr
< (foundAddr
+size
); addr
+= elementSizeAtAddress(addr
) ) {
5053 // make anon atoms for area before label
5054 if ( this->useElementAt(parser
, it
, addr
) ) {
5055 //fprintf(stderr, " 0x%08llX make annon, size=%lld\n", (uint64_t)addr, (uint64_t)elementSizeAtAddress(addr));
5056 allocatedSpace
= (Atom
<A
>*)p
;
5057 new (allocatedSpace
) Atom
<A
>(*this, this->unlabeledAtomName(parser
, addr
), addr
, this->elementSizeAtAddress(addr
),
5058 this->definition(), this->combine(parser
, addr
), this->scopeAtAddress(parser
, addr
),
5059 this->contentType(), this->symbolTableInclusion(),
5060 this->dontDeadStrip(), false, false, this->alignmentForAddress(addr
));
5062 p
+= sizeof(Atom
<A
>);
5067 this->_endAtoms
= (Atom
<A
>*)p
;
5073 template <typename A
>
5074 unsigned long Literal4Section
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5076 const uint32_t* literalContent
= (uint32_t*)atom
->contentPointer();
5077 return *literalContent
;
5080 template <typename A
>
5081 bool Literal4Section
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5082 const ld::IndirectBindingTable
& ind
) const
5084 assert(this->type() == rhs
.section().type());
5085 const uint32_t* literalContent
= (uint32_t*)atom
->contentPointer();
5087 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5088 assert(rhsAtom
!= NULL
);
5089 if ( rhsAtom
!= NULL
) {
5090 const uint32_t* rhsLiteralContent
= (uint32_t*)rhsAtom
->contentPointer();
5091 return (*literalContent
== *rhsLiteralContent
);
5097 template <typename A
>
5098 unsigned long Literal8Section
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5101 const uint64_t* literalContent
= (uint64_t*)atom
->contentPointer();
5102 return *literalContent
;
5104 unsigned long hash
= 5381;
5105 const uint8_t* byteContent
= atom
->contentPointer();
5106 for (int i
=0; i
< 8; ++i
) {
5107 hash
= hash
* 33 + byteContent
[i
];
5113 template <typename A
>
5114 bool Literal8Section
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5115 const ld::IndirectBindingTable
& ind
) const
5117 if ( rhs
.section().type() != ld::Section::typeLiteral8
)
5119 assert(this->type() == rhs
.section().type());
5120 const uint64_t* literalContent
= (uint64_t*)atom
->contentPointer();
5122 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5123 assert(rhsAtom
!= NULL
);
5124 if ( rhsAtom
!= NULL
) {
5125 const uint64_t* rhsLiteralContent
= (uint64_t*)rhsAtom
->contentPointer();
5126 return (*literalContent
== *rhsLiteralContent
);
5132 template <typename A
>
5133 unsigned long Literal16Section
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5135 unsigned long hash
= 5381;
5136 const uint8_t* byteContent
= atom
->contentPointer();
5137 for (int i
=0; i
< 16; ++i
) {
5138 hash
= hash
* 33 + byteContent
[i
];
5143 template <typename A
>
5144 bool Literal16Section
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5145 const ld::IndirectBindingTable
& ind
) const
5147 if ( rhs
.section().type() != ld::Section::typeLiteral16
)
5149 assert(this->type() == rhs
.section().type());
5150 const uint64_t* literalContent
= (uint64_t*)atom
->contentPointer();
5152 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5153 assert(rhsAtom
!= NULL
);
5154 if ( rhsAtom
!= NULL
) {
5155 const uint64_t* rhsLiteralContent
= (uint64_t*)rhsAtom
->contentPointer();
5156 return ((literalContent
[0] == rhsLiteralContent
[0]) && (literalContent
[1] == rhsLiteralContent
[1]));
5163 template <typename A
>
5164 typename
A::P::uint_t CStringSection
<A
>::elementSizeAtAddress(pint_t addr
)
5166 const macho_section
<P
>* sect
= this->machoSection();
5167 const char* stringContent
= (char*)(this->file().fileContent() + sect
->offset() + addr
- sect
->addr());
5168 return strlen(stringContent
) + 1;
5171 template <typename A
>
5172 bool CStringSection
<A
>::useElementAt(Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, pint_t addr
)
5177 template <typename A
>
5178 bool CStringSection
<A
>::ignoreLabel(const char* label
) const
5180 return (label
[0] == 'L') || (label
[0] == 'l');
5184 template <typename A
>
5185 Atom
<A
>* CStringSection
<A
>::findAtomByAddress(pint_t addr
)
5187 Atom
<A
>* result
= this->findContentAtomByAddress(addr
, this->_beginAtoms
, this->_endAtoms
);
5191 template <typename A
>
5192 unsigned long CStringSection
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5194 unsigned long hash
= 5381;
5195 const char* stringContent
= (char*)atom
->contentPointer();
5196 for (const char* s
= stringContent
; *s
!= '\0'; ++s
) {
5197 hash
= hash
* 33 + *s
;
5203 template <typename A
>
5204 bool CStringSection
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5205 const ld::IndirectBindingTable
& ind
) const
5207 if ( rhs
.section().type() != ld::Section::typeCString
)
5209 assert(this->type() == rhs
.section().type());
5210 assert(strcmp(this->sectionName(), rhs
.section().sectionName())== 0);
5211 assert(strcmp(this->segmentName(), rhs
.section().segmentName())== 0);
5212 const char* stringContent
= (char*)atom
->contentPointer();
5214 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5215 assert(rhsAtom
!= NULL
);
5216 if ( rhsAtom
!= NULL
) {
5217 if ( atom
->_size
!= rhsAtom
->_size
)
5219 const char* rhsStringContent
= (char*)rhsAtom
->contentPointer();
5220 return (strcmp(stringContent
, rhsStringContent
) == 0);
5227 ld::Fixup::Kind NonLazyPointerSection
<x86
>::fixupKind()
5229 return ld::Fixup::kindStoreLittleEndian32
;
5233 ld::Fixup::Kind NonLazyPointerSection
<arm
>::fixupKind()
5235 return ld::Fixup::kindStoreLittleEndian32
;
5239 ld::Fixup::Kind NonLazyPointerSection
<arm64
>::fixupKind()
5241 return ld::Fixup::kindStoreLittleEndian64
;
5246 void NonLazyPointerSection
<x86_64
>::makeFixups(class Parser
<x86_64
>& parser
, const struct Parser
<x86_64
>::CFI_CU_InfoArrays
&)
5248 assert(0 && "x86_64 should not have non-lazy-pointer sections in .o files");
5251 template <typename A
>
5252 void NonLazyPointerSection
<A
>::makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&)
5254 // add references for each NLP atom based on indirect symbol table
5255 const macho_section
<P
>* sect
= this->machoSection();
5256 const pint_t endAddr
= sect
->addr() + sect
->size();
5257 for( pint_t addr
= sect
->addr(); addr
< endAddr
; addr
+= sizeof(pint_t
)) {
5258 typename Parser
<A
>::SourceLocation src
;
5259 typename Parser
<A
>::TargetDesc target
;
5260 src
.atom
= this->findAtomByAddress(addr
);
5261 src
.offsetInAtom
= 0;
5262 uint32_t symIndex
= parser
.symbolIndexFromIndirectSectionAddress(addr
, sect
);
5265 target
.weakImport
= false;
5267 if ( symIndex
== INDIRECT_SYMBOL_LOCAL
) {
5268 // use direct reference for local symbols
5269 const pint_t
* nlpContent
= (pint_t
*)(this->file().fileContent() + sect
->offset() + addr
- sect
->addr());
5270 pint_t targetAddr
= P::getP(*nlpContent
);
5271 target
.atom
= parser
.findAtomByAddress(targetAddr
);
5272 target
.weakImport
= false;
5273 target
.addend
= (targetAddr
- target
.atom
->objectAddress());
5274 // <rdar://problem/8385011> if pointer to thumb function, mask of thumb bit (not an addend of +1)
5275 if ( target
.atom
->isThumb() )
5276 target
.addend
&= (-2);
5277 assert(src
.atom
->combine() == ld::Atom::combineNever
);
5280 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(symIndex
);
5281 // use direct reference for local symbols
5282 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && ((sym
.n_type() & N_EXT
) == 0) ) {
5283 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
5284 assert(src
.atom
->combine() == ld::Atom::combineNever
);
5287 target
.name
= parser
.nameFromSymbol(sym
);
5288 target
.weakImport
= parser
.weakImportFromSymbol(sym
);
5289 assert(src
.atom
->combine() == ld::Atom::combineByNameAndReferences
);
5292 parser
.addFixups(src
, this->fixupKind(), target
);
5296 template <typename A
>
5297 ld::Atom::Combine NonLazyPointerSection
<A
>::combine(Parser
<A
>& parser
, pint_t addr
)
5299 const macho_section
<P
>* sect
= this->machoSection();
5300 uint32_t symIndex
= parser
.symbolIndexFromIndirectSectionAddress(addr
, sect
);
5301 if ( symIndex
== INDIRECT_SYMBOL_LOCAL
)
5302 return ld::Atom::combineNever
;
5304 // don't coalesce non-lazy-pointers to local symbols
5305 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(symIndex
);
5306 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && ((sym
.n_type() & N_EXT
) == 0) )
5307 return ld::Atom::combineNever
;
5309 return ld::Atom::combineByNameAndReferences
;
5312 template <typename A
>
5313 const char* NonLazyPointerSection
<A
>::targetName(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
)
5315 assert(atom
->combine() == ld::Atom::combineByNameAndReferences
);
5316 assert(atom
->fixupCount() == 1);
5317 ld::Fixup::iterator fit
= atom
->fixupsBegin();
5318 const char* name
= NULL
;
5319 switch ( fit
->binding
) {
5320 case ld::Fixup::bindingByNameUnbound
:
5323 case ld::Fixup::bindingByContentBound
:
5324 name
= fit
->u
.target
->name();
5326 case ld::Fixup::bindingsIndirectlyBound
:
5327 name
= ind
.indirectName(fit
->u
.bindingIndex
);
5332 assert(name
!= NULL
);
5336 template <typename A
>
5337 unsigned long NonLazyPointerSection
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5339 assert(atom
->combine() == ld::Atom::combineByNameAndReferences
);
5340 unsigned long hash
= 9508;
5341 for (const char* s
= this->targetName(atom
, ind
); *s
!= '\0'; ++s
) {
5342 hash
= hash
* 33 + *s
;
5347 template <typename A
>
5348 bool NonLazyPointerSection
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5349 const ld::IndirectBindingTable
& indirectBindingTable
) const
5351 if ( rhs
.section().type() != ld::Section::typeNonLazyPointer
)
5353 assert(this->type() == rhs
.section().type());
5354 // there can be many non-lazy pointer in different section names
5355 // we only want to coalesce in same section name
5356 if ( *this != rhs
.section() )
5358 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5359 assert(rhsAtom
!= NULL
);
5360 const char* thisName
= this->targetName(atom
, indirectBindingTable
);
5361 const char* rhsName
= this->targetName(rhsAtom
, indirectBindingTable
);
5362 return (strcmp(thisName
, rhsName
) == 0);
5365 template <typename A
>
5366 ld::Atom::Scope NonLazyPointerSection
<A
>::scopeAtAddress(Parser
<A
>& parser
, pint_t addr
)
5368 const macho_section
<P
>* sect
= this->machoSection();
5369 uint32_t symIndex
= parser
.symbolIndexFromIndirectSectionAddress(addr
, sect
);
5370 if ( symIndex
== INDIRECT_SYMBOL_LOCAL
)
5371 return ld::Atom::scopeTranslationUnit
;
5373 return ld::Atom::scopeLinkageUnit
;
5377 template <typename A
>
5378 const uint8_t* CFStringSection
<A
>::targetContent(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
,
5379 ContentType
* ct
, unsigned int* count
)
5381 *ct
= contentUnknown
;
5382 for (ld::Fixup::iterator fit
=atom
->fixupsBegin(), end
=atom
->fixupsEnd(); fit
!= end
; ++fit
) {
5383 const ld::Atom
* targetAtom
= NULL
;
5384 switch ( fit
->binding
) {
5385 case ld::Fixup::bindingByNameUnbound
:
5386 // ignore reference to ___CFConstantStringClassReference
5387 // we are just looking for reference to backing string data
5388 assert(fit
->offsetInAtom
== 0);
5389 assert(strcmp(fit
->u
.name
, "___CFConstantStringClassReference") == 0);
5391 case ld::Fixup::bindingDirectlyBound
:
5392 case ld::Fixup::bindingByContentBound
:
5393 targetAtom
= fit
->u
.target
;
5395 case ld::Fixup::bindingsIndirectlyBound
:
5396 targetAtom
= ind
.indirectAtom(fit
->u
.bindingIndex
);
5399 assert(0 && "bad binding type");
5401 assert(targetAtom
!= NULL
);
5402 const Atom
<A
>* target
= dynamic_cast<const Atom
<A
>*>(targetAtom
);
5403 if ( targetAtom
->section().type() == ld::Section::typeCString
) {
5405 *count
= targetAtom
->size();
5407 else if ( targetAtom
->section().type() == ld::Section::typeUTF16Strings
) {
5409 *count
= (targetAtom
->size()+1)/2; // round up incase of buggy compiler that has only one trailing zero byte
5412 *ct
= contentUnknown
;
5416 return target
->contentPointer();
5422 template <typename A
>
5423 unsigned long CFStringSection
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5425 // base hash of CFString on hash of cstring it wraps
5428 unsigned int charCount
;
5429 const uint8_t* content
= this->targetContent(atom
, ind
, &cType
, &charCount
);
5433 for (const char* s
= (char*)content
; *s
!= '\0'; ++s
) {
5434 hash
= hash
* 33 + *s
;
5439 --charCount
; // don't add last 0x0000 to hash because some buggy compilers only have trailing single byte
5440 for (const uint16_t* s
= (uint16_t*)content
; charCount
> 0; ++s
, --charCount
) {
5441 hash
= hash
* 1025 + *s
;
5444 case contentUnknown
:
5445 // <rdar://problem/14134211> For malformed CFStrings, hash to address of atom so they have unique hashes
5446 return ULONG_MAX
- (unsigned long)(atom
);
5452 template <typename A
>
5453 bool CFStringSection
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5454 const ld::IndirectBindingTable
& indirectBindingTable
) const
5458 if ( rhs
.section().type() != ld::Section::typeCFString
)
5460 assert(this->type() == rhs
.section().type());
5461 assert(strcmp(this->sectionName(), "__cfstring") == 0);
5463 ContentType thisType
;
5464 unsigned int charCount
;
5465 const uint8_t* cstringContent
= this->targetContent(atom
, indirectBindingTable
, &thisType
, &charCount
);
5466 ContentType rhsType
;
5467 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5468 assert(rhsAtom
!= NULL
);
5469 unsigned int rhsCharCount
;
5470 const uint8_t* rhsStringContent
= this->targetContent(rhsAtom
, indirectBindingTable
, &rhsType
, &rhsCharCount
);
5472 if ( thisType
!= rhsType
)
5475 if ( thisType
== contentUnknown
)
5478 if ( rhsType
== contentUnknown
)
5481 // no need to compare content of pointers are already the same
5482 if ( cstringContent
== rhsStringContent
)
5485 // no need to compare content if size is different
5486 if ( charCount
!= rhsCharCount
)
5489 switch ( thisType
) {
5491 return (strcmp((char*)cstringContent
, (char*)rhsStringContent
) == 0);
5494 const uint16_t* cstringContent16
= (uint16_t*)cstringContent
;
5495 const uint16_t* rhsStringContent16
= (uint16_t*)rhsStringContent
;
5496 for (unsigned int i
= 0; i
< charCount
; ++i
) {
5497 if ( cstringContent16
[i
] != rhsStringContent16
[i
] )
5502 case contentUnknown
:
5509 template <typename A
>
5510 typename
A::P::uint_t ObjC1ClassSection
<A
>::elementSizeAtAddress(pint_t addr
)
5512 // nominal size for each class is 48 bytes, but sometimes the compiler
5513 // over aligns and there is padding after class data
5514 const macho_section
<P
>* sct
= this->machoSection();
5515 uint32_t align
= 1 << sct
->align();
5516 uint32_t size
= ((12 * sizeof(pint_t
)) + align
-1) & (-align
);
5520 template <typename A
>
5521 const char* ObjC1ClassSection
<A
>::unlabeledAtomName(Parser
<A
>& parser
, pint_t addr
)
5523 // 8-bytes into class object is pointer to class name
5524 const macho_section
<P
>* sct
= this->machoSection();
5525 uint32_t classObjcFileOffset
= sct
->offset() - sct
->addr() + addr
;
5526 const uint8_t* mappedFileContent
= this->file().fileContent();
5527 pint_t nameAddr
= P::getP(*((pint_t
*)(mappedFileContent
+classObjcFileOffset
+2*sizeof(pint_t
))));
5529 // find section containing string address to get string bytes
5530 const macho_section
<P
>* const sections
= parser
.firstMachOSection();
5531 const uint32_t sectionCount
= parser
.machOSectionCount();
5532 for (uint32_t i
=0; i
< sectionCount
; ++i
) {
5533 const macho_section
<P
>* aSect
= §ions
[i
];
5534 if ( (aSect
->addr() <= nameAddr
) && (nameAddr
< (aSect
->addr()+aSect
->size())) ) {
5535 assert((aSect
->flags() & SECTION_TYPE
) == S_CSTRING_LITERALS
);
5536 uint32_t nameFileOffset
= aSect
->offset() - aSect
->addr() + nameAddr
;
5537 const char* name
= (char*)mappedFileContent
+ nameFileOffset
;
5538 // spin through symbol table to find absolute symbol corresponding to this class
5539 for (uint32_t s
=0; s
< parser
.symbolCount(); ++s
) {
5540 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(s
);
5541 if ( (sym
.n_type() & N_TYPE
) != N_ABS
)
5543 const char* absName
= parser
.nameFromSymbol(sym
);
5544 if ( strncmp(absName
, ".objc_class_name_", 17) == 0 ) {
5545 if ( strcmp(&absName
[17], name
) == 0 )
5549 assert(0 && "obj class name not found in symbol table");
5552 assert(0 && "obj class name not found");
5553 return "unknown objc class";
5557 template <typename A
>
5558 const char* ObjC2ClassRefsSection
<A
>::targetClassName(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5560 assert(atom
->fixupCount() == 1);
5561 ld::Fixup::iterator fit
= atom
->fixupsBegin();
5562 const char* className
= NULL
;
5563 switch ( fit
->binding
) {
5564 case ld::Fixup::bindingByNameUnbound
:
5565 className
= fit
->u
.name
;
5567 case ld::Fixup::bindingDirectlyBound
:
5568 case ld::Fixup::bindingByContentBound
:
5569 className
= fit
->u
.target
->name();
5571 case ld::Fixup::bindingsIndirectlyBound
:
5572 className
= ind
.indirectName(fit
->u
.bindingIndex
);
5575 assert(0 && "unsupported binding in objc2 class ref section");
5577 assert(className
!= NULL
);
5582 template <typename A
>
5583 unsigned long ObjC2ClassRefsSection
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5585 unsigned long hash
= 978;
5586 for (const char* s
= targetClassName(atom
, ind
); *s
!= '\0'; ++s
) {
5587 hash
= hash
* 33 + *s
;
5592 template <typename A
>
5593 bool ObjC2ClassRefsSection
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5594 const ld::IndirectBindingTable
& indirectBindingTable
) const
5596 assert(this->type() == rhs
.section().type());
5597 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5598 assert(rhsAtom
!= NULL
);
5599 const char* thisClassName
= targetClassName(atom
, indirectBindingTable
);
5600 const char* rhsClassName
= targetClassName(rhsAtom
, indirectBindingTable
);
5601 return (strcmp(thisClassName
, rhsClassName
) == 0);
5605 template <typename A
>
5606 const char* Objc1ClassReferences
<A
>::targetCString(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5608 assert(atom
->fixupCount() == 2);
5609 ld::Fixup::iterator fit
= atom
->fixupsBegin();
5610 if ( fit
->kind
== ld::Fixup::kindSetTargetAddress
)
5612 const ld::Atom
* targetAtom
= NULL
;
5613 switch ( fit
->binding
) {
5614 case ld::Fixup::bindingByContentBound
:
5615 targetAtom
= fit
->u
.target
;
5617 case ld::Fixup::bindingsIndirectlyBound
:
5618 targetAtom
= ind
.indirectAtom(fit
->u
.bindingIndex
);
5619 if ( targetAtom
== NULL
) {
5620 fprintf(stderr
, "missing target named %s\n", ind
.indirectName(fit
->u
.bindingIndex
));
5626 assert(targetAtom
!= NULL
);
5627 const Atom
<A
>* target
= dynamic_cast<const Atom
<A
>*>(targetAtom
);
5628 assert(target
!= NULL
);
5629 return (char*)target
->contentPointer();
5633 template <typename A
>
5634 const char* PointerToCStringSection
<A
>::targetCString(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5636 assert(atom
->fixupCount() == 1);
5637 ld::Fixup::iterator fit
= atom
->fixupsBegin();
5638 const ld::Atom
* targetAtom
= NULL
;
5639 switch ( fit
->binding
) {
5640 case ld::Fixup::bindingByContentBound
:
5641 targetAtom
= fit
->u
.target
;
5643 case ld::Fixup::bindingsIndirectlyBound
:
5644 targetAtom
= ind
.indirectAtom(fit
->u
.bindingIndex
);
5646 case ld::Fixup::bindingDirectlyBound
:
5647 targetAtom
= fit
->u
.target
;
5650 assert(0 && "unsupported reference to selector");
5652 assert(targetAtom
!= NULL
);
5653 const Atom
<A
>* target
= dynamic_cast<const Atom
<A
>*>(targetAtom
);
5654 assert(target
!= NULL
);
5655 assert(target
->contentType() == ld::Atom::typeCString
);
5656 return (char*)target
->contentPointer();
5659 template <typename A
>
5660 unsigned long PointerToCStringSection
<A
>::contentHash(const class Atom
<A
>* atom
,
5661 const ld::IndirectBindingTable
& indirectBindingTable
) const
5663 // make hash from section name and target cstring name
5664 unsigned long hash
= 123;
5665 for (const char* s
= this->sectionName(); *s
!= '\0'; ++s
) {
5666 hash
= hash
* 33 + *s
;
5668 for (const char* s
= this->targetCString(atom
, indirectBindingTable
); *s
!= '\0'; ++s
) {
5669 hash
= hash
* 33 + *s
;
5674 template <typename A
>
5675 bool PointerToCStringSection
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5676 const ld::IndirectBindingTable
& indirectBindingTable
) const
5678 assert(this->type() == rhs
.section().type());
5679 // there can be pointers-to-cstrings in different section names
5680 // we only want to coalesce in same section name
5681 if ( *this != rhs
.section() )
5684 // get string content for this
5685 const char* cstringContent
= this->targetCString(atom
, indirectBindingTable
);
5686 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5687 assert(rhsAtom
!= NULL
);
5688 const char* rhsCstringContent
= this->targetCString(rhsAtom
, indirectBindingTable
);
5690 assert(cstringContent
!= NULL
);
5691 assert(rhsCstringContent
!= NULL
);
5692 return (strcmp(cstringContent
, rhsCstringContent
) == 0);
5697 template <typename A
>
5698 unsigned long UTF16StringSection
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5700 unsigned long hash
= 5381;
5701 const uint16_t* stringContent
= (uint16_t*)atom
->contentPointer();
5702 // some buggy compilers end utf16 data with single byte, so don't use last word in hash computation
5703 unsigned int count
= (atom
->size()/2) - 1;
5704 for (const uint16_t* s
= stringContent
; count
> 0; ++s
, --count
) {
5705 hash
= hash
* 33 + *s
;
5710 template <typename A
>
5711 bool UTF16StringSection
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5712 const ld::IndirectBindingTable
& ind
) const
5714 if ( rhs
.section().type() != ld::Section::typeUTF16Strings
)
5727 uint32_t Section
<x86_64
>::x86_64PcRelOffset(uint8_t r_type
)
5730 case X86_64_RELOC_SIGNED
:
5732 case X86_64_RELOC_SIGNED_1
:
5734 case X86_64_RELOC_SIGNED_2
:
5736 case X86_64_RELOC_SIGNED_4
:
5744 bool Section
<x86_64
>::addRelocFixup(class Parser
<x86_64
>& parser
, const macho_relocation_info
<P
>* reloc
)
5746 const macho_section
<P
>* sect
= this->machoSection();
5747 uint64_t srcAddr
= sect
->addr() + reloc
->r_address();
5748 Parser
<x86_64
>::SourceLocation src
;
5749 Parser
<x86_64
>::TargetDesc target
;
5750 Parser
<x86_64
>::TargetDesc toTarget
;
5751 src
.atom
= this->findAtomByAddress(srcAddr
);
5752 src
.offsetInAtom
= srcAddr
- src
.atom
->_objAddress
;
5753 const uint8_t* fixUpPtr
= file().fileContent() + sect
->offset() + reloc
->r_address();
5754 uint64_t contentValue
= 0;
5755 const macho_relocation_info
<x86_64::P
>* nextReloc
= &reloc
[1];
5756 bool result
= false;
5757 bool useDirectBinding
;
5758 switch ( reloc
->r_length() ) {
5760 contentValue
= *fixUpPtr
;
5763 contentValue
= (int64_t)(int16_t)E::get16(*((uint16_t*)fixUpPtr
));
5766 contentValue
= (int64_t)(int32_t)E::get32(*((uint32_t*)fixUpPtr
));
5769 contentValue
= E::get64(*((uint64_t*)fixUpPtr
));
5774 target
.weakImport
= false;
5776 if ( reloc
->r_extern() ) {
5777 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
5778 // use direct reference for local symbols
5779 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && (((sym
.n_type() & N_EXT
) == 0) || (parser
.nameFromSymbol(sym
)[0] == 'L')) ) {
5780 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
5781 target
.addend
+= contentValue
;
5784 target
.name
= parser
.nameFromSymbol(sym
);
5785 target
.weakImport
= parser
.weakImportFromSymbol(sym
);
5786 target
.addend
= contentValue
;
5788 // cfstrings should always use direct reference to backing store
5789 if ( (this->type() == ld::Section::typeCFString
) && (src
.offsetInAtom
!= 0) ) {
5790 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
5791 target
.addend
= contentValue
;
5795 if ( reloc
->r_pcrel() )
5796 contentValue
+= srcAddr
+ x86_64PcRelOffset(reloc
->r_type());
5797 parser
.findTargetFromAddressAndSectionNum(contentValue
, reloc
->r_symbolnum(), target
);
5799 switch ( reloc
->r_type() ) {
5800 case X86_64_RELOC_UNSIGNED
:
5801 if ( reloc
->r_pcrel() )
5802 throw "pcrel and X86_64_RELOC_UNSIGNED not supported";
5803 switch ( reloc
->r_length() ) {
5806 throw "length < 2 and X86_64_RELOC_UNSIGNED not supported";
5808 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian32
, target
);
5811 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian64
, target
);
5815 case X86_64_RELOC_SIGNED
:
5816 case X86_64_RELOC_SIGNED_1
:
5817 case X86_64_RELOC_SIGNED_2
:
5818 case X86_64_RELOC_SIGNED_4
:
5819 if ( ! reloc
->r_pcrel() )
5820 throw "not pcrel and X86_64_RELOC_SIGNED* not supported";
5821 if ( reloc
->r_length() != 2 )
5822 throw "length != 2 and X86_64_RELOC_SIGNED* not supported";
5823 switch ( reloc
->r_type() ) {
5824 case X86_64_RELOC_SIGNED
:
5825 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32
, target
);
5827 case X86_64_RELOC_SIGNED_1
:
5828 if ( reloc
->r_extern() )
5830 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32_1
, target
);
5832 case X86_64_RELOC_SIGNED_2
:
5833 if ( reloc
->r_extern() )
5835 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32_2
, target
);
5837 case X86_64_RELOC_SIGNED_4
:
5838 if ( reloc
->r_extern() )
5840 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32_4
, target
);
5844 case X86_64_RELOC_BRANCH
:
5845 if ( ! reloc
->r_pcrel() )
5846 throw "not pcrel and X86_64_RELOC_BRANCH not supported";
5847 switch ( reloc
->r_length() ) {
5849 if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_probe$", 16) == 0) ) {
5850 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindStoreX86DtraceCallSiteNop
, false, target
.name
);
5851 parser
.addDtraceExtraInfos(src
, &target
.name
[16]);
5853 else if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_isenabled$", 20) == 0) ) {
5854 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindStoreX86DtraceIsEnableSiteClear
, false, target
.name
);
5855 parser
.addDtraceExtraInfos(src
, &target
.name
[20]);
5858 parser
.addFixups(src
, ld::Fixup::kindStoreX86BranchPCRel32
, target
);
5862 parser
.addFixups(src
, ld::Fixup::kindStoreX86BranchPCRel8
, target
);
5865 throwf("length=%d and X86_64_RELOC_BRANCH not supported", reloc
->r_length());
5868 case X86_64_RELOC_GOT
:
5869 if ( ! reloc
->r_extern() )
5870 throw "not extern and X86_64_RELOC_GOT not supported";
5871 if ( ! reloc
->r_pcrel() )
5872 throw "not pcrel and X86_64_RELOC_GOT not supported";
5873 if ( reloc
->r_length() != 2 )
5874 throw "length != 2 and X86_64_RELOC_GOT not supported";
5875 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32GOT
, target
);
5877 case X86_64_RELOC_GOT_LOAD
:
5878 if ( ! reloc
->r_extern() )
5879 throw "not extern and X86_64_RELOC_GOT_LOAD not supported";
5880 if ( ! reloc
->r_pcrel() )
5881 throw "not pcrel and X86_64_RELOC_GOT_LOAD not supported";
5882 if ( reloc
->r_length() != 2 )
5883 throw "length != 2 and X86_64_RELOC_GOT_LOAD not supported";
5884 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32GOTLoad
, target
);
5886 case X86_64_RELOC_SUBTRACTOR
:
5887 if ( reloc
->r_pcrel() )
5888 throw "X86_64_RELOC_SUBTRACTOR cannot be pc-relative";
5889 if ( reloc
->r_length() < 2 )
5890 throw "X86_64_RELOC_SUBTRACTOR must have r_length of 2 or 3";
5891 if ( !reloc
->r_extern() )
5892 throw "X86_64_RELOC_SUBTRACTOR must have r_extern=1";
5893 if ( nextReloc
->r_type() != X86_64_RELOC_UNSIGNED
)
5894 throw "X86_64_RELOC_SUBTRACTOR must be followed by X86_64_RELOC_UNSIGNED";
5896 if ( nextReloc
->r_pcrel() )
5897 throw "X86_64_RELOC_UNSIGNED following a X86_64_RELOC_SUBTRACTOR cannot be pc-relative";
5898 if ( nextReloc
->r_length() != reloc
->r_length() )
5899 throw "X86_64_RELOC_UNSIGNED following a X86_64_RELOC_SUBTRACTOR must have same r_length";
5900 if ( nextReloc
->r_extern() ) {
5901 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(nextReloc
->r_symbolnum());
5902 // use direct reference for local symbols
5903 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && (((sym
.n_type() & N_EXT
) == 0) || (parser
.nameFromSymbol(sym
)[0] == 'L')) ) {
5904 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), toTarget
);
5905 toTarget
.addend
= contentValue
;
5906 useDirectBinding
= true;
5909 toTarget
.name
= parser
.nameFromSymbol(sym
);
5910 toTarget
.weakImport
= parser
.weakImportFromSymbol(sym
);
5911 toTarget
.addend
= contentValue
;
5912 useDirectBinding
= false;
5916 parser
.findTargetFromAddressAndSectionNum(contentValue
, nextReloc
->r_symbolnum(), toTarget
);
5917 useDirectBinding
= (toTarget
.atom
->scope() == ld::Atom::scopeTranslationUnit
);
5919 if ( useDirectBinding
)
5920 parser
.addFixup(src
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, toTarget
.atom
);
5922 parser
.addFixup(src
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, toTarget
.weakImport
, toTarget
.name
);
5923 parser
.addFixup(src
, ld::Fixup::k2of4
, ld::Fixup::kindAddAddend
, toTarget
.addend
);
5924 if ( target
.atom
== NULL
)
5925 parser
.addFixup(src
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractTargetAddress
, false, target
.name
);
5927 parser
.addFixup(src
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractTargetAddress
, target
.atom
);
5928 if ( reloc
->r_length() == 2 )
5929 parser
.addFixup(src
, ld::Fixup::k4of4
, ld::Fixup::kindStoreLittleEndian32
);
5931 parser
.addFixup(src
, ld::Fixup::k4of4
, ld::Fixup::kindStoreLittleEndian64
);
5933 case X86_64_RELOC_TLV
:
5934 if ( ! reloc
->r_extern() )
5935 throw "not extern and X86_64_RELOC_TLV not supported";
5936 if ( ! reloc
->r_pcrel() )
5937 throw "not pcrel and X86_64_RELOC_TLV not supported";
5938 if ( reloc
->r_length() != 2 )
5939 throw "length != 2 and X86_64_RELOC_TLV not supported";
5940 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32TLVLoad
, target
);
5943 throwf("unknown relocation type %d", reloc
->r_type());
5951 bool Section
<x86
>::addRelocFixup(class Parser
<x86
>& parser
, const macho_relocation_info
<P
>* reloc
)
5953 const macho_section
<P
>* sect
= this->machoSection();
5955 const uint8_t* fixUpPtr
;
5956 uint32_t contentValue
= 0;
5957 ld::Fixup::Kind kind
= ld::Fixup::kindNone
;
5958 Parser
<x86
>::SourceLocation src
;
5959 Parser
<x86
>::TargetDesc target
;
5961 if ( (reloc
->r_address() & R_SCATTERED
) == 0 ) {
5962 srcAddr
= sect
->addr() + reloc
->r_address();
5963 src
.atom
= this->findAtomByAddress(srcAddr
);
5964 src
.offsetInAtom
= srcAddr
- src
.atom
->_objAddress
;
5965 fixUpPtr
= file().fileContent() + sect
->offset() + reloc
->r_address();
5966 switch ( reloc
->r_type() ) {
5967 case GENERIC_RELOC_VANILLA
:
5968 switch ( reloc
->r_length() ) {
5970 contentValue
= (int32_t)(int8_t)*fixUpPtr
;
5971 if ( reloc
->r_pcrel() ) {
5972 kind
= ld::Fixup::kindStoreX86BranchPCRel8
;
5973 contentValue
+= srcAddr
+ sizeof(uint8_t);
5976 throw "r_length=0 and r_pcrel=0 not supported";
5979 contentValue
= (int32_t)(int16_t)E::get16(*((uint16_t*)fixUpPtr
));
5980 if ( reloc
->r_pcrel() ) {
5981 kind
= ld::Fixup::kindStoreX86PCRel16
;
5982 contentValue
+= srcAddr
+ sizeof(uint16_t);
5985 kind
= ld::Fixup::kindStoreLittleEndian16
;
5988 contentValue
= E::get32(*((uint32_t*)fixUpPtr
));
5989 if ( reloc
->r_pcrel() ) {
5990 kind
= ld::Fixup::kindStoreX86BranchPCRel32
;
5991 contentValue
+= srcAddr
+ sizeof(uint32_t);
5994 kind
= ld::Fixup::kindStoreLittleEndian32
;
5997 throw "r_length=3 not supported";
5999 if ( reloc
->r_extern() ) {
6001 const macho_nlist
<P
>& targetSymbol
= parser
.symbolFromIndex(reloc
->r_symbolnum());
6002 target
.name
= parser
.nameFromSymbol(targetSymbol
);
6003 target
.weakImport
= parser
.weakImportFromSymbol(targetSymbol
);
6004 target
.addend
= (int32_t)contentValue
;
6007 parser
.findTargetFromAddressAndSectionNum(contentValue
, reloc
->r_symbolnum(), target
);
6009 if ( (kind
== ld::Fixup::kindStoreX86BranchPCRel32
) && (target
.name
!= NULL
) ) {
6010 if ( strncmp(target
.name
, "___dtrace_probe$", 16) == 0 ) {
6011 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindStoreX86DtraceCallSiteNop
, false, target
.name
);
6012 parser
.addDtraceExtraInfos(src
, &target
.name
[16]);
6015 else if ( strncmp(target
.name
, "___dtrace_isenabled$", 20) == 0 ) {
6016 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindStoreX86DtraceIsEnableSiteClear
, false, target
.name
);
6017 parser
.addDtraceExtraInfos(src
, &target
.name
[20]);
6021 parser
.addFixups(src
, kind
, target
);
6024 case GENERIC_RLEOC_TLV
:
6026 if ( !reloc
->r_extern() )
6027 throw "r_extern=0 and r_type=GENERIC_RLEOC_TLV not supported";
6028 if ( reloc
->r_length() != 2 )
6029 throw "r_length!=2 and r_type=GENERIC_RLEOC_TLV not supported";
6030 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
6031 // use direct reference for local symbols
6032 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && ((sym
.n_type() & N_EXT
) == 0) ) {
6033 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
6037 target
.name
= parser
.nameFromSymbol(sym
);
6038 target
.weakImport
= parser
.weakImportFromSymbol(sym
);
6040 target
.addend
= (int64_t)(int32_t)E::get32(*((uint32_t*)fixUpPtr
));
6041 if ( reloc
->r_pcrel() ) {
6042 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32TLVLoad
, target
);
6045 parser
.addFixups(src
, ld::Fixup::kindStoreX86Abs32TLVLoad
, target
);
6051 throwf("unsupported i386 relocation type (%d)", reloc
->r_type());
6055 // scattered relocation
6056 const macho_scattered_relocation_info
<P
>* sreloc
= (macho_scattered_relocation_info
<P
>*)reloc
;
6057 srcAddr
= sect
->addr() + sreloc
->r_address();
6058 src
.atom
= this->findAtomByAddress(srcAddr
);
6059 assert(src
.atom
!= NULL
);
6060 src
.offsetInAtom
= srcAddr
- src
.atom
->_objAddress
;
6061 fixUpPtr
= file().fileContent() + sect
->offset() + sreloc
->r_address();
6062 uint32_t relocValue
= sreloc
->r_value();
6063 bool result
= false;
6064 // file format allows pair to be scattered or not
6065 const macho_scattered_relocation_info
<P
>* nextSReloc
= &sreloc
[1];
6066 const macho_relocation_info
<P
>* nextReloc
= &reloc
[1];
6067 bool nextRelocIsPair
= false;
6068 uint32_t nextRelocAddress
= 0;
6069 uint32_t nextRelocValue
= 0;
6070 if ( (nextReloc
->r_address() & R_SCATTERED
) == 0 ) {
6071 if ( nextReloc
->r_type() == GENERIC_RELOC_PAIR
) {
6072 nextRelocIsPair
= true;
6073 nextRelocAddress
= nextReloc
->r_address();
6074 result
= true; // iterator should skip next reloc, since we've consumed it here
6078 if ( nextSReloc
->r_type() == GENERIC_RELOC_PAIR
) {
6079 nextRelocIsPair
= true;
6080 nextRelocAddress
= nextSReloc
->r_address();
6081 nextRelocValue
= nextSReloc
->r_value();
6084 switch (sreloc
->r_type()) {
6085 case GENERIC_RELOC_VANILLA
:
6086 // with a scattered relocation we get both the target (sreloc->r_value()) and the target+offset (*fixUpPtr)
6087 target
.atom
= parser
.findAtomByAddress(relocValue
);
6088 if ( sreloc
->r_pcrel() ) {
6089 switch ( sreloc
->r_length() ) {
6091 contentValue
= srcAddr
+ 1 + *fixUpPtr
;
6092 target
.addend
= (int32_t)contentValue
- (int32_t)relocValue
;
6093 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel8
, target
);
6096 contentValue
= srcAddr
+ 2 + LittleEndian::get16(*((uint16_t*)fixUpPtr
));
6097 target
.addend
= (int32_t)contentValue
- (int32_t)relocValue
;
6098 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel16
, target
);
6101 contentValue
= srcAddr
+ 4 + LittleEndian::get32(*((uint32_t*)fixUpPtr
));
6102 target
.addend
= (int32_t)contentValue
- (int32_t)relocValue
;
6103 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32
, target
);
6106 throw "unsupported r_length=3 for scattered pc-rel vanilla reloc";
6111 if ( sreloc
->r_length() != 2 )
6112 throwf("unsupported r_length=%d for scattered vanilla reloc", sreloc
->r_length());
6113 contentValue
= LittleEndian::get32(*((uint32_t*)fixUpPtr
));
6114 target
.addend
= (int32_t)contentValue
- (int32_t)(target
.atom
->objectAddress());
6115 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian32
, target
);
6118 case GENERIC_RELOC_SECTDIFF
:
6119 case GENERIC_RELOC_LOCAL_SECTDIFF
:
6121 if ( !nextRelocIsPair
)
6122 throw "GENERIC_RELOC_SECTDIFF missing following pair";
6123 switch ( sreloc
->r_length() ) {
6126 throw "bad length for GENERIC_RELOC_SECTDIFF";
6128 contentValue
= (int32_t)(int16_t)LittleEndian::get16(*((uint16_t*)fixUpPtr
));
6129 kind
= ld::Fixup::kindStoreLittleEndian16
;
6132 contentValue
= LittleEndian::get32(*((uint32_t*)fixUpPtr
));
6133 kind
= ld::Fixup::kindStoreLittleEndian32
;
6136 Atom
<x86
>* fromAtom
= parser
.findAtomByAddress(nextRelocValue
);
6137 uint32_t offsetInFrom
= nextRelocValue
- fromAtom
->_objAddress
;
6138 parser
.findTargetFromAddress(sreloc
->r_value(), target
);
6139 // check for addend encoded in the section content
6140 int64_t addend
= (int32_t)contentValue
- (int32_t)(sreloc
->r_value() - nextRelocValue
);
6142 // switch binding base on coalescing
6143 if ( target
.atom
== NULL
) {
6144 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, target
.name
);
6146 else if ( target
.atom
->scope() == ld::Atom::scopeTranslationUnit
) {
6147 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, target
.atom
);
6149 else if ( (target
.atom
->combine() == ld::Atom::combineByNameAndContent
) || (target
.atom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
6150 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, target
.atom
);
6153 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, target
.atom
->name());
6155 parser
.addFixup(src
, ld::Fixup::k2of5
, ld::Fixup::kindAddAddend
, target
.addend
);
6156 parser
.addFixup(src
, ld::Fixup::k3of5
, ld::Fixup::kindSubtractTargetAddress
, fromAtom
);
6157 parser
.addFixup(src
, ld::Fixup::k4of5
, ld::Fixup::kindSubtractAddend
, offsetInFrom
-addend
);
6158 parser
.addFixup(src
, ld::Fixup::k5of5
, kind
);
6161 // switch binding base on coalescing
6162 if ( target
.atom
== NULL
) {
6163 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, target
.name
);
6165 else if ( target
.atom
->scope() == ld::Atom::scopeTranslationUnit
) {
6166 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, target
.atom
);
6168 else if ( (target
.atom
->combine() == ld::Atom::combineByNameAndContent
) || (target
.atom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
6169 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, target
.atom
);
6172 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, target
.atom
->name());
6174 parser
.addFixup(src
, ld::Fixup::k2of5
, ld::Fixup::kindAddAddend
, target
.addend
+addend
);
6175 parser
.addFixup(src
, ld::Fixup::k3of5
, ld::Fixup::kindSubtractTargetAddress
, fromAtom
);
6176 parser
.addFixup(src
, ld::Fixup::k4of5
, ld::Fixup::kindSubtractAddend
, offsetInFrom
);
6177 parser
.addFixup(src
, ld::Fixup::k5of5
, kind
);
6190 #if SUPPORT_ARCH_arm_any
6192 bool Section
<arm
>::addRelocFixup(class Parser
<arm
>& parser
, const macho_relocation_info
<P
>* reloc
)
6194 const macho_section
<P
>* sect
= this->machoSection();
6195 bool result
= false;
6199 int32_t displacement
= 0;
6200 uint32_t instruction
= 0;
6201 pint_t contentValue
= 0;
6202 Parser
<arm
>::SourceLocation src
;
6203 Parser
<arm
>::TargetDesc target
;
6204 const macho_relocation_info
<P
>* nextReloc
;
6206 if ( (reloc
->r_address() & R_SCATTERED
) == 0 ) {
6207 bool externSymbolIsThumbDef
= false;
6208 srcAddr
= sect
->addr() + reloc
->r_address();
6209 src
.atom
= this->findAtomByAddress(srcAddr
);
6210 src
.offsetInAtom
= srcAddr
- src
.atom
->_objAddress
;
6211 fixUpPtr
= (uint32_t*)(file().fileContent() + sect
->offset() + reloc
->r_address());
6212 if ( reloc
->r_type() != ARM_RELOC_PAIR
)
6213 instruction
= LittleEndian::get32(*fixUpPtr
);
6214 if ( reloc
->r_extern() ) {
6215 const macho_nlist
<P
>& targetSymbol
= parser
.symbolFromIndex(reloc
->r_symbolnum());
6216 // use direct reference for local symbols
6217 if ( ((targetSymbol
.n_type() & N_TYPE
) == N_SECT
) && (((targetSymbol
.n_type() & N_EXT
) == 0) || (parser
.nameFromSymbol(targetSymbol
)[0] == 'L')) ) {
6218 parser
.findTargetFromAddressAndSectionNum(targetSymbol
.n_value(), targetSymbol
.n_sect(), target
);
6222 target
.name
= parser
.nameFromSymbol(targetSymbol
);
6223 target
.weakImport
= parser
.weakImportFromSymbol(targetSymbol
);
6224 if ( ((targetSymbol
.n_type() & N_TYPE
) == N_SECT
) && (targetSymbol
.n_desc() & N_ARM_THUMB_DEF
) )
6225 externSymbolIsThumbDef
= true;
6228 switch ( reloc
->r_type() ) {
6229 case ARM_RELOC_BR24
:
6230 // Sign-extend displacement
6231 displacement
= (instruction
& 0x00FFFFFF) << 2;
6232 if ( (displacement
& 0x02000000) != 0 )
6233 displacement
|= 0xFC000000;
6234 // The pc added will be +8 from the pc
6236 // If this is BLX add H << 1
6237 if ((instruction
& 0xFE000000) == 0xFA000000)
6238 displacement
+= ((instruction
& 0x01000000) >> 23);
6239 if ( reloc
->r_extern() ) {
6240 dstAddr
= srcAddr
+ displacement
;
6241 // <rdar://problem/16652542> support large .o files
6242 if ( srcAddr
> 0x2000000 ) {
6243 dstAddr
-= ((srcAddr
+ 0x1FFFFFF) & 0xFC000000);
6245 target
.addend
= dstAddr
;
6246 if ( externSymbolIsThumbDef
)
6247 target
.addend
&= -2; // remove thumb bit
6250 dstAddr
= srcAddr
+ displacement
;
6251 parser
.findTargetFromAddressAndSectionNum(dstAddr
, reloc
->r_symbolnum(), target
);
6253 // special case "calls" for dtrace
6254 if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_probe$", 16) == 0) ) {
6255 parser
.addFixup(src
, ld::Fixup::k1of1
,
6256 ld::Fixup::kindStoreARMDtraceCallSiteNop
, false, target
.name
);
6257 parser
.addDtraceExtraInfos(src
, &target
.name
[16]);
6259 else if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_isenabled$", 20) == 0) ) {
6260 parser
.addFixup(src
, ld::Fixup::k1of1
,
6261 ld::Fixup::kindStoreARMDtraceIsEnableSiteClear
, false, target
.name
);
6262 parser
.addDtraceExtraInfos(src
, &target
.name
[20]);
6265 parser
.addFixups(src
, ld::Fixup::kindStoreARMBranch24
, target
);
6268 case ARM_THUMB_RELOC_BR22
:
6269 // thumb2 added two more bits to displacement, complicating the displacement decoding
6271 uint32_t s
= (instruction
>> 10) & 0x1;
6272 uint32_t j1
= (instruction
>> 29) & 0x1;
6273 uint32_t j2
= (instruction
>> 27) & 0x1;
6274 uint32_t imm10
= instruction
& 0x3FF;
6275 uint32_t imm11
= (instruction
>> 16) & 0x7FF;
6276 uint32_t i1
= (j1
== s
);
6277 uint32_t i2
= (j2
== s
);
6278 uint32_t dis
= (s
<< 24) | (i1
<< 23) | (i2
<< 22) | (imm10
<< 12) | (imm11
<< 1);
6282 displacement
= sdis
;
6284 // The pc added will be +4 from the pc
6286 // If the instruction was blx, force the low 2 bits to be clear
6287 dstAddr
= srcAddr
+ displacement
;
6288 if ((instruction
& 0xD0000000) == 0xC0000000)
6289 dstAddr
&= 0xFFFFFFFC;
6291 if ( reloc
->r_extern() ) {
6292 // <rdar://problem/16652542> support large .o files
6293 if ( srcAddr
> 0x1000000 ) {
6294 dstAddr
-= ((srcAddr
+ 0xFFFFFF) & 0xFE000000);
6296 target
.addend
= (int64_t)(int32_t)dstAddr
;
6299 parser
.findTargetFromAddressAndSectionNum(dstAddr
, reloc
->r_symbolnum(), target
);
6301 // special case "calls" for dtrace
6302 if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_probe$", 16) == 0) ) {
6303 parser
.addFixup(src
, ld::Fixup::k1of1
,
6304 ld::Fixup::kindStoreThumbDtraceCallSiteNop
, false, target
.name
);
6305 parser
.addDtraceExtraInfos(src
, &target
.name
[16]);
6307 else if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_isenabled$", 20) == 0) ) {
6308 parser
.addFixup(src
, ld::Fixup::k1of1
,
6309 ld::Fixup::kindStoreThumbDtraceIsEnableSiteClear
, false, target
.name
);
6310 parser
.addDtraceExtraInfos(src
, &target
.name
[20]);
6313 parser
.addFixups(src
, ld::Fixup::kindStoreThumbBranch22
, target
);
6316 case ARM_RELOC_VANILLA
:
6317 if ( reloc
->r_length() != 2 )
6318 throw "bad length for ARM_RELOC_VANILLA";
6319 contentValue
= LittleEndian::get32(*fixUpPtr
);
6320 if ( reloc
->r_extern() ) {
6321 target
.addend
= (int32_t)contentValue
;
6322 if ( externSymbolIsThumbDef
)
6323 target
.addend
&= -2; // remove thumb bit
6326 parser
.findTargetFromAddressAndSectionNum(contentValue
, reloc
->r_symbolnum(), target
);
6327 // possible non-extern relocation turned into by-name ref because target is a weak-def
6328 if ( target
.atom
!= NULL
) {
6329 if ( target
.atom
->isThumb() )
6330 target
.addend
&= -2; // remove thumb bit
6331 // if reference to LSDA, add group subordinate fixup
6332 if ( target
.atom
->contentType() == ld::Atom::typeLSDA
) {
6333 Parser
<arm
>::SourceLocation src2
;
6334 src2
.atom
= src
.atom
;
6335 src2
.offsetInAtom
= 0;
6336 parser
.addFixup(src2
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinateLSDA
, target
.atom
);
6340 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian32
, target
);
6342 case ARM_THUMB_32BIT_BRANCH
:
6343 // silently ignore old unnecessary reloc
6345 case ARM_RELOC_HALF
:
6346 nextReloc
= &reloc
[1];
6347 if ( nextReloc
->r_type() == ARM_RELOC_PAIR
) {
6348 uint32_t instruction16
;
6349 uint32_t other16
= (nextReloc
->r_address() & 0xFFFF);
6351 if ( reloc
->r_length() & 2 ) {
6353 uint32_t i
= ((instruction
& 0x00000400) >> 10);
6354 uint32_t imm4
= (instruction
& 0x0000000F);
6355 uint32_t imm3
= ((instruction
& 0x70000000) >> 28);
6356 uint32_t imm8
= ((instruction
& 0x00FF0000) >> 16);
6357 instruction16
= (imm4
<< 12) | (i
<< 11) | (imm3
<< 8) | imm8
;
6361 uint32_t imm4
= ((instruction
& 0x000F0000) >> 16);
6362 uint32_t imm12
= (instruction
& 0x00000FFF);
6363 instruction16
= (imm4
<< 12) | imm12
;
6365 if ( reloc
->r_length() & 1 ) {
6367 dstAddr
= ((instruction16
<< 16) | other16
);
6368 if ( reloc
->r_extern() ) {
6369 target
.addend
= dstAddr
;
6370 if ( externSymbolIsThumbDef
)
6371 target
.addend
&= -2; // remove thumb bit
6374 parser
.findTargetFromAddress(dstAddr
, target
);
6375 if ( target
.atom
->isThumb() )
6376 target
.addend
&= (-2); // remove thumb bit
6378 parser
.addFixups(src
, (isThumb
? ld::Fixup::kindStoreThumbHigh16
: ld::Fixup::kindStoreARMHigh16
), target
);
6382 dstAddr
= (other16
<< 16) | instruction16
;
6383 if ( reloc
->r_extern() ) {
6384 target
.addend
= dstAddr
;
6385 if ( externSymbolIsThumbDef
)
6386 target
.addend
&= -2; // remove thumb bit
6389 parser
.findTargetFromAddress(dstAddr
, target
);
6390 if ( target
.atom
->isThumb() )
6391 target
.addend
&= (-2); // remove thumb bit
6393 parser
.addFixups(src
, (isThumb
? ld::Fixup::kindStoreThumbLow16
: ld::Fixup::kindStoreARMLow16
), target
);
6398 throw "for ARM_RELOC_HALF, next reloc is not ARM_RELOC_PAIR";
6401 throwf("unknown relocation type %d", reloc
->r_type());
6406 const macho_scattered_relocation_info
<P
>* sreloc
= (macho_scattered_relocation_info
<P
>*)reloc
;
6407 // file format allows pair to be scattered or not
6408 const macho_scattered_relocation_info
<P
>* nextSReloc
= &sreloc
[1];
6409 nextReloc
= &reloc
[1];
6410 srcAddr
= sect
->addr() + sreloc
->r_address();
6411 dstAddr
= sreloc
->r_value();
6412 fixUpPtr
= (uint32_t*)(file().fileContent() + sect
->offset() + sreloc
->r_address());
6413 instruction
= LittleEndian::get32(*fixUpPtr
);
6414 src
.atom
= this->findAtomByAddress(srcAddr
);
6415 src
.offsetInAtom
= srcAddr
- src
.atom
->_objAddress
;
6416 bool nextRelocIsPair
= false;
6417 uint32_t nextRelocAddress
= 0;
6418 uint32_t nextRelocValue
= 0;
6419 if ( (nextReloc
->r_address() & R_SCATTERED
) == 0 ) {
6420 if ( nextReloc
->r_type() == ARM_RELOC_PAIR
) {
6421 nextRelocIsPair
= true;
6422 nextRelocAddress
= nextReloc
->r_address();
6427 if ( nextSReloc
->r_type() == ARM_RELOC_PAIR
) {
6428 nextRelocIsPair
= true;
6429 nextRelocAddress
= nextSReloc
->r_address();
6430 nextRelocValue
= nextSReloc
->r_value();
6434 switch ( sreloc
->r_type() ) {
6435 case ARM_RELOC_VANILLA
:
6436 // with a scattered relocation we get both the target (sreloc->r_value()) and the target+offset (*fixUpPtr)
6437 if ( sreloc
->r_length() != 2 )
6438 throw "bad length for ARM_RELOC_VANILLA";
6439 target
.atom
= parser
.findAtomByAddress(sreloc
->r_value());
6440 if ( target
.atom
== NULL
)
6441 throwf("bad r_value (0x%08X) for ARM_RELOC_VANILLA\n", sreloc
->r_value());
6442 contentValue
= LittleEndian::get32(*fixUpPtr
);
6443 target
.addend
= contentValue
- target
.atom
->_objAddress
;
6444 if ( target
.atom
->isThumb() )
6445 target
.addend
&= -2; // remove thumb bit
6446 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian32
, target
);
6448 case ARM_RELOC_BR24
:
6449 // Sign-extend displacement
6450 displacement
= (instruction
& 0x00FFFFFF) << 2;
6451 if ( (displacement
& 0x02000000) != 0 )
6452 displacement
|= 0xFC000000;
6453 // The pc added will be +8 from the pc
6455 // If this is BLX add H << 1
6456 if ((instruction
& 0xFE000000) == 0xFA000000)
6457 displacement
+= ((instruction
& 0x01000000) >> 23);
6458 target
.atom
= parser
.findAtomByAddress(sreloc
->r_value());
6459 target
.addend
= (int64_t)(srcAddr
+ displacement
) - (int64_t)(target
.atom
->_objAddress
);
6460 parser
.addFixups(src
, ld::Fixup::kindStoreARMBranch24
, target
);
6462 case ARM_THUMB_RELOC_BR22
:
6463 // thumb2 added two more bits to displacement, complicating the displacement decoding
6465 uint32_t s
= (instruction
>> 10) & 0x1;
6466 uint32_t j1
= (instruction
>> 29) & 0x1;
6467 uint32_t j2
= (instruction
>> 27) & 0x1;
6468 uint32_t imm10
= instruction
& 0x3FF;
6469 uint32_t imm11
= (instruction
>> 16) & 0x7FF;
6470 uint32_t i1
= (j1
== s
);
6471 uint32_t i2
= (j2
== s
);
6472 uint32_t dis
= (s
<< 24) | (i1
<< 23) | (i2
<< 22) | (imm10
<< 12) | (imm11
<< 1);
6476 displacement
= sdis
;
6478 // The pc added will be +4 from the pc
6480 dstAddr
= srcAddr
+displacement
;
6481 // If the instruction was blx, force the low 2 bits to be clear
6482 if ((instruction
& 0xF8000000) == 0xE8000000)
6483 dstAddr
&= 0xFFFFFFFC;
6484 target
.atom
= parser
.findAtomByAddress(sreloc
->r_value());
6485 target
.addend
= dstAddr
- target
.atom
->_objAddress
;
6486 parser
.addFixups(src
, ld::Fixup::kindStoreThumbBranch22
, target
);
6488 case ARM_RELOC_SECTDIFF
:
6489 case ARM_RELOC_LOCAL_SECTDIFF
:
6491 if ( ! nextRelocIsPair
)
6492 throw "ARM_RELOC_SECTDIFF missing following pair";
6493 if ( sreloc
->r_length() != 2 )
6494 throw "bad length for ARM_RELOC_SECTDIFF";
6495 contentValue
= LittleEndian::get32(*fixUpPtr
);
6496 Atom
<arm
>* fromAtom
= parser
.findAtomByAddress(nextRelocValue
);
6497 uint32_t offsetInFrom
= nextRelocValue
- fromAtom
->_objAddress
;
6498 uint32_t offsetInTarget
;
6499 Atom
<arm
>* targetAtom
= parser
.findAtomByAddressOrLocalTargetOfStub(sreloc
->r_value(), &offsetInTarget
);
6500 // check for addend encoded in the section content
6501 int64_t addend
= (int32_t)contentValue
- (int32_t)(sreloc
->r_value() - nextRelocValue
);
6502 if ( targetAtom
->isThumb() )
6503 addend
&= -2; // remove thumb bit
6504 // if reference to LSDA, add group subordinate fixup
6505 if ( targetAtom
->contentType() == ld::Atom::typeLSDA
) {
6506 Parser
<arm
>::SourceLocation src2
;
6507 src2
.atom
= src
.atom
;
6508 src2
.offsetInAtom
= 0;
6509 parser
.addFixup(src2
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinateLSDA
, targetAtom
);
6512 // switch binding base on coalescing
6513 if ( targetAtom
->scope() == ld::Atom::scopeTranslationUnit
) {
6514 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, targetAtom
);
6516 else if ( (targetAtom
->combine() == ld::Atom::combineByNameAndContent
) || (targetAtom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
6517 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, targetAtom
);
6520 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, targetAtom
->name());
6522 parser
.addFixup(src
, ld::Fixup::k2of5
, ld::Fixup::kindAddAddend
, offsetInTarget
);
6523 parser
.addFixup(src
, ld::Fixup::k3of5
, ld::Fixup::kindSubtractTargetAddress
, fromAtom
);
6524 parser
.addFixup(src
, ld::Fixup::k4of5
, ld::Fixup::kindSubtractAddend
, offsetInFrom
-addend
);
6525 parser
.addFixup(src
, ld::Fixup::k5of5
, ld::Fixup::kindStoreLittleEndian32
);
6528 if ( targetAtom
->scope() == ld::Atom::scopeTranslationUnit
) {
6529 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, targetAtom
);
6531 else if ( (targetAtom
->combine() == ld::Atom::combineByNameAndContent
) || (targetAtom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
6532 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, targetAtom
);
6535 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, targetAtom
->name());
6537 parser
.addFixup(src
, ld::Fixup::k2of5
, ld::Fixup::kindAddAddend
, (uint32_t)(offsetInTarget
+addend
));
6538 parser
.addFixup(src
, ld::Fixup::k3of5
, ld::Fixup::kindSubtractTargetAddress
, fromAtom
);
6539 parser
.addFixup(src
, ld::Fixup::k4of5
, ld::Fixup::kindSubtractAddend
, offsetInFrom
);
6540 parser
.addFixup(src
, ld::Fixup::k5of5
, ld::Fixup::kindStoreLittleEndian32
);
6544 case ARM_RELOC_HALF_SECTDIFF
:
6545 if ( nextRelocIsPair
) {
6546 instruction
= LittleEndian::get32(*fixUpPtr
);
6547 Atom
<arm
>* fromAtom
= parser
.findAtomByAddress(nextRelocValue
);
6548 uint32_t offsetInFrom
= nextRelocValue
- fromAtom
->_objAddress
;
6549 Atom
<arm
>* targetAtom
= parser
.findAtomByAddress(sreloc
->r_value());
6550 uint32_t offsetInTarget
= sreloc
->r_value() - targetAtom
->_objAddress
;
6551 uint32_t instruction16
;
6552 uint32_t other16
= (nextRelocAddress
& 0xFFFF);
6554 if ( sreloc
->r_length() & 2 ) {
6556 uint32_t i
= ((instruction
& 0x00000400) >> 10);
6557 uint32_t imm4
= (instruction
& 0x0000000F);
6558 uint32_t imm3
= ((instruction
& 0x70000000) >> 28);
6559 uint32_t imm8
= ((instruction
& 0x00FF0000) >> 16);
6560 instruction16
= (imm4
<< 12) | (i
<< 11) | (imm3
<< 8) | imm8
;
6564 uint32_t imm4
= ((instruction
& 0x000F0000) >> 16);
6565 uint32_t imm12
= (instruction
& 0x00000FFF);
6566 instruction16
= (imm4
<< 12) | imm12
;
6568 if ( sreloc
->r_length() & 1 )
6569 dstAddr
= ((instruction16
<< 16) | other16
);
6571 dstAddr
= (other16
<< 16) | instruction16
;
6572 if ( targetAtom
->isThumb() )
6573 dstAddr
&= (-2); // remove thumb bit
6574 int32_t addend
= dstAddr
- (sreloc
->r_value() - nextRelocValue
);
6575 if ( targetAtom
->scope() == ld::Atom::scopeTranslationUnit
) {
6576 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, targetAtom
);
6578 else if ( (targetAtom
->combine() == ld::Atom::combineByNameAndContent
) || (targetAtom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
6579 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, targetAtom
);
6582 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, targetAtom
->name());
6584 parser
.addFixup(src
, ld::Fixup::k2of5
, ld::Fixup::kindAddAddend
, (uint32_t)offsetInTarget
+addend
);
6585 parser
.addFixup(src
, ld::Fixup::k3of5
, ld::Fixup::kindSubtractTargetAddress
, fromAtom
);
6586 parser
.addFixup(src
, ld::Fixup::k4of5
, ld::Fixup::kindSubtractAddend
, offsetInFrom
);
6587 if ( sreloc
->r_length() & 1 ) {
6589 parser
.addFixup(src
, ld::Fixup::k5of5
, (isThumb
? ld::Fixup::kindStoreThumbHigh16
: ld::Fixup::kindStoreARMHigh16
));
6593 parser
.addFixup(src
, ld::Fixup::k5of5
, (isThumb
? ld::Fixup::kindStoreThumbLow16
: ld::Fixup::kindStoreARMLow16
));
6598 throw "ARM_RELOC_HALF_SECTDIFF reloc missing following pair";
6600 case ARM_RELOC_HALF
:
6601 if ( nextRelocIsPair
) {
6602 instruction
= LittleEndian::get32(*fixUpPtr
);
6603 Atom
<arm
>* targetAtom
= parser
.findAtomByAddress(sreloc
->r_value());
6604 uint32_t instruction16
;
6605 uint32_t other16
= (nextRelocAddress
& 0xFFFF);
6607 if ( sreloc
->r_length() & 2 ) {
6609 uint32_t i
= ((instruction
& 0x00000400) >> 10);
6610 uint32_t imm4
= (instruction
& 0x0000000F);
6611 uint32_t imm3
= ((instruction
& 0x70000000) >> 28);
6612 uint32_t imm8
= ((instruction
& 0x00FF0000) >> 16);
6613 instruction16
= (imm4
<< 12) | (i
<< 11) | (imm3
<< 8) | imm8
;
6617 uint32_t imm4
= ((instruction
& 0x000F0000) >> 16);
6618 uint32_t imm12
= (instruction
& 0x00000FFF);
6619 instruction16
= (imm4
<< 12) | imm12
;
6621 if ( sreloc
->r_length() & 1 )
6622 dstAddr
= ((instruction16
<< 16) | other16
);
6624 dstAddr
= (other16
<< 16) | instruction16
;
6625 if ( targetAtom
->scope() == ld::Atom::scopeTranslationUnit
) {
6626 parser
.addFixup(src
, ld::Fixup::k1of3
, ld::Fixup::kindSetTargetAddress
, targetAtom
);
6628 else if ( (targetAtom
->combine() == ld::Atom::combineByNameAndContent
) || (targetAtom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
6629 parser
.addFixup(src
, ld::Fixup::k1of3
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, targetAtom
);
6632 parser
.addFixup(src
, ld::Fixup::k1of3
, ld::Fixup::kindSetTargetAddress
, false, targetAtom
->name());
6634 parser
.addFixup(src
, ld::Fixup::k2of3
, ld::Fixup::kindAddAddend
, dstAddr
- targetAtom
->_objAddress
);
6635 if ( sreloc
->r_length() & 1 ) {
6637 parser
.addFixup(src
, ld::Fixup::k3of3
, (isThumb
? ld::Fixup::kindStoreThumbHigh16
: ld::Fixup::kindStoreARMHigh16
));
6641 parser
.addFixup(src
, ld::Fixup::k3of3
, (isThumb
? ld::Fixup::kindStoreThumbLow16
: ld::Fixup::kindStoreARMLow16
));
6646 throw "scattered ARM_RELOC_HALF reloc missing following pair";
6649 throwf("unknown ARM scattered relocation type %d", sreloc
->r_type());
6657 #if SUPPORT_ARCH_arm64
6659 bool Section
<arm64
>::addRelocFixup(class Parser
<arm64
>& parser
, const macho_relocation_info
<P
>* reloc
)
6661 bool result
= false;
6662 Parser
<arm64
>::SourceLocation src
;
6663 Parser
<arm64
>::TargetDesc target
= { NULL
, NULL
, false, 0 };
6664 Parser
<arm64
>::TargetDesc toTarget
;
6665 int32_t prefixRelocAddend
= 0;
6666 if ( reloc
->r_type() == ARM64_RELOC_ADDEND
) {
6667 uint32_t rawAddend
= reloc
->r_symbolnum();
6668 prefixRelocAddend
= rawAddend
;
6669 if ( rawAddend
& 0x00800000 )
6670 prefixRelocAddend
|= 0xFF000000; // sign extend 24-bit signed int to 32-bits
6671 uint32_t addendAddress
= reloc
->r_address();
6672 ++reloc
; //advance to next reloc record
6674 if ( reloc
->r_address() != addendAddress
)
6675 throw "ARM64_RELOC_ADDEND r_address does not match next reloc's r_address";
6677 const macho_section
<P
>* sect
= this->machoSection();
6678 uint64_t srcAddr
= sect
->addr() + reloc
->r_address();
6679 src
.atom
= this->findAtomByAddress(srcAddr
);
6680 src
.offsetInAtom
= srcAddr
- src
.atom
->_objAddress
;
6681 const uint8_t* fixUpPtr
= file().fileContent() + sect
->offset() + reloc
->r_address();
6682 uint64_t contentValue
= 0;
6683 const macho_relocation_info
<arm64::P
>* nextReloc
= &reloc
[1];
6684 bool useDirectBinding
;
6685 uint32_t instruction
;
6686 uint32_t encodedAddend
;
6687 switch ( reloc
->r_length() ) {
6689 contentValue
= *fixUpPtr
;
6692 contentValue
= (int64_t)(int16_t)E::get16(*((uint16_t*)fixUpPtr
));
6695 contentValue
= (int64_t)(int32_t)E::get32(*((uint32_t*)fixUpPtr
));
6698 contentValue
= E::get64(*((uint64_t*)fixUpPtr
));
6701 if ( reloc
->r_extern() ) {
6702 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
6703 const char* symbolName
= parser
.nameFromSymbol(sym
);
6704 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && (((sym
.n_type() & N_EXT
) == 0) || (symbolName
[0] == 'L') || (symbolName
[0] == 'l')) ) {
6705 // use direct reference for local symbols
6706 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
6707 //target.addend += contentValue;
6709 else if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && (src
.atom
->_objAddress
<= sym
.n_value()) && (sym
.n_value() < (src
.atom
->_objAddress
+src
.atom
->size())) ) {
6710 // <rdar://problem/13700961> spurious warning when weak function has reference to itself
6711 // use direct reference when atom targets itself
6712 target
.atom
= src
.atom
;
6716 target
.name
= symbolName
;
6717 target
.weakImport
= parser
.weakImportFromSymbol(sym
);
6718 //target.addend = contentValue;
6720 // cfstrings should always use direct reference to backing store
6721 if ( (this->type() == ld::Section::typeCFString
) && (src
.offsetInAtom
!= 0) ) {
6722 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
6723 //target.addend = contentValue;
6727 if ( reloc
->r_pcrel() )
6728 contentValue
+= srcAddr
;
6729 parser
.findTargetFromAddressAndSectionNum(contentValue
, reloc
->r_symbolnum(), target
);
6731 switch ( reloc
->r_type() ) {
6732 case ARM64_RELOC_UNSIGNED
:
6733 if ( reloc
->r_pcrel() )
6734 throw "pcrel and ARM64_RELOC_UNSIGNED not supported";
6735 target
.addend
= contentValue
;
6736 switch ( reloc
->r_length() ) {
6739 throw "length < 2 and ARM64_RELOC_UNSIGNED not supported";
6741 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian32
, target
);
6744 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian64
, target
);
6748 case ARM64_RELOC_BRANCH26
:
6749 if ( ! reloc
->r_pcrel() )
6750 throw "not pcrel and ARM64_RELOC_BRANCH26 not supported";
6751 if ( ! reloc
->r_extern() )
6752 throw "r_extern == 0 and ARM64_RELOC_BRANCH26 not supported";
6753 if ( reloc
->r_length() != 2 )
6754 throw "r_length != 2 and ARM64_RELOC_BRANCH26 not supported";
6755 if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_probe$", 16) == 0) ) {
6756 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindStoreARM64DtraceCallSiteNop
, false, target
.name
);
6757 parser
.addDtraceExtraInfos(src
, &target
.name
[16]);
6759 else if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_isenabled$", 20) == 0) ) {
6760 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindStoreARM64DtraceIsEnableSiteClear
, false, target
.name
);
6761 parser
.addDtraceExtraInfos(src
, &target
.name
[20]);
6764 target
.addend
= prefixRelocAddend
;
6765 instruction
= contentValue
;
6766 encodedAddend
= (instruction
& 0x03FFFFFF) << 2;
6767 if ( encodedAddend
!= 0 ) {
6768 if ( prefixRelocAddend
== 0 ) {
6769 warning("branch26 instruction at 0x%08X has embedded addend. ARM64_RELOC_ADDEND should be used instead", reloc
->r_address());
6770 target
.addend
= encodedAddend
;
6773 throwf("branch26 instruction at 0x%08X has embedded addend and ARM64_RELOC_ADDEND also used", reloc
->r_address());
6776 parser
.addFixups(src
, ld::Fixup::kindStoreARM64Branch26
, target
);
6779 case ARM64_RELOC_PAGE21
:
6780 if ( ! reloc
->r_pcrel() )
6781 throw "not pcrel and ARM64_RELOC_PAGE21 not supported";
6782 if ( ! reloc
->r_extern() )
6783 throw "r_extern == 0 and ARM64_RELOC_PAGE21 not supported";
6784 if ( reloc
->r_length() != 2 )
6785 throw "length != 2 and ARM64_RELOC_PAGE21 not supported";
6786 target
.addend
= prefixRelocAddend
;
6787 instruction
= contentValue
;
6788 encodedAddend
= ((instruction
& 0x60000000) >> 29) | ((instruction
& 0x01FFFFE0) >> 3);
6789 encodedAddend
*= 4096; // internally addend is in bytes, so scale
6790 if ( encodedAddend
!= 0 ) {
6791 if ( prefixRelocAddend
== 0 ) {
6792 warning("adrp instruction at 0x%08X has embedded addend. ARM64_RELOC_ADDEND should be used instead", reloc
->r_address());
6793 target
.addend
= encodedAddend
;
6796 throwf("adrp instruction at 0x%08X has embedded addend and ARM64_RELOC_ADDEND also used", reloc
->r_address());
6799 parser
.addFixups(src
, ld::Fixup::kindStoreARM64Page21
, target
);
6801 case ARM64_RELOC_PAGEOFF12
:
6802 if ( reloc
->r_pcrel() )
6803 throw "pcrel and ARM64_RELOC_PAGEOFF12 not supported";
6804 if ( ! reloc
->r_extern() )
6805 throw "r_extern == 0 and ARM64_RELOC_PAGEOFF12 not supported";
6806 if ( reloc
->r_length() != 2 )
6807 throw "length != 2 and ARM64_RELOC_PAGEOFF12 not supported";
6808 target
.addend
= prefixRelocAddend
;
6809 instruction
= contentValue
;
6810 encodedAddend
= ((instruction
& 0x003FFC00) >> 10);
6811 // internally addend is in bytes. Some instructions have an implicit scale factor
6812 if ( (instruction
& 0x3B000000) == 0x39000000 ) {
6813 switch ( instruction
& 0xC0000000 ) {
6827 if ( encodedAddend
!= 0 ) {
6828 if ( prefixRelocAddend
== 0 ) {
6829 warning("pageoff12 instruction at 0x%08X has embedded addend. ARM64_RELOC_ADDEND should be used instead", reloc
->r_address());
6830 target
.addend
= encodedAddend
;
6833 throwf("pageoff12 instruction at 0x%08X has embedded addend and ARM64_RELOC_ADDEND also used", reloc
->r_address());
6836 parser
.addFixups(src
, ld::Fixup::kindStoreARM64PageOff12
, target
);
6838 case ARM64_RELOC_GOT_LOAD_PAGE21
:
6839 if ( ! reloc
->r_pcrel() )
6840 throw "not pcrel and ARM64_RELOC_GOT_LOAD_PAGE21 not supported";
6841 if ( ! reloc
->r_extern() )
6842 throw "r_extern == 0 and ARM64_RELOC_GOT_LOAD_PAGE21 not supported";
6843 if ( reloc
->r_length() != 2 )
6844 throw "length != 2 and ARM64_RELOC_GOT_LOAD_PAGE21 not supported";
6845 if ( prefixRelocAddend
!= 0 )
6846 throw "ARM64_RELOC_ADDEND followed by ARM64_RELOC_GOT_LOAD_PAGE21 not supported";
6847 instruction
= contentValue
;
6848 target
.addend
= ((instruction
& 0x60000000) >> 29) | ((instruction
& 0x01FFFFE0) >> 3);
6849 if ( target
.addend
!= 0 )
6850 throw "non-zero addend with ARM64_RELOC_GOT_LOAD_PAGE21 is not supported";
6851 parser
.addFixups(src
, ld::Fixup::kindStoreARM64GOTLoadPage21
, target
);
6853 case ARM64_RELOC_GOT_LOAD_PAGEOFF12
:
6854 if ( reloc
->r_pcrel() )
6855 throw "pcrel and ARM64_RELOC_GOT_LOAD_PAGEOFF12 not supported";
6856 if ( ! reloc
->r_extern() )
6857 throw "r_extern == 0 and ARM64_RELOC_GOT_LOAD_PAGEOFF12 not supported";
6858 if ( reloc
->r_length() != 2 )
6859 throw "length != 2 and ARM64_RELOC_GOT_LOAD_PAGEOFF12 not supported";
6860 if ( prefixRelocAddend
!= 0 )
6861 throw "ARM64_RELOC_ADDEND followed by ARM64_RELOC_GOT_LOAD_PAGEOFF12 not supported";
6862 instruction
= contentValue
;
6863 target
.addend
= ((instruction
& 0x003FFC00) >> 10);
6864 parser
.addFixups(src
, ld::Fixup::kindStoreARM64GOTLoadPageOff12
, target
);
6866 case ARM64_RELOC_TLVP_LOAD_PAGE21
:
6867 if ( ! reloc
->r_pcrel() )
6868 throw "not pcrel and ARM64_RELOC_TLVP_LOAD_PAGE21 not supported";
6869 if ( ! reloc
->r_extern() )
6870 throw "r_extern == 0 and ARM64_RELOC_TLVP_LOAD_PAGE21 not supported";
6871 if ( reloc
->r_length() != 2 )
6872 throw "length != 2 and ARM64_RELOC_TLVP_LOAD_PAGE21 not supported";
6873 if ( prefixRelocAddend
!= 0 )
6874 throw "ARM64_RELOC_ADDEND followed by ARM64_RELOC_TLVP_LOAD_PAGE21 not supported";
6875 instruction
= contentValue
;
6876 target
.addend
= ((instruction
& 0x60000000) >> 29) | ((instruction
& 0x01FFFFE0) >> 3);
6877 if ( target
.addend
!= 0 )
6878 throw "non-zero addend with ARM64_RELOC_GOT_LOAD_PAGE21 is not supported";
6879 parser
.addFixups(src
, ld::Fixup::kindStoreARM64TLVPLoadPage21
, target
);
6881 case ARM64_RELOC_TLVP_LOAD_PAGEOFF12
:
6882 if ( reloc
->r_pcrel() )
6883 throw "pcrel and ARM64_RELOC_TLVP_LOAD_PAGEOFF12 not supported";
6884 if ( ! reloc
->r_extern() )
6885 throw "r_extern == 0 and ARM64_RELOC_TLVP_LOAD_PAGEOFF12 not supported";
6886 if ( reloc
->r_length() != 2 )
6887 throw "length != 2 and ARM64_RELOC_TLVP_LOAD_PAGEOFF12 not supported";
6888 if ( prefixRelocAddend
!= 0 )
6889 throw "ARM64_RELOC_ADDEND followed by ARM64_RELOC_TLVP_LOAD_PAGEOFF12 not supported";
6890 instruction
= contentValue
;
6891 target
.addend
= ((instruction
& 0x003FFC00) >> 10);
6892 parser
.addFixups(src
, ld::Fixup::kindStoreARM64TLVPLoadPageOff12
, target
);
6894 case ARM64_RELOC_SUBTRACTOR
:
6895 if ( reloc
->r_pcrel() )
6896 throw "ARM64_RELOC_SUBTRACTOR cannot be pc-relative";
6897 if ( reloc
->r_length() < 2 )
6898 throw "ARM64_RELOC_SUBTRACTOR must have r_length of 2 or 3";
6899 if ( !reloc
->r_extern() )
6900 throw "ARM64_RELOC_SUBTRACTOR must have r_extern=1";
6901 if ( nextReloc
->r_type() != ARM64_RELOC_UNSIGNED
)
6902 throw "ARM64_RELOC_SUBTRACTOR must be followed by ARM64_RELOC_UNSIGNED";
6903 if ( prefixRelocAddend
!= 0 )
6904 throw "ARM64_RELOC_ADDEND followed by ARM64_RELOC_SUBTRACTOR not supported";
6906 if ( nextReloc
->r_pcrel() )
6907 throw "ARM64_RELOC_UNSIGNED following a ARM64_RELOC_SUBTRACTOR cannot be pc-relative";
6908 if ( nextReloc
->r_length() != reloc
->r_length() )
6909 throw "ARM64_RELOC_UNSIGNED following a ARM64_RELOC_SUBTRACTOR must have same r_length";
6910 if ( nextReloc
->r_extern() ) {
6911 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(nextReloc
->r_symbolnum());
6912 // use direct reference for local symbols
6913 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && (((sym
.n_type() & N_EXT
) == 0) || (parser
.nameFromSymbol(sym
)[0] == 'L')) ) {
6914 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), toTarget
);
6915 toTarget
.addend
= contentValue
;
6916 useDirectBinding
= true;
6919 toTarget
.name
= parser
.nameFromSymbol(sym
);
6920 toTarget
.weakImport
= parser
.weakImportFromSymbol(sym
);
6921 toTarget
.addend
= contentValue
;
6922 useDirectBinding
= false;
6926 parser
.findTargetFromAddressAndSectionNum(contentValue
, nextReloc
->r_symbolnum(), toTarget
);
6927 useDirectBinding
= (toTarget
.atom
->scope() == ld::Atom::scopeTranslationUnit
);
6929 if ( useDirectBinding
)
6930 parser
.addFixup(src
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, toTarget
.atom
);
6932 parser
.addFixup(src
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, toTarget
.weakImport
, toTarget
.name
);
6933 parser
.addFixup(src
, ld::Fixup::k2of4
, ld::Fixup::kindAddAddend
, toTarget
.addend
);
6934 if ( target
.atom
== NULL
)
6935 parser
.addFixup(src
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractTargetAddress
, false, target
.name
);
6937 parser
.addFixup(src
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractTargetAddress
, target
.atom
);
6938 if ( reloc
->r_length() == 2 )
6939 parser
.addFixup(src
, ld::Fixup::k4of4
, ld::Fixup::kindStoreLittleEndian32
);
6941 parser
.addFixup(src
, ld::Fixup::k4of4
, ld::Fixup::kindStoreLittleEndian64
);
6943 case ARM64_RELOC_POINTER_TO_GOT
:
6944 if ( ! reloc
->r_extern() )
6945 throw "r_extern == 0 and ARM64_RELOC_POINTER_TO_GOT not supported";
6946 if ( prefixRelocAddend
!= 0 )
6947 throw "ARM64_RELOC_ADDEND followed by ARM64_RELOC_POINTER_TO_GOT not supported";
6948 if ( reloc
->r_pcrel() ) {
6949 if ( reloc
->r_length() != 2 )
6950 throw "r_length != 2 and r_extern = 1 and ARM64_RELOC_POINTER_TO_GOT not supported";
6951 parser
.addFixups(src
, ld::Fixup::kindStoreARM64PCRelToGOT
, target
);
6954 if ( reloc
->r_length() != 3 )
6955 throw "r_length != 3 and r_extern = 0 and ARM64_RELOC_POINTER_TO_GOT not supported";
6956 parser
.addFixups(src
, ld::Fixup::kindStoreARM64PointerToGOT
, target
);
6960 throwf("unknown relocation type %d", reloc
->r_type());
6966 template <typename A
>
6967 bool ObjC1ClassSection
<A
>::addRelocFixup(class Parser
<A
>& parser
, const macho_relocation_info
<P
>* reloc
)
6970 FixedSizeSection
<A
>::addRelocFixup(parser
, reloc
);
6972 assert(0 && "needs template specialization");
6977 bool ObjC1ClassSection
<x86
>::addRelocFixup(class Parser
<x86
>& parser
, const macho_relocation_info
<x86::P
>* reloc
)
6979 // if this is the reloc for the super class name string, add implicit reference to super class
6980 if ( ((reloc
->r_address() & R_SCATTERED
) == 0) && (reloc
->r_type() == GENERIC_RELOC_VANILLA
) ) {
6981 assert( reloc
->r_length() == 2 );
6982 assert( ! reloc
->r_pcrel() );
6984 const macho_section
<P
>* sect
= this->machoSection();
6985 Parser
<x86
>::SourceLocation src
;
6986 uint32_t srcAddr
= sect
->addr() + reloc
->r_address();
6987 src
.atom
= this->findAtomByAddress(srcAddr
);
6988 src
.offsetInAtom
= srcAddr
- src
.atom
->objectAddress();
6989 if ( src
.offsetInAtom
== 4 ) {
6990 Parser
<x86
>::TargetDesc stringTarget
;
6991 const uint8_t* fixUpPtr
= file().fileContent() + sect
->offset() + reloc
->r_address();
6992 uint32_t contentValue
= LittleEndian::get32(*((uint32_t*)fixUpPtr
));
6993 parser
.findTargetFromAddressAndSectionNum(contentValue
, reloc
->r_symbolnum(), stringTarget
);
6995 assert(stringTarget
.atom
!= NULL
);
6996 assert(stringTarget
.atom
->contentType() == ld::Atom::typeCString
);
6997 const char* superClassBaseName
= (char*)stringTarget
.atom
->rawContentPointer();
6998 char* superClassName
= new char[strlen(superClassBaseName
) + 20];
6999 strcpy(superClassName
, ".objc_class_name_");
7000 strcat(superClassName
, superClassBaseName
);
7002 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindSetTargetAddress
, false, superClassName
);
7006 return FixedSizeSection
<x86
>::addRelocFixup(parser
, reloc
);
7011 template <typename A
>
7012 bool Objc1ClassReferences
<A
>::addRelocFixup(class Parser
<A
>& parser
, const macho_relocation_info
<P
>* reloc
)
7015 PointerToCStringSection
<A
>::addRelocFixup(parser
, reloc
);
7017 assert(0 && "needs template specialization");
7024 bool Objc1ClassReferences
<x86
>::addRelocFixup(class Parser
<x86
>& parser
, const macho_relocation_info
<x86::P
>* reloc
)
7026 // add implict class refs, fixups not usable yet, so look at relocations
7027 assert( (reloc
->r_address() & R_SCATTERED
) == 0 );
7028 assert( reloc
->r_type() == GENERIC_RELOC_VANILLA
);
7029 assert( reloc
->r_length() == 2 );
7030 assert( ! reloc
->r_pcrel() );
7032 const macho_section
<P
>* sect
= this->machoSection();
7033 Parser
<x86
>::SourceLocation src
;
7034 uint32_t srcAddr
= sect
->addr() + reloc
->r_address();
7035 src
.atom
= this->findAtomByAddress(srcAddr
);
7036 src
.offsetInAtom
= srcAddr
- src
.atom
->objectAddress();
7037 Parser
<x86
>::TargetDesc stringTarget
;
7038 const uint8_t* fixUpPtr
= file().fileContent() + sect
->offset() + reloc
->r_address();
7039 uint32_t contentValue
= LittleEndian::get32(*((uint32_t*)fixUpPtr
));
7040 parser
.findTargetFromAddressAndSectionNum(contentValue
, reloc
->r_symbolnum(), stringTarget
);
7042 assert(stringTarget
.atom
!= NULL
);
7043 assert(stringTarget
.atom
->contentType() == ld::Atom::typeCString
);
7044 const char* baseClassName
= (char*)stringTarget
.atom
->rawContentPointer();
7045 char* objcClassName
= new char[strlen(baseClassName
) + 20];
7046 strcpy(objcClassName
, ".objc_class_name_");
7047 strcat(objcClassName
, baseClassName
);
7049 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindSetTargetAddress
, false, objcClassName
);
7052 return PointerToCStringSection
<x86
>::addRelocFixup(parser
, reloc
);
7055 #if SUPPORT_ARCH_arm64
7057 void Section
<arm64
>::addLOH(class Parser
<arm64
>& parser
, int kind
, int count
, const uint64_t addrs
[]) {
7059 case LOH_ARM64_ADRP_ADRP
:
7060 case LOH_ARM64_ADRP_LDR
:
7061 case LOH_ARM64_ADRP_ADD
:
7062 case LOH_ARM64_ADRP_LDR_GOT
:
7064 warning("arm64 Linker Optimiztion Hint %d has wrong number of arguments", kind
);
7066 case LOH_ARM64_ADRP_ADD_LDR
:
7067 case LOH_ARM64_ADRP_LDR_GOT_LDR
:
7068 case LOH_ARM64_ADRP_ADD_STR
:
7069 case LOH_ARM64_ADRP_LDR_GOT_STR
:
7071 warning("arm64 Linker Optimiztion Hint %d has wrong number of arguments", kind
);
7074 // pick lowest address in tuple for use as offsetInAtom
7075 uint64_t lowestAddress
= addrs
[0];
7076 for(int i
=1; i
< count
; ++i
) {
7077 if ( addrs
[i
] < lowestAddress
)
7078 lowestAddress
= addrs
[i
];
7080 // verify all other address are in same atom
7081 Atom
<arm64
>* inAtom
= parser
.findAtomByAddress(lowestAddress
);
7082 const uint64_t atomStartAddr
= inAtom
->objectAddress();
7083 const uint64_t atomEndAddr
= atomStartAddr
+ inAtom
->size();
7084 for(int i
=0; i
< count
; ++i
) {
7085 if ( (addrs
[i
] < atomStartAddr
) || (addrs
[i
] >= atomEndAddr
) ) {
7086 warning("arm64 Linker Optimiztion Hint addresses are not in same atom: 0x%08llX and 0x%08llX",
7087 lowestAddress
, addrs
[i
]);
7088 return; // skip this LOH
7090 if ( (addrs
[i
] & 0x3) != 0 ) {
7091 warning("arm64 Linker Optimiztion Hint address is not 4-byte aligned: 0x%08llX", addrs
[i
]);
7092 return; // skip this LOH
7094 if ( (addrs
[i
] - lowestAddress
) > 0xFFFF ) {
7095 if ( parser
.verboseOptimizationHints() ) {
7096 warning("arm64 Linker Optimiztion Hint addresses are too far apart: 0x%08llX and 0x%08llX",
7097 lowestAddress
, addrs
[i
]);
7099 return; // skip this LOH
7103 // encoded kind, count, and address deltas in 64-bit addend
7104 ld::Fixup::LOH_arm64 extra
;
7106 extra
.info
.kind
= kind
;
7107 extra
.info
.count
= count
-1;
7108 extra
.info
.delta1
= (addrs
[0] - lowestAddress
) >> 2;
7109 extra
.info
.delta2
= (count
> 1) ? ((addrs
[1] - lowestAddress
) >> 2) : 0;
7110 extra
.info
.delta3
= (count
> 2) ? ((addrs
[2] - lowestAddress
) >> 2) : 0;
7111 extra
.info
.delta4
= (count
> 3) ? ((addrs
[3] - lowestAddress
) >> 2) : 0;
7112 typename Parser
<arm64
>::SourceLocation
src(inAtom
, lowestAddress
- inAtom
->objectAddress());
7113 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindLinkerOptimizationHint
, extra
.addend
);
7117 template <typename A
>
7118 void Section
<A
>::addLOH(class Parser
<A
>& parser
, int kind
, int count
, const uint64_t addrs
[]) {
7122 template <typename A
>
7123 void Section
<A
>::makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&)
7125 const macho_section
<P
>* sect
= this->machoSection();
7126 const macho_relocation_info
<P
>* relocs
= (macho_relocation_info
<P
>*)(file().fileContent() + sect
->reloff());
7127 const uint32_t relocCount
= sect
->nreloc();
7128 for (uint32_t r
= 0; r
< relocCount
; ++r
) {
7130 if ( this->addRelocFixup(parser
, &relocs
[r
]) )
7133 catch (const char* msg
) {
7134 throwf("in section %s,%s reloc %u: %s", sect
->segname(), Section
<A
>::makeSectionName(sect
), r
, msg
);
7138 // add follow-on fixups if .o file is missing .subsections_via_symbols
7139 if ( this->addFollowOnFixups() ) {
7140 Atom
<A
>* end
= &_endAtoms
[-1];
7141 for(Atom
<A
>* p
= _beginAtoms
; p
< end
; ++p
) {
7142 typename Parser
<A
>::SourceLocation
src(p
, 0);
7143 Atom
<A
>* nextAtom
= &p
[1];
7144 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindNoneFollowOn
, nextAtom
);
7147 else if ( this->type() == ld::Section::typeCode
) {
7148 // if FDE broke text not at a symbol, use followOn to keep code together
7149 Atom
<A
>* end
= &_endAtoms
[-1];
7150 for(Atom
<A
>* p
= _beginAtoms
; p
< end
; ++p
) {
7151 typename Parser
<A
>::SourceLocation
src(p
, 0);
7152 Atom
<A
>* nextAtom
= &p
[1];
7153 if ( (p
->symbolTableInclusion() == ld::Atom::symbolTableIn
) && (nextAtom
->symbolTableInclusion() == ld::Atom::symbolTableNotIn
) ) {
7154 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindNoneFollowOn
, nextAtom
);
7158 if ( !this->_altEntries
.empty() && !this->addFollowOnFixups() ) {
7159 if ( _altEntries
.count(_beginAtoms
) != 0 )
7160 warning("N_ALT_ENTRY bit set on first atom in section %s/%s", sect
->segname(), Section
<A
>::makeSectionName(sect
));
7162 Atom
<A
>* end
= &_endAtoms
[-1];
7163 for(Atom
<A
>* p
= _beginAtoms
; p
< end
; ++p
) {
7164 Atom
<A
>* nextAtom
= &p
[1];
7165 if ( _altEntries
.count(nextAtom
) != 0 ) {
7166 typename Parser
<A
>::SourceLocation
src(p
, 0);
7167 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindNoneFollowOn
, nextAtom
);
7168 typename Parser
<A
>::SourceLocation
src2(nextAtom
, 0);
7169 parser
.addFixup(src2
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinate
, p
);
7174 // <rdar://problem/9218847> track data-in-code
7175 if ( parser
.hasDataInCodeLabels() && (this->type() == ld::Section::typeCode
) ) {
7176 for (uint32_t i
=0; i
< parser
.symbolCount(); ++i
) {
7177 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(i
);
7179 if ( (sym
.n_type() & N_STAB
) != 0 )
7181 // ignore non-definitions
7182 if ( (sym
.n_type() & N_TYPE
) != N_SECT
)
7185 // 'L' labels do not denote atom breaks
7186 const char* symbolName
= parser
.nameFromSymbol(sym
);
7187 if ( symbolName
[0] == 'L' ) {
7188 if ( strncmp(symbolName
, "L$start$", 8) == 0 ) {
7189 ld::Fixup::Kind kind
= ld::Fixup::kindNone
;
7190 if ( strncmp(&symbolName
[8], "data$", 5) == 0 )
7191 kind
= ld::Fixup::kindDataInCodeStartData
;
7192 else if ( strncmp(&symbolName
[8], "code$", 5) == 0 )
7193 kind
= ld::Fixup::kindDataInCodeEnd
;
7194 else if ( strncmp(&symbolName
[8], "jt8$", 4) == 0 )
7195 kind
= ld::Fixup::kindDataInCodeStartJT8
;
7196 else if ( strncmp(&symbolName
[8], "jt16$", 4) == 0 )
7197 kind
= ld::Fixup::kindDataInCodeStartJT16
;
7198 else if ( strncmp(&symbolName
[8], "jt32$", 4) == 0 )
7199 kind
= ld::Fixup::kindDataInCodeStartJT32
;
7200 else if ( strncmp(&symbolName
[8], "jta32$", 4) == 0 )
7201 kind
= ld::Fixup::kindDataInCodeStartJTA32
;
7203 warning("unknown L$start$ label %s in file %s", symbolName
, this->file().path());
7204 if ( kind
!= ld::Fixup::kindNone
) {
7205 Atom
<A
>* inAtom
= parser
.findAtomByAddress(sym
.n_value());
7206 typename Parser
<A
>::SourceLocation
src(inAtom
, sym
.n_value() - inAtom
->objectAddress());
7207 parser
.addFixup(src
, ld::Fixup::k1of1
, kind
);
7214 // <rdar://problem/11150575> Handle LC_DATA_IN_CODE in object files
7215 if ( this->type() == ld::Section::typeCode
) {
7216 const pint_t startAddr
= this->_machOSection
->addr();
7217 const pint_t endAddr
= startAddr
+ this->_machOSection
->size();
7218 for ( const macho_data_in_code_entry
<P
>* p
= parser
.dataInCodeStart(); p
!= parser
.dataInCodeEnd(); ++p
) {
7219 if ( (p
->offset() >= startAddr
) && (p
->offset() < endAddr
) ) {
7220 ld::Fixup::Kind kind
= ld::Fixup::kindNone
;
7221 switch ( p
->kind() ) {
7222 case DICE_KIND_DATA
:
7223 kind
= ld::Fixup::kindDataInCodeStartData
;
7225 case DICE_KIND_JUMP_TABLE8
:
7226 kind
= ld::Fixup::kindDataInCodeStartJT8
;
7228 case DICE_KIND_JUMP_TABLE16
:
7229 kind
= ld::Fixup::kindDataInCodeStartJT16
;
7231 case DICE_KIND_JUMP_TABLE32
:
7232 kind
= ld::Fixup::kindDataInCodeStartJT32
;
7234 case DICE_KIND_ABS_JUMP_TABLE32
:
7235 kind
= ld::Fixup::kindDataInCodeStartJTA32
;
7238 kind
= ld::Fixup::kindDataInCodeStartData
;
7239 warning("uknown LC_DATA_IN_CODE kind (%d) at offset 0x%08X", p
->kind(), p
->offset());
7242 Atom
<A
>* inAtom
= parser
.findAtomByAddress(p
->offset());
7243 typename Parser
<A
>::SourceLocation
srcStart(inAtom
, p
->offset() - inAtom
->objectAddress());
7244 parser
.addFixup(srcStart
, ld::Fixup::k1of1
, kind
);
7245 typename Parser
<A
>::SourceLocation
srcEnd(inAtom
, p
->offset() + p
->length() - inAtom
->objectAddress());
7246 parser
.addFixup(srcEnd
, ld::Fixup::k1of1
, ld::Fixup::kindDataInCodeEnd
);
7251 // <rdar://problem/11945700> convert linker optimization hints into internal format
7252 if ( this->type() == ld::Section::typeCode
&& parser
.hasOptimizationHints() ) {
7253 const pint_t startAddr
= this->_machOSection
->addr();
7254 const pint_t endAddr
= startAddr
+ this->_machOSection
->size();
7255 for (const uint8_t* p
= parser
.optimizationHintsStart(); p
< parser
.optimizationHintsEnd(); ) {
7257 int32_t kind
= read_uleb128(&p
, parser
.optimizationHintsEnd());
7258 if ( kind
== 0 ) // padding at end of loh buffer
7261 warning("malformed uleb128 kind in LC_LINKER_OPTIMIZATION_HINTS");
7264 int32_t count
= read_uleb128(&p
, parser
.optimizationHintsEnd());
7265 if ( count
== -1 ) {
7266 warning("malformed uleb128 count in LC_LINKER_OPTIMIZATION_HINTS");
7270 warning("address count > 3 in LC_LINKER_OPTIMIZATION_HINTS");
7273 for (int32_t i
=0; i
< count
; ++i
) {
7274 addrs
[i
] = read_uleb128(&p
, parser
.optimizationHintsEnd());
7276 if ( (startAddr
<= addrs
[0]) && (addrs
[0] < endAddr
) ) {
7277 this->addLOH(parser
, kind
, count
, addrs
);
7278 //fprintf(stderr, "kind=%d", kind);
7279 //for (int32_t i=0; i < count; ++i) {
7280 // fprintf(stderr, ", addr=0x%08llX", addrs[i]);
7282 //fprintf(stderr, "\n");
7288 // add follow-on fixups for aliases
7289 if ( _hasAliases
) {
7290 for(Atom
<A
>* p
= _beginAtoms
; p
< _endAtoms
; ++p
) {
7291 if ( p
->isAlias() && ! this->addFollowOnFixups() ) {
7292 Atom
<A
>* targetOfAlias
= &p
[1];
7293 assert(p
< &_endAtoms
[-1]);
7294 assert(p
->_objAddress
== targetOfAlias
->_objAddress
);
7295 typename Parser
<A
>::SourceLocation
src(p
, 0);
7296 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindNoneFollowOn
, targetOfAlias
);
7305 // main function used by linker to instantiate ld::Files
7307 ld::relocatable::File
* parse(const uint8_t* fileContent
, uint64_t fileLength
,
7308 const char* path
, time_t modTime
, ld::File::Ordinal ordinal
, const ParserOptions
& opts
)
7310 switch ( opts
.architecture
) {
7311 #if SUPPORT_ARCH_x86_64
7312 case CPU_TYPE_X86_64
:
7313 if ( mach_o::relocatable::Parser
<x86_64
>::validFile(fileContent
) )
7314 return mach_o::relocatable::Parser
<x86_64
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
);
7317 #if SUPPORT_ARCH_i386
7319 if ( mach_o::relocatable::Parser
<x86
>::validFile(fileContent
) )
7320 return mach_o::relocatable::Parser
<x86
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
);
7323 #if SUPPORT_ARCH_arm_any
7325 if ( mach_o::relocatable::Parser
<arm
>::validFile(fileContent
, opts
.objSubtypeMustMatch
, opts
.subType
) )
7326 return mach_o::relocatable::Parser
<arm
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
);
7329 #if SUPPORT_ARCH_arm64
7330 case CPU_TYPE_ARM64
:
7331 if ( mach_o::relocatable::Parser
<arm64
>::validFile(fileContent
, opts
.objSubtypeMustMatch
, opts
.subType
) )
7332 return mach_o::relocatable::Parser
<arm64
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
);
7340 // used by archive reader to validate member object file
7342 bool isObjectFile(const uint8_t* fileContent
, uint64_t fileLength
, const ParserOptions
& opts
)
7344 switch ( opts
.architecture
) {
7345 case CPU_TYPE_X86_64
:
7346 return ( mach_o::relocatable::Parser
<x86_64
>::validFile(fileContent
) );
7348 return ( mach_o::relocatable::Parser
<x86
>::validFile(fileContent
) );
7350 return ( mach_o::relocatable::Parser
<arm
>::validFile(fileContent
, opts
.objSubtypeMustMatch
, opts
.subType
) );
7351 case CPU_TYPE_ARM64
:
7352 return ( mach_o::relocatable::Parser
<arm64
>::validFile(fileContent
, opts
.objSubtypeMustMatch
, opts
.subType
) );
7358 // used by linker to infer architecture when no -arch is on command line
7360 bool isObjectFile(const uint8_t* fileContent
, cpu_type_t
* result
, cpu_subtype_t
* subResult
)
7362 if ( mach_o::relocatable::Parser
<x86_64
>::validFile(fileContent
) ) {
7363 *result
= CPU_TYPE_X86_64
;
7364 const macho_header
<Pointer64
<LittleEndian
> >* header
= (const macho_header
<Pointer64
<LittleEndian
> >*)fileContent
;
7365 *subResult
= header
->cpusubtype();
7368 if ( mach_o::relocatable::Parser
<x86
>::validFile(fileContent
) ) {
7369 *result
= CPU_TYPE_I386
;
7370 *subResult
= CPU_SUBTYPE_X86_ALL
;
7373 if ( mach_o::relocatable::Parser
<arm
>::validFile(fileContent
, false, 0) ) {
7374 *result
= CPU_TYPE_ARM
;
7375 const macho_header
<Pointer32
<LittleEndian
> >* header
= (const macho_header
<Pointer32
<LittleEndian
> >*)fileContent
;
7376 *subResult
= header
->cpusubtype();
7379 if ( mach_o::relocatable::Parser
<arm64
>::validFile(fileContent
, false, 0) ) {
7380 *result
= CPU_TYPE_ARM64
;
7381 *subResult
= CPU_SUBTYPE_ARM64_ALL
;
7388 // used by linker is error messages to describe bad .o file
7390 const char* archName(const uint8_t* fileContent
)
7392 if ( mach_o::relocatable::Parser
<x86_64
>::validFile(fileContent
) ) {
7393 return mach_o::relocatable::Parser
<x86_64
>::fileKind(fileContent
);
7395 if ( mach_o::relocatable::Parser
<x86
>::validFile(fileContent
) ) {
7396 return mach_o::relocatable::Parser
<x86
>::fileKind(fileContent
);
7398 if ( mach_o::relocatable::Parser
<arm
>::validFile(fileContent
, false, 0) ) {
7399 return mach_o::relocatable::Parser
<arm
>::fileKind(fileContent
);
7405 // Used by archive reader when -ObjC option is specified
7407 bool hasObjC2Categories(const uint8_t* fileContent
)
7409 if ( mach_o::relocatable::Parser
<x86_64
>::validFile(fileContent
) ) {
7410 return mach_o::relocatable::Parser
<x86_64
>::hasObjC2Categories(fileContent
);
7412 else if ( mach_o::relocatable::Parser
<arm
>::validFile(fileContent
, false, 0) ) {
7413 return mach_o::relocatable::Parser
<arm
>::hasObjC2Categories(fileContent
);
7415 else if ( mach_o::relocatable::Parser
<x86
>::validFile(fileContent
, false, 0) ) {
7416 return mach_o::relocatable::Parser
<x86
>::hasObjC2Categories(fileContent
);
7418 #if SUPPORT_ARCH_arm64
7419 else if ( mach_o::relocatable::Parser
<arm64
>::validFile(fileContent
, false, 0) ) {
7420 return mach_o::relocatable::Parser
<arm64
>::hasObjC2Categories(fileContent
);
7427 // Used by archive reader when -ObjC option is specified
7429 bool hasObjC1Categories(const uint8_t* fileContent
)
7431 if ( mach_o::relocatable::Parser
<x86
>::validFile(fileContent
, false, 0) ) {
7432 return mach_o::relocatable::Parser
<x86
>::hasObjC1Categories(fileContent
);
7439 } // namespace relocatable
7440 } // namespace mach_o