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 _srcKind(kSourceUnknown
) {}
92 // overrides of ld::File
93 virtual bool forEachAtom(ld::File::AtomHandler
&) const;
94 virtual bool justInTimeforEachAtom(const char* name
, ld::File::AtomHandler
&) const
96 virtual uint32_t minOSVersion() const { return _minOSVersion
; }
97 virtual uint32_t platformLoadCommand() const { return _platform
; }
99 // overrides of ld::relocatable::File
100 virtual ObjcConstraint
objCConstraint() const { return _objConstraint
; }
101 virtual uint32_t cpuSubType() const { return _cpuSubType
; }
102 virtual DebugInfoKind
debugInfo() const { return _debugInfoKind
; }
103 virtual const std::vector
<ld::relocatable::File::Stab
>* stabs() const { return &_stabs
; }
104 virtual bool canScatterAtoms() const { return _canScatterAtoms
; }
105 virtual const char* translationUnitSource() const;
106 virtual LinkerOptionsList
* linkerOptions() const { return &_linkerOptions
; }
107 virtual uint8_t swiftVersion() const { return _swiftVersion
; }
108 virtual ld::Bitcode
* getBitcode() const { return _bitcode
.get(); }
109 virtual SourceKind
sourceKind() const { return _srcKind
; }
111 const uint8_t* fileContent() { return _fileContent
; }
113 friend class Atom
<A
>;
114 friend class Section
<A
>;
115 friend class Parser
<A
>;
116 friend class CFISection
<A
>::OAS
;
118 typedef typename
A::P P
;
120 const uint8_t* _fileContent
;
121 Section
<A
>** _sectionsArray
;
122 uint8_t* _atomsArray
;
123 uint8_t* _aliasAtomsArray
;
124 uint32_t _sectionsArrayCount
;
125 uint32_t _atomsArrayCount
;
126 uint32_t _aliasAtomsArrayCount
;
127 std::vector
<ld::Fixup
> _fixups
;
128 std::vector
<ld::Atom::UnwindInfo
> _unwindInfos
;
129 std::vector
<ld::Atom::LineInfo
> _lineInfos
;
130 std::vector
<ld::relocatable::File::Stab
>_stabs
;
131 ld::relocatable::File::DebugInfoKind _debugInfoKind
;
132 const char* _dwarfTranslationUnitPath
;
133 const macho_section
<P
>* _dwarfDebugInfoSect
;
134 const macho_section
<P
>* _dwarfDebugAbbrevSect
;
135 const macho_section
<P
>* _dwarfDebugLineSect
;
136 const macho_section
<P
>* _dwarfDebugStringSect
;
137 ld::File::ObjcConstraint _objConstraint
;
138 uint8_t _swiftVersion
;
139 uint32_t _cpuSubType
;
140 uint32_t _minOSVersion
;
142 bool _canScatterAtoms
;
143 std::vector
<std::vector
<const char*> > _linkerOptions
;
144 std::unique_ptr
<ld::Bitcode
> _bitcode
;
149 template <typename A
>
150 class Section
: public ld::Section
153 typedef typename
A::P::uint_t pint_t
;
154 typedef typename
A::P P
;
155 typedef typename
A::P::E E
;
157 virtual ~Section() { }
158 class File
<A
>& file() const { return _file
; }
159 const macho_section
<P
>* machoSection() const { return _machOSection
; }
160 uint32_t sectionNum(class Parser
<A
>&) const;
161 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
);
162 virtual ld::Atom::ContentType
contentType() { return ld::Atom::typeUnclassified
; }
163 virtual bool dontDeadStrip() { return (this->_machOSection
->flags() & S_ATTR_NO_DEAD_STRIP
); }
164 virtual bool dontDeadStripIfReferencesLive() { return ( (this->_machOSection
!= NULL
) && (this->_machOSection
->flags() & S_ATTR_LIVE_SUPPORT
) ); }
165 virtual Atom
<A
>* findAtomByAddress(pint_t addr
) { return this->findContentAtomByAddress(addr
, this->_beginAtoms
, this->_endAtoms
); }
166 virtual bool addFollowOnFixups() const { return ! _file
.canScatterAtoms(); }
167 virtual uint32_t appendAtoms(class Parser
<A
>& parser
, uint8_t* buffer
,
168 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
169 const struct Parser
<A
>::CFI_CU_InfoArrays
&) = 0;
170 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
,
171 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
172 const struct Parser
<A
>::CFI_CU_InfoArrays
&) = 0;
173 virtual void makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
174 virtual bool addRelocFixup(class Parser
<A
>& parser
, const macho_relocation_info
<P
>*);
175 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const { return 0; }
176 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
177 const ld::IndirectBindingTable
& ind
) const { return false; }
178 virtual bool ignoreLabel(const char* label
) const { return false; }
179 static const char* makeSectionName(const macho_section
<typename
A::P
>* s
);
182 Section(File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
183 : ld::Section(makeSegmentName(s
), makeSectionName(s
), sectionType(s
)),
184 _file(f
), _machOSection(s
), _beginAtoms(NULL
), _endAtoms(NULL
), _hasAliases(false) { }
185 Section(File
<A
>& f
, const char* segName
, const char* sectName
, ld::Section::Type t
, bool hidden
=false)
186 : ld::Section(segName
, sectName
, t
, hidden
), _file(f
), _machOSection(NULL
),
187 _beginAtoms(NULL
), _endAtoms(NULL
), _hasAliases(false) { }
190 Atom
<A
>* findContentAtomByAddress(pint_t addr
, class Atom
<A
>* start
, class Atom
<A
>* end
);
191 uint32_t x86_64PcRelOffset(uint8_t r_type
);
192 void addLOH(class Parser
<A
>& parser
, int kind
, int count
, const uint64_t addrs
[]);
193 static const char* makeSegmentName(const macho_section
<typename
A::P
>* s
);
194 static bool readable(const macho_section
<typename
A::P
>* s
);
195 static bool writable(const macho_section
<typename
A::P
>* s
);
196 static bool exectuable(const macho_section
<typename
A::P
>* s
);
197 static ld::Section::Type
sectionType(const macho_section
<typename
A::P
>* s
);
200 const macho_section
<P
>* _machOSection
;
201 class Atom
<A
>* _beginAtoms
;
202 class Atom
<A
>* _endAtoms
;
204 std::set
<const class Atom
<A
>*> _altEntries
;
208 template <typename A
>
209 class CFISection
: public Section
<A
>
212 CFISection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
213 : Section
<A
>(f
, s
) { }
214 uint32_t cfiCount(Parser
<A
>& parser
);
216 virtual ld::Atom::ContentType
contentType() { return ld::Atom::typeCFI
; }
217 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
218 virtual uint32_t appendAtoms(class Parser
<A
>& parser
, uint8_t* buffer
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
219 virtual void makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
220 virtual bool addFollowOnFixups() const { return false; }
224 /// ObjectFileAddressSpace is used as a template parameter to UnwindCursor for parsing
225 /// dwarf CFI information in an object file.
230 typedef typename
A::P::uint_t pint_t
;
231 typedef typename
A::P P
;
232 typedef typename
A::P::E E
;
233 typedef typename
A::P::uint_t sint_t
;
235 OAS(CFISection
<A
>& ehFrameSection
, const uint8_t* ehFrameBuffer
) :
236 _ehFrameSection(ehFrameSection
),
237 _ehFrameContent(ehFrameBuffer
),
238 _ehFrameStartAddr(ehFrameSection
.machoSection()->addr()),
239 _ehFrameEndAddr(ehFrameSection
.machoSection()->addr()+ehFrameSection
.machoSection()->size()) {}
241 uint8_t get8(pint_t addr
) { return *((uint8_t*)mappedAddress(addr
)); }
242 uint16_t get16(pint_t addr
) { return E::get16(*((uint16_t*)mappedAddress(addr
))); }
243 uint32_t get32(pint_t addr
) { return E::get32(*((uint32_t*)mappedAddress(addr
))); }
244 uint64_t get64(pint_t addr
) { return E::get64(*((uint64_t*)mappedAddress(addr
))); }
245 pint_t
getP(pint_t addr
) { return P::getP(*((pint_t
*)mappedAddress(addr
))); }
246 uint64_t getULEB128(pint_t
& addr
, pint_t end
);
247 int64_t getSLEB128(pint_t
& addr
, pint_t end
);
248 pint_t
getEncodedP(pint_t
& addr
, pint_t end
, uint8_t encoding
);
250 const void* mappedAddress(pint_t addr
);
252 CFISection
<A
>& _ehFrameSection
;
253 const uint8_t* _ehFrameContent
;
254 pint_t _ehFrameStartAddr
;
255 pint_t _ehFrameEndAddr
;
259 typedef typename
A::P::uint_t pint_t
;
260 typedef libunwind::CFI_Atom_Info
<OAS
> CFI_Atom_Info
;
262 void cfiParse(class Parser
<A
>& parser
, uint8_t* buffer
, CFI_Atom_Info cfiArray
[], uint32_t& cfiCount
, const pint_t cuStarts
[], uint32_t cuCount
);
263 bool needsRelocating();
265 static bool bigEndian();
267 void addCiePersonalityFixups(class Parser
<A
>& parser
, const CFI_Atom_Info
* cieInfo
);
268 static void warnFunc(void* ref
, uint64_t funcAddr
, const char* msg
);
272 template <typename A
>
273 class CUSection
: public Section
<A
>
276 CUSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
277 : Section
<A
>(f
, s
) { }
279 typedef typename
A::P::uint_t pint_t
;
280 typedef typename
A::P P
;
281 typedef typename
A::P::E E
;
283 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, const struct Parser
<A
>::CFI_CU_InfoArrays
&) { return 0; }
284 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; }
285 virtual void makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
286 virtual bool addFollowOnFixups() const { return false; }
289 pint_t functionStartAddress
;
290 uint32_t functionSymbolIndex
;
291 uint32_t rangeLength
;
292 uint32_t compactUnwindInfo
;
293 const char* personality
;
300 void parse(class Parser
<A
>& parser
, uint32_t cnt
, Info array
[]);
301 static bool encodingMeansUseDwarf(compact_unwind_encoding_t enc
);
306 const char* personalityName(class Parser
<A
>& parser
, const macho_relocation_info
<P
>* reloc
);
308 static int infoSorter(const void* l
, const void* r
);
313 template <typename A
>
314 class TentativeDefinitionSection
: public Section
<A
>
317 TentativeDefinitionSection(Parser
<A
>& parser
, File
<A
>& f
)
318 : Section
<A
>(f
, "__DATA", "__comm/tent", ld::Section::typeTentativeDefs
) {}
320 virtual ld::Atom::ContentType
contentType() { return ld::Atom::typeZeroFill
; }
321 virtual bool addFollowOnFixups() const { return false; }
322 virtual Atom
<A
>* findAtomByAddress(typename
A::P::uint_t addr
) { throw "TentativeDefinitionSection::findAtomByAddress() should never be called"; }
323 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
324 const struct Parser
<A
>::CFI_CU_InfoArrays
&);
325 virtual uint32_t appendAtoms(class Parser
<A
>& parser
, uint8_t* buffer
,
326 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
327 const struct Parser
<A
>::CFI_CU_InfoArrays
&);
328 virtual void makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&) {}
330 typedef typename
A::P::uint_t pint_t
;
331 typedef typename
A::P P
;
335 template <typename A
>
336 class AbsoluteSymbolSection
: public Section
<A
>
339 AbsoluteSymbolSection(Parser
<A
>& parser
, File
<A
>& f
)
340 : Section
<A
>(f
, "__DATA", "__abs", ld::Section::typeAbsoluteSymbols
, true) {}
342 virtual ld::Atom::ContentType
contentType() { return ld::Atom::typeUnclassified
; }
343 virtual bool dontDeadStrip() { return false; }
344 virtual ld::Atom::Alignment
alignmentForAddress(typename
A::P::uint_t addr
) { return ld::Atom::Alignment(0); }
345 virtual bool addFollowOnFixups() const { return false; }
346 virtual Atom
<A
>* findAtomByAddress(typename
A::P::uint_t addr
) { throw "AbsoluteSymbolSection::findAtomByAddress() should never be called"; }
347 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
348 const struct Parser
<A
>::CFI_CU_InfoArrays
&);
349 virtual uint32_t appendAtoms(class Parser
<A
>& parser
, uint8_t* buffer
,
350 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
351 const struct Parser
<A
>::CFI_CU_InfoArrays
&);
352 virtual void makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&) {}
353 virtual Atom
<A
>* findAbsAtomForValue(typename
A::P::uint_t
);
356 typedef typename
A::P::uint_t pint_t
;
357 typedef typename
A::P P
;
361 template <typename A
>
362 class SymboledSection
: public Section
<A
>
365 SymboledSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
);
366 virtual ld::Atom::ContentType
contentType() { return _type
; }
367 virtual bool dontDeadStrip();
368 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
369 const struct Parser
<A
>::CFI_CU_InfoArrays
&);
370 virtual uint32_t appendAtoms(class Parser
<A
>& parser
, uint8_t* buffer
,
371 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
372 const struct Parser
<A
>::CFI_CU_InfoArrays
&);
374 typedef typename
A::P::uint_t pint_t
;
375 typedef typename
A::P P
;
377 ld::Atom::ContentType _type
;
381 template <typename A
>
382 class TLVDefsSection
: public SymboledSection
<A
>
385 TLVDefsSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
) :
386 SymboledSection
<A
>(parser
, f
, s
) { }
393 template <typename A
>
394 class ImplicitSizeSection
: public Section
<A
>
397 ImplicitSizeSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
398 : Section
<A
>(f
, s
) { }
399 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
400 virtual uint32_t appendAtoms(class Parser
<A
>& parser
, uint8_t* buffer
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
402 typedef typename
A::P::uint_t pint_t
;
403 typedef typename
A::P P
;
405 virtual bool addFollowOnFixups() const { return false; }
406 virtual const char* unlabeledAtomName(Parser
<A
>& parser
, pint_t addr
) = 0;
407 virtual ld::Atom::SymbolTableInclusion
symbolTableInclusion();
408 virtual pint_t
elementSizeAtAddress(pint_t addr
) = 0;
409 virtual ld::Atom::Scope
scopeAtAddress(Parser
<A
>& parser
, pint_t addr
) { return ld::Atom::scopeLinkageUnit
; }
410 virtual bool useElementAt(Parser
<A
>& parser
,
411 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, pint_t addr
) = 0;
412 virtual ld::Atom::Definition
definition() { return ld::Atom::definitionRegular
; }
413 virtual ld::Atom::Combine
combine(Parser
<A
>& parser
, pint_t addr
) = 0;
414 virtual bool ignoreLabel(const char* label
) const { return (label
[0] == 'L'); }
418 template <typename A
>
419 class FixedSizeSection
: public ImplicitSizeSection
<A
>
422 FixedSizeSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
423 : ImplicitSizeSection
<A
>(parser
, f
, s
) { }
425 typedef typename
A::P::uint_t pint_t
;
426 typedef typename
A::P P
;
427 typedef typename
A::P::E E
;
429 virtual bool useElementAt(Parser
<A
>& parser
,
430 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, pint_t addr
)
435 template <typename A
>
436 class Literal4Section
: public FixedSizeSection
<A
>
439 Literal4Section(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
440 : FixedSizeSection
<A
>(parser
, f
, s
) {}
442 typedef typename
A::P::uint_t pint_t
;
443 typedef typename
A::P P
;
445 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(2); }
446 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "4-byte-literal"; }
447 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return 4; }
448 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndContent
; }
449 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
450 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
451 const ld::IndirectBindingTable
& ind
) const;
452 virtual bool ignoreLabel(const char* label
) const;
455 template <typename A
>
456 class Literal8Section
: public FixedSizeSection
<A
>
459 Literal8Section(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
460 : FixedSizeSection
<A
>(parser
, f
, s
) {}
462 typedef typename
A::P::uint_t pint_t
;
463 typedef typename
A::P P
;
465 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(3); }
466 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "8-byte-literal"; }
467 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return 8; }
468 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndContent
; }
469 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
470 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
471 const ld::IndirectBindingTable
& ind
) const;
472 virtual bool ignoreLabel(const char* label
) const;
475 template <typename A
>
476 class Literal16Section
: public FixedSizeSection
<A
>
479 Literal16Section(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
480 : FixedSizeSection
<A
>(parser
, f
, s
) {}
482 typedef typename
A::P::uint_t pint_t
;
483 typedef typename
A::P P
;
485 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(4); }
486 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "16-byte-literal"; }
487 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return 16; }
488 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndContent
; }
489 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
490 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
491 const ld::IndirectBindingTable
& ind
) const;
492 virtual bool ignoreLabel(const char* label
) const;
496 template <typename A
>
497 class NonLazyPointerSection
: public FixedSizeSection
<A
>
500 NonLazyPointerSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
501 : FixedSizeSection
<A
>(parser
, f
, s
) {}
503 typedef typename
A::P::uint_t pint_t
;
504 typedef typename
A::P P
;
506 virtual void makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
507 virtual ld::Atom::ContentType
contentType() { return ld::Atom::typeNonLazyPointer
; }
508 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(log2(sizeof(pint_t
))); }
509 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "non_lazy_ptr"; }
510 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return sizeof(pint_t
); }
511 virtual ld::Atom::Scope
scopeAtAddress(Parser
<A
>& parser
, pint_t addr
);
512 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
);
513 virtual bool ignoreLabel(const char* label
) const { return true; }
514 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
515 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
516 const ld::IndirectBindingTable
& ind
) const;
519 static const char* targetName(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
);
520 static ld::Fixup::Kind
fixupKind();
523 template <typename A
>
524 class TLVPointerSection
: public FixedSizeSection
<A
>
527 TLVPointerSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
528 : FixedSizeSection
<A
>(parser
, f
, s
) {}
530 typedef typename
A::P::uint_t pint_t
;
531 typedef typename
A::P P
;
533 virtual ld::Atom::ContentType
contentType() { return ld::Atom::typeTLVPointer
; }
534 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(log2(sizeof(pint_t
))); }
535 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "tlv_lazy_ptr"; }
536 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return sizeof(pint_t
); }
537 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
);
538 virtual bool ignoreLabel(const char* label
) const { return true; }
539 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
540 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
541 const ld::IndirectBindingTable
& ind
) const;
544 static const char* targetName(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
, bool* isStatic
);
548 template <typename A
>
549 class CFStringSection
: public FixedSizeSection
<A
>
552 CFStringSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
553 : FixedSizeSection
<A
>(parser
, f
, s
) {}
555 typedef typename
A::P::uint_t pint_t
;
557 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(log2(sizeof(pint_t
))); }
558 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "CFString"; }
559 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return 4*sizeof(pint_t
); }
560 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndReferences
; }
561 virtual bool ignoreLabel(const char* label
) const { return true; }
562 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
563 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
564 const ld::IndirectBindingTable
& ind
) const;
566 enum ContentType
{ contentUTF8
, contentUTF16
, contentUnknown
};
567 static const uint8_t* targetContent(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
,
568 ContentType
* ct
, unsigned int* count
);
572 template <typename A
>
573 class ObjC1ClassSection
: public FixedSizeSection
<A
>
576 ObjC1ClassSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
577 : FixedSizeSection
<A
>(parser
, f
, s
) {}
579 typedef typename
A::P::uint_t pint_t
;
580 typedef typename
A::P P
;
581 typedef typename
A::P::E E
;
583 virtual ld::Atom::Scope
scopeAtAddress(Parser
<A
>& , pint_t
) { return ld::Atom::scopeGlobal
; }
584 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(2); }
585 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
);
586 virtual ld::Atom::SymbolTableInclusion
symbolTableInclusion() { return ld::Atom::symbolTableIn
; }
587 virtual pint_t
elementSizeAtAddress(pint_t addr
);
588 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineNever
; }
589 virtual bool ignoreLabel(const char* label
) const { return true; }
590 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
592 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
593 const ld::IndirectBindingTable
& ind
) const { return false; }
594 virtual bool addRelocFixup(class Parser
<A
>& parser
, const macho_relocation_info
<P
>*);
598 template <typename A
>
599 class ObjC2ClassRefsSection
: public FixedSizeSection
<A
>
602 ObjC2ClassRefsSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
603 : FixedSizeSection
<A
>(parser
, f
, s
) {}
605 typedef typename
A::P::uint_t pint_t
;
607 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(log2(sizeof(pint_t
))); }
608 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "objc-class-ref"; }
609 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return sizeof(pint_t
); }
610 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndReferences
; }
611 virtual bool ignoreLabel(const char* label
) const { return true; }
612 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
613 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
614 const ld::IndirectBindingTable
& ind
) const;
616 const char* targetClassName(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
620 template <typename A
>
621 class ObjC2CategoryListSection
: public FixedSizeSection
<A
>
624 ObjC2CategoryListSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
625 : FixedSizeSection
<A
>(parser
, f
, s
) {}
627 typedef typename
A::P::uint_t pint_t
;
629 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(log2(sizeof(pint_t
))); }
630 virtual ld::Atom::Scope
scopeAtAddress(Parser
<A
>& parser
, pint_t addr
) { return ld::Atom::scopeTranslationUnit
; }
631 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "objc-cat-list"; }
632 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return sizeof(pint_t
); }
633 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineNever
; }
634 virtual bool ignoreLabel(const char* label
) const { return true; }
636 const char* targetClassName(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
640 template <typename A
>
641 class PointerToCStringSection
: public FixedSizeSection
<A
>
644 PointerToCStringSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
645 : FixedSizeSection
<A
>(parser
, f
, s
) {}
647 typedef typename
A::P::uint_t pint_t
;
649 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(log2(sizeof(pint_t
))); }
650 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "pointer-to-literal-cstring"; }
651 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return sizeof(pint_t
); }
652 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndReferences
; }
653 virtual bool ignoreLabel(const char* label
) const { return true; }
654 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
655 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
656 const ld::IndirectBindingTable
& ind
) const;
657 virtual const char* targetCString(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
661 template <typename A
>
662 class Objc1ClassReferences
: public PointerToCStringSection
<A
>
665 Objc1ClassReferences(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
666 : PointerToCStringSection
<A
>(parser
, f
, s
) {}
668 typedef typename
A::P::uint_t pint_t
;
669 typedef typename
A::P P
;
671 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "pointer-to-literal-objc-class-name"; }
672 virtual bool addRelocFixup(class Parser
<A
>& parser
, const macho_relocation_info
<P
>*);
673 virtual const char* targetCString(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
677 template <typename A
>
678 class CStringSection
: public ImplicitSizeSection
<A
>
681 CStringSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
682 : ImplicitSizeSection
<A
>(parser
, f
, s
) {}
684 typedef typename
A::P::uint_t pint_t
;
685 typedef typename
A::P P
;
687 virtual ld::Atom::ContentType
contentType() { return ld::Atom::typeCString
; }
688 virtual Atom
<A
>* findAtomByAddress(pint_t addr
);
689 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "cstring"; }
690 virtual pint_t
elementSizeAtAddress(pint_t addr
);
691 virtual bool ignoreLabel(const char* label
) const;
692 virtual bool useElementAt(Parser
<A
>& parser
,
693 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, pint_t addr
);
694 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndContent
; }
695 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
696 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
697 const ld::IndirectBindingTable
& ind
) const;
702 template <typename A
>
703 class UTF16StringSection
: public SymboledSection
<A
>
706 UTF16StringSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
707 : SymboledSection
<A
>(parser
, f
, s
) {}
709 typedef typename
A::P::uint_t pint_t
;
710 typedef typename
A::P P
;
712 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndContent
; }
713 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
714 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
715 const ld::IndirectBindingTable
& ind
) const;
720 // Atoms in mach-o files
722 template <typename A
>
723 class Atom
: public ld::Atom
726 // overrides of ld::Atom
727 virtual const ld::File
* file() const;
728 virtual const char* translationUnitSource() const
729 { return sect().file().translationUnitSource(); }
730 virtual const char* name() const { return _name
; }
731 virtual uint64_t size() const { return _size
; }
732 virtual uint64_t objectAddress() const { return _objAddress
; }
733 virtual void copyRawContent(uint8_t buffer
[]) const;
734 virtual const uint8_t* rawContentPointer() const { return contentPointer(); }
735 virtual unsigned long contentHash(const ld::IndirectBindingTable
& ind
) const
736 { if ( _hash
== 0 ) _hash
= sect().contentHash(this, ind
); return _hash
; }
737 virtual bool canCoalesceWith(const ld::Atom
& rhs
, const ld::IndirectBindingTable
& ind
) const
738 { return sect().canCoalesceWith(this, rhs
, ind
); }
739 virtual ld::Fixup::iterator
fixupsBegin() const { return &machofile()._fixups
[_fixupsStartIndex
]; }
740 virtual ld::Fixup::iterator
fixupsEnd() const { return &machofile()._fixups
[_fixupsStartIndex
+_fixupsCount
]; }
741 virtual ld::Atom::UnwindInfo::iterator
beginUnwind() const { return &machofile()._unwindInfos
[_unwindInfoStartIndex
]; }
742 virtual ld::Atom::UnwindInfo::iterator
endUnwind() const { return &machofile()._unwindInfos
[_unwindInfoStartIndex
+_unwindInfoCount
]; }
743 virtual ld::Atom::LineInfo::iterator
beginLineInfo() const{ return &machofile()._lineInfos
[_lineInfoStartIndex
]; }
744 virtual ld::Atom::LineInfo::iterator
endLineInfo() const { return &machofile()._lineInfos
[_lineInfoStartIndex
+_lineInfoCount
]; }
745 virtual void setFile(const ld::File
* f
);
749 enum { kFixupStartIndexBits
= 32,
750 kLineInfoStartIndexBits
= 32,
751 kUnwindInfoStartIndexBits
= 24,
752 kFixupCountBits
= 24,
753 kLineInfoCountBits
= 12,
754 kUnwindInfoCountBits
= 4
755 }; // must sum to 128
758 // methods for all atoms from mach-o object file
759 Section
<A
>& sect() const { return (Section
<A
>&)section(); }
760 File
<A
>& machofile() const { return ((Section
<A
>*)(this->_section
))->file(); }
761 void setFixupsRange(uint32_t s
, uint32_t c
);
762 void setUnwindInfoRange(uint32_t s
, uint32_t c
);
763 void extendUnwindInfoRange();
764 void setLineInfoRange(uint32_t s
, uint32_t c
);
765 bool roomForMoreLineInfoCount() { return (_lineInfoCount
< ((1<<kLineInfoCountBits
)-1)); }
766 void incrementLineInfoCount() { assert(roomForMoreLineInfoCount()); ++_lineInfoCount
; }
767 void incrementFixupCount() { if (_fixupsCount
== ((1 << kFixupCountBits
)-1))
768 throwf("too may fixups in %s", name()); ++_fixupsCount
; }
769 const uint8_t* contentPointer() const;
770 uint32_t fixupCount() const { return _fixupsCount
; }
771 void verifyAlignment(const macho_section
<typename
A::P
>&) const;
773 typedef typename
A::P P
;
774 typedef typename
A::P::E E
;
775 typedef typename
A::P::uint_t pint_t
;
776 // constuct via all attributes
777 Atom(Section
<A
>& sct
, const char* nm
, pint_t addr
, uint64_t sz
,
778 ld::Atom::Definition d
, ld::Atom::Combine c
, ld::Atom::Scope s
,
779 ld::Atom::ContentType ct
, ld::Atom::SymbolTableInclusion i
,
780 bool dds
, bool thumb
, bool al
, ld::Atom::Alignment a
)
781 : ld::Atom((ld::Section
&)sct
, d
, c
, s
, ct
, i
, dds
, thumb
, al
, a
),
782 _size(sz
), _objAddress(addr
), _name(nm
), _hash(0),
783 _fixupsStartIndex(0), _lineInfoStartIndex(0),
784 _unwindInfoStartIndex(0), _fixupsCount(0),
785 _lineInfoCount(0), _unwindInfoCount(0) { }
786 // construct via symbol table entry
787 Atom(Section
<A
>& sct
, Parser
<A
>& parser
, const macho_nlist
<P
>& sym
,
788 uint64_t sz
, bool alias
=false)
789 : ld::Atom((ld::Section
&)sct
, parser
.definitionFromSymbol(sym
),
790 parser
.combineFromSymbol(sym
), parser
.scopeFromSymbol(sym
),
791 parser
.resolverFromSymbol(sym
) ? ld::Atom::typeResolver
: sct
.contentType(),
792 parser
.inclusionFromSymbol(sym
),
793 (parser
.dontDeadStripFromSymbol(sym
) && !sct
.dontDeadStripIfReferencesLive()) || sct
.dontDeadStrip(),
794 parser
.isThumbFromSymbol(sym
), alias
,
795 sct
.alignmentForAddress(sym
.n_value())),
796 _size(sz
), _objAddress(sym
.n_value()),
797 _name(parser
.nameFromSymbol(sym
)), _hash(0),
798 _fixupsStartIndex(0), _lineInfoStartIndex(0),
799 _unwindInfoStartIndex(0), _fixupsCount(0),
800 _lineInfoCount(0), _unwindInfoCount(0) {
801 // <rdar://problem/6783167> support auto-hidden weak symbols
802 if ( _scope
== ld::Atom::scopeGlobal
&&
803 (sym
.n_desc() & (N_WEAK_DEF
|N_WEAK_REF
)) == (N_WEAK_DEF
|N_WEAK_REF
) )
805 this->verifyAlignment(*sct
.machoSection());
806 if ( sct
.dontDeadStripIfReferencesLive() )
807 this->setDontDeadStripIfReferencesLive();
811 friend class Parser
<A
>;
812 friend class Section
<A
>;
813 friend class CStringSection
<A
>;
814 friend class AbsoluteSymbolSection
<A
>;
819 mutable unsigned long _hash
;
821 uint64_t _fixupsStartIndex
: kFixupStartIndexBits
,
822 _lineInfoStartIndex
: kLineInfoStartIndexBits
,
823 _unwindInfoStartIndex
: kUnwindInfoStartIndexBits
,
824 _fixupsCount
: kFixupCountBits
,
825 _lineInfoCount
: kLineInfoCountBits
,
826 _unwindInfoCount
: kUnwindInfoCountBits
;
828 static std::map
<const ld::Atom
*, const ld::File
*> _s_fileOverride
;
831 template <typename A
>
832 std::map
<const ld::Atom
*, const ld::File
*> Atom
<A
>::_s_fileOverride
;
834 template <typename A
>
835 void Atom
<A
>::setFile(const ld::File
* f
) {
836 _s_fileOverride
[this] = f
;
839 template <typename A
>
840 const ld::File
* Atom
<A
>::file() const
842 std::map
<const ld::Atom
*, const ld::File
*>::iterator pos
= _s_fileOverride
.find(this);
843 if ( pos
!= _s_fileOverride
.end() )
846 return §().file();
849 template <typename A
>
850 void Atom
<A
>::setFixupsRange(uint32_t startIndex
, uint32_t count
)
852 if ( count
>= (1 << kFixupCountBits
) )
853 throwf("too many fixups in function %s", this->name());
854 if ( startIndex
>= (1 << kFixupStartIndexBits
) )
855 throwf("too many fixups in file");
856 assert(((startIndex
+count
) <= sect().file()._fixups
.size()) && "fixup index out of range");
857 _fixupsStartIndex
= startIndex
;
858 _fixupsCount
= count
;
861 template <typename A
>
862 void Atom
<A
>::setUnwindInfoRange(uint32_t startIndex
, uint32_t count
)
864 if ( count
>= (1 << kUnwindInfoCountBits
) )
865 throwf("too many compact unwind infos in function %s", this->name());
866 if ( startIndex
>= (1 << kUnwindInfoStartIndexBits
) )
867 throwf("too many compact unwind infos (%d) in file", startIndex
);
868 assert((startIndex
+count
) <= sect().file()._unwindInfos
.size() && "unwindinfo index out of range");
869 _unwindInfoStartIndex
= startIndex
;
870 _unwindInfoCount
= count
;
873 template <typename A
>
874 void Atom
<A
>::extendUnwindInfoRange()
876 if ( _unwindInfoCount
+1 >= (1 << kUnwindInfoCountBits
) )
877 throwf("too many compact unwind infos in function %s", this->name());
878 _unwindInfoCount
+= 1;
881 template <typename A
>
882 void Atom
<A
>::setLineInfoRange(uint32_t startIndex
, uint32_t count
)
884 assert((count
< (1 << kLineInfoCountBits
)) && "too many line infos");
885 assert((startIndex
+count
) < sect().file()._lineInfos
.size() && "line info index out of range");
886 _lineInfoStartIndex
= startIndex
;
887 _lineInfoCount
= count
;
890 template <typename A
>
891 const uint8_t* Atom
<A
>::contentPointer() const
893 const macho_section
<P
>* sct
= this->sect().machoSection();
894 if ( this->_objAddress
> sct
->addr() + sct
->size() )
895 throwf("malformed .o file, symbol has address 0x%0llX which is outside range of its section", (uint64_t)this->_objAddress
);
896 uint32_t fileOffset
= sct
->offset() - sct
->addr() + this->_objAddress
;
897 return this->sect().file().fileContent()+fileOffset
;
901 template <typename A
>
902 void Atom
<A
>::copyRawContent(uint8_t buffer
[]) const
905 if ( this->contentType() == ld::Atom::typeZeroFill
) {
906 bzero(buffer
, _size
);
908 else if ( _size
!= 0 ) {
909 memcpy(buffer
, this->contentPointer(), _size
);
914 void Atom
<arm
>::verifyAlignment(const macho_section
<P
>&) const
916 if ( (this->section().type() == ld::Section::typeCode
) && ! isThumb() ) {
917 if ( ((_objAddress
% 4) != 0) || (this->alignment().powerOf2
< 2) )
918 warning("ARM function not 4-byte aligned: %s from %s", this->name(), this->file()->path());
922 #if SUPPORT_ARCH_arm64
924 void Atom
<arm64
>::verifyAlignment(const macho_section
<P
>& sect
) const
926 if ( (this->section().type() == ld::Section::typeCode
) && (sect
.size() != 0) ) {
927 if ( ((_objAddress
% 4) != 0) || (this->alignment().powerOf2
< 2) )
928 warning("arm64 function not 4-byte aligned: %s from %s", this->name(), this->file()->path());
933 template <typename A
>
934 void Atom
<A
>::verifyAlignment(const macho_section
<P
>&) const
939 class AliasAtom
: public ld::Atom
942 AliasAtom(const char* name
, bool hidden
, const ld::File
* file
, const char* aliasOfName
) :
943 ld::Atom(_s_section
, ld::Atom::definitionRegular
, ld::Atom::combineNever
,
944 (hidden
? ld::Atom::scopeLinkageUnit
: ld::Atom::scopeGlobal
),
945 ld::Atom::typeUnclassified
, ld::Atom::symbolTableIn
,
946 false, false, true, 0),
949 _fixup(0, ld::Fixup::k1of1
, ld::Fixup::kindNoneFollowOn
, ld::Fixup::bindingByNameUnbound
, aliasOfName
) { }
951 virtual const ld::File
* file() const { return _file
; }
952 virtual const char* translationUnitSource() const
954 virtual const char* name() const { return _name
; }
955 virtual uint64_t size() const { return 0; }
956 virtual uint64_t objectAddress() const { return 0; }
957 virtual void copyRawContent(uint8_t buffer
[]) const { }
958 virtual ld::Fixup::iterator
fixupsBegin() const { return &((ld::Fixup
*)&_fixup
)[0]; }
959 virtual ld::Fixup::iterator
fixupsEnd() const { return &((ld::Fixup
*)&_fixup
)[1]; }
962 static ld::Section _s_section
;
964 const ld::File
* _file
;
969 ld::Section
AliasAtom::_s_section("__LD", "__aliases", ld::Section::typeTempAlias
, true);
972 template <typename A
>
976 static bool validFile(const uint8_t* fileContent
, bool subtypeMustMatch
=false,
977 cpu_subtype_t subtype
=0);
978 static const char* fileKind(const uint8_t* fileContent
);
979 static Options::Platform
findPlatform(const macho_header
<typename
A::P
>* header
);
980 static bool hasObjC2Categories(const uint8_t* fileContent
);
981 static bool hasObjC1Categories(const uint8_t* fileContent
);
982 static bool getNonLocalSymbols(const uint8_t* fileContnet
, std::vector
<const char*> &syms
);
983 static ld::relocatable::File
* parse(const uint8_t* fileContent
, uint64_t fileLength
,
984 const char* path
, time_t modTime
, ld::File::Ordinal ordinal
,
985 const ParserOptions
& opts
) {
986 Parser
p(fileContent
, fileLength
, path
, modTime
,
987 ordinal
, opts
.warnUnwindConversionProblems
,
988 opts
.keepDwarfUnwind
, opts
.forceDwarfConversion
,
989 opts
.neverConvertDwarf
, opts
.verboseOptimizationHints
,
990 opts
.ignoreMismatchPlatform
);
991 return p
.parse(opts
);
994 typedef typename
A::P P
;
995 typedef typename
A::P::E E
;
996 typedef typename
A::P::uint_t pint_t
;
998 struct SourceLocation
{
1000 SourceLocation(Atom
<A
>* a
, uint32_t o
) : atom(a
), offsetInAtom(o
) {}
1002 uint32_t offsetInAtom
;
1007 const char* name
; // only used if targetAtom is NULL
1009 bool weakImport
; // only used if targetAtom is NULL
1012 struct FixupInAtom
{
1013 FixupInAtom(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, Atom
<A
>* target
) :
1014 fixup(src
.offsetInAtom
, c
, k
, target
), atom(src
.atom
) { src
.atom
->incrementFixupCount(); }
1016 FixupInAtom(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, ld::Fixup::TargetBinding b
, Atom
<A
>* target
) :
1017 fixup(src
.offsetInAtom
, c
, k
, b
, target
), atom(src
.atom
) { src
.atom
->incrementFixupCount(); }
1019 FixupInAtom(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, bool wi
, const char* name
) :
1020 fixup(src
.offsetInAtom
, c
, k
, wi
, name
), atom(src
.atom
) { src
.atom
->incrementFixupCount(); }
1022 FixupInAtom(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, ld::Fixup::TargetBinding b
, const char* name
) :
1023 fixup(src
.offsetInAtom
, c
, k
, b
, name
), atom(src
.atom
) { src
.atom
->incrementFixupCount(); }
1025 FixupInAtom(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, uint64_t addend
) :
1026 fixup(src
.offsetInAtom
, c
, k
, addend
), atom(src
.atom
) { src
.atom
->incrementFixupCount(); }
1028 FixupInAtom(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
) :
1029 fixup(src
.offsetInAtom
, c
, k
, (uint64_t)0), atom(src
.atom
) { src
.atom
->incrementFixupCount(); }
1035 void addFixup(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, Atom
<A
>* target
) {
1036 _allFixups
.push_back(FixupInAtom(src
, c
, k
, target
));
1039 void addFixup(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, ld::Fixup::TargetBinding b
, Atom
<A
>* target
) {
1040 _allFixups
.push_back(FixupInAtom(src
, c
, k
, b
, target
));
1043 void addFixup(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, bool wi
, const char* name
) {
1044 _allFixups
.push_back(FixupInAtom(src
, c
, k
, wi
, name
));
1047 void addFixup(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, ld::Fixup::TargetBinding b
, const char* name
) {
1048 _allFixups
.push_back(FixupInAtom(src
, c
, k
, b
, name
));
1051 void addFixup(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, uint64_t addend
) {
1052 _allFixups
.push_back(FixupInAtom(src
, c
, k
, addend
));
1055 void addFixup(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
) {
1056 _allFixups
.push_back(FixupInAtom(src
, c
, k
));
1059 const char* path() { return _path
; }
1060 uint32_t symbolCount() { return _symbolCount
; }
1061 uint32_t indirectSymbol(uint32_t indirectIndex
);
1062 const macho_nlist
<P
>& symbolFromIndex(uint32_t index
);
1063 const char* nameFromSymbol(const macho_nlist
<P
>& sym
);
1064 ld::Atom::Scope
scopeFromSymbol(const macho_nlist
<P
>& sym
);
1065 static ld::Atom::Definition
definitionFromSymbol(const macho_nlist
<P
>& sym
);
1066 static ld::Atom::Combine
combineFromSymbol(const macho_nlist
<P
>& sym
);
1067 ld::Atom::SymbolTableInclusion
inclusionFromSymbol(const macho_nlist
<P
>& sym
);
1068 static bool dontDeadStripFromSymbol(const macho_nlist
<P
>& sym
);
1069 static bool isThumbFromSymbol(const macho_nlist
<P
>& sym
);
1070 static bool weakImportFromSymbol(const macho_nlist
<P
>& sym
);
1071 static bool resolverFromSymbol(const macho_nlist
<P
>& sym
);
1072 static bool altEntryFromSymbol(const macho_nlist
<P
>& sym
);
1073 uint32_t symbolIndexFromIndirectSectionAddress(pint_t
,const macho_section
<P
>*);
1074 const macho_section
<P
>* firstMachOSection() { return _sectionsStart
; }
1075 const macho_section
<P
>* machOSectionFromSectionIndex(uint32_t index
);
1076 uint32_t machOSectionCount() { return _machOSectionsCount
; }
1077 uint32_t undefinedStartIndex() { return _undefinedStartIndex
; }
1078 uint32_t undefinedEndIndex() { return _undefinedEndIndex
; }
1079 void addFixup(FixupInAtom f
) { _allFixups
.push_back(f
); }
1080 Section
<A
>* sectionForNum(unsigned int sectNum
);
1081 Section
<A
>* sectionForAddress(pint_t addr
);
1082 Atom
<A
>* findAtomByAddress(pint_t addr
);
1083 Atom
<A
>* findAtomByAddressOrNullIfStub(pint_t addr
);
1084 Atom
<A
>* findAtomByAddressOrLocalTargetOfStub(pint_t addr
, uint32_t* offsetInAtom
);
1085 Atom
<A
>* findAtomByName(const char* name
); // slow!
1086 void findTargetFromAddress(pint_t addr
, TargetDesc
& target
);
1087 void findTargetFromAddress(pint_t baseAddr
, pint_t addr
, TargetDesc
& target
);
1088 void findTargetFromAddressAndSectionNum(pint_t addr
, unsigned int sectNum
,
1089 TargetDesc
& target
);
1090 uint32_t tentativeDefinitionCount() { return _tentativeDefinitionCount
; }
1091 uint32_t absoluteSymbolCount() { return _absoluteSymbolCount
; }
1093 uint32_t fileLength() const { return _fileLength
; }
1094 bool hasStubsSection() { return (_stubsSectionNum
!= 0); }
1095 unsigned int stubsSectionNum() { return _stubsSectionNum
; }
1096 void addDtraceExtraInfos(const SourceLocation
& src
, const char* provider
);
1097 const char* scanSymbolTableForAddress(uint64_t addr
);
1098 bool warnUnwindConversionProblems() { return _warnUnwindConversionProblems
; }
1099 bool hasDataInCodeLabels() { return _hasDataInCodeLabels
; }
1100 bool keepDwarfUnwind() { return _keepDwarfUnwind
; }
1101 bool forceDwarfConversion() { return _forceDwarfConversion
; }
1102 bool verboseOptimizationHints() { return _verboseOptimizationHints
; }
1103 bool neverConvertDwarf() { return _neverConvertDwarf
; }
1104 bool armUsesZeroCostExceptions() { return _armUsesZeroCostExceptions
; }
1105 uint8_t maxDefaultCommonAlignment() { return _maxDefaultCommonAlignment
; }
1108 macho_data_in_code_entry
<P
>* dataInCodeStart() { return _dataInCodeStart
; }
1109 macho_data_in_code_entry
<P
>* dataInCodeEnd() { return _dataInCodeEnd
; }
1110 const uint8_t* optimizationHintsStart() { return _lohStart
; }
1111 const uint8_t* optimizationHintsEnd() { return _lohEnd
; }
1112 bool hasOptimizationHints() { return _lohStart
!= _lohEnd
; }
1115 void addFixups(const SourceLocation
& src
, ld::Fixup::Kind kind
, const TargetDesc
& target
);
1116 void addFixups(const SourceLocation
& src
, ld::Fixup::Kind kind
, const TargetDesc
& target
, const TargetDesc
& picBase
);
1120 struct LabelAndCFIBreakIterator
{
1121 typedef typename CFISection
<A
>::CFI_Atom_Info CFI_Atom_Info
;
1122 LabelAndCFIBreakIterator(const uint32_t* ssa
, uint32_t ssc
, const pint_t
* cfisa
,
1123 uint32_t cfisc
, bool ols
)
1124 : sortedSymbolIndexes(ssa
), sortedSymbolCount(ssc
), cfiStartsArray(cfisa
),
1125 cfiStartsCount(cfisc
), fileHasOverlappingSymbols(ols
),
1126 newSection(false), cfiIndex(0), symIndex(0) {}
1127 bool next(Parser
<A
>& parser
, const Section
<A
>& sect
, uint32_t sectNum
, pint_t startAddr
, pint_t endAddr
,
1128 pint_t
* addr
, pint_t
* size
, const macho_nlist
<P
>** sym
);
1129 pint_t
peek(Parser
<A
>& parser
, pint_t startAddr
, pint_t endAddr
);
1130 void beginSection() { newSection
= true; symIndex
= 0; }
1132 const uint32_t* const sortedSymbolIndexes
;
1133 const uint32_t sortedSymbolCount
;
1134 const pint_t
* cfiStartsArray
;
1135 const uint32_t cfiStartsCount
;
1136 const bool fileHasOverlappingSymbols
;
1142 struct CFI_CU_InfoArrays
{
1143 typedef typename CFISection
<A
>::CFI_Atom_Info CFI_Atom_Info
;
1144 typedef typename CUSection
<A
>::Info CU_Info
;
1145 CFI_CU_InfoArrays(const CFI_Atom_Info
* cfiAr
, uint32_t cfiC
, CU_Info
* cuAr
, uint32_t cuC
)
1146 : cfiArray(cfiAr
), cuArray(cuAr
), cfiCount(cfiC
), cuCount(cuC
) {}
1147 const CFI_Atom_Info
* const cfiArray
;
1148 CU_Info
* const cuArray
;
1149 const uint32_t cfiCount
;
1150 const uint32_t cuCount
;
1156 friend class Section
<A
>;
1158 enum SectionType
{ sectionTypeIgnore
, sectionTypeLiteral4
, sectionTypeLiteral8
, sectionTypeLiteral16
,
1159 sectionTypeNonLazy
, sectionTypeCFI
, sectionTypeCString
, sectionTypeCStringPointer
,
1160 sectionTypeUTF16Strings
, sectionTypeCFString
, sectionTypeObjC2ClassRefs
, typeObjC2CategoryList
,
1161 sectionTypeObjC1Classes
, sectionTypeSymboled
, sectionTypeObjC1ClassRefs
,
1162 sectionTypeTentativeDefinitions
, sectionTypeAbsoluteSymbols
, sectionTypeTLVDefs
,
1163 sectionTypeCompactUnwind
, sectionTypeTLVPointers
};
1165 template <typename P
>
1166 struct MachOSectionAndSectionClass
1168 const macho_section
<P
>* sect
;
1171 static int sorter(const void* l
, const void* r
) {
1172 const MachOSectionAndSectionClass
<P
>* left
= (MachOSectionAndSectionClass
<P
>*)l
;
1173 const MachOSectionAndSectionClass
<P
>* right
= (MachOSectionAndSectionClass
<P
>*)r
;
1174 int64_t diff
= left
->sect
->addr() - right
->sect
->addr();
1184 struct ParserAndSectionsArray
{ Parser
* parser
; const uint32_t* sortedSectionsArray
; };
1187 Parser(const uint8_t* fileContent
, uint64_t fileLength
,
1188 const char* path
, time_t modTime
, ld::File::Ordinal ordinal
,
1189 bool warnUnwindConversionProblems
, bool keepDwarfUnwind
,
1190 bool forceDwarfConversion
, bool neverConvertDwarf
,
1191 bool verboseOptimizationHints
, bool ignoreMismatchPlatform
);
1192 ld::relocatable::File
* parse(const ParserOptions
& opts
);
1193 static uint8_t loadCommandSizeMask();
1194 bool parseLoadCommands(Options::Platform platform
, uint32_t minOSVersion
, bool simulator
, bool ignoreMismatchPlatform
);
1195 void makeSections();
1196 void prescanSymbolTable();
1197 void makeSortedSymbolsArray(uint32_t symArray
[], const uint32_t sectionArray
[]);
1198 void makeSortedSectionsArray(uint32_t array
[]);
1199 static int pointerSorter(const void* l
, const void* r
);
1200 static int symbolIndexSorter(void* extra
, const void* l
, const void* r
);
1201 static int sectionIndexSorter(void* extra
, const void* l
, const void* r
);
1203 void parseDebugInfo();
1205 void appendAliasAtoms(uint8_t* atomBuffer
);
1206 static bool isConstFunStabs(const char *stabStr
);
1207 bool read_comp_unit(const char ** name
, const char ** comp_dir
,
1208 uint64_t *stmt_list
);
1209 pint_t
realAddr(pint_t addr
);
1210 const char* getDwarfString(uint64_t form
, const uint8_t*& p
);
1211 uint64_t getDwarfOffset(uint64_t form
, const uint8_t*& di
, bool dwarf64
);
1212 bool skip_form(const uint8_t ** offset
, const uint8_t * end
,
1213 uint64_t form
, uint8_t addr_size
, bool dwarf64
);
1216 // filled in by constructor
1217 const uint8_t* _fileContent
;
1218 uint32_t _fileLength
;
1221 ld::File::Ordinal _ordinal
;
1223 // filled in by parseLoadCommands()
1225 const macho_nlist
<P
>* _symbols
;
1226 uint32_t _symbolCount
;
1227 uint32_t _indirectSymbolCount
;
1228 const char* _strings
;
1229 uint32_t _stringsSize
;
1230 const uint32_t* _indirectTable
;
1231 uint32_t _indirectTableCount
;
1232 uint32_t _undefinedStartIndex
;
1233 uint32_t _undefinedEndIndex
;
1234 const macho_section
<P
>* _sectionsStart
;
1235 uint32_t _machOSectionsCount
;
1237 macho_data_in_code_entry
<P
>* _dataInCodeStart
;
1238 macho_data_in_code_entry
<P
>* _dataInCodeEnd
;
1239 const uint8_t* _lohStart
;
1240 const uint8_t* _lohEnd
;
1242 // filled in by parse()
1243 CFISection
<A
>* _EHFrameSection
;
1244 CUSection
<A
>* _compactUnwindSection
;
1245 AbsoluteSymbolSection
<A
>* _absoluteSection
;
1246 uint32_t _tentativeDefinitionCount
;
1247 uint32_t _absoluteSymbolCount
;
1248 uint32_t _symbolsInSections
;
1249 bool _hasLongBranchStubs
;
1250 bool _AppleObjc
; // FSF has objc that uses different data layout
1251 bool _overlappingSymbols
;
1252 bool _warnUnwindConversionProblems
;
1253 bool _hasDataInCodeLabels
;
1254 bool _keepDwarfUnwind
;
1255 bool _forceDwarfConversion
;
1256 bool _neverConvertDwarf
;
1257 bool _verboseOptimizationHints
;
1258 bool _armUsesZeroCostExceptions
;
1259 bool _ignoreMismatchPlatform
;
1260 bool _treateBitcodeAsData
;
1262 uint8_t _maxDefaultCommonAlignment
;
1263 unsigned int _stubsSectionNum
;
1264 const macho_section
<P
>* _stubsMachOSection
;
1265 std::vector
<const char*> _dtraceProviderInfo
;
1266 std::vector
<FixupInAtom
> _allFixups
;
1271 template <typename A
>
1272 Parser
<A
>::Parser(const uint8_t* fileContent
, uint64_t fileLength
, const char* path
, time_t modTime
,
1273 ld::File::Ordinal ordinal
, bool convertDUI
, bool keepDwarfUnwind
, bool forceDwarfConversion
,
1274 bool neverConvertDwarf
, bool verboseOptimizationHints
, bool ignoreMismatchPlatform
)
1275 : _fileContent(fileContent
), _fileLength(fileLength
), _path(path
), _modTime(modTime
),
1276 _ordinal(ordinal
), _file(NULL
),
1277 _symbols(NULL
), _symbolCount(0), _indirectSymbolCount(0), _strings(NULL
), _stringsSize(0),
1278 _indirectTable(NULL
), _indirectTableCount(0),
1279 _undefinedStartIndex(0), _undefinedEndIndex(0),
1280 _sectionsStart(NULL
), _machOSectionsCount(0), _hasUUID(false),
1281 _dataInCodeStart(NULL
), _dataInCodeEnd(NULL
),
1282 _lohStart(NULL
), _lohEnd(NULL
),
1283 _EHFrameSection(NULL
), _compactUnwindSection(NULL
), _absoluteSection(NULL
),
1284 _tentativeDefinitionCount(0), _absoluteSymbolCount(0),
1285 _symbolsInSections(0), _hasLongBranchStubs(false), _AppleObjc(false),
1286 _overlappingSymbols(false), _warnUnwindConversionProblems(convertDUI
), _hasDataInCodeLabels(false),
1287 _keepDwarfUnwind(keepDwarfUnwind
), _forceDwarfConversion(forceDwarfConversion
),
1288 _neverConvertDwarf(neverConvertDwarf
),
1289 _verboseOptimizationHints(verboseOptimizationHints
),
1290 _ignoreMismatchPlatform(ignoreMismatchPlatform
),
1291 _stubsSectionNum(0), _stubsMachOSection(NULL
)
1297 bool Parser
<x86
>::validFile(const uint8_t* fileContent
, bool, cpu_subtype_t
)
1299 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1300 if ( header
->magic() != MH_MAGIC
)
1302 if ( header
->cputype() != CPU_TYPE_I386
)
1304 if ( header
->filetype() != MH_OBJECT
)
1310 bool Parser
<x86_64
>::validFile(const uint8_t* fileContent
, bool, cpu_subtype_t
)
1312 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1313 if ( header
->magic() != MH_MAGIC_64
)
1315 if ( header
->cputype() != CPU_TYPE_X86_64
)
1317 if ( header
->filetype() != MH_OBJECT
)
1323 bool Parser
<arm
>::validFile(const uint8_t* fileContent
, bool subtypeMustMatch
, cpu_subtype_t subtype
)
1325 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1326 if ( header
->magic() != MH_MAGIC
)
1328 if ( header
->cputype() != CPU_TYPE_ARM
)
1330 if ( header
->filetype() != MH_OBJECT
)
1332 if ( subtypeMustMatch
) {
1333 if ( (cpu_subtype_t
)header
->cpusubtype() == subtype
)
1335 // hack until libcc_kext.a is made fat
1336 if ( header
->cpusubtype() == CPU_SUBTYPE_ARM_ALL
)
1345 bool Parser
<arm64
>::validFile(const uint8_t* fileContent
, bool subtypeMustMatch
, cpu_subtype_t subtype
)
1347 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1348 if ( header
->magic() != MH_MAGIC_64
)
1350 if ( header
->cputype() != CPU_TYPE_ARM64
)
1352 if ( header
->filetype() != MH_OBJECT
)
1359 const char* Parser
<x86
>::fileKind(const uint8_t* fileContent
)
1361 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1362 if ( header
->magic() != MH_MAGIC
)
1364 if ( header
->cputype() != CPU_TYPE_I386
)
1370 const char* Parser
<x86_64
>::fileKind(const uint8_t* fileContent
)
1372 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1373 if ( header
->magic() != MH_MAGIC_64
)
1375 if ( header
->cputype() != CPU_TYPE_X86_64
)
1381 const char* Parser
<arm
>::fileKind(const uint8_t* fileContent
)
1383 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1384 if ( header
->magic() != MH_MAGIC
)
1386 if ( header
->cputype() != CPU_TYPE_ARM
)
1388 for (const ArchInfo
* t
=archInfoArray
; t
->archName
!= NULL
; ++t
) {
1389 if ( (t
->cpuType
== CPU_TYPE_ARM
) && ((cpu_subtype_t
)header
->cpusubtype() == t
->cpuSubType
) ) {
1396 #if SUPPORT_ARCH_arm64
1398 const char* Parser
<arm64
>::fileKind(const uint8_t* fileContent
)
1400 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1401 if ( header
->magic() != MH_MAGIC_64
)
1403 if ( header
->cputype() != CPU_TYPE_ARM64
)
1409 template <typename A
>
1410 bool Parser
<A
>::hasObjC2Categories(const uint8_t* fileContent
)
1412 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1413 const uint32_t cmd_count
= header
->ncmds();
1414 const macho_load_command
<P
>* const cmds
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>));
1415 const macho_load_command
<P
>* const cmdsEnd
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>) + header
->sizeofcmds());
1416 const macho_load_command
<P
>* cmd
= cmds
;
1417 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1418 if ( cmd
->cmd() == macho_segment_command
<P
>::CMD
) {
1419 const macho_segment_command
<P
>* segment
= (macho_segment_command
<P
>*)cmd
;
1420 const macho_section
<P
>* sectionsStart
= (macho_section
<P
>*)((char*)segment
+ sizeof(macho_segment_command
<P
>));
1421 for (uint32_t si
=0; si
< segment
->nsects(); ++si
) {
1422 const macho_section
<P
>* sect
= §ionsStart
[si
];
1423 if ( (sect
->size() > 0)
1424 && (strcmp(sect
->sectname(), "__objc_catlist") == 0)
1425 && (strcmp(sect
->segname(), "__DATA") == 0) ) {
1430 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
1431 if ( cmd
> cmdsEnd
)
1432 throwf("malformed mach-o file, load command #%d is outside size of load commands", i
);
1438 template <typename A
>
1439 bool Parser
<A
>::hasObjC1Categories(const uint8_t* fileContent
)
1441 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1442 const uint32_t cmd_count
= header
->ncmds();
1443 const macho_load_command
<P
>* const cmds
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>));
1444 const macho_load_command
<P
>* const cmdsEnd
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>) + header
->sizeofcmds());
1445 const macho_load_command
<P
>* cmd
= cmds
;
1446 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1447 if ( cmd
->cmd() == macho_segment_command
<P
>::CMD
) {
1448 const macho_segment_command
<P
>* segment
= (macho_segment_command
<P
>*)cmd
;
1449 const macho_section
<P
>* sectionsStart
= (macho_section
<P
>*)((char*)segment
+ sizeof(macho_segment_command
<P
>));
1450 for (uint32_t si
=0; si
< segment
->nsects(); ++si
) {
1451 const macho_section
<P
>* sect
= §ionsStart
[si
];
1452 if ( (sect
->size() > 0)
1453 && (strcmp(sect
->sectname(), "__category") == 0)
1454 && (strcmp(sect
->segname(), "__OBJC") == 0) ) {
1459 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
1460 if ( cmd
> cmdsEnd
)
1461 throwf("malformed mach-o file, load command #%d is outside size of load commands", i
);
1467 template <typename A
>
1468 bool Parser
<A
>::getNonLocalSymbols(const uint8_t* fileContent
, std::vector
<const char*> &syms
)
1470 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1471 const uint32_t cmd_count
= header
->ncmds();
1472 const macho_load_command
<P
>* const cmds
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>));
1473 const macho_load_command
<P
>* const cmdsEnd
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>) + header
->sizeofcmds());
1474 const macho_load_command
<P
>* cmd
= cmds
;
1475 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1476 if ( cmd
->cmd() == LC_SYMTAB
) {
1477 const macho_symtab_command
<P
>* symtab
= (macho_symtab_command
<P
>*)cmd
;
1478 uint32_t symbolCount
= symtab
->nsyms();
1479 const macho_nlist
<P
>* symbols
= (const macho_nlist
<P
>*)(fileContent
+ symtab
->symoff());
1480 const char* strings
= (char*)fileContent
+ symtab
->stroff();
1481 for (uint32_t j
= 0; j
< symbolCount
; ++j
) {
1482 // ignore stabs and count only ext symbols
1483 if ( (symbols
[j
].n_type() & N_STAB
) == 0 &&
1484 (symbols
[j
].n_type() & N_EXT
) != 0 ) {
1485 const char* symName
= &strings
[symbols
[j
].n_strx()];
1486 syms
.push_back(symName
);
1491 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
1492 if ( cmd
> cmdsEnd
)
1493 throwf("malformed mach-o file, load command #%d is outside size of load commands", i
);
1499 template <typename A
>
1500 int Parser
<A
>::pointerSorter(const void* l
, const void* r
)
1502 // sort references by address
1503 const pint_t
* left
= (pint_t
*)l
;
1504 const pint_t
* right
= (pint_t
*)r
;
1505 return (*left
- *right
);
1508 template <typename A
>
1509 typename
A::P::uint_t Parser
<A
>::LabelAndCFIBreakIterator::peek(Parser
<A
>& parser
, pint_t startAddr
, pint_t endAddr
)
1512 if ( symIndex
< sortedSymbolCount
)
1513 symbolAddr
= parser
.symbolFromIndex(sortedSymbolIndexes
[symIndex
]).n_value();
1515 symbolAddr
= endAddr
;
1517 if ( cfiIndex
< cfiStartsCount
)
1518 cfiAddr
= cfiStartsArray
[cfiIndex
];
1521 if ( (cfiAddr
< symbolAddr
) && (cfiAddr
>= startAddr
) ) {
1522 if ( cfiAddr
< endAddr
)
1528 if ( symbolAddr
< endAddr
)
1536 // Parses up a section into chunks based on labels and CFI information.
1537 // Each call returns the next chunk address and size, and (if the break
1538 // was becuase of a label, the symbol). Returns false when no more chunks.
1540 template <typename A
>
1541 bool Parser
<A
>::LabelAndCFIBreakIterator::next(Parser
<A
>& parser
, const Section
<A
>& sect
, uint32_t sectNum
, pint_t startAddr
, pint_t endAddr
,
1542 pint_t
* addr
, pint_t
* size
, const macho_nlist
<P
>** symbol
)
1544 // may not be a label on start of section, but need atom demarcation there
1547 // advance symIndex until we get to the first label at or past the start of this section
1548 while ( symIndex
< sortedSymbolCount
) {
1549 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(sortedSymbolIndexes
[symIndex
]);
1550 if ( ! sect
.ignoreLabel(parser
.nameFromSymbol(sym
)) ) {
1551 pint_t nextSymbolAddr
= sym
.n_value();
1552 //fprintf(stderr, "sectNum=%d, nextSymbolAddr=0x%08llX, name=%s\n", sectNum, (uint64_t)nextSymbolAddr, parser.nameFromSymbol(sym));
1553 if ( (nextSymbolAddr
> startAddr
) || ((nextSymbolAddr
== startAddr
) && (sym
.n_sect() == sectNum
)) )
1558 if ( symIndex
< sortedSymbolCount
) {
1559 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(sortedSymbolIndexes
[symIndex
]);
1560 pint_t nextSymbolAddr
= sym
.n_value();
1561 // if next symbol found is not in this section
1562 if ( sym
.n_sect() != sectNum
) {
1563 // check for CFI break instead of symbol break
1564 if ( cfiIndex
< cfiStartsCount
) {
1565 pint_t nextCfiAddr
= cfiStartsArray
[cfiIndex
];
1566 if ( nextCfiAddr
< endAddr
) {
1569 *addr
= nextCfiAddr
;
1570 *size
= peek(parser
, startAddr
, endAddr
) - nextCfiAddr
;
1576 *size
= endAddr
- startAddr
;
1578 if ( startAddr
== endAddr
)
1579 return false; // zero size section
1581 return true; // whole section is one atom with no label
1583 // if also CFI break here, eat it
1584 if ( cfiIndex
< cfiStartsCount
) {
1585 if ( cfiStartsArray
[cfiIndex
] == nextSymbolAddr
)
1588 if ( nextSymbolAddr
== startAddr
) {
1589 // label at start of section, return it as chunk
1592 *size
= peek(parser
, startAddr
, endAddr
) - startAddr
;
1596 // return chunk before first symbol
1598 *size
= nextSymbolAddr
- startAddr
;
1602 // no symbols in section, check CFI
1603 if ( cfiIndex
< cfiStartsCount
) {
1604 pint_t nextCfiAddr
= cfiStartsArray
[cfiIndex
];
1605 if ( nextCfiAddr
< endAddr
) {
1608 *addr
= nextCfiAddr
;
1609 *size
= peek(parser
, startAddr
, endAddr
) - nextCfiAddr
;
1614 // no cfi, so whole section is one chunk
1616 *size
= endAddr
- startAddr
;
1618 if ( startAddr
== endAddr
)
1619 return false; // zero size section
1621 return true; // whole section is one atom with no label
1624 while ( (symIndex
< sortedSymbolCount
) && (cfiIndex
< cfiStartsCount
) ) {
1625 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(sortedSymbolIndexes
[symIndex
]);
1626 pint_t nextSymbolAddr
= sym
.n_value();
1627 pint_t nextCfiAddr
= cfiStartsArray
[cfiIndex
];
1628 if ( nextSymbolAddr
< nextCfiAddr
) {
1629 if ( nextSymbolAddr
>= endAddr
)
1632 if ( nextSymbolAddr
< startAddr
)
1634 *addr
= nextSymbolAddr
;
1635 *size
= peek(parser
, startAddr
, endAddr
) - nextSymbolAddr
;
1639 else if ( nextCfiAddr
< nextSymbolAddr
) {
1640 if ( nextCfiAddr
>= endAddr
)
1643 if ( nextCfiAddr
< startAddr
)
1645 *addr
= nextCfiAddr
;
1646 *size
= peek(parser
, startAddr
, endAddr
) - nextCfiAddr
;
1651 if ( nextCfiAddr
>= endAddr
)
1655 if ( nextCfiAddr
< startAddr
)
1657 *addr
= nextCfiAddr
;
1658 *size
= peek(parser
, startAddr
, endAddr
) - nextCfiAddr
;
1663 while ( symIndex
< sortedSymbolCount
) {
1664 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(sortedSymbolIndexes
[symIndex
]);
1665 pint_t nextSymbolAddr
= sym
.n_value();
1666 // if next symbol found is not in this section, then done with iteration
1667 if ( sym
.n_sect() != sectNum
)
1670 if ( nextSymbolAddr
< startAddr
)
1672 *addr
= nextSymbolAddr
;
1673 *size
= peek(parser
, startAddr
, endAddr
) - nextSymbolAddr
;
1677 while ( cfiIndex
< cfiStartsCount
) {
1678 pint_t nextCfiAddr
= cfiStartsArray
[cfiIndex
];
1679 if ( nextCfiAddr
>= endAddr
)
1682 if ( nextCfiAddr
< startAddr
)
1684 *addr
= nextCfiAddr
;
1685 *size
= peek(parser
, startAddr
, endAddr
) - nextCfiAddr
;
1693 typename
arm::P::uint_t Parser
<arm
>::realAddr(typename
arm::P::uint_t addr
)
1698 template <typename A
>
1699 typename
A::P::uint_t Parser
<A
>::realAddr(typename
A::P::uint_t addr
)
1704 #define STACK_ALLOC_IF_SMALL(_type, _name, _actual_count, _maxCount) \
1705 _type* _name = NULL; \
1706 uint32_t _name##_count = 1; \
1707 if ( _actual_count > _maxCount ) \
1708 _name = (_type*)malloc(sizeof(_type) * _actual_count); \
1710 _name##_count = _actual_count; \
1711 _type _name##_buffer[_name##_count]; \
1712 if ( _name == NULL ) \
1713 _name = _name##_buffer;
1716 template <typename A
>
1717 ld::relocatable::File
* Parser
<A
>::parse(const ParserOptions
& opts
)
1719 // create file object
1720 _file
= new File
<A
>(_path
, _modTime
, _fileContent
, _ordinal
);
1723 _file
->_srcKind
= opts
.srcKind
;
1724 // set treatBitcodeAsData
1725 _treateBitcodeAsData
= opts
.treateBitcodeAsData
;
1726 _usingBitcode
= opts
.usingBitcode
;
1728 // respond to -t option
1729 if ( opts
.logAllFiles
)
1730 printf("%s\n", _path
);
1732 _armUsesZeroCostExceptions
= opts
.armUsesZeroCostExceptions
;
1733 _maxDefaultCommonAlignment
= opts
.maxDefaultCommonAlignment
;
1735 // parse start of mach-o file
1736 if ( ! parseLoadCommands(opts
.platform
, opts
.minOSVersion
, opts
.simulator
, opts
.ignoreMismatchPlatform
) )
1740 uint32_t sortedSectionIndexes
[_machOSectionsCount
];
1741 this->makeSortedSectionsArray(sortedSectionIndexes
);
1743 // make symbol table sorted by address
1744 this->prescanSymbolTable();
1745 uint32_t sortedSymbolIndexes
[_symbolsInSections
];
1746 this->makeSortedSymbolsArray(sortedSymbolIndexes
, sortedSectionIndexes
);
1748 // allocate Section<A> object for each mach-o section
1751 // if it exists, do special early parsing of __compact_unwind section
1752 uint32_t countOfCUs
= 0;
1753 if ( _compactUnwindSection
!= NULL
)
1754 countOfCUs
= _compactUnwindSection
->count();
1755 // stack allocate (if not too large) cuInfoBuffer
1756 STACK_ALLOC_IF_SMALL(typename CUSection
<A
>::Info
, cuInfoArray
, countOfCUs
, 1024);
1757 if ( countOfCUs
!= 0 )
1758 _compactUnwindSection
->parse(*this, countOfCUs
, cuInfoArray
);
1760 // create lists of address that already have compact unwind and thus don't need the dwarf parsed
1761 unsigned cuLsdaCount
= 0;
1762 pint_t cuStarts
[countOfCUs
];
1763 for (uint32_t i
=0; i
< countOfCUs
; ++i
) {
1764 if ( CUSection
<A
>::encodingMeansUseDwarf(cuInfoArray
[i
].compactUnwindInfo
) )
1767 cuStarts
[i
] = cuInfoArray
[i
].functionStartAddress
;
1768 if ( cuInfoArray
[i
].lsdaAddress
!= 0 )
1773 // if it exists, do special early parsing of __eh_frame section
1774 // stack allocate (if not too large) array of CFI_Atom_Info
1775 uint32_t countOfCFIs
= 0;
1776 if ( _EHFrameSection
!= NULL
)
1777 countOfCFIs
= _EHFrameSection
->cfiCount(*this);
1778 STACK_ALLOC_IF_SMALL(typename CFISection
<A
>::CFI_Atom_Info
, cfiArray
, countOfCFIs
, 1024);
1780 // stack allocate (if not too large) a copy of __eh_frame to apply relocations to
1781 uint32_t sectSize
= 4;
1782 if ( (countOfCFIs
!= 0) && _EHFrameSection
->needsRelocating() )
1783 sectSize
= _EHFrameSection
->machoSection()->size()+4;
1784 STACK_ALLOC_IF_SMALL(uint8_t, ehBuffer
, sectSize
, 50*1024);
1785 uint32_t cfiStartsCount
= 0;
1786 if ( countOfCFIs
!= 0 ) {
1787 _EHFrameSection
->cfiParse(*this, ehBuffer
, cfiArray
, countOfCFIs
, cuStarts
, countOfCUs
);
1788 // count functions and lsdas
1789 for(uint32_t i
=0; i
< countOfCFIs
; ++i
) {
1790 if ( cfiArray
[i
].isCIE
)
1792 //fprintf(stderr, "cfiArray[i].func = 0x%08llX, cfiArray[i].lsda = 0x%08llX, encoding=0x%08X\n",
1793 // (uint64_t)cfiArray[i].u.fdeInfo.function.targetAddress,
1794 // (uint64_t)cfiArray[i].u.fdeInfo.lsda.targetAddress,
1795 // cfiArray[i].u.fdeInfo.compactUnwindInfo);
1796 if ( cfiArray
[i
].u
.fdeInfo
.function
.targetAddress
!= CFI_INVALID_ADDRESS
)
1798 if ( cfiArray
[i
].u
.fdeInfo
.lsda
.targetAddress
!= CFI_INVALID_ADDRESS
)
1802 CFI_CU_InfoArrays
cfis(cfiArray
, countOfCFIs
, cuInfoArray
, countOfCUs
);
1804 // create sorted array of function starts and lsda starts
1805 pint_t cfiStartsArray
[cfiStartsCount
+cuLsdaCount
];
1806 uint32_t countOfFDEs
= 0;
1807 uint32_t cfiStartsArrayCount
= 0;
1808 if ( countOfCFIs
!= 0 ) {
1809 for(uint32_t i
=0; i
< countOfCFIs
; ++i
) {
1810 if ( cfiArray
[i
].isCIE
)
1812 if ( cfiArray
[i
].u
.fdeInfo
.function
.targetAddress
!= CFI_INVALID_ADDRESS
)
1813 cfiStartsArray
[cfiStartsArrayCount
++] = realAddr(cfiArray
[i
].u
.fdeInfo
.function
.targetAddress
);
1814 if ( cfiArray
[i
].u
.fdeInfo
.lsda
.targetAddress
!= CFI_INVALID_ADDRESS
)
1815 cfiStartsArray
[cfiStartsArrayCount
++] = cfiArray
[i
].u
.fdeInfo
.lsda
.targetAddress
;
1819 if ( cuLsdaCount
!= 0 ) {
1820 // merge in an lsda info from compact unwind
1821 for (uint32_t i
=0; i
< countOfCUs
; ++i
) {
1822 if ( cuInfoArray
[i
].lsdaAddress
== 0 )
1824 // append to cfiStartsArray if not already in that list
1826 for(uint32_t j
=0; j
< cfiStartsArrayCount
; ++j
) {
1827 if ( cfiStartsArray
[j
] == cuInfoArray
[i
].lsdaAddress
)
1831 cfiStartsArray
[cfiStartsArrayCount
++] = cuInfoArray
[i
].lsdaAddress
;
1835 if ( cfiStartsArrayCount
!= 0 ) {
1836 ::qsort(cfiStartsArray
, cfiStartsArrayCount
, sizeof(pint_t
), pointerSorter
);
1838 // scan for FDEs claming the same function
1839 for(uint32_t i
=1; i
< cfiStartsArrayCount
; ++i
) {
1840 assert( cfiStartsArray
[i
] != cfiStartsArray
[i
-1] );
1845 Section
<A
>** sections
= _file
->_sectionsArray
;
1846 uint32_t sectionsCount
= _file
->_sectionsArrayCount
;
1848 // figure out how many atoms will be allocated and allocate
1849 LabelAndCFIBreakIterator
breakIterator(sortedSymbolIndexes
, _symbolsInSections
, cfiStartsArray
,
1850 cfiStartsArrayCount
, _overlappingSymbols
);
1851 uint32_t computedAtomCount
= 0;
1852 for (uint32_t i
=0; i
< sectionsCount
; ++i
) {
1853 breakIterator
.beginSection();
1854 uint32_t count
= sections
[i
]->computeAtomCount(*this, breakIterator
, cfis
);
1855 //const macho_section<P>* sect = sections[i]->machoSection();
1856 //fprintf(stderr, "computed count=%u for section %s size=%llu\n", count, sect->sectname(), (sect != NULL) ? sect->size() : 0);
1857 computedAtomCount
+= count
;
1859 //fprintf(stderr, "allocating %d atoms * sizeof(Atom<A>)=%ld, sizeof(ld::Atom)=%ld\n", computedAtomCount, sizeof(Atom<A>), sizeof(ld::Atom));
1860 _file
->_atomsArray
= new uint8_t[computedAtomCount
*sizeof(Atom
<A
>)];
1861 _file
->_atomsArrayCount
= 0;
1863 // have each section append atoms to _atomsArray
1864 LabelAndCFIBreakIterator
breakIterator2(sortedSymbolIndexes
, _symbolsInSections
, cfiStartsArray
,
1865 cfiStartsArrayCount
, _overlappingSymbols
);
1866 for (uint32_t i
=0; i
< sectionsCount
; ++i
) {
1867 uint8_t* atoms
= _file
->_atomsArray
+ _file
->_atomsArrayCount
*sizeof(Atom
<A
>);
1868 breakIterator2
.beginSection();
1869 uint32_t count
= sections
[i
]->appendAtoms(*this, atoms
, breakIterator2
, cfis
);
1870 //fprintf(stderr, "append count=%u for section %s/%s\n", count, sections[i]->machoSection()->segname(), sections[i]->machoSection()->sectname());
1871 _file
->_atomsArrayCount
+= count
;
1873 assert( _file
->_atomsArrayCount
== computedAtomCount
&& "more atoms allocated than expected");
1876 // have each section add all fix-ups for its atoms
1877 _allFixups
.reserve(computedAtomCount
*5);
1878 for (uint32_t i
=0; i
< sectionsCount
; ++i
)
1879 sections
[i
]->makeFixups(*this, cfis
);
1881 // assign fixups start offset for each atom
1882 uint8_t* p
= _file
->_atomsArray
;
1883 uint32_t fixupOffset
= 0;
1884 for(int i
=_file
->_atomsArrayCount
; i
> 0; --i
) {
1885 Atom
<A
>* atom
= (Atom
<A
>*)p
;
1886 atom
->_fixupsStartIndex
= fixupOffset
;
1887 fixupOffset
+= atom
->_fixupsCount
;
1888 atom
->_fixupsCount
= 0;
1889 p
+= sizeof(Atom
<A
>);
1891 assert(fixupOffset
== _allFixups
.size());
1892 _file
->_fixups
.resize(fixupOffset
);
1894 // copy each fixup for each atom
1895 for(typename
std::vector
<FixupInAtom
>::iterator it
=_allFixups
.begin(); it
!= _allFixups
.end(); ++it
) {
1896 uint32_t slot
= it
->atom
->_fixupsStartIndex
+ it
->atom
->_fixupsCount
;
1897 _file
->_fixups
[slot
] = it
->fixup
;
1898 it
->atom
->_fixupsCount
++;
1901 // done with temp vector
1905 _file
->_unwindInfos
.reserve(countOfFDEs
+countOfCUs
);
1906 for(uint32_t i
=0; i
< countOfCFIs
; ++i
) {
1907 if ( cfiArray
[i
].isCIE
)
1909 if ( cfiArray
[i
].u
.fdeInfo
.function
.targetAddress
!= CFI_INVALID_ADDRESS
) {
1910 ld::Atom::UnwindInfo info
;
1911 info
.startOffset
= 0;
1912 info
.unwindInfo
= cfiArray
[i
].u
.fdeInfo
.compactUnwindInfo
;
1913 _file
->_unwindInfos
.push_back(info
);
1914 Atom
<A
>* func
= findAtomByAddress(cfiArray
[i
].u
.fdeInfo
.function
.targetAddress
);
1915 func
->setUnwindInfoRange(_file
->_unwindInfos
.size()-1, 1);
1916 //fprintf(stderr, "cu from dwarf =0x%08X, atom=%s\n", info.unwindInfo, func->name());
1919 // apply compact infos in __LD,__compact_unwind section to each function
1920 // if function also has dwarf unwind, CU will override it
1921 Atom
<A
>* lastFunc
= NULL
;
1922 uint32_t lastEnd
= 0;
1923 for(uint32_t i
=0; i
< countOfCUs
; ++i
) {
1924 typename CUSection
<A
>::Info
* info
= &cuInfoArray
[i
];
1925 assert(info
->function
!= NULL
);
1926 ld::Atom::UnwindInfo ui
;
1927 ui
.startOffset
= info
->functionStartAddress
- info
->function
->objectAddress();
1928 ui
.unwindInfo
= info
->compactUnwindInfo
;
1929 _file
->_unwindInfos
.push_back(ui
);
1930 // don't override with converted cu with "use dwarf" cu, if forcing dwarf conversion
1931 if ( !_forceDwarfConversion
|| !CUSection
<A
>::encodingMeansUseDwarf(info
->compactUnwindInfo
) ) {
1932 //fprintf(stderr, "cu=0x%08X, atom=%s\n", ui.unwindInfo, info->function->name());
1933 // if previous is for same function, extend range
1934 if ( info
->function
== lastFunc
) {
1935 if ( lastEnd
!= ui
.startOffset
) {
1936 if ( lastEnd
< ui
.startOffset
)
1937 warning("__LD,__compact_unwind entries for %s have a gap at offset 0x%0X", info
->function
->name(), lastEnd
);
1939 warning("__LD,__compact_unwind entries for %s overlap at offset 0x%0X", info
->function
->name(), lastEnd
);
1941 lastFunc
->extendUnwindInfoRange();
1944 info
->function
->setUnwindInfoRange(_file
->_unwindInfos
.size()-1, 1);
1945 lastFunc
= info
->function
;
1946 lastEnd
= ui
.startOffset
+ info
->rangeLength
;
1950 // process indirect symbols which become AliasAtoms
1951 _file
->_aliasAtomsArray
= NULL
;
1952 _file
->_aliasAtomsArrayCount
= 0;
1953 if ( _indirectSymbolCount
!= 0 ) {
1954 _file
->_aliasAtomsArrayCount
= _indirectSymbolCount
;
1955 _file
->_aliasAtomsArray
= new uint8_t[_file
->_aliasAtomsArrayCount
*sizeof(AliasAtom
)];
1956 this->appendAliasAtoms(_file
->_aliasAtomsArray
);
1960 // parse dwarf debug info to get line info
1961 this->parseDebugInfo();
1966 static void versionToString(uint32_t value
, char buffer
[32])
1969 sprintf(buffer
, "%d.%d.%d", value
>> 16, (value
>> 8) & 0xFF, value
& 0xFF);
1971 sprintf(buffer
, "%d.%d", value
>> 16, (value
>> 8) & 0xFF);
1974 template <> uint8_t Parser
<x86
>::loadCommandSizeMask() { return 0x03; }
1975 template <> uint8_t Parser
<x86_64
>::loadCommandSizeMask() { return 0x07; }
1976 template <> uint8_t Parser
<arm
>::loadCommandSizeMask() { return 0x03; }
1977 template <> uint8_t Parser
<arm64
>::loadCommandSizeMask() { return 0x07; }
1979 template <typename A
>
1980 bool Parser
<A
>::parseLoadCommands(Options::Platform platform
, uint32_t linkMinOSVersion
, bool simulator
, bool ignoreMismatchPlatform
)
1982 const macho_header
<P
>* header
= (const macho_header
<P
>*)_fileContent
;
1984 // set File attributes
1985 _file
->_canScatterAtoms
= (header
->flags() & MH_SUBSECTIONS_VIA_SYMBOLS
);
1986 _file
->_cpuSubType
= header
->cpusubtype();
1988 const macho_segment_command
<P
>* segment
= NULL
;
1989 const uint8_t* const endOfFile
= _fileContent
+ _fileLength
;
1990 const uint32_t cmd_count
= header
->ncmds();
1991 // <rdar://problem/5394172> an empty .o file with zero load commands will crash linker
1992 if ( cmd_count
== 0 )
1994 Options::Platform lcPlatform
= Options::kPlatformUnknown
;
1995 const macho_load_command
<P
>* const cmds
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>));
1996 const macho_load_command
<P
>* const cmdsEnd
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>) + header
->sizeofcmds());
1997 const macho_load_command
<P
>* cmd
= cmds
;
1998 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1999 uint32_t size
= cmd
->cmdsize();
2000 if ( (size
& this->loadCommandSizeMask()) != 0 )
2001 throwf("load command #%d has a unaligned size", i
);
2002 const uint8_t* endOfCmd
= ((uint8_t*)cmd
)+cmd
->cmdsize();
2003 if ( endOfCmd
> (uint8_t*)cmdsEnd
)
2004 throwf("load command #%d extends beyond the end of the load commands", i
);
2005 if ( endOfCmd
> endOfFile
)
2006 throwf("load command #%d extends beyond the end of the file", i
);
2007 switch (cmd
->cmd()) {
2010 const macho_symtab_command
<P
>* symtab
= (macho_symtab_command
<P
>*)cmd
;
2011 _symbolCount
= symtab
->nsyms();
2012 _symbols
= (const macho_nlist
<P
>*)(_fileContent
+ symtab
->symoff());
2013 _strings
= (char*)_fileContent
+ symtab
->stroff();
2014 _stringsSize
= symtab
->strsize();
2015 if ( (symtab
->symoff() + _symbolCount
*sizeof(macho_nlist
<P
>)) > _fileLength
)
2016 throw "mach-o symbol table extends beyond end of file";
2017 if ( (_strings
+ _stringsSize
) > (char*)endOfFile
)
2018 throw "mach-o string pool extends beyond end of file";
2019 if ( _indirectTable
== NULL
) {
2020 if ( _undefinedEndIndex
== 0 ) {
2021 _undefinedStartIndex
= 0;
2022 _undefinedEndIndex
= symtab
->nsyms();
2029 const macho_dysymtab_command
<P
>* dsymtab
= (macho_dysymtab_command
<P
>*)cmd
;
2030 _indirectTable
= (uint32_t*)(_fileContent
+ dsymtab
->indirectsymoff());
2031 _indirectTableCount
= dsymtab
->nindirectsyms();
2032 if ( &_indirectTable
[_indirectTableCount
] > (uint32_t*)endOfFile
)
2033 throw "indirect symbol table extends beyond end of file";
2034 _undefinedStartIndex
= dsymtab
->iundefsym();
2035 _undefinedEndIndex
= _undefinedStartIndex
+ dsymtab
->nundefsym();
2041 case LC_DATA_IN_CODE
:
2043 const macho_linkedit_data_command
<P
>* dc
= (macho_linkedit_data_command
<P
>*)cmd
;
2044 _dataInCodeStart
= (macho_data_in_code_entry
<P
>*)(_fileContent
+ dc
->dataoff());
2045 _dataInCodeEnd
= (macho_data_in_code_entry
<P
>*)(_fileContent
+ dc
->dataoff() + dc
->datasize());
2046 if ( _dataInCodeEnd
> (macho_data_in_code_entry
<P
>*)endOfFile
)
2047 throw "LC_DATA_IN_CODE table extends beyond end of file";
2050 case LC_LINKER_OPTION
:
2052 const macho_linker_option_command
<P
>* loc
= (macho_linker_option_command
<P
>*)cmd
;
2053 const char* buffer
= loc
->buffer();
2054 _file
->_linkerOptions
.resize(_file
->_linkerOptions
.size() + 1);
2055 std::vector
<const char*>& vec
= _file
->_linkerOptions
.back();
2056 for (uint32_t j
=0; j
< loc
->count(); ++j
) {
2057 vec
.push_back(buffer
);
2058 buffer
+= strlen(buffer
) + 1;
2060 if ( buffer
> ((char*)cmd
+ loc
->cmdsize()) )
2061 throw "malformed LC_LINKER_OPTION";
2064 case LC_LINKER_OPTIMIZATION_HINTS
:
2066 const macho_linkedit_data_command
<P
>* loh
= (macho_linkedit_data_command
<P
>*)cmd
;
2067 _lohStart
= _fileContent
+ loh
->dataoff();
2068 _lohEnd
= _fileContent
+ loh
->dataoff() + loh
->datasize();
2069 if ( _lohEnd
> endOfFile
)
2070 throw "LC_LINKER_OPTIMIZATION_HINTS table extends beyond end of file";
2073 case LC_VERSION_MIN_MACOSX
:
2074 case LC_VERSION_MIN_IPHONEOS
:
2075 case LC_VERSION_MIN_WATCHOS
:
2076 #if SUPPORT_APPLE_TV
2077 case LC_VERSION_MIN_TVOS
:
2079 if ( ignoreMismatchPlatform
)
2081 _file
->_platform
= cmd
->cmd();
2082 lcPlatform
= Options::platformForLoadCommand(cmd
->cmd());
2083 _file
->_minOSVersion
= ((macho_version_min_command
<P
>*)cmd
)->version();
2085 case macho_segment_command
<P
>::CMD
:
2086 if ( segment
!= NULL
)
2087 throw "more than one LC_SEGMENT found in object file";
2088 segment
= (macho_segment_command
<P
>*)cmd
;
2091 // ignore unknown load commands
2094 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
2095 if ( cmd
> cmdsEnd
)
2096 throwf("malformed mach-o file, load command #%d is outside size of load commands", i
);
2098 // arm/arm64 objects are default to ios platform if not set.
2099 // rdar://problem/21746314
2100 if (lcPlatform
== Options::kPlatformUnknown
&&
2101 (std::is_same
<A
, arm
>::value
|| std::is_same
<A
, arm64
>::value
))
2102 lcPlatform
= Options::kPlatformiOS
;
2104 // Check platform cross-linking.
2105 if ( !ignoreMismatchPlatform
) {
2106 if ( lcPlatform
!= platform
) {
2108 case Options::kPlatformOSX
:
2109 case Options::kPlatformiOS
:
2110 if ( lcPlatform
== Options::kPlatformUnknown
)
2112 // fall through if the Platform is not Unknown
2113 case Options::kPlatformWatchOS
:
2114 // Error when using bitcocde, warning otherwise.
2116 throwf("building for %s%s, but linking in object file built for %s,",
2117 Options::platformName(platform
), (simulator
? " simulator" : ""),
2118 Options::platformName(lcPlatform
));
2120 warning("URGENT: building for %s%s, but linking in object file (%s) built for %s. "
2121 "Note: This will be an error in the future.",
2122 Options::platformName(platform
), (simulator
? " simulator" : ""), path(),
2123 Options::platformName(lcPlatform
));
2125 #if SUPPORT_APPLE_TV
2126 case Options::kPlatform_tvOS
:
2127 // Error when using bitcocde, warning otherwise.
2129 throwf("building for %s%s, but linking in object file built for %s,",
2130 Options::platformName(platform
), (simulator
? " simulator" : ""),
2131 Options::platformName(lcPlatform
));
2133 warning("URGENT: building for %s%s, but linking in object file (%s) built for %s. "
2134 "Note: This will be an error in the future.",
2135 Options::platformName(platform
), (simulator
? " simulator" : ""), path(),
2136 Options::platformName(lcPlatform
));
2139 case Options::kPlatformUnknown
:
2140 // skip if the target platform is unknown
2144 if ( linkMinOSVersion
&& (_file
->_minOSVersion
> linkMinOSVersion
) ) {
2147 versionToString(_file
->_minOSVersion
, t1
);
2148 versionToString(linkMinOSVersion
, t2
);
2149 warning("object file (%s) was built for newer %s version (%s) than being linked (%s)",
2150 _path
, Options::platformName(lcPlatform
), t1
, t2
);
2155 // record range of sections
2156 if ( segment
== NULL
)
2157 throw "missing LC_SEGMENT";
2158 _sectionsStart
= (macho_section
<P
>*)((char*)segment
+ sizeof(macho_segment_command
<P
>));
2159 _machOSectionsCount
= segment
->nsects();
2160 if ( (sizeof(macho_segment_command
<P
>) + _machOSectionsCount
* sizeof(macho_section
<P
>)) > segment
->cmdsize() )
2161 throw "too many sections for size of LC_SEGMENT command";
2165 template <typename A
>
2166 Options::Platform Parser
<A
>::findPlatform(const macho_header
<P
>* header
)
2168 const uint32_t cmd_count
= header
->ncmds();
2169 if ( cmd_count
== 0 )
2170 return Options::kPlatformUnknown
;
2171 const macho_load_command
<P
>* const cmds
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>));
2172 const macho_load_command
<P
>* const cmdsEnd
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>) + header
->sizeofcmds());
2173 const macho_load_command
<P
>* cmd
= cmds
;
2174 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
2175 uint32_t size
= cmd
->cmdsize();
2176 if ( (size
& loadCommandSizeMask()) != 0 )
2177 throwf("load command #%d has a unaligned size", i
);
2178 const uint8_t* endOfCmd
= ((uint8_t*)cmd
)+cmd
->cmdsize();
2179 if ( endOfCmd
> (uint8_t*)cmdsEnd
)
2180 throwf("load command #%d extends beyond the end of the load commands", i
);
2181 switch (cmd
->cmd()) {
2182 case LC_VERSION_MIN_MACOSX
:
2183 return Options::kPlatformOSX
;
2184 case LC_VERSION_MIN_IPHONEOS
:
2185 return Options::kPlatformiOS
;
2187 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
2188 if ( cmd
> cmdsEnd
)
2189 throwf("malformed mach-o file, load command #%d is outside size of load commands", i
);
2191 return Options::kPlatformUnknown
;
2195 template <typename A
>
2196 void Parser
<A
>::prescanSymbolTable()
2198 _tentativeDefinitionCount
= 0;
2199 _absoluteSymbolCount
= 0;
2200 _symbolsInSections
= 0;
2201 _hasDataInCodeLabels
= false;
2202 for (uint32_t i
=0; i
< this->_symbolCount
; ++i
) {
2203 const macho_nlist
<P
>& sym
= symbolFromIndex(i
);
2205 if ( (sym
.n_type() & N_STAB
) != 0 )
2208 // look at undefines
2209 const char* symbolName
= this->nameFromSymbol(sym
);
2210 if ( (sym
.n_type() & N_TYPE
) == N_UNDF
) {
2211 if ( sym
.n_value() != 0 ) {
2212 // count tentative definitions
2213 ++_tentativeDefinitionCount
;
2215 else if ( strncmp(symbolName
, "___dtrace_", 10) == 0 ) {
2216 // any undefined starting with __dtrace_*$ that is not ___dtrace_probe$* or ___dtrace_isenabled$*
2217 // is extra provider info
2218 if ( (strncmp(&symbolName
[10], "probe$", 6) != 0) && (strncmp(&symbolName
[10], "isenabled$", 10) != 0) ) {
2219 _dtraceProviderInfo
.push_back(symbolName
);
2224 else if ( ((sym
.n_type() & N_TYPE
) == N_INDR
) && ((sym
.n_type() & N_EXT
) != 0) ) {
2225 _indirectSymbolCount
++;
2229 // count absolute symbols
2230 if ( (sym
.n_type() & N_TYPE
) == N_ABS
) {
2231 const char* absName
= this->nameFromSymbol(sym
);
2232 // ignore .objc_class_name_* symbols
2233 if ( strncmp(absName
, ".objc_class_name_", 17) == 0 ) {
2237 // ignore .objc_class_name_* symbols
2238 if ( strncmp(absName
, ".objc_category_name_", 20) == 0 )
2240 // ignore empty *.eh symbols
2241 if ( strcmp(&absName
[strlen(absName
)-3], ".eh") == 0 )
2243 ++_absoluteSymbolCount
;
2246 // only look at definitions
2247 if ( (sym
.n_type() & N_TYPE
) != N_SECT
)
2250 // 'L' labels do not denote atom breaks
2251 if ( symbolName
[0] == 'L' ) {
2252 // <rdar://problem/9218847> Formalize data in code with L$start$ labels
2253 if ( strncmp(symbolName
, "L$start$", 8) == 0 )
2254 _hasDataInCodeLabels
= true;
2257 // how many def syms in each section
2258 if ( sym
.n_sect() > _machOSectionsCount
)
2259 throw "bad n_sect in symbol table";
2261 _symbolsInSections
++;
2265 template <typename A
>
2266 void Parser
<A
>::appendAliasAtoms(uint8_t* p
)
2268 for (uint32_t i
=0; i
< this->_symbolCount
; ++i
) {
2269 const macho_nlist
<P
>& sym
= symbolFromIndex(i
);
2271 if ( (sym
.n_type() & N_STAB
) != 0 )
2274 // only look at N_INDR symbols
2275 if ( (sym
.n_type() & N_TYPE
) != N_INDR
)
2278 // skip non-external aliases
2279 if ( (sym
.n_type() & N_EXT
) == 0 )
2282 const char* symbolName
= this->nameFromSymbol(sym
);
2283 const char* aliasOfName
= &_strings
[sym
.n_value()];
2284 bool isHiddenVisibility
= (sym
.n_type() & N_PEXT
);
2285 AliasAtom
* allocatedSpace
= (AliasAtom
*)p
;
2286 new (allocatedSpace
) AliasAtom(symbolName
, isHiddenVisibility
, _file
, aliasOfName
);
2287 p
+= sizeof(AliasAtom
);
2293 template <typename A
>
2294 int Parser
<A
>::sectionIndexSorter(void* extra
, const void* l
, const void* r
)
2296 Parser
<A
>* parser
= (Parser
<A
>*)extra
;
2297 const uint32_t* left
= (uint32_t*)l
;
2298 const uint32_t* right
= (uint32_t*)r
;
2299 const macho_section
<P
>* leftSect
= parser
->machOSectionFromSectionIndex(*left
);
2300 const macho_section
<P
>* rightSect
= parser
->machOSectionFromSectionIndex(*right
);
2302 // can't just return difference because 64-bit diff does not fit in 32-bit return type
2303 int64_t result
= leftSect
->addr() - rightSect
->addr();
2304 if ( result
== 0 ) {
2305 // two sections with same start address
2306 // one with zero size goes first
2307 bool leftEmpty
= ( leftSect
->size() == 0 );
2308 bool rightEmpty
= ( rightSect
->size() == 0 );
2309 if ( leftEmpty
!= rightEmpty
) {
2310 return ( rightEmpty
? 1 : -1 );
2312 if ( !leftEmpty
&& !rightEmpty
)
2313 throwf("overlapping sections");
2314 // both empty, so chose file order
2315 return ( rightSect
- leftSect
);
2317 else if ( result
< 0 )
2323 template <typename A
>
2324 void Parser
<A
>::makeSortedSectionsArray(uint32_t array
[])
2326 const bool log
= false;
2329 fprintf(stderr
, "unsorted sections:\n");
2330 for(unsigned int i
=0; i
< _machOSectionsCount
; ++i
)
2331 fprintf(stderr
, "0x%08llX %s %s\n", _sectionsStart
[i
].addr(), _sectionsStart
[i
].segname(), _sectionsStart
[i
].sectname());
2334 // sort by symbol table address
2335 for (uint32_t i
=0; i
< _machOSectionsCount
; ++i
)
2337 ::qsort_r(array
, _machOSectionsCount
, sizeof(uint32_t), this, §ionIndexSorter
);
2340 fprintf(stderr
, "sorted sections:\n");
2341 for(unsigned int i
=0; i
< _machOSectionsCount
; ++i
)
2342 fprintf(stderr
, "0x%08llX %s %s\n", _sectionsStart
[array
[i
]].addr(), _sectionsStart
[array
[i
]].segname(), _sectionsStart
[array
[i
]].sectname());
2348 template <typename A
>
2349 int Parser
<A
>::symbolIndexSorter(void* extra
, const void* l
, const void* r
)
2351 ParserAndSectionsArray
* extraInfo
= (ParserAndSectionsArray
*)extra
;
2352 Parser
<A
>* parser
= extraInfo
->parser
;
2353 const uint32_t* sortedSectionsArray
= extraInfo
->sortedSectionsArray
;
2354 const uint32_t* left
= (uint32_t*)l
;
2355 const uint32_t* right
= (uint32_t*)r
;
2356 const macho_nlist
<P
>& leftSym
= parser
->symbolFromIndex(*left
);
2357 const macho_nlist
<P
>& rightSym
= parser
->symbolFromIndex(*right
);
2358 // can't just return difference because 64-bit diff does not fit in 32-bit return type
2359 int64_t result
= leftSym
.n_value() - rightSym
.n_value();
2360 if ( result
== 0 ) {
2361 // two symbols with same address
2362 // if in different sections, sort earlier section first
2363 if ( leftSym
.n_sect() != rightSym
.n_sect() ) {
2364 for (uint32_t i
=0; i
< parser
->machOSectionCount(); ++i
) {
2365 if ( sortedSectionsArray
[i
]+1 == leftSym
.n_sect() )
2367 if ( sortedSectionsArray
[i
]+1 == rightSym
.n_sect() )
2371 // two symbols in same section, means one is an alias
2372 // if one is ltmp*, make it an alias (sort first)
2373 const char* leftName
= parser
->nameFromSymbol(leftSym
);
2374 const char* rightName
= parser
->nameFromSymbol(rightSym
);
2375 bool leftIsTmp
= strncmp(leftName
, "ltmp", 4);
2376 bool rightIsTmp
= strncmp(rightName
, "ltmp", 4);
2377 if ( leftIsTmp
!= rightIsTmp
) {
2378 return (rightIsTmp
? -1 : 1);
2381 // if only one is global, make the other an alias (sort first)
2382 if ( (leftSym
.n_type() & N_EXT
) != (rightSym
.n_type() & N_EXT
) ) {
2383 if ( (rightSym
.n_type() & N_EXT
) != 0 )
2388 // if both are global, sort alphabetically. earlier one will be the alias
2389 return ( strcmp(rightName
, leftName
) );
2391 else if ( result
< 0 )
2398 template <typename A
>
2399 void Parser
<A
>::makeSortedSymbolsArray(uint32_t array
[], const uint32_t sectionArray
[])
2401 const bool log
= false;
2403 uint32_t* p
= array
;
2404 for (uint32_t i
=0; i
< this->_symbolCount
; ++i
) {
2405 const macho_nlist
<P
>& sym
= symbolFromIndex(i
);
2407 if ( (sym
.n_type() & N_STAB
) != 0 )
2410 // only look at definitions
2411 if ( (sym
.n_type() & N_TYPE
) != N_SECT
)
2414 // 'L' labels do not denote atom breaks
2415 const char* symbolName
= this->nameFromSymbol(sym
);
2416 if ( symbolName
[0] == 'L' )
2419 // how many def syms in each section
2420 if ( sym
.n_sect() > _machOSectionsCount
)
2421 throw "bad n_sect in symbol table";
2426 assert(p
== &array
[_symbolsInSections
] && "second pass over symbol table yield a different number of symbols");
2428 // sort by symbol table address
2429 ParserAndSectionsArray extra
= { this, sectionArray
};
2430 ::qsort_r(array
, _symbolsInSections
, sizeof(uint32_t), &extra
, &symbolIndexSorter
);
2433 // look for two symbols at same address
2434 _overlappingSymbols
= false;
2435 for (unsigned int i
=1; i
< _symbolsInSections
; ++i
) {
2436 if ( symbolFromIndex(array
[i
-1]).n_value() == symbolFromIndex(array
[i
]).n_value() ) {
2437 //fprintf(stderr, "overlapping symbols at 0x%08llX\n", symbolFromIndex(array[i-1]).n_value());
2438 _overlappingSymbols
= true;
2444 fprintf(stderr
, "sorted symbols:\n");
2445 for(unsigned int i
=0; i
< _symbolsInSections
; ++i
)
2446 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
])) );
2450 template <typename A
>
2451 void Parser
<A
>::makeSections()
2453 // classify each section by type
2454 // compute how many Section objects will be needed and total size for all
2455 unsigned int totalSectionsSize
= 0;
2456 uint8_t machOSectsStorage
[sizeof(MachOSectionAndSectionClass
<P
>)*(_machOSectionsCount
+2)]; // also room for tentative-defs and absolute symbols
2457 // allocate raw storage for all section objects on stack
2458 MachOSectionAndSectionClass
<P
>* machOSects
= (MachOSectionAndSectionClass
<P
>*)machOSectsStorage
;
2459 unsigned int count
= 0;
2460 // local variable for bitcode parsing
2461 const macho_section
<P
>* bitcodeSect
= NULL
;
2462 const macho_section
<P
>* cmdlineSect
= NULL
;
2463 const macho_section
<P
>* swiftCmdlineSect
= NULL
;
2464 const macho_section
<P
>* bundleSect
= NULL
;
2465 bool bitcodeAsm
= false;
2467 for (uint32_t i
=0; i
< _machOSectionsCount
; ++i
) {
2468 const macho_section
<P
>* sect
= &_sectionsStart
[i
];
2469 if ( (sect
->offset() + sect
->size() > _fileLength
) && ((sect
->flags() & SECTION_TYPE
) != S_ZEROFILL
) )
2470 throwf("section %s/%s extends beyond end of file,", sect
->segname(), sect
->sectname());
2472 if ( (sect
->flags() & S_ATTR_DEBUG
) != 0 ) {
2473 if ( strcmp(sect
->segname(), "__DWARF") == 0 ) {
2474 // note that .o file has dwarf
2475 _file
->_debugInfoKind
= ld::relocatable::File::kDebugInfoDwarf
;
2476 // save off iteresting dwarf sections
2477 if ( strcmp(sect
->sectname(), "__debug_info") == 0 )
2478 _file
->_dwarfDebugInfoSect
= sect
;
2479 else if ( strcmp(sect
->sectname(), "__debug_abbrev") == 0 )
2480 _file
->_dwarfDebugAbbrevSect
= sect
;
2481 else if ( strcmp(sect
->sectname(), "__debug_line") == 0 )
2482 _file
->_dwarfDebugLineSect
= sect
;
2483 else if ( strcmp(sect
->sectname(), "__debug_str") == 0 )
2484 _file
->_dwarfDebugStringSect
= sect
;
2485 // linker does not propagate dwarf sections to output file
2488 else if ( strcmp(sect
->segname(), "__LD") == 0 ) {
2489 if ( strncmp(sect
->sectname(), "__compact_unwind", 16) == 0 ) {
2490 machOSects
[count
].sect
= sect
;
2491 totalSectionsSize
+= sizeof(CUSection
<A
>);
2492 machOSects
[count
++].type
= sectionTypeCompactUnwind
;
2497 if ( strcmp(sect
->segname(), "__LLVM") == 0 ) {
2498 // Process bitcode segement
2499 if ( strncmp(sect
->sectname(), "__bitcode", 9) == 0 ) {
2501 } else if ( strncmp(sect
->sectname(), "__cmdline", 9) == 0 ) {
2503 } else if ( strncmp(sect
->sectname(), "__swift_cmdline", 15) == 0 ) {
2504 swiftCmdlineSect
= sect
;
2505 } else if ( strncmp(sect
->sectname(), "__bundle", 8) == 0 ) {
2507 } else if ( strncmp(sect
->sectname(), "__asm", 5) == 0 ) {
2510 // If treat the bitcode as data, continue to parse as a normal section.
2511 if ( !_treateBitcodeAsData
)
2514 // ignore empty __OBJC sections
2515 if ( (sect
->size() == 0) && (strcmp(sect
->segname(), "__OBJC") == 0) )
2517 // objc image info section is really attributes and not content
2518 if ( ((strcmp(sect
->sectname(), "__image_info") == 0) && (strcmp(sect
->segname(), "__OBJC") == 0))
2519 || ((strncmp(sect
->sectname(), "__objc_imageinfo", 16) == 0) && (strcmp(sect
->segname(), "__DATA") == 0)) ) {
2520 // struct objc_image_info {
2521 // uint32_t version; // initially 0
2524 // #define OBJC_IMAGE_SUPPORTS_GC 2
2525 // #define OBJC_IMAGE_GC_ONLY 4
2526 // #define OBJC_IMAGE_IS_SIMULATED 32
2528 const uint32_t* contents
= (uint32_t*)(_file
->fileContent()+sect
->offset());
2529 if ( (sect
->size() >= 8) && (contents
[0] == 0) ) {
2530 uint32_t flags
= E::get32(contents
[1]);
2531 if ( (flags
& 4) == 4 )
2532 _file
->_objConstraint
= ld::File::objcConstraintGC
;
2533 else if ( (flags
& 2) == 2 )
2534 _file
->_objConstraint
= ld::File::objcConstraintRetainReleaseOrGC
;
2535 else if ( (flags
& 32) == 32 )
2536 _file
->_objConstraint
= ld::File::objcConstraintRetainReleaseForSimulator
;
2538 _file
->_objConstraint
= ld::File::objcConstraintRetainRelease
;
2539 _file
->_swiftVersion
= ((flags
>> 8) & 0xFF);
2540 if ( sect
->size() > 8 ) {
2541 warning("section %s/%s has unexpectedly large size %llu in %s",
2542 sect
->segname(), Section
<A
>::makeSectionName(sect
), sect
->size(), _file
->path());
2546 warning("can't parse %s/%s section in %s", sect
->segname(), Section
<A
>::makeSectionName(sect
), _file
->path());
2550 machOSects
[count
].sect
= sect
;
2551 switch ( sect
->flags() & SECTION_TYPE
) {
2552 case S_SYMBOL_STUBS
:
2553 if ( _stubsSectionNum
== 0 ) {
2554 _stubsSectionNum
= i
+1;
2555 _stubsMachOSection
= sect
;
2558 assert(1 && "multiple S_SYMBOL_STUBS sections");
2559 case S_LAZY_SYMBOL_POINTERS
:
2561 case S_4BYTE_LITERALS
:
2562 totalSectionsSize
+= sizeof(Literal4Section
<A
>);
2563 machOSects
[count
++].type
= sectionTypeLiteral4
;
2565 case S_8BYTE_LITERALS
:
2566 totalSectionsSize
+= sizeof(Literal8Section
<A
>);
2567 machOSects
[count
++].type
= sectionTypeLiteral8
;
2569 case S_16BYTE_LITERALS
:
2570 totalSectionsSize
+= sizeof(Literal16Section
<A
>);
2571 machOSects
[count
++].type
= sectionTypeLiteral16
;
2573 case S_NON_LAZY_SYMBOL_POINTERS
:
2574 totalSectionsSize
+= sizeof(NonLazyPointerSection
<A
>);
2575 machOSects
[count
++].type
= sectionTypeNonLazy
;
2577 case S_THREAD_LOCAL_VARIABLE_POINTERS
:
2578 totalSectionsSize
+= sizeof(TLVPointerSection
<A
>);
2579 machOSects
[count
++].type
= sectionTypeTLVPointers
;
2581 case S_LITERAL_POINTERS
:
2582 if ( (strcmp(sect
->segname(), "__OBJC") == 0) && (strcmp(sect
->sectname(), "__cls_refs") == 0) ) {
2583 totalSectionsSize
+= sizeof(Objc1ClassReferences
<A
>);
2584 machOSects
[count
++].type
= sectionTypeObjC1ClassRefs
;
2587 totalSectionsSize
+= sizeof(PointerToCStringSection
<A
>);
2588 machOSects
[count
++].type
= sectionTypeCStringPointer
;
2591 case S_CSTRING_LITERALS
:
2592 totalSectionsSize
+= sizeof(CStringSection
<A
>);
2593 machOSects
[count
++].type
= sectionTypeCString
;
2595 case S_MOD_INIT_FUNC_POINTERS
:
2596 case S_MOD_TERM_FUNC_POINTERS
:
2597 case S_THREAD_LOCAL_INIT_FUNCTION_POINTERS
:
2602 case S_THREAD_LOCAL_REGULAR
:
2603 case S_THREAD_LOCAL_ZEROFILL
:
2604 if ( (strcmp(sect
->segname(), "__TEXT") == 0) && (strcmp(sect
->sectname(), "__eh_frame") == 0) ) {
2605 totalSectionsSize
+= sizeof(CFISection
<A
>);
2606 machOSects
[count
++].type
= sectionTypeCFI
;
2608 else if ( (strcmp(sect
->segname(), "__DATA") == 0) && (strcmp(sect
->sectname(), "__cfstring") == 0) ) {
2609 totalSectionsSize
+= sizeof(CFStringSection
<A
>);
2610 machOSects
[count
++].type
= sectionTypeCFString
;
2612 else if ( (strcmp(sect
->segname(), "__TEXT") == 0) && (strcmp(sect
->sectname(), "__ustring") == 0) ) {
2613 totalSectionsSize
+= sizeof(UTF16StringSection
<A
>);
2614 machOSects
[count
++].type
= sectionTypeUTF16Strings
;
2616 else if ( (strcmp(sect
->segname(), "__DATA") == 0) && (strncmp(sect
->sectname(), "__objc_classrefs", 16) == 0) ) {
2617 totalSectionsSize
+= sizeof(ObjC2ClassRefsSection
<A
>);
2618 machOSects
[count
++].type
= sectionTypeObjC2ClassRefs
;
2620 else if ( (strcmp(sect
->segname(), "__DATA") == 0) && (strcmp(sect
->sectname(), "__objc_catlist") == 0) ) {
2621 totalSectionsSize
+= sizeof(ObjC2CategoryListSection
<A
>);
2622 machOSects
[count
++].type
= typeObjC2CategoryList
;
2624 else if ( _AppleObjc
&& (strcmp(sect
->segname(), "__OBJC") == 0) && (strcmp(sect
->sectname(), "__class") == 0) ) {
2625 totalSectionsSize
+= sizeof(ObjC1ClassSection
<A
>);
2626 machOSects
[count
++].type
= sectionTypeObjC1Classes
;
2629 totalSectionsSize
+= sizeof(SymboledSection
<A
>);
2630 machOSects
[count
++].type
= sectionTypeSymboled
;
2633 case S_THREAD_LOCAL_VARIABLES
:
2634 totalSectionsSize
+= sizeof(TLVDefsSection
<A
>);
2635 machOSects
[count
++].type
= sectionTypeTLVDefs
;
2638 throwf("unknown section type %d", sect
->flags() & SECTION_TYPE
);
2643 if ( bitcodeSect
!= NULL
) {
2644 if ( cmdlineSect
!= NULL
)
2645 _file
->_bitcode
= std::unique_ptr
<ld::Bitcode
>(new ld::ClangBitcode(&_fileContent
[bitcodeSect
->offset()], bitcodeSect
->size(),
2646 &_fileContent
[cmdlineSect
->offset()], cmdlineSect
->size()));
2647 else if ( swiftCmdlineSect
!= NULL
)
2648 _file
->_bitcode
= std::unique_ptr
<ld::Bitcode
>(new ld::SwiftBitcode(&_fileContent
[bitcodeSect
->offset()], bitcodeSect
->size(),
2649 &_fileContent
[swiftCmdlineSect
->offset()], swiftCmdlineSect
->size()));
2651 throwf("Object file with bitcode missing cmdline options: %s", _file
->path());
2653 else if ( bundleSect
!= NULL
)
2654 _file
->_bitcode
= std::unique_ptr
<ld::Bitcode
>(new ld::BundleBitcode(&_fileContent
[bundleSect
->offset()], bundleSect
->size()));
2655 else if ( bitcodeAsm
)
2656 _file
->_bitcode
= std::unique_ptr
<ld::Bitcode
>(new ld::AsmBitcode(_fileContent
, _fileLength
));
2658 // sort by address (mach-o object files don't aways have sections sorted)
2659 ::qsort(machOSects
, count
, sizeof(MachOSectionAndSectionClass
<P
>), MachOSectionAndSectionClass
<P
>::sorter
);
2661 // we will synthesize a dummy Section<A> object for tentative definitions
2662 if ( _tentativeDefinitionCount
> 0 ) {
2663 totalSectionsSize
+= sizeof(TentativeDefinitionSection
<A
>);
2664 machOSects
[count
++].type
= sectionTypeTentativeDefinitions
;
2667 // we will synthesize a dummy Section<A> object for Absolute symbols
2668 if ( _absoluteSymbolCount
> 0 ) {
2669 totalSectionsSize
+= sizeof(AbsoluteSymbolSection
<A
>);
2670 machOSects
[count
++].type
= sectionTypeAbsoluteSymbols
;
2673 // allocate one block for all Section objects as well as pointers to each
2674 uint8_t* space
= new uint8_t[totalSectionsSize
+count
*sizeof(Section
<A
>*)];
2675 _file
->_sectionsArray
= (Section
<A
>**)space
;
2676 _file
->_sectionsArrayCount
= count
;
2677 Section
<A
>** objects
= _file
->_sectionsArray
;
2678 space
+= count
*sizeof(Section
<A
>*);
2679 for (uint32_t i
=0; i
< count
; ++i
) {
2680 switch ( machOSects
[i
].type
) {
2681 case sectionTypeIgnore
:
2683 case sectionTypeLiteral4
:
2684 *objects
++ = new (space
) Literal4Section
<A
>(*this, *_file
, machOSects
[i
].sect
);
2685 space
+= sizeof(Literal4Section
<A
>);
2687 case sectionTypeLiteral8
:
2688 *objects
++ = new (space
) Literal8Section
<A
>(*this, *_file
, machOSects
[i
].sect
);
2689 space
+= sizeof(Literal8Section
<A
>);
2691 case sectionTypeLiteral16
:
2692 *objects
++ = new (space
) Literal16Section
<A
>(*this, *_file
, machOSects
[i
].sect
);
2693 space
+= sizeof(Literal16Section
<A
>);
2695 case sectionTypeNonLazy
:
2696 *objects
++ = new (space
) NonLazyPointerSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2697 space
+= sizeof(NonLazyPointerSection
<A
>);
2699 case sectionTypeTLVPointers
:
2700 *objects
++ = new (space
) TLVPointerSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2701 space
+= sizeof(TLVPointerSection
<A
>);
2703 case sectionTypeCFI
:
2704 _EHFrameSection
= new (space
) CFISection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2705 *objects
++ = _EHFrameSection
;
2706 space
+= sizeof(CFISection
<A
>);
2708 case sectionTypeCString
:
2709 *objects
++ = new (space
) CStringSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2710 space
+= sizeof(CStringSection
<A
>);
2712 case sectionTypeCStringPointer
:
2713 *objects
++ = new (space
) PointerToCStringSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2714 space
+= sizeof(PointerToCStringSection
<A
>);
2716 case sectionTypeObjC1ClassRefs
:
2717 *objects
++ = new (space
) Objc1ClassReferences
<A
>(*this, *_file
, machOSects
[i
].sect
);
2718 space
+= sizeof(Objc1ClassReferences
<A
>);
2720 case sectionTypeUTF16Strings
:
2721 *objects
++ = new (space
) UTF16StringSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2722 space
+= sizeof(UTF16StringSection
<A
>);
2724 case sectionTypeCFString
:
2725 *objects
++ = new (space
) CFStringSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2726 space
+= sizeof(CFStringSection
<A
>);
2728 case sectionTypeObjC2ClassRefs
:
2729 *objects
++ = new (space
) ObjC2ClassRefsSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2730 space
+= sizeof(ObjC2ClassRefsSection
<A
>);
2732 case typeObjC2CategoryList
:
2733 *objects
++ = new (space
) ObjC2CategoryListSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2734 space
+= sizeof(ObjC2CategoryListSection
<A
>);
2736 case sectionTypeObjC1Classes
:
2737 *objects
++ = new (space
) ObjC1ClassSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2738 space
+= sizeof(ObjC1ClassSection
<A
>);
2740 case sectionTypeSymboled
:
2741 *objects
++ = new (space
) SymboledSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2742 space
+= sizeof(SymboledSection
<A
>);
2744 case sectionTypeTLVDefs
:
2745 *objects
++ = new (space
) TLVDefsSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2746 space
+= sizeof(TLVDefsSection
<A
>);
2748 case sectionTypeCompactUnwind
:
2749 _compactUnwindSection
= new (space
) CUSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2750 *objects
++ = _compactUnwindSection
;
2751 space
+= sizeof(CUSection
<A
>);
2753 case sectionTypeTentativeDefinitions
:
2754 *objects
++ = new (space
) TentativeDefinitionSection
<A
>(*this, *_file
);
2755 space
+= sizeof(TentativeDefinitionSection
<A
>);
2757 case sectionTypeAbsoluteSymbols
:
2758 _absoluteSection
= new (space
) AbsoluteSymbolSection
<A
>(*this, *_file
);
2759 *objects
++ = _absoluteSection
;
2760 space
+= sizeof(AbsoluteSymbolSection
<A
>);
2763 throw "internal error uknown SectionType";
2769 template <typename A
>
2770 Section
<A
>* Parser
<A
>::sectionForAddress(typename
A::P::uint_t addr
)
2772 for (uint32_t i
=0; i
< _file
->_sectionsArrayCount
; ++i
) {
2773 const macho_section
<typename
A::P
>* sect
= _file
->_sectionsArray
[i
]->machoSection();
2774 // TentativeDefinitionSection and AbsoluteSymbolSection have no mach-o section
2775 if ( sect
!= NULL
) {
2776 if ( (sect
->addr() <= addr
) && (addr
< (sect
->addr()+sect
->size())) ) {
2777 return _file
->_sectionsArray
[i
];
2781 // not strictly in any section
2782 // may be in a zero length section
2783 for (uint32_t i
=0; i
< _file
->_sectionsArrayCount
; ++i
) {
2784 const macho_section
<typename
A::P
>* sect
= _file
->_sectionsArray
[i
]->machoSection();
2785 // TentativeDefinitionSection and AbsoluteSymbolSection have no mach-o section
2786 if ( sect
!= NULL
) {
2787 if ( (sect
->addr() == addr
) && (sect
->size() == 0) ) {
2788 return _file
->_sectionsArray
[i
];
2793 throwf("sectionForAddress(0x%llX) address not in any section", (uint64_t)addr
);
2796 template <typename A
>
2797 Section
<A
>* Parser
<A
>::sectionForNum(unsigned int num
)
2799 for (uint32_t i
=0; i
< _file
->_sectionsArrayCount
; ++i
) {
2800 const macho_section
<typename
A::P
>* sect
= _file
->_sectionsArray
[i
]->machoSection();
2801 // TentativeDefinitionSection and AbsoluteSymbolSection have no mach-o section
2802 if ( sect
!= NULL
) {
2803 if ( num
== (unsigned int)((sect
- _sectionsStart
)+1) )
2804 return _file
->_sectionsArray
[i
];
2807 throwf("sectionForNum(%u) section number not for any section", num
);
2810 template <typename A
>
2811 Atom
<A
>* Parser
<A
>::findAtomByAddress(pint_t addr
)
2813 Section
<A
>* section
= this->sectionForAddress(addr
);
2814 return section
->findAtomByAddress(addr
);
2817 template <typename A
>
2818 Atom
<A
>* Parser
<A
>::findAtomByAddressOrNullIfStub(pint_t addr
)
2820 if ( hasStubsSection() && (_stubsMachOSection
->addr() <= addr
) && (addr
< (_stubsMachOSection
->addr()+_stubsMachOSection
->size())) )
2822 return findAtomByAddress(addr
);
2825 template <typename A
>
2826 Atom
<A
>* Parser
<A
>::findAtomByAddressOrLocalTargetOfStub(pint_t addr
, uint32_t* offsetInAtom
)
2828 if ( hasStubsSection() && (_stubsMachOSection
->addr() <= addr
) && (addr
< (_stubsMachOSection
->addr()+_stubsMachOSection
->size())) ) {
2829 // target is a stub, remove indirection
2830 uint32_t symbolIndex
= this->symbolIndexFromIndirectSectionAddress(addr
, _stubsMachOSection
);
2831 assert(symbolIndex
!= INDIRECT_SYMBOL_LOCAL
);
2832 const macho_nlist
<P
>& sym
= this->symbolFromIndex(symbolIndex
);
2833 // can't be to external weak symbol
2834 assert( (this->combineFromSymbol(sym
) != ld::Atom::combineByName
) || (this->scopeFromSymbol(sym
) != ld::Atom::scopeGlobal
) );
2836 return this->findAtomByName(this->nameFromSymbol(sym
));
2838 Atom
<A
>* target
= this->findAtomByAddress(addr
);
2839 *offsetInAtom
= addr
- target
->_objAddress
;
2843 template <typename A
>
2844 Atom
<A
>* Parser
<A
>::findAtomByName(const char* name
)
2846 uint8_t* p
= _file
->_atomsArray
;
2847 for(int i
=_file
->_atomsArrayCount
; i
> 0; --i
) {
2848 Atom
<A
>* atom
= (Atom
<A
>*)p
;
2849 if ( strcmp(name
, atom
->name()) == 0 )
2851 p
+= sizeof(Atom
<A
>);
2856 template <typename A
>
2857 void Parser
<A
>::findTargetFromAddress(pint_t addr
, TargetDesc
& target
)
2859 if ( hasStubsSection() && (_stubsMachOSection
->addr() <= addr
) && (addr
< (_stubsMachOSection
->addr()+_stubsMachOSection
->size())) ) {
2860 // target is a stub, remove indirection
2861 uint32_t symbolIndex
= this->symbolIndexFromIndirectSectionAddress(addr
, _stubsMachOSection
);
2862 assert(symbolIndex
!= INDIRECT_SYMBOL_LOCAL
);
2863 const macho_nlist
<P
>& sym
= this->symbolFromIndex(symbolIndex
);
2865 target
.name
= this->nameFromSymbol(sym
);
2866 target
.weakImport
= this->weakImportFromSymbol(sym
);
2870 Section
<A
>* section
= this->sectionForAddress(addr
);
2871 target
.atom
= section
->findAtomByAddress(addr
);
2872 target
.addend
= addr
- target
.atom
->_objAddress
;
2873 target
.weakImport
= false;
2877 template <typename A
>
2878 void Parser
<A
>::findTargetFromAddress(pint_t baseAddr
, pint_t addr
, TargetDesc
& target
)
2880 findTargetFromAddress(baseAddr
, target
);
2881 target
.addend
= addr
- target
.atom
->_objAddress
;
2884 template <typename A
>
2885 void Parser
<A
>::findTargetFromAddressAndSectionNum(pint_t addr
, unsigned int sectNum
, TargetDesc
& target
)
2887 if ( sectNum
== R_ABS
) {
2888 // target is absolute symbol that corresponds to addr
2889 if ( _absoluteSection
!= NULL
) {
2890 target
.atom
= _absoluteSection
->findAbsAtomForValue(addr
);
2891 if ( target
.atom
!= NULL
) {
2893 target
.weakImport
= false;
2898 throwf("R_ABS reloc but no absolute symbol at target address");
2901 if ( hasStubsSection() && (stubsSectionNum() == sectNum
) ) {
2902 // target is a stub, remove indirection
2903 uint32_t symbolIndex
= this->symbolIndexFromIndirectSectionAddress(addr
, _stubsMachOSection
);
2904 assert(symbolIndex
!= INDIRECT_SYMBOL_LOCAL
);
2905 const macho_nlist
<P
>& sym
= this->symbolFromIndex(symbolIndex
);
2906 // use direct reference when stub is to a static function
2907 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && (((sym
.n_type() & N_EXT
) == 0) || (this->nameFromSymbol(sym
)[0] == 'L')) ) {
2908 this->findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
2912 target
.name
= this->nameFromSymbol(sym
);
2913 target
.weakImport
= this->weakImportFromSymbol(sym
);
2918 Section
<A
>* section
= this->sectionForNum(sectNum
);
2919 target
.atom
= section
->findAtomByAddress(addr
);
2920 if ( target
.atom
== NULL
) {
2921 typedef typename
A::P::sint_t sint_t
;
2922 sint_t a
= (sint_t
)addr
;
2923 sint_t sectStart
= (sint_t
)(section
->machoSection()->addr());
2924 sint_t sectEnd
= sectStart
+ section
->machoSection()->size();
2925 if ( a
< sectStart
) {
2926 // target address is before start of section, so must be negative addend
2927 target
.atom
= section
->findAtomByAddress(sectStart
);
2928 target
.addend
= a
- sectStart
;
2929 target
.weakImport
= false;
2933 else if ( a
>= sectEnd
) {
2934 target
.atom
= section
->findAtomByAddress(sectEnd
-1);
2935 target
.addend
= a
- sectEnd
;
2936 target
.weakImport
= false;
2941 assert(target
.atom
!= NULL
);
2942 target
.addend
= addr
- target
.atom
->_objAddress
;
2943 target
.weakImport
= false;
2947 template <typename A
>
2948 void Parser
<A
>::addDtraceExtraInfos(const SourceLocation
& src
, const char* providerName
)
2950 // for every ___dtrace_stability$* and ___dtrace_typedefs$* undefine with
2951 // a matching provider name, add a by-name kDtraceTypeReference at probe site
2952 const char* dollar
= strchr(providerName
, '$');
2953 if ( dollar
!= NULL
) {
2954 int providerNameLen
= dollar
-providerName
+1;
2955 for ( std::vector
<const char*>::iterator it
= _dtraceProviderInfo
.begin(); it
!= _dtraceProviderInfo
.end(); ++it
) {
2956 const char* typeDollar
= strchr(*it
, '$');
2957 if ( typeDollar
!= NULL
) {
2958 if ( strncmp(typeDollar
+1, providerName
, providerNameLen
) == 0 ) {
2959 addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindDtraceExtra
,false, *it
);
2966 template <typename A
>
2967 const char* Parser
<A
>::scanSymbolTableForAddress(uint64_t addr
)
2969 uint64_t closestSymAddr
= 0;
2970 const char* closestSymName
= NULL
;
2971 for (uint32_t i
=0; i
< this->_symbolCount
; ++i
) {
2972 const macho_nlist
<P
>& sym
= symbolFromIndex(i
);
2974 if ( (sym
.n_type() & N_STAB
) != 0 )
2977 // only look at definitions
2978 if ( (sym
.n_type() & N_TYPE
) != N_SECT
)
2981 // return with exact match
2982 if ( sym
.n_value() == addr
) {
2983 const char* name
= nameFromSymbol(sym
);
2984 if ( strncmp(name
, "ltmp", 4) != 0 )
2986 // treat 'ltmp*' labels as close match
2987 closestSymAddr
= sym
.n_value();
2988 closestSymName
= name
;
2991 // record closest seen so far
2992 if ( (sym
.n_value() < addr
) && ((sym
.n_value() > closestSymAddr
) || (closestSymName
== NULL
)) )
2993 closestSymName
= nameFromSymbol(sym
);
2996 return (closestSymName
!= NULL
) ? closestSymName
: "unknown";
3000 template <typename A
>
3001 void Parser
<A
>::addFixups(const SourceLocation
& src
, ld::Fixup::Kind setKind
, const TargetDesc
& target
)
3003 // some fixup pairs can be combined
3004 ld::Fixup::Cluster cl
= ld::Fixup::k1of3
;
3005 ld::Fixup::Kind firstKind
= ld::Fixup::kindSetTargetAddress
;
3006 bool combined
= false;
3007 if ( target
.addend
== 0 ) {
3008 cl
= ld::Fixup::k1of1
;
3010 switch ( setKind
) {
3011 case ld::Fixup::kindStoreLittleEndian32
:
3012 firstKind
= ld::Fixup::kindStoreTargetAddressLittleEndian32
;
3014 case ld::Fixup::kindStoreLittleEndian64
:
3015 firstKind
= ld::Fixup::kindStoreTargetAddressLittleEndian64
;
3017 case ld::Fixup::kindStoreBigEndian32
:
3018 firstKind
= ld::Fixup::kindStoreTargetAddressBigEndian32
;
3020 case ld::Fixup::kindStoreBigEndian64
:
3021 firstKind
= ld::Fixup::kindStoreTargetAddressBigEndian64
;
3023 case ld::Fixup::kindStoreX86BranchPCRel32
:
3024 firstKind
= ld::Fixup::kindStoreTargetAddressX86BranchPCRel32
;
3026 case ld::Fixup::kindStoreX86PCRel32
:
3027 firstKind
= ld::Fixup::kindStoreTargetAddressX86PCRel32
;
3029 case ld::Fixup::kindStoreX86PCRel32GOTLoad
:
3030 firstKind
= ld::Fixup::kindStoreTargetAddressX86PCRel32GOTLoad
;
3032 case ld::Fixup::kindStoreX86PCRel32TLVLoad
:
3033 firstKind
= ld::Fixup::kindStoreTargetAddressX86PCRel32TLVLoad
;
3035 case ld::Fixup::kindStoreX86Abs32TLVLoad
:
3036 firstKind
= ld::Fixup::kindStoreTargetAddressX86Abs32TLVLoad
;
3038 case ld::Fixup::kindStoreARMBranch24
:
3039 firstKind
= ld::Fixup::kindStoreTargetAddressARMBranch24
;
3041 case ld::Fixup::kindStoreThumbBranch22
:
3042 firstKind
= ld::Fixup::kindStoreTargetAddressThumbBranch22
;
3044 #if SUPPORT_ARCH_arm64
3045 case ld::Fixup::kindStoreARM64Branch26
:
3046 firstKind
= ld::Fixup::kindStoreTargetAddressARM64Branch26
;
3048 case ld::Fixup::kindStoreARM64Page21
:
3049 firstKind
= ld::Fixup::kindStoreTargetAddressARM64Page21
;
3051 case ld::Fixup::kindStoreARM64PageOff12
:
3052 firstKind
= ld::Fixup::kindStoreTargetAddressARM64PageOff12
;
3054 case ld::Fixup::kindStoreARM64GOTLoadPage21
:
3055 firstKind
= ld::Fixup::kindStoreTargetAddressARM64GOTLoadPage21
;
3057 case ld::Fixup::kindStoreARM64GOTLoadPageOff12
:
3058 firstKind
= ld::Fixup::kindStoreTargetAddressARM64GOTLoadPageOff12
;
3060 case ld::Fixup::kindStoreARM64TLVPLoadPage21
:
3061 firstKind
= ld::Fixup::kindStoreTargetAddressARM64TLVPLoadPage21
;
3063 case ld::Fixup::kindStoreARM64TLVPLoadPageOff12
:
3064 firstKind
= ld::Fixup::kindStoreTargetAddressARM64TLVPLoadPageOff12
;
3069 cl
= ld::Fixup::k1of2
;
3074 if ( target
.atom
!= NULL
) {
3075 if ( target
.atom
->scope() == ld::Atom::scopeTranslationUnit
) {
3076 addFixup(src
, cl
, firstKind
, target
.atom
);
3078 else if ( (target
.atom
->combine() == ld::Atom::combineByNameAndContent
) || (target
.atom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
3079 addFixup(src
, cl
, firstKind
, ld::Fixup::bindingByContentBound
, target
.atom
);
3081 else if ( (src
.atom
->section().type() == ld::Section::typeCFString
) && (src
.offsetInAtom
!= 0) ) {
3082 // backing string in CFStrings should always be direct
3083 addFixup(src
, cl
, firstKind
, target
.atom
);
3085 else if ( (src
.atom
== target
.atom
) && (target
.atom
->combine() == ld::Atom::combineByName
) ) {
3086 // reference to self should always be direct
3087 addFixup(src
, cl
, firstKind
, target
.atom
);
3090 // change direct fixup to by-name fixup
3091 addFixup(src
, cl
, firstKind
, false, target
.atom
->name());
3095 addFixup(src
, cl
, firstKind
, target
.weakImport
, target
.name
);
3097 if ( target
.addend
== 0 ) {
3099 addFixup(src
, ld::Fixup::k2of2
, setKind
);
3102 addFixup(src
, ld::Fixup::k2of3
, ld::Fixup::kindAddAddend
, target
.addend
);
3103 addFixup(src
, ld::Fixup::k3of3
, setKind
);
3107 template <typename A
>
3108 void Parser
<A
>::addFixups(const SourceLocation
& src
, ld::Fixup::Kind kind
, const TargetDesc
& target
, const TargetDesc
& picBase
)
3110 ld::Fixup::Cluster cl
= (target
.addend
== 0) ? ld::Fixup::k1of4
: ld::Fixup::k1of5
;
3111 if ( target
.atom
!= NULL
) {
3112 if ( target
.atom
->scope() == ld::Atom::scopeTranslationUnit
) {
3113 addFixup(src
, cl
, ld::Fixup::kindSetTargetAddress
, target
.atom
);
3115 else if ( (target
.atom
->combine() == ld::Atom::combineByNameAndContent
) || (target
.atom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
3116 addFixup(src
, cl
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, target
.atom
);
3119 addFixup(src
, cl
, ld::Fixup::kindSetTargetAddress
, false, target
.atom
->name());
3123 addFixup(src
, cl
, ld::Fixup::kindSetTargetAddress
, target
.weakImport
, target
.name
);
3125 if ( target
.addend
== 0 ) {
3126 assert(picBase
.atom
!= NULL
);
3127 addFixup(src
, ld::Fixup::k2of4
, ld::Fixup::kindSubtractTargetAddress
, picBase
.atom
);
3128 addFixup(src
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractAddend
, picBase
.addend
);
3129 addFixup(src
, ld::Fixup::k4of4
, kind
);
3132 addFixup(src
, ld::Fixup::k2of5
, ld::Fixup::kindAddAddend
, target
.addend
);
3133 addFixup(src
, ld::Fixup::k3of5
, ld::Fixup::kindSubtractTargetAddress
, picBase
.atom
);
3134 addFixup(src
, ld::Fixup::k4of5
, ld::Fixup::kindSubtractAddend
, picBase
.addend
);
3135 addFixup(src
, ld::Fixup::k5of5
, kind
);
3141 template <typename A
>
3142 uint32_t TentativeDefinitionSection
<A
>::computeAtomCount(class Parser
<A
>& parser
,
3143 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
3144 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
3146 return parser
.tentativeDefinitionCount();
3149 template <typename A
>
3150 uint32_t TentativeDefinitionSection
<A
>::appendAtoms(class Parser
<A
>& parser
, uint8_t* p
,
3151 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
3152 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
3154 this->_beginAtoms
= (Atom
<A
>*)p
;
3156 for (uint32_t i
=parser
.undefinedStartIndex(); i
< parser
.undefinedEndIndex(); ++i
) {
3157 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(i
);
3158 if ( ((sym
.n_type() & N_TYPE
) == N_UNDF
) && (sym
.n_value() != 0) ) {
3159 uint64_t size
= sym
.n_value();
3160 uint8_t alignP2
= GET_COMM_ALIGN(sym
.n_desc());
3161 if ( alignP2
== 0 ) {
3162 // common symbols align to their size
3163 // that is, a 4-byte common aligns to 4-bytes
3164 // if this size is not a power of two,
3165 // then round up to the next power of two
3166 alignP2
= 63 - (uint8_t)__builtin_clzll(size
);
3167 if ( size
!= (1ULL << alignP2
) )
3170 // limit alignment of extremely large commons to 2^15 bytes (8-page)
3171 if ( alignP2
> parser
.maxDefaultCommonAlignment() )
3172 alignP2
= parser
.maxDefaultCommonAlignment();
3173 Atom
<A
>* allocatedSpace
= (Atom
<A
>*)p
;
3174 new (allocatedSpace
) Atom
<A
>(*this, parser
.nameFromSymbol(sym
), (pint_t
)ULLONG_MAX
, size
,
3175 ld::Atom::definitionTentative
, ld::Atom::combineByName
,
3176 parser
.scopeFromSymbol(sym
), ld::Atom::typeZeroFill
, ld::Atom::symbolTableIn
,
3177 parser
.dontDeadStripFromSymbol(sym
), false, false, ld::Atom::Alignment(alignP2
) );
3178 p
+= sizeof(Atom
<A
>);
3182 this->_endAtoms
= (Atom
<A
>*)p
;
3187 template <typename A
>
3188 uint32_t AbsoluteSymbolSection
<A
>::computeAtomCount(class Parser
<A
>& parser
,
3189 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
3190 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
3192 return parser
.absoluteSymbolCount();
3195 template <typename A
>
3196 uint32_t AbsoluteSymbolSection
<A
>::appendAtoms(class Parser
<A
>& parser
, uint8_t* p
,
3197 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
3198 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
3200 this->_beginAtoms
= (Atom
<A
>*)p
;
3202 for (uint32_t i
=0; i
< parser
.symbolCount(); ++i
) {
3203 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(i
);
3204 if ( (sym
.n_type() & N_TYPE
) != N_ABS
)
3206 const char* absName
= parser
.nameFromSymbol(sym
);
3207 // ignore .objc_class_name_* symbols
3208 if ( strncmp(absName
, ".objc_class_name_", 17) == 0 )
3210 // ignore .objc_class_name_* symbols
3211 if ( strncmp(absName
, ".objc_category_name_", 20) == 0 )
3213 // ignore empty *.eh symbols
3214 if ( strcmp(&absName
[strlen(absName
)-3], ".eh") == 0 )
3217 Atom
<A
>* allocatedSpace
= (Atom
<A
>*)p
;
3218 new (allocatedSpace
) Atom
<A
>(*this, parser
, sym
, 0);
3219 p
+= sizeof(Atom
<A
>);
3222 this->_endAtoms
= (Atom
<A
>*)p
;
3226 template <typename A
>
3227 Atom
<A
>* AbsoluteSymbolSection
<A
>::findAbsAtomForValue(typename
A::P::uint_t value
)
3229 Atom
<A
>* end
= this->_endAtoms
;
3230 for(Atom
<A
>* p
= this->_beginAtoms
; p
< end
; ++p
) {
3231 if ( p
->_objAddress
== value
)
3238 template <typename A
>
3239 uint32_t Parser
<A
>::indirectSymbol(uint32_t indirectIndex
)
3241 if ( indirectIndex
>= _indirectTableCount
)
3242 throw "indirect symbol index out of range";
3243 return E::get32(_indirectTable
[indirectIndex
]);
3246 template <typename A
>
3247 const macho_nlist
<typename
A::P
>& Parser
<A
>::symbolFromIndex(uint32_t index
)
3249 if ( index
> _symbolCount
)
3250 throw "symbol index out of range";
3251 return _symbols
[index
];
3254 template <typename A
>
3255 const macho_section
<typename
A::P
>* Parser
<A
>::machOSectionFromSectionIndex(uint32_t index
)
3257 if ( index
>= _machOSectionsCount
)
3258 throw "section index out of range";
3259 return &_sectionsStart
[index
];
3262 template <typename A
>
3263 uint32_t Parser
<A
>::symbolIndexFromIndirectSectionAddress(pint_t addr
, const macho_section
<P
>* sect
)
3265 uint32_t elementSize
= 0;
3266 switch ( sect
->flags() & SECTION_TYPE
) {
3267 case S_SYMBOL_STUBS
:
3268 elementSize
= sect
->reserved2();
3270 case S_LAZY_SYMBOL_POINTERS
:
3271 case S_NON_LAZY_SYMBOL_POINTERS
:
3272 elementSize
= sizeof(pint_t
);
3275 throw "section does not use inirect symbol table";
3277 uint32_t indexInSection
= (addr
- sect
->addr()) / elementSize
;
3278 uint32_t indexIntoIndirectTable
= sect
->reserved1() + indexInSection
;
3279 return this->indirectSymbol(indexIntoIndirectTable
);
3284 template <typename A
>
3285 const char* Parser
<A
>::nameFromSymbol(const macho_nlist
<P
>& sym
)
3287 return &_strings
[sym
.n_strx()];
3290 template <typename A
>
3291 ld::Atom::Scope Parser
<A
>::scopeFromSymbol(const macho_nlist
<P
>& sym
)
3293 if ( (sym
.n_type() & N_EXT
) == 0 )
3294 return ld::Atom::scopeTranslationUnit
;
3295 else if ( (sym
.n_type() & N_PEXT
) != 0 )
3296 return ld::Atom::scopeLinkageUnit
;
3297 else if ( this->nameFromSymbol(sym
)[0] == 'l' ) // since all 'l' symbols will be remove, don't make them global
3298 return ld::Atom::scopeLinkageUnit
;
3300 return ld::Atom::scopeGlobal
;
3303 template <typename A
>
3304 ld::Atom::Definition Parser
<A
>::definitionFromSymbol(const macho_nlist
<P
>& sym
)
3306 switch ( sym
.n_type() & N_TYPE
) {
3308 return ld::Atom::definitionAbsolute
;
3310 return ld::Atom::definitionRegular
;
3312 if ( sym
.n_value() != 0 )
3313 return ld::Atom::definitionTentative
;
3315 throw "definitionFromSymbol() bad symbol";
3318 template <typename A
>
3319 ld::Atom::Combine Parser
<A
>::combineFromSymbol(const macho_nlist
<P
>& sym
)
3321 if ( sym
.n_desc() & N_WEAK_DEF
)
3322 return ld::Atom::combineByName
;
3324 return ld::Atom::combineNever
;
3328 template <typename A
>
3329 ld::Atom::SymbolTableInclusion Parser
<A
>::inclusionFromSymbol(const macho_nlist
<P
>& sym
)
3331 const char* symbolName
= nameFromSymbol(sym
);
3332 // labels beginning with 'l' (lowercase ell) are automatically removed in final linked images <rdar://problem/4571042>
3333 // labels beginning with 'L' should have been stripped by the assembler, so are stripped now
3334 if ( sym
.n_desc() & REFERENCED_DYNAMICALLY
)
3335 return ld::Atom::symbolTableInAndNeverStrip
;
3336 else if ( symbolName
[0] == 'l' )
3337 return ld::Atom::symbolTableNotInFinalLinkedImages
;
3338 else if ( symbolName
[0] == 'L' )
3339 return ld::Atom::symbolTableNotIn
;
3341 return ld::Atom::symbolTableIn
;
3344 template <typename A
>
3345 bool Parser
<A
>::dontDeadStripFromSymbol(const macho_nlist
<P
>& sym
)
3347 return ( (sym
.n_desc() & (N_NO_DEAD_STRIP
|REFERENCED_DYNAMICALLY
)) != 0 );
3350 template <typename A
>
3351 bool Parser
<A
>::isThumbFromSymbol(const macho_nlist
<P
>& sym
)
3353 return ( sym
.n_desc() & N_ARM_THUMB_DEF
);
3356 template <typename A
>
3357 bool Parser
<A
>::weakImportFromSymbol(const macho_nlist
<P
>& sym
)
3359 return ( ((sym
.n_type() & N_TYPE
) == N_UNDF
) && ((sym
.n_desc() & N_WEAK_REF
) != 0) );
3362 template <typename A
>
3363 bool Parser
<A
>::resolverFromSymbol(const macho_nlist
<P
>& sym
)
3365 return ( sym
.n_desc() & N_SYMBOL_RESOLVER
);
3368 template <typename A
>
3369 bool Parser
<A
>::altEntryFromSymbol(const macho_nlist
<P
>& sym
)
3371 return ( sym
.n_desc() & N_ALT_ENTRY
);
3375 /* Skip over a LEB128 value (signed or unsigned). */
3377 skip_leb128 (const uint8_t ** offset
, const uint8_t * end
)
3379 while (*offset
!= end
&& **offset
>= 0x80)
3385 /* Read a ULEB128 into a 64-bit word. Return (uint64_t)-1 on overflow
3386 or error. On overflow, skip past the rest of the uleb128. */
3388 read_uleb128 (const uint8_t ** offset
, const uint8_t * end
)
3390 uint64_t result
= 0;
3397 return (uint64_t) -1;
3399 b
= **offset
& 0x7f;
3401 if (bit
>= 64 || b
<< bit
>> bit
!= b
)
3402 result
= (uint64_t) -1;
3404 result
|= b
<< bit
, bit
+= 7;
3405 } while (*(*offset
)++ >= 0x80);
3410 /* Skip over a DWARF attribute of form FORM. */
3411 template <typename A
>
3412 bool Parser
<A
>::skip_form(const uint8_t ** offset
, const uint8_t * end
, uint64_t form
,
3413 uint8_t addr_size
, bool dwarf64
)
3423 case DW_FORM_block2
:
3424 if (end
- *offset
< 2)
3426 sz
= 2 + A::P::E::get16(*(uint16_t*)offset
);
3429 case DW_FORM_block4
:
3430 if (end
- *offset
< 4)
3432 sz
= 2 + A::P::E::get32(*(uint32_t*)offset
);
3450 case DW_FORM_string
:
3451 while (*offset
!= end
&& **offset
)
3460 sz
= read_uleb128 (offset
, end
);
3463 case DW_FORM_block1
:
3471 case DW_FORM_ref_udata
:
3472 skip_leb128 (offset
, end
);
3476 case DW_FORM_ref_addr
:
3480 case DW_FORM_sec_offset
:
3481 sz
= sizeof(typename
A::P::uint_t
);
3484 case DW_FORM_exprloc
:
3485 sz
= read_uleb128 (offset
, end
);
3488 case DW_FORM_flag_present
:
3492 case DW_FORM_ref_sig8
:
3499 if (end
- *offset
< sz
)
3506 template <typename A
>
3507 const char* Parser
<A
>::getDwarfString(uint64_t form
, const uint8_t*& di
)
3510 const char* dwarfStrings
;
3511 const char* result
= NULL
;
3513 case DW_FORM_string
:
3514 result
= (const char*)di
;
3515 di
+= strlen(result
) + 1;
3518 offset
= E::get32(*((uint32_t*)di
));
3519 dwarfStrings
= (char*)_file
->fileContent() + _file
->_dwarfDebugStringSect
->offset();
3520 if ( offset
< _file
->_dwarfDebugStringSect
->size() )
3521 result
= &dwarfStrings
[offset
];
3523 warning("dwarf DW_FORM_strp (offset=0x%08X) is too big in %s", offset
, this->_path
);
3527 warning("unknown dwarf string encoding (form=%lld) in %s", form
, this->_path
);
3533 template <typename A
>
3534 uint64_t Parser
<A
>::getDwarfOffset(uint64_t form
, const uint8_t*& di
, bool dwarf64
)
3536 if ( form
== DW_FORM_sec_offset
)
3537 form
= (dwarf64
? DW_FORM_data8
: DW_FORM_data4
);
3538 uint64_t result
= -1;
3541 result
= A::P::E::get32(*(uint32_t*)di
);
3545 result
= A::P::E::get64(*(uint64_t*)di
);
3549 warning("unknown dwarf DW_FORM_ for DW_AT_stmt_list in %s", this->_path
);
3555 template <typename A
>
3556 struct AtomAndLineInfo
{
3558 ld::Atom::LineInfo info
;
3562 // <rdar://problem/5591394> Add support to ld64 for N_FUN stabs when used for symbolic constants
3563 // Returns whether a stabStr belonging to an N_FUN stab represents a
3564 // symbolic constant rather than a function
3565 template <typename A
>
3566 bool Parser
<A
>::isConstFunStabs(const char *stabStr
)
3569 // N_FUN can be used for both constants and for functions. In case it's a constant,
3570 // the format of the stabs string is "symname:c=<value>;"
3571 // ':' cannot appear in the symbol name, except if it's an Objective-C method
3572 // (in which case the symbol name starts with + or -, and then it's definitely
3574 return (stabStr
!= NULL
) && (stabStr
[0] != '+') && (stabStr
[0] != '-')
3575 && ((colon
= strchr(stabStr
, ':')) != NULL
)
3576 && (colon
[1] == 'c') && (colon
[2] == '=');
3580 template <typename A
>
3581 void Parser
<A
>::parseDebugInfo()
3583 // check for dwarf __debug_info section
3584 if ( _file
->_dwarfDebugInfoSect
== NULL
) {
3585 // if no DWARF debug info, look for stabs
3589 if ( _file
->_dwarfDebugInfoSect
->size() == 0 )
3595 if ( !read_comp_unit(&tuName
, &tuDir
, &stmtList
) ) {
3596 // if can't parse dwarf, warn and give up
3597 _file
->_dwarfTranslationUnitPath
= NULL
;
3598 warning("can't parse dwarf compilation unit info in %s", _path
);
3599 _file
->_debugInfoKind
= ld::relocatable::File::kDebugInfoNone
;
3602 if ( (tuName
!= NULL
) && (tuName
[0] == '/') ) {
3603 _file
->_dwarfTranslationUnitPath
= tuName
;
3605 else if ( (tuDir
!= NULL
) && (tuName
!= NULL
) ) {
3606 asprintf((char**)&(_file
->_dwarfTranslationUnitPath
), "%s/%s", tuDir
, tuName
);
3608 else if ( tuDir
== NULL
) {
3609 _file
->_dwarfTranslationUnitPath
= tuName
;
3612 _file
->_dwarfTranslationUnitPath
= NULL
;
3615 // add line number info to atoms from dwarf
3616 std::vector
<AtomAndLineInfo
<A
> > entries
;
3617 entries
.reserve(64);
3618 if ( _file
->_debugInfoKind
== ld::relocatable::File::kDebugInfoDwarf
) {
3619 // file with just data will have no __debug_line info
3620 if ( (_file
->_dwarfDebugLineSect
!= NULL
) && (_file
->_dwarfDebugLineSect
->size() != 0) ) {
3621 // validate stmt_list
3622 if ( (stmtList
!= (uint64_t)-1) && (stmtList
< _file
->_dwarfDebugLineSect
->size()) ) {
3623 const uint8_t* debug_line
= (uint8_t*)_file
->fileContent() + _file
->_dwarfDebugLineSect
->offset();
3624 struct line_reader_data
* lines
= line_open(&debug_line
[stmtList
],
3625 _file
->_dwarfDebugLineSect
->size() - stmtList
, E::little_endian
);
3626 struct line_info result
;
3627 Atom
<A
>* curAtom
= NULL
;
3628 uint32_t curAtomOffset
= 0;
3629 uint32_t curAtomAddress
= 0;
3630 uint32_t curAtomSize
= 0;
3631 std::map
<uint32_t,const char*> dwarfIndexToFile
;
3632 if ( lines
!= NULL
) {
3633 while ( line_next(lines
, &result
, line_stop_pc
) ) {
3634 //fprintf(stderr, "curAtom=%p, result.pc=0x%llX, result.line=%llu, result.end_of_sequence=%d,"
3635 // " curAtomAddress=0x%X, curAtomSize=0x%X\n",
3636 // curAtom, result.pc, result.line, result.end_of_sequence, curAtomAddress, curAtomSize);
3637 // work around weird debug line table compiler generates if no functions in __text section
3638 if ( (curAtom
== NULL
) && (result
.pc
== 0) && result
.end_of_sequence
&& (result
.file
== 1))
3640 // for performance, see if in next pc is in current atom
3641 if ( (curAtom
!= NULL
) && (curAtomAddress
<= result
.pc
) && (result
.pc
< (curAtomAddress
+curAtomSize
)) ) {
3642 curAtomOffset
= result
.pc
- curAtomAddress
;
3644 // or pc at end of current atom
3645 else if ( result
.end_of_sequence
&& (curAtom
!= NULL
) && (result
.pc
== (curAtomAddress
+curAtomSize
)) ) {
3646 curAtomOffset
= result
.pc
- curAtomAddress
;
3648 // or only one function that is a one line function
3649 else if ( result
.end_of_sequence
&& (curAtom
== NULL
) && (this->findAtomByAddress(0) != NULL
) && (result
.pc
== this->findAtomByAddress(0)->size()) ) {
3650 curAtom
= this->findAtomByAddress(0);
3651 curAtomOffset
= result
.pc
- curAtom
->objectAddress();
3652 curAtomAddress
= curAtom
->objectAddress();
3653 curAtomSize
= curAtom
->size();
3656 // do slow look up of atom by address
3658 curAtom
= this->findAtomByAddress(result
.pc
);
3661 // in case of bug in debug info, don't abort link, just limp on
3664 if ( curAtom
== NULL
)
3665 break; // file has line info but no functions
3666 if ( result
.end_of_sequence
&& (curAtomAddress
+curAtomSize
< result
.pc
) ) {
3667 // a one line function can be returned by line_next() as one entry with pc at end of blob
3668 // look for alt atom starting at end of previous atom
3669 uint32_t previousEnd
= curAtomAddress
+curAtomSize
;
3670 Atom
<A
>* alt
= this->findAtomByAddressOrNullIfStub(previousEnd
);
3672 continue; // ignore spurious debug info for stubs
3673 if ( result
.pc
<= alt
->objectAddress() + alt
->size() ) {
3675 curAtomOffset
= result
.pc
- alt
->objectAddress();
3676 curAtomAddress
= alt
->objectAddress();
3677 curAtomSize
= alt
->size();
3680 curAtomOffset
= result
.pc
- curAtom
->objectAddress();
3681 curAtomAddress
= curAtom
->objectAddress();
3682 curAtomSize
= curAtom
->size();
3686 curAtomOffset
= result
.pc
- curAtom
->objectAddress();
3687 curAtomAddress
= curAtom
->objectAddress();
3688 curAtomSize
= curAtom
->size();
3691 const char* filename
;
3692 std::map
<uint32_t,const char*>::iterator pos
= dwarfIndexToFile
.find(result
.file
);
3693 if ( pos
== dwarfIndexToFile
.end() ) {
3694 filename
= line_file(lines
, result
.file
);
3695 dwarfIndexToFile
[result
.file
] = filename
;
3698 filename
= pos
->second
;
3700 // only record for ~8000 line info records per function
3701 if ( curAtom
->roomForMoreLineInfoCount() ) {
3702 AtomAndLineInfo
<A
> entry
;
3703 entry
.atom
= curAtom
;
3704 entry
.info
.atomOffset
= curAtomOffset
;
3705 entry
.info
.fileName
= filename
;
3706 entry
.info
.lineNumber
= result
.line
;
3707 //fprintf(stderr, "addr=0x%08llX, line=%lld, file=%s, atom=%s, atom.size=0x%X, end=%d\n",
3708 // result.pc, result.line, filename, curAtom->name(), curAtomSize, result.end_of_sequence);
3709 entries
.push_back(entry
);
3710 curAtom
->incrementLineInfoCount();
3712 if ( result
.end_of_sequence
) {
3722 // assign line info start offset for each atom
3723 uint8_t* p
= _file
->_atomsArray
;
3724 uint32_t liOffset
= 0;
3725 for(int i
=_file
->_atomsArrayCount
; i
> 0; --i
) {
3726 Atom
<A
>* atom
= (Atom
<A
>*)p
;
3727 atom
->_lineInfoStartIndex
= liOffset
;
3728 liOffset
+= atom
->_lineInfoCount
;
3729 atom
->_lineInfoCount
= 0;
3730 p
+= sizeof(Atom
<A
>);
3732 assert(liOffset
== entries
.size());
3733 _file
->_lineInfos
.resize(liOffset
);
3735 // copy each line info for each atom
3736 for (typename
std::vector
<AtomAndLineInfo
<A
> >::iterator it
= entries
.begin(); it
!= entries
.end(); ++it
) {
3737 uint32_t slot
= it
->atom
->_lineInfoStartIndex
+ it
->atom
->_lineInfoCount
;
3738 _file
->_lineInfos
[slot
] = it
->info
;
3739 it
->atom
->_lineInfoCount
++;
3742 // done with temp vector
3746 template <typename A
>
3747 void Parser
<A
>::parseStabs()
3749 // scan symbol table for stabs entries
3750 Atom
<A
>* currentAtom
= NULL
;
3751 pint_t currentAtomAddress
= 0;
3752 enum { start
, inBeginEnd
, inFun
} state
= start
;
3753 for (uint32_t symbolIndex
= 0; symbolIndex
< _symbolCount
; ++symbolIndex
) {
3754 const macho_nlist
<P
>& sym
= this->symbolFromIndex(symbolIndex
);
3755 bool useStab
= true;
3756 uint8_t type
= sym
.n_type();
3757 const char* symString
= (sym
.n_strx() != 0) ? this->nameFromSymbol(sym
) : NULL
;
3758 if ( (type
& N_STAB
) != 0 ) {
3759 _file
->_debugInfoKind
= (_hasUUID
? ld::relocatable::File::kDebugInfoStabsUUID
: ld::relocatable::File::kDebugInfoStabs
);
3760 ld::relocatable::File::Stab stab
;
3763 stab
.other
= sym
.n_sect();
3764 stab
.desc
= sym
.n_desc();
3765 stab
.value
= sym
.n_value();
3771 // beginning of function block
3773 // fall into case to lookup atom by addresss
3776 currentAtomAddress
= sym
.n_value();
3777 currentAtom
= this->findAtomByAddress(currentAtomAddress
);
3778 if ( currentAtom
!= NULL
) {
3779 stab
.atom
= currentAtom
;
3780 stab
.string
= symString
;
3783 fprintf(stderr
, "can't find atom for stabs BNSYM at %08llX in %s",
3784 (uint64_t)sym
.n_value(), _path
);
3794 // not associated with an atom, just copy
3795 stab
.string
= symString
;
3799 // n_value field is NOT atom address ;-(
3800 // need to find atom by name match
3801 const char* colon
= strchr(symString
, ':');
3802 if ( colon
!= NULL
) {
3803 // build underscore leading name
3804 int nameLen
= colon
- symString
;
3805 char symName
[nameLen
+2];
3806 strlcpy(&symName
[1], symString
, nameLen
+1);
3808 symName
[nameLen
+1] = '\0';
3809 currentAtom
= this->findAtomByName(symName
);
3810 if ( currentAtom
!= NULL
) {
3811 stab
.atom
= currentAtom
;
3812 stab
.string
= symString
;
3816 // might be a debug-note without trailing :G()
3817 currentAtom
= this->findAtomByName(symString
);
3818 if ( currentAtom
!= NULL
) {
3819 stab
.atom
= currentAtom
;
3820 stab
.string
= symString
;
3823 if ( stab
.atom
== NULL
) {
3824 // ld_classic added bogus GSYM stabs for old style dtrace probes
3825 if ( (strncmp(symString
, "__dtrace_probe$", 15) != 0) )
3826 warning("can't find atom for N_GSYM stabs %s in %s", symString
, _path
);
3832 if ( isConstFunStabs(symString
) ) {
3833 // constant not associated with a function
3834 stab
.string
= symString
;
3837 // old style stabs without BNSYM
3839 currentAtomAddress
= sym
.n_value();
3840 currentAtom
= this->findAtomByAddress(currentAtomAddress
);
3841 if ( currentAtom
!= NULL
) {
3842 stab
.atom
= currentAtom
;
3843 stab
.string
= symString
;
3846 warning("can't find atom for stabs FUN at %08llX in %s",
3847 (uint64_t)currentAtomAddress
, _path
);
3853 stab
.string
= symString
;
3859 stab
.string
= symString
;
3860 // -gfull built .o file
3863 warning("unknown stabs type 0x%X in %s", type
, _path
);
3867 stab
.atom
= currentAtom
;
3876 Atom
<A
>* nestedAtom
= this->findAtomByAddress(sym
.n_value());
3877 if ( nestedAtom
!= NULL
) {
3878 stab
.atom
= nestedAtom
;
3879 stab
.string
= symString
;
3882 warning("can't find atom for stabs 0x%X at %08llX in %s",
3883 type
, (uint64_t)sym
.n_value(), _path
);
3890 // adjust value to be offset in atom
3891 stab
.value
-= currentAtomAddress
;
3893 stab
.string
= symString
;
3900 if ( isConstFunStabs(symString
) ) {
3901 stab
.atom
= currentAtom
;
3902 stab
.string
= symString
;
3905 if ( sym
.n_sect() != 0 ) {
3906 // found another start stab, must be really old stabs...
3907 currentAtomAddress
= sym
.n_value();
3908 currentAtom
= this->findAtomByAddress(currentAtomAddress
);
3909 if ( currentAtom
!= NULL
) {
3910 stab
.atom
= currentAtom
;
3911 stab
.string
= symString
;
3914 warning("can't find atom for stabs FUN at %08llX in %s",
3915 (uint64_t)currentAtomAddress
, _path
);
3919 // found ending stab, switch back to start state
3920 stab
.string
= symString
;
3921 stab
.atom
= currentAtom
;
3930 // adjust value to be offset in atom
3931 stab
.value
-= currentAtomAddress
;
3932 stab
.atom
= currentAtom
;
3935 stab
.string
= symString
;
3939 stab
.atom
= currentAtom
;
3940 stab
.string
= symString
;
3945 // add to list of stabs for this .o file
3947 _file
->_stabs
.push_back(stab
);
3954 // Look at the compilation unit DIE and determine
3955 // its NAME, compilation directory (in COMP_DIR) and its
3956 // line number information offset (in STMT_LIST). NAME and COMP_DIR
3957 // may be NULL (especially COMP_DIR) if they are not in the .o file;
3958 // STMT_LIST will be (uint64_t) -1.
3960 // At present this assumes that there's only one compilation unit DIE.
3962 template <typename A
>
3963 bool Parser
<A
>::read_comp_unit(const char ** name
, const char ** comp_dir
,
3964 uint64_t *stmt_list
)
3966 const uint8_t * debug_info
;
3967 const uint8_t * debug_abbrev
;
3969 const uint8_t * next_cu
;
3971 const uint8_t * end
;
3972 const uint8_t * enda
;
3975 uint64_t abbrev_base
;
3977 uint8_t address_size
;
3982 *stmt_list
= (uint64_t) -1;
3984 if ( (_file
->_dwarfDebugInfoSect
== NULL
) || (_file
->_dwarfDebugAbbrevSect
== NULL
) )
3987 if (_file
->_dwarfDebugInfoSect
->size() < 12)
3988 /* Too small to be a real debug_info section. */
3991 debug_info
= (uint8_t*)_file
->fileContent() + _file
->_dwarfDebugInfoSect
->offset();
3992 debug_abbrev
= (uint8_t*)_file
->fileContent() + _file
->_dwarfDebugAbbrevSect
->offset();
3993 next_cu
= debug_info
;
3995 while ((uint64_t)(next_cu
- debug_info
) < _file
->_dwarfDebugInfoSect
->size()) {
3997 sz
= A::P::E::get32(*(uint32_t*)di
);
3999 dwarf64
= sz
== 0xffffffff;
4001 sz
= A::P::E::get64(*(uint64_t*)di
), di
+= 8;
4002 else if (sz
> 0xffffff00)
4003 /* Unknown dwarf format. */
4006 /* Verify claimed size. */
4007 if (sz
+ (di
- debug_info
) > _file
->_dwarfDebugInfoSect
->size() || sz
<= (dwarf64
? 23 : 11))
4012 vers
= A::P::E::get16(*(uint16_t*)di
);
4013 if (vers
< 2 || vers
> 4)
4014 /* DWARF version wrong for this code.
4015 Chances are we could continue anyway, but we don't know for sure. */
4019 /* Find the debug_abbrev section. */
4020 abbrev_base
= dwarf64
? A::P::E::get64(*(uint64_t*)di
) : A::P::E::get32(*(uint32_t*)di
);
4021 di
+= dwarf64
? 8 : 4;
4023 if (abbrev_base
> _file
->_dwarfDebugAbbrevSect
->size())
4025 da
= debug_abbrev
+ abbrev_base
;
4026 enda
= debug_abbrev
+ _file
->_dwarfDebugAbbrevSect
->size();
4028 address_size
= *di
++;
4030 /* Find the abbrev number we're looking for. */
4032 abbrev
= read_uleb128 (&di
, end
);
4033 if (abbrev
== (uint64_t) -1)
4036 /* Skip through the debug_abbrev section looking for that abbrev. */
4039 uint64_t this_abbrev
= read_uleb128 (&da
, enda
);
4042 if (this_abbrev
== abbrev
)
4043 /* This is almost always taken. */
4045 skip_leb128 (&da
, enda
); /* Skip the tag. */
4048 da
++; /* Skip the DW_CHILDREN_* value. */
4051 attr
= read_uleb128 (&da
, enda
);
4052 skip_leb128 (&da
, enda
);
4053 } while (attr
!= 0 && attr
!= (uint64_t) -1);
4058 /* Check that the abbrev is one for a DW_TAG_compile_unit. */
4059 if (read_uleb128 (&da
, enda
) != DW_TAG_compile_unit
)
4063 da
++; /* Skip the DW_CHILDREN_* value. */
4065 /* Now, go through the DIE looking for DW_AT_name,
4066 DW_AT_comp_dir, and DW_AT_stmt_list. */
4067 bool skip_to_next_cu
= false;
4068 while (!skip_to_next_cu
) {
4070 uint64_t attr
= read_uleb128 (&da
, enda
);
4071 uint64_t form
= read_uleb128 (&da
, enda
);
4073 if (attr
== (uint64_t) -1)
4077 if (form
== DW_FORM_indirect
)
4078 form
= read_uleb128 (&di
, end
);
4082 *name
= getDwarfString(form
, di
);
4083 /* Swift object files may contain two CUs: One
4084 describes the Swift code, one is created by the
4085 clang importer. Skip over the CU created by the
4086 clang importer as it may be empty. */
4087 if (std::string(*name
) == "<swift-imported-modules>")
4088 skip_to_next_cu
= true;
4090 case DW_AT_comp_dir
:
4091 *comp_dir
= getDwarfString(form
, di
);
4093 case DW_AT_stmt_list
:
4094 *stmt_list
= getDwarfOffset(form
, di
, dwarf64
);
4097 if (! skip_form (&di
, end
, form
, address_size
, dwarf64
))
4107 template <typename A
>
4110 free(_sectionsArray
);
4114 template <typename A
>
4115 const char* File
<A
>::translationUnitSource() const
4117 return _dwarfTranslationUnitPath
;
4120 template <typename A
>
4121 bool File
<A
>::forEachAtom(ld::File::AtomHandler
& handler
) const
4123 handler
.doFile(*this);
4124 uint8_t* p
= _atomsArray
;
4125 for(int i
=_atomsArrayCount
; i
> 0; --i
) {
4126 handler
.doAtom(*((Atom
<A
>*)p
));
4127 p
+= sizeof(Atom
<A
>);
4129 p
= _aliasAtomsArray
;
4130 for(int i
=_aliasAtomsArrayCount
; i
> 0; --i
) {
4131 handler
.doAtom(*((AliasAtom
*)p
));
4132 p
+= sizeof(AliasAtom
);
4135 return (_atomsArrayCount
!= 0) || (_aliasAtomsArrayCount
!= 0);
4138 template <typename A
>
4139 const char* Section
<A
>::makeSegmentName(const macho_section
<typename
A::P
>* sect
)
4141 // mach-o section record only has room for 16-byte seg/sect names
4142 // so a 16-byte name has no trailing zero
4143 const char* name
= sect
->segname();
4144 if ( strlen(name
) < 16 )
4146 char* tmp
= new char[17];
4147 strlcpy(tmp
, name
, 17);
4151 template <typename A
>
4152 const char* Section
<A
>::makeSectionName(const macho_section
<typename
A::P
>* sect
)
4154 const char* name
= sect
->sectname();
4155 if ( strlen(name
) < 16 )
4158 // special case common long section names so we don't have to malloc
4159 if ( strncmp(sect
->sectname(), "__objc_classrefs", 16) == 0 )
4160 return "__objc_classrefs";
4161 if ( strncmp(sect
->sectname(), "__objc_classlist", 16) == 0 )
4162 return "__objc_classlist";
4163 if ( strncmp(sect
->sectname(), "__objc_nlclslist", 16) == 0 )
4164 return "__objc_nlclslist";
4165 if ( strncmp(sect
->sectname(), "__objc_nlcatlist", 16) == 0 )
4166 return "__objc_nlcatlist";
4167 if ( strncmp(sect
->sectname(), "__objc_protolist", 16) == 0 )
4168 return "__objc_protolist";
4169 if ( strncmp(sect
->sectname(), "__objc_protorefs", 16) == 0 )
4170 return "__objc_protorefs";
4171 if ( strncmp(sect
->sectname(), "__objc_superrefs", 16) == 0 )
4172 return "__objc_superrefs";
4173 if ( strncmp(sect
->sectname(), "__objc_imageinfo", 16) == 0 )
4174 return "__objc_imageinfo";
4175 if ( strncmp(sect
->sectname(), "__objc_stringobj", 16) == 0 )
4176 return "__objc_stringobj";
4177 if ( strncmp(sect
->sectname(), "__gcc_except_tab", 16) == 0 )
4178 return "__gcc_except_tab";
4180 char* tmp
= new char[17];
4181 strlcpy(tmp
, name
, 17);
4185 template <typename A
>
4186 bool Section
<A
>::readable(const macho_section
<typename
A::P
>* sect
)
4191 template <typename A
>
4192 bool Section
<A
>::writable(const macho_section
<typename
A::P
>* sect
)
4194 // mach-o .o files do not contain segment permissions
4195 // we just know TEXT is special
4196 return ( strcmp(sect
->segname(), "__TEXT") != 0 );
4199 template <typename A
>
4200 bool Section
<A
>::exectuable(const macho_section
<typename
A::P
>* sect
)
4202 // mach-o .o files do not contain segment permissions
4203 // we just know TEXT is special
4204 return ( strcmp(sect
->segname(), "__TEXT") == 0 );
4208 template <typename A
>
4209 ld::Section::Type Section
<A
>::sectionType(const macho_section
<typename
A::P
>* sect
)
4211 switch ( sect
->flags() & SECTION_TYPE
) {
4213 return ld::Section::typeZeroFill
;
4214 case S_CSTRING_LITERALS
:
4215 if ( (strcmp(sect
->sectname(), "__cstring") == 0) && (strcmp(sect
->segname(), "__TEXT") == 0) )
4216 return ld::Section::typeCString
;
4218 return ld::Section::typeNonStdCString
;
4219 case S_4BYTE_LITERALS
:
4220 return ld::Section::typeLiteral4
;
4221 case S_8BYTE_LITERALS
:
4222 return ld::Section::typeLiteral8
;
4223 case S_LITERAL_POINTERS
:
4224 return ld::Section::typeCStringPointer
;
4225 case S_NON_LAZY_SYMBOL_POINTERS
:
4226 return ld::Section::typeNonLazyPointer
;
4227 case S_LAZY_SYMBOL_POINTERS
:
4228 return ld::Section::typeLazyPointer
;
4229 case S_SYMBOL_STUBS
:
4230 return ld::Section::typeStub
;
4231 case S_MOD_INIT_FUNC_POINTERS
:
4232 return ld::Section::typeInitializerPointers
;
4233 case S_MOD_TERM_FUNC_POINTERS
:
4234 return ld::Section::typeTerminatorPointers
;
4236 return ld::Section::typeUnclassified
;
4237 case S_16BYTE_LITERALS
:
4238 return ld::Section::typeLiteral16
;
4241 if ( sect
->flags() & S_ATTR_PURE_INSTRUCTIONS
) {
4242 return ld::Section::typeCode
;
4244 else if ( strcmp(sect
->segname(), "__TEXT") == 0 ) {
4245 if ( strcmp(sect
->sectname(), "__eh_frame") == 0 )
4246 return ld::Section::typeCFI
;
4247 else if ( strcmp(sect
->sectname(), "__ustring") == 0 )
4248 return ld::Section::typeUTF16Strings
;
4249 else if ( strcmp(sect
->sectname(), "__textcoal_nt") == 0 )
4250 return ld::Section::typeCode
;
4251 else if ( strcmp(sect
->sectname(), "__StaticInit") == 0 )
4252 return ld::Section::typeCode
;
4253 else if ( strcmp(sect
->sectname(), "__constructor") == 0 )
4254 return ld::Section::typeInitializerPointers
;
4256 else if ( strcmp(sect
->segname(), "__DATA") == 0 ) {
4257 if ( strcmp(sect
->sectname(), "__cfstring") == 0 )
4258 return ld::Section::typeCFString
;
4259 else if ( strcmp(sect
->sectname(), "__dyld") == 0 )
4260 return ld::Section::typeDyldInfo
;
4261 else if ( strcmp(sect
->sectname(), "__program_vars") == 0 )
4262 return ld::Section::typeDyldInfo
;
4263 else if ( strncmp(sect
->sectname(), "__objc_classrefs", 16) == 0 )
4264 return ld::Section::typeObjCClassRefs
;
4265 else if ( strcmp(sect
->sectname(), "__objc_catlist") == 0 )
4266 return ld::Section::typeObjC2CategoryList
;
4268 else if ( strcmp(sect
->segname(), "__OBJC") == 0 ) {
4269 if ( strcmp(sect
->sectname(), "__class") == 0 )
4270 return ld::Section::typeObjC1Classes
;
4273 case S_THREAD_LOCAL_REGULAR
:
4274 return ld::Section::typeTLVInitialValues
;
4275 case S_THREAD_LOCAL_ZEROFILL
:
4276 return ld::Section::typeTLVZeroFill
;
4277 case S_THREAD_LOCAL_VARIABLES
:
4278 return ld::Section::typeTLVDefs
;
4279 case S_THREAD_LOCAL_VARIABLE_POINTERS
:
4280 return ld::Section::typeTLVPointers
;
4281 case S_THREAD_LOCAL_INIT_FUNCTION_POINTERS
:
4282 return ld::Section::typeTLVInitializerPointers
;
4284 return ld::Section::typeUnclassified
;
4288 template <typename A
>
4289 Atom
<A
>* Section
<A
>::findContentAtomByAddress(pint_t addr
, class Atom
<A
>* start
, class Atom
<A
>* end
)
4291 // do a binary search of atom array
4292 uint32_t atomCount
= end
- start
;
4293 Atom
<A
>* base
= start
;
4294 for (uint32_t n
= atomCount
; n
> 0; n
/= 2) {
4295 Atom
<A
>* pivot
= &base
[n
/2];
4296 pint_t atomStartAddr
= pivot
->_objAddress
;
4297 pint_t atomEndAddr
= atomStartAddr
+ pivot
->_size
;
4298 if ( atomStartAddr
<= addr
) {
4299 // address in normal atom
4300 if (addr
< atomEndAddr
)
4302 // address in "end" label (but not in alias)
4303 if ( (pivot
->_size
== 0) && (addr
== atomEndAddr
) && !pivot
->isAlias() )
4306 if ( addr
>= atomEndAddr
) {
4308 // move base to atom after pivot
4320 template <typename A
>
4321 ld::Atom::Alignment Section
<A
>::alignmentForAddress(pint_t addr
)
4323 const uint32_t sectionAlignment
= this->_machOSection
->align();
4324 uint32_t modulus
= (addr
% (1 << sectionAlignment
));
4325 if ( modulus
> 0xFFFF )
4326 warning("alignment for symbol at address 0x%08llX in %s exceeds 2^16", (uint64_t)addr
, this->file().path());
4327 return ld::Atom::Alignment(sectionAlignment
, modulus
);
4330 template <typename A
>
4331 uint32_t Section
<A
>::sectionNum(class Parser
<A
>& parser
) const
4333 if ( _machOSection
== NULL
)
4336 return 1 + (this->_machOSection
- parser
.firstMachOSection());
4339 // arm does not have zero cost exceptions
4341 uint32_t CFISection
<arm
>::cfiCount(Parser
<arm
>& parser
)
4343 if ( parser
.armUsesZeroCostExceptions() ) {
4344 // create ObjectAddressSpace object for use by libunwind
4345 OAS
oas(*this, (uint8_t*)this->file().fileContent()+this->_machOSection
->offset());
4346 return libunwind::CFI_Parser
<OAS
>::getCFICount(oas
,
4347 this->_machOSection
->addr(), this->_machOSection
->size());
4352 template <typename A
>
4353 uint32_t CFISection
<A
>::cfiCount(Parser
<A
>& parser
)
4355 // create ObjectAddressSpace object for use by libunwind
4356 OAS
oas(*this, (uint8_t*)this->file().fileContent()+this->_machOSection
->offset());
4357 return libunwind::CFI_Parser
<OAS
>::getCFICount(oas
,
4358 this->_machOSection
->addr(), this->_machOSection
->size());
4361 template <typename A
>
4362 void CFISection
<A
>::warnFunc(void* ref
, uint64_t funcAddr
, const char* msg
)
4364 Parser
<A
>* parser
= (Parser
<A
>*)ref
;
4365 if ( ! parser
->warnUnwindConversionProblems() )
4367 if ( funcAddr
!= CFI_INVALID_ADDRESS
) {
4368 // atoms are not constructed yet, so scan symbol table for labels
4369 const char* name
= parser
->scanSymbolTableForAddress(funcAddr
);
4370 warning("could not create compact unwind for %s: %s", name
, msg
);
4373 warning("could not create compact unwind: %s", msg
);
4378 bool CFISection
<x86_64
>::needsRelocating()
4384 bool CFISection
<arm64
>::needsRelocating()
4389 template <typename A
>
4390 bool CFISection
<A
>::needsRelocating()
4396 void CFISection
<x86_64
>::cfiParse(class Parser
<x86_64
>& parser
, uint8_t* buffer
,
4397 libunwind::CFI_Atom_Info
<CFISection
<x86_64
>::OAS
>::CFI_Atom_Info cfiArray
[],
4398 uint32_t& count
, const pint_t cuStarts
[], uint32_t cuCount
)
4400 const uint32_t sectionSize
= this->_machOSection
->size();
4401 // copy __eh_frame data to buffer
4402 memcpy(buffer
, file().fileContent() + this->_machOSection
->offset(), sectionSize
);
4404 // and apply relocations
4405 const macho_relocation_info
<P
>* relocs
= (macho_relocation_info
<P
>*)(file().fileContent() + this->_machOSection
->reloff());
4406 const macho_relocation_info
<P
>* relocsEnd
= &relocs
[this->_machOSection
->nreloc()];
4407 for (const macho_relocation_info
<P
>* reloc
= relocs
; reloc
< relocsEnd
; ++reloc
) {
4409 switch ( reloc
->r_type() ) {
4410 case X86_64_RELOC_SUBTRACTOR
:
4411 value
= 0 - parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
4413 if ( reloc
->r_extern() )
4414 value
+= parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
4416 case X86_64_RELOC_UNSIGNED
:
4417 value
= parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
4419 case X86_64_RELOC_GOT
:
4420 // this is used for the reference to the personality function in CIEs
4421 // store the symbol number of the personality function for later use as a Fixup
4422 value
= reloc
->r_symbolnum();
4425 fprintf(stderr
, "CFISection::cfiParse() unexpected relocation type at r_address=0x%08X\n", reloc
->r_address());
4428 if ( reloc
->r_address() > sectionSize
)
4429 throwf("malformed __eh_frame relocation, offset (0x%08X) is beyond end of section,", reloc
->r_address());
4432 switch ( reloc
->r_length() ) {
4434 p64
= (uint64_t*)&buffer
[reloc
->r_address()];
4435 E::set64(*p64
, value
+ E::get64(*p64
));
4438 p32
= (uint32_t*)&buffer
[reloc
->r_address()];
4439 E::set32(*p32
, value
+ E::get32(*p32
));
4442 fprintf(stderr
, "CFISection::cfiParse() unexpected relocation size at r_address=0x%08X\n", reloc
->r_address());
4447 // create ObjectAddressSpace object for use by libunwind
4448 OAS
oas(*this, buffer
);
4450 // use libuwind to parse __eh_frame data into array of CFI_Atom_Info
4452 msg
= libunwind::DwarfInstructions
<OAS
, libunwind::Registers_x86_64
>::parseCFIs(
4453 oas
, this->_machOSection
->addr(), this->_machOSection
->size(),
4454 cuStarts
, cuCount
, parser
.keepDwarfUnwind(), parser
.forceDwarfConversion(), parser
.neverConvertDwarf(),
4455 cfiArray
, count
, (void*)&parser
, warnFunc
);
4457 throwf("malformed __eh_frame section: %s", msg
);
4461 void CFISection
<x86
>::cfiParse(class Parser
<x86
>& parser
, uint8_t* buffer
,
4462 libunwind::CFI_Atom_Info
<CFISection
<x86
>::OAS
>::CFI_Atom_Info cfiArray
[],
4463 uint32_t& count
, const pint_t cuStarts
[], uint32_t cuCount
)
4465 // create ObjectAddressSpace object for use by libunwind
4466 OAS
oas(*this, (uint8_t*)this->file().fileContent()+this->_machOSection
->offset());
4468 // use libuwind to parse __eh_frame data into array of CFI_Atom_Info
4470 msg
= libunwind::DwarfInstructions
<OAS
, libunwind::Registers_x86
>::parseCFIs(
4471 oas
, this->_machOSection
->addr(), this->_machOSection
->size(),
4472 cuStarts
, cuCount
, parser
.keepDwarfUnwind(), parser
.forceDwarfConversion(), parser
.neverConvertDwarf(),
4473 cfiArray
, count
, (void*)&parser
, warnFunc
);
4475 throwf("malformed __eh_frame section: %s", msg
);
4482 void CFISection
<arm
>::cfiParse(class Parser
<arm
>& parser
, uint8_t* buffer
,
4483 libunwind::CFI_Atom_Info
<CFISection
<arm
>::OAS
>::CFI_Atom_Info cfiArray
[],
4484 uint32_t& count
, const pint_t cuStarts
[], uint32_t cuCount
)
4486 if ( !parser
.armUsesZeroCostExceptions() ) {
4487 // most arm do not use zero cost exceptions
4491 // create ObjectAddressSpace object for use by libunwind
4492 OAS
oas(*this, (uint8_t*)this->file().fileContent()+this->_machOSection
->offset());
4494 // use libuwind to parse __eh_frame data into array of CFI_Atom_Info
4496 msg
= libunwind::DwarfInstructions
<OAS
, libunwind::Registers_arm
>::parseCFIs(
4497 oas
, this->_machOSection
->addr(), this->_machOSection
->size(),
4498 cuStarts
, cuCount
, parser
.keepDwarfUnwind(), parser
.forceDwarfConversion(), parser
.neverConvertDwarf(),
4499 cfiArray
, count
, (void*)&parser
, warnFunc
);
4501 throwf("malformed __eh_frame section: %s", msg
);
4508 void CFISection
<arm64
>::cfiParse(class Parser
<arm64
>& parser
, uint8_t* buffer
,
4509 libunwind::CFI_Atom_Info
<CFISection
<arm64
>::OAS
>::CFI_Atom_Info cfiArray
[],
4510 uint32_t& count
, const pint_t cuStarts
[], uint32_t cuCount
)
4512 // copy __eh_frame data to buffer
4513 const uint32_t sectionSize
= this->_machOSection
->size();
4514 memcpy(buffer
, file().fileContent() + this->_machOSection
->offset(), sectionSize
);
4516 // and apply relocations
4517 const macho_relocation_info
<P
>* relocs
= (macho_relocation_info
<P
>*)(file().fileContent() + this->_machOSection
->reloff());
4518 const macho_relocation_info
<P
>* relocsEnd
= &relocs
[this->_machOSection
->nreloc()];
4519 for (const macho_relocation_info
<P
>* reloc
= relocs
; reloc
< relocsEnd
; ++reloc
) {
4520 uint64_t* p64
= (uint64_t*)&buffer
[reloc
->r_address()];
4521 uint32_t* p32
= (uint32_t*)&buffer
[reloc
->r_address()];
4522 uint32_t addend32
= E::get32(*p32
);
4523 uint64_t addend64
= E::get64(*p64
);
4525 switch ( reloc
->r_type() ) {
4526 case ARM64_RELOC_SUBTRACTOR
:
4527 value
= 0 - parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
4529 if ( reloc
->r_extern() )
4530 value
+= parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
4532 case ARM64_RELOC_UNSIGNED
:
4533 value
= parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
4535 case ARM64_RELOC_POINTER_TO_GOT
:
4536 // this is used for the reference to the personality function in CIEs
4537 // store the symbol number of the personality function for later use as a Fixup
4538 value
= reloc
->r_symbolnum();
4543 fprintf(stderr
, "CFISection::cfiParse() unexpected relocation type at r_address=0x%08X\n", reloc
->r_address());
4546 if ( reloc
->r_address() > sectionSize
)
4547 throwf("malformed __eh_frame relocation, offset (0x%08X) is beyond end of section,", reloc
->r_address());
4548 switch ( reloc
->r_length() ) {
4550 E::set64(*p64
, value
+ addend64
);
4553 E::set32(*p32
, value
+ addend32
);
4556 fprintf(stderr
, "CFISection::cfiParse() unexpected relocation size at r_address=0x%08X\n", reloc
->r_address());
4562 // create ObjectAddressSpace object for use by libunwind
4563 OAS
oas(*this, buffer
);
4565 // use libuwind to parse __eh_frame data into array of CFI_Atom_Info
4567 msg
= libunwind::DwarfInstructions
<OAS
, libunwind::Registers_arm64
>::parseCFIs(
4568 oas
, this->_machOSection
->addr(), this->_machOSection
->size(),
4569 cuStarts
, cuCount
, parser
.keepDwarfUnwind(), parser
.forceDwarfConversion(), parser
.neverConvertDwarf(),
4570 cfiArray
, count
, (void*)&parser
, warnFunc
);
4572 throwf("malformed __eh_frame section: %s", msg
);
4576 template <typename A
>
4577 uint32_t CFISection
<A
>::computeAtomCount(class Parser
<A
>& parser
,
4578 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
4579 const struct Parser
<A
>::CFI_CU_InfoArrays
& cfis
)
4581 return cfis
.cfiCount
;
4586 template <typename A
>
4587 uint32_t CFISection
<A
>::appendAtoms(class Parser
<A
>& parser
, uint8_t* p
,
4588 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
4589 const struct Parser
<A
>::CFI_CU_InfoArrays
& cfis
)
4591 this->_beginAtoms
= (Atom
<A
>*)p
;
4592 // walk CFI_Atom_Info array and create atom for each entry
4593 const CFI_Atom_Info
* start
= &cfis
.cfiArray
[0];
4594 const CFI_Atom_Info
* end
= &cfis
.cfiArray
[cfis
.cfiCount
];
4595 for(const CFI_Atom_Info
* a
=start
; a
< end
; ++a
) {
4596 Atom
<A
>* space
= (Atom
<A
>*)p
;
4597 new (space
) Atom
<A
>(*this, (a
->isCIE
? "CIE" : "FDE"), a
->address
, a
->size
,
4598 ld::Atom::definitionRegular
, ld::Atom::combineNever
, ld::Atom::scopeTranslationUnit
,
4599 ld::Atom::typeCFI
, ld::Atom::symbolTableNotInFinalLinkedImages
,
4600 false, false, false, ld::Atom::Alignment(0));
4601 p
+= sizeof(Atom
<A
>);
4603 this->_endAtoms
= (Atom
<A
>*)p
;
4604 return cfis
.cfiCount
;
4608 template <> bool CFISection
<x86_64
>::bigEndian() { return false; }
4609 template <> bool CFISection
<x86
>::bigEndian() { return false; }
4610 template <> bool CFISection
<arm
>::bigEndian() { return false; }
4611 template <> bool CFISection
<arm64
>::bigEndian() { return false; }
4615 void CFISection
<x86_64
>::addCiePersonalityFixups(class Parser
<x86_64
>& parser
, const CFI_Atom_Info
* cieInfo
)
4617 uint8_t personalityEncoding
= cieInfo
->u
.cieInfo
.personality
.encodingOfTargetAddress
;
4618 if ( personalityEncoding
== 0x9B ) {
4619 // compiler always produces X86_64_RELOC_GOT with addend of 4 to personality function
4620 // CFISection<x86_64>::cfiParse() set targetAddress to be symbolIndex + 4 + addressInCIE
4621 uint32_t symbolIndex
= cieInfo
->u
.cieInfo
.personality
.targetAddress
- 4
4622 - cieInfo
->address
- cieInfo
->u
.cieInfo
.personality
.offsetInCFI
;
4623 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(symbolIndex
);
4624 const char* personalityName
= parser
.nameFromSymbol(sym
);
4626 Atom
<x86_64
>* cieAtom
= this->findAtomByAddress(cieInfo
->address
);
4627 Parser
<x86_64
>::SourceLocation
src(cieAtom
, cieInfo
->u
.cieInfo
.personality
.offsetInCFI
);
4628 parser
.addFixup(src
, ld::Fixup::k1of3
, ld::Fixup::kindSetTargetAddress
, false, personalityName
);
4629 parser
.addFixup(src
, ld::Fixup::k2of3
, ld::Fixup::kindAddAddend
, 4);
4630 parser
.addFixup(src
, ld::Fixup::k3of3
, ld::Fixup::kindStoreX86PCRel32GOT
);
4632 else if ( personalityEncoding
!= 0 ) {
4633 throwf("unsupported address encoding (%02X) of personality function in CIE",
4634 personalityEncoding
);
4639 void CFISection
<x86
>::addCiePersonalityFixups(class Parser
<x86
>& parser
, const CFI_Atom_Info
* cieInfo
)
4641 uint8_t personalityEncoding
= cieInfo
->u
.cieInfo
.personality
.encodingOfTargetAddress
;
4642 if ( (personalityEncoding
== 0x9B) || (personalityEncoding
== 0x90) ) {
4643 uint32_t offsetInCFI
= cieInfo
->u
.cieInfo
.personality
.offsetInCFI
;
4644 uint32_t nlpAddr
= cieInfo
->u
.cieInfo
.personality
.targetAddress
;
4645 Atom
<x86
>* cieAtom
= this->findAtomByAddress(cieInfo
->address
);
4646 Atom
<x86
>* nlpAtom
= parser
.findAtomByAddress(nlpAddr
);
4647 assert(nlpAtom
->contentType() == ld::Atom::typeNonLazyPointer
);
4648 Parser
<x86
>::SourceLocation
src(cieAtom
, cieInfo
->u
.cieInfo
.personality
.offsetInCFI
);
4650 parser
.addFixup(src
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, nlpAtom
);
4651 parser
.addFixup(src
, ld::Fixup::k2of4
, ld::Fixup::kindSubtractTargetAddress
, cieAtom
);
4652 parser
.addFixup(src
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractAddend
, offsetInCFI
);
4653 parser
.addFixup(src
, ld::Fixup::k4of4
, ld::Fixup::kindStoreLittleEndian32
);
4655 else if ( personalityEncoding
!= 0 ) {
4656 throwf("unsupported address encoding (%02X) of personality function in CIE", personalityEncoding
);
4660 #if SUPPORT_ARCH_arm64
4662 void CFISection
<arm64
>::addCiePersonalityFixups(class Parser
<arm64
>& parser
, const CFI_Atom_Info
* cieInfo
)
4664 uint8_t personalityEncoding
= cieInfo
->u
.cieInfo
.personality
.encodingOfTargetAddress
;
4665 if ( personalityEncoding
== 0x9B ) {
4666 // compiler always produces ARM64_RELOC_GOT r_pcrel=1 to personality function
4667 // CFISection<arm64>::cfiParse() set targetAddress to be symbolIndex + addressInCIE
4668 uint32_t symbolIndex
= cieInfo
->u
.cieInfo
.personality
.targetAddress
4669 - cieInfo
->address
- cieInfo
->u
.cieInfo
.personality
.offsetInCFI
;
4670 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(symbolIndex
);
4671 const char* personalityName
= parser
.nameFromSymbol(sym
);
4673 Atom
<arm64
>* cieAtom
= this->findAtomByAddress(cieInfo
->address
);
4674 Parser
<arm64
>::SourceLocation
src(cieAtom
, cieInfo
->u
.cieInfo
.personality
.offsetInCFI
);
4675 parser
.addFixup(src
, ld::Fixup::k1of2
, ld::Fixup::kindSetTargetAddress
, false, personalityName
);
4676 parser
.addFixup(src
, ld::Fixup::k2of2
, ld::Fixup::kindStoreARM64PCRelToGOT
);
4678 else if ( personalityEncoding
!= 0 ) {
4679 throwf("unsupported address encoding (%02X) of personality function in CIE",
4680 personalityEncoding
);
4686 void CFISection
<arm
>::addCiePersonalityFixups(class Parser
<arm
>& parser
, const CFI_Atom_Info
* cieInfo
)
4688 uint8_t personalityEncoding
= cieInfo
->u
.cieInfo
.personality
.encodingOfTargetAddress
;
4689 if ( (personalityEncoding
== 0x9B) || (personalityEncoding
== 0x90) ) {
4690 uint32_t offsetInCFI
= cieInfo
->u
.cieInfo
.personality
.offsetInCFI
;
4691 uint32_t nlpAddr
= cieInfo
->u
.cieInfo
.personality
.targetAddress
;
4692 Atom
<arm
>* cieAtom
= this->findAtomByAddress(cieInfo
->address
);
4693 Atom
<arm
>* nlpAtom
= parser
.findAtomByAddress(nlpAddr
);
4694 assert(nlpAtom
->contentType() == ld::Atom::typeNonLazyPointer
);
4695 Parser
<arm
>::SourceLocation
src(cieAtom
, cieInfo
->u
.cieInfo
.personality
.offsetInCFI
);
4697 parser
.addFixup(src
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, nlpAtom
);
4698 parser
.addFixup(src
, ld::Fixup::k2of4
, ld::Fixup::kindSubtractTargetAddress
, cieAtom
);
4699 parser
.addFixup(src
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractAddend
, offsetInCFI
);
4700 parser
.addFixup(src
, ld::Fixup::k4of4
, ld::Fixup::kindStoreLittleEndian32
);
4702 else if ( personalityEncoding
!= 0 ) {
4703 throwf("unsupported address encoding (%02X) of personality function in CIE", personalityEncoding
);
4709 template <typename A
>
4710 void CFISection
<A
>::addCiePersonalityFixups(class Parser
<A
>& parser
, const CFI_Atom_Info
* cieInfo
)
4712 assert(0 && "addCiePersonalityFixups() not implemented for arch");
4715 template <typename A
>
4716 void CFISection
<A
>::makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
& cfis
)
4718 ld::Fixup::Kind store32
= bigEndian() ? ld::Fixup::kindStoreBigEndian32
: ld::Fixup::kindStoreLittleEndian32
;
4719 ld::Fixup::Kind store64
= bigEndian() ? ld::Fixup::kindStoreBigEndian64
: ld::Fixup::kindStoreLittleEndian64
;
4721 // add all references for FDEs, including implicit group references
4722 const CFI_Atom_Info
* end
= &cfis
.cfiArray
[cfis
.cfiCount
];
4723 for(const CFI_Atom_Info
* p
= &cfis
.cfiArray
[0]; p
< end
; ++p
) {
4725 // add reference to personality function if used
4726 if ( p
->u
.cieInfo
.personality
.targetAddress
!= CFI_INVALID_ADDRESS
) {
4727 this->addCiePersonalityFixups(parser
, p
);
4732 Atom
<A
>* fdeAtom
= this->findAtomByAddress(p
->address
);
4733 // find function Atom
4734 Atom
<A
>* functionAtom
= parser
.findAtomByAddress(p
->u
.fdeInfo
.function
.targetAddress
);
4736 Atom
<A
>* cieAtom
= this->findAtomByAddress(p
->u
.fdeInfo
.cie
.targetAddress
);
4738 Atom
<A
>* lsdaAtom
= NULL
;
4739 if ( p
->u
.fdeInfo
.lsda
.targetAddress
!= CFI_INVALID_ADDRESS
) {
4740 lsdaAtom
= parser
.findAtomByAddress(p
->u
.fdeInfo
.lsda
.targetAddress
);
4742 // add reference from FDE to CIE (always 32-bit pc-rel)
4743 typename Parser
<A
>::SourceLocation
fdeToCieSrc(fdeAtom
, p
->u
.fdeInfo
.cie
.offsetInCFI
);
4744 parser
.addFixup(fdeToCieSrc
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, fdeAtom
);
4745 parser
.addFixup(fdeToCieSrc
, ld::Fixup::k2of4
, ld::Fixup::kindAddAddend
, p
->u
.fdeInfo
.cie
.offsetInCFI
);
4746 parser
.addFixup(fdeToCieSrc
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractTargetAddress
, cieAtom
);
4747 parser
.addFixup(fdeToCieSrc
, ld::Fixup::k4of4
, store32
, cieAtom
);
4749 // add reference from FDE to function
4750 typename Parser
<A
>::SourceLocation
fdeToFuncSrc(fdeAtom
, p
->u
.fdeInfo
.function
.offsetInCFI
);
4751 switch (p
->u
.fdeInfo
.function
.encodingOfTargetAddress
) {
4752 case DW_EH_PE_pcrel
|DW_EH_PE_ptr
:
4753 if ( sizeof(typename
A::P::uint_t
) == 8 ) {
4754 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, functionAtom
);
4755 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k2of4
, ld::Fixup::kindSubtractTargetAddress
, fdeAtom
);
4756 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractAddend
, p
->u
.fdeInfo
.function
.offsetInCFI
);
4757 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k4of4
, store64
);
4760 // else fall into 32-bit case
4761 case DW_EH_PE_pcrel
|DW_EH_PE_sdata4
:
4762 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, functionAtom
);
4763 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k2of4
, ld::Fixup::kindSubtractTargetAddress
, fdeAtom
);
4764 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractAddend
, p
->u
.fdeInfo
.function
.offsetInCFI
);
4765 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k4of4
, store32
);
4768 throw "unsupported encoding in FDE of pointer to function";
4771 // add reference from FDE to LSDA
4772 typename Parser
<A
>::SourceLocation
fdeToLsdaSrc(fdeAtom
, p
->u
.fdeInfo
.lsda
.offsetInCFI
);
4773 if ( lsdaAtom
!= NULL
) {
4774 switch (p
->u
.fdeInfo
.lsda
.encodingOfTargetAddress
) {
4775 case DW_EH_PE_pcrel
|DW_EH_PE_ptr
:
4776 if ( sizeof(typename
A::P::uint_t
) == 8 ) {
4777 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, lsdaAtom
);
4778 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k2of4
, ld::Fixup::kindSubtractTargetAddress
, fdeAtom
);
4779 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractAddend
, p
->u
.fdeInfo
.lsda
.offsetInCFI
);
4780 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k4of4
, store64
);
4783 // else fall into 32-bit case
4784 case DW_EH_PE_pcrel
|DW_EH_PE_sdata4
:
4785 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, lsdaAtom
);
4786 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k2of4
, ld::Fixup::kindSubtractTargetAddress
, fdeAtom
);
4787 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractAddend
, p
->u
.fdeInfo
.lsda
.offsetInCFI
);
4788 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k4of4
, store32
);
4791 throw "unsupported encoding in FDE of pointer to LSDA";
4795 // FDE is in group lead by function atom
4796 typename Parser
<A
>::SourceLocation
fdeSrc(functionAtom
,0);
4797 parser
.addFixup(fdeSrc
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinateFDE
, fdeAtom
);
4799 // LSDA is in group lead by function atom
4800 if ( lsdaAtom
!= NULL
) {
4801 parser
.addFixup(fdeSrc
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinateLSDA
, lsdaAtom
);
4810 template <typename A
>
4811 const void* CFISection
<A
>::OAS::mappedAddress(pint_t addr
)
4813 if ( (_ehFrameStartAddr
<= addr
) && (addr
< _ehFrameEndAddr
) )
4814 return &_ehFrameContent
[addr
-_ehFrameStartAddr
];
4816 // requested bytes are not in __eh_frame section
4817 // this can occur when examining the instruction bytes in the __text
4818 File
<A
>& file
= _ehFrameSection
.file();
4819 for (uint32_t i
=0; i
< file
._sectionsArrayCount
; ++i
) {
4820 const macho_section
<typename
A::P
>* sect
= file
._sectionsArray
[i
]->machoSection();
4821 // TentativeDefinitionSection and AbsoluteSymbolSection have no mach-o section
4822 if ( sect
!= NULL
) {
4823 if ( (sect
->addr() <= addr
) && (addr
< (sect
->addr()+sect
->size())) ) {
4824 return file
.fileContent() + sect
->offset() + addr
- sect
->addr();
4828 throwf("__eh_frame parsing problem. Can't find target of reference to address 0x%08llX", (uint64_t)addr
);
4833 template <typename A
>
4834 uint64_t CFISection
<A
>::OAS::getULEB128(pint_t
& logicalAddr
, pint_t end
)
4836 uintptr_t size
= (end
- logicalAddr
);
4837 libunwind::LocalAddressSpace::pint_t laddr
= (libunwind::LocalAddressSpace::pint_t
)mappedAddress(logicalAddr
);
4838 libunwind::LocalAddressSpace::pint_t sladdr
= laddr
;
4839 uint64_t result
= libunwind::LocalAddressSpace::getULEB128(laddr
, laddr
+size
);
4840 logicalAddr
+= (laddr
-sladdr
);
4844 template <typename A
>
4845 int64_t CFISection
<A
>::OAS::getSLEB128(pint_t
& logicalAddr
, pint_t end
)
4847 uintptr_t size
= (end
- logicalAddr
);
4848 libunwind::LocalAddressSpace::pint_t laddr
= (libunwind::LocalAddressSpace::pint_t
)mappedAddress(logicalAddr
);
4849 libunwind::LocalAddressSpace::pint_t sladdr
= laddr
;
4850 int64_t result
= libunwind::LocalAddressSpace::getSLEB128(laddr
, laddr
+size
);
4851 logicalAddr
+= (laddr
-sladdr
);
4855 template <typename A
>
4856 typename
A::P::uint_t CFISection
<A
>::OAS::getEncodedP(pint_t
& addr
, pint_t end
, uint8_t encoding
)
4858 pint_t startAddr
= addr
;
4863 switch (encoding
& 0x0F) {
4865 result
= getP(addr
);
4866 p
+= sizeof(pint_t
);
4869 case DW_EH_PE_uleb128
:
4870 result
= getULEB128(addr
, end
);
4872 case DW_EH_PE_udata2
:
4873 result
= get16(addr
);
4877 case DW_EH_PE_udata4
:
4878 result
= get32(addr
);
4882 case DW_EH_PE_udata8
:
4883 result
= get64(addr
);
4887 case DW_EH_PE_sleb128
:
4888 result
= getSLEB128(addr
, end
);
4890 case DW_EH_PE_sdata2
:
4891 result
= (int16_t)get16(addr
);
4895 case DW_EH_PE_sdata4
:
4896 result
= (int32_t)get32(addr
);
4900 case DW_EH_PE_sdata8
:
4901 result
= get64(addr
);
4906 throwf("ObjectFileAddressSpace<A>::getEncodedP() encoding 0x%08X not supported", encoding
);
4909 // then add relative offset
4910 switch ( encoding
& 0x70 ) {
4911 case DW_EH_PE_absptr
:
4914 case DW_EH_PE_pcrel
:
4915 result
+= startAddr
;
4917 case DW_EH_PE_textrel
:
4918 throw "DW_EH_PE_textrel pointer encoding not supported";
4920 case DW_EH_PE_datarel
:
4921 throw "DW_EH_PE_datarel pointer encoding not supported";
4923 case DW_EH_PE_funcrel
:
4924 throw "DW_EH_PE_funcrel pointer encoding not supported";
4926 case DW_EH_PE_aligned
:
4927 throw "DW_EH_PE_aligned pointer encoding not supported";
4930 throwf("ObjectFileAddressSpace<A>::getEncodedP() encoding 0x%08X not supported", encoding
);
4934 // Note: DW_EH_PE_indirect is only used in CIEs to refernce the personality pointer
4935 // When parsing .o files that pointer contains zero, so we don't to return that.
4936 // Instead we skip the dereference and return the address of the pointer.
4937 // if ( encoding & DW_EH_PE_indirect )
4938 // result = getP(result);
4944 const char* CUSection
<x86_64
>::personalityName(class Parser
<x86_64
>& parser
, const macho_relocation_info
<x86_64::P
>* reloc
)
4946 if ( reloc
->r_extern() ) {
4947 assert((reloc
->r_type() == X86_64_RELOC_UNSIGNED
) && "wrong reloc type on personality column in __compact_unwind section");
4948 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
4949 return parser
.nameFromSymbol(sym
);
4952 const pint_t
* content
= (pint_t
*)(this->file().fileContent() + this->_machOSection
->offset() + reloc
->r_address());
4953 pint_t personalityAddr
= *content
;
4954 assert((parser
.sectionForAddress(personalityAddr
)->type() == ld::Section::typeCode
) && "personality column in __compact_unwind section is not pointer to function");
4955 // atoms may not be constructed yet, so scan symbol table for labels
4956 const char* name
= parser
.scanSymbolTableForAddress(personalityAddr
);
4962 const char* CUSection
<x86
>::personalityName(class Parser
<x86
>& parser
, const macho_relocation_info
<x86::P
>* reloc
)
4964 if ( reloc
->r_extern() ) {
4965 assert((reloc
->r_type() == GENERIC_RELOC_VANILLA
) && "wrong reloc type on personality column in __compact_unwind section");
4966 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
4967 return parser
.nameFromSymbol(sym
);
4970 // support __LD, __compact_unwind personality entries which are pointer to personality non-lazy pointer
4971 const pint_t
* content
= (pint_t
*)(this->file().fileContent() + this->_machOSection
->offset() + reloc
->r_address());
4972 pint_t nlPointerAddr
= *content
;
4973 Section
<x86
>* nlSection
= parser
.sectionForAddress(nlPointerAddr
);
4974 if ( nlSection
->type() == ld::Section::typeCode
) {
4975 // personality function is defined in this .o file, so this is a direct reference to it
4976 // atoms may not be constructed yet, so scan symbol table for labels
4977 const char* name
= parser
.scanSymbolTableForAddress(nlPointerAddr
);
4981 uint32_t symIndex
= parser
.symbolIndexFromIndirectSectionAddress(nlPointerAddr
, nlSection
->machoSection());
4982 const macho_nlist
<P
>& nlSymbol
= parser
.symbolFromIndex(symIndex
);
4983 return parser
.nameFromSymbol(nlSymbol
);
4988 #if SUPPORT_ARCH_arm64
4990 const char* CUSection
<arm64
>::personalityName(class Parser
<arm64
>& parser
, const macho_relocation_info
<arm64::P
>* reloc
)
4992 if ( reloc
->r_extern() ) {
4993 assert((reloc
->r_type() == ARM64_RELOC_UNSIGNED
) && "wrong reloc type on personality column in __compact_unwind section");
4994 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
4995 return parser
.nameFromSymbol(sym
);
4998 const pint_t
* content
= (pint_t
*)(this->file().fileContent() + this->_machOSection
->offset() + reloc
->r_address());
4999 pint_t personalityAddr
= *content
;
5000 Section
<arm64
>* personalitySection
= parser
.sectionForAddress(personalityAddr
);
5001 (void)personalitySection
;
5002 assert((personalitySection
->type() == ld::Section::typeCode
) && "personality column in __compact_unwind section is not pointer to function");
5003 // atoms may not be constructed yet, so scan symbol table for labels
5004 const char* name
= parser
.scanSymbolTableForAddress(personalityAddr
);
5010 #if SUPPORT_ARCH_arm_any
5012 const char* CUSection
<arm
>::personalityName(class Parser
<arm
>& parser
, const macho_relocation_info
<arm::P
>* reloc
)
5014 if ( reloc
->r_extern() ) {
5015 assert((reloc
->r_type() == ARM_RELOC_VANILLA
) && "wrong reloc type on personality column in __compact_unwind section");
5016 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
5017 return parser
.nameFromSymbol(sym
);
5020 // support __LD, __compact_unwind personality entries which are pointer to personality non-lazy pointer
5021 const pint_t
* content
= (pint_t
*)(this->file().fileContent() + this->_machOSection
->offset() + reloc
->r_address());
5022 pint_t nlPointerAddr
= *content
;
5023 Section
<arm
>* nlSection
= parser
.sectionForAddress(nlPointerAddr
);
5024 if ( nlSection
->type() == ld::Section::typeCode
) {
5025 // personality function is defined in this .o file, so this is a direct reference to it
5026 // atoms may not be constructed yet, so scan symbol table for labels
5027 const char* name
= parser
.scanSymbolTableForAddress(nlPointerAddr
);
5031 uint32_t symIndex
= parser
.symbolIndexFromIndirectSectionAddress(nlPointerAddr
, nlSection
->machoSection());
5032 const macho_nlist
<P
>& nlSymbol
= parser
.symbolFromIndex(symIndex
);
5033 return parser
.nameFromSymbol(nlSymbol
);
5040 template <typename A
>
5041 const char* CUSection
<A
>::personalityName(class Parser
<A
>& parser
, const macho_relocation_info
<P
>* reloc
)
5047 bool CUSection
<x86
>::encodingMeansUseDwarf(compact_unwind_encoding_t enc
)
5049 return ((enc
& UNWIND_X86_MODE_MASK
) == UNWIND_X86_MODE_DWARF
);
5053 bool CUSection
<x86_64
>::encodingMeansUseDwarf(compact_unwind_encoding_t enc
)
5055 return ((enc
& UNWIND_X86_64_MODE_MASK
) == UNWIND_X86_64_MODE_DWARF
);
5058 #if SUPPORT_ARCH_arm_any
5060 bool CUSection
<arm
>::encodingMeansUseDwarf(compact_unwind_encoding_t enc
)
5062 return ((enc
& UNWIND_ARM_MODE_MASK
) == UNWIND_ARM_MODE_DWARF
);
5066 #if SUPPORT_ARCH_arm64
5068 bool CUSection
<arm64
>::encodingMeansUseDwarf(compact_unwind_encoding_t enc
)
5070 return ((enc
& UNWIND_ARM64_MODE_MASK
) == UNWIND_ARM64_MODE_DWARF
);
5074 template <typename A
>
5075 int CUSection
<A
>::infoSorter(const void* l
, const void* r
)
5077 // sort references by symbol index, then address
5078 const Info
* left
= (Info
*)l
;
5079 const Info
* right
= (Info
*)r
;
5080 if ( left
->functionSymbolIndex
== right
->functionSymbolIndex
)
5081 return (left
->functionStartAddress
- right
->functionStartAddress
);
5083 return (left
->functionSymbolIndex
- right
->functionSymbolIndex
);
5086 template <typename A
>
5087 void CUSection
<A
>::parse(class Parser
<A
>& parser
, uint32_t cnt
, Info array
[])
5089 // walk section content and copy to Info array
5090 const macho_compact_unwind_entry
<P
>* const entries
= (macho_compact_unwind_entry
<P
>*)(this->file().fileContent() + this->_machOSection
->offset());
5091 for (uint32_t i
=0; i
< cnt
; ++i
) {
5092 Info
* info
= &array
[i
];
5093 const macho_compact_unwind_entry
<P
>* entry
= &entries
[i
];
5094 info
->functionStartAddress
= entry
->codeStart();
5095 info
->functionSymbolIndex
= 0xFFFFFFFF;
5096 info
->rangeLength
= entry
->codeLen();
5097 info
->compactUnwindInfo
= entry
->compactUnwindInfo();
5098 info
->personality
= NULL
;
5099 info
->lsdaAddress
= entry
->lsda();
5100 info
->function
= NULL
;
5102 if ( (info
->compactUnwindInfo
& UNWIND_PERSONALITY_MASK
) != 0 )
5103 warning("no bits should be set in UNWIND_PERSONALITY_MASK of compact unwind encoding in __LD,__compact_unwind section");
5104 if ( info
->lsdaAddress
!= 0 ) {
5105 info
->compactUnwindInfo
|= UNWIND_HAS_LSDA
;
5109 // scan relocs, extern relocs are needed for personality references (possibly for function/lsda refs??)
5110 const uint32_t sectionSize
= this->_machOSection
->size();
5111 const macho_relocation_info
<P
>* relocs
= (macho_relocation_info
<P
>*)(this->file().fileContent() + this->_machOSection
->reloff());
5112 const macho_relocation_info
<P
>* relocsEnd
= &relocs
[this->_machOSection
->nreloc()];
5113 for (const macho_relocation_info
<P
>* reloc
= relocs
; reloc
< relocsEnd
; ++reloc
) {
5114 if ( reloc
->r_address() & R_SCATTERED
)
5116 if ( reloc
->r_address() > sectionSize
)
5117 throwf("malformed __compact_unwind relocation, offset (0x%08X) is beyond end of section,", reloc
->r_address());
5118 if ( reloc
->r_extern() ) {
5119 // only expect external relocs on some colummns
5120 if ( (reloc
->r_address() % sizeof(macho_compact_unwind_entry
<P
>)) == macho_compact_unwind_entry
<P
>::personalityFieldOffset() ) {
5121 uint32_t entryIndex
= reloc
->r_address() / sizeof(macho_compact_unwind_entry
<P
>);
5122 array
[entryIndex
].personality
= this->personalityName(parser
, reloc
);
5124 else if ( (reloc
->r_address() % sizeof(macho_compact_unwind_entry
<P
>)) == macho_compact_unwind_entry
<P
>::lsdaFieldOffset() ) {
5125 uint32_t entryIndex
= reloc
->r_address() / sizeof(macho_compact_unwind_entry
<P
>);
5126 const macho_nlist
<P
>& lsdaSym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
5127 if ( (lsdaSym
.n_type() & N_TYPE
) == N_SECT
)
5128 array
[entryIndex
].lsdaAddress
= lsdaSym
.n_value();
5130 warning("unexpected extern relocation to lsda in __compact_unwind section");
5132 else if ( (reloc
->r_address() % sizeof(macho_compact_unwind_entry
<P
>)) == macho_compact_unwind_entry
<P
>::codeStartFieldOffset() ) {
5133 uint32_t entryIndex
= reloc
->r_address() / sizeof(macho_compact_unwind_entry
<P
>);
5134 array
[entryIndex
].functionSymbolIndex
= reloc
->r_symbolnum();
5135 array
[entryIndex
].functionStartAddress
+= parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
5138 warning("unexpected extern relocation in __compact_unwind section");
5142 if ( (reloc
->r_address() % sizeof(macho_compact_unwind_entry
<P
>)) == macho_compact_unwind_entry
<P
>::personalityFieldOffset() ) {
5143 uint32_t entryIndex
= reloc
->r_address() / sizeof(macho_compact_unwind_entry
<P
>);
5144 array
[entryIndex
].personality
= this->personalityName(parser
, reloc
);
5149 // sort array by function start address so unwind infos will be contiguous for a given function
5150 ::qsort(array
, cnt
, sizeof(Info
), infoSorter
);
5153 template <typename A
>
5154 uint32_t CUSection
<A
>::count()
5156 const macho_section
<P
>* machoSect
= this->machoSection();
5157 if ( (machoSect
->size() % sizeof(macho_compact_unwind_entry
<P
>)) != 0 )
5158 throw "malformed __LD,__compact_unwind section, bad length";
5160 return machoSect
->size() / sizeof(macho_compact_unwind_entry
<P
>);
5163 template <typename A
>
5164 void CUSection
<A
>::makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
& cus
)
5166 Info
* const arrayStart
= cus
.cuArray
;
5167 Info
* const arrayEnd
= &cus
.cuArray
[cus
.cuCount
];
5168 for (Info
* info
=arrayStart
; info
< arrayEnd
; ++info
) {
5169 // find function atom from address
5170 info
->function
= parser
.findAtomByAddress(info
->functionStartAddress
);
5171 // find lsda atom from address
5172 if ( info
->lsdaAddress
!= 0 ) {
5173 info
->lsda
= parser
.findAtomByAddress(info
->lsdaAddress
);
5174 // add lsda subordinate
5175 typename Parser
<A
>::SourceLocation
src(info
->function
, info
->functionStartAddress
- info
->function
->objectAddress());
5176 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinateLSDA
, info
->lsda
);
5178 if ( info
->personality
!= NULL
) {
5179 // add personality subordinate
5180 typename Parser
<A
>::SourceLocation
src(info
->function
, info
->functionStartAddress
- info
->function
->objectAddress());
5181 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinatePersonality
, false, info
->personality
);
5187 template <typename A
>
5188 SymboledSection
<A
>::SymboledSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
5189 : Section
<A
>(f
, s
), _type(ld::Atom::typeUnclassified
)
5191 switch ( s
->flags() & SECTION_TYPE
) {
5193 _type
= ld::Atom::typeZeroFill
;
5195 case S_MOD_INIT_FUNC_POINTERS
:
5196 _type
= ld::Atom::typeInitializerPointers
;
5198 case S_MOD_TERM_FUNC_POINTERS
:
5199 _type
= ld::Atom::typeTerminatorPointers
;
5201 case S_THREAD_LOCAL_VARIABLES
:
5202 _type
= ld::Atom::typeTLV
;
5204 case S_THREAD_LOCAL_ZEROFILL
:
5205 _type
= ld::Atom::typeTLVZeroFill
;
5207 case S_THREAD_LOCAL_REGULAR
:
5208 _type
= ld::Atom::typeTLVInitialValue
;
5210 case S_THREAD_LOCAL_INIT_FUNCTION_POINTERS
:
5211 _type
= ld::Atom::typeTLVInitializerPointers
;
5214 if ( strncmp(s
->sectname(), "__gcc_except_tab", 16) == 0 )
5215 _type
= ld::Atom::typeLSDA
;
5216 else if ( this->type() == ld::Section::typeInitializerPointers
)
5217 _type
= ld::Atom::typeInitializerPointers
;
5223 template <typename A
>
5224 bool SymboledSection
<A
>::dontDeadStrip()
5227 case ld::Atom::typeInitializerPointers
:
5228 case ld::Atom::typeTerminatorPointers
:
5231 // model an object file without MH_SUBSECTIONS_VIA_SYMBOLS as one in which nothing can be dead stripped
5232 if ( ! this->_file
.canScatterAtoms() )
5235 return Section
<A
>::dontDeadStrip();
5241 template <typename A
>
5242 uint32_t SymboledSection
<A
>::computeAtomCount(class Parser
<A
>& parser
,
5243 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
5244 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
5246 const pint_t startAddr
= this->_machOSection
->addr();
5247 const pint_t endAddr
= startAddr
+ this->_machOSection
->size();
5248 const uint32_t sectNum
= this->sectionNum(parser
);
5253 const macho_nlist
<P
>* sym
;
5254 while ( it
.next(parser
, *this, sectNum
, startAddr
, endAddr
, &addr
, &size
, &sym
) ) {
5257 //fprintf(stderr, "computeAtomCount(%s,%s) => %d\n", this->segmentName(), this->sectionName(), count);
5261 template <typename A
>
5262 uint32_t SymboledSection
<A
>::appendAtoms(class Parser
<A
>& parser
, uint8_t* p
,
5263 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
5264 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
5266 this->_beginAtoms
= (Atom
<A
>*)p
;
5268 //fprintf(stderr, "SymboledSection::appendAtoms() in section %s\n", this->_machOSection->sectname());
5269 const pint_t startAddr
= this->_machOSection
->addr();
5270 const pint_t endAddr
= startAddr
+ this->_machOSection
->size();
5271 const uint32_t sectNum
= this->sectionNum(parser
);
5276 const macho_nlist
<P
>* label
;
5277 while ( it
.next(parser
, *this, sectNum
, startAddr
, endAddr
, &addr
, &size
, &label
) ) {
5278 Atom
<A
>* allocatedSpace
= (Atom
<A
>*)p
;
5279 // is break because of label or CFI?
5280 if ( label
!= NULL
) {
5281 // The size is computed based on the address of the next label (or the end of the section for the last label)
5282 // If there are two labels at the same address, we want them one to be an alias of the other.
5283 // If the label is at the end of a section, it is has zero size, but is not an alias
5284 const bool isAlias
= ( (size
== 0) && (addr
< endAddr
) );
5285 new (allocatedSpace
) Atom
<A
>(*this, parser
, *label
, size
, isAlias
);
5287 this->_hasAliases
= true;
5288 if ( parser
.altEntryFromSymbol(*label
) )
5289 this->_altEntries
.insert(allocatedSpace
);
5292 ld::Atom::SymbolTableInclusion inclusion
= ld::Atom::symbolTableNotIn
;
5293 ld::Atom::ContentType ctype
= this->contentType();
5294 if ( ctype
== ld::Atom::typeLSDA
)
5295 inclusion
= ld::Atom::symbolTableInWithRandomAutoStripLabel
;
5296 new (allocatedSpace
) Atom
<A
>(*this, "anon", addr
, size
, ld::Atom::definitionRegular
, ld::Atom::combineNever
,
5297 ld::Atom::scopeTranslationUnit
, ctype
, inclusion
,
5298 this->dontDeadStrip(), false, false, this->alignmentForAddress(addr
));
5300 p
+= sizeof(Atom
<A
>);
5304 this->_endAtoms
= (Atom
<A
>*)p
;
5310 ld::Atom::SymbolTableInclusion ImplicitSizeSection
<arm64
>::symbolTableInclusion()
5312 return ld::Atom::symbolTableInWithRandomAutoStripLabel
;
5315 template <typename A
>
5316 ld::Atom::SymbolTableInclusion ImplicitSizeSection
<A
>::symbolTableInclusion()
5318 return ld::Atom::symbolTableNotIn
;
5322 template <typename A
>
5323 uint32_t ImplicitSizeSection
<A
>::computeAtomCount(class Parser
<A
>& parser
,
5324 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
5325 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
5328 const macho_section
<P
>* sect
= this->machoSection();
5329 const pint_t startAddr
= sect
->addr();
5330 const pint_t endAddr
= startAddr
+ sect
->size();
5331 for (pint_t addr
= startAddr
; addr
< endAddr
; addr
+= elementSizeAtAddress(addr
) ) {
5332 if ( useElementAt(parser
, it
, addr
) )
5335 if ( it
.fileHasOverlappingSymbols
&& (sect
->size() != 0) && (this->combine(parser
, startAddr
) == ld::Atom::combineByNameAndContent
) ) {
5336 // if there are multiple labels in this section for the same address, then clone them into multi atoms
5337 pint_t prevSymbolAddr
= (pint_t
)(-1);
5338 uint8_t prevSymbolSectNum
= 0;
5339 bool prevIgnore
= false;
5340 for(uint32_t i
=0; i
< it
.sortedSymbolCount
; ++i
) {
5341 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(it
.sortedSymbolIndexes
[i
]);
5342 const pint_t symbolAddr
= sym
.n_value();
5343 const uint8_t symbolSectNum
= sym
.n_sect();
5344 const bool ignore
= this->ignoreLabel(parser
.nameFromSymbol(sym
));
5345 if ( !ignore
&& !prevIgnore
&& (symbolAddr
== prevSymbolAddr
) && (prevSymbolSectNum
== symbolSectNum
) && (symbolSectNum
== this->sectionNum(parser
)) ) {
5348 prevSymbolAddr
= symbolAddr
;
5349 prevSymbolSectNum
= symbolSectNum
;
5350 prevIgnore
= ignore
;
5356 template <typename A
>
5357 uint32_t ImplicitSizeSection
<A
>::appendAtoms(class Parser
<A
>& parser
, uint8_t* p
,
5358 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
5359 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
5361 this->_beginAtoms
= (Atom
<A
>*)p
;
5363 const macho_section
<P
>* sect
= this->machoSection();
5364 const pint_t startAddr
= sect
->addr();
5365 const pint_t endAddr
= startAddr
+ sect
->size();
5366 const uint32_t sectNum
= this->sectionNum(parser
);
5367 //fprintf(stderr, "ImplicitSizeSection::appendAtoms() in section %s\n", sect->sectname());
5371 const macho_nlist
<P
>* foundLabel
;
5372 Atom
<A
>* allocatedSpace
;
5373 while ( it
.next(parser
, *this, sectNum
, startAddr
, endAddr
, &foundAddr
, &size
, &foundLabel
) ) {
5374 if ( foundLabel
!= NULL
) {
5376 pint_t labeledAtomSize
= this->elementSizeAtAddress(foundAddr
);
5377 allocatedSpace
= (Atom
<A
>*)p
;
5378 if ( this->ignoreLabel(parser
.nameFromSymbol(*foundLabel
)) ) {
5380 // <rdar://problem/10018737>
5381 // a size of zero means there is another label at same location
5382 // and we are supposed to ignore this label
5386 //fprintf(stderr, " 0x%08llX make annon, size=%lld\n", (uint64_t)foundAddr, (uint64_t)size);
5387 new (allocatedSpace
) Atom
<A
>(*this, this->unlabeledAtomName(parser
, foundAddr
), foundAddr
,
5388 this->elementSizeAtAddress(foundAddr
), this->definition(),
5389 this->combine(parser
, foundAddr
), this->scopeAtAddress(parser
, foundAddr
),
5390 this->contentType(), this->symbolTableInclusion(),
5391 this->dontDeadStrip(), false, false, this->alignmentForAddress(foundAddr
));
5395 // make named atom for label
5396 //fprintf(stderr, " 0x%08llX make labeled\n", (uint64_t)foundAddr);
5397 new (allocatedSpace
) Atom
<A
>(*this, parser
, *foundLabel
, labeledAtomSize
);
5401 p
+= sizeof(Atom
<A
>);
5402 foundAddr
+= labeledAtomSize
;
5403 size
-= labeledAtomSize
;
5406 // some number of anonymous atoms
5407 for (pint_t addr
= foundAddr
; addr
< (foundAddr
+size
); addr
+= elementSizeAtAddress(addr
) ) {
5408 // make anon atoms for area before label
5409 if ( this->useElementAt(parser
, it
, addr
) ) {
5410 //fprintf(stderr, " 0x%08llX make annon, size=%lld\n", (uint64_t)addr, (uint64_t)elementSizeAtAddress(addr));
5411 allocatedSpace
= (Atom
<A
>*)p
;
5412 new (allocatedSpace
) Atom
<A
>(*this, this->unlabeledAtomName(parser
, addr
), addr
, this->elementSizeAtAddress(addr
),
5413 this->definition(), this->combine(parser
, addr
), this->scopeAtAddress(parser
, addr
),
5414 this->contentType(), this->symbolTableInclusion(),
5415 this->dontDeadStrip(), false, false, this->alignmentForAddress(addr
));
5417 p
+= sizeof(Atom
<A
>);
5422 this->_endAtoms
= (Atom
<A
>*)p
;
5427 template <typename A
>
5428 bool Literal4Section
<A
>::ignoreLabel(const char* label
) const
5430 return (label
[0] == 'L') || (label
[0] == 'l');
5433 template <typename A
>
5434 unsigned long Literal4Section
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5436 const uint32_t* literalContent
= (uint32_t*)atom
->contentPointer();
5437 return *literalContent
;
5440 template <typename A
>
5441 bool Literal4Section
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5442 const ld::IndirectBindingTable
& ind
) const
5444 assert(this->type() == rhs
.section().type());
5445 const uint32_t* literalContent
= (uint32_t*)atom
->contentPointer();
5447 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5448 assert(rhsAtom
!= NULL
);
5449 if ( rhsAtom
!= NULL
) {
5450 const uint32_t* rhsLiteralContent
= (uint32_t*)rhsAtom
->contentPointer();
5451 return (*literalContent
== *rhsLiteralContent
);
5457 template <typename A
>
5458 bool Literal8Section
<A
>::ignoreLabel(const char* label
) const
5460 return (label
[0] == 'L') || (label
[0] == 'l');
5463 template <typename A
>
5464 unsigned long Literal8Section
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5467 const uint64_t* literalContent
= (uint64_t*)atom
->contentPointer();
5468 return *literalContent
;
5470 unsigned long hash
= 5381;
5471 const uint8_t* byteContent
= atom
->contentPointer();
5472 for (int i
=0; i
< 8; ++i
) {
5473 hash
= hash
* 33 + byteContent
[i
];
5479 template <typename A
>
5480 bool Literal8Section
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5481 const ld::IndirectBindingTable
& ind
) const
5483 if ( rhs
.section().type() != ld::Section::typeLiteral8
)
5485 assert(this->type() == rhs
.section().type());
5486 const uint64_t* literalContent
= (uint64_t*)atom
->contentPointer();
5488 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5489 assert(rhsAtom
!= NULL
);
5490 if ( rhsAtom
!= NULL
) {
5491 const uint64_t* rhsLiteralContent
= (uint64_t*)rhsAtom
->contentPointer();
5492 return (*literalContent
== *rhsLiteralContent
);
5497 template <typename A
>
5498 bool Literal16Section
<A
>::ignoreLabel(const char* label
) const
5500 return (label
[0] == 'L') || (label
[0] == 'l');
5503 template <typename A
>
5504 unsigned long Literal16Section
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5506 unsigned long hash
= 5381;
5507 const uint8_t* byteContent
= atom
->contentPointer();
5508 for (int i
=0; i
< 16; ++i
) {
5509 hash
= hash
* 33 + byteContent
[i
];
5514 template <typename A
>
5515 bool Literal16Section
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5516 const ld::IndirectBindingTable
& ind
) const
5518 if ( rhs
.section().type() != ld::Section::typeLiteral16
)
5520 assert(this->type() == rhs
.section().type());
5521 const uint64_t* literalContent
= (uint64_t*)atom
->contentPointer();
5523 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5524 assert(rhsAtom
!= NULL
);
5525 if ( rhsAtom
!= NULL
) {
5526 const uint64_t* rhsLiteralContent
= (uint64_t*)rhsAtom
->contentPointer();
5527 return ((literalContent
[0] == rhsLiteralContent
[0]) && (literalContent
[1] == rhsLiteralContent
[1]));
5534 template <typename A
>
5535 typename
A::P::uint_t CStringSection
<A
>::elementSizeAtAddress(pint_t addr
)
5537 const macho_section
<P
>* sect
= this->machoSection();
5538 const char* stringContent
= (char*)(this->file().fileContent() + sect
->offset() + addr
- sect
->addr());
5539 return strlen(stringContent
) + 1;
5542 template <typename A
>
5543 bool CStringSection
<A
>::useElementAt(Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, pint_t addr
)
5548 template <typename A
>
5549 bool CStringSection
<A
>::ignoreLabel(const char* label
) const
5551 return (label
[0] == 'L') || (label
[0] == 'l');
5555 template <typename A
>
5556 Atom
<A
>* CStringSection
<A
>::findAtomByAddress(pint_t addr
)
5558 Atom
<A
>* result
= this->findContentAtomByAddress(addr
, this->_beginAtoms
, this->_endAtoms
);
5562 template <typename A
>
5563 unsigned long CStringSection
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5565 unsigned long hash
= 5381;
5566 const char* stringContent
= (char*)atom
->contentPointer();
5567 for (const char* s
= stringContent
; *s
!= '\0'; ++s
) {
5568 hash
= hash
* 33 + *s
;
5574 template <typename A
>
5575 bool CStringSection
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5576 const ld::IndirectBindingTable
& ind
) const
5578 if ( rhs
.section().type() != ld::Section::typeCString
)
5580 assert(this->type() == rhs
.section().type());
5581 assert(strcmp(this->sectionName(), rhs
.section().sectionName())== 0);
5582 assert(strcmp(this->segmentName(), rhs
.section().segmentName())== 0);
5583 const char* stringContent
= (char*)atom
->contentPointer();
5585 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5586 assert(rhsAtom
!= NULL
);
5587 if ( rhsAtom
!= NULL
) {
5588 if ( atom
->_size
!= rhsAtom
->_size
)
5590 const char* rhsStringContent
= (char*)rhsAtom
->contentPointer();
5591 return (strcmp(stringContent
, rhsStringContent
) == 0);
5598 ld::Fixup::Kind NonLazyPointerSection
<x86
>::fixupKind()
5600 return ld::Fixup::kindStoreLittleEndian32
;
5604 ld::Fixup::Kind NonLazyPointerSection
<arm
>::fixupKind()
5606 return ld::Fixup::kindStoreLittleEndian32
;
5610 ld::Fixup::Kind NonLazyPointerSection
<arm64
>::fixupKind()
5612 return ld::Fixup::kindStoreLittleEndian64
;
5617 void NonLazyPointerSection
<x86_64
>::makeFixups(class Parser
<x86_64
>& parser
, const struct Parser
<x86_64
>::CFI_CU_InfoArrays
&)
5619 assert(0 && "x86_64 should not have non-lazy-pointer sections in .o files");
5622 template <typename A
>
5623 void NonLazyPointerSection
<A
>::makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&)
5625 // add references for each NLP atom based on indirect symbol table
5626 const macho_section
<P
>* sect
= this->machoSection();
5627 const pint_t endAddr
= sect
->addr() + sect
->size();
5628 for( pint_t addr
= sect
->addr(); addr
< endAddr
; addr
+= sizeof(pint_t
)) {
5629 typename Parser
<A
>::SourceLocation src
;
5630 typename Parser
<A
>::TargetDesc target
;
5631 src
.atom
= this->findAtomByAddress(addr
);
5632 src
.offsetInAtom
= 0;
5633 uint32_t symIndex
= parser
.symbolIndexFromIndirectSectionAddress(addr
, sect
);
5636 target
.weakImport
= false;
5638 if ( symIndex
== INDIRECT_SYMBOL_LOCAL
) {
5639 // use direct reference for local symbols
5640 const pint_t
* nlpContent
= (pint_t
*)(this->file().fileContent() + sect
->offset() + addr
- sect
->addr());
5641 pint_t targetAddr
= P::getP(*nlpContent
);
5642 target
.atom
= parser
.findAtomByAddress(targetAddr
);
5643 target
.weakImport
= false;
5644 target
.addend
= (targetAddr
- target
.atom
->objectAddress());
5645 // <rdar://problem/8385011> if pointer to thumb function, mask of thumb bit (not an addend of +1)
5646 if ( target
.atom
->isThumb() )
5647 target
.addend
&= (-2);
5648 assert(src
.atom
->combine() == ld::Atom::combineNever
);
5651 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(symIndex
);
5652 // use direct reference for local symbols
5653 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && ((sym
.n_type() & N_EXT
) == 0) ) {
5654 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
5655 assert(src
.atom
->combine() == ld::Atom::combineNever
);
5658 target
.name
= parser
.nameFromSymbol(sym
);
5659 target
.weakImport
= parser
.weakImportFromSymbol(sym
);
5660 assert(src
.atom
->combine() == ld::Atom::combineByNameAndReferences
);
5663 parser
.addFixups(src
, this->fixupKind(), target
);
5667 template <typename A
>
5668 ld::Atom::Combine NonLazyPointerSection
<A
>::combine(Parser
<A
>& parser
, pint_t addr
)
5670 const macho_section
<P
>* sect
= this->machoSection();
5671 uint32_t symIndex
= parser
.symbolIndexFromIndirectSectionAddress(addr
, sect
);
5672 if ( symIndex
== INDIRECT_SYMBOL_LOCAL
)
5673 return ld::Atom::combineNever
;
5675 // don't coalesce non-lazy-pointers to local symbols
5676 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(symIndex
);
5677 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && ((sym
.n_type() & N_EXT
) == 0) )
5678 return ld::Atom::combineNever
;
5680 return ld::Atom::combineByNameAndReferences
;
5683 template <typename A
>
5684 const char* NonLazyPointerSection
<A
>::targetName(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
)
5686 assert(atom
->combine() == ld::Atom::combineByNameAndReferences
);
5687 assert(atom
->fixupCount() == 1);
5688 ld::Fixup::iterator fit
= atom
->fixupsBegin();
5689 const char* name
= NULL
;
5690 switch ( fit
->binding
) {
5691 case ld::Fixup::bindingByNameUnbound
:
5694 case ld::Fixup::bindingByContentBound
:
5695 name
= fit
->u
.target
->name();
5697 case ld::Fixup::bindingsIndirectlyBound
:
5698 name
= ind
.indirectName(fit
->u
.bindingIndex
);
5703 assert(name
!= NULL
);
5707 template <typename A
>
5708 unsigned long NonLazyPointerSection
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5710 assert(atom
->combine() == ld::Atom::combineByNameAndReferences
);
5711 unsigned long hash
= 9508;
5712 for (const char* s
= this->targetName(atom
, ind
); *s
!= '\0'; ++s
) {
5713 hash
= hash
* 33 + *s
;
5718 template <typename A
>
5719 bool NonLazyPointerSection
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5720 const ld::IndirectBindingTable
& indirectBindingTable
) const
5722 if ( rhs
.section().type() != ld::Section::typeNonLazyPointer
)
5724 assert(this->type() == rhs
.section().type());
5725 // there can be many non-lazy pointer in different section names
5726 // we only want to coalesce in same section name
5727 if ( *this != rhs
.section() )
5729 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5730 assert(rhsAtom
!= NULL
);
5731 const char* thisName
= this->targetName(atom
, indirectBindingTable
);
5732 const char* rhsName
= this->targetName(rhsAtom
, indirectBindingTable
);
5733 return (strcmp(thisName
, rhsName
) == 0);
5736 template <typename A
>
5737 ld::Atom::Scope NonLazyPointerSection
<A
>::scopeAtAddress(Parser
<A
>& parser
, pint_t addr
)
5739 const macho_section
<P
>* sect
= this->machoSection();
5740 uint32_t symIndex
= parser
.symbolIndexFromIndirectSectionAddress(addr
, sect
);
5741 if ( symIndex
== INDIRECT_SYMBOL_LOCAL
)
5742 return ld::Atom::scopeTranslationUnit
;
5744 return ld::Atom::scopeLinkageUnit
;
5749 template <typename A
>
5750 ld::Atom::Combine TLVPointerSection
<A
>::combine(Parser
<A
>& parser
, pint_t addr
)
5752 return ld::Atom::combineByNameAndReferences
;
5756 template <typename A
>
5757 const char* TLVPointerSection
<A
>::targetName(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
, bool* isStatic
)
5759 assert(atom
->combine() == ld::Atom::combineByNameAndReferences
);
5760 assert(atom
->fixupCount() == 1);
5762 ld::Fixup::iterator fit
= atom
->fixupsBegin();
5763 const char* name
= NULL
;
5764 switch ( fit
->binding
) {
5765 case ld::Fixup::bindingByNameUnbound
:
5768 case ld::Fixup::bindingByContentBound
:
5769 name
= fit
->u
.target
->name();
5771 case ld::Fixup::bindingsIndirectlyBound
:
5772 name
= ind
.indirectName(fit
->u
.bindingIndex
);
5774 case ld::Fixup::bindingDirectlyBound
:
5775 name
= fit
->u
.target
->name();
5776 *isStatic
= (fit
->u
.target
->scope() == ld::Atom::scopeTranslationUnit
);
5781 assert(name
!= NULL
);
5785 template <typename A
>
5786 unsigned long TLVPointerSection
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5788 assert(atom
->combine() == ld::Atom::combineByNameAndReferences
);
5789 unsigned long hash
= 9508;
5791 for (const char* s
= this->targetName(atom
, ind
, &isStatic
); *s
!= '\0'; ++s
) {
5792 hash
= hash
* 33 + *s
;
5797 template <typename A
>
5798 bool TLVPointerSection
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5799 const ld::IndirectBindingTable
& indirectBindingTable
) const
5801 if ( rhs
.section().type() != ld::Section::typeTLVPointers
)
5803 assert(this->type() == rhs
.section().type());
5804 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5805 assert(rhsAtom
!= NULL
);
5808 const char* thisName
= this->targetName(atom
, indirectBindingTable
, &thisIsStatic
);
5809 const char* rhsName
= this->targetName(rhsAtom
, indirectBindingTable
, &rhsIsStatic
);
5810 return !thisIsStatic
&& !rhsIsStatic
&& (strcmp(thisName
, rhsName
) == 0);
5814 template <typename A
>
5815 const uint8_t* CFStringSection
<A
>::targetContent(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
,
5816 ContentType
* ct
, unsigned int* count
)
5818 *ct
= contentUnknown
;
5819 for (ld::Fixup::iterator fit
=atom
->fixupsBegin(), end
=atom
->fixupsEnd(); fit
!= end
; ++fit
) {
5820 const ld::Atom
* targetAtom
= NULL
;
5821 switch ( fit
->binding
) {
5822 case ld::Fixup::bindingByNameUnbound
:
5823 // ignore reference to ___CFConstantStringClassReference
5824 // we are just looking for reference to backing string data
5825 assert(fit
->offsetInAtom
== 0);
5826 assert(strcmp(fit
->u
.name
, "___CFConstantStringClassReference") == 0);
5828 case ld::Fixup::bindingDirectlyBound
:
5829 case ld::Fixup::bindingByContentBound
:
5830 targetAtom
= fit
->u
.target
;
5832 case ld::Fixup::bindingsIndirectlyBound
:
5833 targetAtom
= ind
.indirectAtom(fit
->u
.bindingIndex
);
5836 assert(0 && "bad binding type");
5838 assert(targetAtom
!= NULL
);
5839 const Atom
<A
>* target
= dynamic_cast<const Atom
<A
>*>(targetAtom
);
5840 if ( targetAtom
->section().type() == ld::Section::typeCString
) {
5842 *count
= targetAtom
->size();
5844 else if ( targetAtom
->section().type() == ld::Section::typeUTF16Strings
) {
5846 *count
= (targetAtom
->size()+1)/2; // round up incase of buggy compiler that has only one trailing zero byte
5849 *ct
= contentUnknown
;
5853 return target
->contentPointer();
5859 template <typename A
>
5860 unsigned long CFStringSection
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5862 // base hash of CFString on hash of cstring it wraps
5865 unsigned int charCount
;
5866 const uint8_t* content
= this->targetContent(atom
, ind
, &cType
, &charCount
);
5870 for (const char* s
= (char*)content
; *s
!= '\0'; ++s
) {
5871 hash
= hash
* 33 + *s
;
5876 --charCount
; // don't add last 0x0000 to hash because some buggy compilers only have trailing single byte
5877 for (const uint16_t* s
= (uint16_t*)content
; charCount
> 0; ++s
, --charCount
) {
5878 hash
= hash
* 1025 + *s
;
5881 case contentUnknown
:
5882 // <rdar://problem/14134211> For malformed CFStrings, hash to address of atom so they have unique hashes
5883 return ULONG_MAX
- (unsigned long)(atom
);
5889 template <typename A
>
5890 bool CFStringSection
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5891 const ld::IndirectBindingTable
& indirectBindingTable
) const
5895 if ( rhs
.section().type() != ld::Section::typeCFString
)
5897 assert(this->type() == rhs
.section().type());
5898 assert(strcmp(this->sectionName(), "__cfstring") == 0);
5900 ContentType thisType
;
5901 unsigned int charCount
;
5902 const uint8_t* cstringContent
= this->targetContent(atom
, indirectBindingTable
, &thisType
, &charCount
);
5903 ContentType rhsType
;
5904 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5905 assert(rhsAtom
!= NULL
);
5906 unsigned int rhsCharCount
;
5907 const uint8_t* rhsStringContent
= this->targetContent(rhsAtom
, indirectBindingTable
, &rhsType
, &rhsCharCount
);
5909 if ( thisType
!= rhsType
)
5912 if ( thisType
== contentUnknown
)
5915 if ( rhsType
== contentUnknown
)
5918 // no need to compare content of pointers are already the same
5919 if ( cstringContent
== rhsStringContent
)
5922 // no need to compare content if size is different
5923 if ( charCount
!= rhsCharCount
)
5926 switch ( thisType
) {
5928 return (strcmp((char*)cstringContent
, (char*)rhsStringContent
) == 0);
5931 const uint16_t* cstringContent16
= (uint16_t*)cstringContent
;
5932 const uint16_t* rhsStringContent16
= (uint16_t*)rhsStringContent
;
5933 for (unsigned int i
= 0; i
< charCount
; ++i
) {
5934 if ( cstringContent16
[i
] != rhsStringContent16
[i
] )
5939 case contentUnknown
:
5946 template <typename A
>
5947 typename
A::P::uint_t ObjC1ClassSection
<A
>::elementSizeAtAddress(pint_t addr
)
5949 // nominal size for each class is 48 bytes, but sometimes the compiler
5950 // over aligns and there is padding after class data
5951 const macho_section
<P
>* sct
= this->machoSection();
5952 uint32_t align
= 1 << sct
->align();
5953 uint32_t size
= ((12 * sizeof(pint_t
)) + align
-1) & (-align
);
5957 template <typename A
>
5958 const char* ObjC1ClassSection
<A
>::unlabeledAtomName(Parser
<A
>& parser
, pint_t addr
)
5960 // 8-bytes into class object is pointer to class name
5961 const macho_section
<P
>* sct
= this->machoSection();
5962 uint32_t classObjcFileOffset
= sct
->offset() - sct
->addr() + addr
;
5963 const uint8_t* mappedFileContent
= this->file().fileContent();
5964 pint_t nameAddr
= P::getP(*((pint_t
*)(mappedFileContent
+classObjcFileOffset
+2*sizeof(pint_t
))));
5966 // find section containing string address to get string bytes
5967 const macho_section
<P
>* const sections
= parser
.firstMachOSection();
5968 const uint32_t sectionCount
= parser
.machOSectionCount();
5969 for (uint32_t i
=0; i
< sectionCount
; ++i
) {
5970 const macho_section
<P
>* aSect
= §ions
[i
];
5971 if ( (aSect
->addr() <= nameAddr
) && (nameAddr
< (aSect
->addr()+aSect
->size())) ) {
5972 assert((aSect
->flags() & SECTION_TYPE
) == S_CSTRING_LITERALS
);
5973 uint32_t nameFileOffset
= aSect
->offset() - aSect
->addr() + nameAddr
;
5974 const char* name
= (char*)mappedFileContent
+ nameFileOffset
;
5975 // spin through symbol table to find absolute symbol corresponding to this class
5976 for (uint32_t s
=0; s
< parser
.symbolCount(); ++s
) {
5977 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(s
);
5978 if ( (sym
.n_type() & N_TYPE
) != N_ABS
)
5980 const char* absName
= parser
.nameFromSymbol(sym
);
5981 if ( strncmp(absName
, ".objc_class_name_", 17) == 0 ) {
5982 if ( strcmp(&absName
[17], name
) == 0 )
5986 assert(0 && "obj class name not found in symbol table");
5989 assert(0 && "obj class name not found");
5990 return "unknown objc class";
5994 template <typename A
>
5995 const char* ObjC2ClassRefsSection
<A
>::targetClassName(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5997 assert(atom
->fixupCount() == 1);
5998 ld::Fixup::iterator fit
= atom
->fixupsBegin();
5999 const char* className
= NULL
;
6000 switch ( fit
->binding
) {
6001 case ld::Fixup::bindingByNameUnbound
:
6002 className
= fit
->u
.name
;
6004 case ld::Fixup::bindingDirectlyBound
:
6005 case ld::Fixup::bindingByContentBound
:
6006 className
= fit
->u
.target
->name();
6008 case ld::Fixup::bindingsIndirectlyBound
:
6009 className
= ind
.indirectName(fit
->u
.bindingIndex
);
6012 assert(0 && "unsupported binding in objc2 class ref section");
6014 assert(className
!= NULL
);
6019 template <typename A
>
6020 unsigned long ObjC2ClassRefsSection
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
6022 unsigned long hash
= 978;
6023 for (const char* s
= targetClassName(atom
, ind
); *s
!= '\0'; ++s
) {
6024 hash
= hash
* 33 + *s
;
6029 template <typename A
>
6030 bool ObjC2ClassRefsSection
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
6031 const ld::IndirectBindingTable
& indirectBindingTable
) const
6033 assert(this->type() == rhs
.section().type());
6034 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
6035 assert(rhsAtom
!= NULL
);
6036 const char* thisClassName
= targetClassName(atom
, indirectBindingTable
);
6037 const char* rhsClassName
= targetClassName(rhsAtom
, indirectBindingTable
);
6038 return (strcmp(thisClassName
, rhsClassName
) == 0);
6042 template <typename A
>
6043 const char* Objc1ClassReferences
<A
>::targetCString(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
6045 assert(atom
->fixupCount() == 2);
6046 ld::Fixup::iterator fit
= atom
->fixupsBegin();
6047 if ( fit
->kind
== ld::Fixup::kindSetTargetAddress
)
6049 const ld::Atom
* targetAtom
= NULL
;
6050 switch ( fit
->binding
) {
6051 case ld::Fixup::bindingByContentBound
:
6052 targetAtom
= fit
->u
.target
;
6054 case ld::Fixup::bindingsIndirectlyBound
:
6055 targetAtom
= ind
.indirectAtom(fit
->u
.bindingIndex
);
6056 if ( targetAtom
== NULL
) {
6057 fprintf(stderr
, "missing target named %s\n", ind
.indirectName(fit
->u
.bindingIndex
));
6063 assert(targetAtom
!= NULL
);
6064 const Atom
<A
>* target
= dynamic_cast<const Atom
<A
>*>(targetAtom
);
6065 assert(target
!= NULL
);
6066 return (char*)target
->contentPointer();
6070 template <typename A
>
6071 const char* PointerToCStringSection
<A
>::targetCString(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
6073 assert(atom
->fixupCount() == 1);
6074 ld::Fixup::iterator fit
= atom
->fixupsBegin();
6075 const ld::Atom
* targetAtom
= NULL
;
6076 switch ( fit
->binding
) {
6077 case ld::Fixup::bindingByContentBound
:
6078 targetAtom
= fit
->u
.target
;
6080 case ld::Fixup::bindingsIndirectlyBound
:
6081 targetAtom
= ind
.indirectAtom(fit
->u
.bindingIndex
);
6083 case ld::Fixup::bindingDirectlyBound
:
6084 targetAtom
= fit
->u
.target
;
6087 assert(0 && "unsupported reference to selector");
6089 assert(targetAtom
!= NULL
);
6090 const Atom
<A
>* target
= dynamic_cast<const Atom
<A
>*>(targetAtom
);
6091 assert(target
!= NULL
);
6092 assert(target
->contentType() == ld::Atom::typeCString
);
6093 return (char*)target
->contentPointer();
6096 template <typename A
>
6097 unsigned long PointerToCStringSection
<A
>::contentHash(const class Atom
<A
>* atom
,
6098 const ld::IndirectBindingTable
& indirectBindingTable
) const
6100 // make hash from section name and target cstring name
6101 unsigned long hash
= 123;
6102 for (const char* s
= this->sectionName(); *s
!= '\0'; ++s
) {
6103 hash
= hash
* 33 + *s
;
6105 for (const char* s
= this->targetCString(atom
, indirectBindingTable
); *s
!= '\0'; ++s
) {
6106 hash
= hash
* 33 + *s
;
6111 template <typename A
>
6112 bool PointerToCStringSection
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
6113 const ld::IndirectBindingTable
& indirectBindingTable
) const
6115 assert(this->type() == rhs
.section().type());
6116 // there can be pointers-to-cstrings in different section names
6117 // we only want to coalesce in same section name
6118 if ( *this != rhs
.section() )
6121 // get string content for this
6122 const char* cstringContent
= this->targetCString(atom
, indirectBindingTable
);
6123 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
6124 assert(rhsAtom
!= NULL
);
6125 const char* rhsCstringContent
= this->targetCString(rhsAtom
, indirectBindingTable
);
6127 assert(cstringContent
!= NULL
);
6128 assert(rhsCstringContent
!= NULL
);
6129 return (strcmp(cstringContent
, rhsCstringContent
) == 0);
6134 template <typename A
>
6135 unsigned long UTF16StringSection
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
6137 unsigned long hash
= 5381;
6138 const uint16_t* stringContent
= (uint16_t*)atom
->contentPointer();
6139 // some buggy compilers end utf16 data with single byte, so don't use last word in hash computation
6140 unsigned int count
= (atom
->size()/2) - 1;
6141 for (const uint16_t* s
= stringContent
; count
> 0; ++s
, --count
) {
6142 hash
= hash
* 33 + *s
;
6147 template <typename A
>
6148 bool UTF16StringSection
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
6149 const ld::IndirectBindingTable
& ind
) const
6151 if ( rhs
.section().type() != ld::Section::typeUTF16Strings
)
6164 uint32_t Section
<x86_64
>::x86_64PcRelOffset(uint8_t r_type
)
6167 case X86_64_RELOC_SIGNED
:
6169 case X86_64_RELOC_SIGNED_1
:
6171 case X86_64_RELOC_SIGNED_2
:
6173 case X86_64_RELOC_SIGNED_4
:
6181 bool Section
<x86_64
>::addRelocFixup(class Parser
<x86_64
>& parser
, const macho_relocation_info
<P
>* reloc
)
6183 const macho_section
<P
>* sect
= this->machoSection();
6184 uint64_t srcAddr
= sect
->addr() + reloc
->r_address();
6185 Parser
<x86_64
>::SourceLocation src
;
6186 Parser
<x86_64
>::TargetDesc target
;
6187 Parser
<x86_64
>::TargetDesc toTarget
;
6188 src
.atom
= this->findAtomByAddress(srcAddr
);
6189 src
.offsetInAtom
= srcAddr
- src
.atom
->_objAddress
;
6190 const uint8_t* fixUpPtr
= file().fileContent() + sect
->offset() + reloc
->r_address();
6191 uint64_t contentValue
= 0;
6192 const macho_relocation_info
<x86_64::P
>* nextReloc
= &reloc
[1];
6193 bool result
= false;
6194 bool useDirectBinding
;
6195 switch ( reloc
->r_length() ) {
6197 contentValue
= *fixUpPtr
;
6200 contentValue
= (int64_t)(int16_t)E::get16(*((uint16_t*)fixUpPtr
));
6203 contentValue
= (int64_t)(int32_t)E::get32(*((uint32_t*)fixUpPtr
));
6206 contentValue
= E::get64(*((uint64_t*)fixUpPtr
));
6211 target
.weakImport
= false;
6213 if ( reloc
->r_extern() ) {
6214 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
6215 // use direct reference for local symbols
6216 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && (((sym
.n_type() & N_EXT
) == 0) || (parser
.nameFromSymbol(sym
)[0] == 'L')) ) {
6217 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
6218 target
.addend
+= contentValue
;
6221 target
.name
= parser
.nameFromSymbol(sym
);
6222 target
.weakImport
= parser
.weakImportFromSymbol(sym
);
6223 target
.addend
= contentValue
;
6225 // cfstrings should always use direct reference to backing store
6226 if ( (this->type() == ld::Section::typeCFString
) && (src
.offsetInAtom
!= 0) ) {
6227 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
6228 target
.addend
= contentValue
;
6232 if ( reloc
->r_pcrel() )
6233 contentValue
+= srcAddr
+ x86_64PcRelOffset(reloc
->r_type());
6234 parser
.findTargetFromAddressAndSectionNum(contentValue
, reloc
->r_symbolnum(), target
);
6236 switch ( reloc
->r_type() ) {
6237 case X86_64_RELOC_UNSIGNED
:
6238 if ( reloc
->r_pcrel() )
6239 throw "pcrel and X86_64_RELOC_UNSIGNED not supported";
6240 switch ( reloc
->r_length() ) {
6243 throw "length < 2 and X86_64_RELOC_UNSIGNED not supported";
6245 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian32
, target
);
6248 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian64
, target
);
6252 case X86_64_RELOC_SIGNED
:
6253 case X86_64_RELOC_SIGNED_1
:
6254 case X86_64_RELOC_SIGNED_2
:
6255 case X86_64_RELOC_SIGNED_4
:
6256 if ( ! reloc
->r_pcrel() )
6257 throw "not pcrel and X86_64_RELOC_SIGNED* not supported";
6258 if ( reloc
->r_length() != 2 )
6259 throw "length != 2 and X86_64_RELOC_SIGNED* not supported";
6260 switch ( reloc
->r_type() ) {
6261 case X86_64_RELOC_SIGNED
:
6262 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32
, target
);
6264 case X86_64_RELOC_SIGNED_1
:
6265 if ( reloc
->r_extern() )
6267 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32_1
, target
);
6269 case X86_64_RELOC_SIGNED_2
:
6270 if ( reloc
->r_extern() )
6272 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32_2
, target
);
6274 case X86_64_RELOC_SIGNED_4
:
6275 if ( reloc
->r_extern() )
6277 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32_4
, target
);
6281 case X86_64_RELOC_BRANCH
:
6282 if ( ! reloc
->r_pcrel() )
6283 throw "not pcrel and X86_64_RELOC_BRANCH not supported";
6284 switch ( reloc
->r_length() ) {
6286 if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_probe$", 16) == 0) ) {
6287 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindStoreX86DtraceCallSiteNop
, false, target
.name
);
6288 parser
.addDtraceExtraInfos(src
, &target
.name
[16]);
6290 else if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_isenabled$", 20) == 0) ) {
6291 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindStoreX86DtraceIsEnableSiteClear
, false, target
.name
);
6292 parser
.addDtraceExtraInfos(src
, &target
.name
[20]);
6295 parser
.addFixups(src
, ld::Fixup::kindStoreX86BranchPCRel32
, target
);
6299 parser
.addFixups(src
, ld::Fixup::kindStoreX86BranchPCRel8
, target
);
6302 throwf("length=%d and X86_64_RELOC_BRANCH not supported", reloc
->r_length());
6305 case X86_64_RELOC_GOT
:
6306 if ( ! reloc
->r_extern() )
6307 throw "not extern and X86_64_RELOC_GOT not supported";
6308 if ( ! reloc
->r_pcrel() )
6309 throw "not pcrel and X86_64_RELOC_GOT not supported";
6310 if ( reloc
->r_length() != 2 )
6311 throw "length != 2 and X86_64_RELOC_GOT not supported";
6312 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32GOT
, target
);
6314 case X86_64_RELOC_GOT_LOAD
:
6315 if ( ! reloc
->r_extern() )
6316 throw "not extern and X86_64_RELOC_GOT_LOAD not supported";
6317 if ( ! reloc
->r_pcrel() )
6318 throw "not pcrel and X86_64_RELOC_GOT_LOAD not supported";
6319 if ( reloc
->r_length() != 2 )
6320 throw "length != 2 and X86_64_RELOC_GOT_LOAD not supported";
6321 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32GOTLoad
, target
);
6323 case X86_64_RELOC_SUBTRACTOR
:
6324 if ( reloc
->r_pcrel() )
6325 throw "X86_64_RELOC_SUBTRACTOR cannot be pc-relative";
6326 if ( reloc
->r_length() < 2 )
6327 throw "X86_64_RELOC_SUBTRACTOR must have r_length of 2 or 3";
6328 if ( !reloc
->r_extern() )
6329 throw "X86_64_RELOC_SUBTRACTOR must have r_extern=1";
6330 if ( nextReloc
->r_type() != X86_64_RELOC_UNSIGNED
)
6331 throw "X86_64_RELOC_SUBTRACTOR must be followed by X86_64_RELOC_UNSIGNED";
6333 if ( nextReloc
->r_pcrel() )
6334 throw "X86_64_RELOC_UNSIGNED following a X86_64_RELOC_SUBTRACTOR cannot be pc-relative";
6335 if ( nextReloc
->r_length() != reloc
->r_length() )
6336 throw "X86_64_RELOC_UNSIGNED following a X86_64_RELOC_SUBTRACTOR must have same r_length";
6337 if ( nextReloc
->r_extern() ) {
6338 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(nextReloc
->r_symbolnum());
6339 // use direct reference for local symbols
6340 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && (((sym
.n_type() & N_EXT
) == 0) || (parser
.nameFromSymbol(sym
)[0] == 'L')) ) {
6341 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), toTarget
);
6342 toTarget
.addend
= contentValue
;
6343 useDirectBinding
= true;
6346 toTarget
.name
= parser
.nameFromSymbol(sym
);
6347 toTarget
.weakImport
= parser
.weakImportFromSymbol(sym
);
6348 toTarget
.addend
= contentValue
;
6349 useDirectBinding
= false;
6353 parser
.findTargetFromAddressAndSectionNum(contentValue
, nextReloc
->r_symbolnum(), toTarget
);
6354 useDirectBinding
= (toTarget
.atom
->scope() == ld::Atom::scopeTranslationUnit
) || ((toTarget
.atom
->combine() == ld::Atom::combineByNameAndContent
) || (toTarget
.atom
->combine() == ld::Atom::combineByNameAndReferences
));
6356 if ( useDirectBinding
) {
6357 if ( (toTarget
.atom
->combine() == ld::Atom::combineByNameAndContent
) || (toTarget
.atom
->combine() == ld::Atom::combineByNameAndReferences
) )
6358 parser
.addFixup(src
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, toTarget
.atom
);
6360 parser
.addFixup(src
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, toTarget
.atom
);
6363 parser
.addFixup(src
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, toTarget
.weakImport
, toTarget
.name
);
6364 parser
.addFixup(src
, ld::Fixup::k2of4
, ld::Fixup::kindAddAddend
, toTarget
.addend
);
6365 if ( target
.atom
== NULL
)
6366 parser
.addFixup(src
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractTargetAddress
, false, target
.name
);
6368 parser
.addFixup(src
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractTargetAddress
, target
.atom
);
6369 if ( reloc
->r_length() == 2 )
6370 parser
.addFixup(src
, ld::Fixup::k4of4
, ld::Fixup::kindStoreLittleEndian32
);
6372 parser
.addFixup(src
, ld::Fixup::k4of4
, ld::Fixup::kindStoreLittleEndian64
);
6374 case X86_64_RELOC_TLV
:
6375 if ( ! reloc
->r_extern() )
6376 throw "not extern and X86_64_RELOC_TLV not supported";
6377 if ( ! reloc
->r_pcrel() )
6378 throw "not pcrel and X86_64_RELOC_TLV not supported";
6379 if ( reloc
->r_length() != 2 )
6380 throw "length != 2 and X86_64_RELOC_TLV not supported";
6381 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32TLVLoad
, target
);
6384 throwf("unknown relocation type %d", reloc
->r_type());
6392 bool Section
<x86
>::addRelocFixup(class Parser
<x86
>& parser
, const macho_relocation_info
<P
>* reloc
)
6394 const macho_section
<P
>* sect
= this->machoSection();
6396 const uint8_t* fixUpPtr
;
6397 uint32_t contentValue
= 0;
6398 ld::Fixup::Kind kind
= ld::Fixup::kindNone
;
6399 Parser
<x86
>::SourceLocation src
;
6400 Parser
<x86
>::TargetDesc target
;
6402 if ( (reloc
->r_address() & R_SCATTERED
) == 0 ) {
6403 srcAddr
= sect
->addr() + reloc
->r_address();
6404 src
.atom
= this->findAtomByAddress(srcAddr
);
6405 src
.offsetInAtom
= srcAddr
- src
.atom
->_objAddress
;
6406 fixUpPtr
= file().fileContent() + sect
->offset() + reloc
->r_address();
6407 switch ( reloc
->r_type() ) {
6408 case GENERIC_RELOC_VANILLA
:
6409 switch ( reloc
->r_length() ) {
6411 contentValue
= (int32_t)(int8_t)*fixUpPtr
;
6412 if ( reloc
->r_pcrel() ) {
6413 kind
= ld::Fixup::kindStoreX86BranchPCRel8
;
6414 contentValue
+= srcAddr
+ sizeof(uint8_t);
6417 throw "r_length=0 and r_pcrel=0 not supported";
6420 contentValue
= (int32_t)(int16_t)E::get16(*((uint16_t*)fixUpPtr
));
6421 if ( reloc
->r_pcrel() ) {
6422 kind
= ld::Fixup::kindStoreX86PCRel16
;
6423 contentValue
+= srcAddr
+ sizeof(uint16_t);
6426 kind
= ld::Fixup::kindStoreLittleEndian16
;
6429 contentValue
= E::get32(*((uint32_t*)fixUpPtr
));
6430 if ( reloc
->r_pcrel() ) {
6431 kind
= ld::Fixup::kindStoreX86BranchPCRel32
;
6432 contentValue
+= srcAddr
+ sizeof(uint32_t);
6435 kind
= ld::Fixup::kindStoreLittleEndian32
;
6438 throw "r_length=3 not supported";
6440 if ( reloc
->r_extern() ) {
6442 const macho_nlist
<P
>& targetSymbol
= parser
.symbolFromIndex(reloc
->r_symbolnum());
6443 target
.name
= parser
.nameFromSymbol(targetSymbol
);
6444 target
.weakImport
= parser
.weakImportFromSymbol(targetSymbol
);
6445 target
.addend
= (int32_t)contentValue
;
6448 parser
.findTargetFromAddressAndSectionNum(contentValue
, reloc
->r_symbolnum(), target
);
6450 if ( (kind
== ld::Fixup::kindStoreX86BranchPCRel32
) && (target
.name
!= NULL
) ) {
6451 if ( strncmp(target
.name
, "___dtrace_probe$", 16) == 0 ) {
6452 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindStoreX86DtraceCallSiteNop
, false, target
.name
);
6453 parser
.addDtraceExtraInfos(src
, &target
.name
[16]);
6456 else if ( strncmp(target
.name
, "___dtrace_isenabled$", 20) == 0 ) {
6457 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindStoreX86DtraceIsEnableSiteClear
, false, target
.name
);
6458 parser
.addDtraceExtraInfos(src
, &target
.name
[20]);
6462 parser
.addFixups(src
, kind
, target
);
6465 case GENERIC_RLEOC_TLV
:
6467 if ( !reloc
->r_extern() )
6468 throw "r_extern=0 and r_type=GENERIC_RLEOC_TLV not supported";
6469 if ( reloc
->r_length() != 2 )
6470 throw "r_length!=2 and r_type=GENERIC_RLEOC_TLV not supported";
6471 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
6472 // use direct reference for local symbols
6473 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && ((sym
.n_type() & N_EXT
) == 0) ) {
6474 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
6478 target
.name
= parser
.nameFromSymbol(sym
);
6479 target
.weakImport
= parser
.weakImportFromSymbol(sym
);
6481 target
.addend
= (int64_t)(int32_t)E::get32(*((uint32_t*)fixUpPtr
));
6482 if ( reloc
->r_pcrel() ) {
6483 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32TLVLoad
, target
);
6486 parser
.addFixups(src
, ld::Fixup::kindStoreX86Abs32TLVLoad
, target
);
6492 throwf("unsupported i386 relocation type (%d)", reloc
->r_type());
6496 // scattered relocation
6497 const macho_scattered_relocation_info
<P
>* sreloc
= (macho_scattered_relocation_info
<P
>*)reloc
;
6498 srcAddr
= sect
->addr() + sreloc
->r_address();
6499 src
.atom
= this->findAtomByAddress(srcAddr
);
6500 assert(src
.atom
!= NULL
);
6501 src
.offsetInAtom
= srcAddr
- src
.atom
->_objAddress
;
6502 fixUpPtr
= file().fileContent() + sect
->offset() + sreloc
->r_address();
6503 uint32_t relocValue
= sreloc
->r_value();
6504 bool result
= false;
6505 // file format allows pair to be scattered or not
6506 const macho_scattered_relocation_info
<P
>* nextSReloc
= &sreloc
[1];
6507 const macho_relocation_info
<P
>* nextReloc
= &reloc
[1];
6508 bool nextRelocIsPair
= false;
6509 uint32_t nextRelocAddress
= 0;
6510 uint32_t nextRelocValue
= 0;
6511 if ( (nextReloc
->r_address() & R_SCATTERED
) == 0 ) {
6512 if ( nextReloc
->r_type() == GENERIC_RELOC_PAIR
) {
6513 nextRelocIsPair
= true;
6514 nextRelocAddress
= nextReloc
->r_address();
6515 result
= true; // iterator should skip next reloc, since we've consumed it here
6519 if ( nextSReloc
->r_type() == GENERIC_RELOC_PAIR
) {
6520 nextRelocIsPair
= true;
6521 nextRelocAddress
= nextSReloc
->r_address();
6522 nextRelocValue
= nextSReloc
->r_value();
6525 switch (sreloc
->r_type()) {
6526 case GENERIC_RELOC_VANILLA
:
6527 // with a scattered relocation we get both the target (sreloc->r_value()) and the target+offset (*fixUpPtr)
6528 target
.atom
= parser
.findAtomByAddress(relocValue
);
6529 if ( sreloc
->r_pcrel() ) {
6530 switch ( sreloc
->r_length() ) {
6532 contentValue
= srcAddr
+ 1 + *fixUpPtr
;
6533 target
.addend
= (int32_t)contentValue
- (int32_t)relocValue
;
6534 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel8
, target
);
6537 contentValue
= srcAddr
+ 2 + LittleEndian::get16(*((uint16_t*)fixUpPtr
));
6538 target
.addend
= (int32_t)contentValue
- (int32_t)relocValue
;
6539 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel16
, target
);
6542 contentValue
= srcAddr
+ 4 + LittleEndian::get32(*((uint32_t*)fixUpPtr
));
6543 target
.addend
= (int32_t)contentValue
- (int32_t)relocValue
;
6544 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32
, target
);
6547 throw "unsupported r_length=3 for scattered pc-rel vanilla reloc";
6552 if ( sreloc
->r_length() != 2 )
6553 throwf("unsupported r_length=%d for scattered vanilla reloc", sreloc
->r_length());
6554 contentValue
= LittleEndian::get32(*((uint32_t*)fixUpPtr
));
6555 target
.addend
= (int32_t)contentValue
- (int32_t)(target
.atom
->objectAddress());
6556 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian32
, target
);
6559 case GENERIC_RELOC_SECTDIFF
:
6560 case GENERIC_RELOC_LOCAL_SECTDIFF
:
6562 if ( !nextRelocIsPair
)
6563 throw "GENERIC_RELOC_SECTDIFF missing following pair";
6564 switch ( sreloc
->r_length() ) {
6567 throw "bad length for GENERIC_RELOC_SECTDIFF";
6569 contentValue
= (int32_t)(int16_t)LittleEndian::get16(*((uint16_t*)fixUpPtr
));
6570 kind
= ld::Fixup::kindStoreLittleEndian16
;
6573 contentValue
= LittleEndian::get32(*((uint32_t*)fixUpPtr
));
6574 kind
= ld::Fixup::kindStoreLittleEndian32
;
6577 Atom
<x86
>* fromAtom
= parser
.findAtomByAddress(nextRelocValue
);
6578 uint32_t offsetInFrom
= nextRelocValue
- fromAtom
->_objAddress
;
6579 parser
.findTargetFromAddress(sreloc
->r_value(), target
);
6580 // check for addend encoded in the section content
6581 int64_t addend
= (int32_t)contentValue
- (int32_t)(sreloc
->r_value() - nextRelocValue
);
6583 // switch binding base on coalescing
6584 if ( target
.atom
== NULL
) {
6585 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, target
.name
);
6587 else if ( target
.atom
->scope() == ld::Atom::scopeTranslationUnit
) {
6588 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, target
.atom
);
6590 else if ( (target
.atom
->combine() == ld::Atom::combineByNameAndContent
) || (target
.atom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
6591 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, target
.atom
);
6594 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, target
.atom
->name());
6596 parser
.addFixup(src
, ld::Fixup::k2of5
, ld::Fixup::kindAddAddend
, target
.addend
);
6597 parser
.addFixup(src
, ld::Fixup::k3of5
, ld::Fixup::kindSubtractTargetAddress
, fromAtom
);
6598 parser
.addFixup(src
, ld::Fixup::k4of5
, ld::Fixup::kindSubtractAddend
, offsetInFrom
-addend
);
6599 parser
.addFixup(src
, ld::Fixup::k5of5
, kind
);
6602 // switch binding base on coalescing
6603 if ( target
.atom
== NULL
) {
6604 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, target
.name
);
6606 else if ( target
.atom
->scope() == ld::Atom::scopeTranslationUnit
) {
6607 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, target
.atom
);
6609 else if ( (target
.atom
->combine() == ld::Atom::combineByNameAndContent
) || (target
.atom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
6610 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, target
.atom
);
6613 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, target
.atom
->name());
6615 parser
.addFixup(src
, ld::Fixup::k2of5
, ld::Fixup::kindAddAddend
, target
.addend
+addend
);
6616 parser
.addFixup(src
, ld::Fixup::k3of5
, ld::Fixup::kindSubtractTargetAddress
, fromAtom
);
6617 parser
.addFixup(src
, ld::Fixup::k4of5
, ld::Fixup::kindSubtractAddend
, offsetInFrom
);
6618 parser
.addFixup(src
, ld::Fixup::k5of5
, kind
);
6631 #if SUPPORT_ARCH_arm_any
6633 bool Section
<arm
>::addRelocFixup(class Parser
<arm
>& parser
, const macho_relocation_info
<P
>* reloc
)
6635 const macho_section
<P
>* sect
= this->machoSection();
6636 bool result
= false;
6640 int32_t displacement
= 0;
6641 uint32_t instruction
= 0;
6642 pint_t contentValue
= 0;
6643 Parser
<arm
>::SourceLocation src
;
6644 Parser
<arm
>::TargetDesc target
;
6645 const macho_relocation_info
<P
>* nextReloc
;
6647 if ( (reloc
->r_address() & R_SCATTERED
) == 0 ) {
6648 bool externSymbolIsThumbDef
= false;
6649 srcAddr
= sect
->addr() + reloc
->r_address();
6650 src
.atom
= this->findAtomByAddress(srcAddr
);
6651 src
.offsetInAtom
= srcAddr
- src
.atom
->_objAddress
;
6652 fixUpPtr
= (uint32_t*)(file().fileContent() + sect
->offset() + reloc
->r_address());
6653 if ( reloc
->r_type() != ARM_RELOC_PAIR
)
6654 instruction
= LittleEndian::get32(*fixUpPtr
);
6655 if ( reloc
->r_extern() ) {
6656 const macho_nlist
<P
>& targetSymbol
= parser
.symbolFromIndex(reloc
->r_symbolnum());
6657 // use direct reference for local symbols
6658 if ( ((targetSymbol
.n_type() & N_TYPE
) == N_SECT
) && (((targetSymbol
.n_type() & N_EXT
) == 0) || (parser
.nameFromSymbol(targetSymbol
)[0] == 'L')) ) {
6659 parser
.findTargetFromAddressAndSectionNum(targetSymbol
.n_value(), targetSymbol
.n_sect(), target
);
6663 target
.name
= parser
.nameFromSymbol(targetSymbol
);
6664 target
.weakImport
= parser
.weakImportFromSymbol(targetSymbol
);
6665 if ( ((targetSymbol
.n_type() & N_TYPE
) == N_SECT
) && (targetSymbol
.n_desc() & N_ARM_THUMB_DEF
) )
6666 externSymbolIsThumbDef
= true;
6669 switch ( reloc
->r_type() ) {
6670 case ARM_RELOC_BR24
:
6671 // Sign-extend displacement
6672 displacement
= (instruction
& 0x00FFFFFF) << 2;
6673 if ( (displacement
& 0x02000000) != 0 )
6674 displacement
|= 0xFC000000;
6675 // The pc added will be +8 from the pc
6677 // If this is BLX add H << 1
6678 if ((instruction
& 0xFE000000) == 0xFA000000)
6679 displacement
+= ((instruction
& 0x01000000) >> 23);
6680 if ( reloc
->r_extern() ) {
6681 dstAddr
= srcAddr
+ displacement
;
6682 // <rdar://problem/16652542> support large .o files
6683 if ( srcAddr
> 0x2000000 ) {
6684 dstAddr
-= ((srcAddr
+ 0x1FFFFFF) & 0xFC000000);
6686 target
.addend
= dstAddr
;
6687 if ( externSymbolIsThumbDef
)
6688 target
.addend
&= -2; // remove thumb bit
6691 dstAddr
= srcAddr
+ displacement
;
6692 parser
.findTargetFromAddressAndSectionNum(dstAddr
, reloc
->r_symbolnum(), target
);
6694 // special case "calls" for dtrace
6695 if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_probe$", 16) == 0) ) {
6696 parser
.addFixup(src
, ld::Fixup::k1of1
,
6697 ld::Fixup::kindStoreARMDtraceCallSiteNop
, false, target
.name
);
6698 parser
.addDtraceExtraInfos(src
, &target
.name
[16]);
6700 else if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_isenabled$", 20) == 0) ) {
6701 parser
.addFixup(src
, ld::Fixup::k1of1
,
6702 ld::Fixup::kindStoreARMDtraceIsEnableSiteClear
, false, target
.name
);
6703 parser
.addDtraceExtraInfos(src
, &target
.name
[20]);
6706 parser
.addFixups(src
, ld::Fixup::kindStoreARMBranch24
, target
);
6709 case ARM_THUMB_RELOC_BR22
:
6710 // thumb2 added two more bits to displacement, complicating the displacement decoding
6712 uint32_t s
= (instruction
>> 10) & 0x1;
6713 uint32_t j1
= (instruction
>> 29) & 0x1;
6714 uint32_t j2
= (instruction
>> 27) & 0x1;
6715 uint32_t imm10
= instruction
& 0x3FF;
6716 uint32_t imm11
= (instruction
>> 16) & 0x7FF;
6717 uint32_t i1
= (j1
== s
);
6718 uint32_t i2
= (j2
== s
);
6719 uint32_t dis
= (s
<< 24) | (i1
<< 23) | (i2
<< 22) | (imm10
<< 12) | (imm11
<< 1);
6723 displacement
= sdis
;
6725 // The pc added will be +4 from the pc
6727 // If the instruction was blx, force the low 2 bits to be clear
6728 dstAddr
= srcAddr
+ displacement
;
6729 if ((instruction
& 0xD0000000) == 0xC0000000)
6730 dstAddr
&= 0xFFFFFFFC;
6732 if ( reloc
->r_extern() ) {
6733 // <rdar://problem/16652542> support large .o files
6734 if ( srcAddr
> 0x1000000 ) {
6735 dstAddr
-= ((srcAddr
+ 0xFFFFFF) & 0xFE000000);
6737 target
.addend
= (int64_t)(int32_t)dstAddr
;
6740 parser
.findTargetFromAddressAndSectionNum(dstAddr
, reloc
->r_symbolnum(), target
);
6742 // special case "calls" for dtrace
6743 if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_probe$", 16) == 0) ) {
6744 parser
.addFixup(src
, ld::Fixup::k1of1
,
6745 ld::Fixup::kindStoreThumbDtraceCallSiteNop
, false, target
.name
);
6746 parser
.addDtraceExtraInfos(src
, &target
.name
[16]);
6748 else if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_isenabled$", 20) == 0) ) {
6749 parser
.addFixup(src
, ld::Fixup::k1of1
,
6750 ld::Fixup::kindStoreThumbDtraceIsEnableSiteClear
, false, target
.name
);
6751 parser
.addDtraceExtraInfos(src
, &target
.name
[20]);
6754 parser
.addFixups(src
, ld::Fixup::kindStoreThumbBranch22
, target
);
6757 case ARM_RELOC_VANILLA
:
6758 if ( reloc
->r_length() != 2 )
6759 throw "bad length for ARM_RELOC_VANILLA";
6760 contentValue
= LittleEndian::get32(*fixUpPtr
);
6761 if ( reloc
->r_extern() ) {
6762 target
.addend
= (int32_t)contentValue
;
6763 if ( externSymbolIsThumbDef
)
6764 target
.addend
&= -2; // remove thumb bit
6767 parser
.findTargetFromAddressAndSectionNum(contentValue
, reloc
->r_symbolnum(), target
);
6768 // possible non-extern relocation turned into by-name ref because target is a weak-def
6769 if ( target
.atom
!= NULL
) {
6770 if ( target
.atom
->isThumb() )
6771 target
.addend
&= -2; // remove thumb bit
6772 // if reference to LSDA, add group subordinate fixup
6773 if ( target
.atom
->contentType() == ld::Atom::typeLSDA
) {
6774 Parser
<arm
>::SourceLocation src2
;
6775 src2
.atom
= src
.atom
;
6776 src2
.offsetInAtom
= 0;
6777 parser
.addFixup(src2
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinateLSDA
, target
.atom
);
6781 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian32
, target
);
6783 case ARM_THUMB_32BIT_BRANCH
:
6784 // silently ignore old unnecessary reloc
6786 case ARM_RELOC_HALF
:
6787 nextReloc
= &reloc
[1];
6788 if ( nextReloc
->r_type() == ARM_RELOC_PAIR
) {
6789 uint32_t instruction16
;
6790 uint32_t other16
= (nextReloc
->r_address() & 0xFFFF);
6792 if ( reloc
->r_length() & 2 ) {
6794 uint32_t i
= ((instruction
& 0x00000400) >> 10);
6795 uint32_t imm4
= (instruction
& 0x0000000F);
6796 uint32_t imm3
= ((instruction
& 0x70000000) >> 28);
6797 uint32_t imm8
= ((instruction
& 0x00FF0000) >> 16);
6798 instruction16
= (imm4
<< 12) | (i
<< 11) | (imm3
<< 8) | imm8
;
6802 uint32_t imm4
= ((instruction
& 0x000F0000) >> 16);
6803 uint32_t imm12
= (instruction
& 0x00000FFF);
6804 instruction16
= (imm4
<< 12) | imm12
;
6806 if ( reloc
->r_length() & 1 ) {
6808 dstAddr
= ((instruction16
<< 16) | other16
);
6809 if ( reloc
->r_extern() ) {
6810 target
.addend
= dstAddr
;
6811 if ( externSymbolIsThumbDef
)
6812 target
.addend
&= -2; // remove thumb bit
6815 parser
.findTargetFromAddress(dstAddr
, target
);
6816 if ( target
.atom
->isThumb() )
6817 target
.addend
&= (-2); // remove thumb bit
6819 parser
.addFixups(src
, (isThumb
? ld::Fixup::kindStoreThumbHigh16
: ld::Fixup::kindStoreARMHigh16
), target
);
6823 dstAddr
= (other16
<< 16) | instruction16
;
6824 if ( reloc
->r_extern() ) {
6825 target
.addend
= dstAddr
;
6826 if ( externSymbolIsThumbDef
)
6827 target
.addend
&= -2; // remove thumb bit
6830 parser
.findTargetFromAddress(dstAddr
, target
);
6831 if ( target
.atom
->isThumb() )
6832 target
.addend
&= (-2); // remove thumb bit
6834 parser
.addFixups(src
, (isThumb
? ld::Fixup::kindStoreThumbLow16
: ld::Fixup::kindStoreARMLow16
), target
);
6839 throw "for ARM_RELOC_HALF, next reloc is not ARM_RELOC_PAIR";
6842 throwf("unknown relocation type %d", reloc
->r_type());
6847 const macho_scattered_relocation_info
<P
>* sreloc
= (macho_scattered_relocation_info
<P
>*)reloc
;
6848 // file format allows pair to be scattered or not
6849 const macho_scattered_relocation_info
<P
>* nextSReloc
= &sreloc
[1];
6850 nextReloc
= &reloc
[1];
6851 srcAddr
= sect
->addr() + sreloc
->r_address();
6852 dstAddr
= sreloc
->r_value();
6853 fixUpPtr
= (uint32_t*)(file().fileContent() + sect
->offset() + sreloc
->r_address());
6854 instruction
= LittleEndian::get32(*fixUpPtr
);
6855 src
.atom
= this->findAtomByAddress(srcAddr
);
6856 src
.offsetInAtom
= srcAddr
- src
.atom
->_objAddress
;
6857 bool nextRelocIsPair
= false;
6858 uint32_t nextRelocAddress
= 0;
6859 uint32_t nextRelocValue
= 0;
6860 if ( (nextReloc
->r_address() & R_SCATTERED
) == 0 ) {
6861 if ( nextReloc
->r_type() == ARM_RELOC_PAIR
) {
6862 nextRelocIsPair
= true;
6863 nextRelocAddress
= nextReloc
->r_address();
6868 if ( nextSReloc
->r_type() == ARM_RELOC_PAIR
) {
6869 nextRelocIsPair
= true;
6870 nextRelocAddress
= nextSReloc
->r_address();
6871 nextRelocValue
= nextSReloc
->r_value();
6875 switch ( sreloc
->r_type() ) {
6876 case ARM_RELOC_VANILLA
:
6877 // with a scattered relocation we get both the target (sreloc->r_value()) and the target+offset (*fixUpPtr)
6878 if ( sreloc
->r_length() != 2 )
6879 throw "bad length for ARM_RELOC_VANILLA";
6880 target
.atom
= parser
.findAtomByAddress(sreloc
->r_value());
6881 if ( target
.atom
== NULL
)
6882 throwf("bad r_value (0x%08X) for ARM_RELOC_VANILLA\n", sreloc
->r_value());
6883 contentValue
= LittleEndian::get32(*fixUpPtr
);
6884 target
.addend
= contentValue
- target
.atom
->_objAddress
;
6885 if ( target
.atom
->isThumb() )
6886 target
.addend
&= -2; // remove thumb bit
6887 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian32
, target
);
6889 case ARM_RELOC_BR24
:
6890 // Sign-extend displacement
6891 displacement
= (instruction
& 0x00FFFFFF) << 2;
6892 if ( (displacement
& 0x02000000) != 0 )
6893 displacement
|= 0xFC000000;
6894 // The pc added will be +8 from the pc
6896 // If this is BLX add H << 1
6897 if ((instruction
& 0xFE000000) == 0xFA000000)
6898 displacement
+= ((instruction
& 0x01000000) >> 23);
6899 target
.atom
= parser
.findAtomByAddress(sreloc
->r_value());
6900 target
.addend
= (int64_t)(srcAddr
+ displacement
) - (int64_t)(target
.atom
->_objAddress
);
6901 parser
.addFixups(src
, ld::Fixup::kindStoreARMBranch24
, target
);
6903 case ARM_THUMB_RELOC_BR22
:
6904 // thumb2 added two more bits to displacement, complicating the displacement decoding
6906 uint32_t s
= (instruction
>> 10) & 0x1;
6907 uint32_t j1
= (instruction
>> 29) & 0x1;
6908 uint32_t j2
= (instruction
>> 27) & 0x1;
6909 uint32_t imm10
= instruction
& 0x3FF;
6910 uint32_t imm11
= (instruction
>> 16) & 0x7FF;
6911 uint32_t i1
= (j1
== s
);
6912 uint32_t i2
= (j2
== s
);
6913 uint32_t dis
= (s
<< 24) | (i1
<< 23) | (i2
<< 22) | (imm10
<< 12) | (imm11
<< 1);
6917 displacement
= sdis
;
6919 // The pc added will be +4 from the pc
6921 dstAddr
= srcAddr
+displacement
;
6922 // If the instruction was blx, force the low 2 bits to be clear
6923 if ((instruction
& 0xF8000000) == 0xE8000000)
6924 dstAddr
&= 0xFFFFFFFC;
6925 target
.atom
= parser
.findAtomByAddress(sreloc
->r_value());
6926 target
.addend
= dstAddr
- target
.atom
->_objAddress
;
6927 parser
.addFixups(src
, ld::Fixup::kindStoreThumbBranch22
, target
);
6929 case ARM_RELOC_SECTDIFF
:
6930 case ARM_RELOC_LOCAL_SECTDIFF
:
6932 if ( ! nextRelocIsPair
)
6933 throw "ARM_RELOC_SECTDIFF missing following pair";
6934 if ( sreloc
->r_length() != 2 )
6935 throw "bad length for ARM_RELOC_SECTDIFF";
6936 contentValue
= LittleEndian::get32(*fixUpPtr
);
6937 Atom
<arm
>* fromAtom
= parser
.findAtomByAddress(nextRelocValue
);
6938 uint32_t offsetInFrom
= nextRelocValue
- fromAtom
->_objAddress
;
6939 uint32_t offsetInTarget
;
6940 Atom
<arm
>* targetAtom
= parser
.findAtomByAddressOrLocalTargetOfStub(sreloc
->r_value(), &offsetInTarget
);
6941 // check for addend encoded in the section content
6942 int64_t addend
= (int32_t)contentValue
- (int32_t)(sreloc
->r_value() - nextRelocValue
);
6943 if ( targetAtom
->isThumb() )
6944 addend
&= -2; // remove thumb bit
6945 // if reference to LSDA, add group subordinate fixup
6946 if ( targetAtom
->contentType() == ld::Atom::typeLSDA
) {
6947 Parser
<arm
>::SourceLocation src2
;
6948 src2
.atom
= src
.atom
;
6949 src2
.offsetInAtom
= 0;
6950 parser
.addFixup(src2
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinateLSDA
, targetAtom
);
6953 // switch binding base on coalescing
6954 if ( targetAtom
->scope() == ld::Atom::scopeTranslationUnit
) {
6955 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, targetAtom
);
6957 else if ( (targetAtom
->combine() == ld::Atom::combineByNameAndContent
) || (targetAtom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
6958 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, targetAtom
);
6961 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, targetAtom
->name());
6963 parser
.addFixup(src
, ld::Fixup::k2of5
, ld::Fixup::kindAddAddend
, offsetInTarget
);
6964 parser
.addFixup(src
, ld::Fixup::k3of5
, ld::Fixup::kindSubtractTargetAddress
, fromAtom
);
6965 parser
.addFixup(src
, ld::Fixup::k4of5
, ld::Fixup::kindSubtractAddend
, offsetInFrom
-addend
);
6966 parser
.addFixup(src
, ld::Fixup::k5of5
, ld::Fixup::kindStoreLittleEndian32
);
6969 if ( targetAtom
->scope() == ld::Atom::scopeTranslationUnit
) {
6970 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, targetAtom
);
6972 else if ( (targetAtom
->combine() == ld::Atom::combineByNameAndContent
) || (targetAtom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
6973 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, targetAtom
);
6976 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, targetAtom
->name());
6978 parser
.addFixup(src
, ld::Fixup::k2of5
, ld::Fixup::kindAddAddend
, (uint32_t)(offsetInTarget
+addend
));
6979 parser
.addFixup(src
, ld::Fixup::k3of5
, ld::Fixup::kindSubtractTargetAddress
, fromAtom
);
6980 parser
.addFixup(src
, ld::Fixup::k4of5
, ld::Fixup::kindSubtractAddend
, offsetInFrom
);
6981 parser
.addFixup(src
, ld::Fixup::k5of5
, ld::Fixup::kindStoreLittleEndian32
);
6985 case ARM_RELOC_HALF_SECTDIFF
:
6986 if ( nextRelocIsPair
) {
6987 instruction
= LittleEndian::get32(*fixUpPtr
);
6988 Atom
<arm
>* fromAtom
= parser
.findAtomByAddress(nextRelocValue
);
6989 uint32_t offsetInFrom
= nextRelocValue
- fromAtom
->_objAddress
;
6990 Atom
<arm
>* targetAtom
= parser
.findAtomByAddress(sreloc
->r_value());
6991 uint32_t offsetInTarget
= sreloc
->r_value() - targetAtom
->_objAddress
;
6992 uint32_t instruction16
;
6993 uint32_t other16
= (nextRelocAddress
& 0xFFFF);
6995 if ( sreloc
->r_length() & 2 ) {
6997 uint32_t i
= ((instruction
& 0x00000400) >> 10);
6998 uint32_t imm4
= (instruction
& 0x0000000F);
6999 uint32_t imm3
= ((instruction
& 0x70000000) >> 28);
7000 uint32_t imm8
= ((instruction
& 0x00FF0000) >> 16);
7001 instruction16
= (imm4
<< 12) | (i
<< 11) | (imm3
<< 8) | imm8
;
7005 uint32_t imm4
= ((instruction
& 0x000F0000) >> 16);
7006 uint32_t imm12
= (instruction
& 0x00000FFF);
7007 instruction16
= (imm4
<< 12) | imm12
;
7009 if ( sreloc
->r_length() & 1 )
7010 dstAddr
= ((instruction16
<< 16) | other16
);
7012 dstAddr
= (other16
<< 16) | instruction16
;
7013 if ( targetAtom
->isThumb() )
7014 dstAddr
&= (-2); // remove thumb bit
7015 int32_t addend
= dstAddr
- (sreloc
->r_value() - nextRelocValue
);
7016 if ( targetAtom
->scope() == ld::Atom::scopeTranslationUnit
) {
7017 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, targetAtom
);
7019 else if ( (targetAtom
->combine() == ld::Atom::combineByNameAndContent
) || (targetAtom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
7020 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, targetAtom
);
7023 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, targetAtom
->name());
7025 parser
.addFixup(src
, ld::Fixup::k2of5
, ld::Fixup::kindAddAddend
, (uint32_t)offsetInTarget
+addend
);
7026 parser
.addFixup(src
, ld::Fixup::k3of5
, ld::Fixup::kindSubtractTargetAddress
, fromAtom
);
7027 parser
.addFixup(src
, ld::Fixup::k4of5
, ld::Fixup::kindSubtractAddend
, offsetInFrom
);
7028 if ( sreloc
->r_length() & 1 ) {
7030 parser
.addFixup(src
, ld::Fixup::k5of5
, (isThumb
? ld::Fixup::kindStoreThumbHigh16
: ld::Fixup::kindStoreARMHigh16
));
7034 parser
.addFixup(src
, ld::Fixup::k5of5
, (isThumb
? ld::Fixup::kindStoreThumbLow16
: ld::Fixup::kindStoreARMLow16
));
7039 throw "ARM_RELOC_HALF_SECTDIFF reloc missing following pair";
7041 case ARM_RELOC_HALF
:
7042 if ( nextRelocIsPair
) {
7043 instruction
= LittleEndian::get32(*fixUpPtr
);
7044 Atom
<arm
>* targetAtom
= parser
.findAtomByAddress(sreloc
->r_value());
7045 uint32_t instruction16
;
7046 uint32_t other16
= (nextRelocAddress
& 0xFFFF);
7048 if ( sreloc
->r_length() & 2 ) {
7050 uint32_t i
= ((instruction
& 0x00000400) >> 10);
7051 uint32_t imm4
= (instruction
& 0x0000000F);
7052 uint32_t imm3
= ((instruction
& 0x70000000) >> 28);
7053 uint32_t imm8
= ((instruction
& 0x00FF0000) >> 16);
7054 instruction16
= (imm4
<< 12) | (i
<< 11) | (imm3
<< 8) | imm8
;
7058 uint32_t imm4
= ((instruction
& 0x000F0000) >> 16);
7059 uint32_t imm12
= (instruction
& 0x00000FFF);
7060 instruction16
= (imm4
<< 12) | imm12
;
7062 if ( sreloc
->r_length() & 1 )
7063 dstAddr
= ((instruction16
<< 16) | other16
);
7065 dstAddr
= (other16
<< 16) | instruction16
;
7066 if ( targetAtom
->scope() == ld::Atom::scopeTranslationUnit
) {
7067 parser
.addFixup(src
, ld::Fixup::k1of3
, ld::Fixup::kindSetTargetAddress
, targetAtom
);
7069 else if ( (targetAtom
->combine() == ld::Atom::combineByNameAndContent
) || (targetAtom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
7070 parser
.addFixup(src
, ld::Fixup::k1of3
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, targetAtom
);
7073 parser
.addFixup(src
, ld::Fixup::k1of3
, ld::Fixup::kindSetTargetAddress
, false, targetAtom
->name());
7075 parser
.addFixup(src
, ld::Fixup::k2of3
, ld::Fixup::kindAddAddend
, dstAddr
- targetAtom
->_objAddress
);
7076 if ( sreloc
->r_length() & 1 ) {
7078 parser
.addFixup(src
, ld::Fixup::k3of3
, (isThumb
? ld::Fixup::kindStoreThumbHigh16
: ld::Fixup::kindStoreARMHigh16
));
7082 parser
.addFixup(src
, ld::Fixup::k3of3
, (isThumb
? ld::Fixup::kindStoreThumbLow16
: ld::Fixup::kindStoreARMLow16
));
7087 throw "scattered ARM_RELOC_HALF reloc missing following pair";
7090 throwf("unknown ARM scattered relocation type %d", sreloc
->r_type());
7098 #if SUPPORT_ARCH_arm64
7100 bool Section
<arm64
>::addRelocFixup(class Parser
<arm64
>& parser
, const macho_relocation_info
<P
>* reloc
)
7102 bool result
= false;
7103 Parser
<arm64
>::SourceLocation src
;
7104 Parser
<arm64
>::TargetDesc target
= { NULL
, NULL
, false, 0 };
7105 Parser
<arm64
>::TargetDesc toTarget
;
7106 int32_t prefixRelocAddend
= 0;
7107 if ( reloc
->r_type() == ARM64_RELOC_ADDEND
) {
7108 uint32_t rawAddend
= reloc
->r_symbolnum();
7109 prefixRelocAddend
= rawAddend
;
7110 if ( rawAddend
& 0x00800000 )
7111 prefixRelocAddend
|= 0xFF000000; // sign extend 24-bit signed int to 32-bits
7112 uint32_t addendAddress
= reloc
->r_address();
7113 ++reloc
; //advance to next reloc record
7115 if ( reloc
->r_address() != addendAddress
)
7116 throw "ARM64_RELOC_ADDEND r_address does not match next reloc's r_address";
7118 const macho_section
<P
>* sect
= this->machoSection();
7119 uint64_t srcAddr
= sect
->addr() + reloc
->r_address();
7120 src
.atom
= this->findAtomByAddress(srcAddr
);
7121 src
.offsetInAtom
= srcAddr
- src
.atom
->_objAddress
;
7122 const uint8_t* fixUpPtr
= file().fileContent() + sect
->offset() + reloc
->r_address();
7123 uint64_t contentValue
= 0;
7124 const macho_relocation_info
<arm64::P
>* nextReloc
= &reloc
[1];
7125 bool useDirectBinding
;
7126 uint32_t instruction
;
7127 uint32_t encodedAddend
;
7128 switch ( reloc
->r_length() ) {
7130 contentValue
= *fixUpPtr
;
7133 contentValue
= (int64_t)(int16_t)E::get16(*((uint16_t*)fixUpPtr
));
7136 contentValue
= (int64_t)(int32_t)E::get32(*((uint32_t*)fixUpPtr
));
7139 contentValue
= E::get64(*((uint64_t*)fixUpPtr
));
7142 if ( reloc
->r_extern() ) {
7143 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
7144 const char* symbolName
= parser
.nameFromSymbol(sym
);
7145 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && (((sym
.n_type() & N_EXT
) == 0) || (symbolName
[0] == 'L') || (symbolName
[0] == 'l')) ) {
7146 // use direct reference for local symbols
7147 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
7148 //target.addend += contentValue;
7150 else if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && (src
.atom
->_objAddress
<= sym
.n_value()) && (sym
.n_value() < (src
.atom
->_objAddress
+src
.atom
->size())) ) {
7151 // <rdar://problem/13700961> spurious warning when weak function has reference to itself
7152 // use direct reference when atom targets itself
7153 target
.atom
= src
.atom
;
7157 target
.name
= symbolName
;
7158 target
.weakImport
= parser
.weakImportFromSymbol(sym
);
7159 //target.addend = contentValue;
7161 // cfstrings should always use direct reference to backing store
7162 if ( (this->type() == ld::Section::typeCFString
) && (src
.offsetInAtom
!= 0) ) {
7163 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
7164 //target.addend = contentValue;
7168 if ( reloc
->r_pcrel() )
7169 contentValue
+= srcAddr
;
7170 parser
.findTargetFromAddressAndSectionNum(contentValue
, reloc
->r_symbolnum(), target
);
7172 switch ( reloc
->r_type() ) {
7173 case ARM64_RELOC_UNSIGNED
:
7174 if ( reloc
->r_pcrel() )
7175 throw "pcrel and ARM64_RELOC_UNSIGNED not supported";
7176 if ( reloc
->r_extern() )
7177 target
.addend
= contentValue
;
7178 switch ( reloc
->r_length() ) {
7181 throw "length < 2 and ARM64_RELOC_UNSIGNED not supported";
7183 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian32
, target
);
7186 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian64
, target
);
7190 case ARM64_RELOC_BRANCH26
:
7191 if ( ! reloc
->r_pcrel() )
7192 throw "not pcrel and ARM64_RELOC_BRANCH26 not supported";
7193 if ( ! reloc
->r_extern() )
7194 throw "r_extern == 0 and ARM64_RELOC_BRANCH26 not supported";
7195 if ( reloc
->r_length() != 2 )
7196 throw "r_length != 2 and ARM64_RELOC_BRANCH26 not supported";
7197 if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_probe$", 16) == 0) ) {
7198 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindStoreARM64DtraceCallSiteNop
, false, target
.name
);
7199 parser
.addDtraceExtraInfos(src
, &target
.name
[16]);
7201 else if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_isenabled$", 20) == 0) ) {
7202 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindStoreARM64DtraceIsEnableSiteClear
, false, target
.name
);
7203 parser
.addDtraceExtraInfos(src
, &target
.name
[20]);
7206 target
.addend
= prefixRelocAddend
;
7207 instruction
= contentValue
;
7208 encodedAddend
= (instruction
& 0x03FFFFFF) << 2;
7209 if ( encodedAddend
!= 0 ) {
7210 if ( prefixRelocAddend
== 0 ) {
7211 warning("branch26 instruction at 0x%08X has embedded addend. ARM64_RELOC_ADDEND should be used instead", reloc
->r_address());
7212 target
.addend
= encodedAddend
;
7215 throwf("branch26 instruction at 0x%08X has embedded addend and ARM64_RELOC_ADDEND also used", reloc
->r_address());
7218 parser
.addFixups(src
, ld::Fixup::kindStoreARM64Branch26
, target
);
7221 case ARM64_RELOC_PAGE21
:
7222 if ( ! reloc
->r_pcrel() )
7223 throw "not pcrel and ARM64_RELOC_PAGE21 not supported";
7224 if ( ! reloc
->r_extern() )
7225 throw "r_extern == 0 and ARM64_RELOC_PAGE21 not supported";
7226 if ( reloc
->r_length() != 2 )
7227 throw "length != 2 and ARM64_RELOC_PAGE21 not supported";
7228 target
.addend
= prefixRelocAddend
;
7229 instruction
= contentValue
;
7230 encodedAddend
= ((instruction
& 0x60000000) >> 29) | ((instruction
& 0x01FFFFE0) >> 3);
7231 encodedAddend
*= 4096; // internally addend is in bytes, so scale
7232 if ( encodedAddend
!= 0 ) {
7233 if ( prefixRelocAddend
== 0 ) {
7234 warning("adrp instruction at 0x%08X has embedded addend. ARM64_RELOC_ADDEND should be used instead", reloc
->r_address());
7235 target
.addend
= encodedAddend
;
7238 throwf("adrp instruction at 0x%08X has embedded addend and ARM64_RELOC_ADDEND also used", reloc
->r_address());
7241 parser
.addFixups(src
, ld::Fixup::kindStoreARM64Page21
, target
);
7243 case ARM64_RELOC_PAGEOFF12
:
7244 if ( reloc
->r_pcrel() )
7245 throw "pcrel and ARM64_RELOC_PAGEOFF12 not supported";
7246 if ( ! reloc
->r_extern() )
7247 throw "r_extern == 0 and ARM64_RELOC_PAGEOFF12 not supported";
7248 if ( reloc
->r_length() != 2 )
7249 throw "length != 2 and ARM64_RELOC_PAGEOFF12 not supported";
7250 target
.addend
= prefixRelocAddend
;
7251 instruction
= contentValue
;
7252 encodedAddend
= ((instruction
& 0x003FFC00) >> 10);
7253 // internally addend is in bytes. Some instructions have an implicit scale factor
7254 if ( (instruction
& 0x3B000000) == 0x39000000 ) {
7255 switch ( instruction
& 0xC0000000 ) {
7269 if ( encodedAddend
!= 0 ) {
7270 if ( prefixRelocAddend
== 0 ) {
7271 warning("pageoff12 instruction at 0x%08X has embedded addend. ARM64_RELOC_ADDEND should be used instead", reloc
->r_address());
7272 target
.addend
= encodedAddend
;
7275 throwf("pageoff12 instruction at 0x%08X has embedded addend and ARM64_RELOC_ADDEND also used", reloc
->r_address());
7278 parser
.addFixups(src
, ld::Fixup::kindStoreARM64PageOff12
, target
);
7280 case ARM64_RELOC_GOT_LOAD_PAGE21
:
7281 if ( ! reloc
->r_pcrel() )
7282 throw "not pcrel and ARM64_RELOC_GOT_LOAD_PAGE21 not supported";
7283 if ( ! reloc
->r_extern() )
7284 throw "r_extern == 0 and ARM64_RELOC_GOT_LOAD_PAGE21 not supported";
7285 if ( reloc
->r_length() != 2 )
7286 throw "length != 2 and ARM64_RELOC_GOT_LOAD_PAGE21 not supported";
7287 if ( prefixRelocAddend
!= 0 )
7288 throw "ARM64_RELOC_ADDEND followed by ARM64_RELOC_GOT_LOAD_PAGE21 not supported";
7289 instruction
= contentValue
;
7290 target
.addend
= ((instruction
& 0x60000000) >> 29) | ((instruction
& 0x01FFFFE0) >> 3);
7291 if ( target
.addend
!= 0 )
7292 throw "non-zero addend with ARM64_RELOC_GOT_LOAD_PAGE21 is not supported";
7293 parser
.addFixups(src
, ld::Fixup::kindStoreARM64GOTLoadPage21
, target
);
7295 case ARM64_RELOC_GOT_LOAD_PAGEOFF12
:
7296 if ( reloc
->r_pcrel() )
7297 throw "pcrel and ARM64_RELOC_GOT_LOAD_PAGEOFF12 not supported";
7298 if ( ! reloc
->r_extern() )
7299 throw "r_extern == 0 and ARM64_RELOC_GOT_LOAD_PAGEOFF12 not supported";
7300 if ( reloc
->r_length() != 2 )
7301 throw "length != 2 and ARM64_RELOC_GOT_LOAD_PAGEOFF12 not supported";
7302 if ( prefixRelocAddend
!= 0 )
7303 throw "ARM64_RELOC_ADDEND followed by ARM64_RELOC_GOT_LOAD_PAGEOFF12 not supported";
7304 instruction
= contentValue
;
7305 target
.addend
= ((instruction
& 0x003FFC00) >> 10);
7306 parser
.addFixups(src
, ld::Fixup::kindStoreARM64GOTLoadPageOff12
, target
);
7308 case ARM64_RELOC_TLVP_LOAD_PAGE21
:
7309 if ( ! reloc
->r_pcrel() )
7310 throw "not pcrel and ARM64_RELOC_TLVP_LOAD_PAGE21 not supported";
7311 if ( ! reloc
->r_extern() )
7312 throw "r_extern == 0 and ARM64_RELOC_TLVP_LOAD_PAGE21 not supported";
7313 if ( reloc
->r_length() != 2 )
7314 throw "length != 2 and ARM64_RELOC_TLVP_LOAD_PAGE21 not supported";
7315 if ( prefixRelocAddend
!= 0 )
7316 throw "ARM64_RELOC_ADDEND followed by ARM64_RELOC_TLVP_LOAD_PAGE21 not supported";
7317 instruction
= contentValue
;
7318 target
.addend
= ((instruction
& 0x60000000) >> 29) | ((instruction
& 0x01FFFFE0) >> 3);
7319 if ( target
.addend
!= 0 )
7320 throw "non-zero addend with ARM64_RELOC_GOT_LOAD_PAGE21 is not supported";
7321 parser
.addFixups(src
, ld::Fixup::kindStoreARM64TLVPLoadPage21
, target
);
7323 case ARM64_RELOC_TLVP_LOAD_PAGEOFF12
:
7324 if ( reloc
->r_pcrel() )
7325 throw "pcrel and ARM64_RELOC_TLVP_LOAD_PAGEOFF12 not supported";
7326 if ( ! reloc
->r_extern() )
7327 throw "r_extern == 0 and ARM64_RELOC_TLVP_LOAD_PAGEOFF12 not supported";
7328 if ( reloc
->r_length() != 2 )
7329 throw "length != 2 and ARM64_RELOC_TLVP_LOAD_PAGEOFF12 not supported";
7330 if ( prefixRelocAddend
!= 0 )
7331 throw "ARM64_RELOC_ADDEND followed by ARM64_RELOC_TLVP_LOAD_PAGEOFF12 not supported";
7332 instruction
= contentValue
;
7333 target
.addend
= ((instruction
& 0x003FFC00) >> 10);
7334 parser
.addFixups(src
, ld::Fixup::kindStoreARM64TLVPLoadPageOff12
, target
);
7336 case ARM64_RELOC_SUBTRACTOR
:
7337 if ( reloc
->r_pcrel() )
7338 throw "ARM64_RELOC_SUBTRACTOR cannot be pc-relative";
7339 if ( reloc
->r_length() < 2 )
7340 throw "ARM64_RELOC_SUBTRACTOR must have r_length of 2 or 3";
7341 if ( !reloc
->r_extern() )
7342 throw "ARM64_RELOC_SUBTRACTOR must have r_extern=1";
7343 if ( nextReloc
->r_type() != ARM64_RELOC_UNSIGNED
)
7344 throw "ARM64_RELOC_SUBTRACTOR must be followed by ARM64_RELOC_UNSIGNED";
7345 if ( prefixRelocAddend
!= 0 )
7346 throw "ARM64_RELOC_ADDEND followed by ARM64_RELOC_SUBTRACTOR not supported";
7348 if ( nextReloc
->r_pcrel() )
7349 throw "ARM64_RELOC_UNSIGNED following a ARM64_RELOC_SUBTRACTOR cannot be pc-relative";
7350 if ( nextReloc
->r_length() != reloc
->r_length() )
7351 throw "ARM64_RELOC_UNSIGNED following a ARM64_RELOC_SUBTRACTOR must have same r_length";
7352 if ( nextReloc
->r_extern() ) {
7353 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(nextReloc
->r_symbolnum());
7354 // use direct reference for local symbols
7355 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && (((sym
.n_type() & N_EXT
) == 0) || (parser
.nameFromSymbol(sym
)[0] == 'L')) ) {
7356 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), toTarget
);
7357 toTarget
.addend
= contentValue
;
7358 useDirectBinding
= true;
7361 toTarget
.name
= parser
.nameFromSymbol(sym
);
7362 toTarget
.weakImport
= parser
.weakImportFromSymbol(sym
);
7363 toTarget
.addend
= contentValue
;
7364 useDirectBinding
= false;
7368 parser
.findTargetFromAddressAndSectionNum(contentValue
, nextReloc
->r_symbolnum(), toTarget
);
7369 useDirectBinding
= (toTarget
.atom
->scope() == ld::Atom::scopeTranslationUnit
);
7371 if ( useDirectBinding
)
7372 parser
.addFixup(src
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, toTarget
.atom
);
7374 parser
.addFixup(src
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, toTarget
.weakImport
, toTarget
.name
);
7375 parser
.addFixup(src
, ld::Fixup::k2of4
, ld::Fixup::kindAddAddend
, toTarget
.addend
);
7376 if ( target
.atom
== NULL
)
7377 parser
.addFixup(src
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractTargetAddress
, false, target
.name
);
7379 parser
.addFixup(src
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractTargetAddress
, target
.atom
);
7380 if ( reloc
->r_length() == 2 )
7381 parser
.addFixup(src
, ld::Fixup::k4of4
, ld::Fixup::kindStoreLittleEndian32
);
7383 parser
.addFixup(src
, ld::Fixup::k4of4
, ld::Fixup::kindStoreLittleEndian64
);
7385 case ARM64_RELOC_POINTER_TO_GOT
:
7386 if ( ! reloc
->r_extern() )
7387 throw "r_extern == 0 and ARM64_RELOC_POINTER_TO_GOT not supported";
7388 if ( prefixRelocAddend
!= 0 )
7389 throw "ARM64_RELOC_ADDEND followed by ARM64_RELOC_POINTER_TO_GOT not supported";
7390 if ( reloc
->r_pcrel() ) {
7391 if ( reloc
->r_length() != 2 )
7392 throw "r_length != 2 and r_extern = 1 and ARM64_RELOC_POINTER_TO_GOT not supported";
7393 parser
.addFixups(src
, ld::Fixup::kindStoreARM64PCRelToGOT
, target
);
7396 if ( reloc
->r_length() != 3 )
7397 throw "r_length != 3 and r_extern = 0 and ARM64_RELOC_POINTER_TO_GOT not supported";
7398 parser
.addFixups(src
, ld::Fixup::kindStoreARM64PointerToGOT
, target
);
7402 throwf("unknown relocation type %d", reloc
->r_type());
7408 template <typename A
>
7409 bool ObjC1ClassSection
<A
>::addRelocFixup(class Parser
<A
>& parser
, const macho_relocation_info
<P
>* reloc
)
7412 FixedSizeSection
<A
>::addRelocFixup(parser
, reloc
);
7414 assert(0 && "needs template specialization");
7419 bool ObjC1ClassSection
<x86
>::addRelocFixup(class Parser
<x86
>& parser
, const macho_relocation_info
<x86::P
>* reloc
)
7421 // if this is the reloc for the super class name string, add implicit reference to super class
7422 if ( ((reloc
->r_address() & R_SCATTERED
) == 0) && (reloc
->r_type() == GENERIC_RELOC_VANILLA
) ) {
7423 assert( reloc
->r_length() == 2 );
7424 assert( ! reloc
->r_pcrel() );
7426 const macho_section
<P
>* sect
= this->machoSection();
7427 Parser
<x86
>::SourceLocation src
;
7428 uint32_t srcAddr
= sect
->addr() + reloc
->r_address();
7429 src
.atom
= this->findAtomByAddress(srcAddr
);
7430 src
.offsetInAtom
= srcAddr
- src
.atom
->objectAddress();
7431 if ( src
.offsetInAtom
== 4 ) {
7432 Parser
<x86
>::TargetDesc stringTarget
;
7433 const uint8_t* fixUpPtr
= file().fileContent() + sect
->offset() + reloc
->r_address();
7434 uint32_t contentValue
= LittleEndian::get32(*((uint32_t*)fixUpPtr
));
7435 parser
.findTargetFromAddressAndSectionNum(contentValue
, reloc
->r_symbolnum(), stringTarget
);
7437 assert(stringTarget
.atom
!= NULL
);
7438 assert(stringTarget
.atom
->contentType() == ld::Atom::typeCString
);
7439 const char* superClassBaseName
= (char*)stringTarget
.atom
->rawContentPointer();
7440 char* superClassName
= new char[strlen(superClassBaseName
) + 20];
7441 strcpy(superClassName
, ".objc_class_name_");
7442 strcat(superClassName
, superClassBaseName
);
7444 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindSetTargetAddress
, false, superClassName
);
7448 return FixedSizeSection
<x86
>::addRelocFixup(parser
, reloc
);
7453 template <typename A
>
7454 bool Objc1ClassReferences
<A
>::addRelocFixup(class Parser
<A
>& parser
, const macho_relocation_info
<P
>* reloc
)
7457 PointerToCStringSection
<A
>::addRelocFixup(parser
, reloc
);
7459 assert(0 && "needs template specialization");
7466 bool Objc1ClassReferences
<x86
>::addRelocFixup(class Parser
<x86
>& parser
, const macho_relocation_info
<x86::P
>* reloc
)
7468 // add implict class refs, fixups not usable yet, so look at relocations
7469 assert( (reloc
->r_address() & R_SCATTERED
) == 0 );
7470 assert( reloc
->r_type() == GENERIC_RELOC_VANILLA
);
7471 assert( reloc
->r_length() == 2 );
7472 assert( ! reloc
->r_pcrel() );
7474 const macho_section
<P
>* sect
= this->machoSection();
7475 Parser
<x86
>::SourceLocation src
;
7476 uint32_t srcAddr
= sect
->addr() + reloc
->r_address();
7477 src
.atom
= this->findAtomByAddress(srcAddr
);
7478 src
.offsetInAtom
= srcAddr
- src
.atom
->objectAddress();
7479 Parser
<x86
>::TargetDesc stringTarget
;
7480 const uint8_t* fixUpPtr
= file().fileContent() + sect
->offset() + reloc
->r_address();
7481 uint32_t contentValue
= LittleEndian::get32(*((uint32_t*)fixUpPtr
));
7482 parser
.findTargetFromAddressAndSectionNum(contentValue
, reloc
->r_symbolnum(), stringTarget
);
7484 assert(stringTarget
.atom
!= NULL
);
7485 assert(stringTarget
.atom
->contentType() == ld::Atom::typeCString
);
7486 const char* baseClassName
= (char*)stringTarget
.atom
->rawContentPointer();
7487 char* objcClassName
= new char[strlen(baseClassName
) + 20];
7488 strcpy(objcClassName
, ".objc_class_name_");
7489 strcat(objcClassName
, baseClassName
);
7491 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindSetTargetAddress
, false, objcClassName
);
7494 return PointerToCStringSection
<x86
>::addRelocFixup(parser
, reloc
);
7497 #if SUPPORT_ARCH_arm64
7499 void Section
<arm64
>::addLOH(class Parser
<arm64
>& parser
, int kind
, int count
, const uint64_t addrs
[]) {
7501 case LOH_ARM64_ADRP_ADRP
:
7502 case LOH_ARM64_ADRP_LDR
:
7503 case LOH_ARM64_ADRP_ADD
:
7504 case LOH_ARM64_ADRP_LDR_GOT
:
7506 warning("arm64 Linker Optimiztion Hint %d has wrong number of arguments", kind
);
7508 case LOH_ARM64_ADRP_ADD_LDR
:
7509 case LOH_ARM64_ADRP_LDR_GOT_LDR
:
7510 case LOH_ARM64_ADRP_ADD_STR
:
7511 case LOH_ARM64_ADRP_LDR_GOT_STR
:
7513 warning("arm64 Linker Optimiztion Hint %d has wrong number of arguments", kind
);
7516 // pick lowest address in tuple for use as offsetInAtom
7517 uint64_t lowestAddress
= addrs
[0];
7518 for(int i
=1; i
< count
; ++i
) {
7519 if ( addrs
[i
] < lowestAddress
)
7520 lowestAddress
= addrs
[i
];
7522 // verify all other address are in same atom
7523 Atom
<arm64
>* inAtom
= parser
.findAtomByAddress(lowestAddress
);
7524 const uint64_t atomStartAddr
= inAtom
->objectAddress();
7525 const uint64_t atomEndAddr
= atomStartAddr
+ inAtom
->size();
7526 for(int i
=0; i
< count
; ++i
) {
7527 if ( (addrs
[i
] < atomStartAddr
) || (addrs
[i
] >= atomEndAddr
) ) {
7528 warning("arm64 Linker Optimiztion Hint addresses are not in same atom: 0x%08llX and 0x%08llX",
7529 lowestAddress
, addrs
[i
]);
7530 return; // skip this LOH
7532 if ( (addrs
[i
] & 0x3) != 0 ) {
7533 warning("arm64 Linker Optimiztion Hint address is not 4-byte aligned: 0x%08llX", addrs
[i
]);
7534 return; // skip this LOH
7536 if ( (addrs
[i
] - lowestAddress
) > 0xFFFF ) {
7537 if ( parser
.verboseOptimizationHints() ) {
7538 warning("arm64 Linker Optimiztion Hint addresses are too far apart: 0x%08llX and 0x%08llX",
7539 lowestAddress
, addrs
[i
]);
7541 return; // skip this LOH
7545 // encoded kind, count, and address deltas in 64-bit addend
7546 ld::Fixup::LOH_arm64 extra
;
7548 extra
.info
.kind
= kind
;
7549 extra
.info
.count
= count
-1;
7550 extra
.info
.delta1
= (addrs
[0] - lowestAddress
) >> 2;
7551 extra
.info
.delta2
= (count
> 1) ? ((addrs
[1] - lowestAddress
) >> 2) : 0;
7552 extra
.info
.delta3
= (count
> 2) ? ((addrs
[2] - lowestAddress
) >> 2) : 0;
7553 extra
.info
.delta4
= (count
> 3) ? ((addrs
[3] - lowestAddress
) >> 2) : 0;
7554 typename Parser
<arm64
>::SourceLocation
src(inAtom
, lowestAddress
- inAtom
->objectAddress());
7555 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindLinkerOptimizationHint
, extra
.addend
);
7559 template <typename A
>
7560 void Section
<A
>::addLOH(class Parser
<A
>& parser
, int kind
, int count
, const uint64_t addrs
[]) {
7564 template <typename A
>
7565 void Section
<A
>::makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&)
7567 const macho_section
<P
>* sect
= this->machoSection();
7568 if ( sect
->reloff() + (sect
->nreloc() * sizeof(macho_relocation_info
<P
>)) > parser
.fileLength() )
7569 throwf("relocations for section %s/%s extends beyond end of file,", sect
->segname(), Section
<A
>::makeSectionName(sect
) );
7570 const macho_relocation_info
<P
>* relocs
= (macho_relocation_info
<P
>*)(file().fileContent() + sect
->reloff());
7571 const uint32_t relocCount
= sect
->nreloc();
7572 for (uint32_t r
= 0; r
< relocCount
; ++r
) {
7574 if ( this->addRelocFixup(parser
, &relocs
[r
]) )
7577 catch (const char* msg
) {
7578 throwf("in section %s,%s reloc %u: %s", sect
->segname(), Section
<A
>::makeSectionName(sect
), r
, msg
);
7582 // add follow-on fixups if .o file is missing .subsections_via_symbols
7583 if ( this->addFollowOnFixups() ) {
7584 Atom
<A
>* end
= &_endAtoms
[-1];
7585 for(Atom
<A
>* p
= _beginAtoms
; p
< end
; ++p
) {
7586 typename Parser
<A
>::SourceLocation
src(p
, 0);
7587 Atom
<A
>* nextAtom
= &p
[1];
7588 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindNoneFollowOn
, nextAtom
);
7591 else if ( this->type() == ld::Section::typeCode
) {
7592 // if FDE broke text not at a symbol, use followOn to keep code together
7593 Atom
<A
>* end
= &_endAtoms
[-1];
7594 for(Atom
<A
>* p
= _beginAtoms
; p
< end
; ++p
) {
7595 typename Parser
<A
>::SourceLocation
src(p
, 0);
7596 Atom
<A
>* nextAtom
= &p
[1];
7597 if ( (p
->symbolTableInclusion() == ld::Atom::symbolTableIn
) && (nextAtom
->symbolTableInclusion() == ld::Atom::symbolTableNotIn
) ) {
7598 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindNoneFollowOn
, nextAtom
);
7602 if ( !this->_altEntries
.empty() && !this->addFollowOnFixups() ) {
7603 if ( _altEntries
.count(_beginAtoms
) != 0 )
7604 warning("N_ALT_ENTRY bit set on first atom in section %s/%s", sect
->segname(), Section
<A
>::makeSectionName(sect
));
7606 Atom
<A
>* end
= &_endAtoms
[-1];
7607 for(Atom
<A
>* p
= _beginAtoms
; p
< end
; ++p
) {
7608 Atom
<A
>* nextAtom
= &p
[1];
7609 // <rdar://problem/22960070> support alt_entry aliases (alias process already added followOn, don't repeat)
7610 if ( (_altEntries
.count(nextAtom
) != 0) && (p
->_objAddress
!= nextAtom
->_objAddress
) ) {
7611 typename Parser
<A
>::SourceLocation
src(p
, 0);
7612 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindNoneFollowOn
, nextAtom
);
7613 typename Parser
<A
>::SourceLocation
src2(nextAtom
, 0);
7614 parser
.addFixup(src2
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinate
, p
);
7619 // <rdar://problem/9218847> track data-in-code
7620 if ( parser
.hasDataInCodeLabels() && (this->type() == ld::Section::typeCode
) ) {
7621 for (uint32_t i
=0; i
< parser
.symbolCount(); ++i
) {
7622 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(i
);
7624 if ( (sym
.n_type() & N_STAB
) != 0 )
7626 // ignore non-definitions
7627 if ( (sym
.n_type() & N_TYPE
) != N_SECT
)
7630 // 'L' labels do not denote atom breaks
7631 const char* symbolName
= parser
.nameFromSymbol(sym
);
7632 if ( symbolName
[0] == 'L' ) {
7633 if ( strncmp(symbolName
, "L$start$", 8) == 0 ) {
7634 ld::Fixup::Kind kind
= ld::Fixup::kindNone
;
7635 if ( strncmp(&symbolName
[8], "data$", 5) == 0 )
7636 kind
= ld::Fixup::kindDataInCodeStartData
;
7637 else if ( strncmp(&symbolName
[8], "code$", 5) == 0 )
7638 kind
= ld::Fixup::kindDataInCodeEnd
;
7639 else if ( strncmp(&symbolName
[8], "jt8$", 4) == 0 )
7640 kind
= ld::Fixup::kindDataInCodeStartJT8
;
7641 else if ( strncmp(&symbolName
[8], "jt16$", 4) == 0 )
7642 kind
= ld::Fixup::kindDataInCodeStartJT16
;
7643 else if ( strncmp(&symbolName
[8], "jt32$", 4) == 0 )
7644 kind
= ld::Fixup::kindDataInCodeStartJT32
;
7645 else if ( strncmp(&symbolName
[8], "jta32$", 4) == 0 )
7646 kind
= ld::Fixup::kindDataInCodeStartJTA32
;
7648 warning("unknown L$start$ label %s in file %s", symbolName
, this->file().path());
7649 if ( kind
!= ld::Fixup::kindNone
) {
7650 Atom
<A
>* inAtom
= parser
.findAtomByAddress(sym
.n_value());
7651 typename Parser
<A
>::SourceLocation
src(inAtom
, sym
.n_value() - inAtom
->objectAddress());
7652 parser
.addFixup(src
, ld::Fixup::k1of1
, kind
);
7659 // <rdar://problem/11150575> Handle LC_DATA_IN_CODE in object files
7660 if ( this->type() == ld::Section::typeCode
) {
7661 const pint_t startAddr
= this->_machOSection
->addr();
7662 const pint_t endAddr
= startAddr
+ this->_machOSection
->size();
7663 for ( const macho_data_in_code_entry
<P
>* p
= parser
.dataInCodeStart(); p
!= parser
.dataInCodeEnd(); ++p
) {
7664 if ( (p
->offset() >= startAddr
) && (p
->offset() < endAddr
) ) {
7665 ld::Fixup::Kind kind
= ld::Fixup::kindNone
;
7666 switch ( p
->kind() ) {
7667 case DICE_KIND_DATA
:
7668 kind
= ld::Fixup::kindDataInCodeStartData
;
7670 case DICE_KIND_JUMP_TABLE8
:
7671 kind
= ld::Fixup::kindDataInCodeStartJT8
;
7673 case DICE_KIND_JUMP_TABLE16
:
7674 kind
= ld::Fixup::kindDataInCodeStartJT16
;
7676 case DICE_KIND_JUMP_TABLE32
:
7677 kind
= ld::Fixup::kindDataInCodeStartJT32
;
7679 case DICE_KIND_ABS_JUMP_TABLE32
:
7680 kind
= ld::Fixup::kindDataInCodeStartJTA32
;
7683 kind
= ld::Fixup::kindDataInCodeStartData
;
7684 warning("uknown LC_DATA_IN_CODE kind (%d) at offset 0x%08X", p
->kind(), p
->offset());
7687 Atom
<A
>* inAtom
= parser
.findAtomByAddress(p
->offset());
7688 typename Parser
<A
>::SourceLocation
srcStart(inAtom
, p
->offset() - inAtom
->objectAddress());
7689 parser
.addFixup(srcStart
, ld::Fixup::k1of1
, kind
);
7690 typename Parser
<A
>::SourceLocation
srcEnd(inAtom
, p
->offset() + p
->length() - inAtom
->objectAddress());
7691 parser
.addFixup(srcEnd
, ld::Fixup::k1of1
, ld::Fixup::kindDataInCodeEnd
);
7696 // <rdar://problem/11945700> convert linker optimization hints into internal format
7697 if ( this->type() == ld::Section::typeCode
&& parser
.hasOptimizationHints() ) {
7698 const pint_t startAddr
= this->_machOSection
->addr();
7699 const pint_t endAddr
= startAddr
+ this->_machOSection
->size();
7700 for (const uint8_t* p
= parser
.optimizationHintsStart(); p
< parser
.optimizationHintsEnd(); ) {
7702 int32_t kind
= read_uleb128(&p
, parser
.optimizationHintsEnd());
7703 if ( kind
== 0 ) // padding at end of loh buffer
7706 warning("malformed uleb128 kind in LC_LINKER_OPTIMIZATION_HINTS");
7709 int32_t count
= read_uleb128(&p
, parser
.optimizationHintsEnd());
7710 if ( count
== -1 ) {
7711 warning("malformed uleb128 count in LC_LINKER_OPTIMIZATION_HINTS");
7715 warning("address count > 3 in LC_LINKER_OPTIMIZATION_HINTS");
7718 for (int32_t i
=0; i
< count
; ++i
) {
7719 addrs
[i
] = read_uleb128(&p
, parser
.optimizationHintsEnd());
7721 if ( (startAddr
<= addrs
[0]) && (addrs
[0] < endAddr
) ) {
7722 this->addLOH(parser
, kind
, count
, addrs
);
7723 //fprintf(stderr, "kind=%d", kind);
7724 //for (int32_t i=0; i < count; ++i) {
7725 // fprintf(stderr, ", addr=0x%08llX", addrs[i]);
7727 //fprintf(stderr, "\n");
7733 // add follow-on fixups for aliases
7734 if ( _hasAliases
) {
7735 for(Atom
<A
>* p
= _beginAtoms
; p
< _endAtoms
; ++p
) {
7736 if ( p
->isAlias() && ! this->addFollowOnFixups() ) {
7737 Atom
<A
>* targetOfAlias
= &p
[1];
7738 assert(p
< &_endAtoms
[-1]);
7739 assert(p
->_objAddress
== targetOfAlias
->_objAddress
);
7740 typename Parser
<A
>::SourceLocation
src(p
, 0);
7741 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindNoneFollowOn
, targetOfAlias
);
7750 // main function used by linker to instantiate ld::Files
7752 ld::relocatable::File
* parse(const uint8_t* fileContent
, uint64_t fileLength
,
7753 const char* path
, time_t modTime
, ld::File::Ordinal ordinal
, const ParserOptions
& opts
)
7755 switch ( opts
.architecture
) {
7756 #if SUPPORT_ARCH_x86_64
7757 case CPU_TYPE_X86_64
:
7758 if ( mach_o::relocatable::Parser
<x86_64
>::validFile(fileContent
) )
7759 return mach_o::relocatable::Parser
<x86_64
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
);
7762 #if SUPPORT_ARCH_i386
7764 if ( mach_o::relocatable::Parser
<x86
>::validFile(fileContent
) )
7765 return mach_o::relocatable::Parser
<x86
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
);
7768 #if SUPPORT_ARCH_arm_any
7770 if ( mach_o::relocatable::Parser
<arm
>::validFile(fileContent
, opts
.objSubtypeMustMatch
, opts
.subType
) )
7771 return mach_o::relocatable::Parser
<arm
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
);
7774 #if SUPPORT_ARCH_arm64
7775 case CPU_TYPE_ARM64
:
7776 if ( mach_o::relocatable::Parser
<arm64
>::validFile(fileContent
, opts
.objSubtypeMustMatch
, opts
.subType
) )
7777 return mach_o::relocatable::Parser
<arm64
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
);
7785 // used by archive reader to validate member object file
7787 bool isObjectFile(const uint8_t* fileContent
, uint64_t fileLength
, const ParserOptions
& opts
)
7789 switch ( opts
.architecture
) {
7790 case CPU_TYPE_X86_64
:
7791 return ( mach_o::relocatable::Parser
<x86_64
>::validFile(fileContent
) );
7793 return ( mach_o::relocatable::Parser
<x86
>::validFile(fileContent
) );
7795 return ( mach_o::relocatable::Parser
<arm
>::validFile(fileContent
, opts
.objSubtypeMustMatch
, opts
.subType
) );
7796 case CPU_TYPE_ARM64
:
7797 return ( mach_o::relocatable::Parser
<arm64
>::validFile(fileContent
, opts
.objSubtypeMustMatch
, opts
.subType
) );
7803 // used by linker to infer architecture when no -arch is on command line
7805 bool isObjectFile(const uint8_t* fileContent
, cpu_type_t
* result
, cpu_subtype_t
* subResult
, Options::Platform
* platform
)
7807 if ( mach_o::relocatable::Parser
<x86_64
>::validFile(fileContent
) ) {
7808 *result
= CPU_TYPE_X86_64
;
7809 const macho_header
<Pointer64
<LittleEndian
> >* header
= (const macho_header
<Pointer64
<LittleEndian
> >*)fileContent
;
7810 *subResult
= header
->cpusubtype();
7811 *platform
= Parser
<x86_64
>::findPlatform(header
);
7814 if ( mach_o::relocatable::Parser
<x86
>::validFile(fileContent
) ) {
7815 const macho_header
<Pointer32
<LittleEndian
> >* header
= (const macho_header
<Pointer32
<LittleEndian
> >*)fileContent
;
7816 *result
= CPU_TYPE_I386
;
7817 *subResult
= CPU_SUBTYPE_X86_ALL
;
7818 *platform
= Parser
<x86
>::findPlatform(header
);
7821 if ( mach_o::relocatable::Parser
<arm
>::validFile(fileContent
, false, 0) ) {
7822 const macho_header
<Pointer32
<LittleEndian
> >* header
= (const macho_header
<Pointer32
<LittleEndian
> >*)fileContent
;
7823 *result
= CPU_TYPE_ARM
;
7824 *subResult
= header
->cpusubtype();
7825 *platform
= Parser
<arm
>::findPlatform(header
);
7828 if ( mach_o::relocatable::Parser
<arm64
>::validFile(fileContent
, false, 0) ) {
7829 const macho_header
<Pointer64
<LittleEndian
> >* header
= (const macho_header
<Pointer64
<LittleEndian
> >*)fileContent
;
7830 *result
= CPU_TYPE_ARM64
;
7831 *subResult
= CPU_SUBTYPE_ARM64_ALL
;
7832 *platform
= Parser
<arm64
>::findPlatform(header
);
7839 // used by linker is error messages to describe bad .o file
7841 const char* archName(const uint8_t* fileContent
)
7843 if ( mach_o::relocatable::Parser
<x86_64
>::validFile(fileContent
) ) {
7844 return mach_o::relocatable::Parser
<x86_64
>::fileKind(fileContent
);
7846 if ( mach_o::relocatable::Parser
<x86
>::validFile(fileContent
) ) {
7847 return mach_o::relocatable::Parser
<x86
>::fileKind(fileContent
);
7849 if ( mach_o::relocatable::Parser
<arm
>::validFile(fileContent
, false, 0) ) {
7850 return mach_o::relocatable::Parser
<arm
>::fileKind(fileContent
);
7856 // Used by archive reader when -ObjC option is specified
7858 bool hasObjC2Categories(const uint8_t* fileContent
)
7860 if ( mach_o::relocatable::Parser
<x86_64
>::validFile(fileContent
) ) {
7861 return mach_o::relocatable::Parser
<x86_64
>::hasObjC2Categories(fileContent
);
7863 else if ( mach_o::relocatable::Parser
<arm
>::validFile(fileContent
, false, 0) ) {
7864 return mach_o::relocatable::Parser
<arm
>::hasObjC2Categories(fileContent
);
7866 else if ( mach_o::relocatable::Parser
<x86
>::validFile(fileContent
, false, 0) ) {
7867 return mach_o::relocatable::Parser
<x86
>::hasObjC2Categories(fileContent
);
7869 #if SUPPORT_ARCH_arm64
7870 else if ( mach_o::relocatable::Parser
<arm64
>::validFile(fileContent
, false, 0) ) {
7871 return mach_o::relocatable::Parser
<arm64
>::hasObjC2Categories(fileContent
);
7878 // Used by archive reader when -ObjC option is specified
7880 bool hasObjC1Categories(const uint8_t* fileContent
)
7882 if ( mach_o::relocatable::Parser
<x86
>::validFile(fileContent
, false, 0) ) {
7883 return mach_o::relocatable::Parser
<x86
>::hasObjC1Categories(fileContent
);
7889 // Used by bitcode obfuscator to get a list of non local symbols from object file
7891 bool getNonLocalSymbols(const uint8_t* fileContent
, std::vector
<const char*> &syms
)
7893 if ( mach_o::relocatable::Parser
<x86_64
>::validFile(fileContent
) ) {
7894 return mach_o::relocatable::Parser
<x86_64
>::getNonLocalSymbols(fileContent
, syms
);
7896 else if ( mach_o::relocatable::Parser
<arm
>::validFile(fileContent
, false, 0) ) {
7897 return mach_o::relocatable::Parser
<arm
>::getNonLocalSymbols(fileContent
, syms
);
7899 else if ( mach_o::relocatable::Parser
<x86
>::validFile(fileContent
, false, 0) ) {
7900 return mach_o::relocatable::Parser
<x86
>::getNonLocalSymbols(fileContent
, syms
);
7902 else if ( mach_o::relocatable::Parser
<arm64
>::validFile(fileContent
, false, 0) ) {
7903 return mach_o::relocatable::Parser
<arm64
>::getNonLocalSymbols(fileContent
, syms
);
7910 } // namespace relocatable
7911 } // namespace mach_o