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"
45 #include <type_traits>
48 #include "debugline.h"
50 #include "Architectures.hpp"
51 #include "Bitcode.hpp"
53 #include "macho_relocatable_file.h"
57 extern void throwf(const char* format
, ...) __attribute__ ((noreturn
,format(printf
, 1, 2)));
58 extern void warning(const char* format
, ...) __attribute__((format(printf
, 1, 2)));
61 namespace relocatable
{
65 template <typename A
> class Parser
;
66 template <typename A
> class Atom
;
67 template <typename A
> class Section
;
68 template <typename A
> class CFISection
;
69 template <typename A
> class CUSection
;
72 class File
: public ld::relocatable::File
75 File(const char* p
, time_t mTime
, const uint8_t* content
, ld::File::Ordinal ord
) :
76 ld::relocatable::File(p
,mTime
,ord
), _fileContent(content
),
77 _sectionsArray(NULL
), _atomsArray(NULL
),
78 _sectionsArrayCount(0), _atomsArrayCount(0), _aliasAtomsArrayCount(0),
79 _debugInfoKind(ld::relocatable::File::kDebugInfoNone
),
80 _dwarfTranslationUnitPath(NULL
),
81 _dwarfDebugInfoSect(NULL
), _dwarfDebugAbbrevSect(NULL
),
82 _dwarfDebugLineSect(NULL
), _dwarfDebugStringSect(NULL
),
83 _objConstraint(ld::File::objcConstraintNone
),
88 _canScatterAtoms(false),
89 _objcHasCategoryClassPropertiesField(false),
90 _srcKind(kSourceUnknown
) { }
93 // overrides of ld::File
94 virtual bool forEachAtom(ld::File::AtomHandler
&) const;
95 virtual bool justInTimeforEachAtom(const char* name
, ld::File::AtomHandler
&) const
97 virtual uint32_t minOSVersion() const { return _minOSVersion
; }
98 virtual uint32_t platformLoadCommand() const { return _platform
; }
100 // overrides of ld::relocatable::File
101 virtual ObjcConstraint
objCConstraint() const { return _objConstraint
; }
102 virtual bool objcHasCategoryClassPropertiesField() const
103 { return _objcHasCategoryClassPropertiesField
; }
104 virtual uint32_t cpuSubType() const { return _cpuSubType
; }
105 virtual DebugInfoKind
debugInfo() const { return _debugInfoKind
; }
106 virtual const std::vector
<ld::relocatable::File::Stab
>* stabs() const { return &_stabs
; }
107 virtual bool canScatterAtoms() const { return _canScatterAtoms
; }
108 virtual const char* translationUnitSource() const;
109 virtual LinkerOptionsList
* linkerOptions() const { return &_linkerOptions
; }
110 virtual uint8_t swiftVersion() const { return _swiftVersion
; }
111 virtual ld::Bitcode
* getBitcode() const { return _bitcode
.get(); }
112 virtual SourceKind
sourceKind() const { return _srcKind
; }
114 const uint8_t* fileContent() { return _fileContent
; }
116 friend class Atom
<A
>;
117 friend class Section
<A
>;
118 friend class Parser
<A
>;
119 friend class CFISection
<A
>::OAS
;
121 typedef typename
A::P P
;
123 const uint8_t* _fileContent
;
124 Section
<A
>** _sectionsArray
;
125 uint8_t* _atomsArray
;
126 uint8_t* _aliasAtomsArray
;
127 uint32_t _sectionsArrayCount
;
128 uint32_t _atomsArrayCount
;
129 uint32_t _aliasAtomsArrayCount
;
130 std::vector
<ld::Fixup
> _fixups
;
131 std::vector
<ld::Atom::UnwindInfo
> _unwindInfos
;
132 std::vector
<ld::Atom::LineInfo
> _lineInfos
;
133 std::vector
<ld::relocatable::File::Stab
>_stabs
;
134 ld::relocatable::File::DebugInfoKind _debugInfoKind
;
135 const char* _dwarfTranslationUnitPath
;
136 const macho_section
<P
>* _dwarfDebugInfoSect
;
137 const macho_section
<P
>* _dwarfDebugAbbrevSect
;
138 const macho_section
<P
>* _dwarfDebugLineSect
;
139 const macho_section
<P
>* _dwarfDebugStringSect
;
140 ld::File::ObjcConstraint _objConstraint
;
141 uint8_t _swiftVersion
;
142 uint32_t _cpuSubType
;
143 uint32_t _minOSVersion
;
145 bool _canScatterAtoms
;
146 bool _objcHasCategoryClassPropertiesField
;
147 std::vector
<std::vector
<const char*> > _linkerOptions
;
148 std::unique_ptr
<ld::Bitcode
> _bitcode
;
153 template <typename A
>
154 class Section
: public ld::Section
157 typedef typename
A::P::uint_t pint_t
;
158 typedef typename
A::P P
;
159 typedef typename
A::P::E E
;
161 virtual ~Section() { }
162 class File
<A
>& file() const { return _file
; }
163 const macho_section
<P
>* machoSection() const { return _machOSection
; }
164 uint32_t sectionNum(class Parser
<A
>&) const;
165 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
);
166 virtual ld::Atom::ContentType
contentType() { return ld::Atom::typeUnclassified
; }
167 virtual bool dontDeadStrip() { return (this->_machOSection
->flags() & S_ATTR_NO_DEAD_STRIP
); }
168 virtual bool dontDeadStripIfReferencesLive() { return ( (this->_machOSection
!= NULL
) && (this->_machOSection
->flags() & S_ATTR_LIVE_SUPPORT
) ); }
169 virtual Atom
<A
>* findAtomByAddress(pint_t addr
) { return this->findContentAtomByAddress(addr
, this->_beginAtoms
, this->_endAtoms
); }
170 virtual bool addFollowOnFixups() const { return ! _file
.canScatterAtoms(); }
171 virtual uint32_t appendAtoms(class Parser
<A
>& parser
, uint8_t* buffer
,
172 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
173 const struct Parser
<A
>::CFI_CU_InfoArrays
&) = 0;
174 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
,
175 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
176 const struct Parser
<A
>::CFI_CU_InfoArrays
&) = 0;
177 virtual void makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
178 virtual bool addRelocFixup(class Parser
<A
>& parser
, const macho_relocation_info
<P
>*);
179 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const { return 0; }
180 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
181 const ld::IndirectBindingTable
& ind
) const { return false; }
182 virtual bool ignoreLabel(const char* label
) const { return false; }
183 static const char* makeSectionName(const macho_section
<typename
A::P
>* s
);
186 Section(File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
187 : ld::Section(makeSegmentName(s
), makeSectionName(s
), sectionType(s
)),
188 _file(f
), _machOSection(s
), _beginAtoms(NULL
), _endAtoms(NULL
), _hasAliases(false) { }
189 Section(File
<A
>& f
, const char* segName
, const char* sectName
, ld::Section::Type t
, bool hidden
=false)
190 : ld::Section(segName
, sectName
, t
, hidden
), _file(f
), _machOSection(NULL
),
191 _beginAtoms(NULL
), _endAtoms(NULL
), _hasAliases(false) { }
194 Atom
<A
>* findContentAtomByAddress(pint_t addr
, class Atom
<A
>* start
, class Atom
<A
>* end
);
195 uint32_t x86_64PcRelOffset(uint8_t r_type
);
196 void addLOH(class Parser
<A
>& parser
, int kind
, int count
, const uint64_t addrs
[]);
197 static const char* makeSegmentName(const macho_section
<typename
A::P
>* s
);
198 static bool readable(const macho_section
<typename
A::P
>* s
);
199 static bool writable(const macho_section
<typename
A::P
>* s
);
200 static bool exectuable(const macho_section
<typename
A::P
>* s
);
201 static ld::Section::Type
sectionType(const macho_section
<typename
A::P
>* s
);
204 const macho_section
<P
>* _machOSection
;
205 class Atom
<A
>* _beginAtoms
;
206 class Atom
<A
>* _endAtoms
;
208 std::set
<const class Atom
<A
>*> _altEntries
;
212 template <typename A
>
213 class CFISection
: public Section
<A
>
216 CFISection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
217 : Section
<A
>(f
, s
) { }
218 uint32_t cfiCount(Parser
<A
>& parser
);
220 virtual ld::Atom::ContentType
contentType() { return ld::Atom::typeCFI
; }
221 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
222 virtual uint32_t appendAtoms(class Parser
<A
>& parser
, uint8_t* buffer
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
223 virtual void makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
224 virtual bool addFollowOnFixups() const { return false; }
228 /// ObjectFileAddressSpace is used as a template parameter to UnwindCursor for parsing
229 /// dwarf CFI information in an object file.
234 typedef typename
A::P::uint_t pint_t
;
235 typedef typename
A::P P
;
236 typedef typename
A::P::E E
;
237 typedef typename
A::P::uint_t sint_t
;
239 OAS(CFISection
<A
>& ehFrameSection
, const uint8_t* ehFrameBuffer
) :
240 _ehFrameSection(ehFrameSection
),
241 _ehFrameContent(ehFrameBuffer
),
242 _ehFrameStartAddr(ehFrameSection
.machoSection()->addr()),
243 _ehFrameEndAddr(ehFrameSection
.machoSection()->addr()+ehFrameSection
.machoSection()->size()) {}
245 uint8_t get8(pint_t addr
) { return *((uint8_t*)mappedAddress(addr
)); }
246 uint16_t get16(pint_t addr
) { return E::get16(*((uint16_t*)mappedAddress(addr
))); }
247 uint32_t get32(pint_t addr
) { return E::get32(*((uint32_t*)mappedAddress(addr
))); }
248 uint64_t get64(pint_t addr
) { return E::get64(*((uint64_t*)mappedAddress(addr
))); }
249 pint_t
getP(pint_t addr
) { return P::getP(*((pint_t
*)mappedAddress(addr
))); }
250 uint64_t getULEB128(pint_t
& addr
, pint_t end
);
251 int64_t getSLEB128(pint_t
& addr
, pint_t end
);
252 pint_t
getEncodedP(pint_t
& addr
, pint_t end
, uint8_t encoding
);
254 const void* mappedAddress(pint_t addr
);
256 CFISection
<A
>& _ehFrameSection
;
257 const uint8_t* _ehFrameContent
;
258 pint_t _ehFrameStartAddr
;
259 pint_t _ehFrameEndAddr
;
263 typedef typename
A::P::uint_t pint_t
;
264 typedef libunwind::CFI_Atom_Info
<OAS
> CFI_Atom_Info
;
266 void cfiParse(class Parser
<A
>& parser
, uint8_t* buffer
, CFI_Atom_Info cfiArray
[], uint32_t& cfiCount
, const pint_t cuStarts
[], uint32_t cuCount
);
267 bool needsRelocating();
269 static bool bigEndian();
271 void addCiePersonalityFixups(class Parser
<A
>& parser
, const CFI_Atom_Info
* cieInfo
);
272 static void warnFunc(void* ref
, uint64_t funcAddr
, const char* msg
);
276 template <typename A
>
277 class CUSection
: public Section
<A
>
280 CUSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
281 : Section
<A
>(f
, s
) { }
283 typedef typename
A::P::uint_t pint_t
;
284 typedef typename
A::P P
;
285 typedef typename
A::P::E E
;
287 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, const struct Parser
<A
>::CFI_CU_InfoArrays
&) { return 0; }
288 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; }
289 virtual void makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
290 virtual bool addFollowOnFixups() const { return false; }
293 pint_t functionStartAddress
;
294 uint32_t functionSymbolIndex
;
295 uint32_t rangeLength
;
296 uint32_t compactUnwindInfo
;
297 const char* personality
;
304 void parse(class Parser
<A
>& parser
, uint32_t cnt
, Info array
[]);
305 static bool encodingMeansUseDwarf(compact_unwind_encoding_t enc
);
310 const char* personalityName(class Parser
<A
>& parser
, const macho_relocation_info
<P
>* reloc
);
312 static int infoSorter(const void* l
, const void* r
);
317 template <typename A
>
318 class TentativeDefinitionSection
: public Section
<A
>
321 TentativeDefinitionSection(Parser
<A
>& parser
, File
<A
>& f
)
322 : Section
<A
>(f
, "__DATA", "__comm/tent", ld::Section::typeTentativeDefs
) {}
324 virtual ld::Atom::ContentType
contentType() { return ld::Atom::typeZeroFill
; }
325 virtual bool addFollowOnFixups() const { return false; }
326 virtual Atom
<A
>* findAtomByAddress(typename
A::P::uint_t addr
) { throw "TentativeDefinitionSection::findAtomByAddress() should never be called"; }
327 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
328 const struct Parser
<A
>::CFI_CU_InfoArrays
&);
329 virtual uint32_t appendAtoms(class Parser
<A
>& parser
, uint8_t* buffer
,
330 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
331 const struct Parser
<A
>::CFI_CU_InfoArrays
&);
332 virtual void makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&) {}
334 typedef typename
A::P::uint_t pint_t
;
335 typedef typename
A::P P
;
339 template <typename A
>
340 class AbsoluteSymbolSection
: public Section
<A
>
343 AbsoluteSymbolSection(Parser
<A
>& parser
, File
<A
>& f
)
344 : Section
<A
>(f
, "__DATA", "__abs", ld::Section::typeAbsoluteSymbols
, true) {}
346 virtual ld::Atom::ContentType
contentType() { return ld::Atom::typeUnclassified
; }
347 virtual bool dontDeadStrip() { return false; }
348 virtual ld::Atom::Alignment
alignmentForAddress(typename
A::P::uint_t addr
) { return ld::Atom::Alignment(0); }
349 virtual bool addFollowOnFixups() const { return false; }
350 virtual Atom
<A
>* findAtomByAddress(typename
A::P::uint_t addr
) { throw "AbsoluteSymbolSection::findAtomByAddress() should never be called"; }
351 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
352 const struct Parser
<A
>::CFI_CU_InfoArrays
&);
353 virtual uint32_t appendAtoms(class Parser
<A
>& parser
, uint8_t* buffer
,
354 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
355 const struct Parser
<A
>::CFI_CU_InfoArrays
&);
356 virtual void makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&) {}
357 virtual Atom
<A
>* findAbsAtomForValue(typename
A::P::uint_t
);
360 typedef typename
A::P::uint_t pint_t
;
361 typedef typename
A::P P
;
365 template <typename A
>
366 class SymboledSection
: public Section
<A
>
369 SymboledSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
);
370 virtual ld::Atom::ContentType
contentType() { return _type
; }
371 virtual bool dontDeadStrip();
372 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
373 const struct Parser
<A
>::CFI_CU_InfoArrays
&);
374 virtual uint32_t appendAtoms(class Parser
<A
>& parser
, uint8_t* buffer
,
375 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
376 const struct Parser
<A
>::CFI_CU_InfoArrays
&);
378 typedef typename
A::P::uint_t pint_t
;
379 typedef typename
A::P P
;
381 ld::Atom::ContentType _type
;
385 template <typename A
>
386 class TLVDefsSection
: public SymboledSection
<A
>
389 TLVDefsSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
) :
390 SymboledSection
<A
>(parser
, f
, s
) { }
392 typedef typename
A::P::uint_t pint_t
;
394 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(log2(sizeof(pint_t
))); }
401 template <typename A
>
402 class ImplicitSizeSection
: public Section
<A
>
405 ImplicitSizeSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
406 : Section
<A
>(f
, s
) { }
407 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
408 virtual uint32_t appendAtoms(class Parser
<A
>& parser
, uint8_t* buffer
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
410 typedef typename
A::P::uint_t pint_t
;
411 typedef typename
A::P P
;
413 virtual bool addFollowOnFixups() const { return false; }
414 virtual const char* unlabeledAtomName(Parser
<A
>& parser
, pint_t addr
) = 0;
415 virtual ld::Atom::SymbolTableInclusion
symbolTableInclusion();
416 virtual pint_t
elementSizeAtAddress(pint_t addr
) = 0;
417 virtual ld::Atom::Scope
scopeAtAddress(Parser
<A
>& parser
, pint_t addr
) { return ld::Atom::scopeLinkageUnit
; }
418 virtual bool useElementAt(Parser
<A
>& parser
,
419 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, pint_t addr
) = 0;
420 virtual ld::Atom::Definition
definition() { return ld::Atom::definitionRegular
; }
421 virtual ld::Atom::Combine
combine(Parser
<A
>& parser
, pint_t addr
) = 0;
422 virtual bool ignoreLabel(const char* label
) const { return (label
[0] == 'L'); }
426 template <typename A
>
427 class FixedSizeSection
: public ImplicitSizeSection
<A
>
430 FixedSizeSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
431 : ImplicitSizeSection
<A
>(parser
, f
, s
) { }
433 typedef typename
A::P::uint_t pint_t
;
434 typedef typename
A::P P
;
435 typedef typename
A::P::E E
;
437 virtual bool useElementAt(Parser
<A
>& parser
,
438 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, pint_t addr
)
443 template <typename A
>
444 class Literal4Section
: public FixedSizeSection
<A
>
447 Literal4Section(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
448 : FixedSizeSection
<A
>(parser
, f
, s
) {}
450 typedef typename
A::P::uint_t pint_t
;
451 typedef typename
A::P P
;
453 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(2); }
454 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "4-byte-literal"; }
455 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return 4; }
456 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndContent
; }
457 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
458 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
459 const ld::IndirectBindingTable
& ind
) const;
460 virtual bool ignoreLabel(const char* label
) const;
463 template <typename A
>
464 class Literal8Section
: public FixedSizeSection
<A
>
467 Literal8Section(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
468 : FixedSizeSection
<A
>(parser
, f
, s
) {}
470 typedef typename
A::P::uint_t pint_t
;
471 typedef typename
A::P P
;
473 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(3); }
474 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "8-byte-literal"; }
475 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return 8; }
476 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndContent
; }
477 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
478 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
479 const ld::IndirectBindingTable
& ind
) const;
480 virtual bool ignoreLabel(const char* label
) const;
483 template <typename A
>
484 class Literal16Section
: public FixedSizeSection
<A
>
487 Literal16Section(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
488 : FixedSizeSection
<A
>(parser
, f
, s
) {}
490 typedef typename
A::P::uint_t pint_t
;
491 typedef typename
A::P P
;
493 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(4); }
494 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "16-byte-literal"; }
495 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return 16; }
496 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndContent
; }
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;
500 virtual bool ignoreLabel(const char* label
) const;
504 template <typename A
>
505 class NonLazyPointerSection
: public FixedSizeSection
<A
>
508 NonLazyPointerSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
509 : FixedSizeSection
<A
>(parser
, f
, s
) {}
511 typedef typename
A::P::uint_t pint_t
;
512 typedef typename
A::P P
;
514 virtual void makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
515 virtual ld::Atom::ContentType
contentType() { return ld::Atom::typeNonLazyPointer
; }
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 "non_lazy_ptr"; }
518 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return sizeof(pint_t
); }
519 virtual ld::Atom::Scope
scopeAtAddress(Parser
<A
>& parser
, pint_t addr
);
520 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
);
521 virtual bool ignoreLabel(const char* label
) const { return true; }
522 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
523 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
524 const ld::IndirectBindingTable
& ind
) const;
527 static const char* targetName(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
);
528 static ld::Fixup::Kind
fixupKind();
531 template <typename A
>
532 class TLVPointerSection
: public FixedSizeSection
<A
>
535 TLVPointerSection(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
;
541 virtual void makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
542 virtual ld::Atom::ContentType
contentType() { return ld::Atom::typeTLVPointer
; }
543 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(log2(sizeof(pint_t
))); }
544 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "tlv_lazy_ptr"; }
545 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return sizeof(pint_t
); }
546 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
);
547 virtual bool ignoreLabel(const char* label
) const { return true; }
548 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
549 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
550 const ld::IndirectBindingTable
& ind
) const;
553 static const char* targetName(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
, bool* isStatic
);
557 template <typename A
>
558 class CFStringSection
: public FixedSizeSection
<A
>
561 CFStringSection(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 "CFString"; }
568 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return 4*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 enum ContentType
{ contentUTF8
, contentUTF16
, contentUnknown
};
576 static const uint8_t* targetContent(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
,
577 ContentType
* ct
, unsigned int* count
);
581 template <typename A
>
582 class ObjC1ClassSection
: public FixedSizeSection
<A
>
585 ObjC1ClassSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
586 : FixedSizeSection
<A
>(parser
, f
, s
) {}
588 typedef typename
A::P::uint_t pint_t
;
589 typedef typename
A::P P
;
590 typedef typename
A::P::E E
;
592 virtual ld::Atom::Scope
scopeAtAddress(Parser
<A
>& , pint_t
) { return ld::Atom::scopeGlobal
; }
593 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(2); }
594 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
);
595 virtual ld::Atom::SymbolTableInclusion
symbolTableInclusion() { return ld::Atom::symbolTableIn
; }
596 virtual pint_t
elementSizeAtAddress(pint_t addr
);
597 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineNever
; }
598 virtual bool ignoreLabel(const char* label
) const { return true; }
599 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
601 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
602 const ld::IndirectBindingTable
& ind
) const { return false; }
603 virtual bool addRelocFixup(class Parser
<A
>& parser
, const macho_relocation_info
<P
>*);
607 template <typename A
>
608 class ObjC2ClassRefsSection
: public FixedSizeSection
<A
>
611 ObjC2ClassRefsSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
612 : FixedSizeSection
<A
>(parser
, f
, s
) {}
614 typedef typename
A::P::uint_t pint_t
;
616 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(log2(sizeof(pint_t
))); }
617 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "objc-class-ref"; }
618 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return sizeof(pint_t
); }
619 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndReferences
; }
620 virtual bool ignoreLabel(const char* label
) const { return true; }
621 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
622 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
623 const ld::IndirectBindingTable
& ind
) const;
625 const char* targetClassName(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
629 template <typename A
>
630 class ObjC2CategoryListSection
: public FixedSizeSection
<A
>
633 ObjC2CategoryListSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
634 : FixedSizeSection
<A
>(parser
, f
, s
) {}
636 typedef typename
A::P::uint_t pint_t
;
638 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(log2(sizeof(pint_t
))); }
639 virtual ld::Atom::Scope
scopeAtAddress(Parser
<A
>& parser
, pint_t addr
) { return ld::Atom::scopeTranslationUnit
; }
640 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "objc-cat-list"; }
641 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return sizeof(pint_t
); }
642 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineNever
; }
643 virtual bool ignoreLabel(const char* label
) const { return true; }
645 const char* targetClassName(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
649 template <typename A
>
650 class PointerToCStringSection
: public FixedSizeSection
<A
>
653 PointerToCStringSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
654 : FixedSizeSection
<A
>(parser
, f
, s
) {}
656 typedef typename
A::P::uint_t pint_t
;
658 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(log2(sizeof(pint_t
))); }
659 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "pointer-to-literal-cstring"; }
660 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return sizeof(pint_t
); }
661 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndReferences
; }
662 virtual bool ignoreLabel(const char* label
) const { return true; }
663 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
664 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
665 const ld::IndirectBindingTable
& ind
) const;
666 virtual const char* targetCString(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
670 template <typename A
>
671 class Objc1ClassReferences
: public PointerToCStringSection
<A
>
674 Objc1ClassReferences(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
675 : PointerToCStringSection
<A
>(parser
, f
, s
) {}
677 typedef typename
A::P::uint_t pint_t
;
678 typedef typename
A::P P
;
680 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "pointer-to-literal-objc-class-name"; }
681 virtual bool addRelocFixup(class Parser
<A
>& parser
, const macho_relocation_info
<P
>*);
682 virtual const char* targetCString(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
686 template <typename A
>
687 class CStringSection
: public ImplicitSizeSection
<A
>
690 CStringSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
691 : ImplicitSizeSection
<A
>(parser
, f
, s
) {}
693 typedef typename
A::P::uint_t pint_t
;
694 typedef typename
A::P P
;
696 virtual ld::Atom::ContentType
contentType() { return ld::Atom::typeCString
; }
697 virtual Atom
<A
>* findAtomByAddress(pint_t addr
);
698 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "cstring"; }
699 virtual pint_t
elementSizeAtAddress(pint_t addr
);
700 virtual bool ignoreLabel(const char* label
) const;
701 virtual bool useElementAt(Parser
<A
>& parser
,
702 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, pint_t addr
);
703 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndContent
; }
704 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
705 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
706 const ld::IndirectBindingTable
& ind
) const;
711 template <typename A
>
712 class UTF16StringSection
: public SymboledSection
<A
>
715 UTF16StringSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
716 : SymboledSection
<A
>(parser
, f
, s
) {}
718 typedef typename
A::P::uint_t pint_t
;
719 typedef typename
A::P P
;
721 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndContent
; }
722 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
723 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
724 const ld::IndirectBindingTable
& ind
) const;
729 // Atoms in mach-o files
731 template <typename A
>
732 class Atom
: public ld::Atom
735 // overrides of ld::Atom
736 virtual const ld::File
* file() const;
737 virtual const char* translationUnitSource() const
738 { return sect().file().translationUnitSource(); }
739 virtual const char* name() const { return _name
; }
740 virtual uint64_t size() const { return _size
; }
741 virtual uint64_t objectAddress() const { return _objAddress
; }
742 virtual void copyRawContent(uint8_t buffer
[]) const;
743 virtual const uint8_t* rawContentPointer() const { return contentPointer(); }
744 virtual unsigned long contentHash(const ld::IndirectBindingTable
& ind
) const
745 { if ( _hash
== 0 ) _hash
= sect().contentHash(this, ind
); return _hash
; }
746 virtual bool canCoalesceWith(const ld::Atom
& rhs
, const ld::IndirectBindingTable
& ind
) const
747 { return sect().canCoalesceWith(this, rhs
, ind
); }
748 virtual ld::Fixup::iterator
fixupsBegin() const { return &machofile()._fixups
[_fixupsStartIndex
]; }
749 virtual ld::Fixup::iterator
fixupsEnd() const { return &machofile()._fixups
[_fixupsStartIndex
+_fixupsCount
]; }
750 virtual ld::Atom::UnwindInfo::iterator
beginUnwind() const { return &machofile()._unwindInfos
[_unwindInfoStartIndex
]; }
751 virtual ld::Atom::UnwindInfo::iterator
endUnwind() const { return &machofile()._unwindInfos
[_unwindInfoStartIndex
+_unwindInfoCount
]; }
752 virtual ld::Atom::LineInfo::iterator
beginLineInfo() const{ return &machofile()._lineInfos
[_lineInfoStartIndex
]; }
753 virtual ld::Atom::LineInfo::iterator
endLineInfo() const { return &machofile()._lineInfos
[_lineInfoStartIndex
+_lineInfoCount
]; }
754 virtual void setFile(const ld::File
* f
);
758 enum { kFixupStartIndexBits
= 32,
759 kLineInfoStartIndexBits
= 32,
760 kUnwindInfoStartIndexBits
= 24,
761 kFixupCountBits
= 24,
762 kLineInfoCountBits
= 12,
763 kUnwindInfoCountBits
= 4
764 }; // must sum to 128
767 // methods for all atoms from mach-o object file
768 Section
<A
>& sect() const { return (Section
<A
>&)section(); }
769 File
<A
>& machofile() const { return ((Section
<A
>*)(this->_section
))->file(); }
770 void setFixupsRange(uint32_t s
, uint32_t c
);
771 void setUnwindInfoRange(uint32_t s
, uint32_t c
);
772 void extendUnwindInfoRange();
773 void setLineInfoRange(uint32_t s
, uint32_t c
);
774 bool roomForMoreLineInfoCount() { return (_lineInfoCount
< ((1<<kLineInfoCountBits
)-1)); }
775 void incrementLineInfoCount() { assert(roomForMoreLineInfoCount()); ++_lineInfoCount
; }
776 void incrementFixupCount() { if (_fixupsCount
== ((1 << kFixupCountBits
)-1))
777 throwf("too may fixups in %s", name()); ++_fixupsCount
; }
778 const uint8_t* contentPointer() const;
779 uint32_t fixupCount() const { return _fixupsCount
; }
780 void verifyAlignment(const macho_section
<typename
A::P
>&) const;
782 typedef typename
A::P P
;
783 typedef typename
A::P::E E
;
784 typedef typename
A::P::uint_t pint_t
;
785 // constuct via all attributes
786 Atom(Section
<A
>& sct
, const char* nm
, pint_t addr
, uint64_t sz
,
787 ld::Atom::Definition d
, ld::Atom::Combine c
, ld::Atom::Scope s
,
788 ld::Atom::ContentType ct
, ld::Atom::SymbolTableInclusion i
,
789 bool dds
, bool thumb
, bool al
, ld::Atom::Alignment a
)
790 : ld::Atom((ld::Section
&)sct
, d
, c
, s
, ct
, i
, dds
, thumb
, al
, a
),
791 _size(sz
), _objAddress(addr
), _name(nm
), _hash(0),
792 _fixupsStartIndex(0), _lineInfoStartIndex(0),
793 _unwindInfoStartIndex(0), _fixupsCount(0),
794 _lineInfoCount(0), _unwindInfoCount(0) { }
795 // construct via symbol table entry
796 Atom(Section
<A
>& sct
, Parser
<A
>& parser
, const macho_nlist
<P
>& sym
,
797 uint64_t sz
, bool alias
=false)
798 : ld::Atom((ld::Section
&)sct
, parser
.definitionFromSymbol(sym
),
799 parser
.combineFromSymbol(sym
), parser
.scopeFromSymbol(sym
),
800 parser
.resolverFromSymbol(sym
) ? ld::Atom::typeResolver
: sct
.contentType(),
801 parser
.inclusionFromSymbol(sym
),
802 (parser
.dontDeadStripFromSymbol(sym
) && !sct
.dontDeadStripIfReferencesLive()) || sct
.dontDeadStrip(),
803 parser
.isThumbFromSymbol(sym
), alias
,
804 sct
.alignmentForAddress(sym
.n_value())),
805 _size(sz
), _objAddress(sym
.n_value()),
806 _name(parser
.nameFromSymbol(sym
)), _hash(0),
807 _fixupsStartIndex(0), _lineInfoStartIndex(0),
808 _unwindInfoStartIndex(0), _fixupsCount(0),
809 _lineInfoCount(0), _unwindInfoCount(0) {
810 // <rdar://problem/6783167> support auto-hidden weak symbols
811 if ( _scope
== ld::Atom::scopeGlobal
&&
812 (sym
.n_desc() & (N_WEAK_DEF
|N_WEAK_REF
)) == (N_WEAK_DEF
|N_WEAK_REF
) )
814 this->verifyAlignment(*sct
.machoSection());
815 if ( sct
.dontDeadStripIfReferencesLive() )
816 this->setDontDeadStripIfReferencesLive();
820 friend class Parser
<A
>;
821 friend class Section
<A
>;
822 friend class CStringSection
<A
>;
823 friend class AbsoluteSymbolSection
<A
>;
828 mutable unsigned long _hash
;
830 uint64_t _fixupsStartIndex
: kFixupStartIndexBits
,
831 _lineInfoStartIndex
: kLineInfoStartIndexBits
,
832 _unwindInfoStartIndex
: kUnwindInfoStartIndexBits
,
833 _fixupsCount
: kFixupCountBits
,
834 _lineInfoCount
: kLineInfoCountBits
,
835 _unwindInfoCount
: kUnwindInfoCountBits
;
837 static std::map
<const ld::Atom
*, const ld::File
*> _s_fileOverride
;
840 template <typename A
>
841 std::map
<const ld::Atom
*, const ld::File
*> Atom
<A
>::_s_fileOverride
;
843 template <typename A
>
844 void Atom
<A
>::setFile(const ld::File
* f
) {
845 _s_fileOverride
[this] = f
;
848 template <typename A
>
849 const ld::File
* Atom
<A
>::file() const
851 std::map
<const ld::Atom
*, const ld::File
*>::iterator pos
= _s_fileOverride
.find(this);
852 if ( pos
!= _s_fileOverride
.end() )
855 return §().file();
858 template <typename A
>
859 void Atom
<A
>::setFixupsRange(uint32_t startIndex
, uint32_t count
)
861 if ( count
>= (1 << kFixupCountBits
) )
862 throwf("too many fixups in function %s", this->name());
863 if ( startIndex
>= (1 << kFixupStartIndexBits
) )
864 throwf("too many fixups in file");
865 assert(((startIndex
+count
) <= sect().file()._fixups
.size()) && "fixup index out of range");
866 _fixupsStartIndex
= startIndex
;
867 _fixupsCount
= count
;
870 template <typename A
>
871 void Atom
<A
>::setUnwindInfoRange(uint32_t startIndex
, uint32_t count
)
873 if ( count
>= (1 << kUnwindInfoCountBits
) )
874 throwf("too many compact unwind infos in function %s", this->name());
875 if ( startIndex
>= (1 << kUnwindInfoStartIndexBits
) )
876 throwf("too many compact unwind infos (%d) in file", startIndex
);
877 assert((startIndex
+count
) <= sect().file()._unwindInfos
.size() && "unwindinfo index out of range");
878 _unwindInfoStartIndex
= startIndex
;
879 _unwindInfoCount
= count
;
882 template <typename A
>
883 void Atom
<A
>::extendUnwindInfoRange()
885 if ( _unwindInfoCount
+1 >= (1 << kUnwindInfoCountBits
) )
886 throwf("too many compact unwind infos in function %s", this->name());
887 _unwindInfoCount
+= 1;
890 template <typename A
>
891 void Atom
<A
>::setLineInfoRange(uint32_t startIndex
, uint32_t count
)
893 assert((count
< (1 << kLineInfoCountBits
)) && "too many line infos");
894 assert((startIndex
+count
) < sect().file()._lineInfos
.size() && "line info index out of range");
895 _lineInfoStartIndex
= startIndex
;
896 _lineInfoCount
= count
;
899 template <typename A
>
900 const uint8_t* Atom
<A
>::contentPointer() const
902 const macho_section
<P
>* sct
= this->sect().machoSection();
903 if ( this->_objAddress
> sct
->addr() + sct
->size() )
904 throwf("malformed .o file, symbol has address 0x%0llX which is outside range of its section", (uint64_t)this->_objAddress
);
905 uint32_t fileOffset
= sct
->offset() - sct
->addr() + this->_objAddress
;
906 return this->sect().file().fileContent()+fileOffset
;
910 template <typename A
>
911 void Atom
<A
>::copyRawContent(uint8_t buffer
[]) const
914 if ( this->contentType() == ld::Atom::typeZeroFill
) {
915 bzero(buffer
, _size
);
917 else if ( _size
!= 0 ) {
918 memcpy(buffer
, this->contentPointer(), _size
);
923 void Atom
<arm
>::verifyAlignment(const macho_section
<P
>&) const
925 if ( (this->section().type() == ld::Section::typeCode
) && ! isThumb() ) {
926 if ( ((_objAddress
% 4) != 0) || (this->alignment().powerOf2
< 2) )
927 warning("ARM function not 4-byte aligned: %s from %s", this->name(), this->file()->path());
931 #if SUPPORT_ARCH_arm64
933 void Atom
<arm64
>::verifyAlignment(const macho_section
<P
>& sect
) const
935 if ( (this->section().type() == ld::Section::typeCode
) && (sect
.size() != 0) ) {
936 if ( ((_objAddress
% 4) != 0) || (this->alignment().powerOf2
< 2) )
937 warning("arm64 function not 4-byte aligned: %s from %s", this->name(), this->file()->path());
943 template <typename A
>
944 void Atom
<A
>::verifyAlignment(const macho_section
<P
>&) const
949 class AliasAtom
: public ld::Atom
952 AliasAtom(const char* name
, bool hidden
, const ld::File
* file
, const char* aliasOfName
) :
953 ld::Atom(_s_section
, ld::Atom::definitionRegular
, ld::Atom::combineNever
,
954 (hidden
? ld::Atom::scopeLinkageUnit
: ld::Atom::scopeGlobal
),
955 ld::Atom::typeUnclassified
, ld::Atom::symbolTableIn
,
956 false, false, true, 0),
959 _fixup(0, ld::Fixup::k1of1
, ld::Fixup::kindNoneFollowOn
, ld::Fixup::bindingByNameUnbound
, aliasOfName
) { }
961 virtual const ld::File
* file() const { return _file
; }
962 virtual const char* translationUnitSource() const
964 virtual const char* name() const { return _name
; }
965 virtual uint64_t size() const { return 0; }
966 virtual uint64_t objectAddress() const { return 0; }
967 virtual void copyRawContent(uint8_t buffer
[]) const { }
968 virtual ld::Fixup::iterator
fixupsBegin() const { return &((ld::Fixup
*)&_fixup
)[0]; }
969 virtual ld::Fixup::iterator
fixupsEnd() const { return &((ld::Fixup
*)&_fixup
)[1]; }
972 static ld::Section _s_section
;
974 const ld::File
* _file
;
979 ld::Section
AliasAtom::_s_section("__LD", "__aliases", ld::Section::typeTempAlias
, true);
982 template <typename A
>
986 static bool validFile(const uint8_t* fileContent
, bool subtypeMustMatch
=false,
987 cpu_subtype_t subtype
=0);
988 static const char* fileKind(const uint8_t* fileContent
);
989 static Options::Platform
findPlatform(const macho_header
<typename
A::P
>* header
);
990 static bool hasObjC2Categories(const uint8_t* fileContent
);
991 static bool hasObjC1Categories(const uint8_t* fileContent
);
992 static bool getNonLocalSymbols(const uint8_t* fileContnet
, std::vector
<const char*> &syms
);
993 static ld::relocatable::File
* parse(const uint8_t* fileContent
, uint64_t fileLength
,
994 const char* path
, time_t modTime
, ld::File::Ordinal ordinal
,
995 const ParserOptions
& opts
) {
996 Parser
p(fileContent
, fileLength
, path
, modTime
,
997 ordinal
, opts
.warnUnwindConversionProblems
,
998 opts
.keepDwarfUnwind
, opts
.forceDwarfConversion
,
999 opts
.neverConvertDwarf
, opts
.verboseOptimizationHints
,
1000 opts
.ignoreMismatchPlatform
);
1001 return p
.parse(opts
);
1004 typedef typename
A::P P
;
1005 typedef typename
A::P::E E
;
1006 typedef typename
A::P::uint_t pint_t
;
1008 struct SourceLocation
{
1010 SourceLocation(Atom
<A
>* a
, uint32_t o
) : atom(a
), offsetInAtom(o
) {}
1012 uint32_t offsetInAtom
;
1017 const char* name
; // only used if targetAtom is NULL
1019 bool weakImport
; // only used if targetAtom is NULL
1022 struct FixupInAtom
{
1023 FixupInAtom(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, Atom
<A
>* target
) :
1024 fixup(src
.offsetInAtom
, c
, k
, target
), atom(src
.atom
) { src
.atom
->incrementFixupCount(); }
1026 FixupInAtom(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, ld::Fixup::TargetBinding b
, Atom
<A
>* target
) :
1027 fixup(src
.offsetInAtom
, c
, k
, b
, target
), atom(src
.atom
) { src
.atom
->incrementFixupCount(); }
1029 FixupInAtom(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, bool wi
, const char* name
) :
1030 fixup(src
.offsetInAtom
, c
, k
, wi
, name
), atom(src
.atom
) { src
.atom
->incrementFixupCount(); }
1032 FixupInAtom(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, ld::Fixup::TargetBinding b
, const char* name
) :
1033 fixup(src
.offsetInAtom
, c
, k
, b
, name
), atom(src
.atom
) { src
.atom
->incrementFixupCount(); }
1035 FixupInAtom(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, uint64_t addend
) :
1036 fixup(src
.offsetInAtom
, c
, k
, addend
), atom(src
.atom
) { src
.atom
->incrementFixupCount(); }
1038 FixupInAtom(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
) :
1039 fixup(src
.offsetInAtom
, c
, k
, (uint64_t)0), atom(src
.atom
) { src
.atom
->incrementFixupCount(); }
1045 void addFixup(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, Atom
<A
>* target
) {
1046 _allFixups
.push_back(FixupInAtom(src
, c
, k
, target
));
1049 void addFixup(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, ld::Fixup::TargetBinding b
, Atom
<A
>* target
) {
1050 _allFixups
.push_back(FixupInAtom(src
, c
, k
, b
, target
));
1053 void addFixup(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, bool wi
, const char* name
) {
1054 _allFixups
.push_back(FixupInAtom(src
, c
, k
, wi
, name
));
1057 void addFixup(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, ld::Fixup::TargetBinding b
, const char* name
) {
1058 _allFixups
.push_back(FixupInAtom(src
, c
, k
, b
, name
));
1061 void addFixup(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, uint64_t addend
) {
1062 _allFixups
.push_back(FixupInAtom(src
, c
, k
, addend
));
1065 void addFixup(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
) {
1066 _allFixups
.push_back(FixupInAtom(src
, c
, k
));
1069 const char* path() { return _path
; }
1070 uint32_t symbolCount() { return _symbolCount
; }
1071 uint32_t indirectSymbol(uint32_t indirectIndex
);
1072 const macho_nlist
<P
>& symbolFromIndex(uint32_t index
);
1073 const char* nameFromSymbol(const macho_nlist
<P
>& sym
);
1074 ld::Atom::Scope
scopeFromSymbol(const macho_nlist
<P
>& sym
);
1075 static ld::Atom::Definition
definitionFromSymbol(const macho_nlist
<P
>& sym
);
1076 static ld::Atom::Combine
combineFromSymbol(const macho_nlist
<P
>& sym
);
1077 ld::Atom::SymbolTableInclusion
inclusionFromSymbol(const macho_nlist
<P
>& sym
);
1078 static bool dontDeadStripFromSymbol(const macho_nlist
<P
>& sym
);
1079 static bool isThumbFromSymbol(const macho_nlist
<P
>& sym
);
1080 static bool weakImportFromSymbol(const macho_nlist
<P
>& sym
);
1081 static bool resolverFromSymbol(const macho_nlist
<P
>& sym
);
1082 static bool altEntryFromSymbol(const macho_nlist
<P
>& sym
);
1083 uint32_t symbolIndexFromIndirectSectionAddress(pint_t
,const macho_section
<P
>*);
1084 const macho_section
<P
>* firstMachOSection() { return _sectionsStart
; }
1085 const macho_section
<P
>* machOSectionFromSectionIndex(uint32_t index
);
1086 uint32_t machOSectionCount() { return _machOSectionsCount
; }
1087 uint32_t undefinedStartIndex() { return _undefinedStartIndex
; }
1088 uint32_t undefinedEndIndex() { return _undefinedEndIndex
; }
1089 void addFixup(FixupInAtom f
) { _allFixups
.push_back(f
); }
1090 Section
<A
>* sectionForNum(unsigned int sectNum
);
1091 Section
<A
>* sectionForAddress(pint_t addr
);
1092 Atom
<A
>* findAtomByAddress(pint_t addr
);
1093 Atom
<A
>* findAtomByAddressOrNullIfStub(pint_t addr
);
1094 Atom
<A
>* findAtomByAddressOrLocalTargetOfStub(pint_t addr
, uint32_t* offsetInAtom
);
1095 Atom
<A
>* findAtomByName(const char* name
); // slow!
1096 void findTargetFromAddress(pint_t addr
, TargetDesc
& target
);
1097 void findTargetFromAddress(pint_t baseAddr
, pint_t addr
, TargetDesc
& target
);
1098 void findTargetFromAddressAndSectionNum(pint_t addr
, unsigned int sectNum
,
1099 TargetDesc
& target
);
1100 uint32_t tentativeDefinitionCount() { return _tentativeDefinitionCount
; }
1101 uint32_t absoluteSymbolCount() { return _absoluteSymbolCount
; }
1103 uint32_t fileLength() const { return _fileLength
; }
1104 bool hasStubsSection() { return (_stubsSectionNum
!= 0); }
1105 unsigned int stubsSectionNum() { return _stubsSectionNum
; }
1106 void addDtraceExtraInfos(const SourceLocation
& src
, const char* provider
);
1107 const char* scanSymbolTableForAddress(uint64_t addr
);
1108 bool warnUnwindConversionProblems() { return _warnUnwindConversionProblems
; }
1109 bool hasDataInCodeLabels() { return _hasDataInCodeLabels
; }
1110 bool keepDwarfUnwind() { return _keepDwarfUnwind
; }
1111 bool forceDwarfConversion() { return _forceDwarfConversion
; }
1112 bool verboseOptimizationHints() { return _verboseOptimizationHints
; }
1113 bool neverConvertDwarf() { return _neverConvertDwarf
; }
1114 bool armUsesZeroCostExceptions() { return _armUsesZeroCostExceptions
; }
1115 uint8_t maxDefaultCommonAlignment() { return _maxDefaultCommonAlignment
; }
1118 macho_data_in_code_entry
<P
>* dataInCodeStart() { return _dataInCodeStart
; }
1119 macho_data_in_code_entry
<P
>* dataInCodeEnd() { return _dataInCodeEnd
; }
1120 const uint8_t* optimizationHintsStart() { return _lohStart
; }
1121 const uint8_t* optimizationHintsEnd() { return _lohEnd
; }
1122 bool hasOptimizationHints() { return _lohStart
!= _lohEnd
; }
1125 void addFixups(const SourceLocation
& src
, ld::Fixup::Kind kind
, const TargetDesc
& target
);
1126 void addFixups(const SourceLocation
& src
, ld::Fixup::Kind kind
, const TargetDesc
& target
, const TargetDesc
& picBase
);
1130 struct LabelAndCFIBreakIterator
{
1131 typedef typename CFISection
<A
>::CFI_Atom_Info CFI_Atom_Info
;
1132 LabelAndCFIBreakIterator(const uint32_t* ssa
, uint32_t ssc
, const pint_t
* cfisa
,
1133 uint32_t cfisc
, bool ols
)
1134 : sortedSymbolIndexes(ssa
), sortedSymbolCount(ssc
), cfiStartsArray(cfisa
),
1135 cfiStartsCount(cfisc
), fileHasOverlappingSymbols(ols
),
1136 newSection(false), cfiIndex(0), symIndex(0) {}
1137 bool next(Parser
<A
>& parser
, const Section
<A
>& sect
, uint32_t sectNum
, pint_t startAddr
, pint_t endAddr
,
1138 pint_t
* addr
, pint_t
* size
, const macho_nlist
<P
>** sym
);
1139 pint_t
peek(Parser
<A
>& parser
, pint_t startAddr
, pint_t endAddr
);
1140 void beginSection() { newSection
= true; symIndex
= 0; }
1142 const uint32_t* const sortedSymbolIndexes
;
1143 const uint32_t sortedSymbolCount
;
1144 const pint_t
* cfiStartsArray
;
1145 const uint32_t cfiStartsCount
;
1146 const bool fileHasOverlappingSymbols
;
1152 struct CFI_CU_InfoArrays
{
1153 typedef typename CFISection
<A
>::CFI_Atom_Info CFI_Atom_Info
;
1154 typedef typename CUSection
<A
>::Info CU_Info
;
1155 CFI_CU_InfoArrays(const CFI_Atom_Info
* cfiAr
, uint32_t cfiC
, CU_Info
* cuAr
, uint32_t cuC
)
1156 : cfiArray(cfiAr
), cuArray(cuAr
), cfiCount(cfiC
), cuCount(cuC
) {}
1157 const CFI_Atom_Info
* const cfiArray
;
1158 CU_Info
* const cuArray
;
1159 const uint32_t cfiCount
;
1160 const uint32_t cuCount
;
1166 friend class Section
<A
>;
1168 enum SectionType
{ sectionTypeIgnore
, sectionTypeLiteral4
, sectionTypeLiteral8
, sectionTypeLiteral16
,
1169 sectionTypeNonLazy
, sectionTypeCFI
, sectionTypeCString
, sectionTypeCStringPointer
,
1170 sectionTypeUTF16Strings
, sectionTypeCFString
, sectionTypeObjC2ClassRefs
, typeObjC2CategoryList
,
1171 sectionTypeObjC1Classes
, sectionTypeSymboled
, sectionTypeObjC1ClassRefs
,
1172 sectionTypeTentativeDefinitions
, sectionTypeAbsoluteSymbols
, sectionTypeTLVDefs
,
1173 sectionTypeCompactUnwind
, sectionTypeTLVPointers
};
1175 template <typename P
>
1176 struct MachOSectionAndSectionClass
1178 const macho_section
<P
>* sect
;
1181 static int sorter(const void* l
, const void* r
) {
1182 const MachOSectionAndSectionClass
<P
>* left
= (MachOSectionAndSectionClass
<P
>*)l
;
1183 const MachOSectionAndSectionClass
<P
>* right
= (MachOSectionAndSectionClass
<P
>*)r
;
1184 int64_t diff
= left
->sect
->addr() - right
->sect
->addr();
1194 struct ParserAndSectionsArray
{ Parser
* parser
; const uint32_t* sortedSectionsArray
; };
1197 Parser(const uint8_t* fileContent
, uint64_t fileLength
,
1198 const char* path
, time_t modTime
, ld::File::Ordinal ordinal
,
1199 bool warnUnwindConversionProblems
, bool keepDwarfUnwind
,
1200 bool forceDwarfConversion
, bool neverConvertDwarf
,
1201 bool verboseOptimizationHints
, bool ignoreMismatchPlatform
);
1202 ld::relocatable::File
* parse(const ParserOptions
& opts
);
1203 static uint8_t loadCommandSizeMask();
1204 bool parseLoadCommands(Options::Platform platform
, uint32_t minOSVersion
, bool simulator
, bool ignoreMismatchPlatform
);
1205 void makeSections();
1206 void prescanSymbolTable();
1207 void makeSortedSymbolsArray(uint32_t symArray
[], const uint32_t sectionArray
[]);
1208 void makeSortedSectionsArray(uint32_t array
[]);
1209 static int pointerSorter(const void* l
, const void* r
);
1210 static int symbolIndexSorter(void* extra
, const void* l
, const void* r
);
1211 static int sectionIndexSorter(void* extra
, const void* l
, const void* r
);
1213 void parseDebugInfo();
1215 void appendAliasAtoms(uint8_t* atomBuffer
);
1216 static bool isConstFunStabs(const char *stabStr
);
1217 bool read_comp_unit(const char ** name
, const char ** comp_dir
,
1218 uint64_t *stmt_list
);
1219 pint_t
realAddr(pint_t addr
);
1220 const char* getDwarfString(uint64_t form
, const uint8_t*& p
);
1221 uint64_t getDwarfOffset(uint64_t form
, const uint8_t*& di
, bool dwarf64
);
1222 bool skip_form(const uint8_t ** offset
, const uint8_t * end
,
1223 uint64_t form
, uint8_t addr_size
, bool dwarf64
);
1226 // filled in by constructor
1227 const uint8_t* _fileContent
;
1228 uint32_t _fileLength
;
1231 ld::File::Ordinal _ordinal
;
1233 // filled in by parseLoadCommands()
1235 const macho_nlist
<P
>* _symbols
;
1236 uint32_t _symbolCount
;
1237 uint32_t _indirectSymbolCount
;
1238 const char* _strings
;
1239 uint32_t _stringsSize
;
1240 const uint32_t* _indirectTable
;
1241 uint32_t _indirectTableCount
;
1242 uint32_t _undefinedStartIndex
;
1243 uint32_t _undefinedEndIndex
;
1244 const macho_section
<P
>* _sectionsStart
;
1245 uint32_t _machOSectionsCount
;
1247 macho_data_in_code_entry
<P
>* _dataInCodeStart
;
1248 macho_data_in_code_entry
<P
>* _dataInCodeEnd
;
1249 const uint8_t* _lohStart
;
1250 const uint8_t* _lohEnd
;
1252 // filled in by parse()
1253 CFISection
<A
>* _EHFrameSection
;
1254 CUSection
<A
>* _compactUnwindSection
;
1255 AbsoluteSymbolSection
<A
>* _absoluteSection
;
1256 uint32_t _tentativeDefinitionCount
;
1257 uint32_t _absoluteSymbolCount
;
1258 uint32_t _symbolsInSections
;
1259 bool _hasLongBranchStubs
;
1260 bool _AppleObjc
; // FSF has objc that uses different data layout
1261 bool _overlappingSymbols
;
1262 bool _warnUnwindConversionProblems
;
1263 bool _hasDataInCodeLabels
;
1264 bool _keepDwarfUnwind
;
1265 bool _forceDwarfConversion
;
1266 bool _neverConvertDwarf
;
1267 bool _verboseOptimizationHints
;
1268 bool _armUsesZeroCostExceptions
;
1269 bool _ignoreMismatchPlatform
;
1270 bool _treateBitcodeAsData
;
1272 uint8_t _maxDefaultCommonAlignment
;
1273 unsigned int _stubsSectionNum
;
1274 const macho_section
<P
>* _stubsMachOSection
;
1275 std::vector
<const char*> _dtraceProviderInfo
;
1276 std::vector
<FixupInAtom
> _allFixups
;
1281 template <typename A
>
1282 Parser
<A
>::Parser(const uint8_t* fileContent
, uint64_t fileLength
, const char* path
, time_t modTime
,
1283 ld::File::Ordinal ordinal
, bool convertDUI
, bool keepDwarfUnwind
, bool forceDwarfConversion
,
1284 bool neverConvertDwarf
, bool verboseOptimizationHints
, bool ignoreMismatchPlatform
)
1285 : _fileContent(fileContent
), _fileLength(fileLength
), _path(path
), _modTime(modTime
),
1286 _ordinal(ordinal
), _file(NULL
),
1287 _symbols(NULL
), _symbolCount(0), _indirectSymbolCount(0), _strings(NULL
), _stringsSize(0),
1288 _indirectTable(NULL
), _indirectTableCount(0),
1289 _undefinedStartIndex(0), _undefinedEndIndex(0),
1290 _sectionsStart(NULL
), _machOSectionsCount(0), _hasUUID(false),
1291 _dataInCodeStart(NULL
), _dataInCodeEnd(NULL
),
1292 _lohStart(NULL
), _lohEnd(NULL
),
1293 _EHFrameSection(NULL
), _compactUnwindSection(NULL
), _absoluteSection(NULL
),
1294 _tentativeDefinitionCount(0), _absoluteSymbolCount(0),
1295 _symbolsInSections(0), _hasLongBranchStubs(false), _AppleObjc(false),
1296 _overlappingSymbols(false), _warnUnwindConversionProblems(convertDUI
), _hasDataInCodeLabels(false),
1297 _keepDwarfUnwind(keepDwarfUnwind
), _forceDwarfConversion(forceDwarfConversion
),
1298 _neverConvertDwarf(neverConvertDwarf
),
1299 _verboseOptimizationHints(verboseOptimizationHints
),
1300 _ignoreMismatchPlatform(ignoreMismatchPlatform
),
1301 _stubsSectionNum(0), _stubsMachOSection(NULL
)
1307 bool Parser
<x86
>::validFile(const uint8_t* fileContent
, bool, cpu_subtype_t
)
1309 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1310 if ( header
->magic() != MH_MAGIC
)
1312 if ( header
->cputype() != CPU_TYPE_I386
)
1314 if ( header
->filetype() != MH_OBJECT
)
1320 bool Parser
<x86_64
>::validFile(const uint8_t* fileContent
, bool, cpu_subtype_t
)
1322 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1323 if ( header
->magic() != MH_MAGIC_64
)
1325 if ( header
->cputype() != CPU_TYPE_X86_64
)
1327 if ( header
->filetype() != MH_OBJECT
)
1333 bool Parser
<arm
>::validFile(const uint8_t* fileContent
, bool subtypeMustMatch
, cpu_subtype_t subtype
)
1335 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1336 if ( header
->magic() != MH_MAGIC
)
1338 if ( header
->cputype() != CPU_TYPE_ARM
)
1340 if ( header
->filetype() != MH_OBJECT
)
1342 if ( subtypeMustMatch
) {
1343 if ( (cpu_subtype_t
)header
->cpusubtype() == subtype
)
1345 // hack until libcc_kext.a is made fat
1346 if ( header
->cpusubtype() == CPU_SUBTYPE_ARM_ALL
)
1355 bool Parser
<arm64
>::validFile(const uint8_t* fileContent
, bool subtypeMustMatch
, cpu_subtype_t subtype
)
1357 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1358 if ( header
->magic() != MH_MAGIC_64
)
1360 if ( header
->cputype() != CPU_TYPE_ARM64
)
1362 if ( header
->filetype() != MH_OBJECT
)
1369 const char* Parser
<x86
>::fileKind(const uint8_t* fileContent
)
1371 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1372 if ( header
->magic() != MH_MAGIC
)
1374 if ( header
->cputype() != CPU_TYPE_I386
)
1380 const char* Parser
<x86_64
>::fileKind(const uint8_t* fileContent
)
1382 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1383 if ( header
->magic() != MH_MAGIC_64
)
1385 if ( header
->cputype() != CPU_TYPE_X86_64
)
1391 const char* Parser
<arm
>::fileKind(const uint8_t* fileContent
)
1393 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1394 if ( header
->magic() != MH_MAGIC
)
1396 if ( header
->cputype() != CPU_TYPE_ARM
)
1398 for (const ArchInfo
* t
=archInfoArray
; t
->archName
!= NULL
; ++t
) {
1399 if ( (t
->cpuType
== CPU_TYPE_ARM
) && ((cpu_subtype_t
)header
->cpusubtype() == t
->cpuSubType
) ) {
1406 #if SUPPORT_ARCH_arm64
1408 const char* Parser
<arm64
>::fileKind(const uint8_t* fileContent
)
1410 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1411 if ( header
->magic() != MH_MAGIC_64
)
1413 if ( header
->cputype() != CPU_TYPE_ARM64
)
1420 template <typename A
>
1421 bool Parser
<A
>::hasObjC2Categories(const uint8_t* fileContent
)
1423 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1424 const uint32_t cmd_count
= header
->ncmds();
1425 const macho_load_command
<P
>* const cmds
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>));
1426 const macho_load_command
<P
>* const cmdsEnd
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>) + header
->sizeofcmds());
1427 const macho_load_command
<P
>* cmd
= cmds
;
1428 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1429 if ( cmd
->cmd() == macho_segment_command
<P
>::CMD
) {
1430 const macho_segment_command
<P
>* segment
= (macho_segment_command
<P
>*)cmd
;
1431 const macho_section
<P
>* sectionsStart
= (macho_section
<P
>*)((char*)segment
+ sizeof(macho_segment_command
<P
>));
1432 for (uint32_t si
=0; si
< segment
->nsects(); ++si
) {
1433 const macho_section
<P
>* sect
= §ionsStart
[si
];
1434 if ( (sect
->size() > 0)
1435 && (strcmp(sect
->sectname(), "__objc_catlist") == 0)
1436 && (strcmp(sect
->segname(), "__DATA") == 0) ) {
1441 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
1442 if ( cmd
> cmdsEnd
)
1443 throwf("malformed mach-o file, load command #%d is outside size of load commands", i
);
1449 template <typename A
>
1450 bool Parser
<A
>::hasObjC1Categories(const uint8_t* fileContent
)
1452 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1453 const uint32_t cmd_count
= header
->ncmds();
1454 const macho_load_command
<P
>* const cmds
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>));
1455 const macho_load_command
<P
>* const cmdsEnd
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>) + header
->sizeofcmds());
1456 const macho_load_command
<P
>* cmd
= cmds
;
1457 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1458 if ( cmd
->cmd() == macho_segment_command
<P
>::CMD
) {
1459 const macho_segment_command
<P
>* segment
= (macho_segment_command
<P
>*)cmd
;
1460 const macho_section
<P
>* sectionsStart
= (macho_section
<P
>*)((char*)segment
+ sizeof(macho_segment_command
<P
>));
1461 for (uint32_t si
=0; si
< segment
->nsects(); ++si
) {
1462 const macho_section
<P
>* sect
= §ionsStart
[si
];
1463 if ( (sect
->size() > 0)
1464 && (strcmp(sect
->sectname(), "__category") == 0)
1465 && (strcmp(sect
->segname(), "__OBJC") == 0) ) {
1470 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
1471 if ( cmd
> cmdsEnd
)
1472 throwf("malformed mach-o file, load command #%d is outside size of load commands", i
);
1478 template <typename A
>
1479 bool Parser
<A
>::getNonLocalSymbols(const uint8_t* fileContent
, std::vector
<const char*> &syms
)
1481 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1482 const uint32_t cmd_count
= header
->ncmds();
1483 const macho_load_command
<P
>* const cmds
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>));
1484 const macho_load_command
<P
>* const cmdsEnd
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>) + header
->sizeofcmds());
1485 const macho_load_command
<P
>* cmd
= cmds
;
1486 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1487 if ( cmd
->cmd() == LC_SYMTAB
) {
1488 const macho_symtab_command
<P
>* symtab
= (macho_symtab_command
<P
>*)cmd
;
1489 uint32_t symbolCount
= symtab
->nsyms();
1490 const macho_nlist
<P
>* symbols
= (const macho_nlist
<P
>*)(fileContent
+ symtab
->symoff());
1491 const char* strings
= (char*)fileContent
+ symtab
->stroff();
1492 for (uint32_t j
= 0; j
< symbolCount
; ++j
) {
1493 // ignore stabs and count only ext symbols
1494 if ( (symbols
[j
].n_type() & N_STAB
) == 0 &&
1495 (symbols
[j
].n_type() & N_EXT
) != 0 ) {
1496 const char* symName
= &strings
[symbols
[j
].n_strx()];
1497 syms
.push_back(symName
);
1502 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
1503 if ( cmd
> cmdsEnd
)
1504 throwf("malformed mach-o file, load command #%d is outside size of load commands", i
);
1510 template <typename A
>
1511 int Parser
<A
>::pointerSorter(const void* l
, const void* r
)
1513 // sort references by address
1514 const pint_t
* left
= (pint_t
*)l
;
1515 const pint_t
* right
= (pint_t
*)r
;
1516 return (*left
- *right
);
1519 template <typename A
>
1520 typename
A::P::uint_t Parser
<A
>::LabelAndCFIBreakIterator::peek(Parser
<A
>& parser
, pint_t startAddr
, pint_t endAddr
)
1523 if ( symIndex
< sortedSymbolCount
)
1524 symbolAddr
= parser
.symbolFromIndex(sortedSymbolIndexes
[symIndex
]).n_value();
1526 symbolAddr
= endAddr
;
1528 if ( cfiIndex
< cfiStartsCount
)
1529 cfiAddr
= cfiStartsArray
[cfiIndex
];
1532 if ( (cfiAddr
< symbolAddr
) && (cfiAddr
>= startAddr
) ) {
1533 if ( cfiAddr
< endAddr
)
1539 if ( symbolAddr
< endAddr
)
1547 // Parses up a section into chunks based on labels and CFI information.
1548 // Each call returns the next chunk address and size, and (if the break
1549 // was becuase of a label, the symbol). Returns false when no more chunks.
1551 template <typename A
>
1552 bool Parser
<A
>::LabelAndCFIBreakIterator::next(Parser
<A
>& parser
, const Section
<A
>& sect
, uint32_t sectNum
, pint_t startAddr
, pint_t endAddr
,
1553 pint_t
* addr
, pint_t
* size
, const macho_nlist
<P
>** symbol
)
1555 // may not be a label on start of section, but need atom demarcation there
1558 // advance symIndex until we get to the first label at or past the start of this section
1559 while ( symIndex
< sortedSymbolCount
) {
1560 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(sortedSymbolIndexes
[symIndex
]);
1561 if ( ! sect
.ignoreLabel(parser
.nameFromSymbol(sym
)) ) {
1562 pint_t nextSymbolAddr
= sym
.n_value();
1563 //fprintf(stderr, "sectNum=%d, nextSymbolAddr=0x%08llX, name=%s\n", sectNum, (uint64_t)nextSymbolAddr, parser.nameFromSymbol(sym));
1564 if ( (nextSymbolAddr
> startAddr
) || ((nextSymbolAddr
== startAddr
) && (sym
.n_sect() == sectNum
)) )
1569 if ( symIndex
< sortedSymbolCount
) {
1570 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(sortedSymbolIndexes
[symIndex
]);
1571 pint_t nextSymbolAddr
= sym
.n_value();
1572 // if next symbol found is not in this section
1573 if ( sym
.n_sect() != sectNum
) {
1574 // check for CFI break instead of symbol break
1575 if ( cfiIndex
< cfiStartsCount
) {
1576 pint_t nextCfiAddr
= cfiStartsArray
[cfiIndex
];
1577 if ( nextCfiAddr
< endAddr
) {
1580 *addr
= nextCfiAddr
;
1581 *size
= peek(parser
, startAddr
, endAddr
) - nextCfiAddr
;
1587 *size
= endAddr
- startAddr
;
1589 if ( startAddr
== endAddr
)
1590 return false; // zero size section
1592 return true; // whole section is one atom with no label
1594 // if also CFI break here, eat it
1595 if ( cfiIndex
< cfiStartsCount
) {
1596 if ( cfiStartsArray
[cfiIndex
] == nextSymbolAddr
)
1599 if ( nextSymbolAddr
== startAddr
) {
1600 // label at start of section, return it as chunk
1603 *size
= peek(parser
, startAddr
, endAddr
) - startAddr
;
1607 // return chunk before first symbol
1609 *size
= nextSymbolAddr
- startAddr
;
1613 // no symbols in section, check CFI
1614 if ( cfiIndex
< cfiStartsCount
) {
1615 pint_t nextCfiAddr
= cfiStartsArray
[cfiIndex
];
1616 if ( nextCfiAddr
< endAddr
) {
1619 *addr
= nextCfiAddr
;
1620 *size
= peek(parser
, startAddr
, endAddr
) - nextCfiAddr
;
1625 // no cfi, so whole section is one chunk
1627 *size
= endAddr
- startAddr
;
1629 if ( startAddr
== endAddr
)
1630 return false; // zero size section
1632 return true; // whole section is one atom with no label
1635 while ( (symIndex
< sortedSymbolCount
) && (cfiIndex
< cfiStartsCount
) ) {
1636 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(sortedSymbolIndexes
[symIndex
]);
1637 pint_t nextSymbolAddr
= sym
.n_value();
1638 pint_t nextCfiAddr
= cfiStartsArray
[cfiIndex
];
1639 if ( nextSymbolAddr
< nextCfiAddr
) {
1640 if ( nextSymbolAddr
>= endAddr
)
1643 if ( nextSymbolAddr
< startAddr
)
1645 *addr
= nextSymbolAddr
;
1646 *size
= peek(parser
, startAddr
, endAddr
) - nextSymbolAddr
;
1650 else if ( nextCfiAddr
< nextSymbolAddr
) {
1651 if ( nextCfiAddr
>= endAddr
)
1654 if ( nextCfiAddr
< startAddr
)
1656 *addr
= nextCfiAddr
;
1657 *size
= peek(parser
, startAddr
, endAddr
) - nextCfiAddr
;
1662 if ( nextCfiAddr
>= endAddr
)
1666 if ( nextCfiAddr
< startAddr
)
1668 *addr
= nextCfiAddr
;
1669 *size
= peek(parser
, startAddr
, endAddr
) - nextCfiAddr
;
1674 while ( symIndex
< sortedSymbolCount
) {
1675 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(sortedSymbolIndexes
[symIndex
]);
1676 pint_t nextSymbolAddr
= sym
.n_value();
1677 // if next symbol found is not in this section, then done with iteration
1678 if ( sym
.n_sect() != sectNum
)
1681 if ( nextSymbolAddr
< startAddr
)
1683 *addr
= nextSymbolAddr
;
1684 *size
= peek(parser
, startAddr
, endAddr
) - nextSymbolAddr
;
1688 while ( cfiIndex
< cfiStartsCount
) {
1689 pint_t nextCfiAddr
= cfiStartsArray
[cfiIndex
];
1690 if ( nextCfiAddr
>= endAddr
)
1693 if ( nextCfiAddr
< startAddr
)
1695 *addr
= nextCfiAddr
;
1696 *size
= peek(parser
, startAddr
, endAddr
) - nextCfiAddr
;
1704 typename
arm::P::uint_t Parser
<arm
>::realAddr(typename
arm::P::uint_t addr
)
1709 template <typename A
>
1710 typename
A::P::uint_t Parser
<A
>::realAddr(typename
A::P::uint_t addr
)
1715 #define STACK_ALLOC_IF_SMALL(_type, _name, _actual_count, _maxCount) \
1716 _type* _name = NULL; \
1717 uint32_t _name##_count = 1; \
1718 if ( _actual_count > _maxCount ) \
1719 _name = (_type*)malloc(sizeof(_type) * _actual_count); \
1721 _name##_count = _actual_count; \
1722 _type _name##_buffer[_name##_count]; \
1723 if ( _name == NULL ) \
1724 _name = _name##_buffer;
1727 template <typename A
>
1728 ld::relocatable::File
* Parser
<A
>::parse(const ParserOptions
& opts
)
1730 // create file object
1731 _file
= new File
<A
>(_path
, _modTime
, _fileContent
, _ordinal
);
1734 _file
->_srcKind
= opts
.srcKind
;
1735 // set treatBitcodeAsData
1736 _treateBitcodeAsData
= opts
.treateBitcodeAsData
;
1737 _usingBitcode
= opts
.usingBitcode
;
1739 // respond to -t option
1740 if ( opts
.logAllFiles
)
1741 printf("%s\n", _path
);
1743 _armUsesZeroCostExceptions
= opts
.armUsesZeroCostExceptions
;
1744 _maxDefaultCommonAlignment
= opts
.maxDefaultCommonAlignment
;
1746 // parse start of mach-o file
1747 if ( ! parseLoadCommands(opts
.platform
, opts
.minOSVersion
, opts
.simulator
, opts
.ignoreMismatchPlatform
) )
1751 uint32_t sortedSectionIndexes
[_machOSectionsCount
];
1752 this->makeSortedSectionsArray(sortedSectionIndexes
);
1754 // make symbol table sorted by address
1755 this->prescanSymbolTable();
1756 uint32_t sortedSymbolIndexes
[_symbolsInSections
];
1757 this->makeSortedSymbolsArray(sortedSymbolIndexes
, sortedSectionIndexes
);
1759 // allocate Section<A> object for each mach-o section
1762 // if it exists, do special early parsing of __compact_unwind section
1763 uint32_t countOfCUs
= 0;
1764 if ( _compactUnwindSection
!= NULL
)
1765 countOfCUs
= _compactUnwindSection
->count();
1766 // stack allocate (if not too large) cuInfoBuffer
1767 STACK_ALLOC_IF_SMALL(typename CUSection
<A
>::Info
, cuInfoArray
, countOfCUs
, 1024);
1768 if ( countOfCUs
!= 0 )
1769 _compactUnwindSection
->parse(*this, countOfCUs
, cuInfoArray
);
1771 // create lists of address that already have compact unwind and thus don't need the dwarf parsed
1772 unsigned cuLsdaCount
= 0;
1773 pint_t cuStarts
[countOfCUs
];
1774 for (uint32_t i
=0; i
< countOfCUs
; ++i
) {
1775 if ( CUSection
<A
>::encodingMeansUseDwarf(cuInfoArray
[i
].compactUnwindInfo
) )
1778 cuStarts
[i
] = cuInfoArray
[i
].functionStartAddress
;
1779 if ( cuInfoArray
[i
].lsdaAddress
!= 0 )
1784 // if it exists, do special early parsing of __eh_frame section
1785 // stack allocate (if not too large) array of CFI_Atom_Info
1786 uint32_t countOfCFIs
= 0;
1787 if ( _EHFrameSection
!= NULL
)
1788 countOfCFIs
= _EHFrameSection
->cfiCount(*this);
1789 STACK_ALLOC_IF_SMALL(typename CFISection
<A
>::CFI_Atom_Info
, cfiArray
, countOfCFIs
, 1024);
1791 // stack allocate (if not too large) a copy of __eh_frame to apply relocations to
1792 uint32_t sectSize
= 4;
1793 if ( (countOfCFIs
!= 0) && _EHFrameSection
->needsRelocating() )
1794 sectSize
= _EHFrameSection
->machoSection()->size()+4;
1795 STACK_ALLOC_IF_SMALL(uint8_t, ehBuffer
, sectSize
, 50*1024);
1796 uint32_t cfiStartsCount
= 0;
1797 if ( countOfCFIs
!= 0 ) {
1798 _EHFrameSection
->cfiParse(*this, ehBuffer
, cfiArray
, countOfCFIs
, cuStarts
, countOfCUs
);
1799 // count functions and lsdas
1800 for(uint32_t i
=0; i
< countOfCFIs
; ++i
) {
1801 if ( cfiArray
[i
].isCIE
)
1803 //fprintf(stderr, "cfiArray[i].func = 0x%08llX, cfiArray[i].lsda = 0x%08llX, encoding=0x%08X\n",
1804 // (uint64_t)cfiArray[i].u.fdeInfo.function.targetAddress,
1805 // (uint64_t)cfiArray[i].u.fdeInfo.lsda.targetAddress,
1806 // cfiArray[i].u.fdeInfo.compactUnwindInfo);
1807 if ( cfiArray
[i
].u
.fdeInfo
.function
.targetAddress
!= CFI_INVALID_ADDRESS
)
1809 if ( cfiArray
[i
].u
.fdeInfo
.lsda
.targetAddress
!= CFI_INVALID_ADDRESS
)
1813 CFI_CU_InfoArrays
cfis(cfiArray
, countOfCFIs
, cuInfoArray
, countOfCUs
);
1815 // create sorted array of function starts and lsda starts
1816 pint_t cfiStartsArray
[cfiStartsCount
+cuLsdaCount
];
1817 uint32_t countOfFDEs
= 0;
1818 uint32_t cfiStartsArrayCount
= 0;
1819 if ( countOfCFIs
!= 0 ) {
1820 for(uint32_t i
=0; i
< countOfCFIs
; ++i
) {
1821 if ( cfiArray
[i
].isCIE
)
1823 if ( cfiArray
[i
].u
.fdeInfo
.function
.targetAddress
!= CFI_INVALID_ADDRESS
)
1824 cfiStartsArray
[cfiStartsArrayCount
++] = realAddr(cfiArray
[i
].u
.fdeInfo
.function
.targetAddress
);
1825 if ( cfiArray
[i
].u
.fdeInfo
.lsda
.targetAddress
!= CFI_INVALID_ADDRESS
)
1826 cfiStartsArray
[cfiStartsArrayCount
++] = cfiArray
[i
].u
.fdeInfo
.lsda
.targetAddress
;
1830 if ( cuLsdaCount
!= 0 ) {
1831 // merge in an lsda info from compact unwind
1832 for (uint32_t i
=0; i
< countOfCUs
; ++i
) {
1833 if ( cuInfoArray
[i
].lsdaAddress
== 0 )
1835 // append to cfiStartsArray if not already in that list
1837 for(uint32_t j
=0; j
< cfiStartsArrayCount
; ++j
) {
1838 if ( cfiStartsArray
[j
] == cuInfoArray
[i
].lsdaAddress
)
1842 cfiStartsArray
[cfiStartsArrayCount
++] = cuInfoArray
[i
].lsdaAddress
;
1846 if ( cfiStartsArrayCount
!= 0 ) {
1847 ::qsort(cfiStartsArray
, cfiStartsArrayCount
, sizeof(pint_t
), pointerSorter
);
1849 // scan for FDEs claming the same function
1850 for(uint32_t i
=1; i
< cfiStartsArrayCount
; ++i
) {
1851 assert( cfiStartsArray
[i
] != cfiStartsArray
[i
-1] );
1856 Section
<A
>** sections
= _file
->_sectionsArray
;
1857 uint32_t sectionsCount
= _file
->_sectionsArrayCount
;
1859 // figure out how many atoms will be allocated and allocate
1860 LabelAndCFIBreakIterator
breakIterator(sortedSymbolIndexes
, _symbolsInSections
, cfiStartsArray
,
1861 cfiStartsArrayCount
, _overlappingSymbols
);
1862 uint32_t computedAtomCount
= 0;
1863 for (uint32_t i
=0; i
< sectionsCount
; ++i
) {
1864 breakIterator
.beginSection();
1865 uint32_t count
= sections
[i
]->computeAtomCount(*this, breakIterator
, cfis
);
1866 //const macho_section<P>* sect = sections[i]->machoSection();
1867 //fprintf(stderr, "computed count=%u for section %s size=%llu\n", count, sect->sectname(), (sect != NULL) ? sect->size() : 0);
1868 computedAtomCount
+= count
;
1870 //fprintf(stderr, "allocating %d atoms * sizeof(Atom<A>)=%ld, sizeof(ld::Atom)=%ld\n", computedAtomCount, sizeof(Atom<A>), sizeof(ld::Atom));
1871 _file
->_atomsArray
= new uint8_t[computedAtomCount
*sizeof(Atom
<A
>)];
1872 _file
->_atomsArrayCount
= 0;
1874 // have each section append atoms to _atomsArray
1875 LabelAndCFIBreakIterator
breakIterator2(sortedSymbolIndexes
, _symbolsInSections
, cfiStartsArray
,
1876 cfiStartsArrayCount
, _overlappingSymbols
);
1877 for (uint32_t i
=0; i
< sectionsCount
; ++i
) {
1878 uint8_t* atoms
= _file
->_atomsArray
+ _file
->_atomsArrayCount
*sizeof(Atom
<A
>);
1879 breakIterator2
.beginSection();
1880 uint32_t count
= sections
[i
]->appendAtoms(*this, atoms
, breakIterator2
, cfis
);
1881 //fprintf(stderr, "append count=%u for section %s/%s\n", count, sections[i]->machoSection()->segname(), sections[i]->machoSection()->sectname());
1882 _file
->_atomsArrayCount
+= count
;
1884 assert( _file
->_atomsArrayCount
== computedAtomCount
&& "more atoms allocated than expected");
1887 // have each section add all fix-ups for its atoms
1888 _allFixups
.reserve(computedAtomCount
*5);
1889 for (uint32_t i
=0; i
< sectionsCount
; ++i
)
1890 sections
[i
]->makeFixups(*this, cfis
);
1892 // assign fixups start offset for each atom
1893 uint8_t* p
= _file
->_atomsArray
;
1894 uint32_t fixupOffset
= 0;
1895 for(int i
=_file
->_atomsArrayCount
; i
> 0; --i
) {
1896 Atom
<A
>* atom
= (Atom
<A
>*)p
;
1897 atom
->_fixupsStartIndex
= fixupOffset
;
1898 fixupOffset
+= atom
->_fixupsCount
;
1899 atom
->_fixupsCount
= 0;
1900 p
+= sizeof(Atom
<A
>);
1902 assert(fixupOffset
== _allFixups
.size());
1903 _file
->_fixups
.resize(fixupOffset
);
1905 // copy each fixup for each atom
1906 for(typename
std::vector
<FixupInAtom
>::iterator it
=_allFixups
.begin(); it
!= _allFixups
.end(); ++it
) {
1907 uint32_t slot
= it
->atom
->_fixupsStartIndex
+ it
->atom
->_fixupsCount
;
1908 _file
->_fixups
[slot
] = it
->fixup
;
1909 it
->atom
->_fixupsCount
++;
1912 // done with temp vector
1916 _file
->_unwindInfos
.reserve(countOfFDEs
+countOfCUs
);
1917 for(uint32_t i
=0; i
< countOfCFIs
; ++i
) {
1918 if ( cfiArray
[i
].isCIE
)
1920 if ( cfiArray
[i
].u
.fdeInfo
.function
.targetAddress
!= CFI_INVALID_ADDRESS
) {
1921 ld::Atom::UnwindInfo info
;
1922 info
.startOffset
= 0;
1923 info
.unwindInfo
= cfiArray
[i
].u
.fdeInfo
.compactUnwindInfo
;
1924 _file
->_unwindInfos
.push_back(info
);
1925 Atom
<A
>* func
= findAtomByAddress(cfiArray
[i
].u
.fdeInfo
.function
.targetAddress
);
1926 func
->setUnwindInfoRange(_file
->_unwindInfos
.size()-1, 1);
1927 //fprintf(stderr, "cu from dwarf =0x%08X, atom=%s\n", info.unwindInfo, func->name());
1930 // apply compact infos in __LD,__compact_unwind section to each function
1931 // if function also has dwarf unwind, CU will override it
1932 Atom
<A
>* lastFunc
= NULL
;
1933 uint32_t lastEnd
= 0;
1934 for(uint32_t i
=0; i
< countOfCUs
; ++i
) {
1935 typename CUSection
<A
>::Info
* info
= &cuInfoArray
[i
];
1936 assert(info
->function
!= NULL
);
1937 ld::Atom::UnwindInfo ui
;
1938 ui
.startOffset
= info
->functionStartAddress
- info
->function
->objectAddress();
1939 ui
.unwindInfo
= info
->compactUnwindInfo
;
1940 _file
->_unwindInfos
.push_back(ui
);
1941 // don't override with converted cu with "use dwarf" cu, if forcing dwarf conversion
1942 if ( !_forceDwarfConversion
|| !CUSection
<A
>::encodingMeansUseDwarf(info
->compactUnwindInfo
) ) {
1943 //fprintf(stderr, "cu=0x%08X, atom=%s\n", ui.unwindInfo, info->function->name());
1944 // if previous is for same function, extend range
1945 if ( info
->function
== lastFunc
) {
1946 if ( lastEnd
!= ui
.startOffset
) {
1947 if ( lastEnd
< ui
.startOffset
)
1948 warning("__LD,__compact_unwind entries for %s have a gap at offset 0x%0X", info
->function
->name(), lastEnd
);
1950 warning("__LD,__compact_unwind entries for %s overlap at offset 0x%0X", info
->function
->name(), lastEnd
);
1952 lastFunc
->extendUnwindInfoRange();
1955 info
->function
->setUnwindInfoRange(_file
->_unwindInfos
.size()-1, 1);
1956 lastFunc
= info
->function
;
1957 lastEnd
= ui
.startOffset
+ info
->rangeLength
;
1961 // process indirect symbols which become AliasAtoms
1962 _file
->_aliasAtomsArray
= NULL
;
1963 _file
->_aliasAtomsArrayCount
= 0;
1964 if ( _indirectSymbolCount
!= 0 ) {
1965 _file
->_aliasAtomsArrayCount
= _indirectSymbolCount
;
1966 _file
->_aliasAtomsArray
= new uint8_t[_file
->_aliasAtomsArrayCount
*sizeof(AliasAtom
)];
1967 this->appendAliasAtoms(_file
->_aliasAtomsArray
);
1971 // parse dwarf debug info to get line info
1972 this->parseDebugInfo();
1977 static void versionToString(uint32_t value
, char buffer
[32])
1980 sprintf(buffer
, "%d.%d.%d", value
>> 16, (value
>> 8) & 0xFF, value
& 0xFF);
1982 sprintf(buffer
, "%d.%d", value
>> 16, (value
>> 8) & 0xFF);
1985 template <> uint8_t Parser
<x86
>::loadCommandSizeMask() { return 0x03; }
1986 template <> uint8_t Parser
<x86_64
>::loadCommandSizeMask() { return 0x07; }
1987 template <> uint8_t Parser
<arm
>::loadCommandSizeMask() { return 0x03; }
1988 template <> uint8_t Parser
<arm64
>::loadCommandSizeMask() { return 0x07; }
1990 template <typename A
>
1991 bool Parser
<A
>::parseLoadCommands(Options::Platform platform
, uint32_t linkMinOSVersion
, bool simulator
, bool ignoreMismatchPlatform
)
1993 const macho_header
<P
>* header
= (const macho_header
<P
>*)_fileContent
;
1995 // set File attributes
1996 _file
->_canScatterAtoms
= (header
->flags() & MH_SUBSECTIONS_VIA_SYMBOLS
);
1997 _file
->_cpuSubType
= header
->cpusubtype();
1999 const macho_segment_command
<P
>* segment
= NULL
;
2000 const uint8_t* const endOfFile
= _fileContent
+ _fileLength
;
2001 const uint32_t cmd_count
= header
->ncmds();
2002 // <rdar://problem/5394172> an empty .o file with zero load commands will crash linker
2003 if ( cmd_count
== 0 )
2005 Options::Platform lcPlatform
= Options::kPlatformUnknown
;
2006 const macho_load_command
<P
>* const cmds
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>));
2007 const macho_load_command
<P
>* const cmdsEnd
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>) + header
->sizeofcmds());
2008 const macho_load_command
<P
>* cmd
= cmds
;
2009 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
2010 uint32_t size
= cmd
->cmdsize();
2011 if ( (size
& this->loadCommandSizeMask()) != 0 )
2012 throwf("load command #%d has a unaligned size", i
);
2013 const uint8_t* endOfCmd
= ((uint8_t*)cmd
)+cmd
->cmdsize();
2014 if ( endOfCmd
> (uint8_t*)cmdsEnd
)
2015 throwf("load command #%d extends beyond the end of the load commands", i
);
2016 if ( endOfCmd
> endOfFile
)
2017 throwf("load command #%d extends beyond the end of the file", i
);
2018 switch (cmd
->cmd()) {
2021 const macho_symtab_command
<P
>* symtab
= (macho_symtab_command
<P
>*)cmd
;
2022 _symbolCount
= symtab
->nsyms();
2023 _symbols
= (const macho_nlist
<P
>*)(_fileContent
+ symtab
->symoff());
2024 _strings
= (char*)_fileContent
+ symtab
->stroff();
2025 _stringsSize
= symtab
->strsize();
2026 if ( (symtab
->symoff() + _symbolCount
*sizeof(macho_nlist
<P
>)) > _fileLength
)
2027 throw "mach-o symbol table extends beyond end of file";
2028 if ( (_strings
+ _stringsSize
) > (char*)endOfFile
)
2029 throw "mach-o string pool extends beyond end of file";
2030 if ( _indirectTable
== NULL
) {
2031 if ( _undefinedEndIndex
== 0 ) {
2032 _undefinedStartIndex
= 0;
2033 _undefinedEndIndex
= symtab
->nsyms();
2040 const macho_dysymtab_command
<P
>* dsymtab
= (macho_dysymtab_command
<P
>*)cmd
;
2041 _indirectTable
= (uint32_t*)(_fileContent
+ dsymtab
->indirectsymoff());
2042 _indirectTableCount
= dsymtab
->nindirectsyms();
2043 if ( &_indirectTable
[_indirectTableCount
] > (uint32_t*)endOfFile
)
2044 throw "indirect symbol table extends beyond end of file";
2045 _undefinedStartIndex
= dsymtab
->iundefsym();
2046 _undefinedEndIndex
= _undefinedStartIndex
+ dsymtab
->nundefsym();
2052 case LC_DATA_IN_CODE
:
2054 const macho_linkedit_data_command
<P
>* dc
= (macho_linkedit_data_command
<P
>*)cmd
;
2055 _dataInCodeStart
= (macho_data_in_code_entry
<P
>*)(_fileContent
+ dc
->dataoff());
2056 _dataInCodeEnd
= (macho_data_in_code_entry
<P
>*)(_fileContent
+ dc
->dataoff() + dc
->datasize());
2057 if ( _dataInCodeEnd
> (macho_data_in_code_entry
<P
>*)endOfFile
)
2058 throw "LC_DATA_IN_CODE table extends beyond end of file";
2061 case LC_LINKER_OPTION
:
2063 const macho_linker_option_command
<P
>* loc
= (macho_linker_option_command
<P
>*)cmd
;
2064 const char* buffer
= loc
->buffer();
2065 _file
->_linkerOptions
.resize(_file
->_linkerOptions
.size() + 1);
2066 std::vector
<const char*>& vec
= _file
->_linkerOptions
.back();
2067 for (uint32_t j
=0; j
< loc
->count(); ++j
) {
2068 vec
.push_back(buffer
);
2069 buffer
+= strlen(buffer
) + 1;
2071 if ( buffer
> ((char*)cmd
+ loc
->cmdsize()) )
2072 throw "malformed LC_LINKER_OPTION";
2075 case LC_LINKER_OPTIMIZATION_HINTS
:
2077 const macho_linkedit_data_command
<P
>* loh
= (macho_linkedit_data_command
<P
>*)cmd
;
2078 _lohStart
= _fileContent
+ loh
->dataoff();
2079 _lohEnd
= _fileContent
+ loh
->dataoff() + loh
->datasize();
2080 if ( _lohEnd
> endOfFile
)
2081 throw "LC_LINKER_OPTIMIZATION_HINTS table extends beyond end of file";
2084 case LC_VERSION_MIN_MACOSX
:
2085 case LC_VERSION_MIN_IPHONEOS
:
2086 case LC_VERSION_MIN_WATCHOS
:
2087 #if SUPPORT_APPLE_TV
2088 case LC_VERSION_MIN_TVOS
:
2090 if ( ignoreMismatchPlatform
)
2092 _file
->_platform
= cmd
->cmd();
2093 lcPlatform
= Options::platformForLoadCommand(cmd
->cmd());
2094 _file
->_minOSVersion
= ((macho_version_min_command
<P
>*)cmd
)->version();
2096 case macho_segment_command
<P
>::CMD
:
2097 if ( segment
!= NULL
)
2098 throw "more than one LC_SEGMENT found in object file";
2099 segment
= (macho_segment_command
<P
>*)cmd
;
2102 // ignore unknown load commands
2105 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
2106 if ( cmd
> cmdsEnd
)
2107 throwf("malformed mach-o file, load command #%d is outside size of load commands", i
);
2109 // arm/arm64 objects are default to ios platform if not set.
2110 // rdar://problem/21746314
2111 if (lcPlatform
== Options::kPlatformUnknown
&&
2112 (std::is_same
<A
, arm
>::value
|| std::is_same
<A
, arm64
>::value
))
2113 lcPlatform
= Options::kPlatformiOS
;
2115 // Check platform cross-linking.
2116 if ( !ignoreMismatchPlatform
) {
2117 if ( lcPlatform
!= platform
) {
2119 case Options::kPlatformOSX
:
2120 case Options::kPlatformiOS
:
2121 if ( lcPlatform
== Options::kPlatformUnknown
)
2123 // fall through if the Platform is not Unknown
2124 case Options::kPlatformWatchOS
:
2125 // Error when using bitcocde, warning otherwise.
2127 throwf("building for %s%s, but linking in object file built for %s,",
2128 Options::platformName(platform
), (simulator
? " simulator" : ""),
2129 Options::platformName(lcPlatform
));
2131 warning("URGENT: building for %s%s, but linking in object file (%s) built for %s. "
2132 "Note: This will be an error in the future.",
2133 Options::platformName(platform
), (simulator
? " simulator" : ""), path(),
2134 Options::platformName(lcPlatform
));
2136 #if SUPPORT_APPLE_TV
2137 case Options::kPlatform_tvOS
:
2138 // Error when using bitcocde, warning otherwise.
2140 throwf("building for %s%s, but linking in object file built for %s,",
2141 Options::platformName(platform
), (simulator
? " simulator" : ""),
2142 Options::platformName(lcPlatform
));
2144 warning("URGENT: building for %s%s, but linking in object file (%s) built for %s. "
2145 "Note: This will be an error in the future.",
2146 Options::platformName(platform
), (simulator
? " simulator" : ""), path(),
2147 Options::platformName(lcPlatform
));
2150 case Options::kPlatformUnknown
:
2151 // skip if the target platform is unknown
2155 if ( linkMinOSVersion
&& (_file
->_minOSVersion
> linkMinOSVersion
) ) {
2158 versionToString(_file
->_minOSVersion
, t1
);
2159 versionToString(linkMinOSVersion
, t2
);
2160 warning("object file (%s) was built for newer %s version (%s) than being linked (%s)",
2161 _path
, Options::platformName(lcPlatform
), t1
, t2
);
2166 // record range of sections
2167 if ( segment
== NULL
)
2168 throw "missing LC_SEGMENT";
2169 _sectionsStart
= (macho_section
<P
>*)((char*)segment
+ sizeof(macho_segment_command
<P
>));
2170 _machOSectionsCount
= segment
->nsects();
2171 if ( (sizeof(macho_segment_command
<P
>) + _machOSectionsCount
* sizeof(macho_section
<P
>)) > segment
->cmdsize() )
2172 throw "too many sections for size of LC_SEGMENT command";
2176 template <typename A
>
2177 Options::Platform Parser
<A
>::findPlatform(const macho_header
<P
>* header
)
2179 const uint32_t cmd_count
= header
->ncmds();
2180 if ( cmd_count
== 0 )
2181 return Options::kPlatformUnknown
;
2182 const macho_load_command
<P
>* const cmds
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>));
2183 const macho_load_command
<P
>* const cmdsEnd
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>) + header
->sizeofcmds());
2184 const macho_load_command
<P
>* cmd
= cmds
;
2185 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
2186 uint32_t size
= cmd
->cmdsize();
2187 if ( (size
& loadCommandSizeMask()) != 0 )
2188 throwf("load command #%d has a unaligned size", i
);
2189 const uint8_t* endOfCmd
= ((uint8_t*)cmd
)+cmd
->cmdsize();
2190 if ( endOfCmd
> (uint8_t*)cmdsEnd
)
2191 throwf("load command #%d extends beyond the end of the load commands", i
);
2192 switch (cmd
->cmd()) {
2193 case LC_VERSION_MIN_MACOSX
:
2194 return Options::kPlatformOSX
;
2195 case LC_VERSION_MIN_IPHONEOS
:
2196 return Options::kPlatformiOS
;
2198 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
2199 if ( cmd
> cmdsEnd
)
2200 throwf("malformed mach-o file, load command #%d is outside size of load commands", i
);
2202 return Options::kPlatformUnknown
;
2206 template <typename A
>
2207 void Parser
<A
>::prescanSymbolTable()
2209 _tentativeDefinitionCount
= 0;
2210 _absoluteSymbolCount
= 0;
2211 _symbolsInSections
= 0;
2212 _hasDataInCodeLabels
= false;
2213 for (uint32_t i
=0; i
< this->_symbolCount
; ++i
) {
2214 const macho_nlist
<P
>& sym
= symbolFromIndex(i
);
2216 if ( (sym
.n_type() & N_STAB
) != 0 )
2219 // look at undefines
2220 const char* symbolName
= this->nameFromSymbol(sym
);
2221 if ( (sym
.n_type() & N_TYPE
) == N_UNDF
) {
2222 if ( sym
.n_value() != 0 ) {
2223 // count tentative definitions
2224 ++_tentativeDefinitionCount
;
2226 else if ( strncmp(symbolName
, "___dtrace_", 10) == 0 ) {
2227 // any undefined starting with __dtrace_*$ that is not ___dtrace_probe$* or ___dtrace_isenabled$*
2228 // is extra provider info
2229 if ( (strncmp(&symbolName
[10], "probe$", 6) != 0) && (strncmp(&symbolName
[10], "isenabled$", 10) != 0) ) {
2230 _dtraceProviderInfo
.push_back(symbolName
);
2235 else if ( ((sym
.n_type() & N_TYPE
) == N_INDR
) && ((sym
.n_type() & N_EXT
) != 0) ) {
2236 _indirectSymbolCount
++;
2240 // count absolute symbols
2241 if ( (sym
.n_type() & N_TYPE
) == N_ABS
) {
2242 const char* absName
= this->nameFromSymbol(sym
);
2243 // ignore .objc_class_name_* symbols
2244 if ( strncmp(absName
, ".objc_class_name_", 17) == 0 ) {
2248 // ignore .objc_class_name_* symbols
2249 if ( strncmp(absName
, ".objc_category_name_", 20) == 0 )
2251 // ignore empty *.eh symbols
2252 if ( strcmp(&absName
[strlen(absName
)-3], ".eh") == 0 )
2254 ++_absoluteSymbolCount
;
2257 // only look at definitions
2258 if ( (sym
.n_type() & N_TYPE
) != N_SECT
)
2261 // 'L' labels do not denote atom breaks
2262 if ( symbolName
[0] == 'L' ) {
2263 // <rdar://problem/9218847> Formalize data in code with L$start$ labels
2264 if ( strncmp(symbolName
, "L$start$", 8) == 0 )
2265 _hasDataInCodeLabels
= true;
2268 // how many def syms in each section
2269 if ( sym
.n_sect() > _machOSectionsCount
)
2270 throw "bad n_sect in symbol table";
2272 _symbolsInSections
++;
2276 template <typename A
>
2277 void Parser
<A
>::appendAliasAtoms(uint8_t* p
)
2279 for (uint32_t i
=0; i
< this->_symbolCount
; ++i
) {
2280 const macho_nlist
<P
>& sym
= symbolFromIndex(i
);
2282 if ( (sym
.n_type() & N_STAB
) != 0 )
2285 // only look at N_INDR symbols
2286 if ( (sym
.n_type() & N_TYPE
) != N_INDR
)
2289 // skip non-external aliases
2290 if ( (sym
.n_type() & N_EXT
) == 0 )
2293 const char* symbolName
= this->nameFromSymbol(sym
);
2294 const char* aliasOfName
= &_strings
[sym
.n_value()];
2295 bool isHiddenVisibility
= (sym
.n_type() & N_PEXT
);
2296 AliasAtom
* allocatedSpace
= (AliasAtom
*)p
;
2297 new (allocatedSpace
) AliasAtom(symbolName
, isHiddenVisibility
, _file
, aliasOfName
);
2298 p
+= sizeof(AliasAtom
);
2304 template <typename A
>
2305 int Parser
<A
>::sectionIndexSorter(void* extra
, const void* l
, const void* r
)
2307 Parser
<A
>* parser
= (Parser
<A
>*)extra
;
2308 const uint32_t* left
= (uint32_t*)l
;
2309 const uint32_t* right
= (uint32_t*)r
;
2310 const macho_section
<P
>* leftSect
= parser
->machOSectionFromSectionIndex(*left
);
2311 const macho_section
<P
>* rightSect
= parser
->machOSectionFromSectionIndex(*right
);
2313 // can't just return difference because 64-bit diff does not fit in 32-bit return type
2314 int64_t result
= leftSect
->addr() - rightSect
->addr();
2315 if ( result
== 0 ) {
2316 // two sections with same start address
2317 // one with zero size goes first
2318 bool leftEmpty
= ( leftSect
->size() == 0 );
2319 bool rightEmpty
= ( rightSect
->size() == 0 );
2320 if ( leftEmpty
!= rightEmpty
) {
2321 return ( rightEmpty
? 1 : -1 );
2323 if ( !leftEmpty
&& !rightEmpty
)
2324 throwf("overlapping sections");
2325 // both empty, so chose file order
2326 return ( rightSect
- leftSect
);
2328 else if ( result
< 0 )
2334 template <typename A
>
2335 void Parser
<A
>::makeSortedSectionsArray(uint32_t array
[])
2337 const bool log
= false;
2340 fprintf(stderr
, "unsorted sections:\n");
2341 for(unsigned int i
=0; i
< _machOSectionsCount
; ++i
)
2342 fprintf(stderr
, "0x%08llX %s %s\n", _sectionsStart
[i
].addr(), _sectionsStart
[i
].segname(), _sectionsStart
[i
].sectname());
2345 // sort by symbol table address
2346 for (uint32_t i
=0; i
< _machOSectionsCount
; ++i
)
2348 ::qsort_r(array
, _machOSectionsCount
, sizeof(uint32_t), this, §ionIndexSorter
);
2351 fprintf(stderr
, "sorted sections:\n");
2352 for(unsigned int i
=0; i
< _machOSectionsCount
; ++i
)
2353 fprintf(stderr
, "0x%08llX %s %s\n", _sectionsStart
[array
[i
]].addr(), _sectionsStart
[array
[i
]].segname(), _sectionsStart
[array
[i
]].sectname());
2359 template <typename A
>
2360 int Parser
<A
>::symbolIndexSorter(void* extra
, const void* l
, const void* r
)
2362 ParserAndSectionsArray
* extraInfo
= (ParserAndSectionsArray
*)extra
;
2363 Parser
<A
>* parser
= extraInfo
->parser
;
2364 const uint32_t* sortedSectionsArray
= extraInfo
->sortedSectionsArray
;
2365 const uint32_t* left
= (uint32_t*)l
;
2366 const uint32_t* right
= (uint32_t*)r
;
2367 const macho_nlist
<P
>& leftSym
= parser
->symbolFromIndex(*left
);
2368 const macho_nlist
<P
>& rightSym
= parser
->symbolFromIndex(*right
);
2369 // can't just return difference because 64-bit diff does not fit in 32-bit return type
2370 int64_t result
= leftSym
.n_value() - rightSym
.n_value();
2371 if ( result
== 0 ) {
2372 // two symbols with same address
2373 // if in different sections, sort earlier section first
2374 if ( leftSym
.n_sect() != rightSym
.n_sect() ) {
2375 for (uint32_t i
=0; i
< parser
->machOSectionCount(); ++i
) {
2376 if ( sortedSectionsArray
[i
]+1 == leftSym
.n_sect() )
2378 if ( sortedSectionsArray
[i
]+1 == rightSym
.n_sect() )
2382 // two symbols in same section, means one is an alias
2383 // if one is ltmp*, make it an alias (sort first)
2384 const char* leftName
= parser
->nameFromSymbol(leftSym
);
2385 const char* rightName
= parser
->nameFromSymbol(rightSym
);
2386 bool leftIsTmp
= strncmp(leftName
, "ltmp", 4);
2387 bool rightIsTmp
= strncmp(rightName
, "ltmp", 4);
2388 if ( leftIsTmp
!= rightIsTmp
) {
2389 return (rightIsTmp
? -1 : 1);
2392 // if only one is global, make the other an alias (sort first)
2393 if ( (leftSym
.n_type() & N_EXT
) != (rightSym
.n_type() & N_EXT
) ) {
2394 if ( (rightSym
.n_type() & N_EXT
) != 0 )
2399 // if both are global, sort alphabetically. earlier one will be the alias
2400 return ( strcmp(rightName
, leftName
) );
2402 else if ( result
< 0 )
2409 template <typename A
>
2410 void Parser
<A
>::makeSortedSymbolsArray(uint32_t array
[], const uint32_t sectionArray
[])
2412 const bool log
= false;
2414 uint32_t* p
= array
;
2415 for (uint32_t i
=0; i
< this->_symbolCount
; ++i
) {
2416 const macho_nlist
<P
>& sym
= symbolFromIndex(i
);
2418 if ( (sym
.n_type() & N_STAB
) != 0 )
2421 // only look at definitions
2422 if ( (sym
.n_type() & N_TYPE
) != N_SECT
)
2425 // 'L' labels do not denote atom breaks
2426 const char* symbolName
= this->nameFromSymbol(sym
);
2427 if ( symbolName
[0] == 'L' )
2430 // how many def syms in each section
2431 if ( sym
.n_sect() > _machOSectionsCount
)
2432 throw "bad n_sect in symbol table";
2437 assert(p
== &array
[_symbolsInSections
] && "second pass over symbol table yield a different number of symbols");
2439 // sort by symbol table address
2440 ParserAndSectionsArray extra
= { this, sectionArray
};
2441 ::qsort_r(array
, _symbolsInSections
, sizeof(uint32_t), &extra
, &symbolIndexSorter
);
2444 // look for two symbols at same address
2445 _overlappingSymbols
= false;
2446 for (unsigned int i
=1; i
< _symbolsInSections
; ++i
) {
2447 if ( symbolFromIndex(array
[i
-1]).n_value() == symbolFromIndex(array
[i
]).n_value() ) {
2448 //fprintf(stderr, "overlapping symbols at 0x%08llX\n", symbolFromIndex(array[i-1]).n_value());
2449 _overlappingSymbols
= true;
2455 fprintf(stderr
, "sorted symbols:\n");
2456 for(unsigned int i
=0; i
< _symbolsInSections
; ++i
)
2457 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
])) );
2461 template <typename A
>
2462 void Parser
<A
>::makeSections()
2464 // classify each section by type
2465 // compute how many Section objects will be needed and total size for all
2466 unsigned int totalSectionsSize
= 0;
2467 uint8_t machOSectsStorage
[sizeof(MachOSectionAndSectionClass
<P
>)*(_machOSectionsCount
+2)]; // also room for tentative-defs and absolute symbols
2468 // allocate raw storage for all section objects on stack
2469 MachOSectionAndSectionClass
<P
>* machOSects
= (MachOSectionAndSectionClass
<P
>*)machOSectsStorage
;
2470 unsigned int count
= 0;
2471 // local variable for bitcode parsing
2472 const macho_section
<P
>* bitcodeSect
= NULL
;
2473 const macho_section
<P
>* cmdlineSect
= NULL
;
2474 const macho_section
<P
>* swiftCmdlineSect
= NULL
;
2475 const macho_section
<P
>* bundleSect
= NULL
;
2476 bool bitcodeAsm
= false;
2478 for (uint32_t i
=0; i
< _machOSectionsCount
; ++i
) {
2479 const macho_section
<P
>* sect
= &_sectionsStart
[i
];
2480 uint8_t sectionType
= (sect
->flags() & SECTION_TYPE
);
2481 if ( (sect
->offset() + sect
->size() > _fileLength
) && (sectionType
!= S_ZEROFILL
) && (sectionType
!= S_THREAD_LOCAL_ZEROFILL
) )
2482 throwf("section %s/%s extends beyond end of file,", sect
->segname(), sect
->sectname());
2484 if ( (sect
->flags() & S_ATTR_DEBUG
) != 0 ) {
2485 if ( strcmp(sect
->segname(), "__DWARF") == 0 ) {
2486 // note that .o file has dwarf
2487 _file
->_debugInfoKind
= ld::relocatable::File::kDebugInfoDwarf
;
2488 // save off iteresting dwarf sections
2489 if ( strcmp(sect
->sectname(), "__debug_info") == 0 )
2490 _file
->_dwarfDebugInfoSect
= sect
;
2491 else if ( strcmp(sect
->sectname(), "__debug_abbrev") == 0 )
2492 _file
->_dwarfDebugAbbrevSect
= sect
;
2493 else if ( strcmp(sect
->sectname(), "__debug_line") == 0 )
2494 _file
->_dwarfDebugLineSect
= sect
;
2495 else if ( strcmp(sect
->sectname(), "__debug_str") == 0 )
2496 _file
->_dwarfDebugStringSect
= sect
;
2497 // linker does not propagate dwarf sections to output file
2500 else if ( strcmp(sect
->segname(), "__LD") == 0 ) {
2501 if ( strncmp(sect
->sectname(), "__compact_unwind", 16) == 0 ) {
2502 machOSects
[count
].sect
= sect
;
2503 totalSectionsSize
+= sizeof(CUSection
<A
>);
2504 machOSects
[count
++].type
= sectionTypeCompactUnwind
;
2509 if ( strcmp(sect
->segname(), "__LLVM") == 0 ) {
2510 // Process bitcode segement
2511 if ( strncmp(sect
->sectname(), "__bitcode", 9) == 0 ) {
2513 } else if ( strncmp(sect
->sectname(), "__cmdline", 9) == 0 ) {
2515 } else if ( strncmp(sect
->sectname(), "__swift_cmdline", 15) == 0 ) {
2516 swiftCmdlineSect
= sect
;
2517 } else if ( strncmp(sect
->sectname(), "__bundle", 8) == 0 ) {
2519 } else if ( strncmp(sect
->sectname(), "__asm", 5) == 0 ) {
2522 // If treat the bitcode as data, continue to parse as a normal section.
2523 if ( !_treateBitcodeAsData
)
2526 // ignore empty __OBJC sections
2527 if ( (sect
->size() == 0) && (strcmp(sect
->segname(), "__OBJC") == 0) )
2529 // objc image info section is really attributes and not content
2530 if ( ((strcmp(sect
->sectname(), "__image_info") == 0) && (strcmp(sect
->segname(), "__OBJC") == 0))
2531 || ((strncmp(sect
->sectname(), "__objc_imageinfo", 16) == 0) && (strcmp(sect
->segname(), "__DATA") == 0)) ) {
2532 // struct objc_image_info {
2533 // uint32_t version; // initially 0
2536 // #define OBJC_IMAGE_SUPPORTS_GC 2
2537 // #define OBJC_IMAGE_GC_ONLY 4
2538 // #define OBJC_IMAGE_IS_SIMULATED 32
2539 // #define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES 64
2541 const uint32_t* contents
= (uint32_t*)(_file
->fileContent()+sect
->offset());
2542 if ( (sect
->size() >= 8) && (contents
[0] == 0) ) {
2543 uint32_t flags
= E::get32(contents
[1]);
2544 if ( (flags
& 4) == 4 )
2545 _file
->_objConstraint
= ld::File::objcConstraintGC
;
2546 else if ( (flags
& 2) == 2 )
2547 _file
->_objConstraint
= ld::File::objcConstraintRetainReleaseOrGC
;
2548 else if ( (flags
& 32) == 32 )
2549 _file
->_objConstraint
= ld::File::objcConstraintRetainReleaseForSimulator
;
2551 _file
->_objConstraint
= ld::File::objcConstraintRetainRelease
;
2552 _file
->_swiftVersion
= ((flags
>> 8) & 0xFF);
2553 _file
->_objcHasCategoryClassPropertiesField
= (flags
& 64);
2554 if ( sect
->size() > 8 ) {
2555 warning("section %s/%s has unexpectedly large size %llu in %s",
2556 sect
->segname(), Section
<A
>::makeSectionName(sect
), sect
->size(), _file
->path());
2560 warning("can't parse %s/%s section in %s", sect
->segname(), Section
<A
>::makeSectionName(sect
), _file
->path());
2564 machOSects
[count
].sect
= sect
;
2565 switch ( sect
->flags() & SECTION_TYPE
) {
2566 case S_SYMBOL_STUBS
:
2567 if ( _stubsSectionNum
== 0 ) {
2568 _stubsSectionNum
= i
+1;
2569 _stubsMachOSection
= sect
;
2572 assert(1 && "multiple S_SYMBOL_STUBS sections");
2573 case S_LAZY_SYMBOL_POINTERS
:
2575 case S_4BYTE_LITERALS
:
2576 totalSectionsSize
+= sizeof(Literal4Section
<A
>);
2577 machOSects
[count
++].type
= sectionTypeLiteral4
;
2579 case S_8BYTE_LITERALS
:
2580 totalSectionsSize
+= sizeof(Literal8Section
<A
>);
2581 machOSects
[count
++].type
= sectionTypeLiteral8
;
2583 case S_16BYTE_LITERALS
:
2584 totalSectionsSize
+= sizeof(Literal16Section
<A
>);
2585 machOSects
[count
++].type
= sectionTypeLiteral16
;
2587 case S_NON_LAZY_SYMBOL_POINTERS
:
2588 totalSectionsSize
+= sizeof(NonLazyPointerSection
<A
>);
2589 machOSects
[count
++].type
= sectionTypeNonLazy
;
2591 case S_THREAD_LOCAL_VARIABLE_POINTERS
:
2592 totalSectionsSize
+= sizeof(TLVPointerSection
<A
>);
2593 machOSects
[count
++].type
= sectionTypeTLVPointers
;
2595 case S_LITERAL_POINTERS
:
2596 if ( (strcmp(sect
->segname(), "__OBJC") == 0) && (strcmp(sect
->sectname(), "__cls_refs") == 0) ) {
2597 totalSectionsSize
+= sizeof(Objc1ClassReferences
<A
>);
2598 machOSects
[count
++].type
= sectionTypeObjC1ClassRefs
;
2601 totalSectionsSize
+= sizeof(PointerToCStringSection
<A
>);
2602 machOSects
[count
++].type
= sectionTypeCStringPointer
;
2605 case S_CSTRING_LITERALS
:
2606 totalSectionsSize
+= sizeof(CStringSection
<A
>);
2607 machOSects
[count
++].type
= sectionTypeCString
;
2609 case S_MOD_INIT_FUNC_POINTERS
:
2610 case S_MOD_TERM_FUNC_POINTERS
:
2611 case S_THREAD_LOCAL_INIT_FUNCTION_POINTERS
:
2616 case S_THREAD_LOCAL_REGULAR
:
2617 case S_THREAD_LOCAL_ZEROFILL
:
2618 if ( (strcmp(sect
->segname(), "__TEXT") == 0) && (strcmp(sect
->sectname(), "__eh_frame") == 0) ) {
2619 totalSectionsSize
+= sizeof(CFISection
<A
>);
2620 machOSects
[count
++].type
= sectionTypeCFI
;
2622 else if ( (strcmp(sect
->segname(), "__DATA") == 0) && (strcmp(sect
->sectname(), "__cfstring") == 0) ) {
2623 totalSectionsSize
+= sizeof(CFStringSection
<A
>);
2624 machOSects
[count
++].type
= sectionTypeCFString
;
2626 else if ( (strcmp(sect
->segname(), "__TEXT") == 0) && (strcmp(sect
->sectname(), "__ustring") == 0) ) {
2627 totalSectionsSize
+= sizeof(UTF16StringSection
<A
>);
2628 machOSects
[count
++].type
= sectionTypeUTF16Strings
;
2630 else if ( (strcmp(sect
->segname(), "__DATA") == 0) && (strncmp(sect
->sectname(), "__objc_classrefs", 16) == 0) ) {
2631 totalSectionsSize
+= sizeof(ObjC2ClassRefsSection
<A
>);
2632 machOSects
[count
++].type
= sectionTypeObjC2ClassRefs
;
2634 else if ( (strcmp(sect
->segname(), "__DATA") == 0) && (strcmp(sect
->sectname(), "__objc_catlist") == 0) ) {
2635 totalSectionsSize
+= sizeof(ObjC2CategoryListSection
<A
>);
2636 machOSects
[count
++].type
= typeObjC2CategoryList
;
2638 else if ( _AppleObjc
&& (strcmp(sect
->segname(), "__OBJC") == 0) && (strcmp(sect
->sectname(), "__class") == 0) ) {
2639 totalSectionsSize
+= sizeof(ObjC1ClassSection
<A
>);
2640 machOSects
[count
++].type
= sectionTypeObjC1Classes
;
2643 totalSectionsSize
+= sizeof(SymboledSection
<A
>);
2644 machOSects
[count
++].type
= sectionTypeSymboled
;
2647 case S_THREAD_LOCAL_VARIABLES
:
2648 totalSectionsSize
+= sizeof(TLVDefsSection
<A
>);
2649 machOSects
[count
++].type
= sectionTypeTLVDefs
;
2652 throwf("unknown section type %d", sect
->flags() & SECTION_TYPE
);
2657 if ( bitcodeSect
!= NULL
) {
2658 if ( cmdlineSect
!= NULL
)
2659 _file
->_bitcode
= std::unique_ptr
<ld::Bitcode
>(new ld::ClangBitcode(&_fileContent
[bitcodeSect
->offset()], bitcodeSect
->size(),
2660 &_fileContent
[cmdlineSect
->offset()], cmdlineSect
->size()));
2661 else if ( swiftCmdlineSect
!= NULL
)
2662 _file
->_bitcode
= std::unique_ptr
<ld::Bitcode
>(new ld::SwiftBitcode(&_fileContent
[bitcodeSect
->offset()], bitcodeSect
->size(),
2663 &_fileContent
[swiftCmdlineSect
->offset()], swiftCmdlineSect
->size()));
2665 throwf("Object file with bitcode missing cmdline options: %s", _file
->path());
2667 else if ( bundleSect
!= NULL
)
2668 _file
->_bitcode
= std::unique_ptr
<ld::Bitcode
>(new ld::BundleBitcode(&_fileContent
[bundleSect
->offset()], bundleSect
->size()));
2669 else if ( bitcodeAsm
)
2670 _file
->_bitcode
= std::unique_ptr
<ld::Bitcode
>(new ld::AsmBitcode(_fileContent
, _fileLength
));
2672 // sort by address (mach-o object files don't aways have sections sorted)
2673 ::qsort(machOSects
, count
, sizeof(MachOSectionAndSectionClass
<P
>), MachOSectionAndSectionClass
<P
>::sorter
);
2675 // we will synthesize a dummy Section<A> object for tentative definitions
2676 if ( _tentativeDefinitionCount
> 0 ) {
2677 totalSectionsSize
+= sizeof(TentativeDefinitionSection
<A
>);
2678 machOSects
[count
++].type
= sectionTypeTentativeDefinitions
;
2681 // we will synthesize a dummy Section<A> object for Absolute symbols
2682 if ( _absoluteSymbolCount
> 0 ) {
2683 totalSectionsSize
+= sizeof(AbsoluteSymbolSection
<A
>);
2684 machOSects
[count
++].type
= sectionTypeAbsoluteSymbols
;
2687 // allocate one block for all Section objects as well as pointers to each
2688 uint8_t* space
= new uint8_t[totalSectionsSize
+count
*sizeof(Section
<A
>*)];
2689 _file
->_sectionsArray
= (Section
<A
>**)space
;
2690 _file
->_sectionsArrayCount
= count
;
2691 Section
<A
>** objects
= _file
->_sectionsArray
;
2692 space
+= count
*sizeof(Section
<A
>*);
2693 for (uint32_t i
=0; i
< count
; ++i
) {
2694 switch ( machOSects
[i
].type
) {
2695 case sectionTypeIgnore
:
2697 case sectionTypeLiteral4
:
2698 *objects
++ = new (space
) Literal4Section
<A
>(*this, *_file
, machOSects
[i
].sect
);
2699 space
+= sizeof(Literal4Section
<A
>);
2701 case sectionTypeLiteral8
:
2702 *objects
++ = new (space
) Literal8Section
<A
>(*this, *_file
, machOSects
[i
].sect
);
2703 space
+= sizeof(Literal8Section
<A
>);
2705 case sectionTypeLiteral16
:
2706 *objects
++ = new (space
) Literal16Section
<A
>(*this, *_file
, machOSects
[i
].sect
);
2707 space
+= sizeof(Literal16Section
<A
>);
2709 case sectionTypeNonLazy
:
2710 *objects
++ = new (space
) NonLazyPointerSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2711 space
+= sizeof(NonLazyPointerSection
<A
>);
2713 case sectionTypeTLVPointers
:
2714 *objects
++ = new (space
) TLVPointerSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2715 space
+= sizeof(TLVPointerSection
<A
>);
2717 case sectionTypeCFI
:
2718 _EHFrameSection
= new (space
) CFISection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2719 *objects
++ = _EHFrameSection
;
2720 space
+= sizeof(CFISection
<A
>);
2722 case sectionTypeCString
:
2723 *objects
++ = new (space
) CStringSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2724 space
+= sizeof(CStringSection
<A
>);
2726 case sectionTypeCStringPointer
:
2727 *objects
++ = new (space
) PointerToCStringSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2728 space
+= sizeof(PointerToCStringSection
<A
>);
2730 case sectionTypeObjC1ClassRefs
:
2731 *objects
++ = new (space
) Objc1ClassReferences
<A
>(*this, *_file
, machOSects
[i
].sect
);
2732 space
+= sizeof(Objc1ClassReferences
<A
>);
2734 case sectionTypeUTF16Strings
:
2735 *objects
++ = new (space
) UTF16StringSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2736 space
+= sizeof(UTF16StringSection
<A
>);
2738 case sectionTypeCFString
:
2739 *objects
++ = new (space
) CFStringSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2740 space
+= sizeof(CFStringSection
<A
>);
2742 case sectionTypeObjC2ClassRefs
:
2743 *objects
++ = new (space
) ObjC2ClassRefsSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2744 space
+= sizeof(ObjC2ClassRefsSection
<A
>);
2746 case typeObjC2CategoryList
:
2747 *objects
++ = new (space
) ObjC2CategoryListSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2748 space
+= sizeof(ObjC2CategoryListSection
<A
>);
2750 case sectionTypeObjC1Classes
:
2751 *objects
++ = new (space
) ObjC1ClassSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2752 space
+= sizeof(ObjC1ClassSection
<A
>);
2754 case sectionTypeSymboled
:
2755 *objects
++ = new (space
) SymboledSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2756 space
+= sizeof(SymboledSection
<A
>);
2758 case sectionTypeTLVDefs
:
2759 *objects
++ = new (space
) TLVDefsSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2760 space
+= sizeof(TLVDefsSection
<A
>);
2762 case sectionTypeCompactUnwind
:
2763 _compactUnwindSection
= new (space
) CUSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2764 *objects
++ = _compactUnwindSection
;
2765 space
+= sizeof(CUSection
<A
>);
2767 case sectionTypeTentativeDefinitions
:
2768 *objects
++ = new (space
) TentativeDefinitionSection
<A
>(*this, *_file
);
2769 space
+= sizeof(TentativeDefinitionSection
<A
>);
2771 case sectionTypeAbsoluteSymbols
:
2772 _absoluteSection
= new (space
) AbsoluteSymbolSection
<A
>(*this, *_file
);
2773 *objects
++ = _absoluteSection
;
2774 space
+= sizeof(AbsoluteSymbolSection
<A
>);
2777 throw "internal error uknown SectionType";
2783 template <typename A
>
2784 Section
<A
>* Parser
<A
>::sectionForAddress(typename
A::P::uint_t addr
)
2786 for (uint32_t i
=0; i
< _file
->_sectionsArrayCount
; ++i
) {
2787 const macho_section
<typename
A::P
>* sect
= _file
->_sectionsArray
[i
]->machoSection();
2788 // TentativeDefinitionSection and AbsoluteSymbolSection have no mach-o section
2789 if ( sect
!= NULL
) {
2790 if ( (sect
->addr() <= addr
) && (addr
< (sect
->addr()+sect
->size())) ) {
2791 return _file
->_sectionsArray
[i
];
2795 // not strictly in any section
2796 // may be in a zero length section
2797 for (uint32_t i
=0; i
< _file
->_sectionsArrayCount
; ++i
) {
2798 const macho_section
<typename
A::P
>* sect
= _file
->_sectionsArray
[i
]->machoSection();
2799 // TentativeDefinitionSection and AbsoluteSymbolSection have no mach-o section
2800 if ( sect
!= NULL
) {
2801 if ( (sect
->addr() == addr
) && (sect
->size() == 0) ) {
2802 return _file
->_sectionsArray
[i
];
2807 throwf("sectionForAddress(0x%llX) address not in any section", (uint64_t)addr
);
2810 template <typename A
>
2811 Section
<A
>* Parser
<A
>::sectionForNum(unsigned int num
)
2813 for (uint32_t i
=0; i
< _file
->_sectionsArrayCount
; ++i
) {
2814 const macho_section
<typename
A::P
>* sect
= _file
->_sectionsArray
[i
]->machoSection();
2815 // TentativeDefinitionSection and AbsoluteSymbolSection have no mach-o section
2816 if ( sect
!= NULL
) {
2817 if ( num
== (unsigned int)((sect
- _sectionsStart
)+1) )
2818 return _file
->_sectionsArray
[i
];
2821 throwf("sectionForNum(%u) section number not for any section", num
);
2824 template <typename A
>
2825 Atom
<A
>* Parser
<A
>::findAtomByAddress(pint_t addr
)
2827 Section
<A
>* section
= this->sectionForAddress(addr
);
2828 return section
->findAtomByAddress(addr
);
2831 template <typename A
>
2832 Atom
<A
>* Parser
<A
>::findAtomByAddressOrNullIfStub(pint_t addr
)
2834 if ( hasStubsSection() && (_stubsMachOSection
->addr() <= addr
) && (addr
< (_stubsMachOSection
->addr()+_stubsMachOSection
->size())) )
2836 return findAtomByAddress(addr
);
2839 template <typename A
>
2840 Atom
<A
>* Parser
<A
>::findAtomByAddressOrLocalTargetOfStub(pint_t addr
, uint32_t* offsetInAtom
)
2842 if ( hasStubsSection() && (_stubsMachOSection
->addr() <= addr
) && (addr
< (_stubsMachOSection
->addr()+_stubsMachOSection
->size())) ) {
2843 // target is a stub, remove indirection
2844 uint32_t symbolIndex
= this->symbolIndexFromIndirectSectionAddress(addr
, _stubsMachOSection
);
2845 assert(symbolIndex
!= INDIRECT_SYMBOL_LOCAL
);
2846 const macho_nlist
<P
>& sym
= this->symbolFromIndex(symbolIndex
);
2847 // can't be to external weak symbol
2848 assert( (this->combineFromSymbol(sym
) != ld::Atom::combineByName
) || (this->scopeFromSymbol(sym
) != ld::Atom::scopeGlobal
) );
2850 return this->findAtomByName(this->nameFromSymbol(sym
));
2852 Atom
<A
>* target
= this->findAtomByAddress(addr
);
2853 *offsetInAtom
= addr
- target
->_objAddress
;
2857 template <typename A
>
2858 Atom
<A
>* Parser
<A
>::findAtomByName(const char* name
)
2860 uint8_t* p
= _file
->_atomsArray
;
2861 for(int i
=_file
->_atomsArrayCount
; i
> 0; --i
) {
2862 Atom
<A
>* atom
= (Atom
<A
>*)p
;
2863 if ( strcmp(name
, atom
->name()) == 0 )
2865 p
+= sizeof(Atom
<A
>);
2870 template <typename A
>
2871 void Parser
<A
>::findTargetFromAddress(pint_t addr
, TargetDesc
& target
)
2873 if ( hasStubsSection() && (_stubsMachOSection
->addr() <= addr
) && (addr
< (_stubsMachOSection
->addr()+_stubsMachOSection
->size())) ) {
2874 // target is a stub, remove indirection
2875 uint32_t symbolIndex
= this->symbolIndexFromIndirectSectionAddress(addr
, _stubsMachOSection
);
2876 assert(symbolIndex
!= INDIRECT_SYMBOL_LOCAL
);
2877 const macho_nlist
<P
>& sym
= this->symbolFromIndex(symbolIndex
);
2879 target
.name
= this->nameFromSymbol(sym
);
2880 target
.weakImport
= this->weakImportFromSymbol(sym
);
2884 Section
<A
>* section
= this->sectionForAddress(addr
);
2885 target
.atom
= section
->findAtomByAddress(addr
);
2886 target
.addend
= addr
- target
.atom
->_objAddress
;
2887 target
.weakImport
= false;
2891 template <typename A
>
2892 void Parser
<A
>::findTargetFromAddress(pint_t baseAddr
, pint_t addr
, TargetDesc
& target
)
2894 findTargetFromAddress(baseAddr
, target
);
2895 target
.addend
= addr
- target
.atom
->_objAddress
;
2898 template <typename A
>
2899 void Parser
<A
>::findTargetFromAddressAndSectionNum(pint_t addr
, unsigned int sectNum
, TargetDesc
& target
)
2901 if ( sectNum
== R_ABS
) {
2902 // target is absolute symbol that corresponds to addr
2903 if ( _absoluteSection
!= NULL
) {
2904 target
.atom
= _absoluteSection
->findAbsAtomForValue(addr
);
2905 if ( target
.atom
!= NULL
) {
2907 target
.weakImport
= false;
2912 throwf("R_ABS reloc but no absolute symbol at target address");
2915 if ( hasStubsSection() && (stubsSectionNum() == sectNum
) ) {
2916 // target is a stub, remove indirection
2917 uint32_t symbolIndex
= this->symbolIndexFromIndirectSectionAddress(addr
, _stubsMachOSection
);
2918 assert(symbolIndex
!= INDIRECT_SYMBOL_LOCAL
);
2919 const macho_nlist
<P
>& sym
= this->symbolFromIndex(symbolIndex
);
2920 // use direct reference when stub is to a static function
2921 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && (((sym
.n_type() & N_EXT
) == 0) || (this->nameFromSymbol(sym
)[0] == 'L')) ) {
2922 this->findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
2926 target
.name
= this->nameFromSymbol(sym
);
2927 target
.weakImport
= this->weakImportFromSymbol(sym
);
2932 Section
<A
>* section
= this->sectionForNum(sectNum
);
2933 target
.atom
= section
->findAtomByAddress(addr
);
2934 if ( target
.atom
== NULL
) {
2935 typedef typename
A::P::sint_t sint_t
;
2936 sint_t a
= (sint_t
)addr
;
2937 sint_t sectStart
= (sint_t
)(section
->machoSection()->addr());
2938 sint_t sectEnd
= sectStart
+ section
->machoSection()->size();
2939 if ( a
< sectStart
) {
2940 // target address is before start of section, so must be negative addend
2941 target
.atom
= section
->findAtomByAddress(sectStart
);
2942 target
.addend
= a
- sectStart
;
2943 target
.weakImport
= false;
2947 else if ( a
>= sectEnd
) {
2948 target
.atom
= section
->findAtomByAddress(sectEnd
-1);
2949 target
.addend
= a
- sectEnd
;
2950 target
.weakImport
= false;
2955 assert(target
.atom
!= NULL
);
2956 target
.addend
= addr
- target
.atom
->_objAddress
;
2957 target
.weakImport
= false;
2961 template <typename A
>
2962 void Parser
<A
>::addDtraceExtraInfos(const SourceLocation
& src
, const char* providerName
)
2964 // for every ___dtrace_stability$* and ___dtrace_typedefs$* undefine with
2965 // a matching provider name, add a by-name kDtraceTypeReference at probe site
2966 const char* dollar
= strchr(providerName
, '$');
2967 if ( dollar
!= NULL
) {
2968 int providerNameLen
= dollar
-providerName
+1;
2969 for ( std::vector
<const char*>::iterator it
= _dtraceProviderInfo
.begin(); it
!= _dtraceProviderInfo
.end(); ++it
) {
2970 const char* typeDollar
= strchr(*it
, '$');
2971 if ( typeDollar
!= NULL
) {
2972 if ( strncmp(typeDollar
+1, providerName
, providerNameLen
) == 0 ) {
2973 addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindDtraceExtra
,false, *it
);
2980 template <typename A
>
2981 const char* Parser
<A
>::scanSymbolTableForAddress(uint64_t addr
)
2983 uint64_t closestSymAddr
= 0;
2984 const char* closestSymName
= NULL
;
2985 for (uint32_t i
=0; i
< this->_symbolCount
; ++i
) {
2986 const macho_nlist
<P
>& sym
= symbolFromIndex(i
);
2988 if ( (sym
.n_type() & N_STAB
) != 0 )
2991 // only look at definitions
2992 if ( (sym
.n_type() & N_TYPE
) != N_SECT
)
2995 // return with exact match
2996 if ( sym
.n_value() == addr
) {
2997 const char* name
= nameFromSymbol(sym
);
2998 if ( strncmp(name
, "ltmp", 4) != 0 )
3000 // treat 'ltmp*' labels as close match
3001 closestSymAddr
= sym
.n_value();
3002 closestSymName
= name
;
3005 // record closest seen so far
3006 if ( (sym
.n_value() < addr
) && ((sym
.n_value() > closestSymAddr
) || (closestSymName
== NULL
)) )
3007 closestSymName
= nameFromSymbol(sym
);
3010 return (closestSymName
!= NULL
) ? closestSymName
: "unknown";
3014 template <typename A
>
3015 void Parser
<A
>::addFixups(const SourceLocation
& src
, ld::Fixup::Kind setKind
, const TargetDesc
& target
)
3017 // some fixup pairs can be combined
3018 ld::Fixup::Cluster cl
= ld::Fixup::k1of3
;
3019 ld::Fixup::Kind firstKind
= ld::Fixup::kindSetTargetAddress
;
3020 bool combined
= false;
3021 if ( target
.addend
== 0 ) {
3022 cl
= ld::Fixup::k1of1
;
3024 switch ( setKind
) {
3025 case ld::Fixup::kindStoreLittleEndian32
:
3026 firstKind
= ld::Fixup::kindStoreTargetAddressLittleEndian32
;
3028 case ld::Fixup::kindStoreLittleEndian64
:
3029 firstKind
= ld::Fixup::kindStoreTargetAddressLittleEndian64
;
3031 case ld::Fixup::kindStoreBigEndian32
:
3032 firstKind
= ld::Fixup::kindStoreTargetAddressBigEndian32
;
3034 case ld::Fixup::kindStoreBigEndian64
:
3035 firstKind
= ld::Fixup::kindStoreTargetAddressBigEndian64
;
3037 case ld::Fixup::kindStoreX86BranchPCRel32
:
3038 firstKind
= ld::Fixup::kindStoreTargetAddressX86BranchPCRel32
;
3040 case ld::Fixup::kindStoreX86PCRel32
:
3041 firstKind
= ld::Fixup::kindStoreTargetAddressX86PCRel32
;
3043 case ld::Fixup::kindStoreX86PCRel32GOTLoad
:
3044 firstKind
= ld::Fixup::kindStoreTargetAddressX86PCRel32GOTLoad
;
3046 case ld::Fixup::kindStoreX86PCRel32TLVLoad
:
3047 firstKind
= ld::Fixup::kindStoreTargetAddressX86PCRel32TLVLoad
;
3049 case ld::Fixup::kindStoreX86Abs32TLVLoad
:
3050 firstKind
= ld::Fixup::kindStoreTargetAddressX86Abs32TLVLoad
;
3052 case ld::Fixup::kindStoreARMBranch24
:
3053 firstKind
= ld::Fixup::kindStoreTargetAddressARMBranch24
;
3055 case ld::Fixup::kindStoreThumbBranch22
:
3056 firstKind
= ld::Fixup::kindStoreTargetAddressThumbBranch22
;
3058 #if SUPPORT_ARCH_arm64
3059 case ld::Fixup::kindStoreARM64Branch26
:
3060 firstKind
= ld::Fixup::kindStoreTargetAddressARM64Branch26
;
3062 case ld::Fixup::kindStoreARM64Page21
:
3063 firstKind
= ld::Fixup::kindStoreTargetAddressARM64Page21
;
3065 case ld::Fixup::kindStoreARM64PageOff12
:
3066 firstKind
= ld::Fixup::kindStoreTargetAddressARM64PageOff12
;
3068 case ld::Fixup::kindStoreARM64GOTLoadPage21
:
3069 firstKind
= ld::Fixup::kindStoreTargetAddressARM64GOTLoadPage21
;
3071 case ld::Fixup::kindStoreARM64GOTLoadPageOff12
:
3072 firstKind
= ld::Fixup::kindStoreTargetAddressARM64GOTLoadPageOff12
;
3074 case ld::Fixup::kindStoreARM64TLVPLoadPage21
:
3075 firstKind
= ld::Fixup::kindStoreTargetAddressARM64TLVPLoadPage21
;
3077 case ld::Fixup::kindStoreARM64TLVPLoadPageOff12
:
3078 firstKind
= ld::Fixup::kindStoreTargetAddressARM64TLVPLoadPageOff12
;
3083 cl
= ld::Fixup::k1of2
;
3088 if ( target
.atom
!= NULL
) {
3089 if ( target
.atom
->scope() == ld::Atom::scopeTranslationUnit
) {
3090 addFixup(src
, cl
, firstKind
, target
.atom
);
3092 else if ( (target
.atom
->combine() == ld::Atom::combineByNameAndContent
) || (target
.atom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
3093 addFixup(src
, cl
, firstKind
, ld::Fixup::bindingByContentBound
, target
.atom
);
3095 else if ( (src
.atom
->section().type() == ld::Section::typeCFString
) && (src
.offsetInAtom
!= 0) ) {
3096 // backing string in CFStrings should always be direct
3097 addFixup(src
, cl
, firstKind
, target
.atom
);
3099 else if ( (src
.atom
== target
.atom
) && (target
.atom
->combine() == ld::Atom::combineByName
) ) {
3100 // reference to self should always be direct
3101 addFixup(src
, cl
, firstKind
, target
.atom
);
3104 // change direct fixup to by-name fixup
3105 addFixup(src
, cl
, firstKind
, false, target
.atom
->name());
3109 addFixup(src
, cl
, firstKind
, target
.weakImport
, target
.name
);
3111 if ( target
.addend
== 0 ) {
3113 addFixup(src
, ld::Fixup::k2of2
, setKind
);
3116 addFixup(src
, ld::Fixup::k2of3
, ld::Fixup::kindAddAddend
, target
.addend
);
3117 addFixup(src
, ld::Fixup::k3of3
, setKind
);
3121 template <typename A
>
3122 void Parser
<A
>::addFixups(const SourceLocation
& src
, ld::Fixup::Kind kind
, const TargetDesc
& target
, const TargetDesc
& picBase
)
3124 ld::Fixup::Cluster cl
= (target
.addend
== 0) ? ld::Fixup::k1of4
: ld::Fixup::k1of5
;
3125 if ( target
.atom
!= NULL
) {
3126 if ( target
.atom
->scope() == ld::Atom::scopeTranslationUnit
) {
3127 addFixup(src
, cl
, ld::Fixup::kindSetTargetAddress
, target
.atom
);
3129 else if ( (target
.atom
->combine() == ld::Atom::combineByNameAndContent
) || (target
.atom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
3130 addFixup(src
, cl
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, target
.atom
);
3133 addFixup(src
, cl
, ld::Fixup::kindSetTargetAddress
, false, target
.atom
->name());
3137 addFixup(src
, cl
, ld::Fixup::kindSetTargetAddress
, target
.weakImport
, target
.name
);
3139 if ( target
.addend
== 0 ) {
3140 assert(picBase
.atom
!= NULL
);
3141 addFixup(src
, ld::Fixup::k2of4
, ld::Fixup::kindSubtractTargetAddress
, picBase
.atom
);
3142 addFixup(src
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractAddend
, picBase
.addend
);
3143 addFixup(src
, ld::Fixup::k4of4
, kind
);
3146 addFixup(src
, ld::Fixup::k2of5
, ld::Fixup::kindAddAddend
, target
.addend
);
3147 addFixup(src
, ld::Fixup::k3of5
, ld::Fixup::kindSubtractTargetAddress
, picBase
.atom
);
3148 addFixup(src
, ld::Fixup::k4of5
, ld::Fixup::kindSubtractAddend
, picBase
.addend
);
3149 addFixup(src
, ld::Fixup::k5of5
, kind
);
3155 template <typename A
>
3156 uint32_t TentativeDefinitionSection
<A
>::computeAtomCount(class Parser
<A
>& parser
,
3157 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
3158 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
3160 return parser
.tentativeDefinitionCount();
3163 template <typename A
>
3164 uint32_t TentativeDefinitionSection
<A
>::appendAtoms(class Parser
<A
>& parser
, uint8_t* p
,
3165 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
3166 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
3168 this->_beginAtoms
= (Atom
<A
>*)p
;
3170 for (uint32_t i
=parser
.undefinedStartIndex(); i
< parser
.undefinedEndIndex(); ++i
) {
3171 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(i
);
3172 if ( ((sym
.n_type() & N_TYPE
) == N_UNDF
) && (sym
.n_value() != 0) ) {
3173 uint64_t size
= sym
.n_value();
3174 uint8_t alignP2
= GET_COMM_ALIGN(sym
.n_desc());
3175 if ( alignP2
== 0 ) {
3176 // common symbols align to their size
3177 // that is, a 4-byte common aligns to 4-bytes
3178 // if this size is not a power of two,
3179 // then round up to the next power of two
3180 alignP2
= 63 - (uint8_t)__builtin_clzll(size
);
3181 if ( size
!= (1ULL << alignP2
) )
3183 // <rdar://problem/24871389> limit default alignment of large commons
3184 if ( alignP2
> parser
.maxDefaultCommonAlignment() )
3185 alignP2
= parser
.maxDefaultCommonAlignment();
3187 Atom
<A
>* allocatedSpace
= (Atom
<A
>*)p
;
3188 new (allocatedSpace
) Atom
<A
>(*this, parser
.nameFromSymbol(sym
), (pint_t
)ULLONG_MAX
, size
,
3189 ld::Atom::definitionTentative
, ld::Atom::combineByName
,
3190 parser
.scopeFromSymbol(sym
), ld::Atom::typeZeroFill
, ld::Atom::symbolTableIn
,
3191 parser
.dontDeadStripFromSymbol(sym
), false, false, ld::Atom::Alignment(alignP2
) );
3192 p
+= sizeof(Atom
<A
>);
3196 this->_endAtoms
= (Atom
<A
>*)p
;
3201 template <typename A
>
3202 uint32_t AbsoluteSymbolSection
<A
>::computeAtomCount(class Parser
<A
>& parser
,
3203 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
3204 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
3206 return parser
.absoluteSymbolCount();
3209 template <typename A
>
3210 uint32_t AbsoluteSymbolSection
<A
>::appendAtoms(class Parser
<A
>& parser
, uint8_t* p
,
3211 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
3212 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
3214 this->_beginAtoms
= (Atom
<A
>*)p
;
3216 for (uint32_t i
=0; i
< parser
.symbolCount(); ++i
) {
3217 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(i
);
3218 if ( (sym
.n_type() & N_TYPE
) != N_ABS
)
3220 const char* absName
= parser
.nameFromSymbol(sym
);
3221 // ignore .objc_class_name_* symbols
3222 if ( strncmp(absName
, ".objc_class_name_", 17) == 0 )
3224 // ignore .objc_class_name_* symbols
3225 if ( strncmp(absName
, ".objc_category_name_", 20) == 0 )
3227 // ignore empty *.eh symbols
3228 if ( strcmp(&absName
[strlen(absName
)-3], ".eh") == 0 )
3231 Atom
<A
>* allocatedSpace
= (Atom
<A
>*)p
;
3232 new (allocatedSpace
) Atom
<A
>(*this, parser
, sym
, 0);
3233 p
+= sizeof(Atom
<A
>);
3236 this->_endAtoms
= (Atom
<A
>*)p
;
3240 template <typename A
>
3241 Atom
<A
>* AbsoluteSymbolSection
<A
>::findAbsAtomForValue(typename
A::P::uint_t value
)
3243 Atom
<A
>* end
= this->_endAtoms
;
3244 for(Atom
<A
>* p
= this->_beginAtoms
; p
< end
; ++p
) {
3245 if ( p
->_objAddress
== value
)
3252 template <typename A
>
3253 uint32_t Parser
<A
>::indirectSymbol(uint32_t indirectIndex
)
3255 if ( indirectIndex
>= _indirectTableCount
)
3256 throw "indirect symbol index out of range";
3257 return E::get32(_indirectTable
[indirectIndex
]);
3260 template <typename A
>
3261 const macho_nlist
<typename
A::P
>& Parser
<A
>::symbolFromIndex(uint32_t index
)
3263 if ( index
> _symbolCount
)
3264 throw "symbol index out of range";
3265 return _symbols
[index
];
3268 template <typename A
>
3269 const macho_section
<typename
A::P
>* Parser
<A
>::machOSectionFromSectionIndex(uint32_t index
)
3271 if ( index
>= _machOSectionsCount
)
3272 throw "section index out of range";
3273 return &_sectionsStart
[index
];
3276 template <typename A
>
3277 uint32_t Parser
<A
>::symbolIndexFromIndirectSectionAddress(pint_t addr
, const macho_section
<P
>* sect
)
3279 uint32_t elementSize
= 0;
3280 switch ( sect
->flags() & SECTION_TYPE
) {
3281 case S_SYMBOL_STUBS
:
3282 elementSize
= sect
->reserved2();
3284 case S_LAZY_SYMBOL_POINTERS
:
3285 case S_NON_LAZY_SYMBOL_POINTERS
:
3286 case S_THREAD_LOCAL_VARIABLE_POINTERS
:
3287 elementSize
= sizeof(pint_t
);
3290 throw "section does not use indirect symbol table";
3292 uint32_t indexInSection
= (addr
- sect
->addr()) / elementSize
;
3293 uint32_t indexIntoIndirectTable
= sect
->reserved1() + indexInSection
;
3294 return this->indirectSymbol(indexIntoIndirectTable
);
3299 template <typename A
>
3300 const char* Parser
<A
>::nameFromSymbol(const macho_nlist
<P
>& sym
)
3302 return &_strings
[sym
.n_strx()];
3305 template <typename A
>
3306 ld::Atom::Scope Parser
<A
>::scopeFromSymbol(const macho_nlist
<P
>& sym
)
3308 if ( (sym
.n_type() & N_EXT
) == 0 )
3309 return ld::Atom::scopeTranslationUnit
;
3310 else if ( (sym
.n_type() & N_PEXT
) != 0 )
3311 return ld::Atom::scopeLinkageUnit
;
3312 else if ( this->nameFromSymbol(sym
)[0] == 'l' ) // since all 'l' symbols will be remove, don't make them global
3313 return ld::Atom::scopeLinkageUnit
;
3315 return ld::Atom::scopeGlobal
;
3318 template <typename A
>
3319 ld::Atom::Definition Parser
<A
>::definitionFromSymbol(const macho_nlist
<P
>& sym
)
3321 switch ( sym
.n_type() & N_TYPE
) {
3323 return ld::Atom::definitionAbsolute
;
3325 return ld::Atom::definitionRegular
;
3327 if ( sym
.n_value() != 0 )
3328 return ld::Atom::definitionTentative
;
3330 throw "definitionFromSymbol() bad symbol";
3333 template <typename A
>
3334 ld::Atom::Combine Parser
<A
>::combineFromSymbol(const macho_nlist
<P
>& sym
)
3336 if ( sym
.n_desc() & N_WEAK_DEF
)
3337 return ld::Atom::combineByName
;
3339 return ld::Atom::combineNever
;
3343 template <typename A
>
3344 ld::Atom::SymbolTableInclusion Parser
<A
>::inclusionFromSymbol(const macho_nlist
<P
>& sym
)
3346 const char* symbolName
= nameFromSymbol(sym
);
3347 // labels beginning with 'l' (lowercase ell) are automatically removed in final linked images <rdar://problem/4571042>
3348 // labels beginning with 'L' should have been stripped by the assembler, so are stripped now
3349 if ( sym
.n_desc() & REFERENCED_DYNAMICALLY
)
3350 return ld::Atom::symbolTableInAndNeverStrip
;
3351 else if ( symbolName
[0] == 'l' )
3352 return ld::Atom::symbolTableNotInFinalLinkedImages
;
3353 else if ( symbolName
[0] == 'L' )
3354 return ld::Atom::symbolTableNotIn
;
3356 return ld::Atom::symbolTableIn
;
3359 template <typename A
>
3360 bool Parser
<A
>::dontDeadStripFromSymbol(const macho_nlist
<P
>& sym
)
3362 return ( (sym
.n_desc() & (N_NO_DEAD_STRIP
|REFERENCED_DYNAMICALLY
)) != 0 );
3365 template <typename A
>
3366 bool Parser
<A
>::isThumbFromSymbol(const macho_nlist
<P
>& sym
)
3368 return ( sym
.n_desc() & N_ARM_THUMB_DEF
);
3371 template <typename A
>
3372 bool Parser
<A
>::weakImportFromSymbol(const macho_nlist
<P
>& sym
)
3374 return ( ((sym
.n_type() & N_TYPE
) == N_UNDF
) && ((sym
.n_desc() & N_WEAK_REF
) != 0) );
3377 template <typename A
>
3378 bool Parser
<A
>::resolverFromSymbol(const macho_nlist
<P
>& sym
)
3380 return ( sym
.n_desc() & N_SYMBOL_RESOLVER
);
3383 template <typename A
>
3384 bool Parser
<A
>::altEntryFromSymbol(const macho_nlist
<P
>& sym
)
3386 return ( sym
.n_desc() & N_ALT_ENTRY
);
3390 /* Skip over a LEB128 value (signed or unsigned). */
3392 skip_leb128 (const uint8_t ** offset
, const uint8_t * end
)
3394 while (*offset
!= end
&& **offset
>= 0x80)
3400 /* Read a ULEB128 into a 64-bit word. Return (uint64_t)-1 on overflow
3401 or error. On overflow, skip past the rest of the uleb128. */
3403 read_uleb128 (const uint8_t ** offset
, const uint8_t * end
)
3405 uint64_t result
= 0;
3412 return (uint64_t) -1;
3414 b
= **offset
& 0x7f;
3416 if (bit
>= 64 || b
<< bit
>> bit
!= b
)
3417 result
= (uint64_t) -1;
3419 result
|= b
<< bit
, bit
+= 7;
3420 } while (*(*offset
)++ >= 0x80);
3425 /* Skip over a DWARF attribute of form FORM. */
3426 template <typename A
>
3427 bool Parser
<A
>::skip_form(const uint8_t ** offset
, const uint8_t * end
, uint64_t form
,
3428 uint8_t addr_size
, bool dwarf64
)
3438 case DW_FORM_block2
:
3439 if (end
- *offset
< 2)
3441 sz
= 2 + A::P::E::get16(*(uint16_t*)offset
);
3444 case DW_FORM_block4
:
3445 if (end
- *offset
< 4)
3447 sz
= 2 + A::P::E::get32(*(uint32_t*)offset
);
3465 case DW_FORM_string
:
3466 while (*offset
!= end
&& **offset
)
3475 sz
= read_uleb128 (offset
, end
);
3478 case DW_FORM_block1
:
3486 case DW_FORM_ref_udata
:
3487 skip_leb128 (offset
, end
);
3491 case DW_FORM_ref_addr
:
3495 case DW_FORM_sec_offset
:
3496 sz
= sizeof(typename
A::P::uint_t
);
3499 case DW_FORM_exprloc
:
3500 sz
= read_uleb128 (offset
, end
);
3503 case DW_FORM_flag_present
:
3507 case DW_FORM_ref_sig8
:
3514 if (end
- *offset
< sz
)
3521 template <typename A
>
3522 const char* Parser
<A
>::getDwarfString(uint64_t form
, const uint8_t*& di
)
3525 const char* dwarfStrings
;
3526 const char* result
= NULL
;
3528 case DW_FORM_string
:
3529 result
= (const char*)di
;
3530 di
+= strlen(result
) + 1;
3533 offset
= E::get32(*((uint32_t*)di
));
3534 dwarfStrings
= (char*)_file
->fileContent() + _file
->_dwarfDebugStringSect
->offset();
3535 if ( offset
< _file
->_dwarfDebugStringSect
->size() )
3536 result
= &dwarfStrings
[offset
];
3538 warning("dwarf DW_FORM_strp (offset=0x%08X) is too big in %s", offset
, this->_path
);
3542 warning("unknown dwarf string encoding (form=%lld) in %s", form
, this->_path
);
3548 template <typename A
>
3549 uint64_t Parser
<A
>::getDwarfOffset(uint64_t form
, const uint8_t*& di
, bool dwarf64
)
3551 if ( form
== DW_FORM_sec_offset
)
3552 form
= (dwarf64
? DW_FORM_data8
: DW_FORM_data4
);
3553 uint64_t result
= -1;
3556 result
= A::P::E::get32(*(uint32_t*)di
);
3560 result
= A::P::E::get64(*(uint64_t*)di
);
3564 warning("unknown dwarf DW_FORM_ for DW_AT_stmt_list in %s", this->_path
);
3570 template <typename A
>
3571 struct AtomAndLineInfo
{
3573 ld::Atom::LineInfo info
;
3577 // <rdar://problem/5591394> Add support to ld64 for N_FUN stabs when used for symbolic constants
3578 // Returns whether a stabStr belonging to an N_FUN stab represents a
3579 // symbolic constant rather than a function
3580 template <typename A
>
3581 bool Parser
<A
>::isConstFunStabs(const char *stabStr
)
3584 // N_FUN can be used for both constants and for functions. In case it's a constant,
3585 // the format of the stabs string is "symname:c=<value>;"
3586 // ':' cannot appear in the symbol name, except if it's an Objective-C method
3587 // (in which case the symbol name starts with + or -, and then it's definitely
3589 return (stabStr
!= NULL
) && (stabStr
[0] != '+') && (stabStr
[0] != '-')
3590 && ((colon
= strchr(stabStr
, ':')) != NULL
)
3591 && (colon
[1] == 'c') && (colon
[2] == '=');
3595 template <typename A
>
3596 void Parser
<A
>::parseDebugInfo()
3598 // check for dwarf __debug_info section
3599 if ( _file
->_dwarfDebugInfoSect
== NULL
) {
3600 // if no DWARF debug info, look for stabs
3604 if ( _file
->_dwarfDebugInfoSect
->size() == 0 )
3610 if ( !read_comp_unit(&tuName
, &tuDir
, &stmtList
) ) {
3611 // if can't parse dwarf, warn and give up
3612 _file
->_dwarfTranslationUnitPath
= NULL
;
3613 warning("can't parse dwarf compilation unit info in %s", _path
);
3614 _file
->_debugInfoKind
= ld::relocatable::File::kDebugInfoNone
;
3617 if ( (tuName
!= NULL
) && (tuName
[0] == '/') ) {
3618 _file
->_dwarfTranslationUnitPath
= tuName
;
3620 else if ( (tuDir
!= NULL
) && (tuName
!= NULL
) ) {
3621 asprintf((char**)&(_file
->_dwarfTranslationUnitPath
), "%s/%s", tuDir
, tuName
);
3623 else if ( tuDir
== NULL
) {
3624 _file
->_dwarfTranslationUnitPath
= tuName
;
3627 _file
->_dwarfTranslationUnitPath
= NULL
;
3630 // add line number info to atoms from dwarf
3631 std::vector
<AtomAndLineInfo
<A
> > entries
;
3632 entries
.reserve(64);
3633 if ( _file
->_debugInfoKind
== ld::relocatable::File::kDebugInfoDwarf
) {
3634 // file with just data will have no __debug_line info
3635 if ( (_file
->_dwarfDebugLineSect
!= NULL
) && (_file
->_dwarfDebugLineSect
->size() != 0) ) {
3636 // validate stmt_list
3637 if ( (stmtList
!= (uint64_t)-1) && (stmtList
< _file
->_dwarfDebugLineSect
->size()) ) {
3638 const uint8_t* debug_line
= (uint8_t*)_file
->fileContent() + _file
->_dwarfDebugLineSect
->offset();
3639 struct line_reader_data
* lines
= line_open(&debug_line
[stmtList
],
3640 _file
->_dwarfDebugLineSect
->size() - stmtList
, E::little_endian
);
3641 struct line_info result
;
3642 Atom
<A
>* curAtom
= NULL
;
3643 uint32_t curAtomOffset
= 0;
3644 uint32_t curAtomAddress
= 0;
3645 uint32_t curAtomSize
= 0;
3646 std::map
<uint32_t,const char*> dwarfIndexToFile
;
3647 if ( lines
!= NULL
) {
3648 while ( line_next(lines
, &result
, line_stop_pc
) ) {
3649 //fprintf(stderr, "curAtom=%p, result.pc=0x%llX, result.line=%llu, result.end_of_sequence=%d,"
3650 // " curAtomAddress=0x%X, curAtomSize=0x%X\n",
3651 // curAtom, result.pc, result.line, result.end_of_sequence, curAtomAddress, curAtomSize);
3652 // work around weird debug line table compiler generates if no functions in __text section
3653 if ( (curAtom
== NULL
) && (result
.pc
== 0) && result
.end_of_sequence
&& (result
.file
== 1))
3655 // for performance, see if in next pc is in current atom
3656 if ( (curAtom
!= NULL
) && (curAtomAddress
<= result
.pc
) && (result
.pc
< (curAtomAddress
+curAtomSize
)) ) {
3657 curAtomOffset
= result
.pc
- curAtomAddress
;
3659 // or pc at end of current atom
3660 else if ( result
.end_of_sequence
&& (curAtom
!= NULL
) && (result
.pc
== (curAtomAddress
+curAtomSize
)) ) {
3661 curAtomOffset
= result
.pc
- curAtomAddress
;
3663 // or only one function that is a one line function
3664 else if ( result
.end_of_sequence
&& (curAtom
== NULL
) && (this->findAtomByAddress(0) != NULL
) && (result
.pc
== this->findAtomByAddress(0)->size()) ) {
3665 curAtom
= this->findAtomByAddress(0);
3666 curAtomOffset
= result
.pc
- curAtom
->objectAddress();
3667 curAtomAddress
= curAtom
->objectAddress();
3668 curAtomSize
= curAtom
->size();
3671 // do slow look up of atom by address
3673 curAtom
= this->findAtomByAddress(result
.pc
);
3676 // in case of bug in debug info, don't abort link, just limp on
3679 if ( curAtom
== NULL
)
3680 break; // file has line info but no functions
3681 if ( result
.end_of_sequence
&& (curAtomAddress
+curAtomSize
< result
.pc
) ) {
3682 // a one line function can be returned by line_next() as one entry with pc at end of blob
3683 // look for alt atom starting at end of previous atom
3684 uint32_t previousEnd
= curAtomAddress
+curAtomSize
;
3685 Atom
<A
>* alt
= this->findAtomByAddressOrNullIfStub(previousEnd
);
3687 continue; // ignore spurious debug info for stubs
3688 if ( result
.pc
<= alt
->objectAddress() + alt
->size() ) {
3690 curAtomOffset
= result
.pc
- alt
->objectAddress();
3691 curAtomAddress
= alt
->objectAddress();
3692 curAtomSize
= alt
->size();
3695 curAtomOffset
= result
.pc
- curAtom
->objectAddress();
3696 curAtomAddress
= curAtom
->objectAddress();
3697 curAtomSize
= curAtom
->size();
3701 curAtomOffset
= result
.pc
- curAtom
->objectAddress();
3702 curAtomAddress
= curAtom
->objectAddress();
3703 curAtomSize
= curAtom
->size();
3706 const char* filename
;
3707 std::map
<uint32_t,const char*>::iterator pos
= dwarfIndexToFile
.find(result
.file
);
3708 if ( pos
== dwarfIndexToFile
.end() ) {
3709 filename
= line_file(lines
, result
.file
);
3710 dwarfIndexToFile
[result
.file
] = filename
;
3713 filename
= pos
->second
;
3715 // only record for ~8000 line info records per function
3716 if ( curAtom
->roomForMoreLineInfoCount() ) {
3717 AtomAndLineInfo
<A
> entry
;
3718 entry
.atom
= curAtom
;
3719 entry
.info
.atomOffset
= curAtomOffset
;
3720 entry
.info
.fileName
= filename
;
3721 entry
.info
.lineNumber
= result
.line
;
3722 //fprintf(stderr, "addr=0x%08llX, line=%lld, file=%s, atom=%s, atom.size=0x%X, end=%d\n",
3723 // result.pc, result.line, filename, curAtom->name(), curAtomSize, result.end_of_sequence);
3724 entries
.push_back(entry
);
3725 curAtom
->incrementLineInfoCount();
3727 if ( result
.end_of_sequence
) {
3737 // assign line info start offset for each atom
3738 uint8_t* p
= _file
->_atomsArray
;
3739 uint32_t liOffset
= 0;
3740 for(int i
=_file
->_atomsArrayCount
; i
> 0; --i
) {
3741 Atom
<A
>* atom
= (Atom
<A
>*)p
;
3742 atom
->_lineInfoStartIndex
= liOffset
;
3743 liOffset
+= atom
->_lineInfoCount
;
3744 atom
->_lineInfoCount
= 0;
3745 p
+= sizeof(Atom
<A
>);
3747 assert(liOffset
== entries
.size());
3748 _file
->_lineInfos
.resize(liOffset
);
3750 // copy each line info for each atom
3751 for (typename
std::vector
<AtomAndLineInfo
<A
> >::iterator it
= entries
.begin(); it
!= entries
.end(); ++it
) {
3752 uint32_t slot
= it
->atom
->_lineInfoStartIndex
+ it
->atom
->_lineInfoCount
;
3753 _file
->_lineInfos
[slot
] = it
->info
;
3754 it
->atom
->_lineInfoCount
++;
3757 // done with temp vector
3761 template <typename A
>
3762 void Parser
<A
>::parseStabs()
3764 // scan symbol table for stabs entries
3765 Atom
<A
>* currentAtom
= NULL
;
3766 pint_t currentAtomAddress
= 0;
3767 enum { start
, inBeginEnd
, inFun
} state
= start
;
3768 for (uint32_t symbolIndex
= 0; symbolIndex
< _symbolCount
; ++symbolIndex
) {
3769 const macho_nlist
<P
>& sym
= this->symbolFromIndex(symbolIndex
);
3770 bool useStab
= true;
3771 uint8_t type
= sym
.n_type();
3772 const char* symString
= (sym
.n_strx() != 0) ? this->nameFromSymbol(sym
) : NULL
;
3773 if ( (type
& N_STAB
) != 0 ) {
3774 _file
->_debugInfoKind
= (_hasUUID
? ld::relocatable::File::kDebugInfoStabsUUID
: ld::relocatable::File::kDebugInfoStabs
);
3775 ld::relocatable::File::Stab stab
;
3778 stab
.other
= sym
.n_sect();
3779 stab
.desc
= sym
.n_desc();
3780 stab
.value
= sym
.n_value();
3786 // beginning of function block
3788 // fall into case to lookup atom by addresss
3791 currentAtomAddress
= sym
.n_value();
3792 currentAtom
= this->findAtomByAddress(currentAtomAddress
);
3793 if ( currentAtom
!= NULL
) {
3794 stab
.atom
= currentAtom
;
3795 stab
.string
= symString
;
3798 fprintf(stderr
, "can't find atom for stabs BNSYM at %08llX in %s",
3799 (uint64_t)sym
.n_value(), _path
);
3809 // not associated with an atom, just copy
3810 stab
.string
= symString
;
3814 // n_value field is NOT atom address ;-(
3815 // need to find atom by name match
3816 const char* colon
= strchr(symString
, ':');
3817 if ( colon
!= NULL
) {
3818 // build underscore leading name
3819 int nameLen
= colon
- symString
;
3820 char symName
[nameLen
+2];
3821 strlcpy(&symName
[1], symString
, nameLen
+1);
3823 symName
[nameLen
+1] = '\0';
3824 currentAtom
= this->findAtomByName(symName
);
3825 if ( currentAtom
!= NULL
) {
3826 stab
.atom
= currentAtom
;
3827 stab
.string
= symString
;
3831 // might be a debug-note without trailing :G()
3832 currentAtom
= this->findAtomByName(symString
);
3833 if ( currentAtom
!= NULL
) {
3834 stab
.atom
= currentAtom
;
3835 stab
.string
= symString
;
3838 if ( stab
.atom
== NULL
) {
3839 // ld_classic added bogus GSYM stabs for old style dtrace probes
3840 if ( (strncmp(symString
, "__dtrace_probe$", 15) != 0) )
3841 warning("can't find atom for N_GSYM stabs %s in %s", symString
, _path
);
3847 if ( isConstFunStabs(symString
) ) {
3848 // constant not associated with a function
3849 stab
.string
= symString
;
3852 // old style stabs without BNSYM
3854 currentAtomAddress
= sym
.n_value();
3855 currentAtom
= this->findAtomByAddress(currentAtomAddress
);
3856 if ( currentAtom
!= NULL
) {
3857 stab
.atom
= currentAtom
;
3858 stab
.string
= symString
;
3861 warning("can't find atom for stabs FUN at %08llX in %s",
3862 (uint64_t)currentAtomAddress
, _path
);
3868 stab
.string
= symString
;
3874 stab
.string
= symString
;
3875 // -gfull built .o file
3878 warning("unknown stabs type 0x%X in %s", type
, _path
);
3882 stab
.atom
= currentAtom
;
3891 Atom
<A
>* nestedAtom
= this->findAtomByAddress(sym
.n_value());
3892 if ( nestedAtom
!= NULL
) {
3893 stab
.atom
= nestedAtom
;
3894 stab
.string
= symString
;
3897 warning("can't find atom for stabs 0x%X at %08llX in %s",
3898 type
, (uint64_t)sym
.n_value(), _path
);
3905 // adjust value to be offset in atom
3906 stab
.value
-= currentAtomAddress
;
3908 stab
.string
= symString
;
3915 if ( isConstFunStabs(symString
) ) {
3916 stab
.atom
= currentAtom
;
3917 stab
.string
= symString
;
3920 if ( sym
.n_sect() != 0 ) {
3921 // found another start stab, must be really old stabs...
3922 currentAtomAddress
= sym
.n_value();
3923 currentAtom
= this->findAtomByAddress(currentAtomAddress
);
3924 if ( currentAtom
!= NULL
) {
3925 stab
.atom
= currentAtom
;
3926 stab
.string
= symString
;
3929 warning("can't find atom for stabs FUN at %08llX in %s",
3930 (uint64_t)currentAtomAddress
, _path
);
3934 // found ending stab, switch back to start state
3935 stab
.string
= symString
;
3936 stab
.atom
= currentAtom
;
3945 // adjust value to be offset in atom
3946 stab
.value
-= currentAtomAddress
;
3947 stab
.atom
= currentAtom
;
3950 stab
.string
= symString
;
3954 stab
.atom
= currentAtom
;
3955 stab
.string
= symString
;
3960 // add to list of stabs for this .o file
3962 _file
->_stabs
.push_back(stab
);
3969 // Look at the compilation unit DIE and determine
3970 // its NAME, compilation directory (in COMP_DIR) and its
3971 // line number information offset (in STMT_LIST). NAME and COMP_DIR
3972 // may be NULL (especially COMP_DIR) if they are not in the .o file;
3973 // STMT_LIST will be (uint64_t) -1.
3975 // At present this assumes that there's only one compilation unit DIE.
3977 template <typename A
>
3978 bool Parser
<A
>::read_comp_unit(const char ** name
, const char ** comp_dir
,
3979 uint64_t *stmt_list
)
3981 const uint8_t * debug_info
;
3982 const uint8_t * debug_abbrev
;
3984 const uint8_t * next_cu
;
3986 const uint8_t * end
;
3987 const uint8_t * enda
;
3990 uint64_t abbrev_base
;
3992 uint8_t address_size
;
3997 *stmt_list
= (uint64_t) -1;
3999 if ( (_file
->_dwarfDebugInfoSect
== NULL
) || (_file
->_dwarfDebugAbbrevSect
== NULL
) )
4002 if (_file
->_dwarfDebugInfoSect
->size() < 12)
4003 /* Too small to be a real debug_info section. */
4006 debug_info
= (uint8_t*)_file
->fileContent() + _file
->_dwarfDebugInfoSect
->offset();
4007 debug_abbrev
= (uint8_t*)_file
->fileContent() + _file
->_dwarfDebugAbbrevSect
->offset();
4008 next_cu
= debug_info
;
4010 while ((uint64_t)(next_cu
- debug_info
) < _file
->_dwarfDebugInfoSect
->size()) {
4012 sz
= A::P::E::get32(*(uint32_t*)di
);
4014 dwarf64
= sz
== 0xffffffff;
4016 sz
= A::P::E::get64(*(uint64_t*)di
), di
+= 8;
4017 else if (sz
> 0xffffff00)
4018 /* Unknown dwarf format. */
4021 /* Verify claimed size. */
4022 if (sz
+ (di
- debug_info
) > _file
->_dwarfDebugInfoSect
->size() || sz
<= (dwarf64
? 23 : 11))
4027 vers
= A::P::E::get16(*(uint16_t*)di
);
4028 if (vers
< 2 || vers
> 4)
4029 /* DWARF version wrong for this code.
4030 Chances are we could continue anyway, but we don't know for sure. */
4034 /* Find the debug_abbrev section. */
4035 abbrev_base
= dwarf64
? A::P::E::get64(*(uint64_t*)di
) : A::P::E::get32(*(uint32_t*)di
);
4036 di
+= dwarf64
? 8 : 4;
4038 if (abbrev_base
> _file
->_dwarfDebugAbbrevSect
->size())
4040 da
= debug_abbrev
+ abbrev_base
;
4041 enda
= debug_abbrev
+ _file
->_dwarfDebugAbbrevSect
->size();
4043 address_size
= *di
++;
4045 /* Find the abbrev number we're looking for. */
4047 abbrev
= read_uleb128 (&di
, end
);
4048 if (abbrev
== (uint64_t) -1)
4051 /* Skip through the debug_abbrev section looking for that abbrev. */
4054 uint64_t this_abbrev
= read_uleb128 (&da
, enda
);
4057 if (this_abbrev
== abbrev
)
4058 /* This is almost always taken. */
4060 skip_leb128 (&da
, enda
); /* Skip the tag. */
4063 da
++; /* Skip the DW_CHILDREN_* value. */
4066 attr
= read_uleb128 (&da
, enda
);
4067 skip_leb128 (&da
, enda
);
4068 } while (attr
!= 0 && attr
!= (uint64_t) -1);
4073 /* Check that the abbrev is one for a DW_TAG_compile_unit. */
4074 if (read_uleb128 (&da
, enda
) != DW_TAG_compile_unit
)
4078 da
++; /* Skip the DW_CHILDREN_* value. */
4080 /* Now, go through the DIE looking for DW_AT_name,
4081 DW_AT_comp_dir, and DW_AT_stmt_list. */
4082 bool skip_to_next_cu
= false;
4083 while (!skip_to_next_cu
) {
4085 uint64_t attr
= read_uleb128 (&da
, enda
);
4086 uint64_t form
= read_uleb128 (&da
, enda
);
4088 if (attr
== (uint64_t) -1)
4092 if (form
== DW_FORM_indirect
)
4093 form
= read_uleb128 (&di
, end
);
4097 *name
= getDwarfString(form
, di
);
4098 /* Swift object files may contain two CUs: One
4099 describes the Swift code, one is created by the
4100 clang importer. Skip over the CU created by the
4101 clang importer as it may be empty. */
4102 if (std::string(*name
) == "<swift-imported-modules>")
4103 skip_to_next_cu
= true;
4105 case DW_AT_comp_dir
:
4106 *comp_dir
= getDwarfString(form
, di
);
4108 case DW_AT_stmt_list
:
4109 *stmt_list
= getDwarfOffset(form
, di
, dwarf64
);
4112 if (! skip_form (&di
, end
, form
, address_size
, dwarf64
))
4122 template <typename A
>
4125 free(_sectionsArray
);
4129 template <typename A
>
4130 const char* File
<A
>::translationUnitSource() const
4132 return _dwarfTranslationUnitPath
;
4135 template <typename A
>
4136 bool File
<A
>::forEachAtom(ld::File::AtomHandler
& handler
) const
4138 handler
.doFile(*this);
4139 uint8_t* p
= _atomsArray
;
4140 for(int i
=_atomsArrayCount
; i
> 0; --i
) {
4141 handler
.doAtom(*((Atom
<A
>*)p
));
4142 p
+= sizeof(Atom
<A
>);
4144 p
= _aliasAtomsArray
;
4145 for(int i
=_aliasAtomsArrayCount
; i
> 0; --i
) {
4146 handler
.doAtom(*((AliasAtom
*)p
));
4147 p
+= sizeof(AliasAtom
);
4150 return (_atomsArrayCount
!= 0) || (_aliasAtomsArrayCount
!= 0);
4153 template <typename A
>
4154 const char* Section
<A
>::makeSegmentName(const macho_section
<typename
A::P
>* sect
)
4156 // mach-o section record only has room for 16-byte seg/sect names
4157 // so a 16-byte name has no trailing zero
4158 const char* name
= sect
->segname();
4159 if ( strlen(name
) < 16 )
4161 char* tmp
= new char[17];
4162 strlcpy(tmp
, name
, 17);
4166 template <typename A
>
4167 const char* Section
<A
>::makeSectionName(const macho_section
<typename
A::P
>* sect
)
4169 const char* name
= sect
->sectname();
4170 if ( strlen(name
) < 16 )
4173 // special case common long section names so we don't have to malloc
4174 if ( strncmp(sect
->sectname(), "__objc_classrefs", 16) == 0 )
4175 return "__objc_classrefs";
4176 if ( strncmp(sect
->sectname(), "__objc_classlist", 16) == 0 )
4177 return "__objc_classlist";
4178 if ( strncmp(sect
->sectname(), "__objc_nlclslist", 16) == 0 )
4179 return "__objc_nlclslist";
4180 if ( strncmp(sect
->sectname(), "__objc_nlcatlist", 16) == 0 )
4181 return "__objc_nlcatlist";
4182 if ( strncmp(sect
->sectname(), "__objc_protolist", 16) == 0 )
4183 return "__objc_protolist";
4184 if ( strncmp(sect
->sectname(), "__objc_protorefs", 16) == 0 )
4185 return "__objc_protorefs";
4186 if ( strncmp(sect
->sectname(), "__objc_superrefs", 16) == 0 )
4187 return "__objc_superrefs";
4188 if ( strncmp(sect
->sectname(), "__objc_imageinfo", 16) == 0 )
4189 return "__objc_imageinfo";
4190 if ( strncmp(sect
->sectname(), "__objc_stringobj", 16) == 0 )
4191 return "__objc_stringobj";
4192 if ( strncmp(sect
->sectname(), "__gcc_except_tab", 16) == 0 )
4193 return "__gcc_except_tab";
4195 char* tmp
= new char[17];
4196 strlcpy(tmp
, name
, 17);
4200 template <typename A
>
4201 bool Section
<A
>::readable(const macho_section
<typename
A::P
>* sect
)
4206 template <typename A
>
4207 bool Section
<A
>::writable(const macho_section
<typename
A::P
>* sect
)
4209 // mach-o .o files do not contain segment permissions
4210 // we just know TEXT is special
4211 return ( strcmp(sect
->segname(), "__TEXT") != 0 );
4214 template <typename A
>
4215 bool Section
<A
>::exectuable(const macho_section
<typename
A::P
>* sect
)
4217 // mach-o .o files do not contain segment permissions
4218 // we just know TEXT is special
4219 return ( strcmp(sect
->segname(), "__TEXT") == 0 );
4223 template <typename A
>
4224 ld::Section::Type Section
<A
>::sectionType(const macho_section
<typename
A::P
>* sect
)
4226 switch ( sect
->flags() & SECTION_TYPE
) {
4228 return ld::Section::typeZeroFill
;
4229 case S_CSTRING_LITERALS
:
4230 if ( (strcmp(sect
->sectname(), "__cstring") == 0) && (strcmp(sect
->segname(), "__TEXT") == 0) )
4231 return ld::Section::typeCString
;
4233 return ld::Section::typeNonStdCString
;
4234 case S_4BYTE_LITERALS
:
4235 return ld::Section::typeLiteral4
;
4236 case S_8BYTE_LITERALS
:
4237 return ld::Section::typeLiteral8
;
4238 case S_LITERAL_POINTERS
:
4239 return ld::Section::typeCStringPointer
;
4240 case S_NON_LAZY_SYMBOL_POINTERS
:
4241 return ld::Section::typeNonLazyPointer
;
4242 case S_LAZY_SYMBOL_POINTERS
:
4243 return ld::Section::typeLazyPointer
;
4244 case S_SYMBOL_STUBS
:
4245 return ld::Section::typeStub
;
4246 case S_MOD_INIT_FUNC_POINTERS
:
4247 return ld::Section::typeInitializerPointers
;
4248 case S_MOD_TERM_FUNC_POINTERS
:
4249 return ld::Section::typeTerminatorPointers
;
4251 return ld::Section::typeUnclassified
;
4252 case S_16BYTE_LITERALS
:
4253 return ld::Section::typeLiteral16
;
4256 if ( sect
->flags() & S_ATTR_PURE_INSTRUCTIONS
) {
4257 return ld::Section::typeCode
;
4259 else if ( strcmp(sect
->segname(), "__TEXT") == 0 ) {
4260 if ( strcmp(sect
->sectname(), "__eh_frame") == 0 )
4261 return ld::Section::typeCFI
;
4262 else if ( strcmp(sect
->sectname(), "__ustring") == 0 )
4263 return ld::Section::typeUTF16Strings
;
4264 else if ( strcmp(sect
->sectname(), "__textcoal_nt") == 0 )
4265 return ld::Section::typeCode
;
4266 else if ( strcmp(sect
->sectname(), "__StaticInit") == 0 )
4267 return ld::Section::typeCode
;
4268 else if ( strcmp(sect
->sectname(), "__constructor") == 0 )
4269 return ld::Section::typeInitializerPointers
;
4271 else if ( strcmp(sect
->segname(), "__DATA") == 0 ) {
4272 if ( strcmp(sect
->sectname(), "__cfstring") == 0 )
4273 return ld::Section::typeCFString
;
4274 else if ( strcmp(sect
->sectname(), "__dyld") == 0 )
4275 return ld::Section::typeDyldInfo
;
4276 else if ( strcmp(sect
->sectname(), "__program_vars") == 0 )
4277 return ld::Section::typeDyldInfo
;
4278 else if ( strncmp(sect
->sectname(), "__objc_classrefs", 16) == 0 )
4279 return ld::Section::typeObjCClassRefs
;
4280 else if ( strcmp(sect
->sectname(), "__objc_catlist") == 0 )
4281 return ld::Section::typeObjC2CategoryList
;
4283 else if ( strcmp(sect
->segname(), "__OBJC") == 0 ) {
4284 if ( strcmp(sect
->sectname(), "__class") == 0 )
4285 return ld::Section::typeObjC1Classes
;
4288 case S_THREAD_LOCAL_REGULAR
:
4289 return ld::Section::typeTLVInitialValues
;
4290 case S_THREAD_LOCAL_ZEROFILL
:
4291 return ld::Section::typeTLVZeroFill
;
4292 case S_THREAD_LOCAL_VARIABLES
:
4293 return ld::Section::typeTLVDefs
;
4294 case S_THREAD_LOCAL_VARIABLE_POINTERS
:
4295 return ld::Section::typeTLVPointers
;
4296 case S_THREAD_LOCAL_INIT_FUNCTION_POINTERS
:
4297 return ld::Section::typeTLVInitializerPointers
;
4299 return ld::Section::typeUnclassified
;
4303 template <typename A
>
4304 Atom
<A
>* Section
<A
>::findContentAtomByAddress(pint_t addr
, class Atom
<A
>* start
, class Atom
<A
>* end
)
4306 // do a binary search of atom array
4307 uint32_t atomCount
= end
- start
;
4308 Atom
<A
>* base
= start
;
4309 for (uint32_t n
= atomCount
; n
> 0; n
/= 2) {
4310 Atom
<A
>* pivot
= &base
[n
/2];
4311 pint_t atomStartAddr
= pivot
->_objAddress
;
4312 pint_t atomEndAddr
= atomStartAddr
+ pivot
->_size
;
4313 if ( atomStartAddr
<= addr
) {
4314 // address in normal atom
4315 if (addr
< atomEndAddr
)
4317 // address in "end" label (but not in alias)
4318 if ( (pivot
->_size
== 0) && (addr
== atomEndAddr
) && !pivot
->isAlias() )
4321 if ( addr
>= atomEndAddr
) {
4323 // move base to atom after pivot
4335 template <typename A
>
4336 ld::Atom::Alignment Section
<A
>::alignmentForAddress(pint_t addr
)
4338 const uint32_t sectionAlignment
= this->_machOSection
->align();
4339 uint32_t modulus
= (addr
% (1 << sectionAlignment
));
4340 if ( modulus
> 0xFFFF )
4341 warning("alignment for symbol at address 0x%08llX in %s exceeds 2^16", (uint64_t)addr
, this->file().path());
4342 return ld::Atom::Alignment(sectionAlignment
, modulus
);
4345 template <typename A
>
4346 uint32_t Section
<A
>::sectionNum(class Parser
<A
>& parser
) const
4348 if ( _machOSection
== NULL
)
4351 return 1 + (this->_machOSection
- parser
.firstMachOSection());
4354 // arm does not have zero cost exceptions
4356 uint32_t CFISection
<arm
>::cfiCount(Parser
<arm
>& parser
)
4358 if ( parser
.armUsesZeroCostExceptions() ) {
4359 // create ObjectAddressSpace object for use by libunwind
4360 OAS
oas(*this, (uint8_t*)this->file().fileContent()+this->_machOSection
->offset());
4361 return libunwind::CFI_Parser
<OAS
>::getCFICount(oas
,
4362 this->_machOSection
->addr(), this->_machOSection
->size());
4367 template <typename A
>
4368 uint32_t CFISection
<A
>::cfiCount(Parser
<A
>& parser
)
4370 // create ObjectAddressSpace object for use by libunwind
4371 OAS
oas(*this, (uint8_t*)this->file().fileContent()+this->_machOSection
->offset());
4372 return libunwind::CFI_Parser
<OAS
>::getCFICount(oas
,
4373 this->_machOSection
->addr(), this->_machOSection
->size());
4376 template <typename A
>
4377 void CFISection
<A
>::warnFunc(void* ref
, uint64_t funcAddr
, const char* msg
)
4379 Parser
<A
>* parser
= (Parser
<A
>*)ref
;
4380 if ( ! parser
->warnUnwindConversionProblems() )
4382 if ( funcAddr
!= CFI_INVALID_ADDRESS
) {
4383 // atoms are not constructed yet, so scan symbol table for labels
4384 const char* name
= parser
->scanSymbolTableForAddress(funcAddr
);
4385 warning("could not create compact unwind for %s: %s", name
, msg
);
4388 warning("could not create compact unwind: %s", msg
);
4393 bool CFISection
<x86_64
>::needsRelocating()
4399 bool CFISection
<arm64
>::needsRelocating()
4405 template <typename A
>
4406 bool CFISection
<A
>::needsRelocating()
4412 void CFISection
<x86_64
>::cfiParse(class Parser
<x86_64
>& parser
, uint8_t* buffer
,
4413 libunwind::CFI_Atom_Info
<CFISection
<x86_64
>::OAS
>::CFI_Atom_Info cfiArray
[],
4414 uint32_t& count
, const pint_t cuStarts
[], uint32_t cuCount
)
4416 const uint32_t sectionSize
= this->_machOSection
->size();
4417 // copy __eh_frame data to buffer
4418 memcpy(buffer
, file().fileContent() + this->_machOSection
->offset(), sectionSize
);
4420 // and apply relocations
4421 const macho_relocation_info
<P
>* relocs
= (macho_relocation_info
<P
>*)(file().fileContent() + this->_machOSection
->reloff());
4422 const macho_relocation_info
<P
>* relocsEnd
= &relocs
[this->_machOSection
->nreloc()];
4423 for (const macho_relocation_info
<P
>* reloc
= relocs
; reloc
< relocsEnd
; ++reloc
) {
4425 switch ( reloc
->r_type() ) {
4426 case X86_64_RELOC_SUBTRACTOR
:
4427 value
= 0 - parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
4429 if ( reloc
->r_extern() )
4430 value
+= parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
4432 case X86_64_RELOC_UNSIGNED
:
4433 value
= parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
4435 case X86_64_RELOC_GOT
:
4436 // this is used for the reference to the personality function in CIEs
4437 // store the symbol number of the personality function for later use as a Fixup
4438 value
= reloc
->r_symbolnum();
4441 fprintf(stderr
, "CFISection::cfiParse() unexpected relocation type at r_address=0x%08X\n", reloc
->r_address());
4444 if ( reloc
->r_address() > sectionSize
)
4445 throwf("malformed __eh_frame relocation, offset (0x%08X) is beyond end of section,", reloc
->r_address());
4448 switch ( reloc
->r_length() ) {
4450 p64
= (uint64_t*)&buffer
[reloc
->r_address()];
4451 E::set64(*p64
, value
+ E::get64(*p64
));
4454 p32
= (uint32_t*)&buffer
[reloc
->r_address()];
4455 E::set32(*p32
, value
+ E::get32(*p32
));
4458 fprintf(stderr
, "CFISection::cfiParse() unexpected relocation size at r_address=0x%08X\n", reloc
->r_address());
4463 // create ObjectAddressSpace object for use by libunwind
4464 OAS
oas(*this, buffer
);
4466 // use libuwind to parse __eh_frame data into array of CFI_Atom_Info
4468 msg
= libunwind::DwarfInstructions
<OAS
, libunwind::Registers_x86_64
>::parseCFIs(
4469 oas
, this->_machOSection
->addr(), this->_machOSection
->size(),
4470 cuStarts
, cuCount
, parser
.keepDwarfUnwind(), parser
.forceDwarfConversion(), parser
.neverConvertDwarf(),
4471 cfiArray
, count
, (void*)&parser
, warnFunc
);
4473 throwf("malformed __eh_frame section: %s", msg
);
4477 void CFISection
<x86
>::cfiParse(class Parser
<x86
>& parser
, uint8_t* buffer
,
4478 libunwind::CFI_Atom_Info
<CFISection
<x86
>::OAS
>::CFI_Atom_Info cfiArray
[],
4479 uint32_t& count
, const pint_t cuStarts
[], uint32_t cuCount
)
4481 // create ObjectAddressSpace object for use by libunwind
4482 OAS
oas(*this, (uint8_t*)this->file().fileContent()+this->_machOSection
->offset());
4484 // use libuwind to parse __eh_frame data into array of CFI_Atom_Info
4486 msg
= libunwind::DwarfInstructions
<OAS
, libunwind::Registers_x86
>::parseCFIs(
4487 oas
, this->_machOSection
->addr(), this->_machOSection
->size(),
4488 cuStarts
, cuCount
, parser
.keepDwarfUnwind(), parser
.forceDwarfConversion(), parser
.neverConvertDwarf(),
4489 cfiArray
, count
, (void*)&parser
, warnFunc
);
4491 throwf("malformed __eh_frame section: %s", msg
);
4498 void CFISection
<arm
>::cfiParse(class Parser
<arm
>& parser
, uint8_t* buffer
,
4499 libunwind::CFI_Atom_Info
<CFISection
<arm
>::OAS
>::CFI_Atom_Info cfiArray
[],
4500 uint32_t& count
, const pint_t cuStarts
[], uint32_t cuCount
)
4502 if ( !parser
.armUsesZeroCostExceptions() ) {
4503 // most arm do not use zero cost exceptions
4507 // create ObjectAddressSpace object for use by libunwind
4508 OAS
oas(*this, (uint8_t*)this->file().fileContent()+this->_machOSection
->offset());
4510 // use libuwind to parse __eh_frame data into array of CFI_Atom_Info
4512 msg
= libunwind::DwarfInstructions
<OAS
, libunwind::Registers_arm
>::parseCFIs(
4513 oas
, this->_machOSection
->addr(), this->_machOSection
->size(),
4514 cuStarts
, cuCount
, parser
.keepDwarfUnwind(), parser
.forceDwarfConversion(), parser
.neverConvertDwarf(),
4515 cfiArray
, count
, (void*)&parser
, warnFunc
);
4517 throwf("malformed __eh_frame section: %s", msg
);
4524 void CFISection
<arm64
>::cfiParse(class Parser
<arm64
>& parser
, uint8_t* buffer
,
4525 libunwind::CFI_Atom_Info
<CFISection
<arm64
>::OAS
>::CFI_Atom_Info cfiArray
[],
4526 uint32_t& count
, const pint_t cuStarts
[], uint32_t cuCount
)
4528 // copy __eh_frame data to buffer
4529 const uint32_t sectionSize
= this->_machOSection
->size();
4530 memcpy(buffer
, file().fileContent() + this->_machOSection
->offset(), sectionSize
);
4532 // and apply relocations
4533 const macho_relocation_info
<P
>* relocs
= (macho_relocation_info
<P
>*)(file().fileContent() + this->_machOSection
->reloff());
4534 const macho_relocation_info
<P
>* relocsEnd
= &relocs
[this->_machOSection
->nreloc()];
4535 for (const macho_relocation_info
<P
>* reloc
= relocs
; reloc
< relocsEnd
; ++reloc
) {
4536 uint64_t* p64
= (uint64_t*)&buffer
[reloc
->r_address()];
4537 uint32_t* p32
= (uint32_t*)&buffer
[reloc
->r_address()];
4538 uint32_t addend32
= E::get32(*p32
);
4539 uint64_t addend64
= E::get64(*p64
);
4541 switch ( reloc
->r_type() ) {
4542 case ARM64_RELOC_SUBTRACTOR
:
4543 value
= 0 - parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
4545 if ( reloc
->r_extern() )
4546 value
+= parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
4548 case ARM64_RELOC_UNSIGNED
:
4549 value
= parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
4551 case ARM64_RELOC_POINTER_TO_GOT
:
4552 // this is used for the reference to the personality function in CIEs
4553 // store the symbol number of the personality function for later use as a Fixup
4554 value
= reloc
->r_symbolnum();
4559 fprintf(stderr
, "CFISection::cfiParse() unexpected relocation type at r_address=0x%08X\n", reloc
->r_address());
4562 if ( reloc
->r_address() > sectionSize
)
4563 throwf("malformed __eh_frame relocation, offset (0x%08X) is beyond end of section,", reloc
->r_address());
4564 switch ( reloc
->r_length() ) {
4566 E::set64(*p64
, value
+ addend64
);
4569 E::set32(*p32
, value
+ addend32
);
4572 fprintf(stderr
, "CFISection::cfiParse() unexpected relocation size at r_address=0x%08X\n", reloc
->r_address());
4578 // create ObjectAddressSpace object for use by libunwind
4579 OAS
oas(*this, buffer
);
4581 // use libuwind to parse __eh_frame data into array of CFI_Atom_Info
4583 msg
= libunwind::DwarfInstructions
<OAS
, libunwind::Registers_arm64
>::parseCFIs(
4584 oas
, this->_machOSection
->addr(), this->_machOSection
->size(),
4585 cuStarts
, cuCount
, parser
.keepDwarfUnwind(), parser
.forceDwarfConversion(), parser
.neverConvertDwarf(),
4586 cfiArray
, count
, (void*)&parser
, warnFunc
);
4588 throwf("malformed __eh_frame section: %s", msg
);
4592 template <typename A
>
4593 uint32_t CFISection
<A
>::computeAtomCount(class Parser
<A
>& parser
,
4594 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
4595 const struct Parser
<A
>::CFI_CU_InfoArrays
& cfis
)
4597 return cfis
.cfiCount
;
4602 template <typename A
>
4603 uint32_t CFISection
<A
>::appendAtoms(class Parser
<A
>& parser
, uint8_t* p
,
4604 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
4605 const struct Parser
<A
>::CFI_CU_InfoArrays
& cfis
)
4607 this->_beginAtoms
= (Atom
<A
>*)p
;
4608 // walk CFI_Atom_Info array and create atom for each entry
4609 const CFI_Atom_Info
* start
= &cfis
.cfiArray
[0];
4610 const CFI_Atom_Info
* end
= &cfis
.cfiArray
[cfis
.cfiCount
];
4611 for(const CFI_Atom_Info
* a
=start
; a
< end
; ++a
) {
4612 Atom
<A
>* space
= (Atom
<A
>*)p
;
4613 new (space
) Atom
<A
>(*this, (a
->isCIE
? "CIE" : "FDE"), a
->address
, a
->size
,
4614 ld::Atom::definitionRegular
, ld::Atom::combineNever
, ld::Atom::scopeTranslationUnit
,
4615 ld::Atom::typeCFI
, ld::Atom::symbolTableNotInFinalLinkedImages
,
4616 false, false, false, ld::Atom::Alignment(0));
4617 p
+= sizeof(Atom
<A
>);
4619 this->_endAtoms
= (Atom
<A
>*)p
;
4620 return cfis
.cfiCount
;
4624 template <> bool CFISection
<x86_64
>::bigEndian() { return false; }
4625 template <> bool CFISection
<x86
>::bigEndian() { return false; }
4626 template <> bool CFISection
<arm
>::bigEndian() { return false; }
4627 template <> bool CFISection
<arm64
>::bigEndian() { return false; }
4630 void CFISection
<x86_64
>::addCiePersonalityFixups(class Parser
<x86_64
>& parser
, const CFI_Atom_Info
* cieInfo
)
4632 uint8_t personalityEncoding
= cieInfo
->u
.cieInfo
.personality
.encodingOfTargetAddress
;
4633 if ( personalityEncoding
== 0x9B ) {
4634 // compiler always produces X86_64_RELOC_GOT with addend of 4 to personality function
4635 // CFISection<x86_64>::cfiParse() set targetAddress to be symbolIndex + 4 + addressInCIE
4636 uint32_t symbolIndex
= cieInfo
->u
.cieInfo
.personality
.targetAddress
- 4
4637 - cieInfo
->address
- cieInfo
->u
.cieInfo
.personality
.offsetInCFI
;
4638 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(symbolIndex
);
4639 const char* personalityName
= parser
.nameFromSymbol(sym
);
4641 Atom
<x86_64
>* cieAtom
= this->findAtomByAddress(cieInfo
->address
);
4642 Parser
<x86_64
>::SourceLocation
src(cieAtom
, cieInfo
->u
.cieInfo
.personality
.offsetInCFI
);
4643 parser
.addFixup(src
, ld::Fixup::k1of3
, ld::Fixup::kindSetTargetAddress
, false, personalityName
);
4644 parser
.addFixup(src
, ld::Fixup::k2of3
, ld::Fixup::kindAddAddend
, 4);
4645 parser
.addFixup(src
, ld::Fixup::k3of3
, ld::Fixup::kindStoreX86PCRel32GOT
);
4647 else if ( personalityEncoding
!= 0 ) {
4648 throwf("unsupported address encoding (%02X) of personality function in CIE",
4649 personalityEncoding
);
4654 void CFISection
<x86
>::addCiePersonalityFixups(class Parser
<x86
>& parser
, const CFI_Atom_Info
* cieInfo
)
4656 uint8_t personalityEncoding
= cieInfo
->u
.cieInfo
.personality
.encodingOfTargetAddress
;
4657 if ( (personalityEncoding
== 0x9B) || (personalityEncoding
== 0x90) ) {
4658 uint32_t offsetInCFI
= cieInfo
->u
.cieInfo
.personality
.offsetInCFI
;
4659 uint32_t nlpAddr
= cieInfo
->u
.cieInfo
.personality
.targetAddress
;
4660 Atom
<x86
>* cieAtom
= this->findAtomByAddress(cieInfo
->address
);
4661 Atom
<x86
>* nlpAtom
= parser
.findAtomByAddress(nlpAddr
);
4662 assert(nlpAtom
->contentType() == ld::Atom::typeNonLazyPointer
);
4663 Parser
<x86
>::SourceLocation
src(cieAtom
, cieInfo
->u
.cieInfo
.personality
.offsetInCFI
);
4665 parser
.addFixup(src
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, nlpAtom
);
4666 parser
.addFixup(src
, ld::Fixup::k2of4
, ld::Fixup::kindSubtractTargetAddress
, cieAtom
);
4667 parser
.addFixup(src
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractAddend
, offsetInCFI
);
4668 parser
.addFixup(src
, ld::Fixup::k4of4
, ld::Fixup::kindStoreLittleEndian32
);
4670 else if ( personalityEncoding
!= 0 ) {
4671 throwf("unsupported address encoding (%02X) of personality function in CIE", personalityEncoding
);
4675 #if SUPPORT_ARCH_arm64
4677 void CFISection
<arm64
>::addCiePersonalityFixups(class Parser
<arm64
>& parser
, const CFI_Atom_Info
* cieInfo
)
4679 uint8_t personalityEncoding
= cieInfo
->u
.cieInfo
.personality
.encodingOfTargetAddress
;
4680 if ( personalityEncoding
== 0x9B ) {
4681 // compiler always produces ARM64_RELOC_GOT r_pcrel=1 to personality function
4682 // CFISection<arm64>::cfiParse() set targetAddress to be symbolIndex + addressInCIE
4683 uint32_t symbolIndex
= cieInfo
->u
.cieInfo
.personality
.targetAddress
4684 - cieInfo
->address
- cieInfo
->u
.cieInfo
.personality
.offsetInCFI
;
4685 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(symbolIndex
);
4686 const char* personalityName
= parser
.nameFromSymbol(sym
);
4688 Atom
<arm64
>* cieAtom
= this->findAtomByAddress(cieInfo
->address
);
4689 Parser
<arm64
>::SourceLocation
src(cieAtom
, cieInfo
->u
.cieInfo
.personality
.offsetInCFI
);
4690 parser
.addFixup(src
, ld::Fixup::k1of2
, ld::Fixup::kindSetTargetAddress
, false, personalityName
);
4691 parser
.addFixup(src
, ld::Fixup::k2of2
, ld::Fixup::kindStoreARM64PCRelToGOT
);
4693 else if ( personalityEncoding
!= 0 ) {
4694 throwf("unsupported address encoding (%02X) of personality function in CIE",
4695 personalityEncoding
);
4702 void CFISection
<arm
>::addCiePersonalityFixups(class Parser
<arm
>& parser
, const CFI_Atom_Info
* cieInfo
)
4704 uint8_t personalityEncoding
= cieInfo
->u
.cieInfo
.personality
.encodingOfTargetAddress
;
4705 if ( (personalityEncoding
== 0x9B) || (personalityEncoding
== 0x90) ) {
4706 uint32_t offsetInCFI
= cieInfo
->u
.cieInfo
.personality
.offsetInCFI
;
4707 uint32_t nlpAddr
= cieInfo
->u
.cieInfo
.personality
.targetAddress
;
4708 Atom
<arm
>* cieAtom
= this->findAtomByAddress(cieInfo
->address
);
4709 Atom
<arm
>* nlpAtom
= parser
.findAtomByAddress(nlpAddr
);
4710 assert(nlpAtom
->contentType() == ld::Atom::typeNonLazyPointer
);
4711 Parser
<arm
>::SourceLocation
src(cieAtom
, cieInfo
->u
.cieInfo
.personality
.offsetInCFI
);
4713 parser
.addFixup(src
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, nlpAtom
);
4714 parser
.addFixup(src
, ld::Fixup::k2of4
, ld::Fixup::kindSubtractTargetAddress
, cieAtom
);
4715 parser
.addFixup(src
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractAddend
, offsetInCFI
);
4716 parser
.addFixup(src
, ld::Fixup::k4of4
, ld::Fixup::kindStoreLittleEndian32
);
4718 else if ( personalityEncoding
!= 0 ) {
4719 throwf("unsupported address encoding (%02X) of personality function in CIE", personalityEncoding
);
4725 template <typename A
>
4726 void CFISection
<A
>::addCiePersonalityFixups(class Parser
<A
>& parser
, const CFI_Atom_Info
* cieInfo
)
4728 assert(0 && "addCiePersonalityFixups() not implemented for arch");
4731 template <typename A
>
4732 void CFISection
<A
>::makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
& cfis
)
4734 ld::Fixup::Kind store32
= bigEndian() ? ld::Fixup::kindStoreBigEndian32
: ld::Fixup::kindStoreLittleEndian32
;
4735 ld::Fixup::Kind store64
= bigEndian() ? ld::Fixup::kindStoreBigEndian64
: ld::Fixup::kindStoreLittleEndian64
;
4737 // add all references for FDEs, including implicit group references
4738 const CFI_Atom_Info
* end
= &cfis
.cfiArray
[cfis
.cfiCount
];
4739 for(const CFI_Atom_Info
* p
= &cfis
.cfiArray
[0]; p
< end
; ++p
) {
4741 // add reference to personality function if used
4742 if ( p
->u
.cieInfo
.personality
.targetAddress
!= CFI_INVALID_ADDRESS
) {
4743 this->addCiePersonalityFixups(parser
, p
);
4748 Atom
<A
>* fdeAtom
= this->findAtomByAddress(p
->address
);
4749 // find function Atom
4750 Atom
<A
>* functionAtom
= parser
.findAtomByAddress(p
->u
.fdeInfo
.function
.targetAddress
);
4752 Atom
<A
>* cieAtom
= this->findAtomByAddress(p
->u
.fdeInfo
.cie
.targetAddress
);
4754 Atom
<A
>* lsdaAtom
= NULL
;
4755 if ( p
->u
.fdeInfo
.lsda
.targetAddress
!= CFI_INVALID_ADDRESS
) {
4756 lsdaAtom
= parser
.findAtomByAddress(p
->u
.fdeInfo
.lsda
.targetAddress
);
4758 // add reference from FDE to CIE (always 32-bit pc-rel)
4759 typename Parser
<A
>::SourceLocation
fdeToCieSrc(fdeAtom
, p
->u
.fdeInfo
.cie
.offsetInCFI
);
4760 parser
.addFixup(fdeToCieSrc
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, fdeAtom
);
4761 parser
.addFixup(fdeToCieSrc
, ld::Fixup::k2of4
, ld::Fixup::kindAddAddend
, p
->u
.fdeInfo
.cie
.offsetInCFI
);
4762 parser
.addFixup(fdeToCieSrc
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractTargetAddress
, cieAtom
);
4763 parser
.addFixup(fdeToCieSrc
, ld::Fixup::k4of4
, store32
, cieAtom
);
4765 // add reference from FDE to function
4766 typename Parser
<A
>::SourceLocation
fdeToFuncSrc(fdeAtom
, p
->u
.fdeInfo
.function
.offsetInCFI
);
4767 switch (p
->u
.fdeInfo
.function
.encodingOfTargetAddress
) {
4768 case DW_EH_PE_pcrel
|DW_EH_PE_ptr
:
4769 if ( sizeof(typename
A::P::uint_t
) == 8 ) {
4770 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, functionAtom
);
4771 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k2of4
, ld::Fixup::kindSubtractTargetAddress
, fdeAtom
);
4772 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractAddend
, p
->u
.fdeInfo
.function
.offsetInCFI
);
4773 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k4of4
, store64
);
4776 // else fall into 32-bit case
4777 case DW_EH_PE_pcrel
|DW_EH_PE_sdata4
:
4778 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, functionAtom
);
4779 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k2of4
, ld::Fixup::kindSubtractTargetAddress
, fdeAtom
);
4780 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractAddend
, p
->u
.fdeInfo
.function
.offsetInCFI
);
4781 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k4of4
, store32
);
4784 throw "unsupported encoding in FDE of pointer to function";
4787 // add reference from FDE to LSDA
4788 typename Parser
<A
>::SourceLocation
fdeToLsdaSrc(fdeAtom
, p
->u
.fdeInfo
.lsda
.offsetInCFI
);
4789 if ( lsdaAtom
!= NULL
) {
4790 switch (p
->u
.fdeInfo
.lsda
.encodingOfTargetAddress
) {
4791 case DW_EH_PE_pcrel
|DW_EH_PE_ptr
:
4792 if ( sizeof(typename
A::P::uint_t
) == 8 ) {
4793 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, lsdaAtom
);
4794 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k2of4
, ld::Fixup::kindSubtractTargetAddress
, fdeAtom
);
4795 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractAddend
, p
->u
.fdeInfo
.lsda
.offsetInCFI
);
4796 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k4of4
, store64
);
4799 // else fall into 32-bit case
4800 case DW_EH_PE_pcrel
|DW_EH_PE_sdata4
:
4801 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, lsdaAtom
);
4802 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k2of4
, ld::Fixup::kindSubtractTargetAddress
, fdeAtom
);
4803 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractAddend
, p
->u
.fdeInfo
.lsda
.offsetInCFI
);
4804 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k4of4
, store32
);
4807 throw "unsupported encoding in FDE of pointer to LSDA";
4811 // FDE is in group lead by function atom
4812 typename Parser
<A
>::SourceLocation
fdeSrc(functionAtom
,0);
4813 parser
.addFixup(fdeSrc
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinateFDE
, fdeAtom
);
4815 // LSDA is in group lead by function atom
4816 if ( lsdaAtom
!= NULL
) {
4817 parser
.addFixup(fdeSrc
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinateLSDA
, lsdaAtom
);
4826 template <typename A
>
4827 const void* CFISection
<A
>::OAS::mappedAddress(pint_t addr
)
4829 if ( (_ehFrameStartAddr
<= addr
) && (addr
< _ehFrameEndAddr
) )
4830 return &_ehFrameContent
[addr
-_ehFrameStartAddr
];
4832 // requested bytes are not in __eh_frame section
4833 // this can occur when examining the instruction bytes in the __text
4834 File
<A
>& file
= _ehFrameSection
.file();
4835 for (uint32_t i
=0; i
< file
._sectionsArrayCount
; ++i
) {
4836 const macho_section
<typename
A::P
>* sect
= file
._sectionsArray
[i
]->machoSection();
4837 // TentativeDefinitionSection and AbsoluteSymbolSection have no mach-o section
4838 if ( sect
!= NULL
) {
4839 if ( (sect
->addr() <= addr
) && (addr
< (sect
->addr()+sect
->size())) ) {
4840 return file
.fileContent() + sect
->offset() + addr
- sect
->addr();
4844 throwf("__eh_frame parsing problem. Can't find target of reference to address 0x%08llX", (uint64_t)addr
);
4849 template <typename A
>
4850 uint64_t CFISection
<A
>::OAS::getULEB128(pint_t
& logicalAddr
, pint_t end
)
4852 uintptr_t size
= (end
- logicalAddr
);
4853 libunwind::LocalAddressSpace::pint_t laddr
= (libunwind::LocalAddressSpace::pint_t
)mappedAddress(logicalAddr
);
4854 libunwind::LocalAddressSpace::pint_t sladdr
= laddr
;
4855 uint64_t result
= libunwind::LocalAddressSpace::getULEB128(laddr
, laddr
+size
);
4856 logicalAddr
+= (laddr
-sladdr
);
4860 template <typename A
>
4861 int64_t CFISection
<A
>::OAS::getSLEB128(pint_t
& logicalAddr
, pint_t end
)
4863 uintptr_t size
= (end
- logicalAddr
);
4864 libunwind::LocalAddressSpace::pint_t laddr
= (libunwind::LocalAddressSpace::pint_t
)mappedAddress(logicalAddr
);
4865 libunwind::LocalAddressSpace::pint_t sladdr
= laddr
;
4866 int64_t result
= libunwind::LocalAddressSpace::getSLEB128(laddr
, laddr
+size
);
4867 logicalAddr
+= (laddr
-sladdr
);
4871 template <typename A
>
4872 typename
A::P::uint_t CFISection
<A
>::OAS::getEncodedP(pint_t
& addr
, pint_t end
, uint8_t encoding
)
4874 pint_t startAddr
= addr
;
4879 switch (encoding
& 0x0F) {
4881 result
= getP(addr
);
4882 p
+= sizeof(pint_t
);
4885 case DW_EH_PE_uleb128
:
4886 result
= getULEB128(addr
, end
);
4888 case DW_EH_PE_udata2
:
4889 result
= get16(addr
);
4893 case DW_EH_PE_udata4
:
4894 result
= get32(addr
);
4898 case DW_EH_PE_udata8
:
4899 result
= get64(addr
);
4903 case DW_EH_PE_sleb128
:
4904 result
= getSLEB128(addr
, end
);
4906 case DW_EH_PE_sdata2
:
4907 result
= (int16_t)get16(addr
);
4911 case DW_EH_PE_sdata4
:
4912 result
= (int32_t)get32(addr
);
4916 case DW_EH_PE_sdata8
:
4917 result
= get64(addr
);
4922 throwf("ObjectFileAddressSpace<A>::getEncodedP() encoding 0x%08X not supported", encoding
);
4925 // then add relative offset
4926 switch ( encoding
& 0x70 ) {
4927 case DW_EH_PE_absptr
:
4930 case DW_EH_PE_pcrel
:
4931 result
+= startAddr
;
4933 case DW_EH_PE_textrel
:
4934 throw "DW_EH_PE_textrel pointer encoding not supported";
4936 case DW_EH_PE_datarel
:
4937 throw "DW_EH_PE_datarel pointer encoding not supported";
4939 case DW_EH_PE_funcrel
:
4940 throw "DW_EH_PE_funcrel pointer encoding not supported";
4942 case DW_EH_PE_aligned
:
4943 throw "DW_EH_PE_aligned pointer encoding not supported";
4946 throwf("ObjectFileAddressSpace<A>::getEncodedP() encoding 0x%08X not supported", encoding
);
4950 // Note: DW_EH_PE_indirect is only used in CIEs to refernce the personality pointer
4951 // When parsing .o files that pointer contains zero, so we don't to return that.
4952 // Instead we skip the dereference and return the address of the pointer.
4953 // if ( encoding & DW_EH_PE_indirect )
4954 // result = getP(result);
4960 const char* CUSection
<x86_64
>::personalityName(class Parser
<x86_64
>& parser
, const macho_relocation_info
<x86_64::P
>* reloc
)
4962 if ( reloc
->r_extern() ) {
4963 assert((reloc
->r_type() == X86_64_RELOC_UNSIGNED
) && "wrong reloc type on personality column in __compact_unwind section");
4964 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
4965 return parser
.nameFromSymbol(sym
);
4968 const pint_t
* content
= (pint_t
*)(this->file().fileContent() + this->_machOSection
->offset() + reloc
->r_address());
4969 pint_t personalityAddr
= *content
;
4970 assert((parser
.sectionForAddress(personalityAddr
)->type() == ld::Section::typeCode
) && "personality column in __compact_unwind section is not pointer to function");
4971 // atoms may not be constructed yet, so scan symbol table for labels
4972 const char* name
= parser
.scanSymbolTableForAddress(personalityAddr
);
4978 const char* CUSection
<x86
>::personalityName(class Parser
<x86
>& parser
, const macho_relocation_info
<x86::P
>* reloc
)
4980 if ( reloc
->r_extern() ) {
4981 assert((reloc
->r_type() == GENERIC_RELOC_VANILLA
) && "wrong reloc type on personality column in __compact_unwind section");
4982 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
4983 return parser
.nameFromSymbol(sym
);
4986 // support __LD, __compact_unwind personality entries which are pointer to personality non-lazy pointer
4987 const pint_t
* content
= (pint_t
*)(this->file().fileContent() + this->_machOSection
->offset() + reloc
->r_address());
4988 pint_t nlPointerAddr
= *content
;
4989 Section
<x86
>* nlSection
= parser
.sectionForAddress(nlPointerAddr
);
4990 if ( nlSection
->type() == ld::Section::typeCode
) {
4991 // personality function is defined in this .o file, so this is a direct reference to it
4992 // atoms may not be constructed yet, so scan symbol table for labels
4993 const char* name
= parser
.scanSymbolTableForAddress(nlPointerAddr
);
4997 uint32_t symIndex
= parser
.symbolIndexFromIndirectSectionAddress(nlPointerAddr
, nlSection
->machoSection());
4998 const macho_nlist
<P
>& nlSymbol
= parser
.symbolFromIndex(symIndex
);
4999 return parser
.nameFromSymbol(nlSymbol
);
5004 #if SUPPORT_ARCH_arm64
5006 const char* CUSection
<arm64
>::personalityName(class Parser
<arm64
>& parser
, const macho_relocation_info
<arm64::P
>* reloc
)
5008 if ( reloc
->r_extern() ) {
5009 assert((reloc
->r_type() == ARM64_RELOC_UNSIGNED
) && "wrong reloc type on personality column in __compact_unwind section");
5010 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
5011 return parser
.nameFromSymbol(sym
);
5014 const pint_t
* content
= (pint_t
*)(this->file().fileContent() + this->_machOSection
->offset() + reloc
->r_address());
5015 pint_t personalityAddr
= *content
;
5016 Section
<arm64
>* personalitySection
= parser
.sectionForAddress(personalityAddr
);
5017 (void)personalitySection
;
5018 assert((personalitySection
->type() == ld::Section::typeCode
) && "personality column in __compact_unwind section is not pointer to function");
5019 // atoms may not be constructed yet, so scan symbol table for labels
5020 const char* name
= parser
.scanSymbolTableForAddress(personalityAddr
);
5027 #if SUPPORT_ARCH_arm_any
5029 const char* CUSection
<arm
>::personalityName(class Parser
<arm
>& parser
, const macho_relocation_info
<arm::P
>* reloc
)
5031 if ( reloc
->r_extern() ) {
5032 assert((reloc
->r_type() == ARM_RELOC_VANILLA
) && "wrong reloc type on personality column in __compact_unwind section");
5033 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
5034 return parser
.nameFromSymbol(sym
);
5037 // support __LD, __compact_unwind personality entries which are pointer to personality non-lazy pointer
5038 const pint_t
* content
= (pint_t
*)(this->file().fileContent() + this->_machOSection
->offset() + reloc
->r_address());
5039 pint_t nlPointerAddr
= *content
;
5040 Section
<arm
>* nlSection
= parser
.sectionForAddress(nlPointerAddr
);
5041 if ( nlSection
->type() == ld::Section::typeCode
) {
5042 // personality function is defined in this .o file, so this is a direct reference to it
5043 // atoms may not be constructed yet, so scan symbol table for labels
5044 const char* name
= parser
.scanSymbolTableForAddress(nlPointerAddr
);
5048 uint32_t symIndex
= parser
.symbolIndexFromIndirectSectionAddress(nlPointerAddr
, nlSection
->machoSection());
5049 const macho_nlist
<P
>& nlSymbol
= parser
.symbolFromIndex(symIndex
);
5050 return parser
.nameFromSymbol(nlSymbol
);
5057 template <typename A
>
5058 const char* CUSection
<A
>::personalityName(class Parser
<A
>& parser
, const macho_relocation_info
<P
>* reloc
)
5064 bool CUSection
<x86
>::encodingMeansUseDwarf(compact_unwind_encoding_t enc
)
5066 return ((enc
& UNWIND_X86_MODE_MASK
) == UNWIND_X86_MODE_DWARF
);
5070 bool CUSection
<x86_64
>::encodingMeansUseDwarf(compact_unwind_encoding_t enc
)
5072 return ((enc
& UNWIND_X86_64_MODE_MASK
) == UNWIND_X86_64_MODE_DWARF
);
5075 #if SUPPORT_ARCH_arm_any
5077 bool CUSection
<arm
>::encodingMeansUseDwarf(compact_unwind_encoding_t enc
)
5079 return ((enc
& UNWIND_ARM_MODE_MASK
) == UNWIND_ARM_MODE_DWARF
);
5083 #if SUPPORT_ARCH_arm64
5085 bool CUSection
<arm64
>::encodingMeansUseDwarf(compact_unwind_encoding_t enc
)
5087 return ((enc
& UNWIND_ARM64_MODE_MASK
) == UNWIND_ARM64_MODE_DWARF
);
5092 template <typename A
>
5093 int CUSection
<A
>::infoSorter(const void* l
, const void* r
)
5095 // sort references by symbol index, then address
5096 const Info
* left
= (Info
*)l
;
5097 const Info
* right
= (Info
*)r
;
5098 if ( left
->functionSymbolIndex
== right
->functionSymbolIndex
)
5099 return (left
->functionStartAddress
- right
->functionStartAddress
);
5101 return (left
->functionSymbolIndex
- right
->functionSymbolIndex
);
5104 template <typename A
>
5105 void CUSection
<A
>::parse(class Parser
<A
>& parser
, uint32_t cnt
, Info array
[])
5107 // walk section content and copy to Info array
5108 const macho_compact_unwind_entry
<P
>* const entries
= (macho_compact_unwind_entry
<P
>*)(this->file().fileContent() + this->_machOSection
->offset());
5109 for (uint32_t i
=0; i
< cnt
; ++i
) {
5110 Info
* info
= &array
[i
];
5111 const macho_compact_unwind_entry
<P
>* entry
= &entries
[i
];
5112 info
->functionStartAddress
= entry
->codeStart();
5113 info
->functionSymbolIndex
= 0xFFFFFFFF;
5114 info
->rangeLength
= entry
->codeLen();
5115 info
->compactUnwindInfo
= entry
->compactUnwindInfo();
5116 info
->personality
= NULL
;
5117 info
->lsdaAddress
= entry
->lsda();
5118 info
->function
= NULL
;
5120 if ( (info
->compactUnwindInfo
& UNWIND_PERSONALITY_MASK
) != 0 )
5121 warning("no bits should be set in UNWIND_PERSONALITY_MASK of compact unwind encoding in __LD,__compact_unwind section");
5122 if ( info
->lsdaAddress
!= 0 ) {
5123 info
->compactUnwindInfo
|= UNWIND_HAS_LSDA
;
5127 // scan relocs, extern relocs are needed for personality references (possibly for function/lsda refs??)
5128 const uint32_t sectionSize
= this->_machOSection
->size();
5129 const macho_relocation_info
<P
>* relocs
= (macho_relocation_info
<P
>*)(this->file().fileContent() + this->_machOSection
->reloff());
5130 const macho_relocation_info
<P
>* relocsEnd
= &relocs
[this->_machOSection
->nreloc()];
5131 for (const macho_relocation_info
<P
>* reloc
= relocs
; reloc
< relocsEnd
; ++reloc
) {
5132 if ( reloc
->r_address() & R_SCATTERED
)
5134 if ( reloc
->r_address() > sectionSize
)
5135 throwf("malformed __compact_unwind relocation, offset (0x%08X) is beyond end of section,", reloc
->r_address());
5136 if ( reloc
->r_extern() ) {
5137 // only expect external relocs on some colummns
5138 if ( (reloc
->r_address() % sizeof(macho_compact_unwind_entry
<P
>)) == macho_compact_unwind_entry
<P
>::personalityFieldOffset() ) {
5139 uint32_t entryIndex
= reloc
->r_address() / sizeof(macho_compact_unwind_entry
<P
>);
5140 array
[entryIndex
].personality
= this->personalityName(parser
, reloc
);
5142 else if ( (reloc
->r_address() % sizeof(macho_compact_unwind_entry
<P
>)) == macho_compact_unwind_entry
<P
>::lsdaFieldOffset() ) {
5143 uint32_t entryIndex
= reloc
->r_address() / sizeof(macho_compact_unwind_entry
<P
>);
5144 const macho_nlist
<P
>& lsdaSym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
5145 if ( (lsdaSym
.n_type() & N_TYPE
) == N_SECT
)
5146 array
[entryIndex
].lsdaAddress
= lsdaSym
.n_value();
5148 warning("unexpected extern relocation to lsda in __compact_unwind section");
5150 else if ( (reloc
->r_address() % sizeof(macho_compact_unwind_entry
<P
>)) == macho_compact_unwind_entry
<P
>::codeStartFieldOffset() ) {
5151 uint32_t entryIndex
= reloc
->r_address() / sizeof(macho_compact_unwind_entry
<P
>);
5152 array
[entryIndex
].functionSymbolIndex
= reloc
->r_symbolnum();
5153 array
[entryIndex
].functionStartAddress
+= parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
5156 warning("unexpected extern relocation in __compact_unwind section");
5160 if ( (reloc
->r_address() % sizeof(macho_compact_unwind_entry
<P
>)) == macho_compact_unwind_entry
<P
>::personalityFieldOffset() ) {
5161 uint32_t entryIndex
= reloc
->r_address() / sizeof(macho_compact_unwind_entry
<P
>);
5162 array
[entryIndex
].personality
= this->personalityName(parser
, reloc
);
5167 // sort array by function start address so unwind infos will be contiguous for a given function
5168 ::qsort(array
, cnt
, sizeof(Info
), infoSorter
);
5171 template <typename A
>
5172 uint32_t CUSection
<A
>::count()
5174 const macho_section
<P
>* machoSect
= this->machoSection();
5175 if ( (machoSect
->size() % sizeof(macho_compact_unwind_entry
<P
>)) != 0 )
5176 throw "malformed __LD,__compact_unwind section, bad length";
5178 return machoSect
->size() / sizeof(macho_compact_unwind_entry
<P
>);
5181 template <typename A
>
5182 void CUSection
<A
>::makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
& cus
)
5184 Info
* const arrayStart
= cus
.cuArray
;
5185 Info
* const arrayEnd
= &cus
.cuArray
[cus
.cuCount
];
5186 for (Info
* info
=arrayStart
; info
< arrayEnd
; ++info
) {
5187 // find function atom from address
5188 info
->function
= parser
.findAtomByAddress(info
->functionStartAddress
);
5189 // find lsda atom from address
5190 if ( info
->lsdaAddress
!= 0 ) {
5191 info
->lsda
= parser
.findAtomByAddress(info
->lsdaAddress
);
5192 // add lsda subordinate
5193 typename Parser
<A
>::SourceLocation
src(info
->function
, info
->functionStartAddress
- info
->function
->objectAddress());
5194 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinateLSDA
, info
->lsda
);
5196 if ( info
->personality
!= NULL
) {
5197 // add personality subordinate
5198 typename Parser
<A
>::SourceLocation
src(info
->function
, info
->functionStartAddress
- info
->function
->objectAddress());
5199 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinatePersonality
, false, info
->personality
);
5205 template <typename A
>
5206 SymboledSection
<A
>::SymboledSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
5207 : Section
<A
>(f
, s
), _type(ld::Atom::typeUnclassified
)
5209 switch ( s
->flags() & SECTION_TYPE
) {
5211 _type
= ld::Atom::typeZeroFill
;
5213 case S_MOD_INIT_FUNC_POINTERS
:
5214 _type
= ld::Atom::typeInitializerPointers
;
5216 case S_MOD_TERM_FUNC_POINTERS
:
5217 _type
= ld::Atom::typeTerminatorPointers
;
5219 case S_THREAD_LOCAL_VARIABLES
:
5220 _type
= ld::Atom::typeTLV
;
5222 case S_THREAD_LOCAL_ZEROFILL
:
5223 _type
= ld::Atom::typeTLVZeroFill
;
5225 case S_THREAD_LOCAL_REGULAR
:
5226 _type
= ld::Atom::typeTLVInitialValue
;
5228 case S_THREAD_LOCAL_INIT_FUNCTION_POINTERS
:
5229 _type
= ld::Atom::typeTLVInitializerPointers
;
5232 if ( strncmp(s
->sectname(), "__gcc_except_tab", 16) == 0 )
5233 _type
= ld::Atom::typeLSDA
;
5234 else if ( this->type() == ld::Section::typeInitializerPointers
)
5235 _type
= ld::Atom::typeInitializerPointers
;
5241 template <typename A
>
5242 bool SymboledSection
<A
>::dontDeadStrip()
5245 case ld::Atom::typeInitializerPointers
:
5246 case ld::Atom::typeTerminatorPointers
:
5249 // model an object file without MH_SUBSECTIONS_VIA_SYMBOLS as one in which nothing can be dead stripped
5250 if ( ! this->_file
.canScatterAtoms() )
5253 return Section
<A
>::dontDeadStrip();
5259 template <typename A
>
5260 uint32_t SymboledSection
<A
>::computeAtomCount(class Parser
<A
>& parser
,
5261 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
5262 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
5264 const pint_t startAddr
= this->_machOSection
->addr();
5265 const pint_t endAddr
= startAddr
+ this->_machOSection
->size();
5266 const uint32_t sectNum
= this->sectionNum(parser
);
5271 const macho_nlist
<P
>* sym
;
5272 while ( it
.next(parser
, *this, sectNum
, startAddr
, endAddr
, &addr
, &size
, &sym
) ) {
5275 //fprintf(stderr, "computeAtomCount(%s,%s) => %d\n", this->segmentName(), this->sectionName(), count);
5279 template <typename A
>
5280 uint32_t SymboledSection
<A
>::appendAtoms(class Parser
<A
>& parser
, uint8_t* p
,
5281 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
5282 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
5284 this->_beginAtoms
= (Atom
<A
>*)p
;
5286 //fprintf(stderr, "SymboledSection::appendAtoms() in section %s\n", this->_machOSection->sectname());
5287 const pint_t startAddr
= this->_machOSection
->addr();
5288 const pint_t endAddr
= startAddr
+ this->_machOSection
->size();
5289 const uint32_t sectNum
= this->sectionNum(parser
);
5294 const macho_nlist
<P
>* label
;
5295 while ( it
.next(parser
, *this, sectNum
, startAddr
, endAddr
, &addr
, &size
, &label
) ) {
5296 Atom
<A
>* allocatedSpace
= (Atom
<A
>*)p
;
5297 // is break because of label or CFI?
5298 if ( label
!= NULL
) {
5299 // The size is computed based on the address of the next label (or the end of the section for the last label)
5300 // If there are two labels at the same address, we want them one to be an alias of the other.
5301 // If the label is at the end of a section, it is has zero size, but is not an alias
5302 const bool isAlias
= ( (size
== 0) && (addr
< endAddr
) );
5303 new (allocatedSpace
) Atom
<A
>(*this, parser
, *label
, size
, isAlias
);
5305 this->_hasAliases
= true;
5306 if ( parser
.altEntryFromSymbol(*label
) )
5307 this->_altEntries
.insert(allocatedSpace
);
5310 ld::Atom::SymbolTableInclusion inclusion
= ld::Atom::symbolTableNotIn
;
5311 ld::Atom::ContentType ctype
= this->contentType();
5312 if ( ctype
== ld::Atom::typeLSDA
)
5313 inclusion
= ld::Atom::symbolTableInWithRandomAutoStripLabel
;
5314 new (allocatedSpace
) Atom
<A
>(*this, "anon", addr
, size
, ld::Atom::definitionRegular
, ld::Atom::combineNever
,
5315 ld::Atom::scopeTranslationUnit
, ctype
, inclusion
,
5316 this->dontDeadStrip(), false, false, this->alignmentForAddress(addr
));
5318 p
+= sizeof(Atom
<A
>);
5322 this->_endAtoms
= (Atom
<A
>*)p
;
5328 ld::Atom::SymbolTableInclusion ImplicitSizeSection
<arm64
>::symbolTableInclusion()
5330 return ld::Atom::symbolTableInWithRandomAutoStripLabel
;
5334 template <typename A
>
5335 ld::Atom::SymbolTableInclusion ImplicitSizeSection
<A
>::symbolTableInclusion()
5337 return ld::Atom::symbolTableNotIn
;
5341 template <typename A
>
5342 uint32_t ImplicitSizeSection
<A
>::computeAtomCount(class Parser
<A
>& parser
,
5343 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
5344 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
5347 const macho_section
<P
>* sect
= this->machoSection();
5348 const pint_t startAddr
= sect
->addr();
5349 const pint_t endAddr
= startAddr
+ sect
->size();
5350 for (pint_t addr
= startAddr
; addr
< endAddr
; addr
+= elementSizeAtAddress(addr
) ) {
5351 if ( useElementAt(parser
, it
, addr
) )
5354 if ( it
.fileHasOverlappingSymbols
&& (sect
->size() != 0) && (this->combine(parser
, startAddr
) == ld::Atom::combineByNameAndContent
) ) {
5355 // if there are multiple labels in this section for the same address, then clone them into multi atoms
5356 pint_t prevSymbolAddr
= (pint_t
)(-1);
5357 uint8_t prevSymbolSectNum
= 0;
5358 bool prevIgnore
= false;
5359 for(uint32_t i
=0; i
< it
.sortedSymbolCount
; ++i
) {
5360 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(it
.sortedSymbolIndexes
[i
]);
5361 const pint_t symbolAddr
= sym
.n_value();
5362 const uint8_t symbolSectNum
= sym
.n_sect();
5363 const bool ignore
= this->ignoreLabel(parser
.nameFromSymbol(sym
));
5364 if ( !ignore
&& !prevIgnore
&& (symbolAddr
== prevSymbolAddr
) && (prevSymbolSectNum
== symbolSectNum
) && (symbolSectNum
== this->sectionNum(parser
)) ) {
5367 prevSymbolAddr
= symbolAddr
;
5368 prevSymbolSectNum
= symbolSectNum
;
5369 prevIgnore
= ignore
;
5375 template <typename A
>
5376 uint32_t ImplicitSizeSection
<A
>::appendAtoms(class Parser
<A
>& parser
, uint8_t* p
,
5377 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
5378 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
5380 this->_beginAtoms
= (Atom
<A
>*)p
;
5382 const macho_section
<P
>* sect
= this->machoSection();
5383 const pint_t startAddr
= sect
->addr();
5384 const pint_t endAddr
= startAddr
+ sect
->size();
5385 const uint32_t sectNum
= this->sectionNum(parser
);
5386 //fprintf(stderr, "ImplicitSizeSection::appendAtoms() in section %s\n", sect->sectname());
5390 const macho_nlist
<P
>* foundLabel
;
5391 Atom
<A
>* allocatedSpace
;
5392 while ( it
.next(parser
, *this, sectNum
, startAddr
, endAddr
, &foundAddr
, &size
, &foundLabel
) ) {
5393 if ( foundLabel
!= NULL
) {
5395 pint_t labeledAtomSize
= this->elementSizeAtAddress(foundAddr
);
5396 allocatedSpace
= (Atom
<A
>*)p
;
5397 if ( this->ignoreLabel(parser
.nameFromSymbol(*foundLabel
)) ) {
5399 // <rdar://problem/10018737>
5400 // a size of zero means there is another label at same location
5401 // and we are supposed to ignore this label
5405 //fprintf(stderr, " 0x%08llX make annon, size=%lld\n", (uint64_t)foundAddr, (uint64_t)size);
5406 new (allocatedSpace
) Atom
<A
>(*this, this->unlabeledAtomName(parser
, foundAddr
), foundAddr
,
5407 this->elementSizeAtAddress(foundAddr
), this->definition(),
5408 this->combine(parser
, foundAddr
), this->scopeAtAddress(parser
, foundAddr
),
5409 this->contentType(), this->symbolTableInclusion(),
5410 this->dontDeadStrip(), false, false, this->alignmentForAddress(foundAddr
));
5414 // make named atom for label
5415 //fprintf(stderr, " 0x%08llX make labeled\n", (uint64_t)foundAddr);
5416 new (allocatedSpace
) Atom
<A
>(*this, parser
, *foundLabel
, labeledAtomSize
);
5420 p
+= sizeof(Atom
<A
>);
5421 foundAddr
+= labeledAtomSize
;
5422 size
-= labeledAtomSize
;
5425 // some number of anonymous atoms
5426 for (pint_t addr
= foundAddr
; addr
< (foundAddr
+size
); addr
+= elementSizeAtAddress(addr
) ) {
5427 // make anon atoms for area before label
5428 if ( this->useElementAt(parser
, it
, addr
) ) {
5429 //fprintf(stderr, " 0x%08llX make annon, size=%lld\n", (uint64_t)addr, (uint64_t)elementSizeAtAddress(addr));
5430 allocatedSpace
= (Atom
<A
>*)p
;
5431 new (allocatedSpace
) Atom
<A
>(*this, this->unlabeledAtomName(parser
, addr
), addr
, this->elementSizeAtAddress(addr
),
5432 this->definition(), this->combine(parser
, addr
), this->scopeAtAddress(parser
, addr
),
5433 this->contentType(), this->symbolTableInclusion(),
5434 this->dontDeadStrip(), false, false, this->alignmentForAddress(addr
));
5436 p
+= sizeof(Atom
<A
>);
5441 this->_endAtoms
= (Atom
<A
>*)p
;
5446 template <typename A
>
5447 bool Literal4Section
<A
>::ignoreLabel(const char* label
) const
5449 return (label
[0] == 'L') || (label
[0] == 'l');
5452 template <typename A
>
5453 unsigned long Literal4Section
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5455 const uint32_t* literalContent
= (uint32_t*)atom
->contentPointer();
5456 return *literalContent
;
5459 template <typename A
>
5460 bool Literal4Section
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5461 const ld::IndirectBindingTable
& ind
) const
5463 assert(this->type() == rhs
.section().type());
5464 const uint32_t* literalContent
= (uint32_t*)atom
->contentPointer();
5466 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5467 assert(rhsAtom
!= NULL
);
5468 if ( rhsAtom
!= NULL
) {
5469 const uint32_t* rhsLiteralContent
= (uint32_t*)rhsAtom
->contentPointer();
5470 return (*literalContent
== *rhsLiteralContent
);
5476 template <typename A
>
5477 bool Literal8Section
<A
>::ignoreLabel(const char* label
) const
5479 return (label
[0] == 'L') || (label
[0] == 'l');
5482 template <typename A
>
5483 unsigned long Literal8Section
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5486 const uint64_t* literalContent
= (uint64_t*)atom
->contentPointer();
5487 return *literalContent
;
5489 unsigned long hash
= 5381;
5490 const uint8_t* byteContent
= atom
->contentPointer();
5491 for (int i
=0; i
< 8; ++i
) {
5492 hash
= hash
* 33 + byteContent
[i
];
5498 template <typename A
>
5499 bool Literal8Section
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5500 const ld::IndirectBindingTable
& ind
) const
5502 if ( rhs
.section().type() != ld::Section::typeLiteral8
)
5504 assert(this->type() == rhs
.section().type());
5505 const uint64_t* literalContent
= (uint64_t*)atom
->contentPointer();
5507 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5508 assert(rhsAtom
!= NULL
);
5509 if ( rhsAtom
!= NULL
) {
5510 const uint64_t* rhsLiteralContent
= (uint64_t*)rhsAtom
->contentPointer();
5511 return (*literalContent
== *rhsLiteralContent
);
5516 template <typename A
>
5517 bool Literal16Section
<A
>::ignoreLabel(const char* label
) const
5519 return (label
[0] == 'L') || (label
[0] == 'l');
5522 template <typename A
>
5523 unsigned long Literal16Section
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5525 unsigned long hash
= 5381;
5526 const uint8_t* byteContent
= atom
->contentPointer();
5527 for (int i
=0; i
< 16; ++i
) {
5528 hash
= hash
* 33 + byteContent
[i
];
5533 template <typename A
>
5534 bool Literal16Section
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5535 const ld::IndirectBindingTable
& ind
) const
5537 if ( rhs
.section().type() != ld::Section::typeLiteral16
)
5539 assert(this->type() == rhs
.section().type());
5540 const uint64_t* literalContent
= (uint64_t*)atom
->contentPointer();
5542 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5543 assert(rhsAtom
!= NULL
);
5544 if ( rhsAtom
!= NULL
) {
5545 const uint64_t* rhsLiteralContent
= (uint64_t*)rhsAtom
->contentPointer();
5546 return ((literalContent
[0] == rhsLiteralContent
[0]) && (literalContent
[1] == rhsLiteralContent
[1]));
5553 template <typename A
>
5554 typename
A::P::uint_t CStringSection
<A
>::elementSizeAtAddress(pint_t addr
)
5556 const macho_section
<P
>* sect
= this->machoSection();
5557 const char* stringContent
= (char*)(this->file().fileContent() + sect
->offset() + addr
- sect
->addr());
5558 return strlen(stringContent
) + 1;
5561 template <typename A
>
5562 bool CStringSection
<A
>::useElementAt(Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, pint_t addr
)
5567 template <typename A
>
5568 bool CStringSection
<A
>::ignoreLabel(const char* label
) const
5570 return (label
[0] == 'L') || (label
[0] == 'l');
5574 template <typename A
>
5575 Atom
<A
>* CStringSection
<A
>::findAtomByAddress(pint_t addr
)
5577 Atom
<A
>* result
= this->findContentAtomByAddress(addr
, this->_beginAtoms
, this->_endAtoms
);
5581 template <typename A
>
5582 unsigned long CStringSection
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5584 unsigned long hash
= 5381;
5585 const char* stringContent
= (char*)atom
->contentPointer();
5586 for (const char* s
= stringContent
; *s
!= '\0'; ++s
) {
5587 hash
= hash
* 33 + *s
;
5593 template <typename A
>
5594 bool CStringSection
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5595 const ld::IndirectBindingTable
& ind
) const
5597 if ( rhs
.section().type() != ld::Section::typeCString
)
5599 assert(this->type() == rhs
.section().type());
5600 assert(strcmp(this->sectionName(), rhs
.section().sectionName())== 0);
5601 assert(strcmp(this->segmentName(), rhs
.section().segmentName())== 0);
5602 const char* stringContent
= (char*)atom
->contentPointer();
5604 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5605 assert(rhsAtom
!= NULL
);
5606 if ( rhsAtom
!= NULL
) {
5607 if ( atom
->_size
!= rhsAtom
->_size
)
5609 const char* rhsStringContent
= (char*)rhsAtom
->contentPointer();
5610 return (strcmp(stringContent
, rhsStringContent
) == 0);
5617 ld::Fixup::Kind NonLazyPointerSection
<x86
>::fixupKind()
5619 return ld::Fixup::kindStoreLittleEndian32
;
5623 ld::Fixup::Kind NonLazyPointerSection
<arm
>::fixupKind()
5625 return ld::Fixup::kindStoreLittleEndian32
;
5629 ld::Fixup::Kind NonLazyPointerSection
<arm64
>::fixupKind()
5631 return ld::Fixup::kindStoreLittleEndian64
;
5636 void NonLazyPointerSection
<x86_64
>::makeFixups(class Parser
<x86_64
>& parser
, const struct Parser
<x86_64
>::CFI_CU_InfoArrays
&)
5638 assert(0 && "x86_64 should not have non-lazy-pointer sections in .o files");
5641 template <typename A
>
5642 void NonLazyPointerSection
<A
>::makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&)
5644 // add references for each NLP atom based on indirect symbol table
5645 const macho_section
<P
>* sect
= this->machoSection();
5646 const pint_t endAddr
= sect
->addr() + sect
->size();
5647 for( pint_t addr
= sect
->addr(); addr
< endAddr
; addr
+= sizeof(pint_t
)) {
5648 typename Parser
<A
>::SourceLocation src
;
5649 typename Parser
<A
>::TargetDesc target
;
5650 src
.atom
= this->findAtomByAddress(addr
);
5651 src
.offsetInAtom
= 0;
5652 uint32_t symIndex
= parser
.symbolIndexFromIndirectSectionAddress(addr
, sect
);
5655 target
.weakImport
= false;
5657 if ( symIndex
== INDIRECT_SYMBOL_LOCAL
) {
5658 // use direct reference for local symbols
5659 const pint_t
* nlpContent
= (pint_t
*)(this->file().fileContent() + sect
->offset() + addr
- sect
->addr());
5660 pint_t targetAddr
= P::getP(*nlpContent
);
5661 target
.atom
= parser
.findAtomByAddress(targetAddr
);
5662 target
.weakImport
= false;
5663 target
.addend
= (targetAddr
- target
.atom
->objectAddress());
5664 // <rdar://problem/8385011> if pointer to thumb function, mask of thumb bit (not an addend of +1)
5665 if ( target
.atom
->isThumb() )
5666 target
.addend
&= (-2);
5667 assert(src
.atom
->combine() == ld::Atom::combineNever
);
5670 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(symIndex
);
5671 // use direct reference for local symbols
5672 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && ((sym
.n_type() & N_EXT
) == 0) ) {
5673 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
5674 assert(src
.atom
->combine() == ld::Atom::combineNever
);
5677 target
.name
= parser
.nameFromSymbol(sym
);
5678 target
.weakImport
= parser
.weakImportFromSymbol(sym
);
5679 assert(src
.atom
->combine() == ld::Atom::combineByNameAndReferences
);
5682 parser
.addFixups(src
, this->fixupKind(), target
);
5686 template <typename A
>
5687 ld::Atom::Combine NonLazyPointerSection
<A
>::combine(Parser
<A
>& parser
, pint_t addr
)
5689 const macho_section
<P
>* sect
= this->machoSection();
5690 uint32_t symIndex
= parser
.symbolIndexFromIndirectSectionAddress(addr
, sect
);
5691 if ( symIndex
== INDIRECT_SYMBOL_LOCAL
)
5692 return ld::Atom::combineNever
;
5694 // don't coalesce non-lazy-pointers to local symbols
5695 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(symIndex
);
5696 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && ((sym
.n_type() & N_EXT
) == 0) )
5697 return ld::Atom::combineNever
;
5699 return ld::Atom::combineByNameAndReferences
;
5702 template <typename A
>
5703 const char* NonLazyPointerSection
<A
>::targetName(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
)
5705 assert(atom
->combine() == ld::Atom::combineByNameAndReferences
);
5706 assert(atom
->fixupCount() == 1);
5707 ld::Fixup::iterator fit
= atom
->fixupsBegin();
5708 const char* name
= NULL
;
5709 switch ( fit
->binding
) {
5710 case ld::Fixup::bindingByNameUnbound
:
5713 case ld::Fixup::bindingByContentBound
:
5714 name
= fit
->u
.target
->name();
5716 case ld::Fixup::bindingsIndirectlyBound
:
5717 name
= ind
.indirectName(fit
->u
.bindingIndex
);
5722 assert(name
!= NULL
);
5726 template <typename A
>
5727 unsigned long NonLazyPointerSection
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5729 assert(atom
->combine() == ld::Atom::combineByNameAndReferences
);
5730 unsigned long hash
= 9508;
5731 for (const char* s
= this->targetName(atom
, ind
); *s
!= '\0'; ++s
) {
5732 hash
= hash
* 33 + *s
;
5737 template <typename A
>
5738 bool NonLazyPointerSection
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5739 const ld::IndirectBindingTable
& indirectBindingTable
) const
5741 if ( rhs
.section().type() != ld::Section::typeNonLazyPointer
)
5743 assert(this->type() == rhs
.section().type());
5744 // there can be many non-lazy pointer in different section names
5745 // we only want to coalesce in same section name
5746 if ( *this != rhs
.section() )
5748 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5749 assert(rhsAtom
!= NULL
);
5750 const char* thisName
= this->targetName(atom
, indirectBindingTable
);
5751 const char* rhsName
= this->targetName(rhsAtom
, indirectBindingTable
);
5752 return (strcmp(thisName
, rhsName
) == 0);
5755 template <typename A
>
5756 ld::Atom::Scope NonLazyPointerSection
<A
>::scopeAtAddress(Parser
<A
>& parser
, pint_t addr
)
5758 const macho_section
<P
>* sect
= this->machoSection();
5759 uint32_t symIndex
= parser
.symbolIndexFromIndirectSectionAddress(addr
, sect
);
5760 if ( symIndex
== INDIRECT_SYMBOL_LOCAL
)
5761 return ld::Atom::scopeTranslationUnit
;
5763 return ld::Atom::scopeLinkageUnit
;
5768 template <typename A
>
5769 ld::Atom::Combine TLVPointerSection
<A
>::combine(Parser
<A
>& parser
, pint_t addr
)
5771 return ld::Atom::combineByNameAndReferences
;
5775 void TLVPointerSection
<arm
>::makeFixups(class Parser
<arm
>& parser
, const struct Parser
<arm
>::CFI_CU_InfoArrays
&)
5777 // add references for each thread local pointer atom based on indirect symbol table
5778 const macho_section
<P
>* sect
= this->machoSection();
5779 const pint_t endAddr
= sect
->addr() + sect
->size();
5780 for (pint_t addr
= sect
->addr(); addr
< endAddr
; addr
+= sizeof(pint_t
)) {
5781 typename Parser
<arm
>::SourceLocation src
;
5782 typename Parser
<arm
>::TargetDesc target
;
5783 src
.atom
= this->findAtomByAddress(addr
);
5784 src
.offsetInAtom
= 0;
5785 uint32_t symIndex
= parser
.symbolIndexFromIndirectSectionAddress(addr
, sect
);
5788 target
.weakImport
= false;
5790 if ( symIndex
== INDIRECT_SYMBOL_LOCAL
) {
5791 throwf("unexpected INDIRECT_SYMBOL_LOCAL in section %s", this->sectionName());
5794 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(symIndex
);
5795 // use direct reference for local symbols
5796 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && ((sym
.n_type() & N_EXT
) == 0) ) {
5797 throwf("unexpected pointer to local symbol in section %s", this->sectionName());
5800 target
.name
= parser
.nameFromSymbol(sym
);
5801 target
.weakImport
= parser
.weakImportFromSymbol(sym
);
5802 assert(src
.atom
->combine() == ld::Atom::combineByNameAndReferences
);
5805 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian32
, target
);
5809 template <typename A
>
5810 void TLVPointerSection
<A
>::makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&)
5812 assert(0 && "should not have thread-local-pointer sections in .o files");
5816 template <typename A
>
5817 const char* TLVPointerSection
<A
>::targetName(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
, bool* isStatic
)
5819 assert(atom
->combine() == ld::Atom::combineByNameAndReferences
);
5820 assert(atom
->fixupCount() == 1);
5822 ld::Fixup::iterator fit
= atom
->fixupsBegin();
5823 const char* name
= NULL
;
5824 switch ( fit
->binding
) {
5825 case ld::Fixup::bindingByNameUnbound
:
5828 case ld::Fixup::bindingByContentBound
:
5829 name
= fit
->u
.target
->name();
5831 case ld::Fixup::bindingsIndirectlyBound
:
5832 name
= ind
.indirectName(fit
->u
.bindingIndex
);
5834 case ld::Fixup::bindingDirectlyBound
:
5835 name
= fit
->u
.target
->name();
5836 *isStatic
= (fit
->u
.target
->scope() == ld::Atom::scopeTranslationUnit
);
5841 assert(name
!= NULL
);
5845 template <typename A
>
5846 unsigned long TLVPointerSection
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5848 assert(atom
->combine() == ld::Atom::combineByNameAndReferences
);
5849 unsigned long hash
= 9508;
5851 for (const char* s
= this->targetName(atom
, ind
, &isStatic
); *s
!= '\0'; ++s
) {
5852 hash
= hash
* 33 + *s
;
5857 template <typename A
>
5858 bool TLVPointerSection
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5859 const ld::IndirectBindingTable
& indirectBindingTable
) const
5861 if ( rhs
.section().type() != ld::Section::typeTLVPointers
)
5863 assert(this->type() == rhs
.section().type());
5864 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5865 assert(rhsAtom
!= NULL
);
5868 const char* thisName
= this->targetName(atom
, indirectBindingTable
, &thisIsStatic
);
5869 const char* rhsName
= this->targetName(rhsAtom
, indirectBindingTable
, &rhsIsStatic
);
5870 return !thisIsStatic
&& !rhsIsStatic
&& (strcmp(thisName
, rhsName
) == 0);
5874 template <typename A
>
5875 const uint8_t* CFStringSection
<A
>::targetContent(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
,
5876 ContentType
* ct
, unsigned int* count
)
5878 *ct
= contentUnknown
;
5879 for (ld::Fixup::iterator fit
=atom
->fixupsBegin(), end
=atom
->fixupsEnd(); fit
!= end
; ++fit
) {
5880 const ld::Atom
* targetAtom
= NULL
;
5881 switch ( fit
->binding
) {
5882 case ld::Fixup::bindingByNameUnbound
:
5883 // ignore reference to ___CFConstantStringClassReference
5884 // we are just looking for reference to backing string data
5885 assert(fit
->offsetInAtom
== 0);
5886 assert(strcmp(fit
->u
.name
, "___CFConstantStringClassReference") == 0);
5888 case ld::Fixup::bindingDirectlyBound
:
5889 case ld::Fixup::bindingByContentBound
:
5890 targetAtom
= fit
->u
.target
;
5892 case ld::Fixup::bindingsIndirectlyBound
:
5893 targetAtom
= ind
.indirectAtom(fit
->u
.bindingIndex
);
5896 assert(0 && "bad binding type");
5898 assert(targetAtom
!= NULL
);
5899 const Atom
<A
>* target
= dynamic_cast<const Atom
<A
>*>(targetAtom
);
5900 if ( targetAtom
->section().type() == ld::Section::typeCString
) {
5902 *count
= targetAtom
->size();
5904 else if ( targetAtom
->section().type() == ld::Section::typeUTF16Strings
) {
5906 *count
= (targetAtom
->size()+1)/2; // round up incase of buggy compiler that has only one trailing zero byte
5909 *ct
= contentUnknown
;
5913 return target
->contentPointer();
5919 template <typename A
>
5920 unsigned long CFStringSection
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5922 // base hash of CFString on hash of cstring it wraps
5925 unsigned int charCount
;
5926 const uint8_t* content
= this->targetContent(atom
, ind
, &cType
, &charCount
);
5930 for (const char* s
= (char*)content
; *s
!= '\0'; ++s
) {
5931 hash
= hash
* 33 + *s
;
5936 --charCount
; // don't add last 0x0000 to hash because some buggy compilers only have trailing single byte
5937 for (const uint16_t* s
= (uint16_t*)content
; charCount
> 0; ++s
, --charCount
) {
5938 hash
= hash
* 1025 + *s
;
5941 case contentUnknown
:
5942 // <rdar://problem/14134211> For malformed CFStrings, hash to address of atom so they have unique hashes
5943 return ULONG_MAX
- (unsigned long)(atom
);
5949 template <typename A
>
5950 bool CFStringSection
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5951 const ld::IndirectBindingTable
& indirectBindingTable
) const
5955 if ( rhs
.section().type() != ld::Section::typeCFString
)
5957 assert(this->type() == rhs
.section().type());
5958 assert(strcmp(this->sectionName(), "__cfstring") == 0);
5960 ContentType thisType
;
5961 unsigned int charCount
;
5962 const uint8_t* cstringContent
= this->targetContent(atom
, indirectBindingTable
, &thisType
, &charCount
);
5963 ContentType rhsType
;
5964 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5965 assert(rhsAtom
!= NULL
);
5966 unsigned int rhsCharCount
;
5967 const uint8_t* rhsStringContent
= this->targetContent(rhsAtom
, indirectBindingTable
, &rhsType
, &rhsCharCount
);
5969 if ( thisType
!= rhsType
)
5972 if ( thisType
== contentUnknown
)
5975 if ( rhsType
== contentUnknown
)
5978 // no need to compare content of pointers are already the same
5979 if ( cstringContent
== rhsStringContent
)
5982 // no need to compare content if size is different
5983 if ( charCount
!= rhsCharCount
)
5986 switch ( thisType
) {
5988 return (strcmp((char*)cstringContent
, (char*)rhsStringContent
) == 0);
5991 const uint16_t* cstringContent16
= (uint16_t*)cstringContent
;
5992 const uint16_t* rhsStringContent16
= (uint16_t*)rhsStringContent
;
5993 for (unsigned int i
= 0; i
< charCount
; ++i
) {
5994 if ( cstringContent16
[i
] != rhsStringContent16
[i
] )
5999 case contentUnknown
:
6006 template <typename A
>
6007 typename
A::P::uint_t ObjC1ClassSection
<A
>::elementSizeAtAddress(pint_t addr
)
6009 // nominal size for each class is 48 bytes, but sometimes the compiler
6010 // over aligns and there is padding after class data
6011 const macho_section
<P
>* sct
= this->machoSection();
6012 uint32_t align
= 1 << sct
->align();
6013 uint32_t size
= ((12 * sizeof(pint_t
)) + align
-1) & (-align
);
6017 template <typename A
>
6018 const char* ObjC1ClassSection
<A
>::unlabeledAtomName(Parser
<A
>& parser
, pint_t addr
)
6020 // 8-bytes into class object is pointer to class name
6021 const macho_section
<P
>* sct
= this->machoSection();
6022 uint32_t classObjcFileOffset
= sct
->offset() - sct
->addr() + addr
;
6023 const uint8_t* mappedFileContent
= this->file().fileContent();
6024 pint_t nameAddr
= P::getP(*((pint_t
*)(mappedFileContent
+classObjcFileOffset
+2*sizeof(pint_t
))));
6026 // find section containing string address to get string bytes
6027 const macho_section
<P
>* const sections
= parser
.firstMachOSection();
6028 const uint32_t sectionCount
= parser
.machOSectionCount();
6029 for (uint32_t i
=0; i
< sectionCount
; ++i
) {
6030 const macho_section
<P
>* aSect
= §ions
[i
];
6031 if ( (aSect
->addr() <= nameAddr
) && (nameAddr
< (aSect
->addr()+aSect
->size())) ) {
6032 assert((aSect
->flags() & SECTION_TYPE
) == S_CSTRING_LITERALS
);
6033 uint32_t nameFileOffset
= aSect
->offset() - aSect
->addr() + nameAddr
;
6034 const char* name
= (char*)mappedFileContent
+ nameFileOffset
;
6035 // spin through symbol table to find absolute symbol corresponding to this class
6036 for (uint32_t s
=0; s
< parser
.symbolCount(); ++s
) {
6037 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(s
);
6038 if ( (sym
.n_type() & N_TYPE
) != N_ABS
)
6040 const char* absName
= parser
.nameFromSymbol(sym
);
6041 if ( strncmp(absName
, ".objc_class_name_", 17) == 0 ) {
6042 if ( strcmp(&absName
[17], name
) == 0 )
6046 assert(0 && "obj class name not found in symbol table");
6049 assert(0 && "obj class name not found");
6050 return "unknown objc class";
6054 template <typename A
>
6055 const char* ObjC2ClassRefsSection
<A
>::targetClassName(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
6057 assert(atom
->fixupCount() == 1);
6058 ld::Fixup::iterator fit
= atom
->fixupsBegin();
6059 const char* className
= NULL
;
6060 switch ( fit
->binding
) {
6061 case ld::Fixup::bindingByNameUnbound
:
6062 className
= fit
->u
.name
;
6064 case ld::Fixup::bindingDirectlyBound
:
6065 case ld::Fixup::bindingByContentBound
:
6066 className
= fit
->u
.target
->name();
6068 case ld::Fixup::bindingsIndirectlyBound
:
6069 className
= ind
.indirectName(fit
->u
.bindingIndex
);
6072 assert(0 && "unsupported binding in objc2 class ref section");
6074 assert(className
!= NULL
);
6079 template <typename A
>
6080 unsigned long ObjC2ClassRefsSection
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
6082 unsigned long hash
= 978;
6083 for (const char* s
= targetClassName(atom
, ind
); *s
!= '\0'; ++s
) {
6084 hash
= hash
* 33 + *s
;
6089 template <typename A
>
6090 bool ObjC2ClassRefsSection
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
6091 const ld::IndirectBindingTable
& indirectBindingTable
) const
6093 assert(this->type() == rhs
.section().type());
6094 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
6095 assert(rhsAtom
!= NULL
);
6096 const char* thisClassName
= targetClassName(atom
, indirectBindingTable
);
6097 const char* rhsClassName
= targetClassName(rhsAtom
, indirectBindingTable
);
6098 return (strcmp(thisClassName
, rhsClassName
) == 0);
6102 template <typename A
>
6103 const char* Objc1ClassReferences
<A
>::targetCString(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
6105 assert(atom
->fixupCount() == 2);
6106 ld::Fixup::iterator fit
= atom
->fixupsBegin();
6107 if ( fit
->kind
== ld::Fixup::kindSetTargetAddress
)
6109 const ld::Atom
* targetAtom
= NULL
;
6110 switch ( fit
->binding
) {
6111 case ld::Fixup::bindingByContentBound
:
6112 targetAtom
= fit
->u
.target
;
6114 case ld::Fixup::bindingsIndirectlyBound
:
6115 targetAtom
= ind
.indirectAtom(fit
->u
.bindingIndex
);
6116 if ( targetAtom
== NULL
) {
6117 fprintf(stderr
, "missing target named %s\n", ind
.indirectName(fit
->u
.bindingIndex
));
6123 assert(targetAtom
!= NULL
);
6124 const Atom
<A
>* target
= dynamic_cast<const Atom
<A
>*>(targetAtom
);
6125 assert(target
!= NULL
);
6126 return (char*)target
->contentPointer();
6130 template <typename A
>
6131 const char* PointerToCStringSection
<A
>::targetCString(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
6133 assert(atom
->fixupCount() == 1);
6134 ld::Fixup::iterator fit
= atom
->fixupsBegin();
6135 const ld::Atom
* targetAtom
= NULL
;
6136 switch ( fit
->binding
) {
6137 case ld::Fixup::bindingByContentBound
:
6138 targetAtom
= fit
->u
.target
;
6140 case ld::Fixup::bindingsIndirectlyBound
:
6141 targetAtom
= ind
.indirectAtom(fit
->u
.bindingIndex
);
6143 case ld::Fixup::bindingDirectlyBound
:
6144 targetAtom
= fit
->u
.target
;
6147 assert(0 && "unsupported reference to selector");
6149 assert(targetAtom
!= NULL
);
6150 const Atom
<A
>* target
= dynamic_cast<const Atom
<A
>*>(targetAtom
);
6151 assert(target
!= NULL
);
6152 assert(target
->contentType() == ld::Atom::typeCString
);
6153 return (char*)target
->contentPointer();
6156 template <typename A
>
6157 unsigned long PointerToCStringSection
<A
>::contentHash(const class Atom
<A
>* atom
,
6158 const ld::IndirectBindingTable
& indirectBindingTable
) const
6160 // make hash from section name and target cstring name
6161 unsigned long hash
= 123;
6162 for (const char* s
= this->sectionName(); *s
!= '\0'; ++s
) {
6163 hash
= hash
* 33 + *s
;
6165 for (const char* s
= this->targetCString(atom
, indirectBindingTable
); *s
!= '\0'; ++s
) {
6166 hash
= hash
* 33 + *s
;
6171 template <typename A
>
6172 bool PointerToCStringSection
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
6173 const ld::IndirectBindingTable
& indirectBindingTable
) const
6175 assert(this->type() == rhs
.section().type());
6176 // there can be pointers-to-cstrings in different section names
6177 // we only want to coalesce in same section name
6178 if ( *this != rhs
.section() )
6181 // get string content for this
6182 const char* cstringContent
= this->targetCString(atom
, indirectBindingTable
);
6183 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
6184 assert(rhsAtom
!= NULL
);
6185 const char* rhsCstringContent
= this->targetCString(rhsAtom
, indirectBindingTable
);
6187 assert(cstringContent
!= NULL
);
6188 assert(rhsCstringContent
!= NULL
);
6189 return (strcmp(cstringContent
, rhsCstringContent
) == 0);
6194 template <typename A
>
6195 unsigned long UTF16StringSection
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
6197 unsigned long hash
= 5381;
6198 const uint16_t* stringContent
= (uint16_t*)atom
->contentPointer();
6199 // some buggy compilers end utf16 data with single byte, so don't use last word in hash computation
6200 unsigned int count
= (atom
->size()/2) - 1;
6201 for (const uint16_t* s
= stringContent
; count
> 0; ++s
, --count
) {
6202 hash
= hash
* 33 + *s
;
6207 template <typename A
>
6208 bool UTF16StringSection
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
6209 const ld::IndirectBindingTable
& ind
) const
6211 if ( rhs
.section().type() != ld::Section::typeUTF16Strings
)
6224 uint32_t Section
<x86_64
>::x86_64PcRelOffset(uint8_t r_type
)
6227 case X86_64_RELOC_SIGNED
:
6229 case X86_64_RELOC_SIGNED_1
:
6231 case X86_64_RELOC_SIGNED_2
:
6233 case X86_64_RELOC_SIGNED_4
:
6241 bool Section
<x86_64
>::addRelocFixup(class Parser
<x86_64
>& parser
, const macho_relocation_info
<P
>* reloc
)
6243 const macho_section
<P
>* sect
= this->machoSection();
6244 uint64_t srcAddr
= sect
->addr() + reloc
->r_address();
6245 Parser
<x86_64
>::SourceLocation src
;
6246 Parser
<x86_64
>::TargetDesc target
;
6247 Parser
<x86_64
>::TargetDesc toTarget
;
6248 src
.atom
= this->findAtomByAddress(srcAddr
);
6249 src
.offsetInAtom
= srcAddr
- src
.atom
->_objAddress
;
6250 const uint8_t* fixUpPtr
= file().fileContent() + sect
->offset() + reloc
->r_address();
6251 uint64_t contentValue
= 0;
6252 const macho_relocation_info
<x86_64::P
>* nextReloc
= &reloc
[1];
6253 bool result
= false;
6254 bool useDirectBinding
;
6255 switch ( reloc
->r_length() ) {
6257 contentValue
= *fixUpPtr
;
6260 contentValue
= (int64_t)(int16_t)E::get16(*((uint16_t*)fixUpPtr
));
6263 contentValue
= (int64_t)(int32_t)E::get32(*((uint32_t*)fixUpPtr
));
6266 contentValue
= E::get64(*((uint64_t*)fixUpPtr
));
6271 target
.weakImport
= false;
6273 if ( reloc
->r_extern() ) {
6274 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
6275 // use direct reference for local symbols
6276 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && (((sym
.n_type() & N_EXT
) == 0) || (parser
.nameFromSymbol(sym
)[0] == 'L')) ) {
6277 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
6278 target
.addend
+= contentValue
;
6281 target
.name
= parser
.nameFromSymbol(sym
);
6282 target
.weakImport
= parser
.weakImportFromSymbol(sym
);
6283 target
.addend
= contentValue
;
6285 // cfstrings should always use direct reference to backing store
6286 if ( (this->type() == ld::Section::typeCFString
) && (src
.offsetInAtom
!= 0) ) {
6287 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
6288 target
.addend
= contentValue
;
6292 if ( reloc
->r_pcrel() )
6293 contentValue
+= srcAddr
+ x86_64PcRelOffset(reloc
->r_type());
6294 parser
.findTargetFromAddressAndSectionNum(contentValue
, reloc
->r_symbolnum(), target
);
6296 switch ( reloc
->r_type() ) {
6297 case X86_64_RELOC_UNSIGNED
:
6298 if ( reloc
->r_pcrel() )
6299 throw "pcrel and X86_64_RELOC_UNSIGNED not supported";
6300 switch ( reloc
->r_length() ) {
6303 throw "length < 2 and X86_64_RELOC_UNSIGNED not supported";
6305 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian32
, target
);
6308 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian64
, target
);
6312 case X86_64_RELOC_SIGNED
:
6313 case X86_64_RELOC_SIGNED_1
:
6314 case X86_64_RELOC_SIGNED_2
:
6315 case X86_64_RELOC_SIGNED_4
:
6316 if ( ! reloc
->r_pcrel() )
6317 throw "not pcrel and X86_64_RELOC_SIGNED* not supported";
6318 if ( reloc
->r_length() != 2 )
6319 throw "length != 2 and X86_64_RELOC_SIGNED* not supported";
6320 switch ( reloc
->r_type() ) {
6321 case X86_64_RELOC_SIGNED
:
6322 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32
, target
);
6324 case X86_64_RELOC_SIGNED_1
:
6325 if ( reloc
->r_extern() )
6327 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32_1
, target
);
6329 case X86_64_RELOC_SIGNED_2
:
6330 if ( reloc
->r_extern() )
6332 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32_2
, target
);
6334 case X86_64_RELOC_SIGNED_4
:
6335 if ( reloc
->r_extern() )
6337 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32_4
, target
);
6341 case X86_64_RELOC_BRANCH
:
6342 if ( ! reloc
->r_pcrel() )
6343 throw "not pcrel and X86_64_RELOC_BRANCH not supported";
6344 switch ( reloc
->r_length() ) {
6346 if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_probe$", 16) == 0) ) {
6347 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindStoreX86DtraceCallSiteNop
, false, target
.name
);
6348 parser
.addDtraceExtraInfos(src
, &target
.name
[16]);
6350 else if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_isenabled$", 20) == 0) ) {
6351 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindStoreX86DtraceIsEnableSiteClear
, false, target
.name
);
6352 parser
.addDtraceExtraInfos(src
, &target
.name
[20]);
6355 parser
.addFixups(src
, ld::Fixup::kindStoreX86BranchPCRel32
, target
);
6359 parser
.addFixups(src
, ld::Fixup::kindStoreX86BranchPCRel8
, target
);
6362 throwf("length=%d and X86_64_RELOC_BRANCH not supported", reloc
->r_length());
6365 case X86_64_RELOC_GOT
:
6366 if ( ! reloc
->r_extern() )
6367 throw "not extern and X86_64_RELOC_GOT not supported";
6368 if ( ! reloc
->r_pcrel() )
6369 throw "not pcrel and X86_64_RELOC_GOT not supported";
6370 if ( reloc
->r_length() != 2 )
6371 throw "length != 2 and X86_64_RELOC_GOT not supported";
6372 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32GOT
, target
);
6374 case X86_64_RELOC_GOT_LOAD
:
6375 if ( ! reloc
->r_extern() )
6376 throw "not extern and X86_64_RELOC_GOT_LOAD not supported";
6377 if ( ! reloc
->r_pcrel() )
6378 throw "not pcrel and X86_64_RELOC_GOT_LOAD not supported";
6379 if ( reloc
->r_length() != 2 )
6380 throw "length != 2 and X86_64_RELOC_GOT_LOAD not supported";
6381 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32GOTLoad
, target
);
6383 case X86_64_RELOC_SUBTRACTOR
:
6384 if ( reloc
->r_pcrel() )
6385 throw "X86_64_RELOC_SUBTRACTOR cannot be pc-relative";
6386 if ( reloc
->r_length() < 2 )
6387 throw "X86_64_RELOC_SUBTRACTOR must have r_length of 2 or 3";
6388 if ( !reloc
->r_extern() )
6389 throw "X86_64_RELOC_SUBTRACTOR must have r_extern=1";
6390 if ( nextReloc
->r_type() != X86_64_RELOC_UNSIGNED
)
6391 throw "X86_64_RELOC_SUBTRACTOR must be followed by X86_64_RELOC_UNSIGNED";
6393 if ( nextReloc
->r_pcrel() )
6394 throw "X86_64_RELOC_UNSIGNED following a X86_64_RELOC_SUBTRACTOR cannot be pc-relative";
6395 if ( nextReloc
->r_length() != reloc
->r_length() )
6396 throw "X86_64_RELOC_UNSIGNED following a X86_64_RELOC_SUBTRACTOR must have same r_length";
6397 if ( nextReloc
->r_extern() ) {
6398 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(nextReloc
->r_symbolnum());
6399 // use direct reference for local symbols
6400 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && (((sym
.n_type() & N_EXT
) == 0) || (parser
.nameFromSymbol(sym
)[0] == 'L')) ) {
6401 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), toTarget
);
6402 toTarget
.addend
= contentValue
;
6403 useDirectBinding
= true;
6406 toTarget
.name
= parser
.nameFromSymbol(sym
);
6407 toTarget
.weakImport
= parser
.weakImportFromSymbol(sym
);
6408 toTarget
.addend
= contentValue
;
6409 useDirectBinding
= false;
6413 parser
.findTargetFromAddressAndSectionNum(contentValue
, nextReloc
->r_symbolnum(), toTarget
);
6414 useDirectBinding
= (toTarget
.atom
->scope() == ld::Atom::scopeTranslationUnit
) || ((toTarget
.atom
->combine() == ld::Atom::combineByNameAndContent
) || (toTarget
.atom
->combine() == ld::Atom::combineByNameAndReferences
));
6416 if ( useDirectBinding
) {
6417 if ( (toTarget
.atom
->combine() == ld::Atom::combineByNameAndContent
) || (toTarget
.atom
->combine() == ld::Atom::combineByNameAndReferences
) )
6418 parser
.addFixup(src
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, toTarget
.atom
);
6420 parser
.addFixup(src
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, toTarget
.atom
);
6423 parser
.addFixup(src
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, toTarget
.weakImport
, toTarget
.name
);
6424 parser
.addFixup(src
, ld::Fixup::k2of4
, ld::Fixup::kindAddAddend
, toTarget
.addend
);
6425 if ( target
.atom
== NULL
)
6426 parser
.addFixup(src
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractTargetAddress
, false, target
.name
);
6428 parser
.addFixup(src
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractTargetAddress
, target
.atom
);
6429 if ( reloc
->r_length() == 2 )
6430 parser
.addFixup(src
, ld::Fixup::k4of4
, ld::Fixup::kindStoreLittleEndian32
);
6432 parser
.addFixup(src
, ld::Fixup::k4of4
, ld::Fixup::kindStoreLittleEndian64
);
6434 case X86_64_RELOC_TLV
:
6435 if ( ! reloc
->r_extern() )
6436 throw "not extern and X86_64_RELOC_TLV not supported";
6437 if ( ! reloc
->r_pcrel() )
6438 throw "not pcrel and X86_64_RELOC_TLV not supported";
6439 if ( reloc
->r_length() != 2 )
6440 throw "length != 2 and X86_64_RELOC_TLV not supported";
6441 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32TLVLoad
, target
);
6444 throwf("unknown relocation type %d", reloc
->r_type());
6452 bool Section
<x86
>::addRelocFixup(class Parser
<x86
>& parser
, const macho_relocation_info
<P
>* reloc
)
6454 const macho_section
<P
>* sect
= this->machoSection();
6456 const uint8_t* fixUpPtr
;
6457 uint32_t contentValue
= 0;
6458 ld::Fixup::Kind kind
= ld::Fixup::kindNone
;
6459 Parser
<x86
>::SourceLocation src
;
6460 Parser
<x86
>::TargetDesc target
;
6462 if ( (reloc
->r_address() & R_SCATTERED
) == 0 ) {
6463 srcAddr
= sect
->addr() + reloc
->r_address();
6464 src
.atom
= this->findAtomByAddress(srcAddr
);
6465 src
.offsetInAtom
= srcAddr
- src
.atom
->_objAddress
;
6466 fixUpPtr
= file().fileContent() + sect
->offset() + reloc
->r_address();
6467 switch ( reloc
->r_type() ) {
6468 case GENERIC_RELOC_VANILLA
:
6469 switch ( reloc
->r_length() ) {
6471 contentValue
= (int32_t)(int8_t)*fixUpPtr
;
6472 if ( reloc
->r_pcrel() ) {
6473 kind
= ld::Fixup::kindStoreX86BranchPCRel8
;
6474 contentValue
+= srcAddr
+ sizeof(uint8_t);
6477 throw "r_length=0 and r_pcrel=0 not supported";
6480 contentValue
= (int32_t)(int16_t)E::get16(*((uint16_t*)fixUpPtr
));
6481 if ( reloc
->r_pcrel() ) {
6482 kind
= ld::Fixup::kindStoreX86PCRel16
;
6483 contentValue
+= srcAddr
+ sizeof(uint16_t);
6486 kind
= ld::Fixup::kindStoreLittleEndian16
;
6489 contentValue
= E::get32(*((uint32_t*)fixUpPtr
));
6490 if ( reloc
->r_pcrel() ) {
6491 kind
= ld::Fixup::kindStoreX86BranchPCRel32
;
6492 contentValue
+= srcAddr
+ sizeof(uint32_t);
6495 kind
= ld::Fixup::kindStoreLittleEndian32
;
6498 throw "r_length=3 not supported";
6500 if ( reloc
->r_extern() ) {
6502 const macho_nlist
<P
>& targetSymbol
= parser
.symbolFromIndex(reloc
->r_symbolnum());
6503 target
.name
= parser
.nameFromSymbol(targetSymbol
);
6504 target
.weakImport
= parser
.weakImportFromSymbol(targetSymbol
);
6505 target
.addend
= (int32_t)contentValue
;
6508 parser
.findTargetFromAddressAndSectionNum(contentValue
, reloc
->r_symbolnum(), target
);
6510 if ( (kind
== ld::Fixup::kindStoreX86BranchPCRel32
) && (target
.name
!= NULL
) ) {
6511 if ( strncmp(target
.name
, "___dtrace_probe$", 16) == 0 ) {
6512 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindStoreX86DtraceCallSiteNop
, false, target
.name
);
6513 parser
.addDtraceExtraInfos(src
, &target
.name
[16]);
6516 else if ( strncmp(target
.name
, "___dtrace_isenabled$", 20) == 0 ) {
6517 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindStoreX86DtraceIsEnableSiteClear
, false, target
.name
);
6518 parser
.addDtraceExtraInfos(src
, &target
.name
[20]);
6522 parser
.addFixups(src
, kind
, target
);
6525 case GENERIC_RLEOC_TLV
:
6527 if ( !reloc
->r_extern() )
6528 throw "r_extern=0 and r_type=GENERIC_RLEOC_TLV not supported";
6529 if ( reloc
->r_length() != 2 )
6530 throw "r_length!=2 and r_type=GENERIC_RLEOC_TLV not supported";
6531 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
6532 // use direct reference for local symbols
6533 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && ((sym
.n_type() & N_EXT
) == 0) ) {
6534 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
6538 target
.name
= parser
.nameFromSymbol(sym
);
6539 target
.weakImport
= parser
.weakImportFromSymbol(sym
);
6541 target
.addend
= (int64_t)(int32_t)E::get32(*((uint32_t*)fixUpPtr
));
6542 if ( reloc
->r_pcrel() ) {
6543 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32TLVLoad
, target
);
6546 parser
.addFixups(src
, ld::Fixup::kindStoreX86Abs32TLVLoad
, target
);
6552 throwf("unsupported i386 relocation type (%d)", reloc
->r_type());
6556 // scattered relocation
6557 const macho_scattered_relocation_info
<P
>* sreloc
= (macho_scattered_relocation_info
<P
>*)reloc
;
6558 srcAddr
= sect
->addr() + sreloc
->r_address();
6559 src
.atom
= this->findAtomByAddress(srcAddr
);
6560 assert(src
.atom
!= NULL
);
6561 src
.offsetInAtom
= srcAddr
- src
.atom
->_objAddress
;
6562 fixUpPtr
= file().fileContent() + sect
->offset() + sreloc
->r_address();
6563 uint32_t relocValue
= sreloc
->r_value();
6564 bool result
= false;
6565 // file format allows pair to be scattered or not
6566 const macho_scattered_relocation_info
<P
>* nextSReloc
= &sreloc
[1];
6567 const macho_relocation_info
<P
>* nextReloc
= &reloc
[1];
6568 bool nextRelocIsPair
= false;
6569 uint32_t nextRelocAddress
= 0;
6570 uint32_t nextRelocValue
= 0;
6571 if ( (nextReloc
->r_address() & R_SCATTERED
) == 0 ) {
6572 if ( nextReloc
->r_type() == GENERIC_RELOC_PAIR
) {
6573 nextRelocIsPair
= true;
6574 nextRelocAddress
= nextReloc
->r_address();
6575 result
= true; // iterator should skip next reloc, since we've consumed it here
6579 if ( nextSReloc
->r_type() == GENERIC_RELOC_PAIR
) {
6580 nextRelocIsPair
= true;
6581 nextRelocAddress
= nextSReloc
->r_address();
6582 nextRelocValue
= nextSReloc
->r_value();
6585 switch (sreloc
->r_type()) {
6586 case GENERIC_RELOC_VANILLA
:
6587 // with a scattered relocation we get both the target (sreloc->r_value()) and the target+offset (*fixUpPtr)
6588 target
.atom
= parser
.findAtomByAddress(relocValue
);
6589 if ( sreloc
->r_pcrel() ) {
6590 switch ( sreloc
->r_length() ) {
6592 contentValue
= srcAddr
+ 1 + *fixUpPtr
;
6593 target
.addend
= (int32_t)contentValue
- (int32_t)relocValue
;
6594 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel8
, target
);
6597 contentValue
= srcAddr
+ 2 + LittleEndian::get16(*((uint16_t*)fixUpPtr
));
6598 target
.addend
= (int32_t)contentValue
- (int32_t)relocValue
;
6599 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel16
, target
);
6602 contentValue
= srcAddr
+ 4 + LittleEndian::get32(*((uint32_t*)fixUpPtr
));
6603 target
.addend
= (int32_t)contentValue
- (int32_t)relocValue
;
6604 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32
, target
);
6607 throw "unsupported r_length=3 for scattered pc-rel vanilla reloc";
6612 if ( sreloc
->r_length() != 2 )
6613 throwf("unsupported r_length=%d for scattered vanilla reloc", sreloc
->r_length());
6614 contentValue
= LittleEndian::get32(*((uint32_t*)fixUpPtr
));
6615 target
.addend
= (int32_t)contentValue
- (int32_t)(target
.atom
->objectAddress());
6616 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian32
, target
);
6619 case GENERIC_RELOC_SECTDIFF
:
6620 case GENERIC_RELOC_LOCAL_SECTDIFF
:
6622 if ( !nextRelocIsPair
)
6623 throw "GENERIC_RELOC_SECTDIFF missing following pair";
6624 switch ( sreloc
->r_length() ) {
6627 throw "bad length for GENERIC_RELOC_SECTDIFF";
6629 contentValue
= (int32_t)(int16_t)LittleEndian::get16(*((uint16_t*)fixUpPtr
));
6630 kind
= ld::Fixup::kindStoreLittleEndian16
;
6633 contentValue
= LittleEndian::get32(*((uint32_t*)fixUpPtr
));
6634 kind
= ld::Fixup::kindStoreLittleEndian32
;
6637 Atom
<x86
>* fromAtom
= parser
.findAtomByAddress(nextRelocValue
);
6638 uint32_t offsetInFrom
= nextRelocValue
- fromAtom
->_objAddress
;
6639 parser
.findTargetFromAddress(sreloc
->r_value(), target
);
6640 // check for addend encoded in the section content
6641 int64_t addend
= (int32_t)contentValue
- (int32_t)(sreloc
->r_value() - nextRelocValue
);
6643 // switch binding base on coalescing
6644 if ( target
.atom
== NULL
) {
6645 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, target
.name
);
6647 else if ( target
.atom
->scope() == ld::Atom::scopeTranslationUnit
) {
6648 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, target
.atom
);
6650 else if ( (target
.atom
->combine() == ld::Atom::combineByNameAndContent
) || (target
.atom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
6651 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, target
.atom
);
6654 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, target
.atom
->name());
6656 parser
.addFixup(src
, ld::Fixup::k2of5
, ld::Fixup::kindAddAddend
, target
.addend
);
6657 parser
.addFixup(src
, ld::Fixup::k3of5
, ld::Fixup::kindSubtractTargetAddress
, fromAtom
);
6658 parser
.addFixup(src
, ld::Fixup::k4of5
, ld::Fixup::kindSubtractAddend
, offsetInFrom
-addend
);
6659 parser
.addFixup(src
, ld::Fixup::k5of5
, kind
);
6662 // switch binding base on coalescing
6663 if ( target
.atom
== NULL
) {
6664 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, target
.name
);
6666 else if ( target
.atom
->scope() == ld::Atom::scopeTranslationUnit
) {
6667 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, target
.atom
);
6669 else if ( (target
.atom
->combine() == ld::Atom::combineByNameAndContent
) || (target
.atom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
6670 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, target
.atom
);
6673 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, target
.atom
->name());
6675 parser
.addFixup(src
, ld::Fixup::k2of5
, ld::Fixup::kindAddAddend
, target
.addend
+addend
);
6676 parser
.addFixup(src
, ld::Fixup::k3of5
, ld::Fixup::kindSubtractTargetAddress
, fromAtom
);
6677 parser
.addFixup(src
, ld::Fixup::k4of5
, ld::Fixup::kindSubtractAddend
, offsetInFrom
);
6678 parser
.addFixup(src
, ld::Fixup::k5of5
, kind
);
6691 #if SUPPORT_ARCH_arm_any
6693 bool Section
<arm
>::addRelocFixup(class Parser
<arm
>& parser
, const macho_relocation_info
<P
>* reloc
)
6695 const macho_section
<P
>* sect
= this->machoSection();
6696 bool result
= false;
6700 int32_t displacement
= 0;
6701 uint32_t instruction
= 0;
6702 pint_t contentValue
= 0;
6703 Parser
<arm
>::SourceLocation src
;
6704 Parser
<arm
>::TargetDesc target
;
6705 const macho_relocation_info
<P
>* nextReloc
;
6707 if ( (reloc
->r_address() & R_SCATTERED
) == 0 ) {
6708 bool externSymbolIsThumbDef
= false;
6709 srcAddr
= sect
->addr() + reloc
->r_address();
6710 src
.atom
= this->findAtomByAddress(srcAddr
);
6711 src
.offsetInAtom
= srcAddr
- src
.atom
->_objAddress
;
6712 fixUpPtr
= (uint32_t*)(file().fileContent() + sect
->offset() + reloc
->r_address());
6713 if ( reloc
->r_type() != ARM_RELOC_PAIR
)
6714 instruction
= LittleEndian::get32(*fixUpPtr
);
6715 if ( reloc
->r_extern() ) {
6716 const macho_nlist
<P
>& targetSymbol
= parser
.symbolFromIndex(reloc
->r_symbolnum());
6717 // use direct reference for local symbols
6718 if ( ((targetSymbol
.n_type() & N_TYPE
) == N_SECT
) && (((targetSymbol
.n_type() & N_EXT
) == 0) || (parser
.nameFromSymbol(targetSymbol
)[0] == 'L')) ) {
6719 parser
.findTargetFromAddressAndSectionNum(targetSymbol
.n_value(), targetSymbol
.n_sect(), target
);
6723 target
.name
= parser
.nameFromSymbol(targetSymbol
);
6724 target
.weakImport
= parser
.weakImportFromSymbol(targetSymbol
);
6725 if ( ((targetSymbol
.n_type() & N_TYPE
) == N_SECT
) && (targetSymbol
.n_desc() & N_ARM_THUMB_DEF
) )
6726 externSymbolIsThumbDef
= true;
6729 switch ( reloc
->r_type() ) {
6730 case ARM_RELOC_BR24
:
6731 // Sign-extend displacement
6732 displacement
= (instruction
& 0x00FFFFFF) << 2;
6733 if ( (displacement
& 0x02000000) != 0 )
6734 displacement
|= 0xFC000000;
6735 // The pc added will be +8 from the pc
6737 // If this is BLX add H << 1
6738 if ((instruction
& 0xFE000000) == 0xFA000000)
6739 displacement
+= ((instruction
& 0x01000000) >> 23);
6740 if ( reloc
->r_extern() ) {
6741 dstAddr
= srcAddr
+ displacement
;
6742 // <rdar://problem/16652542> support large .o files
6743 if ( srcAddr
> 0x2000000 ) {
6744 dstAddr
-= ((srcAddr
+ 0x1FFFFFF) & 0xFC000000);
6746 target
.addend
= dstAddr
;
6747 if ( externSymbolIsThumbDef
)
6748 target
.addend
&= -2; // remove thumb bit
6751 dstAddr
= srcAddr
+ displacement
;
6752 parser
.findTargetFromAddressAndSectionNum(dstAddr
, reloc
->r_symbolnum(), target
);
6754 // special case "calls" for dtrace
6755 if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_probe$", 16) == 0) ) {
6756 parser
.addFixup(src
, ld::Fixup::k1of1
,
6757 ld::Fixup::kindStoreARMDtraceCallSiteNop
, false, target
.name
);
6758 parser
.addDtraceExtraInfos(src
, &target
.name
[16]);
6760 else if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_isenabled$", 20) == 0) ) {
6761 parser
.addFixup(src
, ld::Fixup::k1of1
,
6762 ld::Fixup::kindStoreARMDtraceIsEnableSiteClear
, false, target
.name
);
6763 parser
.addDtraceExtraInfos(src
, &target
.name
[20]);
6766 parser
.addFixups(src
, ld::Fixup::kindStoreARMBranch24
, target
);
6769 case ARM_THUMB_RELOC_BR22
:
6770 // thumb2 added two more bits to displacement, complicating the displacement decoding
6772 uint32_t s
= (instruction
>> 10) & 0x1;
6773 uint32_t j1
= (instruction
>> 29) & 0x1;
6774 uint32_t j2
= (instruction
>> 27) & 0x1;
6775 uint32_t imm10
= instruction
& 0x3FF;
6776 uint32_t imm11
= (instruction
>> 16) & 0x7FF;
6777 uint32_t i1
= (j1
== s
);
6778 uint32_t i2
= (j2
== s
);
6779 uint32_t dis
= (s
<< 24) | (i1
<< 23) | (i2
<< 22) | (imm10
<< 12) | (imm11
<< 1);
6783 displacement
= sdis
;
6785 // The pc added will be +4 from the pc
6787 // If the instruction was blx, force the low 2 bits to be clear
6788 dstAddr
= srcAddr
+ displacement
;
6789 if ((instruction
& 0xD0000000) == 0xC0000000)
6790 dstAddr
&= 0xFFFFFFFC;
6792 if ( reloc
->r_extern() ) {
6793 // <rdar://problem/16652542> support large .o files
6794 if ( srcAddr
> 0x1000000 ) {
6795 dstAddr
-= ((srcAddr
+ 0xFFFFFF) & 0xFE000000);
6797 target
.addend
= (int64_t)(int32_t)dstAddr
;
6800 parser
.findTargetFromAddressAndSectionNum(dstAddr
, reloc
->r_symbolnum(), target
);
6802 // special case "calls" for dtrace
6803 if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_probe$", 16) == 0) ) {
6804 parser
.addFixup(src
, ld::Fixup::k1of1
,
6805 ld::Fixup::kindStoreThumbDtraceCallSiteNop
, false, target
.name
);
6806 parser
.addDtraceExtraInfos(src
, &target
.name
[16]);
6808 else if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_isenabled$", 20) == 0) ) {
6809 parser
.addFixup(src
, ld::Fixup::k1of1
,
6810 ld::Fixup::kindStoreThumbDtraceIsEnableSiteClear
, false, target
.name
);
6811 parser
.addDtraceExtraInfos(src
, &target
.name
[20]);
6814 parser
.addFixups(src
, ld::Fixup::kindStoreThumbBranch22
, target
);
6817 case ARM_RELOC_VANILLA
:
6818 if ( reloc
->r_length() != 2 )
6819 throw "bad length for ARM_RELOC_VANILLA";
6820 contentValue
= LittleEndian::get32(*fixUpPtr
);
6821 if ( reloc
->r_extern() ) {
6822 target
.addend
= (int32_t)contentValue
;
6823 if ( externSymbolIsThumbDef
)
6824 target
.addend
&= -2; // remove thumb bit
6827 parser
.findTargetFromAddressAndSectionNum(contentValue
, reloc
->r_symbolnum(), target
);
6828 // possible non-extern relocation turned into by-name ref because target is a weak-def
6829 if ( target
.atom
!= NULL
) {
6830 if ( target
.atom
->isThumb() )
6831 target
.addend
&= -2; // remove thumb bit
6832 // if reference to LSDA, add group subordinate fixup
6833 if ( target
.atom
->contentType() == ld::Atom::typeLSDA
) {
6834 Parser
<arm
>::SourceLocation src2
;
6835 src2
.atom
= src
.atom
;
6836 src2
.offsetInAtom
= 0;
6837 parser
.addFixup(src2
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinateLSDA
, target
.atom
);
6841 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian32
, target
);
6843 case ARM_THUMB_32BIT_BRANCH
:
6844 // silently ignore old unnecessary reloc
6846 case ARM_RELOC_HALF
:
6847 nextReloc
= &reloc
[1];
6848 if ( nextReloc
->r_type() == ARM_RELOC_PAIR
) {
6849 uint32_t instruction16
;
6850 uint32_t other16
= (nextReloc
->r_address() & 0xFFFF);
6852 if ( reloc
->r_length() & 2 ) {
6854 uint32_t i
= ((instruction
& 0x00000400) >> 10);
6855 uint32_t imm4
= (instruction
& 0x0000000F);
6856 uint32_t imm3
= ((instruction
& 0x70000000) >> 28);
6857 uint32_t imm8
= ((instruction
& 0x00FF0000) >> 16);
6858 instruction16
= (imm4
<< 12) | (i
<< 11) | (imm3
<< 8) | imm8
;
6862 uint32_t imm4
= ((instruction
& 0x000F0000) >> 16);
6863 uint32_t imm12
= (instruction
& 0x00000FFF);
6864 instruction16
= (imm4
<< 12) | imm12
;
6866 if ( reloc
->r_length() & 1 ) {
6868 dstAddr
= ((instruction16
<< 16) | other16
);
6869 if ( reloc
->r_extern() ) {
6870 target
.addend
= dstAddr
;
6871 if ( externSymbolIsThumbDef
)
6872 target
.addend
&= -2; // remove thumb bit
6875 parser
.findTargetFromAddress(dstAddr
, target
);
6876 if ( target
.atom
->isThumb() )
6877 target
.addend
&= (-2); // remove thumb bit
6879 parser
.addFixups(src
, (isThumb
? ld::Fixup::kindStoreThumbHigh16
: ld::Fixup::kindStoreARMHigh16
), target
);
6883 dstAddr
= (other16
<< 16) | instruction16
;
6884 if ( reloc
->r_extern() ) {
6885 target
.addend
= dstAddr
;
6886 if ( externSymbolIsThumbDef
)
6887 target
.addend
&= -2; // remove thumb bit
6890 parser
.findTargetFromAddress(dstAddr
, target
);
6891 if ( target
.atom
->isThumb() )
6892 target
.addend
&= (-2); // remove thumb bit
6894 parser
.addFixups(src
, (isThumb
? ld::Fixup::kindStoreThumbLow16
: ld::Fixup::kindStoreARMLow16
), target
);
6899 throw "for ARM_RELOC_HALF, next reloc is not ARM_RELOC_PAIR";
6902 throwf("unknown relocation type %d", reloc
->r_type());
6907 const macho_scattered_relocation_info
<P
>* sreloc
= (macho_scattered_relocation_info
<P
>*)reloc
;
6908 // file format allows pair to be scattered or not
6909 const macho_scattered_relocation_info
<P
>* nextSReloc
= &sreloc
[1];
6910 nextReloc
= &reloc
[1];
6911 srcAddr
= sect
->addr() + sreloc
->r_address();
6912 dstAddr
= sreloc
->r_value();
6913 fixUpPtr
= (uint32_t*)(file().fileContent() + sect
->offset() + sreloc
->r_address());
6914 instruction
= LittleEndian::get32(*fixUpPtr
);
6915 src
.atom
= this->findAtomByAddress(srcAddr
);
6916 src
.offsetInAtom
= srcAddr
- src
.atom
->_objAddress
;
6917 bool nextRelocIsPair
= false;
6918 uint32_t nextRelocAddress
= 0;
6919 uint32_t nextRelocValue
= 0;
6920 if ( (nextReloc
->r_address() & R_SCATTERED
) == 0 ) {
6921 if ( nextReloc
->r_type() == ARM_RELOC_PAIR
) {
6922 nextRelocIsPair
= true;
6923 nextRelocAddress
= nextReloc
->r_address();
6928 if ( nextSReloc
->r_type() == ARM_RELOC_PAIR
) {
6929 nextRelocIsPair
= true;
6930 nextRelocAddress
= nextSReloc
->r_address();
6931 nextRelocValue
= nextSReloc
->r_value();
6935 switch ( sreloc
->r_type() ) {
6936 case ARM_RELOC_VANILLA
:
6937 // with a scattered relocation we get both the target (sreloc->r_value()) and the target+offset (*fixUpPtr)
6938 if ( sreloc
->r_length() != 2 )
6939 throw "bad length for ARM_RELOC_VANILLA";
6940 target
.atom
= parser
.findAtomByAddress(sreloc
->r_value());
6941 if ( target
.atom
== NULL
)
6942 throwf("bad r_value (0x%08X) for ARM_RELOC_VANILLA\n", sreloc
->r_value());
6943 contentValue
= LittleEndian::get32(*fixUpPtr
);
6944 target
.addend
= contentValue
- target
.atom
->_objAddress
;
6945 if ( target
.atom
->isThumb() )
6946 target
.addend
&= -2; // remove thumb bit
6947 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian32
, target
);
6949 case ARM_RELOC_BR24
:
6950 // Sign-extend displacement
6951 displacement
= (instruction
& 0x00FFFFFF) << 2;
6952 if ( (displacement
& 0x02000000) != 0 )
6953 displacement
|= 0xFC000000;
6954 // The pc added will be +8 from the pc
6956 // If this is BLX add H << 1
6957 if ((instruction
& 0xFE000000) == 0xFA000000)
6958 displacement
+= ((instruction
& 0x01000000) >> 23);
6959 target
.atom
= parser
.findAtomByAddress(sreloc
->r_value());
6960 target
.addend
= (int64_t)(srcAddr
+ displacement
) - (int64_t)(target
.atom
->_objAddress
);
6961 parser
.addFixups(src
, ld::Fixup::kindStoreARMBranch24
, target
);
6963 case ARM_THUMB_RELOC_BR22
:
6964 // thumb2 added two more bits to displacement, complicating the displacement decoding
6966 uint32_t s
= (instruction
>> 10) & 0x1;
6967 uint32_t j1
= (instruction
>> 29) & 0x1;
6968 uint32_t j2
= (instruction
>> 27) & 0x1;
6969 uint32_t imm10
= instruction
& 0x3FF;
6970 uint32_t imm11
= (instruction
>> 16) & 0x7FF;
6971 uint32_t i1
= (j1
== s
);
6972 uint32_t i2
= (j2
== s
);
6973 uint32_t dis
= (s
<< 24) | (i1
<< 23) | (i2
<< 22) | (imm10
<< 12) | (imm11
<< 1);
6977 displacement
= sdis
;
6979 // The pc added will be +4 from the pc
6981 dstAddr
= srcAddr
+displacement
;
6982 // If the instruction was blx, force the low 2 bits to be clear
6983 if ((instruction
& 0xF8000000) == 0xE8000000)
6984 dstAddr
&= 0xFFFFFFFC;
6985 target
.atom
= parser
.findAtomByAddress(sreloc
->r_value());
6986 target
.addend
= dstAddr
- target
.atom
->_objAddress
;
6987 parser
.addFixups(src
, ld::Fixup::kindStoreThumbBranch22
, target
);
6989 case ARM_RELOC_SECTDIFF
:
6990 case ARM_RELOC_LOCAL_SECTDIFF
:
6992 if ( ! nextRelocIsPair
)
6993 throw "ARM_RELOC_SECTDIFF missing following pair";
6994 if ( sreloc
->r_length() != 2 )
6995 throw "bad length for ARM_RELOC_SECTDIFF";
6996 contentValue
= LittleEndian::get32(*fixUpPtr
);
6997 Atom
<arm
>* fromAtom
= parser
.findAtomByAddress(nextRelocValue
);
6998 uint32_t offsetInFrom
= nextRelocValue
- fromAtom
->_objAddress
;
6999 uint32_t offsetInTarget
;
7000 Atom
<arm
>* targetAtom
= parser
.findAtomByAddressOrLocalTargetOfStub(sreloc
->r_value(), &offsetInTarget
);
7001 // check for addend encoded in the section content
7002 int64_t addend
= (int32_t)contentValue
- (int32_t)(sreloc
->r_value() - nextRelocValue
);
7003 if ( targetAtom
->isThumb() )
7004 addend
&= -2; // remove thumb bit
7005 // if reference to LSDA, add group subordinate fixup
7006 if ( targetAtom
->contentType() == ld::Atom::typeLSDA
) {
7007 Parser
<arm
>::SourceLocation src2
;
7008 src2
.atom
= src
.atom
;
7009 src2
.offsetInAtom
= 0;
7010 parser
.addFixup(src2
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinateLSDA
, targetAtom
);
7013 // switch binding base on coalescing
7014 if ( targetAtom
->scope() == ld::Atom::scopeTranslationUnit
) {
7015 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, targetAtom
);
7017 else if ( (targetAtom
->combine() == ld::Atom::combineByNameAndContent
) || (targetAtom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
7018 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, targetAtom
);
7021 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, targetAtom
->name());
7023 parser
.addFixup(src
, ld::Fixup::k2of5
, ld::Fixup::kindAddAddend
, offsetInTarget
);
7024 parser
.addFixup(src
, ld::Fixup::k3of5
, ld::Fixup::kindSubtractTargetAddress
, fromAtom
);
7025 parser
.addFixup(src
, ld::Fixup::k4of5
, ld::Fixup::kindSubtractAddend
, offsetInFrom
-addend
);
7026 parser
.addFixup(src
, ld::Fixup::k5of5
, ld::Fixup::kindStoreLittleEndian32
);
7029 if ( targetAtom
->scope() == ld::Atom::scopeTranslationUnit
) {
7030 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, targetAtom
);
7032 else if ( (targetAtom
->combine() == ld::Atom::combineByNameAndContent
) || (targetAtom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
7033 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, targetAtom
);
7036 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, targetAtom
->name());
7038 parser
.addFixup(src
, ld::Fixup::k2of5
, ld::Fixup::kindAddAddend
, (uint32_t)(offsetInTarget
+addend
));
7039 parser
.addFixup(src
, ld::Fixup::k3of5
, ld::Fixup::kindSubtractTargetAddress
, fromAtom
);
7040 parser
.addFixup(src
, ld::Fixup::k4of5
, ld::Fixup::kindSubtractAddend
, offsetInFrom
);
7041 parser
.addFixup(src
, ld::Fixup::k5of5
, ld::Fixup::kindStoreLittleEndian32
);
7045 case ARM_RELOC_HALF_SECTDIFF
:
7046 if ( nextRelocIsPair
) {
7047 instruction
= LittleEndian::get32(*fixUpPtr
);
7048 Atom
<arm
>* fromAtom
= parser
.findAtomByAddress(nextRelocValue
);
7049 uint32_t offsetInFrom
= nextRelocValue
- fromAtom
->_objAddress
;
7050 Atom
<arm
>* targetAtom
= parser
.findAtomByAddress(sreloc
->r_value());
7051 uint32_t offsetInTarget
= sreloc
->r_value() - targetAtom
->_objAddress
;
7052 uint32_t instruction16
;
7053 uint32_t other16
= (nextRelocAddress
& 0xFFFF);
7055 if ( sreloc
->r_length() & 2 ) {
7057 uint32_t i
= ((instruction
& 0x00000400) >> 10);
7058 uint32_t imm4
= (instruction
& 0x0000000F);
7059 uint32_t imm3
= ((instruction
& 0x70000000) >> 28);
7060 uint32_t imm8
= ((instruction
& 0x00FF0000) >> 16);
7061 instruction16
= (imm4
<< 12) | (i
<< 11) | (imm3
<< 8) | imm8
;
7065 uint32_t imm4
= ((instruction
& 0x000F0000) >> 16);
7066 uint32_t imm12
= (instruction
& 0x00000FFF);
7067 instruction16
= (imm4
<< 12) | imm12
;
7069 if ( sreloc
->r_length() & 1 )
7070 dstAddr
= ((instruction16
<< 16) | other16
);
7072 dstAddr
= (other16
<< 16) | instruction16
;
7073 if ( targetAtom
->isThumb() )
7074 dstAddr
&= (-2); // remove thumb bit
7075 int32_t addend
= dstAddr
- (sreloc
->r_value() - nextRelocValue
);
7076 if ( targetAtom
->scope() == ld::Atom::scopeTranslationUnit
) {
7077 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, targetAtom
);
7079 else if ( (targetAtom
->combine() == ld::Atom::combineByNameAndContent
) || (targetAtom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
7080 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, targetAtom
);
7083 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, targetAtom
->name());
7085 parser
.addFixup(src
, ld::Fixup::k2of5
, ld::Fixup::kindAddAddend
, (uint32_t)offsetInTarget
+addend
);
7086 parser
.addFixup(src
, ld::Fixup::k3of5
, ld::Fixup::kindSubtractTargetAddress
, fromAtom
);
7087 parser
.addFixup(src
, ld::Fixup::k4of5
, ld::Fixup::kindSubtractAddend
, offsetInFrom
);
7088 if ( sreloc
->r_length() & 1 ) {
7090 parser
.addFixup(src
, ld::Fixup::k5of5
, (isThumb
? ld::Fixup::kindStoreThumbHigh16
: ld::Fixup::kindStoreARMHigh16
));
7094 parser
.addFixup(src
, ld::Fixup::k5of5
, (isThumb
? ld::Fixup::kindStoreThumbLow16
: ld::Fixup::kindStoreARMLow16
));
7099 throw "ARM_RELOC_HALF_SECTDIFF reloc missing following pair";
7101 case ARM_RELOC_HALF
:
7102 if ( nextRelocIsPair
) {
7103 instruction
= LittleEndian::get32(*fixUpPtr
);
7104 Atom
<arm
>* targetAtom
= parser
.findAtomByAddress(sreloc
->r_value());
7105 uint32_t instruction16
;
7106 uint32_t other16
= (nextRelocAddress
& 0xFFFF);
7108 if ( sreloc
->r_length() & 2 ) {
7110 uint32_t i
= ((instruction
& 0x00000400) >> 10);
7111 uint32_t imm4
= (instruction
& 0x0000000F);
7112 uint32_t imm3
= ((instruction
& 0x70000000) >> 28);
7113 uint32_t imm8
= ((instruction
& 0x00FF0000) >> 16);
7114 instruction16
= (imm4
<< 12) | (i
<< 11) | (imm3
<< 8) | imm8
;
7118 uint32_t imm4
= ((instruction
& 0x000F0000) >> 16);
7119 uint32_t imm12
= (instruction
& 0x00000FFF);
7120 instruction16
= (imm4
<< 12) | imm12
;
7122 if ( sreloc
->r_length() & 1 )
7123 dstAddr
= ((instruction16
<< 16) | other16
);
7125 dstAddr
= (other16
<< 16) | instruction16
;
7126 if ( targetAtom
->scope() == ld::Atom::scopeTranslationUnit
) {
7127 parser
.addFixup(src
, ld::Fixup::k1of3
, ld::Fixup::kindSetTargetAddress
, targetAtom
);
7129 else if ( (targetAtom
->combine() == ld::Atom::combineByNameAndContent
) || (targetAtom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
7130 parser
.addFixup(src
, ld::Fixup::k1of3
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, targetAtom
);
7133 parser
.addFixup(src
, ld::Fixup::k1of3
, ld::Fixup::kindSetTargetAddress
, false, targetAtom
->name());
7135 parser
.addFixup(src
, ld::Fixup::k2of3
, ld::Fixup::kindAddAddend
, dstAddr
- targetAtom
->_objAddress
);
7136 if ( sreloc
->r_length() & 1 ) {
7138 parser
.addFixup(src
, ld::Fixup::k3of3
, (isThumb
? ld::Fixup::kindStoreThumbHigh16
: ld::Fixup::kindStoreARMHigh16
));
7142 parser
.addFixup(src
, ld::Fixup::k3of3
, (isThumb
? ld::Fixup::kindStoreThumbLow16
: ld::Fixup::kindStoreARMLow16
));
7147 throw "scattered ARM_RELOC_HALF reloc missing following pair";
7150 throwf("unknown ARM scattered relocation type %d", sreloc
->r_type());
7158 #if SUPPORT_ARCH_arm64
7160 bool Section
<arm64
>::addRelocFixup(class Parser
<arm64
>& parser
, const macho_relocation_info
<P
>* reloc
)
7162 bool result
= false;
7163 Parser
<arm64
>::SourceLocation src
;
7164 Parser
<arm64
>::TargetDesc target
= { NULL
, NULL
, false, 0 };
7165 Parser
<arm64
>::TargetDesc toTarget
;
7166 int32_t prefixRelocAddend
= 0;
7167 if ( reloc
->r_type() == ARM64_RELOC_ADDEND
) {
7168 uint32_t rawAddend
= reloc
->r_symbolnum();
7169 prefixRelocAddend
= rawAddend
;
7170 if ( rawAddend
& 0x00800000 )
7171 prefixRelocAddend
|= 0xFF000000; // sign extend 24-bit signed int to 32-bits
7172 uint32_t addendAddress
= reloc
->r_address();
7173 ++reloc
; //advance to next reloc record
7175 if ( reloc
->r_address() != addendAddress
)
7176 throw "ARM64_RELOC_ADDEND r_address does not match next reloc's r_address";
7178 const macho_section
<P
>* sect
= this->machoSection();
7179 uint64_t srcAddr
= sect
->addr() + reloc
->r_address();
7180 src
.atom
= this->findAtomByAddress(srcAddr
);
7181 src
.offsetInAtom
= srcAddr
- src
.atom
->_objAddress
;
7182 const uint8_t* fixUpPtr
= file().fileContent() + sect
->offset() + reloc
->r_address();
7183 uint64_t contentValue
= 0;
7184 const macho_relocation_info
<arm64::P
>* nextReloc
= &reloc
[1];
7185 bool useDirectBinding
;
7186 uint32_t instruction
;
7187 uint32_t encodedAddend
;
7188 switch ( reloc
->r_length() ) {
7190 contentValue
= *fixUpPtr
;
7193 contentValue
= (int64_t)(int16_t)E::get16(*((uint16_t*)fixUpPtr
));
7196 contentValue
= (int64_t)(int32_t)E::get32(*((uint32_t*)fixUpPtr
));
7199 contentValue
= E::get64(*((uint64_t*)fixUpPtr
));
7202 if ( reloc
->r_extern() ) {
7203 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
7204 const char* symbolName
= parser
.nameFromSymbol(sym
);
7205 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && (((sym
.n_type() & N_EXT
) == 0) || (symbolName
[0] == 'L') || (symbolName
[0] == 'l')) ) {
7206 // use direct reference for local symbols
7207 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
7208 //target.addend += contentValue;
7210 else if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && (src
.atom
->_objAddress
<= sym
.n_value()) && (sym
.n_value() < (src
.atom
->_objAddress
+src
.atom
->size())) ) {
7211 // <rdar://problem/13700961> spurious warning when weak function has reference to itself
7212 // use direct reference when atom targets itself
7213 target
.atom
= src
.atom
;
7217 target
.name
= symbolName
;
7218 target
.weakImport
= parser
.weakImportFromSymbol(sym
);
7219 //target.addend = contentValue;
7221 // cfstrings should always use direct reference to backing store
7222 if ( (this->type() == ld::Section::typeCFString
) && (src
.offsetInAtom
!= 0) ) {
7223 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
7224 //target.addend = contentValue;
7228 if ( reloc
->r_pcrel() )
7229 contentValue
+= srcAddr
;
7230 parser
.findTargetFromAddressAndSectionNum(contentValue
, reloc
->r_symbolnum(), target
);
7232 switch ( reloc
->r_type() ) {
7233 case ARM64_RELOC_UNSIGNED
:
7234 if ( reloc
->r_pcrel() )
7235 throw "pcrel and ARM64_RELOC_UNSIGNED not supported";
7236 if ( reloc
->r_extern() )
7237 target
.addend
= contentValue
;
7238 switch ( reloc
->r_length() ) {
7241 throw "length < 2 and ARM64_RELOC_UNSIGNED not supported";
7243 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian32
, target
);
7246 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian64
, target
);
7250 case ARM64_RELOC_BRANCH26
:
7251 if ( ! reloc
->r_pcrel() )
7252 throw "not pcrel and ARM64_RELOC_BRANCH26 not supported";
7253 if ( ! reloc
->r_extern() )
7254 throw "r_extern == 0 and ARM64_RELOC_BRANCH26 not supported";
7255 if ( reloc
->r_length() != 2 )
7256 throw "r_length != 2 and ARM64_RELOC_BRANCH26 not supported";
7257 if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_probe$", 16) == 0) ) {
7258 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindStoreARM64DtraceCallSiteNop
, false, target
.name
);
7259 parser
.addDtraceExtraInfos(src
, &target
.name
[16]);
7261 else if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_isenabled$", 20) == 0) ) {
7262 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindStoreARM64DtraceIsEnableSiteClear
, false, target
.name
);
7263 parser
.addDtraceExtraInfos(src
, &target
.name
[20]);
7266 target
.addend
= prefixRelocAddend
;
7267 instruction
= contentValue
;
7268 encodedAddend
= (instruction
& 0x03FFFFFF) << 2;
7269 if ( encodedAddend
!= 0 ) {
7270 if ( prefixRelocAddend
== 0 ) {
7271 warning("branch26 instruction at 0x%08X has embedded addend. ARM64_RELOC_ADDEND should be used instead", reloc
->r_address());
7272 target
.addend
= encodedAddend
;
7275 throwf("branch26 instruction at 0x%08X has embedded addend and ARM64_RELOC_ADDEND also used", reloc
->r_address());
7278 parser
.addFixups(src
, ld::Fixup::kindStoreARM64Branch26
, target
);
7281 case ARM64_RELOC_PAGE21
:
7282 if ( ! reloc
->r_pcrel() )
7283 throw "not pcrel and ARM64_RELOC_PAGE21 not supported";
7284 if ( ! reloc
->r_extern() )
7285 throw "r_extern == 0 and ARM64_RELOC_PAGE21 not supported";
7286 if ( reloc
->r_length() != 2 )
7287 throw "length != 2 and ARM64_RELOC_PAGE21 not supported";
7288 target
.addend
= prefixRelocAddend
;
7289 instruction
= contentValue
;
7290 encodedAddend
= ((instruction
& 0x60000000) >> 29) | ((instruction
& 0x01FFFFE0) >> 3);
7291 encodedAddend
*= 4096; // internally addend is in bytes, so scale
7292 if ( encodedAddend
!= 0 ) {
7293 if ( prefixRelocAddend
== 0 ) {
7294 warning("adrp instruction at 0x%08X has embedded addend. ARM64_RELOC_ADDEND should be used instead", reloc
->r_address());
7295 target
.addend
= encodedAddend
;
7298 throwf("adrp instruction at 0x%08X has embedded addend and ARM64_RELOC_ADDEND also used", reloc
->r_address());
7301 parser
.addFixups(src
, ld::Fixup::kindStoreARM64Page21
, target
);
7303 case ARM64_RELOC_PAGEOFF12
:
7304 if ( reloc
->r_pcrel() )
7305 throw "pcrel and ARM64_RELOC_PAGEOFF12 not supported";
7306 if ( ! reloc
->r_extern() )
7307 throw "r_extern == 0 and ARM64_RELOC_PAGEOFF12 not supported";
7308 if ( reloc
->r_length() != 2 )
7309 throw "length != 2 and ARM64_RELOC_PAGEOFF12 not supported";
7310 target
.addend
= prefixRelocAddend
;
7311 instruction
= contentValue
;
7312 encodedAddend
= ((instruction
& 0x003FFC00) >> 10);
7313 // internally addend is in bytes. Some instructions have an implicit scale factor
7314 if ( (instruction
& 0x3B000000) == 0x39000000 ) {
7315 switch ( instruction
& 0xC0000000 ) {
7329 if ( encodedAddend
!= 0 ) {
7330 if ( prefixRelocAddend
== 0 ) {
7331 warning("pageoff12 instruction at 0x%08X has embedded addend. ARM64_RELOC_ADDEND should be used instead", reloc
->r_address());
7332 target
.addend
= encodedAddend
;
7335 throwf("pageoff12 instruction at 0x%08X has embedded addend and ARM64_RELOC_ADDEND also used", reloc
->r_address());
7338 parser
.addFixups(src
, ld::Fixup::kindStoreARM64PageOff12
, target
);
7340 case ARM64_RELOC_GOT_LOAD_PAGE21
:
7341 if ( ! reloc
->r_pcrel() )
7342 throw "not pcrel and ARM64_RELOC_GOT_LOAD_PAGE21 not supported";
7343 if ( ! reloc
->r_extern() )
7344 throw "r_extern == 0 and ARM64_RELOC_GOT_LOAD_PAGE21 not supported";
7345 if ( reloc
->r_length() != 2 )
7346 throw "length != 2 and ARM64_RELOC_GOT_LOAD_PAGE21 not supported";
7347 if ( prefixRelocAddend
!= 0 )
7348 throw "ARM64_RELOC_ADDEND followed by ARM64_RELOC_GOT_LOAD_PAGE21 not supported";
7349 instruction
= contentValue
;
7350 target
.addend
= ((instruction
& 0x60000000) >> 29) | ((instruction
& 0x01FFFFE0) >> 3);
7351 if ( target
.addend
!= 0 )
7352 throw "non-zero addend with ARM64_RELOC_GOT_LOAD_PAGE21 is not supported";
7353 parser
.addFixups(src
, ld::Fixup::kindStoreARM64GOTLoadPage21
, target
);
7355 case ARM64_RELOC_GOT_LOAD_PAGEOFF12
:
7356 if ( reloc
->r_pcrel() )
7357 throw "pcrel and ARM64_RELOC_GOT_LOAD_PAGEOFF12 not supported";
7358 if ( ! reloc
->r_extern() )
7359 throw "r_extern == 0 and ARM64_RELOC_GOT_LOAD_PAGEOFF12 not supported";
7360 if ( reloc
->r_length() != 2 )
7361 throw "length != 2 and ARM64_RELOC_GOT_LOAD_PAGEOFF12 not supported";
7362 if ( prefixRelocAddend
!= 0 )
7363 throw "ARM64_RELOC_ADDEND followed by ARM64_RELOC_GOT_LOAD_PAGEOFF12 not supported";
7364 instruction
= contentValue
;
7365 target
.addend
= ((instruction
& 0x003FFC00) >> 10);
7366 parser
.addFixups(src
, ld::Fixup::kindStoreARM64GOTLoadPageOff12
, target
);
7368 case ARM64_RELOC_TLVP_LOAD_PAGE21
:
7369 if ( ! reloc
->r_pcrel() )
7370 throw "not pcrel and ARM64_RELOC_TLVP_LOAD_PAGE21 not supported";
7371 if ( ! reloc
->r_extern() )
7372 throw "r_extern == 0 and ARM64_RELOC_TLVP_LOAD_PAGE21 not supported";
7373 if ( reloc
->r_length() != 2 )
7374 throw "length != 2 and ARM64_RELOC_TLVP_LOAD_PAGE21 not supported";
7375 if ( prefixRelocAddend
!= 0 )
7376 throw "ARM64_RELOC_ADDEND followed by ARM64_RELOC_TLVP_LOAD_PAGE21 not supported";
7377 instruction
= contentValue
;
7378 target
.addend
= ((instruction
& 0x60000000) >> 29) | ((instruction
& 0x01FFFFE0) >> 3);
7379 if ( target
.addend
!= 0 )
7380 throw "non-zero addend with ARM64_RELOC_GOT_LOAD_PAGE21 is not supported";
7381 parser
.addFixups(src
, ld::Fixup::kindStoreARM64TLVPLoadPage21
, target
);
7383 case ARM64_RELOC_TLVP_LOAD_PAGEOFF12
:
7384 if ( reloc
->r_pcrel() )
7385 throw "pcrel and ARM64_RELOC_TLVP_LOAD_PAGEOFF12 not supported";
7386 if ( ! reloc
->r_extern() )
7387 throw "r_extern == 0 and ARM64_RELOC_TLVP_LOAD_PAGEOFF12 not supported";
7388 if ( reloc
->r_length() != 2 )
7389 throw "length != 2 and ARM64_RELOC_TLVP_LOAD_PAGEOFF12 not supported";
7390 if ( prefixRelocAddend
!= 0 )
7391 throw "ARM64_RELOC_ADDEND followed by ARM64_RELOC_TLVP_LOAD_PAGEOFF12 not supported";
7392 instruction
= contentValue
;
7393 target
.addend
= ((instruction
& 0x003FFC00) >> 10);
7394 parser
.addFixups(src
, ld::Fixup::kindStoreARM64TLVPLoadPageOff12
, target
);
7396 case ARM64_RELOC_SUBTRACTOR
:
7397 if ( reloc
->r_pcrel() )
7398 throw "ARM64_RELOC_SUBTRACTOR cannot be pc-relative";
7399 if ( reloc
->r_length() < 2 )
7400 throw "ARM64_RELOC_SUBTRACTOR must have r_length of 2 or 3";
7401 if ( !reloc
->r_extern() )
7402 throw "ARM64_RELOC_SUBTRACTOR must have r_extern=1";
7403 if ( nextReloc
->r_type() != ARM64_RELOC_UNSIGNED
)
7404 throw "ARM64_RELOC_SUBTRACTOR must be followed by ARM64_RELOC_UNSIGNED";
7405 if ( prefixRelocAddend
!= 0 )
7406 throw "ARM64_RELOC_ADDEND followed by ARM64_RELOC_SUBTRACTOR not supported";
7408 if ( nextReloc
->r_pcrel() )
7409 throw "ARM64_RELOC_UNSIGNED following a ARM64_RELOC_SUBTRACTOR cannot be pc-relative";
7410 if ( nextReloc
->r_length() != reloc
->r_length() )
7411 throw "ARM64_RELOC_UNSIGNED following a ARM64_RELOC_SUBTRACTOR must have same r_length";
7412 if ( nextReloc
->r_extern() ) {
7413 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(nextReloc
->r_symbolnum());
7414 // use direct reference for local symbols
7415 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && (((sym
.n_type() & N_EXT
) == 0) || (parser
.nameFromSymbol(sym
)[0] == 'L')) ) {
7416 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), toTarget
);
7417 toTarget
.addend
= contentValue
;
7418 useDirectBinding
= true;
7421 toTarget
.name
= parser
.nameFromSymbol(sym
);
7422 toTarget
.weakImport
= parser
.weakImportFromSymbol(sym
);
7423 toTarget
.addend
= contentValue
;
7424 useDirectBinding
= false;
7428 parser
.findTargetFromAddressAndSectionNum(contentValue
, nextReloc
->r_symbolnum(), toTarget
);
7429 useDirectBinding
= (toTarget
.atom
->scope() == ld::Atom::scopeTranslationUnit
);
7431 if ( useDirectBinding
)
7432 parser
.addFixup(src
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, toTarget
.atom
);
7434 parser
.addFixup(src
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, toTarget
.weakImport
, toTarget
.name
);
7435 parser
.addFixup(src
, ld::Fixup::k2of4
, ld::Fixup::kindAddAddend
, toTarget
.addend
);
7436 if ( target
.atom
== NULL
)
7437 parser
.addFixup(src
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractTargetAddress
, false, target
.name
);
7439 parser
.addFixup(src
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractTargetAddress
, target
.atom
);
7440 if ( reloc
->r_length() == 2 )
7441 parser
.addFixup(src
, ld::Fixup::k4of4
, ld::Fixup::kindStoreLittleEndian32
);
7443 parser
.addFixup(src
, ld::Fixup::k4of4
, ld::Fixup::kindStoreLittleEndian64
);
7445 case ARM64_RELOC_POINTER_TO_GOT
:
7446 if ( ! reloc
->r_extern() )
7447 throw "r_extern == 0 and ARM64_RELOC_POINTER_TO_GOT not supported";
7448 if ( prefixRelocAddend
!= 0 )
7449 throw "ARM64_RELOC_ADDEND followed by ARM64_RELOC_POINTER_TO_GOT not supported";
7450 if ( reloc
->r_pcrel() ) {
7451 if ( reloc
->r_length() != 2 )
7452 throw "r_length != 2 and r_extern = 1 and ARM64_RELOC_POINTER_TO_GOT not supported";
7453 parser
.addFixups(src
, ld::Fixup::kindStoreARM64PCRelToGOT
, target
);
7456 if ( reloc
->r_length() != 3 )
7457 throw "r_length != 3 and r_extern = 0 and ARM64_RELOC_POINTER_TO_GOT not supported";
7458 parser
.addFixups(src
, ld::Fixup::kindStoreARM64PointerToGOT
, target
);
7462 throwf("unknown relocation type %d", reloc
->r_type());
7469 template <typename A
>
7470 bool ObjC1ClassSection
<A
>::addRelocFixup(class Parser
<A
>& parser
, const macho_relocation_info
<P
>* reloc
)
7473 FixedSizeSection
<A
>::addRelocFixup(parser
, reloc
);
7475 assert(0 && "needs template specialization");
7480 bool ObjC1ClassSection
<x86
>::addRelocFixup(class Parser
<x86
>& parser
, const macho_relocation_info
<x86::P
>* reloc
)
7482 // if this is the reloc for the super class name string, add implicit reference to super class
7483 if ( ((reloc
->r_address() & R_SCATTERED
) == 0) && (reloc
->r_type() == GENERIC_RELOC_VANILLA
) ) {
7484 assert( reloc
->r_length() == 2 );
7485 assert( ! reloc
->r_pcrel() );
7487 const macho_section
<P
>* sect
= this->machoSection();
7488 Parser
<x86
>::SourceLocation src
;
7489 uint32_t srcAddr
= sect
->addr() + reloc
->r_address();
7490 src
.atom
= this->findAtomByAddress(srcAddr
);
7491 src
.offsetInAtom
= srcAddr
- src
.atom
->objectAddress();
7492 if ( src
.offsetInAtom
== 4 ) {
7493 Parser
<x86
>::TargetDesc stringTarget
;
7494 const uint8_t* fixUpPtr
= file().fileContent() + sect
->offset() + reloc
->r_address();
7495 uint32_t contentValue
= LittleEndian::get32(*((uint32_t*)fixUpPtr
));
7496 parser
.findTargetFromAddressAndSectionNum(contentValue
, reloc
->r_symbolnum(), stringTarget
);
7498 assert(stringTarget
.atom
!= NULL
);
7499 assert(stringTarget
.atom
->contentType() == ld::Atom::typeCString
);
7500 const char* superClassBaseName
= (char*)stringTarget
.atom
->rawContentPointer();
7501 char* superClassName
= new char[strlen(superClassBaseName
) + 20];
7502 strcpy(superClassName
, ".objc_class_name_");
7503 strcat(superClassName
, superClassBaseName
);
7505 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindSetTargetAddress
, false, superClassName
);
7509 return FixedSizeSection
<x86
>::addRelocFixup(parser
, reloc
);
7514 template <typename A
>
7515 bool Objc1ClassReferences
<A
>::addRelocFixup(class Parser
<A
>& parser
, const macho_relocation_info
<P
>* reloc
)
7518 PointerToCStringSection
<A
>::addRelocFixup(parser
, reloc
);
7520 assert(0 && "needs template specialization");
7527 bool Objc1ClassReferences
<x86
>::addRelocFixup(class Parser
<x86
>& parser
, const macho_relocation_info
<x86::P
>* reloc
)
7529 // add implict class refs, fixups not usable yet, so look at relocations
7530 assert( (reloc
->r_address() & R_SCATTERED
) == 0 );
7531 assert( reloc
->r_type() == GENERIC_RELOC_VANILLA
);
7532 assert( reloc
->r_length() == 2 );
7533 assert( ! reloc
->r_pcrel() );
7535 const macho_section
<P
>* sect
= this->machoSection();
7536 Parser
<x86
>::SourceLocation src
;
7537 uint32_t srcAddr
= sect
->addr() + reloc
->r_address();
7538 src
.atom
= this->findAtomByAddress(srcAddr
);
7539 src
.offsetInAtom
= srcAddr
- src
.atom
->objectAddress();
7540 Parser
<x86
>::TargetDesc stringTarget
;
7541 const uint8_t* fixUpPtr
= file().fileContent() + sect
->offset() + reloc
->r_address();
7542 uint32_t contentValue
= LittleEndian::get32(*((uint32_t*)fixUpPtr
));
7543 parser
.findTargetFromAddressAndSectionNum(contentValue
, reloc
->r_symbolnum(), stringTarget
);
7545 assert(stringTarget
.atom
!= NULL
);
7546 assert(stringTarget
.atom
->contentType() == ld::Atom::typeCString
);
7547 const char* baseClassName
= (char*)stringTarget
.atom
->rawContentPointer();
7548 char* objcClassName
= new char[strlen(baseClassName
) + 20];
7549 strcpy(objcClassName
, ".objc_class_name_");
7550 strcat(objcClassName
, baseClassName
);
7552 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindSetTargetAddress
, false, objcClassName
);
7555 return PointerToCStringSection
<x86
>::addRelocFixup(parser
, reloc
);
7558 #if SUPPORT_ARCH_arm64
7560 void Section
<arm64
>::addLOH(class Parser
<arm64
>& parser
, int kind
, int count
, const uint64_t addrs
[]) {
7562 case LOH_ARM64_ADRP_ADRP
:
7563 case LOH_ARM64_ADRP_LDR
:
7564 case LOH_ARM64_ADRP_ADD
:
7565 case LOH_ARM64_ADRP_LDR_GOT
:
7567 warning("arm64 Linker Optimiztion Hint %d has wrong number of arguments", kind
);
7569 case LOH_ARM64_ADRP_ADD_LDR
:
7570 case LOH_ARM64_ADRP_LDR_GOT_LDR
:
7571 case LOH_ARM64_ADRP_ADD_STR
:
7572 case LOH_ARM64_ADRP_LDR_GOT_STR
:
7574 warning("arm64 Linker Optimiztion Hint %d has wrong number of arguments", kind
);
7577 // pick lowest address in tuple for use as offsetInAtom
7578 uint64_t lowestAddress
= addrs
[0];
7579 for(int i
=1; i
< count
; ++i
) {
7580 if ( addrs
[i
] < lowestAddress
)
7581 lowestAddress
= addrs
[i
];
7583 // verify all other address are in same atom
7584 Atom
<arm64
>* inAtom
= parser
.findAtomByAddress(lowestAddress
);
7585 const uint64_t atomStartAddr
= inAtom
->objectAddress();
7586 const uint64_t atomEndAddr
= atomStartAddr
+ inAtom
->size();
7587 for(int i
=0; i
< count
; ++i
) {
7588 if ( (addrs
[i
] < atomStartAddr
) || (addrs
[i
] >= atomEndAddr
) ) {
7589 warning("arm64 Linker Optimiztion Hint addresses are not in same atom: 0x%08llX and 0x%08llX",
7590 lowestAddress
, addrs
[i
]);
7591 return; // skip this LOH
7593 if ( (addrs
[i
] & 0x3) != 0 ) {
7594 warning("arm64 Linker Optimiztion Hint address is not 4-byte aligned: 0x%08llX", addrs
[i
]);
7595 return; // skip this LOH
7597 if ( (addrs
[i
] - lowestAddress
) > 0xFFFF ) {
7598 if ( parser
.verboseOptimizationHints() ) {
7599 warning("arm64 Linker Optimiztion Hint addresses are too far apart: 0x%08llX and 0x%08llX",
7600 lowestAddress
, addrs
[i
]);
7602 return; // skip this LOH
7606 // encoded kind, count, and address deltas in 64-bit addend
7607 ld::Fixup::LOH_arm64 extra
;
7609 extra
.info
.kind
= kind
;
7610 extra
.info
.count
= count
-1;
7611 extra
.info
.delta1
= (addrs
[0] - lowestAddress
) >> 2;
7612 extra
.info
.delta2
= (count
> 1) ? ((addrs
[1] - lowestAddress
) >> 2) : 0;
7613 extra
.info
.delta3
= (count
> 2) ? ((addrs
[2] - lowestAddress
) >> 2) : 0;
7614 extra
.info
.delta4
= (count
> 3) ? ((addrs
[3] - lowestAddress
) >> 2) : 0;
7615 typename Parser
<arm64
>::SourceLocation
src(inAtom
, lowestAddress
- inAtom
->objectAddress());
7616 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindLinkerOptimizationHint
, extra
.addend
);
7621 template <typename A
>
7622 void Section
<A
>::addLOH(class Parser
<A
>& parser
, int kind
, int count
, const uint64_t addrs
[]) {
7626 template <typename A
>
7627 void Section
<A
>::makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&)
7629 const macho_section
<P
>* sect
= this->machoSection();
7630 if ( sect
->reloff() + (sect
->nreloc() * sizeof(macho_relocation_info
<P
>)) > parser
.fileLength() )
7631 throwf("relocations for section %s/%s extends beyond end of file,", sect
->segname(), Section
<A
>::makeSectionName(sect
) );
7632 const macho_relocation_info
<P
>* relocs
= (macho_relocation_info
<P
>*)(file().fileContent() + sect
->reloff());
7633 const uint32_t relocCount
= sect
->nreloc();
7634 for (uint32_t r
= 0; r
< relocCount
; ++r
) {
7636 if ( this->addRelocFixup(parser
, &relocs
[r
]) )
7639 catch (const char* msg
) {
7640 throwf("in section %s,%s reloc %u: %s", sect
->segname(), Section
<A
>::makeSectionName(sect
), r
, msg
);
7644 // add follow-on fixups if .o file is missing .subsections_via_symbols
7645 if ( this->addFollowOnFixups() ) {
7646 Atom
<A
>* end
= &_endAtoms
[-1];
7647 for(Atom
<A
>* p
= _beginAtoms
; p
< end
; ++p
) {
7648 typename Parser
<A
>::SourceLocation
src(p
, 0);
7649 Atom
<A
>* nextAtom
= &p
[1];
7650 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindNoneFollowOn
, nextAtom
);
7653 else if ( this->type() == ld::Section::typeCode
) {
7654 // if FDE broke text not at a symbol, use followOn to keep code together
7655 Atom
<A
>* end
= &_endAtoms
[-1];
7656 for(Atom
<A
>* p
= _beginAtoms
; p
< end
; ++p
) {
7657 typename Parser
<A
>::SourceLocation
src(p
, 0);
7658 Atom
<A
>* nextAtom
= &p
[1];
7659 if ( (p
->symbolTableInclusion() == ld::Atom::symbolTableIn
) && (nextAtom
->symbolTableInclusion() == ld::Atom::symbolTableNotIn
) ) {
7660 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindNoneFollowOn
, nextAtom
);
7664 if ( !this->_altEntries
.empty() && !this->addFollowOnFixups() ) {
7665 if ( _altEntries
.count(_beginAtoms
) != 0 )
7666 warning("N_ALT_ENTRY bit set on first atom in section %s/%s", sect
->segname(), Section
<A
>::makeSectionName(sect
));
7668 Atom
<A
>* end
= &_endAtoms
[-1];
7669 for(Atom
<A
>* p
= _beginAtoms
; p
< end
; ++p
) {
7670 Atom
<A
>* nextAtom
= &p
[1];
7671 // <rdar://problem/22960070> support alt_entry aliases (alias process already added followOn, don't repeat)
7672 if ( (_altEntries
.count(nextAtom
) != 0) && (p
->_objAddress
!= nextAtom
->_objAddress
) ) {
7673 typename Parser
<A
>::SourceLocation
src(p
, 0);
7674 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindNoneFollowOn
, nextAtom
);
7675 typename Parser
<A
>::SourceLocation
src2(nextAtom
, 0);
7676 parser
.addFixup(src2
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinate
, p
);
7681 // <rdar://problem/9218847> track data-in-code
7682 if ( parser
.hasDataInCodeLabels() && (this->type() == ld::Section::typeCode
) ) {
7683 for (uint32_t i
=0; i
< parser
.symbolCount(); ++i
) {
7684 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(i
);
7686 if ( (sym
.n_type() & N_STAB
) != 0 )
7688 // ignore non-definitions
7689 if ( (sym
.n_type() & N_TYPE
) != N_SECT
)
7692 // 'L' labels do not denote atom breaks
7693 const char* symbolName
= parser
.nameFromSymbol(sym
);
7694 if ( symbolName
[0] == 'L' ) {
7695 if ( strncmp(symbolName
, "L$start$", 8) == 0 ) {
7696 ld::Fixup::Kind kind
= ld::Fixup::kindNone
;
7697 if ( strncmp(&symbolName
[8], "data$", 5) == 0 )
7698 kind
= ld::Fixup::kindDataInCodeStartData
;
7699 else if ( strncmp(&symbolName
[8], "code$", 5) == 0 )
7700 kind
= ld::Fixup::kindDataInCodeEnd
;
7701 else if ( strncmp(&symbolName
[8], "jt8$", 4) == 0 )
7702 kind
= ld::Fixup::kindDataInCodeStartJT8
;
7703 else if ( strncmp(&symbolName
[8], "jt16$", 4) == 0 )
7704 kind
= ld::Fixup::kindDataInCodeStartJT16
;
7705 else if ( strncmp(&symbolName
[8], "jt32$", 4) == 0 )
7706 kind
= ld::Fixup::kindDataInCodeStartJT32
;
7707 else if ( strncmp(&symbolName
[8], "jta32$", 4) == 0 )
7708 kind
= ld::Fixup::kindDataInCodeStartJTA32
;
7710 warning("unknown L$start$ label %s in file %s", symbolName
, this->file().path());
7711 if ( kind
!= ld::Fixup::kindNone
) {
7712 Atom
<A
>* inAtom
= parser
.findAtomByAddress(sym
.n_value());
7713 typename Parser
<A
>::SourceLocation
src(inAtom
, sym
.n_value() - inAtom
->objectAddress());
7714 parser
.addFixup(src
, ld::Fixup::k1of1
, kind
);
7721 // <rdar://problem/11150575> Handle LC_DATA_IN_CODE in object files
7722 if ( this->type() == ld::Section::typeCode
) {
7723 const pint_t startAddr
= this->_machOSection
->addr();
7724 const pint_t endAddr
= startAddr
+ this->_machOSection
->size();
7725 for ( const macho_data_in_code_entry
<P
>* p
= parser
.dataInCodeStart(); p
!= parser
.dataInCodeEnd(); ++p
) {
7726 if ( (p
->offset() >= startAddr
) && (p
->offset() < endAddr
) ) {
7727 ld::Fixup::Kind kind
= ld::Fixup::kindNone
;
7728 switch ( p
->kind() ) {
7729 case DICE_KIND_DATA
:
7730 kind
= ld::Fixup::kindDataInCodeStartData
;
7732 case DICE_KIND_JUMP_TABLE8
:
7733 kind
= ld::Fixup::kindDataInCodeStartJT8
;
7735 case DICE_KIND_JUMP_TABLE16
:
7736 kind
= ld::Fixup::kindDataInCodeStartJT16
;
7738 case DICE_KIND_JUMP_TABLE32
:
7739 kind
= ld::Fixup::kindDataInCodeStartJT32
;
7741 case DICE_KIND_ABS_JUMP_TABLE32
:
7742 kind
= ld::Fixup::kindDataInCodeStartJTA32
;
7745 kind
= ld::Fixup::kindDataInCodeStartData
;
7746 warning("uknown LC_DATA_IN_CODE kind (%d) at offset 0x%08X", p
->kind(), p
->offset());
7749 Atom
<A
>* inAtom
= parser
.findAtomByAddress(p
->offset());
7750 typename Parser
<A
>::SourceLocation
srcStart(inAtom
, p
->offset() - inAtom
->objectAddress());
7751 parser
.addFixup(srcStart
, ld::Fixup::k1of1
, kind
);
7752 typename Parser
<A
>::SourceLocation
srcEnd(inAtom
, p
->offset() + p
->length() - inAtom
->objectAddress());
7753 parser
.addFixup(srcEnd
, ld::Fixup::k1of1
, ld::Fixup::kindDataInCodeEnd
);
7758 // <rdar://problem/11945700> convert linker optimization hints into internal format
7759 if ( this->type() == ld::Section::typeCode
&& parser
.hasOptimizationHints() ) {
7760 const pint_t startAddr
= this->_machOSection
->addr();
7761 const pint_t endAddr
= startAddr
+ this->_machOSection
->size();
7762 for (const uint8_t* p
= parser
.optimizationHintsStart(); p
< parser
.optimizationHintsEnd(); ) {
7764 int32_t kind
= read_uleb128(&p
, parser
.optimizationHintsEnd());
7765 if ( kind
== 0 ) // padding at end of loh buffer
7768 warning("malformed uleb128 kind in LC_LINKER_OPTIMIZATION_HINTS");
7771 int32_t count
= read_uleb128(&p
, parser
.optimizationHintsEnd());
7772 if ( count
== -1 ) {
7773 warning("malformed uleb128 count in LC_LINKER_OPTIMIZATION_HINTS");
7777 warning("address count > 3 in LC_LINKER_OPTIMIZATION_HINTS");
7780 for (int32_t i
=0; i
< count
; ++i
) {
7781 addrs
[i
] = read_uleb128(&p
, parser
.optimizationHintsEnd());
7783 if ( (startAddr
<= addrs
[0]) && (addrs
[0] < endAddr
) ) {
7784 this->addLOH(parser
, kind
, count
, addrs
);
7785 //fprintf(stderr, "kind=%d", kind);
7786 //for (int32_t i=0; i < count; ++i) {
7787 // fprintf(stderr, ", addr=0x%08llX", addrs[i]);
7789 //fprintf(stderr, "\n");
7795 // add follow-on fixups for aliases
7796 if ( _hasAliases
) {
7797 for(Atom
<A
>* p
= _beginAtoms
; p
< _endAtoms
; ++p
) {
7798 if ( p
->isAlias() && ! this->addFollowOnFixups() ) {
7799 Atom
<A
>* targetOfAlias
= &p
[1];
7800 assert(p
< &_endAtoms
[-1]);
7801 assert(p
->_objAddress
== targetOfAlias
->_objAddress
);
7802 typename Parser
<A
>::SourceLocation
src(p
, 0);
7803 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindNoneFollowOn
, targetOfAlias
);
7812 // main function used by linker to instantiate ld::Files
7814 ld::relocatable::File
* parse(const uint8_t* fileContent
, uint64_t fileLength
,
7815 const char* path
, time_t modTime
, ld::File::Ordinal ordinal
, const ParserOptions
& opts
)
7817 switch ( opts
.architecture
) {
7818 #if SUPPORT_ARCH_x86_64
7819 case CPU_TYPE_X86_64
:
7820 if ( mach_o::relocatable::Parser
<x86_64
>::validFile(fileContent
) )
7821 return mach_o::relocatable::Parser
<x86_64
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
);
7824 #if SUPPORT_ARCH_i386
7826 if ( mach_o::relocatable::Parser
<x86
>::validFile(fileContent
) )
7827 return mach_o::relocatable::Parser
<x86
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
);
7830 #if SUPPORT_ARCH_arm_any
7832 if ( mach_o::relocatable::Parser
<arm
>::validFile(fileContent
, opts
.objSubtypeMustMatch
, opts
.subType
) )
7833 return mach_o::relocatable::Parser
<arm
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
);
7836 #if SUPPORT_ARCH_arm64
7837 case CPU_TYPE_ARM64
:
7838 if ( mach_o::relocatable::Parser
<arm64
>::validFile(fileContent
, opts
.objSubtypeMustMatch
, opts
.subType
) )
7839 return mach_o::relocatable::Parser
<arm64
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
);
7847 // used by archive reader to validate member object file
7849 bool isObjectFile(const uint8_t* fileContent
, uint64_t fileLength
, const ParserOptions
& opts
)
7851 switch ( opts
.architecture
) {
7852 case CPU_TYPE_X86_64
:
7853 return ( mach_o::relocatable::Parser
<x86_64
>::validFile(fileContent
) );
7855 return ( mach_o::relocatable::Parser
<x86
>::validFile(fileContent
) );
7857 return ( mach_o::relocatable::Parser
<arm
>::validFile(fileContent
, opts
.objSubtypeMustMatch
, opts
.subType
) );
7858 case CPU_TYPE_ARM64
:
7859 return ( mach_o::relocatable::Parser
<arm64
>::validFile(fileContent
, opts
.objSubtypeMustMatch
, opts
.subType
) );
7865 // used by linker to infer architecture when no -arch is on command line
7867 bool isObjectFile(const uint8_t* fileContent
, cpu_type_t
* result
, cpu_subtype_t
* subResult
, Options::Platform
* platform
)
7869 if ( mach_o::relocatable::Parser
<x86_64
>::validFile(fileContent
) ) {
7870 *result
= CPU_TYPE_X86_64
;
7871 const macho_header
<Pointer64
<LittleEndian
> >* header
= (const macho_header
<Pointer64
<LittleEndian
> >*)fileContent
;
7872 *subResult
= header
->cpusubtype();
7873 *platform
= Parser
<x86_64
>::findPlatform(header
);
7876 if ( mach_o::relocatable::Parser
<x86
>::validFile(fileContent
) ) {
7877 const macho_header
<Pointer32
<LittleEndian
> >* header
= (const macho_header
<Pointer32
<LittleEndian
> >*)fileContent
;
7878 *result
= CPU_TYPE_I386
;
7879 *subResult
= CPU_SUBTYPE_X86_ALL
;
7880 *platform
= Parser
<x86
>::findPlatform(header
);
7883 if ( mach_o::relocatable::Parser
<arm
>::validFile(fileContent
, false, 0) ) {
7884 const macho_header
<Pointer32
<LittleEndian
> >* header
= (const macho_header
<Pointer32
<LittleEndian
> >*)fileContent
;
7885 *result
= CPU_TYPE_ARM
;
7886 *subResult
= header
->cpusubtype();
7887 *platform
= Parser
<arm
>::findPlatform(header
);
7890 if ( mach_o::relocatable::Parser
<arm64
>::validFile(fileContent
, false, 0) ) {
7891 const macho_header
<Pointer64
<LittleEndian
> >* header
= (const macho_header
<Pointer64
<LittleEndian
> >*)fileContent
;
7892 *result
= CPU_TYPE_ARM64
;
7893 *subResult
= CPU_SUBTYPE_ARM64_ALL
;
7894 *platform
= Parser
<arm64
>::findPlatform(header
);
7901 // used by linker is error messages to describe bad .o file
7903 const char* archName(const uint8_t* fileContent
)
7905 if ( mach_o::relocatable::Parser
<x86_64
>::validFile(fileContent
) ) {
7906 return mach_o::relocatable::Parser
<x86_64
>::fileKind(fileContent
);
7908 if ( mach_o::relocatable::Parser
<x86
>::validFile(fileContent
) ) {
7909 return mach_o::relocatable::Parser
<x86
>::fileKind(fileContent
);
7911 if ( mach_o::relocatable::Parser
<arm
>::validFile(fileContent
, false, 0) ) {
7912 return mach_o::relocatable::Parser
<arm
>::fileKind(fileContent
);
7918 // Used by archive reader when -ObjC option is specified
7920 bool hasObjC2Categories(const uint8_t* fileContent
)
7922 if ( mach_o::relocatable::Parser
<x86_64
>::validFile(fileContent
) ) {
7923 return mach_o::relocatable::Parser
<x86_64
>::hasObjC2Categories(fileContent
);
7925 else if ( mach_o::relocatable::Parser
<arm
>::validFile(fileContent
, false, 0) ) {
7926 return mach_o::relocatable::Parser
<arm
>::hasObjC2Categories(fileContent
);
7928 else if ( mach_o::relocatable::Parser
<x86
>::validFile(fileContent
, false, 0) ) {
7929 return mach_o::relocatable::Parser
<x86
>::hasObjC2Categories(fileContent
);
7931 #if SUPPORT_ARCH_arm64
7932 else if ( mach_o::relocatable::Parser
<arm64
>::validFile(fileContent
, false, 0) ) {
7933 return mach_o::relocatable::Parser
<arm64
>::hasObjC2Categories(fileContent
);
7940 // Used by archive reader when -ObjC option is specified
7942 bool hasObjC1Categories(const uint8_t* fileContent
)
7944 if ( mach_o::relocatable::Parser
<x86
>::validFile(fileContent
, false, 0) ) {
7945 return mach_o::relocatable::Parser
<x86
>::hasObjC1Categories(fileContent
);
7951 // Used by bitcode obfuscator to get a list of non local symbols from object file
7953 bool getNonLocalSymbols(const uint8_t* fileContent
, std::vector
<const char*> &syms
)
7955 if ( mach_o::relocatable::Parser
<x86_64
>::validFile(fileContent
) ) {
7956 return mach_o::relocatable::Parser
<x86_64
>::getNonLocalSymbols(fileContent
, syms
);
7958 else if ( mach_o::relocatable::Parser
<arm
>::validFile(fileContent
, false, 0) ) {
7959 return mach_o::relocatable::Parser
<arm
>::getNonLocalSymbols(fileContent
, syms
);
7961 else if ( mach_o::relocatable::Parser
<x86
>::validFile(fileContent
, false, 0) ) {
7962 return mach_o::relocatable::Parser
<x86
>::getNonLocalSymbols(fileContent
, syms
);
7964 else if ( mach_o::relocatable::Parser
<arm64
>::validFile(fileContent
, false, 0) ) {
7965 return mach_o::relocatable::Parser
<arm64
>::getNonLocalSymbols(fileContent
, syms
);
7972 } // namespace relocatable
7973 } // namespace mach_o