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
),
87 _platform(Options::kPlatformUnknown
),
88 _canScatterAtoms(false),
89 _objcHasCategoryClassPropertiesField(false),
90 _srcKind(kSourceUnknown
) { }
93 // overrides of ld::File
94 virtual bool forEachAtom(ld::File::AtomHandler
&) const;
95 virtual bool justInTimeforEachAtom(const char* name
, ld::File::AtomHandler
&) const
97 virtual uint32_t minOSVersion() const { return _minOSVersion
; }
98 virtual uint32_t platform() const { return _platform
; }
100 // overrides of ld::relocatable::File
101 virtual ObjcConstraint
objCConstraint() const { return _objConstraint
; }
102 virtual bool objcHasCategoryClassPropertiesField() const
103 { return _objcHasCategoryClassPropertiesField
; }
104 virtual uint32_t cpuSubType() const { return _cpuSubType
; }
105 virtual DebugInfoKind
debugInfo() const { return _debugInfoKind
; }
106 virtual const std::vector
<ld::relocatable::File::Stab
>* stabs() const { return &_stabs
; }
107 virtual bool canScatterAtoms() const { return _canScatterAtoms
; }
108 virtual const char* translationUnitSource() const;
109 virtual LinkerOptionsList
* linkerOptions() const { return &_linkerOptions
; }
110 virtual const ToolVersionList
& toolVersions() const { return _toolVersions
; }
111 virtual uint8_t swiftVersion() const { return _swiftVersion
; }
112 virtual ld::Bitcode
* getBitcode() const { return _bitcode
.get(); }
113 virtual SourceKind
sourceKind() const { return _srcKind
; }
115 virtual const uint8_t* fileContent() const { return _fileContent
; }
117 friend class Atom
<A
>;
118 friend class Section
<A
>;
119 friend class Parser
<A
>;
120 friend class CFISection
<A
>::OAS
;
122 typedef typename
A::P P
;
124 const uint8_t* _fileContent
;
125 Section
<A
>** _sectionsArray
;
126 uint8_t* _atomsArray
;
127 uint8_t* _aliasAtomsArray
;
128 uint32_t _sectionsArrayCount
;
129 uint32_t _atomsArrayCount
;
130 uint32_t _aliasAtomsArrayCount
;
131 std::vector
<ld::Fixup
> _fixups
;
132 std::vector
<ld::Atom::UnwindInfo
> _unwindInfos
;
133 std::vector
<ld::Atom::LineInfo
> _lineInfos
;
134 std::vector
<ld::relocatable::File::Stab
>_stabs
;
135 ld::relocatable::File::DebugInfoKind _debugInfoKind
;
136 const char* _dwarfTranslationUnitPath
;
137 const macho_section
<P
>* _dwarfDebugInfoSect
;
138 const macho_section
<P
>* _dwarfDebugAbbrevSect
;
139 const macho_section
<P
>* _dwarfDebugLineSect
;
140 const macho_section
<P
>* _dwarfDebugStringSect
;
141 ld::File::ObjcConstraint _objConstraint
;
142 uint8_t _swiftVersion
;
143 uint32_t _cpuSubType
;
144 uint32_t _minOSVersion
;
145 Options::Platform _platform
;
146 bool _canScatterAtoms
;
147 bool _objcHasCategoryClassPropertiesField
;
148 std::vector
<std::vector
<const char*> > _linkerOptions
;
149 std::unique_ptr
<ld::Bitcode
> _bitcode
;
151 ToolVersionList _toolVersions
;
155 template <typename A
>
156 class Section
: public ld::Section
159 typedef typename
A::P::uint_t pint_t
;
160 typedef typename
A::P P
;
161 typedef typename
A::P::E E
;
163 virtual ~Section() { }
164 class File
<A
>& file() const { return _file
; }
165 const macho_section
<P
>* machoSection() const { return _machOSection
; }
166 uint32_t sectionNum(class Parser
<A
>&) const;
167 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
);
168 virtual ld::Atom::ContentType
contentType() { return ld::Atom::typeUnclassified
; }
169 virtual bool dontDeadStrip() { return (this->_machOSection
->flags() & S_ATTR_NO_DEAD_STRIP
); }
170 virtual bool dontDeadStripIfReferencesLive() { return ( (this->_machOSection
!= NULL
) && (this->_machOSection
->flags() & S_ATTR_LIVE_SUPPORT
) ); }
171 virtual Atom
<A
>* findAtomByAddress(pint_t addr
) { return this->findContentAtomByAddress(addr
, this->_beginAtoms
, this->_endAtoms
); }
172 virtual bool addFollowOnFixups() const { return ! _file
.canScatterAtoms(); }
173 virtual uint32_t appendAtoms(class Parser
<A
>& parser
, uint8_t* buffer
,
174 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
175 const struct Parser
<A
>::CFI_CU_InfoArrays
&) = 0;
176 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
,
177 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
178 const struct Parser
<A
>::CFI_CU_InfoArrays
&) = 0;
179 virtual void makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
180 virtual bool addRelocFixup(class Parser
<A
>& parser
, const macho_relocation_info
<P
>*);
181 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const { return 0; }
182 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
183 const ld::IndirectBindingTable
& ind
) const { return false; }
184 virtual bool ignoreLabel(const char* label
) const { return false; }
185 static const char* makeSectionName(const macho_section
<typename
A::P
>* s
);
188 Section(File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
189 : ld::Section(makeSegmentName(s
), makeSectionName(s
), sectionType(s
)),
190 _file(f
), _machOSection(s
), _beginAtoms(NULL
), _endAtoms(NULL
), _hasAliases(false) { }
191 Section(File
<A
>& f
, const char* segName
, const char* sectName
, ld::Section::Type t
, bool hidden
=false)
192 : ld::Section(segName
, sectName
, t
, hidden
), _file(f
), _machOSection(NULL
),
193 _beginAtoms(NULL
), _endAtoms(NULL
), _hasAliases(false) { }
196 Atom
<A
>* findContentAtomByAddress(pint_t addr
, class Atom
<A
>* start
, class Atom
<A
>* end
);
197 uint32_t x86_64PcRelOffset(uint8_t r_type
);
198 void addLOH(class Parser
<A
>& parser
, int kind
, int count
, const uint64_t addrs
[]);
199 static const char* makeSegmentName(const macho_section
<typename
A::P
>* s
);
200 static bool readable(const macho_section
<typename
A::P
>* s
);
201 static bool writable(const macho_section
<typename
A::P
>* s
);
202 static bool exectuable(const macho_section
<typename
A::P
>* s
);
203 static ld::Section::Type
sectionType(const macho_section
<typename
A::P
>* s
);
206 const macho_section
<P
>* _machOSection
;
207 class Atom
<A
>* _beginAtoms
;
208 class Atom
<A
>* _endAtoms
;
210 std::set
<const class Atom
<A
>*> _altEntries
;
214 template <typename A
>
215 class CFISection
: public Section
<A
>
218 CFISection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
219 : Section
<A
>(f
, s
) { }
220 uint32_t cfiCount(Parser
<A
>& parser
);
222 virtual ld::Atom::ContentType
contentType() { return ld::Atom::typeCFI
; }
223 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
224 virtual uint32_t appendAtoms(class Parser
<A
>& parser
, uint8_t* buffer
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
225 virtual void makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
226 virtual bool addFollowOnFixups() const { return false; }
230 /// ObjectFileAddressSpace is used as a template parameter to UnwindCursor for parsing
231 /// dwarf CFI information in an object file.
236 typedef typename
A::P::uint_t pint_t
;
237 typedef typename
A::P P
;
238 typedef typename
A::P::E E
;
239 typedef typename
A::P::uint_t sint_t
;
241 OAS(CFISection
<A
>& ehFrameSection
, const uint8_t* ehFrameBuffer
) :
242 _ehFrameSection(ehFrameSection
),
243 _ehFrameContent(ehFrameBuffer
),
244 _ehFrameStartAddr(ehFrameSection
.machoSection()->addr()),
245 _ehFrameEndAddr(ehFrameSection
.machoSection()->addr()+ehFrameSection
.machoSection()->size()) {}
247 uint8_t get8(pint_t addr
) { return *((uint8_t*)mappedAddress(addr
)); }
248 uint16_t get16(pint_t addr
) { return E::get16(*((uint16_t*)mappedAddress(addr
))); }
249 uint32_t get32(pint_t addr
) { return E::get32(*((uint32_t*)mappedAddress(addr
))); }
250 uint64_t get64(pint_t addr
) { return E::get64(*((uint64_t*)mappedAddress(addr
))); }
251 pint_t
getP(pint_t addr
) { return P::getP(*((pint_t
*)mappedAddress(addr
))); }
252 uint64_t getULEB128(pint_t
& addr
, pint_t end
);
253 int64_t getSLEB128(pint_t
& addr
, pint_t end
);
254 pint_t
getEncodedP(pint_t
& addr
, pint_t end
, uint8_t encoding
);
256 const void* mappedAddress(pint_t addr
);
258 CFISection
<A
>& _ehFrameSection
;
259 const uint8_t* _ehFrameContent
;
260 pint_t _ehFrameStartAddr
;
261 pint_t _ehFrameEndAddr
;
265 typedef typename
A::P::uint_t pint_t
;
266 typedef libunwind::CFI_Atom_Info
<OAS
> CFI_Atom_Info
;
268 void cfiParse(class Parser
<A
>& parser
, uint8_t* buffer
, CFI_Atom_Info cfiArray
[], uint32_t& cfiCount
, const pint_t cuStarts
[], uint32_t cuCount
);
269 bool needsRelocating();
271 static bool bigEndian();
273 void addCiePersonalityFixups(class Parser
<A
>& parser
, const CFI_Atom_Info
* cieInfo
);
274 static void warnFunc(void* ref
, uint64_t funcAddr
, const char* msg
);
278 template <typename A
>
279 class CUSection
: public Section
<A
>
282 CUSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
283 : Section
<A
>(f
, s
) { }
285 typedef typename
A::P::uint_t pint_t
;
286 typedef typename
A::P P
;
287 typedef typename
A::P::E E
;
289 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, const struct Parser
<A
>::CFI_CU_InfoArrays
&) { return 0; }
290 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; }
291 virtual void makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
292 virtual bool addFollowOnFixups() const { return false; }
295 pint_t functionStartAddress
;
296 uint32_t functionSymbolIndex
;
297 uint32_t rangeLength
;
298 uint32_t compactUnwindInfo
;
299 const char* personality
;
306 void parse(class Parser
<A
>& parser
, uint32_t cnt
, Info array
[]);
307 static bool encodingMeansUseDwarf(compact_unwind_encoding_t enc
);
312 const char* personalityName(class Parser
<A
>& parser
, const macho_relocation_info
<P
>* reloc
);
314 static int infoSorter(const void* l
, const void* r
);
319 template <typename A
>
320 class TentativeDefinitionSection
: public Section
<A
>
323 TentativeDefinitionSection(Parser
<A
>& parser
, File
<A
>& f
)
324 : Section
<A
>(f
, "__DATA", "__comm/tent", ld::Section::typeTentativeDefs
) {}
326 virtual ld::Atom::ContentType
contentType() { return ld::Atom::typeZeroFill
; }
327 virtual bool addFollowOnFixups() const { return false; }
328 virtual Atom
<A
>* findAtomByAddress(typename
A::P::uint_t addr
) { throw "TentativeDefinitionSection::findAtomByAddress() should never be called"; }
329 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
330 const struct Parser
<A
>::CFI_CU_InfoArrays
&);
331 virtual uint32_t appendAtoms(class Parser
<A
>& parser
, uint8_t* buffer
,
332 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
333 const struct Parser
<A
>::CFI_CU_InfoArrays
&);
334 virtual void makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&) {}
336 typedef typename
A::P::uint_t pint_t
;
337 typedef typename
A::P P
;
341 template <typename A
>
342 class AbsoluteSymbolSection
: public Section
<A
>
345 AbsoluteSymbolSection(Parser
<A
>& parser
, File
<A
>& f
)
346 : Section
<A
>(f
, "__DATA", "__abs", ld::Section::typeAbsoluteSymbols
, true) {}
348 virtual ld::Atom::ContentType
contentType() { return ld::Atom::typeUnclassified
; }
349 virtual bool dontDeadStrip() { return false; }
350 virtual ld::Atom::Alignment
alignmentForAddress(typename
A::P::uint_t addr
) { return ld::Atom::Alignment(0); }
351 virtual bool addFollowOnFixups() const { return false; }
352 virtual Atom
<A
>* findAtomByAddress(typename
A::P::uint_t addr
) { throw "AbsoluteSymbolSection::findAtomByAddress() should never be called"; }
353 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
354 const struct Parser
<A
>::CFI_CU_InfoArrays
&);
355 virtual uint32_t appendAtoms(class Parser
<A
>& parser
, uint8_t* buffer
,
356 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
357 const struct Parser
<A
>::CFI_CU_InfoArrays
&);
358 virtual void makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&) {}
359 virtual Atom
<A
>* findAbsAtomForValue(typename
A::P::uint_t
);
362 typedef typename
A::P::uint_t pint_t
;
363 typedef typename
A::P P
;
367 template <typename A
>
368 class SymboledSection
: public Section
<A
>
371 SymboledSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
);
372 virtual ld::Atom::ContentType
contentType() { return _type
; }
373 virtual bool dontDeadStrip();
374 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
375 const struct Parser
<A
>::CFI_CU_InfoArrays
&);
376 virtual uint32_t appendAtoms(class Parser
<A
>& parser
, uint8_t* buffer
,
377 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
378 const struct Parser
<A
>::CFI_CU_InfoArrays
&);
380 typedef typename
A::P::uint_t pint_t
;
381 typedef typename
A::P P
;
383 ld::Atom::ContentType _type
;
387 template <typename A
>
388 class TLVDefsSection
: public SymboledSection
<A
>
391 TLVDefsSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
) :
392 SymboledSection
<A
>(parser
, f
, s
) { }
394 typedef typename
A::P::uint_t pint_t
;
396 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(log2(sizeof(pint_t
))); }
403 template <typename A
>
404 class ImplicitSizeSection
: public Section
<A
>
407 ImplicitSizeSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
408 : Section
<A
>(f
, s
) { }
409 virtual uint32_t computeAtomCount(class Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
410 virtual uint32_t appendAtoms(class Parser
<A
>& parser
, uint8_t* buffer
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
412 typedef typename
A::P::uint_t pint_t
;
413 typedef typename
A::P P
;
415 virtual bool addFollowOnFixups() const { return false; }
416 virtual const char* unlabeledAtomName(Parser
<A
>& parser
, pint_t addr
) = 0;
417 virtual ld::Atom::SymbolTableInclusion
symbolTableInclusion();
418 virtual pint_t
elementSizeAtAddress(pint_t addr
) = 0;
419 virtual ld::Atom::Scope
scopeAtAddress(Parser
<A
>& parser
, pint_t addr
) { return ld::Atom::scopeLinkageUnit
; }
420 virtual bool useElementAt(Parser
<A
>& parser
,
421 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, pint_t addr
) = 0;
422 virtual ld::Atom::Definition
definition() { return ld::Atom::definitionRegular
; }
423 virtual ld::Atom::Combine
combine(Parser
<A
>& parser
, pint_t addr
) = 0;
424 virtual bool ignoreLabel(const char* label
) const { return (label
[0] == 'L'); }
428 template <typename A
>
429 class FixedSizeSection
: public ImplicitSizeSection
<A
>
432 FixedSizeSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
433 : ImplicitSizeSection
<A
>(parser
, f
, s
) { }
435 typedef typename
A::P::uint_t pint_t
;
436 typedef typename
A::P P
;
437 typedef typename
A::P::E E
;
439 virtual bool useElementAt(Parser
<A
>& parser
,
440 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, pint_t addr
)
445 template <typename A
>
446 class Literal4Section
: public FixedSizeSection
<A
>
449 Literal4Section(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
450 : FixedSizeSection
<A
>(parser
, f
, s
) {}
452 typedef typename
A::P::uint_t pint_t
;
453 typedef typename
A::P P
;
455 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(2); }
456 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "4-byte-literal"; }
457 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return 4; }
458 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndContent
; }
459 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
460 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
461 const ld::IndirectBindingTable
& ind
) const;
462 virtual bool ignoreLabel(const char* label
) const;
465 template <typename A
>
466 class Literal8Section
: public FixedSizeSection
<A
>
469 Literal8Section(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
470 : FixedSizeSection
<A
>(parser
, f
, s
) {}
472 typedef typename
A::P::uint_t pint_t
;
473 typedef typename
A::P P
;
475 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(3); }
476 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "8-byte-literal"; }
477 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return 8; }
478 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndContent
; }
479 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
480 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
481 const ld::IndirectBindingTable
& ind
) const;
482 virtual bool ignoreLabel(const char* label
) const;
485 template <typename A
>
486 class Literal16Section
: public FixedSizeSection
<A
>
489 Literal16Section(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
490 : FixedSizeSection
<A
>(parser
, f
, s
) {}
492 typedef typename
A::P::uint_t pint_t
;
493 typedef typename
A::P P
;
495 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(4); }
496 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "16-byte-literal"; }
497 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return 16; }
498 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndContent
; }
499 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
500 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
501 const ld::IndirectBindingTable
& ind
) const;
502 virtual bool ignoreLabel(const char* label
) const;
506 template <typename A
>
507 class NonLazyPointerSection
: public FixedSizeSection
<A
>
510 NonLazyPointerSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
511 : FixedSizeSection
<A
>(parser
, f
, s
) {}
513 typedef typename
A::P::uint_t pint_t
;
514 typedef typename
A::P P
;
516 virtual void makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
517 virtual ld::Atom::ContentType
contentType() { return ld::Atom::typeNonLazyPointer
; }
518 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(log2(sizeof(pint_t
))); }
519 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "non_lazy_ptr"; }
520 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return sizeof(pint_t
); }
521 virtual ld::Atom::Scope
scopeAtAddress(Parser
<A
>& parser
, pint_t addr
);
522 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
);
523 virtual bool ignoreLabel(const char* label
) const { return true; }
524 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
525 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
526 const ld::IndirectBindingTable
& ind
) const;
529 static const char* targetName(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
);
530 static ld::Fixup::Kind
fixupKind();
533 template <typename A
>
534 class TLVPointerSection
: public FixedSizeSection
<A
>
537 TLVPointerSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
538 : FixedSizeSection
<A
>(parser
, f
, s
) {}
540 typedef typename
A::P::uint_t pint_t
;
541 typedef typename
A::P P
;
543 virtual void makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&);
544 virtual ld::Atom::ContentType
contentType() { return ld::Atom::typeTLVPointer
; }
545 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(log2(sizeof(pint_t
))); }
546 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "tlv_lazy_ptr"; }
547 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return sizeof(pint_t
); }
548 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
);
549 virtual bool ignoreLabel(const char* label
) const { return true; }
550 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
551 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
552 const ld::IndirectBindingTable
& ind
) const;
555 static const char* targetName(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
, bool* isStatic
);
559 template <typename A
>
560 class CFStringSection
: public FixedSizeSection
<A
>
563 CFStringSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
564 : FixedSizeSection
<A
>(parser
, f
, s
) {}
566 typedef typename
A::P::uint_t pint_t
;
568 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(log2(sizeof(pint_t
))); }
569 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "CFString"; }
570 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return 4*sizeof(pint_t
); }
571 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndReferences
; }
572 virtual bool ignoreLabel(const char* label
) const { return true; }
573 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
574 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
575 const ld::IndirectBindingTable
& ind
) const;
577 enum ContentType
{ contentUTF8
, contentUTF16
, contentUnknown
};
578 static const uint8_t* targetContent(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
,
579 ContentType
* ct
, unsigned int* count
);
583 template <typename A
>
584 class ObjC1ClassSection
: public FixedSizeSection
<A
>
587 ObjC1ClassSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
588 : FixedSizeSection
<A
>(parser
, f
, s
) {}
590 typedef typename
A::P::uint_t pint_t
;
591 typedef typename
A::P P
;
592 typedef typename
A::P::E E
;
594 virtual ld::Atom::Scope
scopeAtAddress(Parser
<A
>& , pint_t
) { return ld::Atom::scopeGlobal
; }
595 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(2); }
596 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
);
597 virtual ld::Atom::SymbolTableInclusion
symbolTableInclusion() { return ld::Atom::symbolTableIn
; }
598 virtual pint_t
elementSizeAtAddress(pint_t addr
);
599 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineNever
; }
600 virtual bool ignoreLabel(const char* label
) const { return true; }
601 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
603 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
604 const ld::IndirectBindingTable
& ind
) const { return false; }
605 virtual bool addRelocFixup(class Parser
<A
>& parser
, const macho_relocation_info
<P
>*);
609 template <typename A
>
610 class ObjC2ClassRefsSection
: public FixedSizeSection
<A
>
613 ObjC2ClassRefsSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
614 : FixedSizeSection
<A
>(parser
, f
, s
) {}
616 typedef typename
A::P::uint_t pint_t
;
618 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(log2(sizeof(pint_t
))); }
619 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "objc-class-ref"; }
620 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return sizeof(pint_t
); }
621 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndReferences
; }
622 virtual bool ignoreLabel(const char* label
) const { return true; }
623 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
624 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
625 const ld::IndirectBindingTable
& ind
) const;
627 const char* targetClassName(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
631 template <typename A
>
632 class ObjC2CategoryListSection
: public FixedSizeSection
<A
>
635 ObjC2CategoryListSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
636 : FixedSizeSection
<A
>(parser
, f
, s
) {}
638 typedef typename
A::P::uint_t pint_t
;
640 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(log2(sizeof(pint_t
))); }
641 virtual ld::Atom::Scope
scopeAtAddress(Parser
<A
>& parser
, pint_t addr
) { return ld::Atom::scopeTranslationUnit
; }
642 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "objc-cat-list"; }
643 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return sizeof(pint_t
); }
644 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineNever
; }
645 virtual bool ignoreLabel(const char* label
) const { return true; }
647 const char* targetClassName(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
651 template <typename A
>
652 class PointerToCStringSection
: public FixedSizeSection
<A
>
655 PointerToCStringSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
656 : FixedSizeSection
<A
>(parser
, f
, s
) {}
658 typedef typename
A::P::uint_t pint_t
;
660 virtual ld::Atom::Alignment
alignmentForAddress(pint_t addr
) { return ld::Atom::Alignment(log2(sizeof(pint_t
))); }
661 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "pointer-to-literal-cstring"; }
662 virtual pint_t
elementSizeAtAddress(pint_t addr
) { return sizeof(pint_t
); }
663 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndReferences
; }
664 virtual bool ignoreLabel(const char* label
) const { return true; }
665 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
666 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
667 const ld::IndirectBindingTable
& ind
) const;
668 virtual const char* targetCString(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
672 template <typename A
>
673 class Objc1ClassReferences
: public PointerToCStringSection
<A
>
676 Objc1ClassReferences(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
677 : PointerToCStringSection
<A
>(parser
, f
, s
) {}
679 typedef typename
A::P::uint_t pint_t
;
680 typedef typename
A::P P
;
682 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "pointer-to-literal-objc-class-name"; }
683 virtual bool addRelocFixup(class Parser
<A
>& parser
, const macho_relocation_info
<P
>*);
684 virtual const char* targetCString(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
688 template <typename A
>
689 class CStringSection
: public ImplicitSizeSection
<A
>
692 CStringSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
693 : ImplicitSizeSection
<A
>(parser
, f
, s
) {}
695 typedef typename
A::P::uint_t pint_t
;
696 typedef typename
A::P P
;
698 virtual ld::Atom::ContentType
contentType() { return ld::Atom::typeCString
; }
699 virtual Atom
<A
>* findAtomByAddress(pint_t addr
);
700 virtual const char* unlabeledAtomName(Parser
<A
>&, pint_t
) { return "cstring"; }
701 virtual pint_t
elementSizeAtAddress(pint_t addr
);
702 virtual bool ignoreLabel(const char* label
) const;
703 virtual bool useElementAt(Parser
<A
>& parser
,
704 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, pint_t addr
);
705 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndContent
; }
706 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
707 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
708 const ld::IndirectBindingTable
& ind
) const;
713 template <typename A
>
714 class UTF16StringSection
: public SymboledSection
<A
>
717 UTF16StringSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
718 : SymboledSection
<A
>(parser
, f
, s
) {}
720 typedef typename
A::P::uint_t pint_t
;
721 typedef typename
A::P P
;
723 virtual ld::Atom::Combine
combine(Parser
<A
>&, pint_t
) { return ld::Atom::combineByNameAndContent
; }
724 virtual unsigned long contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const;
725 virtual bool canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
726 const ld::IndirectBindingTable
& ind
) const;
731 // Atoms in mach-o files
733 template <typename A
>
734 class Atom
: public ld::Atom
737 // overrides of ld::Atom
738 virtual const ld::File
* file() const;
739 virtual const char* translationUnitSource() const
740 { return sect().file().translationUnitSource(); }
741 virtual const char* name() const { return _name
; }
742 virtual uint64_t size() const { return _size
; }
743 virtual uint64_t objectAddress() const { return _objAddress
; }
744 virtual void copyRawContent(uint8_t buffer
[]) const;
745 virtual const uint8_t* rawContentPointer() const { return contentPointer(); }
746 virtual unsigned long contentHash(const ld::IndirectBindingTable
& ind
) const
747 { if ( _hash
== 0 ) _hash
= sect().contentHash(this, ind
); return _hash
; }
748 virtual bool canCoalesceWith(const ld::Atom
& rhs
, const ld::IndirectBindingTable
& ind
) const
749 { return sect().canCoalesceWith(this, rhs
, ind
); }
750 virtual ld::Fixup::iterator
fixupsBegin() const { return &machofile()._fixups
[_fixupsStartIndex
]; }
751 virtual ld::Fixup::iterator
fixupsEnd() const { return &machofile()._fixups
[_fixupsStartIndex
+_fixupsCount
]; }
752 virtual ld::Atom::UnwindInfo::iterator
beginUnwind() const { return &machofile()._unwindInfos
[_unwindInfoStartIndex
]; }
753 virtual ld::Atom::UnwindInfo::iterator
endUnwind() const { return &machofile()._unwindInfos
[_unwindInfoStartIndex
+_unwindInfoCount
]; }
754 virtual ld::Atom::LineInfo::iterator
beginLineInfo() const{ return &machofile()._lineInfos
[_lineInfoStartIndex
]; }
755 virtual ld::Atom::LineInfo::iterator
endLineInfo() const { return &machofile()._lineInfos
[_lineInfoStartIndex
+_lineInfoCount
]; }
756 virtual void setFile(const ld::File
* f
);
760 enum { kFixupStartIndexBits
= 32,
761 kLineInfoStartIndexBits
= 32,
762 kUnwindInfoStartIndexBits
= 24,
763 kFixupCountBits
= 24,
764 kLineInfoCountBits
= 12,
765 kUnwindInfoCountBits
= 4
766 }; // must sum to 128
769 // methods for all atoms from mach-o object file
770 Section
<A
>& sect() const { return (Section
<A
>&)section(); }
771 File
<A
>& machofile() const { return ((Section
<A
>*)(this->_section
))->file(); }
772 void setFixupsRange(uint32_t s
, uint32_t c
);
773 void setUnwindInfoRange(uint32_t s
, uint32_t c
);
774 void extendUnwindInfoRange();
775 void setLineInfoRange(uint32_t s
, uint32_t c
);
776 bool roomForMoreLineInfoCount() { return (_lineInfoCount
< ((1<<kLineInfoCountBits
)-1)); }
777 void incrementLineInfoCount() { assert(roomForMoreLineInfoCount()); ++_lineInfoCount
; }
778 void incrementFixupCount() { if (_fixupsCount
== ((1 << kFixupCountBits
)-1))
779 throwf("too may fixups in %s", name()); ++_fixupsCount
; }
780 const uint8_t* contentPointer() const;
781 uint32_t fixupCount() const { return _fixupsCount
; }
782 void verifyAlignment(const macho_section
<typename
A::P
>&) const;
784 typedef typename
A::P P
;
785 typedef typename
A::P::E E
;
786 typedef typename
A::P::uint_t pint_t
;
787 // constuct via all attributes
788 Atom(Section
<A
>& sct
, const char* nm
, pint_t addr
, uint64_t sz
,
789 ld::Atom::Definition d
, ld::Atom::Combine c
, ld::Atom::Scope s
,
790 ld::Atom::ContentType ct
, ld::Atom::SymbolTableInclusion i
,
791 bool dds
, bool thumb
, bool al
, ld::Atom::Alignment a
)
792 : ld::Atom((ld::Section
&)sct
, d
, c
, s
, ct
, i
, dds
, thumb
, al
, a
),
793 _size(sz
), _objAddress(addr
), _name(nm
), _hash(0),
794 _fixupsStartIndex(0), _lineInfoStartIndex(0),
795 _unwindInfoStartIndex(0), _fixupsCount(0),
796 _lineInfoCount(0), _unwindInfoCount(0) { }
797 // construct via symbol table entry
798 Atom(Section
<A
>& sct
, Parser
<A
>& parser
, const macho_nlist
<P
>& sym
,
799 uint64_t sz
, bool alias
=false)
800 : ld::Atom((ld::Section
&)sct
, parser
.definitionFromSymbol(sym
),
801 parser
.combineFromSymbol(sym
), parser
.scopeFromSymbol(sym
),
802 parser
.resolverFromSymbol(sym
) ? ld::Atom::typeResolver
: sct
.contentType(),
803 parser
.inclusionFromSymbol(sym
),
804 (parser
.dontDeadStripFromSymbol(sym
) && !sct
.dontDeadStripIfReferencesLive()) || sct
.dontDeadStrip(),
805 parser
.isThumbFromSymbol(sym
), alias
,
806 sct
.alignmentForAddress(sym
.n_value())),
807 _size(sz
), _objAddress(sym
.n_value()),
808 _name(parser
.nameFromSymbol(sym
)), _hash(0),
809 _fixupsStartIndex(0), _lineInfoStartIndex(0),
810 _unwindInfoStartIndex(0), _fixupsCount(0),
811 _lineInfoCount(0), _unwindInfoCount(0) {
812 // <rdar://problem/6783167> support auto-hidden weak symbols
813 if ( _scope
== ld::Atom::scopeGlobal
&&
814 (sym
.n_desc() & (N_WEAK_DEF
|N_WEAK_REF
)) == (N_WEAK_DEF
|N_WEAK_REF
) )
816 this->verifyAlignment(*sct
.machoSection());
817 if ( sct
.dontDeadStripIfReferencesLive() )
818 this->setDontDeadStripIfReferencesLive();
822 friend class Parser
<A
>;
823 friend class Section
<A
>;
824 friend class CStringSection
<A
>;
825 friend class AbsoluteSymbolSection
<A
>;
830 mutable unsigned long _hash
;
832 uint64_t _fixupsStartIndex
: kFixupStartIndexBits
,
833 _lineInfoStartIndex
: kLineInfoStartIndexBits
,
834 _unwindInfoStartIndex
: kUnwindInfoStartIndexBits
,
835 _fixupsCount
: kFixupCountBits
,
836 _lineInfoCount
: kLineInfoCountBits
,
837 _unwindInfoCount
: kUnwindInfoCountBits
;
839 static std::map
<const ld::Atom
*, const ld::File
*> _s_fileOverride
;
842 template <typename A
>
843 std::map
<const ld::Atom
*, const ld::File
*> Atom
<A
>::_s_fileOverride
;
845 template <typename A
>
846 void Atom
<A
>::setFile(const ld::File
* f
) {
847 _s_fileOverride
[this] = f
;
850 template <typename A
>
851 const ld::File
* Atom
<A
>::file() const
853 std::map
<const ld::Atom
*, const ld::File
*>::iterator pos
= _s_fileOverride
.find(this);
854 if ( pos
!= _s_fileOverride
.end() )
857 return §().file();
860 template <typename A
>
861 void Atom
<A
>::setFixupsRange(uint32_t startIndex
, uint32_t count
)
863 if ( count
>= (1 << kFixupCountBits
) )
864 throwf("too many fixups in function %s", this->name());
865 if ( startIndex
>= (1 << kFixupStartIndexBits
) )
866 throwf("too many fixups in file");
867 assert(((startIndex
+count
) <= sect().file()._fixups
.size()) && "fixup index out of range");
868 _fixupsStartIndex
= startIndex
;
869 _fixupsCount
= count
;
872 template <typename A
>
873 void Atom
<A
>::setUnwindInfoRange(uint32_t startIndex
, uint32_t count
)
875 if ( count
>= (1 << kUnwindInfoCountBits
) )
876 throwf("too many compact unwind infos in function %s", this->name());
877 if ( startIndex
>= (1 << kUnwindInfoStartIndexBits
) )
878 throwf("too many compact unwind infos (%d) in file", startIndex
);
879 assert((startIndex
+count
) <= sect().file()._unwindInfos
.size() && "unwindinfo index out of range");
880 _unwindInfoStartIndex
= startIndex
;
881 _unwindInfoCount
= count
;
884 template <typename A
>
885 void Atom
<A
>::extendUnwindInfoRange()
887 if ( _unwindInfoCount
+1 >= (1 << kUnwindInfoCountBits
) )
888 throwf("too many compact unwind infos in function %s", this->name());
889 _unwindInfoCount
+= 1;
892 template <typename A
>
893 void Atom
<A
>::setLineInfoRange(uint32_t startIndex
, uint32_t count
)
895 assert((count
< (1 << kLineInfoCountBits
)) && "too many line infos");
896 assert((startIndex
+count
) < sect().file()._lineInfos
.size() && "line info index out of range");
897 _lineInfoStartIndex
= startIndex
;
898 _lineInfoCount
= count
;
901 template <typename A
>
902 const uint8_t* Atom
<A
>::contentPointer() const
904 const macho_section
<P
>* sct
= this->sect().machoSection();
905 if ( this->_objAddress
> sct
->addr() + sct
->size() )
906 throwf("malformed .o file, symbol has address 0x%0llX which is outside range of its section", (uint64_t)this->_objAddress
);
907 uint32_t fileOffset
= sct
->offset() - sct
->addr() + this->_objAddress
;
908 return this->sect().file().fileContent()+fileOffset
;
912 template <typename A
>
913 void Atom
<A
>::copyRawContent(uint8_t buffer
[]) const
916 if ( this->contentType() == ld::Atom::typeZeroFill
) {
917 bzero(buffer
, _size
);
919 else if ( _size
!= 0 ) {
920 memcpy(buffer
, this->contentPointer(), _size
);
925 void Atom
<arm
>::verifyAlignment(const macho_section
<P
>&) const
927 if ( (this->section().type() == ld::Section::typeCode
) && ! isThumb() ) {
928 if ( ((_objAddress
% 4) != 0) || (this->alignment().powerOf2
< 2) )
929 warning("ARM function not 4-byte aligned: %s from %s", this->name(), this->file()->path());
933 #if SUPPORT_ARCH_arm64
935 void Atom
<arm64
>::verifyAlignment(const macho_section
<P
>& sect
) const
937 if ( (this->section().type() == ld::Section::typeCode
) && (sect
.size() != 0) ) {
938 if ( ((_objAddress
% 4) != 0) || (this->alignment().powerOf2
< 2) )
939 warning("arm64 function not 4-byte aligned: %s from %s", this->name(), this->file()->path());
945 template <typename A
>
946 void Atom
<A
>::verifyAlignment(const macho_section
<P
>&) const
951 class AliasAtom
: public ld::Atom
954 AliasAtom(const char* name
, bool hidden
, const ld::File
* file
, const char* aliasOfName
) :
955 ld::Atom(_s_section
, ld::Atom::definitionRegular
, ld::Atom::combineNever
,
956 (hidden
? ld::Atom::scopeLinkageUnit
: ld::Atom::scopeGlobal
),
957 ld::Atom::typeUnclassified
, ld::Atom::symbolTableIn
,
958 false, false, true, 0),
961 _fixup(0, ld::Fixup::k1of1
, ld::Fixup::kindNoneFollowOn
, ld::Fixup::bindingByNameUnbound
, aliasOfName
) { }
963 virtual const ld::File
* file() const { return _file
; }
964 virtual const char* translationUnitSource() const
966 virtual const char* name() const { return _name
; }
967 virtual uint64_t size() const { return 0; }
968 virtual uint64_t objectAddress() const { return 0; }
969 virtual void copyRawContent(uint8_t buffer
[]) const { }
970 virtual ld::Fixup::iterator
fixupsBegin() const { return &((ld::Fixup
*)&_fixup
)[0]; }
971 virtual ld::Fixup::iterator
fixupsEnd() const { return &((ld::Fixup
*)&_fixup
)[1]; }
974 static ld::Section _s_section
;
976 const ld::File
* _file
;
981 ld::Section
AliasAtom::_s_section("__LD", "__aliases", ld::Section::typeTempAlias
, true);
984 template <typename A
>
988 static bool validFile(const uint8_t* fileContent
, bool subtypeMustMatch
=false,
989 cpu_subtype_t subtype
=0);
990 static const char* fileKind(const uint8_t* fileContent
);
991 static Options::Platform
findPlatform(const macho_header
<typename
A::P
>* header
);
992 static bool hasObjC2Categories(const uint8_t* fileContent
);
993 static bool hasObjC1Categories(const uint8_t* fileContent
);
994 static bool getNonLocalSymbols(const uint8_t* fileContnet
, std::vector
<const char*> &syms
);
995 static ld::relocatable::File
* parse(const uint8_t* fileContent
, uint64_t fileLength
,
996 const char* path
, time_t modTime
, ld::File::Ordinal ordinal
,
997 const ParserOptions
& opts
) {
998 Parser
p(fileContent
, fileLength
, path
, modTime
,
999 ordinal
, opts
.warnUnwindConversionProblems
,
1000 opts
.keepDwarfUnwind
, opts
.forceDwarfConversion
,
1001 opts
.neverConvertDwarf
, opts
.verboseOptimizationHints
,
1002 opts
.ignoreMismatchPlatform
);
1003 return p
.parse(opts
);
1006 typedef typename
A::P P
;
1007 typedef typename
A::P::E E
;
1008 typedef typename
A::P::uint_t pint_t
;
1010 struct SourceLocation
{
1012 SourceLocation(Atom
<A
>* a
, uint32_t o
) : atom(a
), offsetInAtom(o
) {}
1014 uint32_t offsetInAtom
;
1019 const char* name
; // only used if targetAtom is NULL
1021 bool weakImport
; // only used if targetAtom is NULL
1024 struct FixupInAtom
{
1025 FixupInAtom(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, Atom
<A
>* target
) :
1026 fixup(src
.offsetInAtom
, c
, k
, target
), atom(src
.atom
) { src
.atom
->incrementFixupCount(); }
1028 FixupInAtom(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, ld::Fixup::TargetBinding b
, Atom
<A
>* target
) :
1029 fixup(src
.offsetInAtom
, c
, k
, b
, target
), atom(src
.atom
) { src
.atom
->incrementFixupCount(); }
1031 FixupInAtom(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, bool wi
, const char* name
) :
1032 fixup(src
.offsetInAtom
, c
, k
, wi
, name
), atom(src
.atom
) { src
.atom
->incrementFixupCount(); }
1034 FixupInAtom(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, ld::Fixup::TargetBinding b
, const char* name
) :
1035 fixup(src
.offsetInAtom
, c
, k
, b
, name
), atom(src
.atom
) { src
.atom
->incrementFixupCount(); }
1037 FixupInAtom(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, uint64_t addend
) :
1038 fixup(src
.offsetInAtom
, c
, k
, addend
), atom(src
.atom
) { src
.atom
->incrementFixupCount(); }
1040 FixupInAtom(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
) :
1041 fixup(src
.offsetInAtom
, c
, k
, (uint64_t)0), atom(src
.atom
) { src
.atom
->incrementFixupCount(); }
1047 void addFixup(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, Atom
<A
>* target
) {
1048 _allFixups
.push_back(FixupInAtom(src
, c
, k
, target
));
1051 void addFixup(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, ld::Fixup::TargetBinding b
, Atom
<A
>* target
) {
1052 _allFixups
.push_back(FixupInAtom(src
, c
, k
, b
, target
));
1055 void addFixup(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, bool wi
, const char* name
) {
1056 _allFixups
.push_back(FixupInAtom(src
, c
, k
, wi
, name
));
1059 void addFixup(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, ld::Fixup::TargetBinding b
, const char* name
) {
1060 _allFixups
.push_back(FixupInAtom(src
, c
, k
, b
, name
));
1063 void addFixup(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
, uint64_t addend
) {
1064 _allFixups
.push_back(FixupInAtom(src
, c
, k
, addend
));
1067 void addFixup(const SourceLocation
& src
, ld::Fixup::Cluster c
, ld::Fixup::Kind k
) {
1068 _allFixups
.push_back(FixupInAtom(src
, c
, k
));
1071 const char* path() { return _path
; }
1072 uint32_t symbolCount() { return _symbolCount
; }
1073 uint32_t indirectSymbol(uint32_t indirectIndex
);
1074 const macho_nlist
<P
>& symbolFromIndex(uint32_t index
);
1075 const char* nameFromSymbol(const macho_nlist
<P
>& sym
);
1076 ld::Atom::Scope
scopeFromSymbol(const macho_nlist
<P
>& sym
);
1077 static ld::Atom::Definition
definitionFromSymbol(const macho_nlist
<P
>& sym
);
1078 static ld::Atom::Combine
combineFromSymbol(const macho_nlist
<P
>& sym
);
1079 ld::Atom::SymbolTableInclusion
inclusionFromSymbol(const macho_nlist
<P
>& sym
);
1080 static bool dontDeadStripFromSymbol(const macho_nlist
<P
>& sym
);
1081 static bool isThumbFromSymbol(const macho_nlist
<P
>& sym
);
1082 static bool weakImportFromSymbol(const macho_nlist
<P
>& sym
);
1083 static bool resolverFromSymbol(const macho_nlist
<P
>& sym
);
1084 static bool altEntryFromSymbol(const macho_nlist
<P
>& sym
);
1085 uint32_t symbolIndexFromIndirectSectionAddress(pint_t
,const macho_section
<P
>*);
1086 const macho_section
<P
>* firstMachOSection() { return _sectionsStart
; }
1087 const macho_section
<P
>* machOSectionFromSectionIndex(uint32_t index
);
1088 uint32_t machOSectionCount() { return _machOSectionsCount
; }
1089 uint32_t undefinedStartIndex() { return _undefinedStartIndex
; }
1090 uint32_t undefinedEndIndex() { return _undefinedEndIndex
; }
1091 void addFixup(FixupInAtom f
) { _allFixups
.push_back(f
); }
1092 Section
<A
>* sectionForNum(unsigned int sectNum
);
1093 Section
<A
>* sectionForAddress(pint_t addr
);
1094 Atom
<A
>* findAtomByAddress(pint_t addr
);
1095 Atom
<A
>* findAtomByAddressOrNullIfStub(pint_t addr
);
1096 Atom
<A
>* findAtomByAddressOrLocalTargetOfStub(pint_t addr
, uint32_t* offsetInAtom
);
1097 Atom
<A
>* findAtomByName(const char* name
); // slow!
1098 void findTargetFromAddress(pint_t addr
, TargetDesc
& target
);
1099 void findTargetFromAddress(pint_t baseAddr
, pint_t addr
, TargetDesc
& target
);
1100 void findTargetFromAddressAndSectionNum(pint_t addr
, unsigned int sectNum
,
1101 TargetDesc
& target
);
1102 uint32_t tentativeDefinitionCount() { return _tentativeDefinitionCount
; }
1103 uint32_t absoluteSymbolCount() { return _absoluteSymbolCount
; }
1105 uint32_t fileLength() const { return _fileLength
; }
1106 bool hasStubsSection() { return (_stubsSectionNum
!= 0); }
1107 unsigned int stubsSectionNum() { return _stubsSectionNum
; }
1108 void addDtraceExtraInfos(const SourceLocation
& src
, const char* provider
);
1109 const char* scanSymbolTableForAddress(uint64_t addr
);
1110 bool warnUnwindConversionProblems() { return _warnUnwindConversionProblems
; }
1111 bool hasDataInCodeLabels() { return _hasDataInCodeLabels
; }
1112 bool keepDwarfUnwind() { return _keepDwarfUnwind
; }
1113 bool forceDwarfConversion() { return _forceDwarfConversion
; }
1114 bool verboseOptimizationHints() { return _verboseOptimizationHints
; }
1115 bool neverConvertDwarf() { return _neverConvertDwarf
; }
1116 bool armUsesZeroCostExceptions() { return _armUsesZeroCostExceptions
; }
1117 uint8_t maxDefaultCommonAlignment() { return _maxDefaultCommonAlignment
; }
1120 macho_data_in_code_entry
<P
>* dataInCodeStart() { return _dataInCodeStart
; }
1121 macho_data_in_code_entry
<P
>* dataInCodeEnd() { return _dataInCodeEnd
; }
1122 const uint8_t* optimizationHintsStart() { return _lohStart
; }
1123 const uint8_t* optimizationHintsEnd() { return _lohEnd
; }
1124 bool hasOptimizationHints() { return _lohStart
!= _lohEnd
; }
1127 void addFixups(const SourceLocation
& src
, ld::Fixup::Kind kind
, const TargetDesc
& target
);
1128 void addFixups(const SourceLocation
& src
, ld::Fixup::Kind kind
, const TargetDesc
& target
, const TargetDesc
& picBase
);
1132 struct LabelAndCFIBreakIterator
{
1133 typedef typename CFISection
<A
>::CFI_Atom_Info CFI_Atom_Info
;
1134 LabelAndCFIBreakIterator(const uint32_t* ssa
, uint32_t ssc
, const pint_t
* cfisa
,
1135 uint32_t cfisc
, bool ols
)
1136 : sortedSymbolIndexes(ssa
), sortedSymbolCount(ssc
), cfiStartsArray(cfisa
),
1137 cfiStartsCount(cfisc
), fileHasOverlappingSymbols(ols
),
1138 newSection(false), cfiIndex(0), symIndex(0) {}
1139 bool next(Parser
<A
>& parser
, const Section
<A
>& sect
, uint32_t sectNum
, pint_t startAddr
, pint_t endAddr
,
1140 pint_t
* addr
, pint_t
* size
, const macho_nlist
<P
>** sym
);
1141 pint_t
peek(Parser
<A
>& parser
, pint_t startAddr
, pint_t endAddr
);
1142 void beginSection() { newSection
= true; symIndex
= 0; }
1144 const uint32_t* const sortedSymbolIndexes
;
1145 const uint32_t sortedSymbolCount
;
1146 const pint_t
* cfiStartsArray
;
1147 const uint32_t cfiStartsCount
;
1148 const bool fileHasOverlappingSymbols
;
1154 struct CFI_CU_InfoArrays
{
1155 typedef typename CFISection
<A
>::CFI_Atom_Info CFI_Atom_Info
;
1156 typedef typename CUSection
<A
>::Info CU_Info
;
1157 CFI_CU_InfoArrays(const CFI_Atom_Info
* cfiAr
, uint32_t cfiC
, CU_Info
* cuAr
, uint32_t cuC
)
1158 : cfiArray(cfiAr
), cuArray(cuAr
), cfiCount(cfiC
), cuCount(cuC
) {}
1159 const CFI_Atom_Info
* const cfiArray
;
1160 CU_Info
* const cuArray
;
1161 const uint32_t cfiCount
;
1162 const uint32_t cuCount
;
1168 friend class Section
<A
>;
1170 enum SectionType
{ sectionTypeIgnore
, sectionTypeLiteral4
, sectionTypeLiteral8
, sectionTypeLiteral16
,
1171 sectionTypeNonLazy
, sectionTypeCFI
, sectionTypeCString
, sectionTypeCStringPointer
,
1172 sectionTypeUTF16Strings
, sectionTypeCFString
, sectionTypeObjC2ClassRefs
, typeObjC2CategoryList
,
1173 sectionTypeObjC1Classes
, sectionTypeSymboled
, sectionTypeObjC1ClassRefs
,
1174 sectionTypeTentativeDefinitions
, sectionTypeAbsoluteSymbols
, sectionTypeTLVDefs
,
1175 sectionTypeCompactUnwind
, sectionTypeTLVPointers
};
1177 template <typename P
>
1178 struct MachOSectionAndSectionClass
1180 const macho_section
<P
>* sect
;
1183 static int sorter(const void* l
, const void* r
) {
1184 const MachOSectionAndSectionClass
<P
>* left
= (MachOSectionAndSectionClass
<P
>*)l
;
1185 const MachOSectionAndSectionClass
<P
>* right
= (MachOSectionAndSectionClass
<P
>*)r
;
1186 int64_t diff
= left
->sect
->addr() - right
->sect
->addr();
1196 struct ParserAndSectionsArray
{ Parser
* parser
; const uint32_t* sortedSectionsArray
; };
1199 Parser(const uint8_t* fileContent
, uint64_t fileLength
,
1200 const char* path
, time_t modTime
, ld::File::Ordinal ordinal
,
1201 bool warnUnwindConversionProblems
, bool keepDwarfUnwind
,
1202 bool forceDwarfConversion
, bool neverConvertDwarf
,
1203 bool verboseOptimizationHints
, bool ignoreMismatchPlatform
);
1204 ld::relocatable::File
* parse(const ParserOptions
& opts
);
1205 static uint8_t loadCommandSizeMask();
1206 bool parseLoadCommands(Options::Platform platform
, uint32_t minOSVersion
, bool simulator
, bool ignoreMismatchPlatform
);
1207 void makeSections();
1208 void prescanSymbolTable();
1209 void makeSortedSymbolsArray(uint32_t symArray
[], const uint32_t sectionArray
[]);
1210 void makeSortedSectionsArray(uint32_t array
[]);
1211 static int pointerSorter(const void* l
, const void* r
);
1212 static int symbolIndexSorter(void* extra
, const void* l
, const void* r
);
1213 static int sectionIndexSorter(void* extra
, const void* l
, const void* r
);
1215 void parseDebugInfo();
1217 void appendAliasAtoms(uint8_t* atomBuffer
);
1218 static bool isConstFunStabs(const char *stabStr
);
1219 bool read_comp_unit(const char ** name
, const char ** comp_dir
,
1220 uint64_t *stmt_list
);
1221 pint_t
realAddr(pint_t addr
);
1222 const char* getDwarfString(uint64_t form
, const uint8_t*& p
);
1223 uint64_t getDwarfOffset(uint64_t form
, const uint8_t*& di
, bool dwarf64
);
1224 bool skip_form(const uint8_t ** offset
, const uint8_t * end
,
1225 uint64_t form
, uint8_t addr_size
, bool dwarf64
);
1228 // filled in by constructor
1229 const uint8_t* _fileContent
;
1230 uint32_t _fileLength
;
1233 ld::File::Ordinal _ordinal
;
1235 // filled in by parseLoadCommands()
1237 const macho_nlist
<P
>* _symbols
;
1238 uint32_t _symbolCount
;
1239 uint32_t _indirectSymbolCount
;
1240 const char* _strings
;
1241 uint32_t _stringsSize
;
1242 const uint32_t* _indirectTable
;
1243 uint32_t _indirectTableCount
;
1244 uint32_t _undefinedStartIndex
;
1245 uint32_t _undefinedEndIndex
;
1246 const macho_section
<P
>* _sectionsStart
;
1247 uint32_t _machOSectionsCount
;
1249 macho_data_in_code_entry
<P
>* _dataInCodeStart
;
1250 macho_data_in_code_entry
<P
>* _dataInCodeEnd
;
1251 const uint8_t* _lohStart
;
1252 const uint8_t* _lohEnd
;
1254 // filled in by parse()
1255 CFISection
<A
>* _EHFrameSection
;
1256 CUSection
<A
>* _compactUnwindSection
;
1257 AbsoluteSymbolSection
<A
>* _absoluteSection
;
1258 uint32_t _tentativeDefinitionCount
;
1259 uint32_t _absoluteSymbolCount
;
1260 uint32_t _symbolsInSections
;
1261 bool _hasLongBranchStubs
;
1262 bool _AppleObjc
; // FSF has objc that uses different data layout
1263 bool _overlappingSymbols
;
1264 bool _warnUnwindConversionProblems
;
1265 bool _hasDataInCodeLabels
;
1266 bool _keepDwarfUnwind
;
1267 bool _forceDwarfConversion
;
1268 bool _neverConvertDwarf
;
1269 bool _verboseOptimizationHints
;
1270 bool _armUsesZeroCostExceptions
;
1271 bool _ignoreMismatchPlatform
;
1272 bool _treateBitcodeAsData
;
1274 uint8_t _maxDefaultCommonAlignment
;
1275 unsigned int _stubsSectionNum
;
1276 const macho_section
<P
>* _stubsMachOSection
;
1277 std::vector
<const char*> _dtraceProviderInfo
;
1278 std::vector
<FixupInAtom
> _allFixups
;
1283 template <typename A
>
1284 Parser
<A
>::Parser(const uint8_t* fileContent
, uint64_t fileLength
, const char* path
, time_t modTime
,
1285 ld::File::Ordinal ordinal
, bool convertDUI
, bool keepDwarfUnwind
, bool forceDwarfConversion
,
1286 bool neverConvertDwarf
, bool verboseOptimizationHints
, bool ignoreMismatchPlatform
)
1287 : _fileContent(fileContent
), _fileLength(fileLength
), _path(path
), _modTime(modTime
),
1288 _ordinal(ordinal
), _file(NULL
),
1289 _symbols(NULL
), _symbolCount(0), _indirectSymbolCount(0), _strings(NULL
), _stringsSize(0),
1290 _indirectTable(NULL
), _indirectTableCount(0),
1291 _undefinedStartIndex(0), _undefinedEndIndex(0),
1292 _sectionsStart(NULL
), _machOSectionsCount(0), _hasUUID(false),
1293 _dataInCodeStart(NULL
), _dataInCodeEnd(NULL
),
1294 _lohStart(NULL
), _lohEnd(NULL
),
1295 _EHFrameSection(NULL
), _compactUnwindSection(NULL
), _absoluteSection(NULL
),
1296 _tentativeDefinitionCount(0), _absoluteSymbolCount(0),
1297 _symbolsInSections(0), _hasLongBranchStubs(false), _AppleObjc(false),
1298 _overlappingSymbols(false), _warnUnwindConversionProblems(convertDUI
), _hasDataInCodeLabels(false),
1299 _keepDwarfUnwind(keepDwarfUnwind
), _forceDwarfConversion(forceDwarfConversion
),
1300 _neverConvertDwarf(neverConvertDwarf
),
1301 _verboseOptimizationHints(verboseOptimizationHints
),
1302 _ignoreMismatchPlatform(ignoreMismatchPlatform
),
1303 _stubsSectionNum(0), _stubsMachOSection(NULL
)
1309 bool Parser
<x86
>::validFile(const uint8_t* fileContent
, bool, cpu_subtype_t
)
1311 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1312 if ( header
->magic() != MH_MAGIC
)
1314 if ( header
->cputype() != CPU_TYPE_I386
)
1316 if ( header
->filetype() != MH_OBJECT
)
1322 bool Parser
<x86_64
>::validFile(const uint8_t* fileContent
, bool, cpu_subtype_t
)
1324 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1325 if ( header
->magic() != MH_MAGIC_64
)
1327 if ( header
->cputype() != CPU_TYPE_X86_64
)
1329 if ( header
->filetype() != MH_OBJECT
)
1335 bool Parser
<arm
>::validFile(const uint8_t* fileContent
, bool subtypeMustMatch
, cpu_subtype_t subtype
)
1337 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1338 if ( header
->magic() != MH_MAGIC
)
1340 if ( header
->cputype() != CPU_TYPE_ARM
)
1342 if ( header
->filetype() != MH_OBJECT
)
1344 if ( subtypeMustMatch
) {
1345 if ( (cpu_subtype_t
)header
->cpusubtype() == subtype
)
1347 // hack until libcc_kext.a is made fat
1348 if ( header
->cpusubtype() == CPU_SUBTYPE_ARM_ALL
)
1357 bool Parser
<arm64
>::validFile(const uint8_t* fileContent
, bool subtypeMustMatch
, cpu_subtype_t subtype
)
1359 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1360 if ( header
->magic() != MH_MAGIC_64
)
1362 if ( header
->cputype() != CPU_TYPE_ARM64
)
1364 if ( header
->filetype() != MH_OBJECT
)
1371 const char* Parser
<x86
>::fileKind(const uint8_t* fileContent
)
1373 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1374 if ( header
->magic() != MH_MAGIC
)
1376 if ( header
->cputype() != CPU_TYPE_I386
)
1382 const char* Parser
<x86_64
>::fileKind(const uint8_t* fileContent
)
1384 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1385 if ( header
->magic() != MH_MAGIC_64
)
1387 if ( header
->cputype() != CPU_TYPE_X86_64
)
1393 const char* Parser
<arm
>::fileKind(const uint8_t* fileContent
)
1395 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1396 if ( header
->magic() != MH_MAGIC
)
1398 if ( header
->cputype() != CPU_TYPE_ARM
)
1400 for (const ArchInfo
* t
=archInfoArray
; t
->archName
!= NULL
; ++t
) {
1401 if ( (t
->cpuType
== CPU_TYPE_ARM
) && ((cpu_subtype_t
)header
->cpusubtype() == t
->cpuSubType
) ) {
1408 #if SUPPORT_ARCH_arm64
1410 const char* Parser
<arm64
>::fileKind(const uint8_t* fileContent
)
1412 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1413 if ( header
->magic() != MH_MAGIC_64
)
1415 if ( header
->cputype() != CPU_TYPE_ARM64
)
1422 template <typename A
>
1423 bool Parser
<A
>::hasObjC2Categories(const uint8_t* fileContent
)
1425 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1426 const uint32_t cmd_count
= header
->ncmds();
1427 const macho_load_command
<P
>* const cmds
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>));
1428 const macho_load_command
<P
>* const cmdsEnd
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>) + header
->sizeofcmds());
1429 const macho_load_command
<P
>* cmd
= cmds
;
1430 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1431 if ( cmd
->cmd() == macho_segment_command
<P
>::CMD
) {
1432 const macho_segment_command
<P
>* segment
= (macho_segment_command
<P
>*)cmd
;
1433 const macho_section
<P
>* sectionsStart
= (macho_section
<P
>*)((char*)segment
+ sizeof(macho_segment_command
<P
>));
1434 for (uint32_t si
=0; si
< segment
->nsects(); ++si
) {
1435 const macho_section
<P
>* sect
= §ionsStart
[si
];
1436 if ( (sect
->size() > 0)
1437 && (strcmp(sect
->sectname(), "__objc_catlist") == 0)
1438 && (strcmp(sect
->segname(), "__DATA") == 0) ) {
1443 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
1444 if ( cmd
> cmdsEnd
)
1445 throwf("malformed mach-o file, load command #%d is outside size of load commands", i
);
1451 template <typename A
>
1452 bool Parser
<A
>::hasObjC1Categories(const uint8_t* fileContent
)
1454 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1455 const uint32_t cmd_count
= header
->ncmds();
1456 const macho_load_command
<P
>* const cmds
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>));
1457 const macho_load_command
<P
>* const cmdsEnd
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>) + header
->sizeofcmds());
1458 const macho_load_command
<P
>* cmd
= cmds
;
1459 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1460 if ( cmd
->cmd() == macho_segment_command
<P
>::CMD
) {
1461 const macho_segment_command
<P
>* segment
= (macho_segment_command
<P
>*)cmd
;
1462 const macho_section
<P
>* sectionsStart
= (macho_section
<P
>*)((char*)segment
+ sizeof(macho_segment_command
<P
>));
1463 for (uint32_t si
=0; si
< segment
->nsects(); ++si
) {
1464 const macho_section
<P
>* sect
= §ionsStart
[si
];
1465 if ( (sect
->size() > 0)
1466 && (strcmp(sect
->sectname(), "__category") == 0)
1467 && (strcmp(sect
->segname(), "__OBJC") == 0) ) {
1472 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
1473 if ( cmd
> cmdsEnd
)
1474 throwf("malformed mach-o file, load command #%d is outside size of load commands", i
);
1480 template <typename A
>
1481 bool Parser
<A
>::getNonLocalSymbols(const uint8_t* fileContent
, std::vector
<const char*> &syms
)
1483 const macho_header
<P
>* header
= (const macho_header
<P
>*)fileContent
;
1484 const uint32_t cmd_count
= header
->ncmds();
1485 const macho_load_command
<P
>* const cmds
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>));
1486 const macho_load_command
<P
>* const cmdsEnd
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>) + header
->sizeofcmds());
1487 const macho_load_command
<P
>* cmd
= cmds
;
1488 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1489 if ( cmd
->cmd() == LC_SYMTAB
) {
1490 const macho_symtab_command
<P
>* symtab
= (macho_symtab_command
<P
>*)cmd
;
1491 uint32_t symbolCount
= symtab
->nsyms();
1492 const macho_nlist
<P
>* symbols
= (const macho_nlist
<P
>*)(fileContent
+ symtab
->symoff());
1493 const char* strings
= (char*)fileContent
+ symtab
->stroff();
1494 for (uint32_t j
= 0; j
< symbolCount
; ++j
) {
1495 // ignore stabs and count only ext symbols
1496 if ( (symbols
[j
].n_type() & N_STAB
) == 0 &&
1497 (symbols
[j
].n_type() & N_EXT
) != 0 ) {
1498 const char* symName
= &strings
[symbols
[j
].n_strx()];
1499 syms
.push_back(symName
);
1504 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
1505 if ( cmd
> cmdsEnd
)
1506 throwf("malformed mach-o file, load command #%d is outside size of load commands", i
);
1512 template <typename A
>
1513 int Parser
<A
>::pointerSorter(const void* l
, const void* r
)
1515 // sort references by address
1516 const pint_t
* left
= (pint_t
*)l
;
1517 const pint_t
* right
= (pint_t
*)r
;
1518 return (*left
- *right
);
1521 template <typename A
>
1522 typename
A::P::uint_t Parser
<A
>::LabelAndCFIBreakIterator::peek(Parser
<A
>& parser
, pint_t startAddr
, pint_t endAddr
)
1525 if ( symIndex
< sortedSymbolCount
)
1526 symbolAddr
= parser
.symbolFromIndex(sortedSymbolIndexes
[symIndex
]).n_value();
1528 symbolAddr
= endAddr
;
1530 if ( cfiIndex
< cfiStartsCount
)
1531 cfiAddr
= cfiStartsArray
[cfiIndex
];
1534 if ( (cfiAddr
< symbolAddr
) && (cfiAddr
>= startAddr
) ) {
1535 if ( cfiAddr
< endAddr
)
1541 if ( symbolAddr
< endAddr
)
1549 // Parses up a section into chunks based on labels and CFI information.
1550 // Each call returns the next chunk address and size, and (if the break
1551 // was becuase of a label, the symbol). Returns false when no more chunks.
1553 template <typename A
>
1554 bool Parser
<A
>::LabelAndCFIBreakIterator::next(Parser
<A
>& parser
, const Section
<A
>& sect
, uint32_t sectNum
, pint_t startAddr
, pint_t endAddr
,
1555 pint_t
* addr
, pint_t
* size
, const macho_nlist
<P
>** symbol
)
1557 // may not be a label on start of section, but need atom demarcation there
1560 // advance symIndex until we get to the first label at or past the start of this section
1561 while ( symIndex
< sortedSymbolCount
) {
1562 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(sortedSymbolIndexes
[symIndex
]);
1563 if ( ! sect
.ignoreLabel(parser
.nameFromSymbol(sym
)) ) {
1564 pint_t nextSymbolAddr
= sym
.n_value();
1565 //fprintf(stderr, "sectNum=%d, nextSymbolAddr=0x%08llX, name=%s\n", sectNum, (uint64_t)nextSymbolAddr, parser.nameFromSymbol(sym));
1566 if ( (nextSymbolAddr
> startAddr
) || ((nextSymbolAddr
== startAddr
) && (sym
.n_sect() == sectNum
)) )
1571 if ( symIndex
< sortedSymbolCount
) {
1572 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(sortedSymbolIndexes
[symIndex
]);
1573 pint_t nextSymbolAddr
= sym
.n_value();
1574 // if next symbol found is not in this section
1575 if ( sym
.n_sect() != sectNum
) {
1576 // check for CFI break instead of symbol break
1577 if ( cfiIndex
< cfiStartsCount
) {
1578 pint_t nextCfiAddr
= cfiStartsArray
[cfiIndex
];
1579 if ( nextCfiAddr
< endAddr
) {
1582 *addr
= nextCfiAddr
;
1583 *size
= peek(parser
, startAddr
, endAddr
) - nextCfiAddr
;
1589 *size
= endAddr
- startAddr
;
1591 if ( startAddr
== endAddr
)
1592 return false; // zero size section
1594 return true; // whole section is one atom with no label
1596 // if also CFI break here, eat it
1597 if ( cfiIndex
< cfiStartsCount
) {
1598 if ( cfiStartsArray
[cfiIndex
] == nextSymbolAddr
)
1601 if ( nextSymbolAddr
== startAddr
) {
1602 // label at start of section, return it as chunk
1605 *size
= peek(parser
, startAddr
, endAddr
) - startAddr
;
1609 // return chunk before first symbol
1611 *size
= nextSymbolAddr
- startAddr
;
1615 // no symbols in section, check CFI
1616 if ( cfiIndex
< cfiStartsCount
) {
1617 pint_t nextCfiAddr
= cfiStartsArray
[cfiIndex
];
1618 if ( nextCfiAddr
< endAddr
) {
1621 *addr
= nextCfiAddr
;
1622 *size
= peek(parser
, startAddr
, endAddr
) - nextCfiAddr
;
1627 // no cfi, so whole section is one chunk
1629 *size
= endAddr
- startAddr
;
1631 if ( startAddr
== endAddr
)
1632 return false; // zero size section
1634 return true; // whole section is one atom with no label
1637 while ( (symIndex
< sortedSymbolCount
) && (cfiIndex
< cfiStartsCount
) ) {
1638 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(sortedSymbolIndexes
[symIndex
]);
1639 pint_t nextSymbolAddr
= sym
.n_value();
1640 pint_t nextCfiAddr
= cfiStartsArray
[cfiIndex
];
1641 if ( nextSymbolAddr
< nextCfiAddr
) {
1642 if ( nextSymbolAddr
>= endAddr
)
1645 if ( nextSymbolAddr
< startAddr
)
1647 *addr
= nextSymbolAddr
;
1648 *size
= peek(parser
, startAddr
, endAddr
) - nextSymbolAddr
;
1652 else if ( nextCfiAddr
< nextSymbolAddr
) {
1653 if ( nextCfiAddr
>= endAddr
)
1656 if ( nextCfiAddr
< startAddr
)
1658 *addr
= nextCfiAddr
;
1659 *size
= peek(parser
, startAddr
, endAddr
) - nextCfiAddr
;
1664 if ( nextCfiAddr
>= endAddr
)
1668 if ( nextCfiAddr
< startAddr
)
1670 *addr
= nextCfiAddr
;
1671 *size
= peek(parser
, startAddr
, endAddr
) - nextCfiAddr
;
1676 while ( symIndex
< sortedSymbolCount
) {
1677 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(sortedSymbolIndexes
[symIndex
]);
1678 pint_t nextSymbolAddr
= sym
.n_value();
1679 // if next symbol found is not in this section, then done with iteration
1680 if ( sym
.n_sect() != sectNum
)
1683 if ( nextSymbolAddr
< startAddr
)
1685 *addr
= nextSymbolAddr
;
1686 *size
= peek(parser
, startAddr
, endAddr
) - nextSymbolAddr
;
1690 while ( cfiIndex
< cfiStartsCount
) {
1691 pint_t nextCfiAddr
= cfiStartsArray
[cfiIndex
];
1692 if ( nextCfiAddr
>= endAddr
)
1695 if ( nextCfiAddr
< startAddr
)
1697 *addr
= nextCfiAddr
;
1698 *size
= peek(parser
, startAddr
, endAddr
) - nextCfiAddr
;
1706 typename
arm::P::uint_t Parser
<arm
>::realAddr(typename
arm::P::uint_t addr
)
1711 template <typename A
>
1712 typename
A::P::uint_t Parser
<A
>::realAddr(typename
A::P::uint_t addr
)
1717 #define STACK_ALLOC_IF_SMALL(_type, _name, _actual_count, _maxCount) \
1718 _type* _name = NULL; \
1719 uint32_t _name##_count = 1; \
1720 uint32_t _name##_stack_count = _actual_count; \
1721 if ( _actual_count > _maxCount ) { \
1722 _name = (_type*)malloc(sizeof(_type) * _actual_count); \
1723 _name##_stack_count = 1; \
1726 _name##_count = _actual_count; \
1727 _type _name##_buffer[_name##_stack_count]; \
1728 if ( _name == NULL ) \
1729 _name = _name##_buffer;
1732 template <typename A
>
1733 ld::relocatable::File
* Parser
<A
>::parse(const ParserOptions
& opts
)
1735 // create file object
1736 _file
= new File
<A
>(_path
, _modTime
, _fileContent
, _ordinal
);
1739 _file
->_srcKind
= opts
.srcKind
;
1740 // set treatBitcodeAsData
1741 _treateBitcodeAsData
= opts
.treateBitcodeAsData
;
1742 _usingBitcode
= opts
.usingBitcode
;
1744 // respond to -t option
1745 if ( opts
.logAllFiles
)
1746 printf("%s\n", _path
);
1748 _armUsesZeroCostExceptions
= opts
.armUsesZeroCostExceptions
;
1749 _maxDefaultCommonAlignment
= opts
.maxDefaultCommonAlignment
;
1751 // parse start of mach-o file
1752 if ( ! parseLoadCommands(opts
.platform
, opts
.minOSVersion
, opts
.simulator
, opts
.ignoreMismatchPlatform
) )
1756 uint32_t sortedSectionIndexes
[_machOSectionsCount
];
1757 this->makeSortedSectionsArray(sortedSectionIndexes
);
1759 // make symbol table sorted by address
1760 this->prescanSymbolTable();
1761 uint32_t sortedSymbolIndexes
[_symbolsInSections
];
1762 this->makeSortedSymbolsArray(sortedSymbolIndexes
, sortedSectionIndexes
);
1764 // allocate Section<A> object for each mach-o section
1767 // if it exists, do special early parsing of __compact_unwind section
1768 uint32_t countOfCUs
= 0;
1769 if ( _compactUnwindSection
!= NULL
)
1770 countOfCUs
= _compactUnwindSection
->count();
1771 // stack allocate (if not too large) cuInfoBuffer
1772 STACK_ALLOC_IF_SMALL(typename CUSection
<A
>::Info
, cuInfoArray
, countOfCUs
, 1024);
1773 if ( countOfCUs
!= 0 )
1774 _compactUnwindSection
->parse(*this, countOfCUs
, cuInfoArray
);
1776 // create lists of address that already have compact unwind and thus don't need the dwarf parsed
1777 unsigned cuLsdaCount
= 0;
1778 STACK_ALLOC_IF_SMALL(pint_t
, cuStarts
, countOfCUs
, 1024);
1779 for (uint32_t i
=0; i
< countOfCUs
; ++i
) {
1780 if ( CUSection
<A
>::encodingMeansUseDwarf(cuInfoArray
[i
].compactUnwindInfo
) )
1783 cuStarts
[i
] = cuInfoArray
[i
].functionStartAddress
;
1784 if ( cuInfoArray
[i
].lsdaAddress
!= 0 )
1789 // if it exists, do special early parsing of __eh_frame section
1790 // stack allocate (if not too large) array of CFI_Atom_Info
1791 uint32_t countOfCFIs
= 0;
1792 if ( _EHFrameSection
!= NULL
)
1793 countOfCFIs
= _EHFrameSection
->cfiCount(*this);
1794 STACK_ALLOC_IF_SMALL(typename CFISection
<A
>::CFI_Atom_Info
, cfiArray
, countOfCFIs
, 1024);
1796 // stack allocate (if not too large) a copy of __eh_frame to apply relocations to
1797 uint32_t sectSize
= 4;
1798 if ( (countOfCFIs
!= 0) && _EHFrameSection
->needsRelocating() )
1799 sectSize
= _EHFrameSection
->machoSection()->size()+4;
1800 STACK_ALLOC_IF_SMALL(uint8_t, ehBuffer
, sectSize
, 50*1024);
1801 uint32_t cfiStartsCount
= 0;
1802 if ( countOfCFIs
!= 0 ) {
1803 _EHFrameSection
->cfiParse(*this, ehBuffer
, cfiArray
, countOfCFIs
, cuStarts
, countOfCUs
);
1804 // count functions and lsdas
1805 for(uint32_t i
=0; i
< countOfCFIs
; ++i
) {
1806 if ( cfiArray
[i
].isCIE
)
1808 //fprintf(stderr, "cfiArray[i].func = 0x%08llX, cfiArray[i].lsda = 0x%08llX, encoding=0x%08X\n",
1809 // (uint64_t)cfiArray[i].u.fdeInfo.function.targetAddress,
1810 // (uint64_t)cfiArray[i].u.fdeInfo.lsda.targetAddress,
1811 // cfiArray[i].u.fdeInfo.compactUnwindInfo);
1812 if ( cfiArray
[i
].u
.fdeInfo
.function
.targetAddress
!= CFI_INVALID_ADDRESS
)
1814 if ( cfiArray
[i
].u
.fdeInfo
.lsda
.targetAddress
!= CFI_INVALID_ADDRESS
)
1818 CFI_CU_InfoArrays
cfis(cfiArray
, countOfCFIs
, cuInfoArray
, countOfCUs
);
1820 // create sorted array of function starts and lsda starts
1821 pint_t cfiStartsArray
[cfiStartsCount
+cuLsdaCount
];
1822 uint32_t countOfFDEs
= 0;
1823 uint32_t cfiStartsArrayCount
= 0;
1824 if ( countOfCFIs
!= 0 ) {
1825 for(uint32_t i
=0; i
< countOfCFIs
; ++i
) {
1826 if ( cfiArray
[i
].isCIE
)
1828 if ( cfiArray
[i
].u
.fdeInfo
.function
.targetAddress
!= CFI_INVALID_ADDRESS
)
1829 cfiStartsArray
[cfiStartsArrayCount
++] = realAddr(cfiArray
[i
].u
.fdeInfo
.function
.targetAddress
);
1830 if ( cfiArray
[i
].u
.fdeInfo
.lsda
.targetAddress
!= CFI_INVALID_ADDRESS
)
1831 cfiStartsArray
[cfiStartsArrayCount
++] = cfiArray
[i
].u
.fdeInfo
.lsda
.targetAddress
;
1835 if ( cuLsdaCount
!= 0 ) {
1836 // merge in an lsda info from compact unwind
1837 for (uint32_t i
=0; i
< countOfCUs
; ++i
) {
1838 if ( cuInfoArray
[i
].lsdaAddress
== 0 )
1840 // append to cfiStartsArray if not already in that list
1842 for(uint32_t j
=0; j
< cfiStartsArrayCount
; ++j
) {
1843 if ( cfiStartsArray
[j
] == cuInfoArray
[i
].lsdaAddress
)
1847 cfiStartsArray
[cfiStartsArrayCount
++] = cuInfoArray
[i
].lsdaAddress
;
1851 if ( cfiStartsArrayCount
!= 0 ) {
1852 ::qsort(cfiStartsArray
, cfiStartsArrayCount
, sizeof(pint_t
), pointerSorter
);
1854 // scan for FDEs claming the same function
1855 for(uint32_t i
=1; i
< cfiStartsArrayCount
; ++i
) {
1856 assert( cfiStartsArray
[i
] != cfiStartsArray
[i
-1] );
1861 Section
<A
>** sections
= _file
->_sectionsArray
;
1862 uint32_t sectionsCount
= _file
->_sectionsArrayCount
;
1864 // figure out how many atoms will be allocated and allocate
1865 LabelAndCFIBreakIterator
breakIterator(sortedSymbolIndexes
, _symbolsInSections
, cfiStartsArray
,
1866 cfiStartsArrayCount
, _overlappingSymbols
);
1867 uint32_t computedAtomCount
= 0;
1868 for (uint32_t i
=0; i
< sectionsCount
; ++i
) {
1869 breakIterator
.beginSection();
1870 uint32_t count
= sections
[i
]->computeAtomCount(*this, breakIterator
, cfis
);
1871 //const macho_section<P>* sect = sections[i]->machoSection();
1872 //fprintf(stderr, "computed count=%u for section %s size=%llu\n", count, sect->sectname(), (sect != NULL) ? sect->size() : 0);
1873 computedAtomCount
+= count
;
1875 //fprintf(stderr, "allocating %d atoms * sizeof(Atom<A>)=%ld, sizeof(ld::Atom)=%ld\n", computedAtomCount, sizeof(Atom<A>), sizeof(ld::Atom));
1876 _file
->_atomsArray
= new uint8_t[computedAtomCount
*sizeof(Atom
<A
>)];
1877 _file
->_atomsArrayCount
= 0;
1879 // have each section append atoms to _atomsArray
1880 LabelAndCFIBreakIterator
breakIterator2(sortedSymbolIndexes
, _symbolsInSections
, cfiStartsArray
,
1881 cfiStartsArrayCount
, _overlappingSymbols
);
1882 for (uint32_t i
=0; i
< sectionsCount
; ++i
) {
1883 uint8_t* atoms
= _file
->_atomsArray
+ _file
->_atomsArrayCount
*sizeof(Atom
<A
>);
1884 breakIterator2
.beginSection();
1885 uint32_t count
= sections
[i
]->appendAtoms(*this, atoms
, breakIterator2
, cfis
);
1886 //fprintf(stderr, "append count=%u for section %s/%s\n", count, sections[i]->machoSection()->segname(), sections[i]->machoSection()->sectname());
1887 _file
->_atomsArrayCount
+= count
;
1889 assert( _file
->_atomsArrayCount
== computedAtomCount
&& "more atoms allocated than expected");
1892 // have each section add all fix-ups for its atoms
1893 _allFixups
.reserve(computedAtomCount
*5);
1894 for (uint32_t i
=0; i
< sectionsCount
; ++i
)
1895 sections
[i
]->makeFixups(*this, cfis
);
1897 // assign fixups start offset for each atom
1898 uint8_t* p
= _file
->_atomsArray
;
1899 uint32_t fixupOffset
= 0;
1900 for(int i
=_file
->_atomsArrayCount
; i
> 0; --i
) {
1901 Atom
<A
>* atom
= (Atom
<A
>*)p
;
1902 atom
->_fixupsStartIndex
= fixupOffset
;
1903 fixupOffset
+= atom
->_fixupsCount
;
1904 atom
->_fixupsCount
= 0;
1905 p
+= sizeof(Atom
<A
>);
1907 assert(fixupOffset
== _allFixups
.size());
1908 _file
->_fixups
.resize(fixupOffset
);
1910 // copy each fixup for each atom
1911 for(typename
std::vector
<FixupInAtom
>::iterator it
=_allFixups
.begin(); it
!= _allFixups
.end(); ++it
) {
1912 uint32_t slot
= it
->atom
->_fixupsStartIndex
+ it
->atom
->_fixupsCount
;
1913 _file
->_fixups
[slot
] = it
->fixup
;
1914 it
->atom
->_fixupsCount
++;
1917 // done with temp vector
1921 _file
->_unwindInfos
.reserve(countOfFDEs
+countOfCUs
);
1922 for(uint32_t i
=0; i
< countOfCFIs
; ++i
) {
1923 if ( cfiArray
[i
].isCIE
)
1925 if ( cfiArray
[i
].u
.fdeInfo
.function
.targetAddress
!= CFI_INVALID_ADDRESS
) {
1926 ld::Atom::UnwindInfo info
;
1927 info
.startOffset
= 0;
1928 info
.unwindInfo
= cfiArray
[i
].u
.fdeInfo
.compactUnwindInfo
;
1929 _file
->_unwindInfos
.push_back(info
);
1930 Atom
<A
>* func
= findAtomByAddress(cfiArray
[i
].u
.fdeInfo
.function
.targetAddress
);
1931 func
->setUnwindInfoRange(_file
->_unwindInfos
.size()-1, 1);
1932 //fprintf(stderr, "cu from dwarf =0x%08X, atom=%s\n", info.unwindInfo, func->name());
1935 // apply compact infos in __LD,__compact_unwind section to each function
1936 // if function also has dwarf unwind, CU will override it
1937 Atom
<A
>* lastFunc
= NULL
;
1938 uint32_t lastEnd
= 0;
1939 for(uint32_t i
=0; i
< countOfCUs
; ++i
) {
1940 typename CUSection
<A
>::Info
* info
= &cuInfoArray
[i
];
1941 assert(info
->function
!= NULL
);
1942 ld::Atom::UnwindInfo ui
;
1943 ui
.startOffset
= info
->functionStartAddress
- info
->function
->objectAddress();
1944 ui
.unwindInfo
= info
->compactUnwindInfo
;
1945 _file
->_unwindInfos
.push_back(ui
);
1946 // don't override with converted cu with "use dwarf" cu, if forcing dwarf conversion
1947 if ( !_forceDwarfConversion
|| !CUSection
<A
>::encodingMeansUseDwarf(info
->compactUnwindInfo
) ) {
1948 //fprintf(stderr, "cu=0x%08X, atom=%s\n", ui.unwindInfo, info->function->name());
1949 // if previous is for same function, extend range
1950 if ( info
->function
== lastFunc
) {
1951 if ( lastEnd
!= ui
.startOffset
) {
1952 if ( lastEnd
< ui
.startOffset
)
1953 warning("__LD,__compact_unwind entries for %s have a gap at offset 0x%0X", info
->function
->name(), lastEnd
);
1955 warning("__LD,__compact_unwind entries for %s overlap at offset 0x%0X", info
->function
->name(), lastEnd
);
1957 lastFunc
->extendUnwindInfoRange();
1960 info
->function
->setUnwindInfoRange(_file
->_unwindInfos
.size()-1, 1);
1961 lastFunc
= info
->function
;
1962 lastEnd
= ui
.startOffset
+ info
->rangeLength
;
1966 // process indirect symbols which become AliasAtoms
1967 _file
->_aliasAtomsArray
= NULL
;
1968 _file
->_aliasAtomsArrayCount
= 0;
1969 if ( _indirectSymbolCount
!= 0 ) {
1970 _file
->_aliasAtomsArrayCount
= _indirectSymbolCount
;
1971 _file
->_aliasAtomsArray
= new uint8_t[_file
->_aliasAtomsArrayCount
*sizeof(AliasAtom
)];
1972 this->appendAliasAtoms(_file
->_aliasAtomsArray
);
1976 // parse dwarf debug info to get line info
1977 this->parseDebugInfo();
1982 static void versionToString(uint32_t value
, char buffer
[32])
1985 sprintf(buffer
, "%d.%d.%d", value
>> 16, (value
>> 8) & 0xFF, value
& 0xFF);
1987 sprintf(buffer
, "%d.%d", value
>> 16, (value
>> 8) & 0xFF);
1990 template <> uint8_t Parser
<x86
>::loadCommandSizeMask() { return 0x03; }
1991 template <> uint8_t Parser
<x86_64
>::loadCommandSizeMask() { return 0x07; }
1992 template <> uint8_t Parser
<arm
>::loadCommandSizeMask() { return 0x03; }
1993 template <> uint8_t Parser
<arm64
>::loadCommandSizeMask() { return 0x07; }
1995 template <typename A
>
1996 bool Parser
<A
>::parseLoadCommands(Options::Platform platform
, uint32_t linkMinOSVersion
, bool simulator
, bool ignoreMismatchPlatform
)
1998 const macho_header
<P
>* header
= (const macho_header
<P
>*)_fileContent
;
2000 // set File attributes
2001 _file
->_canScatterAtoms
= (header
->flags() & MH_SUBSECTIONS_VIA_SYMBOLS
);
2002 _file
->_cpuSubType
= header
->cpusubtype();
2004 const macho_segment_command
<P
>* segment
= NULL
;
2005 const uint8_t* const endOfFile
= _fileContent
+ _fileLength
;
2006 const uint32_t cmd_count
= header
->ncmds();
2007 // <rdar://problem/5394172> an empty .o file with zero load commands will crash linker
2008 if ( cmd_count
== 0 )
2010 Options::Platform lcPlatform
= Options::kPlatformUnknown
;
2011 const macho_load_command
<P
>* const cmds
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>));
2012 const macho_load_command
<P
>* const cmdsEnd
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>) + header
->sizeofcmds());
2013 const macho_load_command
<P
>* cmd
= cmds
;
2014 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
2015 uint32_t size
= cmd
->cmdsize();
2016 if ( (size
& this->loadCommandSizeMask()) != 0 )
2017 throwf("load command #%d has a unaligned size", i
);
2018 const uint8_t* endOfCmd
= ((uint8_t*)cmd
)+cmd
->cmdsize();
2019 if ( endOfCmd
> (uint8_t*)cmdsEnd
)
2020 throwf("load command #%d extends beyond the end of the load commands", i
);
2021 if ( endOfCmd
> endOfFile
)
2022 throwf("load command #%d extends beyond the end of the file", i
);
2023 switch (cmd
->cmd()) {
2026 const macho_symtab_command
<P
>* symtab
= (macho_symtab_command
<P
>*)cmd
;
2027 _symbolCount
= symtab
->nsyms();
2028 _symbols
= (const macho_nlist
<P
>*)(_fileContent
+ symtab
->symoff());
2029 _strings
= (char*)_fileContent
+ symtab
->stroff();
2030 _stringsSize
= symtab
->strsize();
2031 if ( (symtab
->symoff() + _symbolCount
*sizeof(macho_nlist
<P
>)) > _fileLength
)
2032 throw "mach-o symbol table extends beyond end of file";
2033 if ( (_strings
+ _stringsSize
) > (char*)endOfFile
)
2034 throw "mach-o string pool extends beyond end of file";
2035 if ( _indirectTable
== NULL
) {
2036 if ( _undefinedEndIndex
== 0 ) {
2037 _undefinedStartIndex
= 0;
2038 _undefinedEndIndex
= symtab
->nsyms();
2045 const macho_dysymtab_command
<P
>* dsymtab
= (macho_dysymtab_command
<P
>*)cmd
;
2046 _indirectTable
= (uint32_t*)(_fileContent
+ dsymtab
->indirectsymoff());
2047 _indirectTableCount
= dsymtab
->nindirectsyms();
2048 if ( &_indirectTable
[_indirectTableCount
] > (uint32_t*)endOfFile
)
2049 throw "indirect symbol table extends beyond end of file";
2050 _undefinedStartIndex
= dsymtab
->iundefsym();
2051 _undefinedEndIndex
= _undefinedStartIndex
+ dsymtab
->nundefsym();
2057 case LC_DATA_IN_CODE
:
2059 const macho_linkedit_data_command
<P
>* dc
= (macho_linkedit_data_command
<P
>*)cmd
;
2060 _dataInCodeStart
= (macho_data_in_code_entry
<P
>*)(_fileContent
+ dc
->dataoff());
2061 _dataInCodeEnd
= (macho_data_in_code_entry
<P
>*)(_fileContent
+ dc
->dataoff() + dc
->datasize());
2062 if ( _dataInCodeEnd
> (macho_data_in_code_entry
<P
>*)endOfFile
)
2063 throw "LC_DATA_IN_CODE table extends beyond end of file";
2066 case LC_LINKER_OPTION
:
2068 const macho_linker_option_command
<P
>* loc
= (macho_linker_option_command
<P
>*)cmd
;
2069 const char* buffer
= loc
->buffer();
2070 _file
->_linkerOptions
.resize(_file
->_linkerOptions
.size() + 1);
2071 std::vector
<const char*>& vec
= _file
->_linkerOptions
.back();
2072 for (uint32_t j
=0; j
< loc
->count(); ++j
) {
2073 vec
.push_back(buffer
);
2074 buffer
+= strlen(buffer
) + 1;
2076 if ( buffer
> ((char*)cmd
+ loc
->cmdsize()) )
2077 throw "malformed LC_LINKER_OPTION";
2080 case LC_LINKER_OPTIMIZATION_HINTS
:
2082 const macho_linkedit_data_command
<P
>* loh
= (macho_linkedit_data_command
<P
>*)cmd
;
2083 _lohStart
= _fileContent
+ loh
->dataoff();
2084 _lohEnd
= _fileContent
+ loh
->dataoff() + loh
->datasize();
2085 if ( _lohEnd
> endOfFile
)
2086 throw "LC_LINKER_OPTIMIZATION_HINTS table extends beyond end of file";
2089 case LC_VERSION_MIN_MACOSX
:
2090 case LC_VERSION_MIN_IPHONEOS
:
2091 case LC_VERSION_MIN_WATCHOS
:
2092 #if SUPPORT_APPLE_TV
2093 case LC_VERSION_MIN_TVOS
:
2095 if ( ignoreMismatchPlatform
)
2097 lcPlatform
= Options::platformForLoadCommand(cmd
->cmd());
2098 _file
->_platform
= lcPlatform
;
2099 _file
->_minOSVersion
= ((macho_version_min_command
<P
>*)cmd
)->version();
2101 case LC_BUILD_VERSION
:
2103 const macho_build_version_command
<P
>* buildVersCmd
= (macho_build_version_command
<P
>*)cmd
;
2104 if ( ignoreMismatchPlatform
)
2106 lcPlatform
= (Options::Platform
)buildVersCmd
->platform();
2107 _file
->_platform
= lcPlatform
;
2108 _file
->_minOSVersion
= buildVersCmd
->minos();
2109 const macho_build_tool_version
<P
>* entry
= (macho_build_tool_version
<P
>*)((uint8_t*)cmd
+ sizeof(macho_build_version_command
<P
>));
2110 for (uint32_t t
=0; t
< buildVersCmd
->ntools(); ++t
) {
2111 _file
->_toolVersions
.push_back(std::make_pair(entry
->tool(), entry
->version()));
2116 case macho_segment_command
<P
>::CMD
:
2117 if ( segment
!= NULL
)
2118 throw "more than one LC_SEGMENT found in object file";
2119 segment
= (macho_segment_command
<P
>*)cmd
;
2122 // ignore unknown load commands
2125 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
2126 if ( cmd
> cmdsEnd
)
2127 throwf("malformed mach-o file, load command #%d is outside size of load commands", i
);
2129 // arm/arm64 objects are default to ios platform if not set.
2130 // rdar://problem/21746314
2131 if (lcPlatform
== Options::kPlatformUnknown
&&
2132 (std::is_same
<A
, arm
>::value
|| std::is_same
<A
, arm64
>::value
))
2133 lcPlatform
= Options::kPlatformiOS
;
2135 // Check platform cross-linking.
2136 if ( !ignoreMismatchPlatform
) {
2137 if ( lcPlatform
!= platform
) {
2139 case Options::kPlatformOSX
:
2140 case Options::kPlatformiOS
:
2141 if ( lcPlatform
== Options::kPlatformUnknown
)
2143 // fall through if the Platform is not Unknown
2144 case Options::kPlatform_bridgeOS
:
2145 case Options::kPlatformWatchOS
:
2146 // Error when using bitcocde, warning otherwise.
2148 throwf("building for %s%s, but linking in object file built for %s,",
2149 Options::platformName(platform
), (simulator
? " simulator" : ""),
2150 Options::platformName(lcPlatform
));
2152 warning("URGENT: building for %s%s, but linking in object file (%s) built for %s. "
2153 "Note: This will be an error in the future.",
2154 Options::platformName(platform
), (simulator
? " simulator" : ""), path(),
2155 Options::platformName(lcPlatform
));
2157 #if SUPPORT_APPLE_TV
2158 case Options::kPlatform_tvOS
:
2159 // Error when using bitcocde, warning otherwise.
2161 throwf("building for %s%s, but linking in object file built for %s,",
2162 Options::platformName(platform
), (simulator
? " simulator" : ""),
2163 Options::platformName(lcPlatform
));
2165 warning("URGENT: building for %s%s, but linking in object file (%s) built for %s. "
2166 "Note: This will be an error in the future.",
2167 Options::platformName(platform
), (simulator
? " simulator" : ""), path(),
2168 Options::platformName(lcPlatform
));
2171 case Options::kPlatformUnknown
:
2172 // skip if the target platform is unknown
2176 if ( linkMinOSVersion
&& (_file
->_minOSVersion
> linkMinOSVersion
) ) {
2179 versionToString(_file
->_minOSVersion
, t1
);
2180 versionToString(linkMinOSVersion
, t2
);
2181 warning("object file (%s) was built for newer %s version (%s) than being linked (%s)",
2182 _path
, Options::platformName(lcPlatform
), t1
, t2
);
2187 // record range of sections
2188 if ( segment
== NULL
)
2189 throw "missing LC_SEGMENT";
2190 _sectionsStart
= (macho_section
<P
>*)((char*)segment
+ sizeof(macho_segment_command
<P
>));
2191 _machOSectionsCount
= segment
->nsects();
2192 if ( (sizeof(macho_segment_command
<P
>) + _machOSectionsCount
* sizeof(macho_section
<P
>)) > segment
->cmdsize() )
2193 throw "too many sections for size of LC_SEGMENT command";
2197 template <typename A
>
2198 Options::Platform Parser
<A
>::findPlatform(const macho_header
<P
>* header
)
2200 const uint32_t cmd_count
= header
->ncmds();
2201 if ( cmd_count
== 0 )
2202 return Options::kPlatformUnknown
;
2203 const macho_load_command
<P
>* const cmds
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>));
2204 const macho_load_command
<P
>* const cmdsEnd
= (macho_load_command
<P
>*)((char*)header
+ sizeof(macho_header
<P
>) + header
->sizeofcmds());
2205 const macho_load_command
<P
>* cmd
= cmds
;
2206 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
2207 uint32_t size
= cmd
->cmdsize();
2208 if ( (size
& loadCommandSizeMask()) != 0 )
2209 throwf("load command #%d has a unaligned size", i
);
2210 const uint8_t* endOfCmd
= ((uint8_t*)cmd
)+cmd
->cmdsize();
2211 if ( endOfCmd
> (uint8_t*)cmdsEnd
)
2212 throwf("load command #%d extends beyond the end of the load commands", i
);
2213 switch (cmd
->cmd()) {
2214 case LC_VERSION_MIN_MACOSX
:
2215 return Options::kPlatformOSX
;
2216 case LC_VERSION_MIN_IPHONEOS
:
2217 return Options::kPlatformiOS
;
2218 case LC_VERSION_MIN_WATCHOS
:
2219 return Options::kPlatformWatchOS
;
2220 #if SUPPORT_APPLE_TV
2221 case LC_VERSION_MIN_TVOS
:
2222 return Options::kPlatform_tvOS
;
2224 case LC_BUILD_VERSION
:
2225 return (Options::Platform
)((macho_build_version_command
<P
>*)cmd
)->platform();
2227 cmd
= (const macho_load_command
<P
>*)(((char*)cmd
)+cmd
->cmdsize());
2228 if ( cmd
> cmdsEnd
)
2229 throwf("malformed mach-o file, load command #%d is outside size of load commands", i
);
2231 return Options::kPlatformUnknown
;
2235 template <typename A
>
2236 void Parser
<A
>::prescanSymbolTable()
2238 _tentativeDefinitionCount
= 0;
2239 _absoluteSymbolCount
= 0;
2240 _symbolsInSections
= 0;
2241 _hasDataInCodeLabels
= false;
2242 for (uint32_t i
=0; i
< this->_symbolCount
; ++i
) {
2243 const macho_nlist
<P
>& sym
= symbolFromIndex(i
);
2245 if ( (sym
.n_type() & N_STAB
) != 0 )
2248 // look at undefines
2249 const char* symbolName
= this->nameFromSymbol(sym
);
2250 if ( (sym
.n_type() & N_TYPE
) == N_UNDF
) {
2251 if ( sym
.n_value() != 0 ) {
2252 // count tentative definitions
2253 ++_tentativeDefinitionCount
;
2255 else if ( strncmp(symbolName
, "___dtrace_", 10) == 0 ) {
2256 // any undefined starting with __dtrace_*$ that is not ___dtrace_probe$* or ___dtrace_isenabled$*
2257 // is extra provider info
2258 if ( (strncmp(&symbolName
[10], "probe$", 6) != 0) && (strncmp(&symbolName
[10], "isenabled$", 10) != 0) ) {
2259 _dtraceProviderInfo
.push_back(symbolName
);
2264 else if ( ((sym
.n_type() & N_TYPE
) == N_INDR
) && ((sym
.n_type() & N_EXT
) != 0) ) {
2265 _indirectSymbolCount
++;
2269 // count absolute symbols
2270 if ( (sym
.n_type() & N_TYPE
) == N_ABS
) {
2271 const char* absName
= this->nameFromSymbol(sym
);
2272 // ignore .objc_class_name_* symbols
2273 if ( strncmp(absName
, ".objc_class_name_", 17) == 0 ) {
2277 // ignore .objc_class_name_* symbols
2278 if ( strncmp(absName
, ".objc_category_name_", 20) == 0 )
2280 // ignore empty *.eh symbols
2281 if ( strcmp(&absName
[strlen(absName
)-3], ".eh") == 0 )
2283 ++_absoluteSymbolCount
;
2286 // only look at definitions
2287 if ( (sym
.n_type() & N_TYPE
) != N_SECT
)
2290 // 'L' labels do not denote atom breaks
2291 if ( symbolName
[0] == 'L' ) {
2292 // <rdar://problem/9218847> Formalize data in code with L$start$ labels
2293 if ( strncmp(symbolName
, "L$start$", 8) == 0 )
2294 _hasDataInCodeLabels
= true;
2297 // how many def syms in each section
2298 if ( sym
.n_sect() > _machOSectionsCount
)
2299 throw "bad n_sect in symbol table";
2301 _symbolsInSections
++;
2305 template <typename A
>
2306 void Parser
<A
>::appendAliasAtoms(uint8_t* p
)
2308 for (uint32_t i
=0; i
< this->_symbolCount
; ++i
) {
2309 const macho_nlist
<P
>& sym
= symbolFromIndex(i
);
2311 if ( (sym
.n_type() & N_STAB
) != 0 )
2314 // only look at N_INDR symbols
2315 if ( (sym
.n_type() & N_TYPE
) != N_INDR
)
2318 // skip non-external aliases
2319 if ( (sym
.n_type() & N_EXT
) == 0 )
2322 const char* symbolName
= this->nameFromSymbol(sym
);
2323 const char* aliasOfName
= &_strings
[sym
.n_value()];
2324 bool isHiddenVisibility
= (sym
.n_type() & N_PEXT
);
2325 AliasAtom
* allocatedSpace
= (AliasAtom
*)p
;
2326 new (allocatedSpace
) AliasAtom(symbolName
, isHiddenVisibility
, _file
, aliasOfName
);
2327 p
+= sizeof(AliasAtom
);
2333 template <typename A
>
2334 int Parser
<A
>::sectionIndexSorter(void* extra
, const void* l
, const void* r
)
2336 Parser
<A
>* parser
= (Parser
<A
>*)extra
;
2337 const uint32_t* left
= (uint32_t*)l
;
2338 const uint32_t* right
= (uint32_t*)r
;
2339 const macho_section
<P
>* leftSect
= parser
->machOSectionFromSectionIndex(*left
);
2340 const macho_section
<P
>* rightSect
= parser
->machOSectionFromSectionIndex(*right
);
2342 // can't just return difference because 64-bit diff does not fit in 32-bit return type
2343 int64_t result
= leftSect
->addr() - rightSect
->addr();
2344 if ( result
== 0 ) {
2345 // two sections with same start address
2346 // one with zero size goes first
2347 bool leftEmpty
= ( leftSect
->size() == 0 );
2348 bool rightEmpty
= ( rightSect
->size() == 0 );
2349 if ( leftEmpty
!= rightEmpty
) {
2350 return ( rightEmpty
? 1 : -1 );
2352 if ( !leftEmpty
&& !rightEmpty
)
2353 throwf("overlapping sections");
2354 // both empty, so chose file order
2355 return ( rightSect
- leftSect
);
2357 else if ( result
< 0 )
2363 template <typename A
>
2364 void Parser
<A
>::makeSortedSectionsArray(uint32_t array
[])
2366 const bool log
= false;
2369 fprintf(stderr
, "unsorted sections:\n");
2370 for(unsigned int i
=0; i
< _machOSectionsCount
; ++i
)
2371 fprintf(stderr
, "0x%08llX %s %s\n", _sectionsStart
[i
].addr(), _sectionsStart
[i
].segname(), _sectionsStart
[i
].sectname());
2374 // sort by symbol table address
2375 for (uint32_t i
=0; i
< _machOSectionsCount
; ++i
)
2377 ::qsort_r(array
, _machOSectionsCount
, sizeof(uint32_t), this, §ionIndexSorter
);
2380 fprintf(stderr
, "sorted sections:\n");
2381 for(unsigned int i
=0; i
< _machOSectionsCount
; ++i
)
2382 fprintf(stderr
, "0x%08llX %s %s\n", _sectionsStart
[array
[i
]].addr(), _sectionsStart
[array
[i
]].segname(), _sectionsStart
[array
[i
]].sectname());
2388 template <typename A
>
2389 int Parser
<A
>::symbolIndexSorter(void* extra
, const void* l
, const void* r
)
2391 ParserAndSectionsArray
* extraInfo
= (ParserAndSectionsArray
*)extra
;
2392 Parser
<A
>* parser
= extraInfo
->parser
;
2393 const uint32_t* sortedSectionsArray
= extraInfo
->sortedSectionsArray
;
2394 const uint32_t* left
= (uint32_t*)l
;
2395 const uint32_t* right
= (uint32_t*)r
;
2396 const macho_nlist
<P
>& leftSym
= parser
->symbolFromIndex(*left
);
2397 const macho_nlist
<P
>& rightSym
= parser
->symbolFromIndex(*right
);
2398 // can't just return difference because 64-bit diff does not fit in 32-bit return type
2399 int64_t result
= leftSym
.n_value() - rightSym
.n_value();
2400 if ( result
== 0 ) {
2401 // two symbols with same address
2402 // if in different sections, sort earlier section first
2403 if ( leftSym
.n_sect() != rightSym
.n_sect() ) {
2404 for (uint32_t i
=0; i
< parser
->machOSectionCount(); ++i
) {
2405 if ( sortedSectionsArray
[i
]+1 == leftSym
.n_sect() )
2407 if ( sortedSectionsArray
[i
]+1 == rightSym
.n_sect() )
2411 // two symbols in same section, means one is an alias
2412 // if one is ltmp*, make it an alias (sort first)
2413 const char* leftName
= parser
->nameFromSymbol(leftSym
);
2414 const char* rightName
= parser
->nameFromSymbol(rightSym
);
2415 bool leftIsTmp
= strncmp(leftName
, "ltmp", 4);
2416 bool rightIsTmp
= strncmp(rightName
, "ltmp", 4);
2417 if ( leftIsTmp
!= rightIsTmp
) {
2418 return (rightIsTmp
? -1 : 1);
2421 // if only one is global, make the other an alias (sort first)
2422 if ( (leftSym
.n_type() & N_EXT
) != (rightSym
.n_type() & N_EXT
) ) {
2423 if ( (rightSym
.n_type() & N_EXT
) != 0 )
2428 // if both are global, sort alphabetically. earlier one will be the alias
2429 return ( strcmp(rightName
, leftName
) );
2431 else if ( result
< 0 )
2438 template <typename A
>
2439 void Parser
<A
>::makeSortedSymbolsArray(uint32_t array
[], const uint32_t sectionArray
[])
2441 const bool log
= false;
2443 uint32_t* p
= array
;
2444 for (uint32_t i
=0; i
< this->_symbolCount
; ++i
) {
2445 const macho_nlist
<P
>& sym
= symbolFromIndex(i
);
2447 if ( (sym
.n_type() & N_STAB
) != 0 )
2450 // only look at definitions
2451 if ( (sym
.n_type() & N_TYPE
) != N_SECT
)
2454 // 'L' labels do not denote atom breaks
2455 const char* symbolName
= this->nameFromSymbol(sym
);
2456 if ( symbolName
[0] == 'L' )
2459 // how many def syms in each section
2460 if ( sym
.n_sect() > _machOSectionsCount
)
2461 throw "bad n_sect in symbol table";
2466 assert(p
== &array
[_symbolsInSections
] && "second pass over symbol table yield a different number of symbols");
2468 // sort by symbol table address
2469 ParserAndSectionsArray extra
= { this, sectionArray
};
2470 ::qsort_r(array
, _symbolsInSections
, sizeof(uint32_t), &extra
, &symbolIndexSorter
);
2473 // look for two symbols at same address
2474 _overlappingSymbols
= false;
2475 for (unsigned int i
=1; i
< _symbolsInSections
; ++i
) {
2476 if ( symbolFromIndex(array
[i
-1]).n_value() == symbolFromIndex(array
[i
]).n_value() ) {
2477 //fprintf(stderr, "overlapping symbols at 0x%08llX\n", symbolFromIndex(array[i-1]).n_value());
2478 _overlappingSymbols
= true;
2484 fprintf(stderr
, "sorted symbols:\n");
2485 for(unsigned int i
=0; i
< _symbolsInSections
; ++i
)
2486 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
])) );
2490 template <typename A
>
2491 void Parser
<A
>::makeSections()
2493 // classify each section by type
2494 // compute how many Section objects will be needed and total size for all
2495 unsigned int totalSectionsSize
= 0;
2496 uint8_t machOSectsStorage
[sizeof(MachOSectionAndSectionClass
<P
>)*(_machOSectionsCount
+2)]; // also room for tentative-defs and absolute symbols
2497 // allocate raw storage for all section objects on stack
2498 MachOSectionAndSectionClass
<P
>* machOSects
= (MachOSectionAndSectionClass
<P
>*)machOSectsStorage
;
2499 unsigned int count
= 0;
2500 // local variable for bitcode parsing
2501 const macho_section
<P
>* bitcodeSect
= NULL
;
2502 const macho_section
<P
>* cmdlineSect
= NULL
;
2503 const macho_section
<P
>* swiftCmdlineSect
= NULL
;
2504 const macho_section
<P
>* bundleSect
= NULL
;
2505 bool bitcodeAsm
= false;
2507 for (uint32_t i
=0; i
< _machOSectionsCount
; ++i
) {
2508 const macho_section
<P
>* sect
= &_sectionsStart
[i
];
2509 uint8_t sectionType
= (sect
->flags() & SECTION_TYPE
);
2510 if ( (sect
->offset() + sect
->size() > _fileLength
) && (sectionType
!= S_ZEROFILL
) && (sectionType
!= S_THREAD_LOCAL_ZEROFILL
) )
2511 throwf("section %s/%s extends beyond end of file,", sect
->segname(), sect
->sectname());
2513 if ( (sect
->flags() & S_ATTR_DEBUG
) != 0 ) {
2514 if ( strcmp(sect
->segname(), "__DWARF") == 0 ) {
2515 // note that .o file has dwarf
2516 _file
->_debugInfoKind
= ld::relocatable::File::kDebugInfoDwarf
;
2517 // save off iteresting dwarf sections
2518 if ( strcmp(sect
->sectname(), "__debug_info") == 0 )
2519 _file
->_dwarfDebugInfoSect
= sect
;
2520 else if ( strcmp(sect
->sectname(), "__debug_abbrev") == 0 )
2521 _file
->_dwarfDebugAbbrevSect
= sect
;
2522 else if ( strcmp(sect
->sectname(), "__debug_line") == 0 )
2523 _file
->_dwarfDebugLineSect
= sect
;
2524 else if ( strcmp(sect
->sectname(), "__debug_str") == 0 )
2525 _file
->_dwarfDebugStringSect
= sect
;
2526 // linker does not propagate dwarf sections to output file
2529 else if ( strcmp(sect
->segname(), "__LD") == 0 ) {
2530 if ( strncmp(sect
->sectname(), "__compact_unwind", 16) == 0 ) {
2531 machOSects
[count
].sect
= sect
;
2532 totalSectionsSize
+= sizeof(CUSection
<A
>);
2533 machOSects
[count
++].type
= sectionTypeCompactUnwind
;
2538 if ( strcmp(sect
->segname(), "__LLVM") == 0 ) {
2539 // Process bitcode segement
2540 if ( strncmp(sect
->sectname(), "__bitcode", 9) == 0 ) {
2542 } else if ( strncmp(sect
->sectname(), "__cmdline", 9) == 0 ) {
2544 } else if ( strncmp(sect
->sectname(), "__swift_cmdline", 15) == 0 ) {
2545 swiftCmdlineSect
= sect
;
2546 } else if ( strncmp(sect
->sectname(), "__bundle", 8) == 0 ) {
2548 } else if ( strncmp(sect
->sectname(), "__asm", 5) == 0 ) {
2551 // If treat the bitcode as data, continue to parse as a normal section.
2552 if ( !_treateBitcodeAsData
)
2555 // ignore empty __OBJC sections
2556 if ( (sect
->size() == 0) && (strcmp(sect
->segname(), "__OBJC") == 0) )
2558 // objc image info section is really attributes and not content
2559 if ( ((strcmp(sect
->sectname(), "__image_info") == 0) && (strcmp(sect
->segname(), "__OBJC") == 0))
2560 || ((strncmp(sect
->sectname(), "__objc_imageinfo", 16) == 0) && (strcmp(sect
->segname(), "__DATA") == 0)) ) {
2561 // struct objc_image_info {
2562 // uint32_t version; // initially 0
2565 // #define OBJC_IMAGE_SUPPORTS_GC 2
2566 // #define OBJC_IMAGE_GC_ONLY 4
2567 // #define OBJC_IMAGE_IS_SIMULATED 32
2568 // #define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES 64
2570 const uint32_t* contents
= (uint32_t*)(_file
->fileContent()+sect
->offset());
2571 if ( (sect
->size() >= 8) && (contents
[0] == 0) ) {
2572 uint32_t flags
= E::get32(contents
[1]);
2573 if ( (flags
& 4) == 4 )
2574 _file
->_objConstraint
= ld::File::objcConstraintGC
;
2575 else if ( (flags
& 2) == 2 )
2576 _file
->_objConstraint
= ld::File::objcConstraintRetainReleaseOrGC
;
2577 else if ( (flags
& 32) == 32 )
2578 _file
->_objConstraint
= ld::File::objcConstraintRetainReleaseForSimulator
;
2580 _file
->_objConstraint
= ld::File::objcConstraintRetainRelease
;
2581 _file
->_swiftVersion
= ((flags
>> 8) & 0xFF);
2582 _file
->_objcHasCategoryClassPropertiesField
= (flags
& 64);
2583 if ( sect
->size() > 8 ) {
2584 warning("section %s/%s has unexpectedly large size %llu in %s",
2585 sect
->segname(), Section
<A
>::makeSectionName(sect
), sect
->size(), _file
->path());
2589 warning("can't parse %s/%s section in %s", sect
->segname(), Section
<A
>::makeSectionName(sect
), _file
->path());
2593 machOSects
[count
].sect
= sect
;
2594 switch ( sect
->flags() & SECTION_TYPE
) {
2595 case S_SYMBOL_STUBS
:
2596 if ( _stubsSectionNum
== 0 ) {
2597 _stubsSectionNum
= i
+1;
2598 _stubsMachOSection
= sect
;
2601 assert(1 && "multiple S_SYMBOL_STUBS sections");
2602 case S_LAZY_SYMBOL_POINTERS
:
2604 case S_4BYTE_LITERALS
:
2605 totalSectionsSize
+= sizeof(Literal4Section
<A
>);
2606 machOSects
[count
++].type
= sectionTypeLiteral4
;
2608 case S_8BYTE_LITERALS
:
2609 totalSectionsSize
+= sizeof(Literal8Section
<A
>);
2610 machOSects
[count
++].type
= sectionTypeLiteral8
;
2612 case S_16BYTE_LITERALS
:
2613 totalSectionsSize
+= sizeof(Literal16Section
<A
>);
2614 machOSects
[count
++].type
= sectionTypeLiteral16
;
2616 case S_NON_LAZY_SYMBOL_POINTERS
:
2617 totalSectionsSize
+= sizeof(NonLazyPointerSection
<A
>);
2618 machOSects
[count
++].type
= sectionTypeNonLazy
;
2620 case S_THREAD_LOCAL_VARIABLE_POINTERS
:
2621 totalSectionsSize
+= sizeof(TLVPointerSection
<A
>);
2622 machOSects
[count
++].type
= sectionTypeTLVPointers
;
2624 case S_LITERAL_POINTERS
:
2625 if ( (strcmp(sect
->segname(), "__OBJC") == 0) && (strcmp(sect
->sectname(), "__cls_refs") == 0) ) {
2626 totalSectionsSize
+= sizeof(Objc1ClassReferences
<A
>);
2627 machOSects
[count
++].type
= sectionTypeObjC1ClassRefs
;
2630 totalSectionsSize
+= sizeof(PointerToCStringSection
<A
>);
2631 machOSects
[count
++].type
= sectionTypeCStringPointer
;
2634 case S_CSTRING_LITERALS
:
2635 totalSectionsSize
+= sizeof(CStringSection
<A
>);
2636 machOSects
[count
++].type
= sectionTypeCString
;
2638 case S_MOD_INIT_FUNC_POINTERS
:
2639 case S_MOD_TERM_FUNC_POINTERS
:
2640 case S_THREAD_LOCAL_INIT_FUNCTION_POINTERS
:
2645 case S_THREAD_LOCAL_REGULAR
:
2646 case S_THREAD_LOCAL_ZEROFILL
:
2647 if ( (strcmp(sect
->segname(), "__TEXT") == 0) && (strcmp(sect
->sectname(), "__eh_frame") == 0) ) {
2648 totalSectionsSize
+= sizeof(CFISection
<A
>);
2649 machOSects
[count
++].type
= sectionTypeCFI
;
2651 else if ( (strcmp(sect
->segname(), "__DATA") == 0) && (strcmp(sect
->sectname(), "__cfstring") == 0) ) {
2652 totalSectionsSize
+= sizeof(CFStringSection
<A
>);
2653 machOSects
[count
++].type
= sectionTypeCFString
;
2655 else if ( (strcmp(sect
->segname(), "__TEXT") == 0) && (strcmp(sect
->sectname(), "__ustring") == 0) ) {
2656 totalSectionsSize
+= sizeof(UTF16StringSection
<A
>);
2657 machOSects
[count
++].type
= sectionTypeUTF16Strings
;
2659 else if ( (strcmp(sect
->segname(), "__DATA") == 0) && (strncmp(sect
->sectname(), "__objc_classrefs", 16) == 0) ) {
2660 totalSectionsSize
+= sizeof(ObjC2ClassRefsSection
<A
>);
2661 machOSects
[count
++].type
= sectionTypeObjC2ClassRefs
;
2663 else if ( (strcmp(sect
->segname(), "__DATA") == 0) && (strcmp(sect
->sectname(), "__objc_catlist") == 0) ) {
2664 totalSectionsSize
+= sizeof(ObjC2CategoryListSection
<A
>);
2665 machOSects
[count
++].type
= typeObjC2CategoryList
;
2667 else if ( _AppleObjc
&& (strcmp(sect
->segname(), "__OBJC") == 0) && (strcmp(sect
->sectname(), "__class") == 0) ) {
2668 totalSectionsSize
+= sizeof(ObjC1ClassSection
<A
>);
2669 machOSects
[count
++].type
= sectionTypeObjC1Classes
;
2672 totalSectionsSize
+= sizeof(SymboledSection
<A
>);
2673 machOSects
[count
++].type
= sectionTypeSymboled
;
2676 case S_THREAD_LOCAL_VARIABLES
:
2677 totalSectionsSize
+= sizeof(TLVDefsSection
<A
>);
2678 machOSects
[count
++].type
= sectionTypeTLVDefs
;
2681 throwf("unknown section type %d", sect
->flags() & SECTION_TYPE
);
2686 if ( bitcodeSect
!= NULL
) {
2687 if ( cmdlineSect
!= NULL
)
2688 _file
->_bitcode
= std::unique_ptr
<ld::Bitcode
>(new ld::ClangBitcode(&_fileContent
[bitcodeSect
->offset()], bitcodeSect
->size(),
2689 &_fileContent
[cmdlineSect
->offset()], cmdlineSect
->size()));
2690 else if ( swiftCmdlineSect
!= NULL
)
2691 _file
->_bitcode
= std::unique_ptr
<ld::Bitcode
>(new ld::SwiftBitcode(&_fileContent
[bitcodeSect
->offset()], bitcodeSect
->size(),
2692 &_fileContent
[swiftCmdlineSect
->offset()], swiftCmdlineSect
->size()));
2694 throwf("Object file with bitcode missing cmdline options: %s", _file
->path());
2696 else if ( bundleSect
!= NULL
)
2697 _file
->_bitcode
= std::unique_ptr
<ld::Bitcode
>(new ld::BundleBitcode(&_fileContent
[bundleSect
->offset()], bundleSect
->size()));
2698 else if ( bitcodeAsm
)
2699 _file
->_bitcode
= std::unique_ptr
<ld::Bitcode
>(new ld::AsmBitcode(_fileContent
, _fileLength
));
2701 // sort by address (mach-o object files don't aways have sections sorted)
2702 ::qsort(machOSects
, count
, sizeof(MachOSectionAndSectionClass
<P
>), MachOSectionAndSectionClass
<P
>::sorter
);
2704 // we will synthesize a dummy Section<A> object for tentative definitions
2705 if ( _tentativeDefinitionCount
> 0 ) {
2706 totalSectionsSize
+= sizeof(TentativeDefinitionSection
<A
>);
2707 machOSects
[count
++].type
= sectionTypeTentativeDefinitions
;
2710 // we will synthesize a dummy Section<A> object for Absolute symbols
2711 if ( _absoluteSymbolCount
> 0 ) {
2712 totalSectionsSize
+= sizeof(AbsoluteSymbolSection
<A
>);
2713 machOSects
[count
++].type
= sectionTypeAbsoluteSymbols
;
2716 // allocate one block for all Section objects as well as pointers to each
2717 uint8_t* space
= new uint8_t[totalSectionsSize
+count
*sizeof(Section
<A
>*)];
2718 _file
->_sectionsArray
= (Section
<A
>**)space
;
2719 _file
->_sectionsArrayCount
= count
;
2720 Section
<A
>** objects
= _file
->_sectionsArray
;
2721 space
+= count
*sizeof(Section
<A
>*);
2722 for (uint32_t i
=0; i
< count
; ++i
) {
2723 switch ( machOSects
[i
].type
) {
2724 case sectionTypeIgnore
:
2726 case sectionTypeLiteral4
:
2727 *objects
++ = new (space
) Literal4Section
<A
>(*this, *_file
, machOSects
[i
].sect
);
2728 space
+= sizeof(Literal4Section
<A
>);
2730 case sectionTypeLiteral8
:
2731 *objects
++ = new (space
) Literal8Section
<A
>(*this, *_file
, machOSects
[i
].sect
);
2732 space
+= sizeof(Literal8Section
<A
>);
2734 case sectionTypeLiteral16
:
2735 *objects
++ = new (space
) Literal16Section
<A
>(*this, *_file
, machOSects
[i
].sect
);
2736 space
+= sizeof(Literal16Section
<A
>);
2738 case sectionTypeNonLazy
:
2739 *objects
++ = new (space
) NonLazyPointerSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2740 space
+= sizeof(NonLazyPointerSection
<A
>);
2742 case sectionTypeTLVPointers
:
2743 *objects
++ = new (space
) TLVPointerSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2744 space
+= sizeof(TLVPointerSection
<A
>);
2746 case sectionTypeCFI
:
2747 _EHFrameSection
= new (space
) CFISection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2748 *objects
++ = _EHFrameSection
;
2749 space
+= sizeof(CFISection
<A
>);
2751 case sectionTypeCString
:
2752 *objects
++ = new (space
) CStringSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2753 space
+= sizeof(CStringSection
<A
>);
2755 case sectionTypeCStringPointer
:
2756 *objects
++ = new (space
) PointerToCStringSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2757 space
+= sizeof(PointerToCStringSection
<A
>);
2759 case sectionTypeObjC1ClassRefs
:
2760 *objects
++ = new (space
) Objc1ClassReferences
<A
>(*this, *_file
, machOSects
[i
].sect
);
2761 space
+= sizeof(Objc1ClassReferences
<A
>);
2763 case sectionTypeUTF16Strings
:
2764 *objects
++ = new (space
) UTF16StringSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2765 space
+= sizeof(UTF16StringSection
<A
>);
2767 case sectionTypeCFString
:
2768 *objects
++ = new (space
) CFStringSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2769 space
+= sizeof(CFStringSection
<A
>);
2771 case sectionTypeObjC2ClassRefs
:
2772 *objects
++ = new (space
) ObjC2ClassRefsSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2773 space
+= sizeof(ObjC2ClassRefsSection
<A
>);
2775 case typeObjC2CategoryList
:
2776 *objects
++ = new (space
) ObjC2CategoryListSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2777 space
+= sizeof(ObjC2CategoryListSection
<A
>);
2779 case sectionTypeObjC1Classes
:
2780 *objects
++ = new (space
) ObjC1ClassSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2781 space
+= sizeof(ObjC1ClassSection
<A
>);
2783 case sectionTypeSymboled
:
2784 *objects
++ = new (space
) SymboledSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2785 space
+= sizeof(SymboledSection
<A
>);
2787 case sectionTypeTLVDefs
:
2788 *objects
++ = new (space
) TLVDefsSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2789 space
+= sizeof(TLVDefsSection
<A
>);
2791 case sectionTypeCompactUnwind
:
2792 _compactUnwindSection
= new (space
) CUSection
<A
>(*this, *_file
, machOSects
[i
].sect
);
2793 *objects
++ = _compactUnwindSection
;
2794 space
+= sizeof(CUSection
<A
>);
2796 case sectionTypeTentativeDefinitions
:
2797 *objects
++ = new (space
) TentativeDefinitionSection
<A
>(*this, *_file
);
2798 space
+= sizeof(TentativeDefinitionSection
<A
>);
2800 case sectionTypeAbsoluteSymbols
:
2801 _absoluteSection
= new (space
) AbsoluteSymbolSection
<A
>(*this, *_file
);
2802 *objects
++ = _absoluteSection
;
2803 space
+= sizeof(AbsoluteSymbolSection
<A
>);
2806 throw "internal error uknown SectionType";
2812 template <typename A
>
2813 Section
<A
>* Parser
<A
>::sectionForAddress(typename
A::P::uint_t addr
)
2815 for (uint32_t i
=0; i
< _file
->_sectionsArrayCount
; ++i
) {
2816 const macho_section
<typename
A::P
>* sect
= _file
->_sectionsArray
[i
]->machoSection();
2817 // TentativeDefinitionSection and AbsoluteSymbolSection have no mach-o section
2818 if ( sect
!= NULL
) {
2819 if ( (sect
->addr() <= addr
) && (addr
< (sect
->addr()+sect
->size())) ) {
2820 return _file
->_sectionsArray
[i
];
2824 // not strictly in any section
2825 // may be in a zero length section
2826 for (uint32_t i
=0; i
< _file
->_sectionsArrayCount
; ++i
) {
2827 const macho_section
<typename
A::P
>* sect
= _file
->_sectionsArray
[i
]->machoSection();
2828 // TentativeDefinitionSection and AbsoluteSymbolSection have no mach-o section
2829 if ( sect
!= NULL
) {
2830 if ( (sect
->addr() == addr
) && (sect
->size() == 0) ) {
2831 return _file
->_sectionsArray
[i
];
2836 throwf("sectionForAddress(0x%llX) address not in any section", (uint64_t)addr
);
2839 template <typename A
>
2840 Section
<A
>* Parser
<A
>::sectionForNum(unsigned int num
)
2842 for (uint32_t i
=0; i
< _file
->_sectionsArrayCount
; ++i
) {
2843 const macho_section
<typename
A::P
>* sect
= _file
->_sectionsArray
[i
]->machoSection();
2844 // TentativeDefinitionSection and AbsoluteSymbolSection have no mach-o section
2845 if ( sect
!= NULL
) {
2846 if ( num
== (unsigned int)((sect
- _sectionsStart
)+1) )
2847 return _file
->_sectionsArray
[i
];
2850 throwf("sectionForNum(%u) section number not for any section", num
);
2853 template <typename A
>
2854 Atom
<A
>* Parser
<A
>::findAtomByAddress(pint_t addr
)
2856 Section
<A
>* section
= this->sectionForAddress(addr
);
2857 return section
->findAtomByAddress(addr
);
2860 template <typename A
>
2861 Atom
<A
>* Parser
<A
>::findAtomByAddressOrNullIfStub(pint_t addr
)
2863 if ( hasStubsSection() && (_stubsMachOSection
->addr() <= addr
) && (addr
< (_stubsMachOSection
->addr()+_stubsMachOSection
->size())) )
2865 return findAtomByAddress(addr
);
2868 template <typename A
>
2869 Atom
<A
>* Parser
<A
>::findAtomByAddressOrLocalTargetOfStub(pint_t addr
, uint32_t* offsetInAtom
)
2871 if ( hasStubsSection() && (_stubsMachOSection
->addr() <= addr
) && (addr
< (_stubsMachOSection
->addr()+_stubsMachOSection
->size())) ) {
2872 // target is a stub, remove indirection
2873 uint32_t symbolIndex
= this->symbolIndexFromIndirectSectionAddress(addr
, _stubsMachOSection
);
2874 assert(symbolIndex
!= INDIRECT_SYMBOL_LOCAL
);
2875 const macho_nlist
<P
>& sym
= this->symbolFromIndex(symbolIndex
);
2876 // can't be to external weak symbol
2877 assert( (this->combineFromSymbol(sym
) != ld::Atom::combineByName
) || (this->scopeFromSymbol(sym
) != ld::Atom::scopeGlobal
) );
2879 return this->findAtomByName(this->nameFromSymbol(sym
));
2881 Atom
<A
>* target
= this->findAtomByAddress(addr
);
2882 *offsetInAtom
= addr
- target
->_objAddress
;
2886 template <typename A
>
2887 Atom
<A
>* Parser
<A
>::findAtomByName(const char* name
)
2889 uint8_t* p
= _file
->_atomsArray
;
2890 for(int i
=_file
->_atomsArrayCount
; i
> 0; --i
) {
2891 Atom
<A
>* atom
= (Atom
<A
>*)p
;
2892 if ( strcmp(name
, atom
->name()) == 0 )
2894 p
+= sizeof(Atom
<A
>);
2899 template <typename A
>
2900 void Parser
<A
>::findTargetFromAddress(pint_t addr
, TargetDesc
& target
)
2902 if ( hasStubsSection() && (_stubsMachOSection
->addr() <= addr
) && (addr
< (_stubsMachOSection
->addr()+_stubsMachOSection
->size())) ) {
2903 // target is a stub, remove indirection
2904 uint32_t symbolIndex
= this->symbolIndexFromIndirectSectionAddress(addr
, _stubsMachOSection
);
2905 assert(symbolIndex
!= INDIRECT_SYMBOL_LOCAL
);
2906 const macho_nlist
<P
>& sym
= this->symbolFromIndex(symbolIndex
);
2908 target
.name
= this->nameFromSymbol(sym
);
2909 target
.weakImport
= this->weakImportFromSymbol(sym
);
2913 Section
<A
>* section
= this->sectionForAddress(addr
);
2914 target
.atom
= section
->findAtomByAddress(addr
);
2915 target
.addend
= addr
- target
.atom
->_objAddress
;
2916 target
.weakImport
= false;
2920 template <typename A
>
2921 void Parser
<A
>::findTargetFromAddress(pint_t baseAddr
, pint_t addr
, TargetDesc
& target
)
2923 findTargetFromAddress(baseAddr
, target
);
2924 target
.addend
= addr
- target
.atom
->_objAddress
;
2927 template <typename A
>
2928 void Parser
<A
>::findTargetFromAddressAndSectionNum(pint_t addr
, unsigned int sectNum
, TargetDesc
& target
)
2930 if ( sectNum
== R_ABS
) {
2931 // target is absolute symbol that corresponds to addr
2932 if ( _absoluteSection
!= NULL
) {
2933 target
.atom
= _absoluteSection
->findAbsAtomForValue(addr
);
2934 if ( target
.atom
!= NULL
) {
2936 target
.weakImport
= false;
2941 throwf("R_ABS reloc but no absolute symbol at target address");
2944 if ( hasStubsSection() && (stubsSectionNum() == sectNum
) ) {
2945 // target is a stub, remove indirection
2946 uint32_t symbolIndex
= this->symbolIndexFromIndirectSectionAddress(addr
, _stubsMachOSection
);
2947 assert(symbolIndex
!= INDIRECT_SYMBOL_LOCAL
);
2948 const macho_nlist
<P
>& sym
= this->symbolFromIndex(symbolIndex
);
2949 // use direct reference when stub is to a static function
2950 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && (((sym
.n_type() & N_EXT
) == 0) || (this->nameFromSymbol(sym
)[0] == 'L')) ) {
2951 this->findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
2955 target
.name
= this->nameFromSymbol(sym
);
2956 target
.weakImport
= this->weakImportFromSymbol(sym
);
2961 Section
<A
>* section
= this->sectionForNum(sectNum
);
2962 target
.atom
= section
->findAtomByAddress(addr
);
2963 if ( target
.atom
== NULL
) {
2964 typedef typename
A::P::sint_t sint_t
;
2965 sint_t a
= (sint_t
)addr
;
2966 sint_t sectStart
= (sint_t
)(section
->machoSection()->addr());
2967 sint_t sectEnd
= sectStart
+ section
->machoSection()->size();
2968 if ( a
< sectStart
) {
2969 // target address is before start of section, so must be negative addend
2970 target
.atom
= section
->findAtomByAddress(sectStart
);
2971 target
.addend
= a
- sectStart
;
2972 target
.weakImport
= false;
2976 else if ( a
>= sectEnd
) {
2977 target
.atom
= section
->findAtomByAddress(sectEnd
-1);
2978 target
.addend
= a
- sectEnd
;
2979 target
.weakImport
= false;
2984 assert(target
.atom
!= NULL
);
2985 target
.addend
= addr
- target
.atom
->_objAddress
;
2986 target
.weakImport
= false;
2990 template <typename A
>
2991 void Parser
<A
>::addDtraceExtraInfos(const SourceLocation
& src
, const char* providerName
)
2993 // for every ___dtrace_stability$* and ___dtrace_typedefs$* undefine with
2994 // a matching provider name, add a by-name kDtraceTypeReference at probe site
2995 const char* dollar
= strchr(providerName
, '$');
2996 if ( dollar
!= NULL
) {
2997 int providerNameLen
= dollar
-providerName
+1;
2998 for ( std::vector
<const char*>::iterator it
= _dtraceProviderInfo
.begin(); it
!= _dtraceProviderInfo
.end(); ++it
) {
2999 const char* typeDollar
= strchr(*it
, '$');
3000 if ( typeDollar
!= NULL
) {
3001 if ( strncmp(typeDollar
+1, providerName
, providerNameLen
) == 0 ) {
3002 addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindDtraceExtra
,false, *it
);
3009 template <typename A
>
3010 const char* Parser
<A
>::scanSymbolTableForAddress(uint64_t addr
)
3012 uint64_t closestSymAddr
= 0;
3013 const char* closestSymName
= NULL
;
3014 for (uint32_t i
=0; i
< this->_symbolCount
; ++i
) {
3015 const macho_nlist
<P
>& sym
= symbolFromIndex(i
);
3017 if ( (sym
.n_type() & N_STAB
) != 0 )
3020 // only look at definitions
3021 if ( (sym
.n_type() & N_TYPE
) != N_SECT
)
3024 // return with exact match
3025 if ( sym
.n_value() == addr
) {
3026 const char* name
= nameFromSymbol(sym
);
3027 if ( strncmp(name
, "ltmp", 4) != 0 )
3029 // treat 'ltmp*' labels as close match
3030 closestSymAddr
= sym
.n_value();
3031 closestSymName
= name
;
3034 // record closest seen so far
3035 if ( (sym
.n_value() < addr
) && ((sym
.n_value() > closestSymAddr
) || (closestSymName
== NULL
)) )
3036 closestSymName
= nameFromSymbol(sym
);
3039 return (closestSymName
!= NULL
) ? closestSymName
: "unknown";
3043 template <typename A
>
3044 void Parser
<A
>::addFixups(const SourceLocation
& src
, ld::Fixup::Kind setKind
, const TargetDesc
& target
)
3046 // some fixup pairs can be combined
3047 ld::Fixup::Cluster cl
= ld::Fixup::k1of3
;
3048 ld::Fixup::Kind firstKind
= ld::Fixup::kindSetTargetAddress
;
3049 bool combined
= false;
3050 if ( target
.addend
== 0 ) {
3051 cl
= ld::Fixup::k1of1
;
3053 switch ( setKind
) {
3054 case ld::Fixup::kindStoreLittleEndian32
:
3055 firstKind
= ld::Fixup::kindStoreTargetAddressLittleEndian32
;
3057 case ld::Fixup::kindStoreLittleEndian64
:
3058 firstKind
= ld::Fixup::kindStoreTargetAddressLittleEndian64
;
3060 case ld::Fixup::kindStoreBigEndian32
:
3061 firstKind
= ld::Fixup::kindStoreTargetAddressBigEndian32
;
3063 case ld::Fixup::kindStoreBigEndian64
:
3064 firstKind
= ld::Fixup::kindStoreTargetAddressBigEndian64
;
3066 case ld::Fixup::kindStoreX86BranchPCRel32
:
3067 firstKind
= ld::Fixup::kindStoreTargetAddressX86BranchPCRel32
;
3069 case ld::Fixup::kindStoreX86PCRel32
:
3070 firstKind
= ld::Fixup::kindStoreTargetAddressX86PCRel32
;
3072 case ld::Fixup::kindStoreX86PCRel32GOTLoad
:
3073 firstKind
= ld::Fixup::kindStoreTargetAddressX86PCRel32GOTLoad
;
3075 case ld::Fixup::kindStoreX86PCRel32TLVLoad
:
3076 firstKind
= ld::Fixup::kindStoreTargetAddressX86PCRel32TLVLoad
;
3078 case ld::Fixup::kindStoreX86Abs32TLVLoad
:
3079 firstKind
= ld::Fixup::kindStoreTargetAddressX86Abs32TLVLoad
;
3081 case ld::Fixup::kindStoreARMBranch24
:
3082 firstKind
= ld::Fixup::kindStoreTargetAddressARMBranch24
;
3084 case ld::Fixup::kindStoreThumbBranch22
:
3085 firstKind
= ld::Fixup::kindStoreTargetAddressThumbBranch22
;
3087 #if SUPPORT_ARCH_arm64
3088 case ld::Fixup::kindStoreARM64Branch26
:
3089 firstKind
= ld::Fixup::kindStoreTargetAddressARM64Branch26
;
3091 case ld::Fixup::kindStoreARM64Page21
:
3092 firstKind
= ld::Fixup::kindStoreTargetAddressARM64Page21
;
3094 case ld::Fixup::kindStoreARM64PageOff12
:
3095 firstKind
= ld::Fixup::kindStoreTargetAddressARM64PageOff12
;
3097 case ld::Fixup::kindStoreARM64GOTLoadPage21
:
3098 firstKind
= ld::Fixup::kindStoreTargetAddressARM64GOTLoadPage21
;
3100 case ld::Fixup::kindStoreARM64GOTLoadPageOff12
:
3101 firstKind
= ld::Fixup::kindStoreTargetAddressARM64GOTLoadPageOff12
;
3103 case ld::Fixup::kindStoreARM64TLVPLoadPage21
:
3104 firstKind
= ld::Fixup::kindStoreTargetAddressARM64TLVPLoadPage21
;
3106 case ld::Fixup::kindStoreARM64TLVPLoadPageOff12
:
3107 firstKind
= ld::Fixup::kindStoreTargetAddressARM64TLVPLoadPageOff12
;
3112 cl
= ld::Fixup::k1of2
;
3117 if ( target
.atom
!= NULL
) {
3118 if ( target
.atom
->scope() == ld::Atom::scopeTranslationUnit
) {
3119 addFixup(src
, cl
, firstKind
, target
.atom
);
3121 else if ( (target
.atom
->combine() == ld::Atom::combineByNameAndContent
) || (target
.atom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
3122 addFixup(src
, cl
, firstKind
, ld::Fixup::bindingByContentBound
, target
.atom
);
3124 else if ( (src
.atom
->section().type() == ld::Section::typeCFString
) && (src
.offsetInAtom
!= 0) ) {
3125 // backing string in CFStrings should always be direct
3126 addFixup(src
, cl
, firstKind
, target
.atom
);
3128 else if ( (src
.atom
== target
.atom
) && (target
.atom
->combine() == ld::Atom::combineByName
) ) {
3129 // reference to self should always be direct
3130 addFixup(src
, cl
, firstKind
, target
.atom
);
3133 // change direct fixup to by-name fixup
3134 addFixup(src
, cl
, firstKind
, false, target
.atom
->name());
3138 addFixup(src
, cl
, firstKind
, target
.weakImport
, target
.name
);
3140 if ( target
.addend
== 0 ) {
3142 addFixup(src
, ld::Fixup::k2of2
, setKind
);
3145 addFixup(src
, ld::Fixup::k2of3
, ld::Fixup::kindAddAddend
, target
.addend
);
3146 addFixup(src
, ld::Fixup::k3of3
, setKind
);
3150 template <typename A
>
3151 void Parser
<A
>::addFixups(const SourceLocation
& src
, ld::Fixup::Kind kind
, const TargetDesc
& target
, const TargetDesc
& picBase
)
3153 ld::Fixup::Cluster cl
= (target
.addend
== 0) ? ld::Fixup::k1of4
: ld::Fixup::k1of5
;
3154 if ( target
.atom
!= NULL
) {
3155 if ( target
.atom
->scope() == ld::Atom::scopeTranslationUnit
) {
3156 addFixup(src
, cl
, ld::Fixup::kindSetTargetAddress
, target
.atom
);
3158 else if ( (target
.atom
->combine() == ld::Atom::combineByNameAndContent
) || (target
.atom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
3159 addFixup(src
, cl
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, target
.atom
);
3162 addFixup(src
, cl
, ld::Fixup::kindSetTargetAddress
, false, target
.atom
->name());
3166 addFixup(src
, cl
, ld::Fixup::kindSetTargetAddress
, target
.weakImport
, target
.name
);
3168 if ( target
.addend
== 0 ) {
3169 assert(picBase
.atom
!= NULL
);
3170 addFixup(src
, ld::Fixup::k2of4
, ld::Fixup::kindSubtractTargetAddress
, picBase
.atom
);
3171 addFixup(src
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractAddend
, picBase
.addend
);
3172 addFixup(src
, ld::Fixup::k4of4
, kind
);
3175 addFixup(src
, ld::Fixup::k2of5
, ld::Fixup::kindAddAddend
, target
.addend
);
3176 addFixup(src
, ld::Fixup::k3of5
, ld::Fixup::kindSubtractTargetAddress
, picBase
.atom
);
3177 addFixup(src
, ld::Fixup::k4of5
, ld::Fixup::kindSubtractAddend
, picBase
.addend
);
3178 addFixup(src
, ld::Fixup::k5of5
, kind
);
3184 template <typename A
>
3185 uint32_t TentativeDefinitionSection
<A
>::computeAtomCount(class Parser
<A
>& parser
,
3186 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
3187 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
3189 return parser
.tentativeDefinitionCount();
3192 template <typename A
>
3193 uint32_t TentativeDefinitionSection
<A
>::appendAtoms(class Parser
<A
>& parser
, uint8_t* p
,
3194 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
3195 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
3197 this->_beginAtoms
= (Atom
<A
>*)p
;
3199 for (uint32_t i
=parser
.undefinedStartIndex(); i
< parser
.undefinedEndIndex(); ++i
) {
3200 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(i
);
3201 if ( ((sym
.n_type() & N_TYPE
) == N_UNDF
) && (sym
.n_value() != 0) ) {
3202 uint64_t size
= sym
.n_value();
3203 uint8_t alignP2
= GET_COMM_ALIGN(sym
.n_desc());
3204 if ( alignP2
== 0 ) {
3205 // common symbols align to their size
3206 // that is, a 4-byte common aligns to 4-bytes
3207 // if this size is not a power of two,
3208 // then round up to the next power of two
3209 alignP2
= 63 - (uint8_t)__builtin_clzll(size
);
3210 if ( size
!= (1ULL << alignP2
) )
3212 // <rdar://problem/24871389> limit default alignment of large commons
3213 if ( alignP2
> parser
.maxDefaultCommonAlignment() )
3214 alignP2
= parser
.maxDefaultCommonAlignment();
3216 Atom
<A
>* allocatedSpace
= (Atom
<A
>*)p
;
3217 new (allocatedSpace
) Atom
<A
>(*this, parser
.nameFromSymbol(sym
), (pint_t
)ULLONG_MAX
, size
,
3218 ld::Atom::definitionTentative
, ld::Atom::combineByName
,
3219 parser
.scopeFromSymbol(sym
), ld::Atom::typeZeroFill
, ld::Atom::symbolTableIn
,
3220 parser
.dontDeadStripFromSymbol(sym
), false, false, ld::Atom::Alignment(alignP2
) );
3221 p
+= sizeof(Atom
<A
>);
3225 this->_endAtoms
= (Atom
<A
>*)p
;
3230 template <typename A
>
3231 uint32_t AbsoluteSymbolSection
<A
>::computeAtomCount(class Parser
<A
>& parser
,
3232 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
3233 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
3235 return parser
.absoluteSymbolCount();
3238 template <typename A
>
3239 uint32_t AbsoluteSymbolSection
<A
>::appendAtoms(class Parser
<A
>& parser
, uint8_t* p
,
3240 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
3241 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
3243 this->_beginAtoms
= (Atom
<A
>*)p
;
3245 for (uint32_t i
=0; i
< parser
.symbolCount(); ++i
) {
3246 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(i
);
3247 if ( (sym
.n_type() & N_TYPE
) != N_ABS
)
3249 const char* absName
= parser
.nameFromSymbol(sym
);
3250 // ignore .objc_class_name_* symbols
3251 if ( strncmp(absName
, ".objc_class_name_", 17) == 0 )
3253 // ignore .objc_class_name_* symbols
3254 if ( strncmp(absName
, ".objc_category_name_", 20) == 0 )
3256 // ignore empty *.eh symbols
3257 if ( strcmp(&absName
[strlen(absName
)-3], ".eh") == 0 )
3260 Atom
<A
>* allocatedSpace
= (Atom
<A
>*)p
;
3261 new (allocatedSpace
) Atom
<A
>(*this, parser
, sym
, 0);
3262 p
+= sizeof(Atom
<A
>);
3265 this->_endAtoms
= (Atom
<A
>*)p
;
3269 template <typename A
>
3270 Atom
<A
>* AbsoluteSymbolSection
<A
>::findAbsAtomForValue(typename
A::P::uint_t value
)
3272 Atom
<A
>* end
= this->_endAtoms
;
3273 for(Atom
<A
>* p
= this->_beginAtoms
; p
< end
; ++p
) {
3274 if ( p
->_objAddress
== value
)
3281 template <typename A
>
3282 uint32_t Parser
<A
>::indirectSymbol(uint32_t indirectIndex
)
3284 if ( indirectIndex
>= _indirectTableCount
)
3285 throw "indirect symbol index out of range";
3286 return E::get32(_indirectTable
[indirectIndex
]);
3289 template <typename A
>
3290 const macho_nlist
<typename
A::P
>& Parser
<A
>::symbolFromIndex(uint32_t index
)
3292 if ( index
> _symbolCount
)
3293 throw "symbol index out of range";
3294 return _symbols
[index
];
3297 template <typename A
>
3298 const macho_section
<typename
A::P
>* Parser
<A
>::machOSectionFromSectionIndex(uint32_t index
)
3300 if ( index
>= _machOSectionsCount
)
3301 throw "section index out of range";
3302 return &_sectionsStart
[index
];
3305 template <typename A
>
3306 uint32_t Parser
<A
>::symbolIndexFromIndirectSectionAddress(pint_t addr
, const macho_section
<P
>* sect
)
3308 uint32_t elementSize
= 0;
3309 switch ( sect
->flags() & SECTION_TYPE
) {
3310 case S_SYMBOL_STUBS
:
3311 elementSize
= sect
->reserved2();
3313 case S_LAZY_SYMBOL_POINTERS
:
3314 case S_NON_LAZY_SYMBOL_POINTERS
:
3315 case S_THREAD_LOCAL_VARIABLE_POINTERS
:
3316 elementSize
= sizeof(pint_t
);
3319 throw "section does not use indirect symbol table";
3321 uint32_t indexInSection
= (addr
- sect
->addr()) / elementSize
;
3322 uint32_t indexIntoIndirectTable
= sect
->reserved1() + indexInSection
;
3323 return this->indirectSymbol(indexIntoIndirectTable
);
3328 template <typename A
>
3329 const char* Parser
<A
>::nameFromSymbol(const macho_nlist
<P
>& sym
)
3331 return &_strings
[sym
.n_strx()];
3334 template <typename A
>
3335 ld::Atom::Scope Parser
<A
>::scopeFromSymbol(const macho_nlist
<P
>& sym
)
3337 if ( (sym
.n_type() & N_EXT
) == 0 )
3338 return ld::Atom::scopeTranslationUnit
;
3339 else if ( (sym
.n_type() & N_PEXT
) != 0 )
3340 return ld::Atom::scopeLinkageUnit
;
3341 else if ( this->nameFromSymbol(sym
)[0] == 'l' ) // since all 'l' symbols will be remove, don't make them global
3342 return ld::Atom::scopeLinkageUnit
;
3344 return ld::Atom::scopeGlobal
;
3347 template <typename A
>
3348 ld::Atom::Definition Parser
<A
>::definitionFromSymbol(const macho_nlist
<P
>& sym
)
3350 switch ( sym
.n_type() & N_TYPE
) {
3352 return ld::Atom::definitionAbsolute
;
3354 return ld::Atom::definitionRegular
;
3356 if ( sym
.n_value() != 0 )
3357 return ld::Atom::definitionTentative
;
3359 throw "definitionFromSymbol() bad symbol";
3362 template <typename A
>
3363 ld::Atom::Combine Parser
<A
>::combineFromSymbol(const macho_nlist
<P
>& sym
)
3365 if ( sym
.n_desc() & N_WEAK_DEF
)
3366 return ld::Atom::combineByName
;
3368 return ld::Atom::combineNever
;
3372 template <typename A
>
3373 ld::Atom::SymbolTableInclusion Parser
<A
>::inclusionFromSymbol(const macho_nlist
<P
>& sym
)
3375 const char* symbolName
= nameFromSymbol(sym
);
3376 // labels beginning with 'l' (lowercase ell) are automatically removed in final linked images <rdar://problem/4571042>
3377 // labels beginning with 'L' should have been stripped by the assembler, so are stripped now
3378 if ( sym
.n_desc() & REFERENCED_DYNAMICALLY
)
3379 return ld::Atom::symbolTableInAndNeverStrip
;
3380 else if ( symbolName
[0] == 'l' )
3381 return ld::Atom::symbolTableNotInFinalLinkedImages
;
3382 else if ( symbolName
[0] == 'L' )
3383 return ld::Atom::symbolTableNotIn
;
3385 return ld::Atom::symbolTableIn
;
3388 template <typename A
>
3389 bool Parser
<A
>::dontDeadStripFromSymbol(const macho_nlist
<P
>& sym
)
3391 return ( (sym
.n_desc() & (N_NO_DEAD_STRIP
|REFERENCED_DYNAMICALLY
)) != 0 );
3394 template <typename A
>
3395 bool Parser
<A
>::isThumbFromSymbol(const macho_nlist
<P
>& sym
)
3397 return ( sym
.n_desc() & N_ARM_THUMB_DEF
);
3400 template <typename A
>
3401 bool Parser
<A
>::weakImportFromSymbol(const macho_nlist
<P
>& sym
)
3403 return ( ((sym
.n_type() & N_TYPE
) == N_UNDF
) && ((sym
.n_desc() & N_WEAK_REF
) != 0) );
3406 template <typename A
>
3407 bool Parser
<A
>::resolverFromSymbol(const macho_nlist
<P
>& sym
)
3409 return ( sym
.n_desc() & N_SYMBOL_RESOLVER
);
3412 template <typename A
>
3413 bool Parser
<A
>::altEntryFromSymbol(const macho_nlist
<P
>& sym
)
3415 return ( sym
.n_desc() & N_ALT_ENTRY
);
3419 /* Skip over a LEB128 value (signed or unsigned). */
3421 skip_leb128 (const uint8_t ** offset
, const uint8_t * end
)
3423 while (*offset
!= end
&& **offset
>= 0x80)
3429 /* Read a ULEB128 into a 64-bit word. Return (uint64_t)-1 on overflow
3430 or error. On overflow, skip past the rest of the uleb128. */
3432 read_uleb128 (const uint8_t ** offset
, const uint8_t * end
)
3434 uint64_t result
= 0;
3441 return (uint64_t) -1;
3443 b
= **offset
& 0x7f;
3445 if (bit
>= 64 || b
<< bit
>> bit
!= b
)
3446 result
= (uint64_t) -1;
3448 result
|= b
<< bit
, bit
+= 7;
3449 } while (*(*offset
)++ >= 0x80);
3454 /* Skip over a DWARF attribute of form FORM. */
3455 template <typename A
>
3456 bool Parser
<A
>::skip_form(const uint8_t ** offset
, const uint8_t * end
, uint64_t form
,
3457 uint8_t addr_size
, bool dwarf64
)
3467 case DW_FORM_block2
:
3468 if (end
- *offset
< 2)
3470 sz
= 2 + A::P::E::get16(*(uint16_t*)offset
);
3473 case DW_FORM_block4
:
3474 if (end
- *offset
< 4)
3476 sz
= 2 + A::P::E::get32(*(uint32_t*)offset
);
3494 case DW_FORM_string
:
3495 while (*offset
!= end
&& **offset
)
3504 sz
= read_uleb128 (offset
, end
);
3507 case DW_FORM_block1
:
3515 case DW_FORM_ref_udata
:
3516 skip_leb128 (offset
, end
);
3520 case DW_FORM_ref_addr
:
3524 case DW_FORM_sec_offset
:
3525 sz
= sizeof(typename
A::P::uint_t
);
3528 case DW_FORM_exprloc
:
3529 sz
= read_uleb128 (offset
, end
);
3532 case DW_FORM_flag_present
:
3536 case DW_FORM_ref_sig8
:
3543 if (end
- *offset
< sz
)
3550 template <typename A
>
3551 const char* Parser
<A
>::getDwarfString(uint64_t form
, const uint8_t*& di
)
3554 const char* dwarfStrings
;
3555 const char* result
= NULL
;
3557 case DW_FORM_string
:
3558 result
= (const char*)di
;
3559 di
+= strlen(result
) + 1;
3562 offset
= E::get32(*((uint32_t*)di
));
3563 dwarfStrings
= (char*)_file
->fileContent() + _file
->_dwarfDebugStringSect
->offset();
3564 if ( offset
< _file
->_dwarfDebugStringSect
->size() )
3565 result
= &dwarfStrings
[offset
];
3567 warning("dwarf DW_FORM_strp (offset=0x%08X) is too big in %s", offset
, this->_path
);
3571 warning("unknown dwarf string encoding (form=%lld) in %s", form
, this->_path
);
3577 template <typename A
>
3578 uint64_t Parser
<A
>::getDwarfOffset(uint64_t form
, const uint8_t*& di
, bool dwarf64
)
3580 if ( form
== DW_FORM_sec_offset
)
3581 form
= (dwarf64
? DW_FORM_data8
: DW_FORM_data4
);
3582 uint64_t result
= -1;
3585 result
= A::P::E::get32(*(uint32_t*)di
);
3589 result
= A::P::E::get64(*(uint64_t*)di
);
3593 warning("unknown dwarf DW_FORM_ for DW_AT_stmt_list in %s", this->_path
);
3599 template <typename A
>
3600 struct AtomAndLineInfo
{
3602 ld::Atom::LineInfo info
;
3606 // <rdar://problem/5591394> Add support to ld64 for N_FUN stabs when used for symbolic constants
3607 // Returns whether a stabStr belonging to an N_FUN stab represents a
3608 // symbolic constant rather than a function
3609 template <typename A
>
3610 bool Parser
<A
>::isConstFunStabs(const char *stabStr
)
3613 // N_FUN can be used for both constants and for functions. In case it's a constant,
3614 // the format of the stabs string is "symname:c=<value>;"
3615 // ':' cannot appear in the symbol name, except if it's an Objective-C method
3616 // (in which case the symbol name starts with + or -, and then it's definitely
3618 return (stabStr
!= NULL
) && (stabStr
[0] != '+') && (stabStr
[0] != '-')
3619 && ((colon
= strchr(stabStr
, ':')) != NULL
)
3620 && (colon
[1] == 'c') && (colon
[2] == '=');
3624 template <typename A
>
3625 void Parser
<A
>::parseDebugInfo()
3627 // check for dwarf __debug_info section
3628 if ( _file
->_dwarfDebugInfoSect
== NULL
) {
3629 // if no DWARF debug info, look for stabs
3633 if ( _file
->_dwarfDebugInfoSect
->size() == 0 )
3639 if ( !read_comp_unit(&tuName
, &tuDir
, &stmtList
) ) {
3640 // if can't parse dwarf, warn and give up
3641 _file
->_dwarfTranslationUnitPath
= NULL
;
3642 warning("can't parse dwarf compilation unit info in %s", _path
);
3643 _file
->_debugInfoKind
= ld::relocatable::File::kDebugInfoNone
;
3646 if ( (tuName
!= NULL
) && (tuName
[0] == '/') ) {
3647 _file
->_dwarfTranslationUnitPath
= tuName
;
3649 else if ( (tuDir
!= NULL
) && (tuName
!= NULL
) ) {
3650 asprintf((char**)&(_file
->_dwarfTranslationUnitPath
), "%s/%s", tuDir
, tuName
);
3652 else if ( tuDir
== NULL
) {
3653 _file
->_dwarfTranslationUnitPath
= tuName
;
3656 _file
->_dwarfTranslationUnitPath
= NULL
;
3659 // add line number info to atoms from dwarf
3660 std::vector
<AtomAndLineInfo
<A
> > entries
;
3661 entries
.reserve(64);
3662 if ( _file
->_debugInfoKind
== ld::relocatable::File::kDebugInfoDwarf
) {
3663 // file with just data will have no __debug_line info
3664 if ( (_file
->_dwarfDebugLineSect
!= NULL
) && (_file
->_dwarfDebugLineSect
->size() != 0) ) {
3665 // validate stmt_list
3666 if ( (stmtList
!= (uint64_t)-1) && (stmtList
< _file
->_dwarfDebugLineSect
->size()) ) {
3667 const uint8_t* debug_line
= (uint8_t*)_file
->fileContent() + _file
->_dwarfDebugLineSect
->offset();
3668 struct line_reader_data
* lines
= line_open(&debug_line
[stmtList
],
3669 _file
->_dwarfDebugLineSect
->size() - stmtList
, E::little_endian
);
3670 struct line_info result
;
3671 Atom
<A
>* curAtom
= NULL
;
3672 uint32_t curAtomOffset
= 0;
3673 uint32_t curAtomAddress
= 0;
3674 uint32_t curAtomSize
= 0;
3675 std::map
<uint32_t,const char*> dwarfIndexToFile
;
3676 if ( lines
!= NULL
) {
3677 while ( line_next(lines
, &result
, line_stop_pc
) ) {
3678 //fprintf(stderr, "curAtom=%p, result.pc=0x%llX, result.line=%llu, result.end_of_sequence=%d,"
3679 // " curAtomAddress=0x%X, curAtomSize=0x%X\n",
3680 // curAtom, result.pc, result.line, result.end_of_sequence, curAtomAddress, curAtomSize);
3681 // work around weird debug line table compiler generates if no functions in __text section
3682 if ( (curAtom
== NULL
) && (result
.pc
== 0) && result
.end_of_sequence
&& (result
.file
== 1))
3684 // for performance, see if in next pc is in current atom
3685 if ( (curAtom
!= NULL
) && (curAtomAddress
<= result
.pc
) && (result
.pc
< (curAtomAddress
+curAtomSize
)) ) {
3686 curAtomOffset
= result
.pc
- curAtomAddress
;
3688 // or pc at end of current atom
3689 else if ( result
.end_of_sequence
&& (curAtom
!= NULL
) && (result
.pc
== (curAtomAddress
+curAtomSize
)) ) {
3690 curAtomOffset
= result
.pc
- curAtomAddress
;
3692 // or only one function that is a one line function
3693 else if ( result
.end_of_sequence
&& (curAtom
== NULL
) && (this->findAtomByAddress(0) != NULL
) && (result
.pc
== this->findAtomByAddress(0)->size()) ) {
3694 curAtom
= this->findAtomByAddress(0);
3695 curAtomOffset
= result
.pc
- curAtom
->objectAddress();
3696 curAtomAddress
= curAtom
->objectAddress();
3697 curAtomSize
= curAtom
->size();
3700 // do slow look up of atom by address
3702 curAtom
= this->findAtomByAddress(result
.pc
);
3705 // in case of bug in debug info, don't abort link, just limp on
3708 if ( curAtom
== NULL
)
3709 break; // file has line info but no functions
3710 if ( result
.end_of_sequence
&& (curAtomAddress
+curAtomSize
< result
.pc
) ) {
3711 // a one line function can be returned by line_next() as one entry with pc at end of blob
3712 // look for alt atom starting at end of previous atom
3713 uint32_t previousEnd
= curAtomAddress
+curAtomSize
;
3714 Atom
<A
>* alt
= this->findAtomByAddressOrNullIfStub(previousEnd
);
3716 continue; // ignore spurious debug info for stubs
3717 if ( result
.pc
<= alt
->objectAddress() + alt
->size() ) {
3719 curAtomOffset
= result
.pc
- alt
->objectAddress();
3720 curAtomAddress
= alt
->objectAddress();
3721 curAtomSize
= alt
->size();
3724 curAtomOffset
= result
.pc
- curAtom
->objectAddress();
3725 curAtomAddress
= curAtom
->objectAddress();
3726 curAtomSize
= curAtom
->size();
3730 curAtomOffset
= result
.pc
- curAtom
->objectAddress();
3731 curAtomAddress
= curAtom
->objectAddress();
3732 curAtomSize
= curAtom
->size();
3735 const char* filename
;
3736 std::map
<uint32_t,const char*>::iterator pos
= dwarfIndexToFile
.find(result
.file
);
3737 if ( pos
== dwarfIndexToFile
.end() ) {
3738 filename
= line_file(lines
, result
.file
);
3739 dwarfIndexToFile
[result
.file
] = filename
;
3742 filename
= pos
->second
;
3744 // only record for ~8000 line info records per function
3745 if ( curAtom
->roomForMoreLineInfoCount() ) {
3746 AtomAndLineInfo
<A
> entry
;
3747 entry
.atom
= curAtom
;
3748 entry
.info
.atomOffset
= curAtomOffset
;
3749 entry
.info
.fileName
= filename
;
3750 entry
.info
.lineNumber
= result
.line
;
3751 //fprintf(stderr, "addr=0x%08llX, line=%lld, file=%s, atom=%s, atom.size=0x%X, end=%d\n",
3752 // result.pc, result.line, filename, curAtom->name(), curAtomSize, result.end_of_sequence);
3753 entries
.push_back(entry
);
3754 curAtom
->incrementLineInfoCount();
3756 if ( result
.end_of_sequence
) {
3766 // assign line info start offset for each atom
3767 uint8_t* p
= _file
->_atomsArray
;
3768 uint32_t liOffset
= 0;
3769 for(int i
=_file
->_atomsArrayCount
; i
> 0; --i
) {
3770 Atom
<A
>* atom
= (Atom
<A
>*)p
;
3771 atom
->_lineInfoStartIndex
= liOffset
;
3772 liOffset
+= atom
->_lineInfoCount
;
3773 atom
->_lineInfoCount
= 0;
3774 p
+= sizeof(Atom
<A
>);
3776 assert(liOffset
== entries
.size());
3777 _file
->_lineInfos
.resize(liOffset
);
3779 // copy each line info for each atom
3780 for (typename
std::vector
<AtomAndLineInfo
<A
> >::iterator it
= entries
.begin(); it
!= entries
.end(); ++it
) {
3781 uint32_t slot
= it
->atom
->_lineInfoStartIndex
+ it
->atom
->_lineInfoCount
;
3782 _file
->_lineInfos
[slot
] = it
->info
;
3783 it
->atom
->_lineInfoCount
++;
3786 // done with temp vector
3790 template <typename A
>
3791 void Parser
<A
>::parseStabs()
3793 // scan symbol table for stabs entries
3794 Atom
<A
>* currentAtom
= NULL
;
3795 pint_t currentAtomAddress
= 0;
3796 enum { start
, inBeginEnd
, inFun
} state
= start
;
3797 for (uint32_t symbolIndex
= 0; symbolIndex
< _symbolCount
; ++symbolIndex
) {
3798 const macho_nlist
<P
>& sym
= this->symbolFromIndex(symbolIndex
);
3799 bool useStab
= true;
3800 uint8_t type
= sym
.n_type();
3801 const char* symString
= (sym
.n_strx() != 0) ? this->nameFromSymbol(sym
) : NULL
;
3802 if ( (type
& N_STAB
) != 0 ) {
3803 _file
->_debugInfoKind
= (_hasUUID
? ld::relocatable::File::kDebugInfoStabsUUID
: ld::relocatable::File::kDebugInfoStabs
);
3804 ld::relocatable::File::Stab stab
;
3807 stab
.other
= sym
.n_sect();
3808 stab
.desc
= sym
.n_desc();
3809 stab
.value
= sym
.n_value();
3815 // beginning of function block
3817 // fall into case to lookup atom by addresss
3820 currentAtomAddress
= sym
.n_value();
3821 currentAtom
= this->findAtomByAddress(currentAtomAddress
);
3822 if ( currentAtom
!= NULL
) {
3823 stab
.atom
= currentAtom
;
3824 stab
.string
= symString
;
3827 fprintf(stderr
, "can't find atom for stabs BNSYM at %08llX in %s",
3828 (uint64_t)sym
.n_value(), _path
);
3838 // not associated with an atom, just copy
3839 stab
.string
= symString
;
3843 // n_value field is NOT atom address ;-(
3844 // need to find atom by name match
3845 const char* colon
= strchr(symString
, ':');
3846 if ( colon
!= NULL
) {
3847 // build underscore leading name
3848 int nameLen
= colon
- symString
;
3849 char symName
[nameLen
+2];
3850 strlcpy(&symName
[1], symString
, nameLen
+1);
3852 symName
[nameLen
+1] = '\0';
3853 currentAtom
= this->findAtomByName(symName
);
3854 if ( currentAtom
!= NULL
) {
3855 stab
.atom
= currentAtom
;
3856 stab
.string
= symString
;
3860 // might be a debug-note without trailing :G()
3861 currentAtom
= this->findAtomByName(symString
);
3862 if ( currentAtom
!= NULL
) {
3863 stab
.atom
= currentAtom
;
3864 stab
.string
= symString
;
3867 if ( stab
.atom
== NULL
) {
3868 // ld_classic added bogus GSYM stabs for old style dtrace probes
3869 if ( (strncmp(symString
, "__dtrace_probe$", 15) != 0) )
3870 warning("can't find atom for N_GSYM stabs %s in %s", symString
, _path
);
3876 if ( isConstFunStabs(symString
) ) {
3877 // constant not associated with a function
3878 stab
.string
= symString
;
3881 // old style stabs without BNSYM
3883 currentAtomAddress
= sym
.n_value();
3884 currentAtom
= this->findAtomByAddress(currentAtomAddress
);
3885 if ( currentAtom
!= NULL
) {
3886 stab
.atom
= currentAtom
;
3887 stab
.string
= symString
;
3890 warning("can't find atom for stabs FUN at %08llX in %s",
3891 (uint64_t)currentAtomAddress
, _path
);
3897 stab
.string
= symString
;
3903 stab
.string
= symString
;
3904 // -gfull built .o file
3907 warning("unknown stabs type 0x%X in %s", type
, _path
);
3911 stab
.atom
= currentAtom
;
3920 Atom
<A
>* nestedAtom
= this->findAtomByAddress(sym
.n_value());
3921 if ( nestedAtom
!= NULL
) {
3922 stab
.atom
= nestedAtom
;
3923 stab
.string
= symString
;
3926 warning("can't find atom for stabs 0x%X at %08llX in %s",
3927 type
, (uint64_t)sym
.n_value(), _path
);
3934 // adjust value to be offset in atom
3935 stab
.value
-= currentAtomAddress
;
3937 stab
.string
= symString
;
3944 if ( isConstFunStabs(symString
) ) {
3945 stab
.atom
= currentAtom
;
3946 stab
.string
= symString
;
3949 if ( sym
.n_sect() != 0 ) {
3950 // found another start stab, must be really old stabs...
3951 currentAtomAddress
= sym
.n_value();
3952 currentAtom
= this->findAtomByAddress(currentAtomAddress
);
3953 if ( currentAtom
!= NULL
) {
3954 stab
.atom
= currentAtom
;
3955 stab
.string
= symString
;
3958 warning("can't find atom for stabs FUN at %08llX in %s",
3959 (uint64_t)currentAtomAddress
, _path
);
3963 // found ending stab, switch back to start state
3964 stab
.string
= symString
;
3965 stab
.atom
= currentAtom
;
3974 // adjust value to be offset in atom
3975 stab
.value
-= currentAtomAddress
;
3976 stab
.atom
= currentAtom
;
3979 stab
.string
= symString
;
3983 stab
.atom
= currentAtom
;
3984 stab
.string
= symString
;
3989 // add to list of stabs for this .o file
3991 _file
->_stabs
.push_back(stab
);
3998 // Look at the compilation unit DIE and determine
3999 // its NAME, compilation directory (in COMP_DIR) and its
4000 // line number information offset (in STMT_LIST). NAME and COMP_DIR
4001 // may be NULL (especially COMP_DIR) if they are not in the .o file;
4002 // STMT_LIST will be (uint64_t) -1.
4004 // At present this assumes that there's only one compilation unit DIE.
4006 template <typename A
>
4007 bool Parser
<A
>::read_comp_unit(const char ** name
, const char ** comp_dir
,
4008 uint64_t *stmt_list
)
4010 const uint8_t * debug_info
;
4011 const uint8_t * debug_abbrev
;
4013 const uint8_t * next_cu
;
4015 const uint8_t * end
;
4016 const uint8_t * enda
;
4019 uint64_t abbrev_base
;
4021 uint8_t address_size
;
4026 *stmt_list
= (uint64_t) -1;
4028 if ( (_file
->_dwarfDebugInfoSect
== NULL
) || (_file
->_dwarfDebugAbbrevSect
== NULL
) )
4031 if (_file
->_dwarfDebugInfoSect
->size() < 12)
4032 /* Too small to be a real debug_info section. */
4035 debug_info
= (uint8_t*)_file
->fileContent() + _file
->_dwarfDebugInfoSect
->offset();
4036 debug_abbrev
= (uint8_t*)_file
->fileContent() + _file
->_dwarfDebugAbbrevSect
->offset();
4037 next_cu
= debug_info
;
4039 while ((uint64_t)(next_cu
- debug_info
) < _file
->_dwarfDebugInfoSect
->size()) {
4041 sz
= A::P::E::get32(*(uint32_t*)di
);
4043 dwarf64
= sz
== 0xffffffff;
4045 sz
= A::P::E::get64(*(uint64_t*)di
), di
+= 8;
4046 else if (sz
> 0xffffff00)
4047 /* Unknown dwarf format. */
4050 /* Verify claimed size. */
4051 if (sz
+ (di
- debug_info
) > _file
->_dwarfDebugInfoSect
->size() || sz
<= (dwarf64
? 23 : 11))
4056 vers
= A::P::E::get16(*(uint16_t*)di
);
4057 if (vers
< 2 || vers
> 4)
4058 /* DWARF version wrong for this code.
4059 Chances are we could continue anyway, but we don't know for sure. */
4063 /* Find the debug_abbrev section. */
4064 abbrev_base
= dwarf64
? A::P::E::get64(*(uint64_t*)di
) : A::P::E::get32(*(uint32_t*)di
);
4065 di
+= dwarf64
? 8 : 4;
4067 if (abbrev_base
> _file
->_dwarfDebugAbbrevSect
->size())
4069 da
= debug_abbrev
+ abbrev_base
;
4070 enda
= debug_abbrev
+ _file
->_dwarfDebugAbbrevSect
->size();
4072 address_size
= *di
++;
4074 /* Find the abbrev number we're looking for. */
4076 abbrev
= read_uleb128 (&di
, end
);
4077 if (abbrev
== (uint64_t) -1)
4080 /* Skip through the debug_abbrev section looking for that abbrev. */
4083 uint64_t this_abbrev
= read_uleb128 (&da
, enda
);
4086 if (this_abbrev
== abbrev
)
4087 /* This is almost always taken. */
4089 skip_leb128 (&da
, enda
); /* Skip the tag. */
4092 da
++; /* Skip the DW_CHILDREN_* value. */
4095 attr
= read_uleb128 (&da
, enda
);
4096 skip_leb128 (&da
, enda
);
4097 } while (attr
!= 0 && attr
!= (uint64_t) -1);
4102 /* Check that the abbrev is one for a DW_TAG_compile_unit. */
4103 if (read_uleb128 (&da
, enda
) != DW_TAG_compile_unit
)
4107 da
++; /* Skip the DW_CHILDREN_* value. */
4109 /* Now, go through the DIE looking for DW_AT_name,
4110 DW_AT_comp_dir, and DW_AT_stmt_list. */
4111 bool skip_to_next_cu
= false;
4112 while (!skip_to_next_cu
) {
4114 uint64_t attr
= read_uleb128 (&da
, enda
);
4115 uint64_t form
= read_uleb128 (&da
, enda
);
4117 if (attr
== (uint64_t) -1)
4121 if (form
== DW_FORM_indirect
)
4122 form
= read_uleb128 (&di
, end
);
4126 *name
= getDwarfString(form
, di
);
4127 /* Swift object files may contain two CUs: One
4128 describes the Swift code, one is created by the
4129 clang importer. Skip over the CU created by the
4130 clang importer as it may be empty. */
4131 if (std::string(*name
) == "<swift-imported-modules>")
4132 skip_to_next_cu
= true;
4134 case DW_AT_comp_dir
:
4135 *comp_dir
= getDwarfString(form
, di
);
4137 case DW_AT_stmt_list
:
4138 *stmt_list
= getDwarfOffset(form
, di
, dwarf64
);
4141 if (! skip_form (&di
, end
, form
, address_size
, dwarf64
))
4151 template <typename A
>
4154 free(_sectionsArray
);
4158 template <typename A
>
4159 const char* File
<A
>::translationUnitSource() const
4161 return _dwarfTranslationUnitPath
;
4164 template <typename A
>
4165 bool File
<A
>::forEachAtom(ld::File::AtomHandler
& handler
) const
4167 handler
.doFile(*this);
4168 uint8_t* p
= _atomsArray
;
4169 for(int i
=_atomsArrayCount
; i
> 0; --i
) {
4170 handler
.doAtom(*((Atom
<A
>*)p
));
4171 p
+= sizeof(Atom
<A
>);
4173 p
= _aliasAtomsArray
;
4174 for(int i
=_aliasAtomsArrayCount
; i
> 0; --i
) {
4175 handler
.doAtom(*((AliasAtom
*)p
));
4176 p
+= sizeof(AliasAtom
);
4179 return (_atomsArrayCount
!= 0) || (_aliasAtomsArrayCount
!= 0);
4182 template <typename A
>
4183 const char* Section
<A
>::makeSegmentName(const macho_section
<typename
A::P
>* sect
)
4185 // mach-o section record only has room for 16-byte seg/sect names
4186 // so a 16-byte name has no trailing zero
4187 const char* name
= sect
->segname();
4188 if ( strlen(name
) < 16 )
4190 char* tmp
= new char[17];
4191 strlcpy(tmp
, name
, 17);
4195 template <typename A
>
4196 const char* Section
<A
>::makeSectionName(const macho_section
<typename
A::P
>* sect
)
4198 const char* name
= sect
->sectname();
4199 if ( strlen(name
) < 16 )
4202 // special case common long section names so we don't have to malloc
4203 if ( strncmp(sect
->sectname(), "__objc_classrefs", 16) == 0 )
4204 return "__objc_classrefs";
4205 if ( strncmp(sect
->sectname(), "__objc_classlist", 16) == 0 )
4206 return "__objc_classlist";
4207 if ( strncmp(sect
->sectname(), "__objc_nlclslist", 16) == 0 )
4208 return "__objc_nlclslist";
4209 if ( strncmp(sect
->sectname(), "__objc_nlcatlist", 16) == 0 )
4210 return "__objc_nlcatlist";
4211 if ( strncmp(sect
->sectname(), "__objc_protolist", 16) == 0 )
4212 return "__objc_protolist";
4213 if ( strncmp(sect
->sectname(), "__objc_protorefs", 16) == 0 )
4214 return "__objc_protorefs";
4215 if ( strncmp(sect
->sectname(), "__objc_superrefs", 16) == 0 )
4216 return "__objc_superrefs";
4217 if ( strncmp(sect
->sectname(), "__objc_imageinfo", 16) == 0 )
4218 return "__objc_imageinfo";
4219 if ( strncmp(sect
->sectname(), "__objc_stringobj", 16) == 0 )
4220 return "__objc_stringobj";
4221 if ( strncmp(sect
->sectname(), "__gcc_except_tab", 16) == 0 )
4222 return "__gcc_except_tab";
4224 char* tmp
= new char[17];
4225 strlcpy(tmp
, name
, 17);
4229 template <typename A
>
4230 bool Section
<A
>::readable(const macho_section
<typename
A::P
>* sect
)
4235 template <typename A
>
4236 bool Section
<A
>::writable(const macho_section
<typename
A::P
>* sect
)
4238 // mach-o .o files do not contain segment permissions
4239 // we just know TEXT is special
4240 return ( strcmp(sect
->segname(), "__TEXT") != 0 );
4243 template <typename A
>
4244 bool Section
<A
>::exectuable(const macho_section
<typename
A::P
>* sect
)
4246 // mach-o .o files do not contain segment permissions
4247 // we just know TEXT is special
4248 return ( strcmp(sect
->segname(), "__TEXT") == 0 );
4252 template <typename A
>
4253 ld::Section::Type Section
<A
>::sectionType(const macho_section
<typename
A::P
>* sect
)
4255 switch ( sect
->flags() & SECTION_TYPE
) {
4257 return ld::Section::typeZeroFill
;
4258 case S_CSTRING_LITERALS
:
4259 if ( (strcmp(sect
->sectname(), "__cstring") == 0) && (strcmp(sect
->segname(), "__TEXT") == 0) )
4260 return ld::Section::typeCString
;
4262 return ld::Section::typeNonStdCString
;
4263 case S_4BYTE_LITERALS
:
4264 return ld::Section::typeLiteral4
;
4265 case S_8BYTE_LITERALS
:
4266 return ld::Section::typeLiteral8
;
4267 case S_LITERAL_POINTERS
:
4268 return ld::Section::typeCStringPointer
;
4269 case S_NON_LAZY_SYMBOL_POINTERS
:
4270 return ld::Section::typeNonLazyPointer
;
4271 case S_LAZY_SYMBOL_POINTERS
:
4272 return ld::Section::typeLazyPointer
;
4273 case S_SYMBOL_STUBS
:
4274 return ld::Section::typeStub
;
4275 case S_MOD_INIT_FUNC_POINTERS
:
4276 return ld::Section::typeInitializerPointers
;
4277 case S_MOD_TERM_FUNC_POINTERS
:
4278 return ld::Section::typeTerminatorPointers
;
4280 return ld::Section::typeUnclassified
;
4281 case S_16BYTE_LITERALS
:
4282 return ld::Section::typeLiteral16
;
4285 if ( sect
->flags() & S_ATTR_PURE_INSTRUCTIONS
) {
4286 return ld::Section::typeCode
;
4288 else if ( strcmp(sect
->segname(), "__TEXT") == 0 ) {
4289 if ( strcmp(sect
->sectname(), "__eh_frame") == 0 )
4290 return ld::Section::typeCFI
;
4291 else if ( strcmp(sect
->sectname(), "__ustring") == 0 )
4292 return ld::Section::typeUTF16Strings
;
4293 else if ( strcmp(sect
->sectname(), "__textcoal_nt") == 0 )
4294 return ld::Section::typeCode
;
4295 else if ( strcmp(sect
->sectname(), "__StaticInit") == 0 )
4296 return ld::Section::typeCode
;
4297 else if ( strcmp(sect
->sectname(), "__constructor") == 0 )
4298 return ld::Section::typeInitializerPointers
;
4300 else if ( strcmp(sect
->segname(), "__DATA") == 0 ) {
4301 if ( strcmp(sect
->sectname(), "__cfstring") == 0 )
4302 return ld::Section::typeCFString
;
4303 else if ( strcmp(sect
->sectname(), "__dyld") == 0 )
4304 return ld::Section::typeDyldInfo
;
4305 else if ( strcmp(sect
->sectname(), "__program_vars") == 0 )
4306 return ld::Section::typeDyldInfo
;
4307 else if ( strncmp(sect
->sectname(), "__objc_classrefs", 16) == 0 )
4308 return ld::Section::typeObjCClassRefs
;
4309 else if ( strcmp(sect
->sectname(), "__objc_catlist") == 0 )
4310 return ld::Section::typeObjC2CategoryList
;
4312 else if ( strcmp(sect
->segname(), "__OBJC") == 0 ) {
4313 if ( strcmp(sect
->sectname(), "__class") == 0 )
4314 return ld::Section::typeObjC1Classes
;
4317 case S_THREAD_LOCAL_REGULAR
:
4318 return ld::Section::typeTLVInitialValues
;
4319 case S_THREAD_LOCAL_ZEROFILL
:
4320 return ld::Section::typeTLVZeroFill
;
4321 case S_THREAD_LOCAL_VARIABLES
:
4322 return ld::Section::typeTLVDefs
;
4323 case S_THREAD_LOCAL_VARIABLE_POINTERS
:
4324 return ld::Section::typeTLVPointers
;
4325 case S_THREAD_LOCAL_INIT_FUNCTION_POINTERS
:
4326 return ld::Section::typeTLVInitializerPointers
;
4328 return ld::Section::typeUnclassified
;
4332 template <typename A
>
4333 Atom
<A
>* Section
<A
>::findContentAtomByAddress(pint_t addr
, class Atom
<A
>* start
, class Atom
<A
>* end
)
4335 // do a binary search of atom array
4336 uint32_t atomCount
= end
- start
;
4337 Atom
<A
>* base
= start
;
4338 for (uint32_t n
= atomCount
; n
> 0; n
/= 2) {
4339 Atom
<A
>* pivot
= &base
[n
/2];
4340 pint_t atomStartAddr
= pivot
->_objAddress
;
4341 pint_t atomEndAddr
= atomStartAddr
+ pivot
->_size
;
4342 if ( atomStartAddr
<= addr
) {
4343 // address in normal atom
4344 if (addr
< atomEndAddr
)
4346 // address in "end" label (but not in alias)
4347 if ( (pivot
->_size
== 0) && (addr
== atomEndAddr
) && !pivot
->isAlias() )
4350 if ( addr
>= atomEndAddr
) {
4352 // move base to atom after pivot
4364 template <typename A
>
4365 ld::Atom::Alignment Section
<A
>::alignmentForAddress(pint_t addr
)
4367 const uint32_t sectionAlignment
= this->_machOSection
->align();
4368 uint32_t modulus
= (addr
% (1 << sectionAlignment
));
4369 if ( modulus
> 0xFFFF )
4370 warning("alignment for symbol at address 0x%08llX in %s exceeds 2^16", (uint64_t)addr
, this->file().path());
4371 return ld::Atom::Alignment(sectionAlignment
, modulus
);
4374 template <typename A
>
4375 uint32_t Section
<A
>::sectionNum(class Parser
<A
>& parser
) const
4377 if ( _machOSection
== NULL
)
4380 return 1 + (this->_machOSection
- parser
.firstMachOSection());
4383 // arm does not have zero cost exceptions
4385 uint32_t CFISection
<arm
>::cfiCount(Parser
<arm
>& parser
)
4387 if ( parser
.armUsesZeroCostExceptions() ) {
4388 // create ObjectAddressSpace object for use by libunwind
4389 OAS
oas(*this, (uint8_t*)this->file().fileContent()+this->_machOSection
->offset());
4390 return libunwind::CFI_Parser
<OAS
>::getCFICount(oas
,
4391 this->_machOSection
->addr(), this->_machOSection
->size());
4396 template <typename A
>
4397 uint32_t CFISection
<A
>::cfiCount(Parser
<A
>& parser
)
4399 // create ObjectAddressSpace object for use by libunwind
4400 OAS
oas(*this, (uint8_t*)this->file().fileContent()+this->_machOSection
->offset());
4401 return libunwind::CFI_Parser
<OAS
>::getCFICount(oas
,
4402 this->_machOSection
->addr(), this->_machOSection
->size());
4405 template <typename A
>
4406 void CFISection
<A
>::warnFunc(void* ref
, uint64_t funcAddr
, const char* msg
)
4408 Parser
<A
>* parser
= (Parser
<A
>*)ref
;
4409 if ( ! parser
->warnUnwindConversionProblems() )
4411 if ( funcAddr
!= CFI_INVALID_ADDRESS
) {
4412 // atoms are not constructed yet, so scan symbol table for labels
4413 const char* name
= parser
->scanSymbolTableForAddress(funcAddr
);
4414 warning("could not create compact unwind for %s: %s", name
, msg
);
4417 warning("could not create compact unwind: %s", msg
);
4422 bool CFISection
<x86_64
>::needsRelocating()
4428 bool CFISection
<arm64
>::needsRelocating()
4434 template <typename A
>
4435 bool CFISection
<A
>::needsRelocating()
4441 void CFISection
<x86_64
>::cfiParse(class Parser
<x86_64
>& parser
, uint8_t* buffer
,
4442 libunwind::CFI_Atom_Info
<CFISection
<x86_64
>::OAS
>::CFI_Atom_Info cfiArray
[],
4443 uint32_t& count
, const pint_t cuStarts
[], uint32_t cuCount
)
4445 const uint32_t sectionSize
= this->_machOSection
->size();
4446 // copy __eh_frame data to buffer
4447 memcpy(buffer
, file().fileContent() + this->_machOSection
->offset(), sectionSize
);
4449 // and apply relocations
4450 const macho_relocation_info
<P
>* relocs
= (macho_relocation_info
<P
>*)(file().fileContent() + this->_machOSection
->reloff());
4451 const macho_relocation_info
<P
>* relocsEnd
= &relocs
[this->_machOSection
->nreloc()];
4452 for (const macho_relocation_info
<P
>* reloc
= relocs
; reloc
< relocsEnd
; ++reloc
) {
4454 switch ( reloc
->r_type() ) {
4455 case X86_64_RELOC_SUBTRACTOR
:
4456 value
= 0 - parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
4458 if ( reloc
->r_extern() )
4459 value
+= parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
4461 case X86_64_RELOC_UNSIGNED
:
4462 value
= parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
4464 case X86_64_RELOC_GOT
:
4465 // this is used for the reference to the personality function in CIEs
4466 // store the symbol number of the personality function for later use as a Fixup
4467 value
= reloc
->r_symbolnum();
4470 fprintf(stderr
, "CFISection::cfiParse() unexpected relocation type at r_address=0x%08X\n", reloc
->r_address());
4473 if ( reloc
->r_address() > sectionSize
)
4474 throwf("malformed __eh_frame relocation, offset (0x%08X) is beyond end of section,", reloc
->r_address());
4477 switch ( reloc
->r_length() ) {
4479 p64
= (uint64_t*)&buffer
[reloc
->r_address()];
4480 E::set64(*p64
, value
+ E::get64(*p64
));
4483 p32
= (uint32_t*)&buffer
[reloc
->r_address()];
4484 E::set32(*p32
, value
+ E::get32(*p32
));
4487 fprintf(stderr
, "CFISection::cfiParse() unexpected relocation size at r_address=0x%08X\n", reloc
->r_address());
4492 // create ObjectAddressSpace object for use by libunwind
4493 OAS
oas(*this, buffer
);
4495 // use libuwind to parse __eh_frame data into array of CFI_Atom_Info
4497 msg
= libunwind::DwarfInstructions
<OAS
, libunwind::Registers_x86_64
>::parseCFIs(
4498 oas
, this->_machOSection
->addr(), this->_machOSection
->size(),
4499 cuStarts
, cuCount
, parser
.keepDwarfUnwind(), parser
.forceDwarfConversion(), parser
.neverConvertDwarf(),
4500 cfiArray
, count
, (void*)&parser
, warnFunc
);
4502 throwf("malformed __eh_frame section: %s", msg
);
4506 void CFISection
<x86
>::cfiParse(class Parser
<x86
>& parser
, uint8_t* buffer
,
4507 libunwind::CFI_Atom_Info
<CFISection
<x86
>::OAS
>::CFI_Atom_Info cfiArray
[],
4508 uint32_t& count
, const pint_t cuStarts
[], uint32_t cuCount
)
4510 // create ObjectAddressSpace object for use by libunwind
4511 OAS
oas(*this, (uint8_t*)this->file().fileContent()+this->_machOSection
->offset());
4513 // use libuwind to parse __eh_frame data into array of CFI_Atom_Info
4515 msg
= libunwind::DwarfInstructions
<OAS
, libunwind::Registers_x86
>::parseCFIs(
4516 oas
, this->_machOSection
->addr(), this->_machOSection
->size(),
4517 cuStarts
, cuCount
, parser
.keepDwarfUnwind(), parser
.forceDwarfConversion(), parser
.neverConvertDwarf(),
4518 cfiArray
, count
, (void*)&parser
, warnFunc
);
4520 throwf("malformed __eh_frame section: %s", msg
);
4527 void CFISection
<arm
>::cfiParse(class Parser
<arm
>& parser
, uint8_t* buffer
,
4528 libunwind::CFI_Atom_Info
<CFISection
<arm
>::OAS
>::CFI_Atom_Info cfiArray
[],
4529 uint32_t& count
, const pint_t cuStarts
[], uint32_t cuCount
)
4531 if ( !parser
.armUsesZeroCostExceptions() ) {
4532 // most arm do not use zero cost exceptions
4536 // create ObjectAddressSpace object for use by libunwind
4537 OAS
oas(*this, (uint8_t*)this->file().fileContent()+this->_machOSection
->offset());
4539 // use libuwind to parse __eh_frame data into array of CFI_Atom_Info
4541 msg
= libunwind::DwarfInstructions
<OAS
, libunwind::Registers_arm
>::parseCFIs(
4542 oas
, this->_machOSection
->addr(), this->_machOSection
->size(),
4543 cuStarts
, cuCount
, parser
.keepDwarfUnwind(), parser
.forceDwarfConversion(), parser
.neverConvertDwarf(),
4544 cfiArray
, count
, (void*)&parser
, warnFunc
);
4546 throwf("malformed __eh_frame section: %s", msg
);
4553 void CFISection
<arm64
>::cfiParse(class Parser
<arm64
>& parser
, uint8_t* buffer
,
4554 libunwind::CFI_Atom_Info
<CFISection
<arm64
>::OAS
>::CFI_Atom_Info cfiArray
[],
4555 uint32_t& count
, const pint_t cuStarts
[], uint32_t cuCount
)
4557 // copy __eh_frame data to buffer
4558 const uint32_t sectionSize
= this->_machOSection
->size();
4559 memcpy(buffer
, file().fileContent() + this->_machOSection
->offset(), sectionSize
);
4561 // and apply relocations
4562 const macho_relocation_info
<P
>* relocs
= (macho_relocation_info
<P
>*)(file().fileContent() + this->_machOSection
->reloff());
4563 const macho_relocation_info
<P
>* relocsEnd
= &relocs
[this->_machOSection
->nreloc()];
4564 for (const macho_relocation_info
<P
>* reloc
= relocs
; reloc
< relocsEnd
; ++reloc
) {
4565 uint64_t* p64
= (uint64_t*)&buffer
[reloc
->r_address()];
4566 uint32_t* p32
= (uint32_t*)&buffer
[reloc
->r_address()];
4567 uint32_t addend32
= E::get32(*p32
);
4568 uint64_t addend64
= E::get64(*p64
);
4570 switch ( reloc
->r_type() ) {
4571 case ARM64_RELOC_SUBTRACTOR
:
4572 value
= 0 - parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
4574 if ( reloc
->r_extern() )
4575 value
+= parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
4577 case ARM64_RELOC_UNSIGNED
:
4578 value
= parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
4580 case ARM64_RELOC_POINTER_TO_GOT
:
4581 // this is used for the reference to the personality function in CIEs
4582 // store the symbol number of the personality function for later use as a Fixup
4583 value
= reloc
->r_symbolnum();
4588 fprintf(stderr
, "CFISection::cfiParse() unexpected relocation type at r_address=0x%08X\n", reloc
->r_address());
4591 if ( reloc
->r_address() > sectionSize
)
4592 throwf("malformed __eh_frame relocation, offset (0x%08X) is beyond end of section,", reloc
->r_address());
4593 switch ( reloc
->r_length() ) {
4595 E::set64(*p64
, value
+ addend64
);
4598 E::set32(*p32
, value
+ addend32
);
4601 fprintf(stderr
, "CFISection::cfiParse() unexpected relocation size at r_address=0x%08X\n", reloc
->r_address());
4607 // create ObjectAddressSpace object for use by libunwind
4608 OAS
oas(*this, buffer
);
4610 // use libuwind to parse __eh_frame data into array of CFI_Atom_Info
4612 msg
= libunwind::DwarfInstructions
<OAS
, libunwind::Registers_arm64
>::parseCFIs(
4613 oas
, this->_machOSection
->addr(), this->_machOSection
->size(),
4614 cuStarts
, cuCount
, parser
.keepDwarfUnwind(), parser
.forceDwarfConversion(), parser
.neverConvertDwarf(),
4615 cfiArray
, count
, (void*)&parser
, warnFunc
);
4617 throwf("malformed __eh_frame section: %s", msg
);
4621 template <typename A
>
4622 uint32_t CFISection
<A
>::computeAtomCount(class Parser
<A
>& parser
,
4623 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
4624 const struct Parser
<A
>::CFI_CU_InfoArrays
& cfis
)
4626 return cfis
.cfiCount
;
4631 template <typename A
>
4632 uint32_t CFISection
<A
>::appendAtoms(class Parser
<A
>& parser
, uint8_t* p
,
4633 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
4634 const struct Parser
<A
>::CFI_CU_InfoArrays
& cfis
)
4636 this->_beginAtoms
= (Atom
<A
>*)p
;
4637 // walk CFI_Atom_Info array and create atom for each entry
4638 const CFI_Atom_Info
* start
= &cfis
.cfiArray
[0];
4639 const CFI_Atom_Info
* end
= &cfis
.cfiArray
[cfis
.cfiCount
];
4640 for(const CFI_Atom_Info
* a
=start
; a
< end
; ++a
) {
4641 Atom
<A
>* space
= (Atom
<A
>*)p
;
4642 new (space
) Atom
<A
>(*this, (a
->isCIE
? "CIE" : "FDE"), a
->address
, a
->size
,
4643 ld::Atom::definitionRegular
, ld::Atom::combineNever
, ld::Atom::scopeTranslationUnit
,
4644 ld::Atom::typeCFI
, ld::Atom::symbolTableNotInFinalLinkedImages
,
4645 false, false, false, ld::Atom::Alignment(0));
4646 p
+= sizeof(Atom
<A
>);
4648 this->_endAtoms
= (Atom
<A
>*)p
;
4649 return cfis
.cfiCount
;
4653 template <> bool CFISection
<x86_64
>::bigEndian() { return false; }
4654 template <> bool CFISection
<x86
>::bigEndian() { return false; }
4655 template <> bool CFISection
<arm
>::bigEndian() { return false; }
4656 template <> bool CFISection
<arm64
>::bigEndian() { return false; }
4659 void CFISection
<x86_64
>::addCiePersonalityFixups(class Parser
<x86_64
>& parser
, const CFI_Atom_Info
* cieInfo
)
4661 uint8_t personalityEncoding
= cieInfo
->u
.cieInfo
.personality
.encodingOfTargetAddress
;
4662 if ( personalityEncoding
== 0x9B ) {
4663 // compiler always produces X86_64_RELOC_GOT with addend of 4 to personality function
4664 // CFISection<x86_64>::cfiParse() set targetAddress to be symbolIndex + 4 + addressInCIE
4665 uint32_t symbolIndex
= cieInfo
->u
.cieInfo
.personality
.targetAddress
- 4
4666 - cieInfo
->address
- cieInfo
->u
.cieInfo
.personality
.offsetInCFI
;
4667 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(symbolIndex
);
4668 const char* personalityName
= parser
.nameFromSymbol(sym
);
4670 Atom
<x86_64
>* cieAtom
= this->findAtomByAddress(cieInfo
->address
);
4671 Parser
<x86_64
>::SourceLocation
src(cieAtom
, cieInfo
->u
.cieInfo
.personality
.offsetInCFI
);
4672 parser
.addFixup(src
, ld::Fixup::k1of3
, ld::Fixup::kindSetTargetAddress
, false, personalityName
);
4673 parser
.addFixup(src
, ld::Fixup::k2of3
, ld::Fixup::kindAddAddend
, 4);
4674 parser
.addFixup(src
, ld::Fixup::k3of3
, ld::Fixup::kindStoreX86PCRel32GOT
);
4676 else if ( personalityEncoding
!= 0 ) {
4677 throwf("unsupported address encoding (%02X) of personality function in CIE",
4678 personalityEncoding
);
4683 void CFISection
<x86
>::addCiePersonalityFixups(class Parser
<x86
>& parser
, const CFI_Atom_Info
* cieInfo
)
4685 uint8_t personalityEncoding
= cieInfo
->u
.cieInfo
.personality
.encodingOfTargetAddress
;
4686 if ( (personalityEncoding
== 0x9B) || (personalityEncoding
== 0x90) ) {
4687 uint32_t offsetInCFI
= cieInfo
->u
.cieInfo
.personality
.offsetInCFI
;
4688 uint32_t nlpAddr
= cieInfo
->u
.cieInfo
.personality
.targetAddress
;
4689 Atom
<x86
>* cieAtom
= this->findAtomByAddress(cieInfo
->address
);
4690 Atom
<x86
>* nlpAtom
= parser
.findAtomByAddress(nlpAddr
);
4691 assert(nlpAtom
->contentType() == ld::Atom::typeNonLazyPointer
);
4692 Parser
<x86
>::SourceLocation
src(cieAtom
, cieInfo
->u
.cieInfo
.personality
.offsetInCFI
);
4694 parser
.addFixup(src
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, nlpAtom
);
4695 parser
.addFixup(src
, ld::Fixup::k2of4
, ld::Fixup::kindSubtractTargetAddress
, cieAtom
);
4696 parser
.addFixup(src
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractAddend
, offsetInCFI
);
4697 parser
.addFixup(src
, ld::Fixup::k4of4
, ld::Fixup::kindStoreLittleEndian32
);
4699 else if ( personalityEncoding
!= 0 ) {
4700 throwf("unsupported address encoding (%02X) of personality function in CIE", personalityEncoding
);
4704 #if SUPPORT_ARCH_arm64
4706 void CFISection
<arm64
>::addCiePersonalityFixups(class Parser
<arm64
>& parser
, const CFI_Atom_Info
* cieInfo
)
4708 uint8_t personalityEncoding
= cieInfo
->u
.cieInfo
.personality
.encodingOfTargetAddress
;
4709 if ( personalityEncoding
== 0x9B ) {
4710 // compiler always produces ARM64_RELOC_GOT r_pcrel=1 to personality function
4711 // CFISection<arm64>::cfiParse() set targetAddress to be symbolIndex + addressInCIE
4712 uint32_t symbolIndex
= cieInfo
->u
.cieInfo
.personality
.targetAddress
4713 - cieInfo
->address
- cieInfo
->u
.cieInfo
.personality
.offsetInCFI
;
4714 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(symbolIndex
);
4715 const char* personalityName
= parser
.nameFromSymbol(sym
);
4717 Atom
<arm64
>* cieAtom
= this->findAtomByAddress(cieInfo
->address
);
4718 Parser
<arm64
>::SourceLocation
src(cieAtom
, cieInfo
->u
.cieInfo
.personality
.offsetInCFI
);
4719 parser
.addFixup(src
, ld::Fixup::k1of2
, ld::Fixup::kindSetTargetAddress
, false, personalityName
);
4720 parser
.addFixup(src
, ld::Fixup::k2of2
, ld::Fixup::kindStoreARM64PCRelToGOT
);
4722 else if ( personalityEncoding
!= 0 ) {
4723 throwf("unsupported address encoding (%02X) of personality function in CIE",
4724 personalityEncoding
);
4731 void CFISection
<arm
>::addCiePersonalityFixups(class Parser
<arm
>& parser
, const CFI_Atom_Info
* cieInfo
)
4733 uint8_t personalityEncoding
= cieInfo
->u
.cieInfo
.personality
.encodingOfTargetAddress
;
4734 if ( (personalityEncoding
== 0x9B) || (personalityEncoding
== 0x90) ) {
4735 uint32_t offsetInCFI
= cieInfo
->u
.cieInfo
.personality
.offsetInCFI
;
4736 uint32_t nlpAddr
= cieInfo
->u
.cieInfo
.personality
.targetAddress
;
4737 Atom
<arm
>* cieAtom
= this->findAtomByAddress(cieInfo
->address
);
4738 Atom
<arm
>* nlpAtom
= parser
.findAtomByAddress(nlpAddr
);
4739 assert(nlpAtom
->contentType() == ld::Atom::typeNonLazyPointer
);
4740 Parser
<arm
>::SourceLocation
src(cieAtom
, cieInfo
->u
.cieInfo
.personality
.offsetInCFI
);
4742 parser
.addFixup(src
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, nlpAtom
);
4743 parser
.addFixup(src
, ld::Fixup::k2of4
, ld::Fixup::kindSubtractTargetAddress
, cieAtom
);
4744 parser
.addFixup(src
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractAddend
, offsetInCFI
);
4745 parser
.addFixup(src
, ld::Fixup::k4of4
, ld::Fixup::kindStoreLittleEndian32
);
4747 else if ( personalityEncoding
!= 0 ) {
4748 throwf("unsupported address encoding (%02X) of personality function in CIE", personalityEncoding
);
4754 template <typename A
>
4755 void CFISection
<A
>::addCiePersonalityFixups(class Parser
<A
>& parser
, const CFI_Atom_Info
* cieInfo
)
4757 assert(0 && "addCiePersonalityFixups() not implemented for arch");
4760 template <typename A
>
4761 void CFISection
<A
>::makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
& cfis
)
4763 ld::Fixup::Kind store32
= bigEndian() ? ld::Fixup::kindStoreBigEndian32
: ld::Fixup::kindStoreLittleEndian32
;
4764 ld::Fixup::Kind store64
= bigEndian() ? ld::Fixup::kindStoreBigEndian64
: ld::Fixup::kindStoreLittleEndian64
;
4766 // add all references for FDEs, including implicit group references
4767 const CFI_Atom_Info
* end
= &cfis
.cfiArray
[cfis
.cfiCount
];
4768 for(const CFI_Atom_Info
* p
= &cfis
.cfiArray
[0]; p
< end
; ++p
) {
4770 // add reference to personality function if used
4771 if ( p
->u
.cieInfo
.personality
.targetAddress
!= CFI_INVALID_ADDRESS
) {
4772 this->addCiePersonalityFixups(parser
, p
);
4777 Atom
<A
>* fdeAtom
= this->findAtomByAddress(p
->address
);
4778 // find function Atom
4779 Atom
<A
>* functionAtom
= parser
.findAtomByAddress(p
->u
.fdeInfo
.function
.targetAddress
);
4781 Atom
<A
>* cieAtom
= this->findAtomByAddress(p
->u
.fdeInfo
.cie
.targetAddress
);
4783 Atom
<A
>* lsdaAtom
= NULL
;
4784 if ( p
->u
.fdeInfo
.lsda
.targetAddress
!= CFI_INVALID_ADDRESS
) {
4785 lsdaAtom
= parser
.findAtomByAddress(p
->u
.fdeInfo
.lsda
.targetAddress
);
4787 // add reference from FDE to CIE (always 32-bit pc-rel)
4788 typename Parser
<A
>::SourceLocation
fdeToCieSrc(fdeAtom
, p
->u
.fdeInfo
.cie
.offsetInCFI
);
4789 parser
.addFixup(fdeToCieSrc
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, fdeAtom
);
4790 parser
.addFixup(fdeToCieSrc
, ld::Fixup::k2of4
, ld::Fixup::kindAddAddend
, p
->u
.fdeInfo
.cie
.offsetInCFI
);
4791 parser
.addFixup(fdeToCieSrc
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractTargetAddress
, cieAtom
);
4792 parser
.addFixup(fdeToCieSrc
, ld::Fixup::k4of4
, store32
, cieAtom
);
4794 // add reference from FDE to function
4795 typename Parser
<A
>::SourceLocation
fdeToFuncSrc(fdeAtom
, p
->u
.fdeInfo
.function
.offsetInCFI
);
4796 switch (p
->u
.fdeInfo
.function
.encodingOfTargetAddress
) {
4797 case DW_EH_PE_pcrel
|DW_EH_PE_ptr
:
4798 if ( sizeof(typename
A::P::uint_t
) == 8 ) {
4799 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, functionAtom
);
4800 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k2of4
, ld::Fixup::kindSubtractTargetAddress
, fdeAtom
);
4801 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractAddend
, p
->u
.fdeInfo
.function
.offsetInCFI
);
4802 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k4of4
, store64
);
4805 // else fall into 32-bit case
4806 case DW_EH_PE_pcrel
|DW_EH_PE_sdata4
:
4807 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, functionAtom
);
4808 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k2of4
, ld::Fixup::kindSubtractTargetAddress
, fdeAtom
);
4809 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractAddend
, p
->u
.fdeInfo
.function
.offsetInCFI
);
4810 parser
.addFixup(fdeToFuncSrc
, ld::Fixup::k4of4
, store32
);
4813 throw "unsupported encoding in FDE of pointer to function";
4816 // add reference from FDE to LSDA
4817 typename Parser
<A
>::SourceLocation
fdeToLsdaSrc(fdeAtom
, p
->u
.fdeInfo
.lsda
.offsetInCFI
);
4818 if ( lsdaAtom
!= NULL
) {
4819 switch (p
->u
.fdeInfo
.lsda
.encodingOfTargetAddress
) {
4820 case DW_EH_PE_pcrel
|DW_EH_PE_ptr
:
4821 if ( sizeof(typename
A::P::uint_t
) == 8 ) {
4822 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, lsdaAtom
);
4823 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k2of4
, ld::Fixup::kindSubtractTargetAddress
, fdeAtom
);
4824 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractAddend
, p
->u
.fdeInfo
.lsda
.offsetInCFI
);
4825 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k4of4
, store64
);
4828 // else fall into 32-bit case
4829 case DW_EH_PE_pcrel
|DW_EH_PE_sdata4
:
4830 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, lsdaAtom
);
4831 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k2of4
, ld::Fixup::kindSubtractTargetAddress
, fdeAtom
);
4832 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractAddend
, p
->u
.fdeInfo
.lsda
.offsetInCFI
);
4833 parser
.addFixup(fdeToLsdaSrc
, ld::Fixup::k4of4
, store32
);
4836 throw "unsupported encoding in FDE of pointer to LSDA";
4840 // FDE is in group lead by function atom
4841 typename Parser
<A
>::SourceLocation
fdeSrc(functionAtom
,0);
4842 parser
.addFixup(fdeSrc
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinateFDE
, fdeAtom
);
4844 // LSDA is in group lead by function atom
4845 if ( lsdaAtom
!= NULL
) {
4846 parser
.addFixup(fdeSrc
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinateLSDA
, lsdaAtom
);
4855 template <typename A
>
4856 const void* CFISection
<A
>::OAS::mappedAddress(pint_t addr
)
4858 if ( (_ehFrameStartAddr
<= addr
) && (addr
< _ehFrameEndAddr
) )
4859 return &_ehFrameContent
[addr
-_ehFrameStartAddr
];
4861 // requested bytes are not in __eh_frame section
4862 // this can occur when examining the instruction bytes in the __text
4863 File
<A
>& file
= _ehFrameSection
.file();
4864 for (uint32_t i
=0; i
< file
._sectionsArrayCount
; ++i
) {
4865 const macho_section
<typename
A::P
>* sect
= file
._sectionsArray
[i
]->machoSection();
4866 // TentativeDefinitionSection and AbsoluteSymbolSection have no mach-o section
4867 if ( sect
!= NULL
) {
4868 if ( (sect
->addr() <= addr
) && (addr
< (sect
->addr()+sect
->size())) ) {
4869 return file
.fileContent() + sect
->offset() + addr
- sect
->addr();
4873 throwf("__eh_frame parsing problem. Can't find target of reference to address 0x%08llX", (uint64_t)addr
);
4878 template <typename A
>
4879 uint64_t CFISection
<A
>::OAS::getULEB128(pint_t
& logicalAddr
, pint_t end
)
4881 uintptr_t size
= (end
- logicalAddr
);
4882 libunwind::LocalAddressSpace::pint_t laddr
= (libunwind::LocalAddressSpace::pint_t
)mappedAddress(logicalAddr
);
4883 libunwind::LocalAddressSpace::pint_t sladdr
= laddr
;
4884 uint64_t result
= libunwind::LocalAddressSpace::getULEB128(laddr
, laddr
+size
);
4885 logicalAddr
+= (laddr
-sladdr
);
4889 template <typename A
>
4890 int64_t CFISection
<A
>::OAS::getSLEB128(pint_t
& logicalAddr
, pint_t end
)
4892 uintptr_t size
= (end
- logicalAddr
);
4893 libunwind::LocalAddressSpace::pint_t laddr
= (libunwind::LocalAddressSpace::pint_t
)mappedAddress(logicalAddr
);
4894 libunwind::LocalAddressSpace::pint_t sladdr
= laddr
;
4895 int64_t result
= libunwind::LocalAddressSpace::getSLEB128(laddr
, laddr
+size
);
4896 logicalAddr
+= (laddr
-sladdr
);
4900 template <typename A
>
4901 typename
A::P::uint_t CFISection
<A
>::OAS::getEncodedP(pint_t
& addr
, pint_t end
, uint8_t encoding
)
4903 pint_t startAddr
= addr
;
4908 switch (encoding
& 0x0F) {
4910 result
= getP(addr
);
4911 p
+= sizeof(pint_t
);
4914 case DW_EH_PE_uleb128
:
4915 result
= getULEB128(addr
, end
);
4917 case DW_EH_PE_udata2
:
4918 result
= get16(addr
);
4922 case DW_EH_PE_udata4
:
4923 result
= get32(addr
);
4927 case DW_EH_PE_udata8
:
4928 result
= get64(addr
);
4932 case DW_EH_PE_sleb128
:
4933 result
= getSLEB128(addr
, end
);
4935 case DW_EH_PE_sdata2
:
4936 result
= (int16_t)get16(addr
);
4940 case DW_EH_PE_sdata4
:
4941 result
= (int32_t)get32(addr
);
4945 case DW_EH_PE_sdata8
:
4946 result
= get64(addr
);
4951 throwf("ObjectFileAddressSpace<A>::getEncodedP() encoding 0x%08X not supported", encoding
);
4954 // then add relative offset
4955 switch ( encoding
& 0x70 ) {
4956 case DW_EH_PE_absptr
:
4959 case DW_EH_PE_pcrel
:
4960 result
+= startAddr
;
4962 case DW_EH_PE_textrel
:
4963 throw "DW_EH_PE_textrel pointer encoding not supported";
4965 case DW_EH_PE_datarel
:
4966 throw "DW_EH_PE_datarel pointer encoding not supported";
4968 case DW_EH_PE_funcrel
:
4969 throw "DW_EH_PE_funcrel pointer encoding not supported";
4971 case DW_EH_PE_aligned
:
4972 throw "DW_EH_PE_aligned pointer encoding not supported";
4975 throwf("ObjectFileAddressSpace<A>::getEncodedP() encoding 0x%08X not supported", encoding
);
4979 // Note: DW_EH_PE_indirect is only used in CIEs to refernce the personality pointer
4980 // When parsing .o files that pointer contains zero, so we don't to return that.
4981 // Instead we skip the dereference and return the address of the pointer.
4982 // if ( encoding & DW_EH_PE_indirect )
4983 // result = getP(result);
4989 const char* CUSection
<x86_64
>::personalityName(class Parser
<x86_64
>& parser
, const macho_relocation_info
<x86_64::P
>* reloc
)
4991 if ( reloc
->r_extern() ) {
4992 assert((reloc
->r_type() == X86_64_RELOC_UNSIGNED
) && "wrong reloc type on personality column in __compact_unwind section");
4993 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
4994 return parser
.nameFromSymbol(sym
);
4997 const pint_t
* content
= (pint_t
*)(this->file().fileContent() + this->_machOSection
->offset() + reloc
->r_address());
4998 pint_t personalityAddr
= *content
;
4999 assert((parser
.sectionForAddress(personalityAddr
)->type() == ld::Section::typeCode
) && "personality column in __compact_unwind section is not pointer to function");
5000 // atoms may not be constructed yet, so scan symbol table for labels
5001 const char* name
= parser
.scanSymbolTableForAddress(personalityAddr
);
5007 const char* CUSection
<x86
>::personalityName(class Parser
<x86
>& parser
, const macho_relocation_info
<x86::P
>* reloc
)
5009 if ( reloc
->r_extern() ) {
5010 assert((reloc
->r_type() == GENERIC_RELOC_VANILLA
) && "wrong reloc type on personality column in __compact_unwind section");
5011 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
5012 return parser
.nameFromSymbol(sym
);
5015 // support __LD, __compact_unwind personality entries which are pointer to personality non-lazy pointer
5016 const pint_t
* content
= (pint_t
*)(this->file().fileContent() + this->_machOSection
->offset() + reloc
->r_address());
5017 pint_t nlPointerAddr
= *content
;
5018 Section
<x86
>* nlSection
= parser
.sectionForAddress(nlPointerAddr
);
5019 if ( nlSection
->type() == ld::Section::typeCode
) {
5020 // personality function is defined in this .o file, so this is a direct reference to it
5021 // atoms may not be constructed yet, so scan symbol table for labels
5022 const char* name
= parser
.scanSymbolTableForAddress(nlPointerAddr
);
5026 uint32_t symIndex
= parser
.symbolIndexFromIndirectSectionAddress(nlPointerAddr
, nlSection
->machoSection());
5027 const macho_nlist
<P
>& nlSymbol
= parser
.symbolFromIndex(symIndex
);
5028 return parser
.nameFromSymbol(nlSymbol
);
5033 #if SUPPORT_ARCH_arm64
5035 const char* CUSection
<arm64
>::personalityName(class Parser
<arm64
>& parser
, const macho_relocation_info
<arm64::P
>* reloc
)
5037 if ( reloc
->r_extern() ) {
5038 assert((reloc
->r_type() == ARM64_RELOC_UNSIGNED
) && "wrong reloc type on personality column in __compact_unwind section");
5039 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
5040 return parser
.nameFromSymbol(sym
);
5043 const pint_t
* content
= (pint_t
*)(this->file().fileContent() + this->_machOSection
->offset() + reloc
->r_address());
5044 pint_t personalityAddr
= *content
;
5045 Section
<arm64
>* personalitySection
= parser
.sectionForAddress(personalityAddr
);
5046 (void)personalitySection
;
5047 assert((personalitySection
->type() == ld::Section::typeCode
) && "personality column in __compact_unwind section is not pointer to function");
5048 // atoms may not be constructed yet, so scan symbol table for labels
5049 const char* name
= parser
.scanSymbolTableForAddress(personalityAddr
);
5056 #if SUPPORT_ARCH_arm_any
5058 const char* CUSection
<arm
>::personalityName(class Parser
<arm
>& parser
, const macho_relocation_info
<arm::P
>* reloc
)
5060 if ( reloc
->r_extern() ) {
5061 assert((reloc
->r_type() == ARM_RELOC_VANILLA
) && "wrong reloc type on personality column in __compact_unwind section");
5062 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
5063 return parser
.nameFromSymbol(sym
);
5066 // support __LD, __compact_unwind personality entries which are pointer to personality non-lazy pointer
5067 const pint_t
* content
= (pint_t
*)(this->file().fileContent() + this->_machOSection
->offset() + reloc
->r_address());
5068 pint_t nlPointerAddr
= *content
;
5069 Section
<arm
>* nlSection
= parser
.sectionForAddress(nlPointerAddr
);
5070 if ( nlSection
->type() == ld::Section::typeCode
) {
5071 // personality function is defined in this .o file, so this is a direct reference to it
5072 // atoms may not be constructed yet, so scan symbol table for labels
5073 const char* name
= parser
.scanSymbolTableForAddress(nlPointerAddr
);
5077 uint32_t symIndex
= parser
.symbolIndexFromIndirectSectionAddress(nlPointerAddr
, nlSection
->machoSection());
5078 const macho_nlist
<P
>& nlSymbol
= parser
.symbolFromIndex(symIndex
);
5079 return parser
.nameFromSymbol(nlSymbol
);
5086 template <typename A
>
5087 const char* CUSection
<A
>::personalityName(class Parser
<A
>& parser
, const macho_relocation_info
<P
>* reloc
)
5093 bool CUSection
<x86
>::encodingMeansUseDwarf(compact_unwind_encoding_t enc
)
5095 return ((enc
& UNWIND_X86_MODE_MASK
) == UNWIND_X86_MODE_DWARF
);
5099 bool CUSection
<x86_64
>::encodingMeansUseDwarf(compact_unwind_encoding_t enc
)
5101 return ((enc
& UNWIND_X86_64_MODE_MASK
) == UNWIND_X86_64_MODE_DWARF
);
5104 #if SUPPORT_ARCH_arm_any
5106 bool CUSection
<arm
>::encodingMeansUseDwarf(compact_unwind_encoding_t enc
)
5108 return ((enc
& UNWIND_ARM_MODE_MASK
) == UNWIND_ARM_MODE_DWARF
);
5112 #if SUPPORT_ARCH_arm64
5114 bool CUSection
<arm64
>::encodingMeansUseDwarf(compact_unwind_encoding_t enc
)
5116 return ((enc
& UNWIND_ARM64_MODE_MASK
) == UNWIND_ARM64_MODE_DWARF
);
5121 template <typename A
>
5122 int CUSection
<A
>::infoSorter(const void* l
, const void* r
)
5124 // sort references by symbol index, then address
5125 const Info
* left
= (Info
*)l
;
5126 const Info
* right
= (Info
*)r
;
5127 if ( left
->functionSymbolIndex
== right
->functionSymbolIndex
)
5128 return (left
->functionStartAddress
- right
->functionStartAddress
);
5130 return (left
->functionSymbolIndex
- right
->functionSymbolIndex
);
5133 template <typename A
>
5134 void CUSection
<A
>::parse(class Parser
<A
>& parser
, uint32_t cnt
, Info array
[])
5136 // walk section content and copy to Info array
5137 const macho_compact_unwind_entry
<P
>* const entries
= (macho_compact_unwind_entry
<P
>*)(this->file().fileContent() + this->_machOSection
->offset());
5138 for (uint32_t i
=0; i
< cnt
; ++i
) {
5139 Info
* info
= &array
[i
];
5140 const macho_compact_unwind_entry
<P
>* entry
= &entries
[i
];
5141 info
->functionStartAddress
= entry
->codeStart();
5142 info
->functionSymbolIndex
= 0xFFFFFFFF;
5143 info
->rangeLength
= entry
->codeLen();
5144 info
->compactUnwindInfo
= entry
->compactUnwindInfo();
5145 info
->personality
= NULL
;
5146 info
->lsdaAddress
= entry
->lsda();
5147 info
->function
= NULL
;
5149 if ( (info
->compactUnwindInfo
& UNWIND_PERSONALITY_MASK
) != 0 )
5150 warning("no bits should be set in UNWIND_PERSONALITY_MASK of compact unwind encoding in __LD,__compact_unwind section");
5151 if ( info
->lsdaAddress
!= 0 ) {
5152 info
->compactUnwindInfo
|= UNWIND_HAS_LSDA
;
5156 // scan relocs, extern relocs are needed for personality references (possibly for function/lsda refs??)
5157 const uint32_t sectionSize
= this->_machOSection
->size();
5158 const macho_relocation_info
<P
>* relocs
= (macho_relocation_info
<P
>*)(this->file().fileContent() + this->_machOSection
->reloff());
5159 const macho_relocation_info
<P
>* relocsEnd
= &relocs
[this->_machOSection
->nreloc()];
5160 for (const macho_relocation_info
<P
>* reloc
= relocs
; reloc
< relocsEnd
; ++reloc
) {
5161 if ( reloc
->r_address() & R_SCATTERED
)
5163 if ( reloc
->r_address() > sectionSize
)
5164 throwf("malformed __compact_unwind relocation, offset (0x%08X) is beyond end of section,", reloc
->r_address());
5165 if ( reloc
->r_extern() ) {
5166 // only expect external relocs on some colummns
5167 if ( (reloc
->r_address() % sizeof(macho_compact_unwind_entry
<P
>)) == macho_compact_unwind_entry
<P
>::personalityFieldOffset() ) {
5168 uint32_t entryIndex
= reloc
->r_address() / sizeof(macho_compact_unwind_entry
<P
>);
5169 array
[entryIndex
].personality
= this->personalityName(parser
, reloc
);
5171 else if ( (reloc
->r_address() % sizeof(macho_compact_unwind_entry
<P
>)) == macho_compact_unwind_entry
<P
>::lsdaFieldOffset() ) {
5172 uint32_t entryIndex
= reloc
->r_address() / sizeof(macho_compact_unwind_entry
<P
>);
5173 const macho_nlist
<P
>& lsdaSym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
5174 if ( (lsdaSym
.n_type() & N_TYPE
) == N_SECT
)
5175 array
[entryIndex
].lsdaAddress
= lsdaSym
.n_value();
5177 warning("unexpected extern relocation to lsda in __compact_unwind section");
5179 else if ( (reloc
->r_address() % sizeof(macho_compact_unwind_entry
<P
>)) == macho_compact_unwind_entry
<P
>::codeStartFieldOffset() ) {
5180 uint32_t entryIndex
= reloc
->r_address() / sizeof(macho_compact_unwind_entry
<P
>);
5181 array
[entryIndex
].functionSymbolIndex
= reloc
->r_symbolnum();
5182 array
[entryIndex
].functionStartAddress
+= parser
.symbolFromIndex(reloc
->r_symbolnum()).n_value();
5185 warning("unexpected extern relocation in __compact_unwind section");
5189 if ( (reloc
->r_address() % sizeof(macho_compact_unwind_entry
<P
>)) == macho_compact_unwind_entry
<P
>::personalityFieldOffset() ) {
5190 uint32_t entryIndex
= reloc
->r_address() / sizeof(macho_compact_unwind_entry
<P
>);
5191 array
[entryIndex
].personality
= this->personalityName(parser
, reloc
);
5196 // sort array by function start address so unwind infos will be contiguous for a given function
5197 ::qsort(array
, cnt
, sizeof(Info
), infoSorter
);
5200 template <typename A
>
5201 uint32_t CUSection
<A
>::count()
5203 const macho_section
<P
>* machoSect
= this->machoSection();
5204 if ( (machoSect
->size() % sizeof(macho_compact_unwind_entry
<P
>)) != 0 )
5205 throw "malformed __LD,__compact_unwind section, bad length";
5207 return machoSect
->size() / sizeof(macho_compact_unwind_entry
<P
>);
5210 template <typename A
>
5211 void CUSection
<A
>::makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
& cus
)
5213 Info
* const arrayStart
= cus
.cuArray
;
5214 Info
* const arrayEnd
= &cus
.cuArray
[cus
.cuCount
];
5215 for (Info
* info
=arrayStart
; info
< arrayEnd
; ++info
) {
5216 // find function atom from address
5217 info
->function
= parser
.findAtomByAddress(info
->functionStartAddress
);
5218 // find lsda atom from address
5219 if ( info
->lsdaAddress
!= 0 ) {
5220 info
->lsda
= parser
.findAtomByAddress(info
->lsdaAddress
);
5221 // add lsda subordinate
5222 typename Parser
<A
>::SourceLocation
src(info
->function
, info
->functionStartAddress
- info
->function
->objectAddress());
5223 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinateLSDA
, info
->lsda
);
5225 if ( info
->personality
!= NULL
) {
5226 // add personality subordinate
5227 typename Parser
<A
>::SourceLocation
src(info
->function
, info
->functionStartAddress
- info
->function
->objectAddress());
5228 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinatePersonality
, false, info
->personality
);
5234 template <typename A
>
5235 SymboledSection
<A
>::SymboledSection(Parser
<A
>& parser
, File
<A
>& f
, const macho_section
<typename
A::P
>* s
)
5236 : Section
<A
>(f
, s
), _type(ld::Atom::typeUnclassified
)
5238 switch ( s
->flags() & SECTION_TYPE
) {
5240 _type
= ld::Atom::typeZeroFill
;
5242 case S_MOD_INIT_FUNC_POINTERS
:
5243 _type
= ld::Atom::typeInitializerPointers
;
5245 case S_MOD_TERM_FUNC_POINTERS
:
5246 _type
= ld::Atom::typeTerminatorPointers
;
5248 case S_THREAD_LOCAL_VARIABLES
:
5249 _type
= ld::Atom::typeTLV
;
5251 case S_THREAD_LOCAL_ZEROFILL
:
5252 _type
= ld::Atom::typeTLVZeroFill
;
5254 case S_THREAD_LOCAL_REGULAR
:
5255 _type
= ld::Atom::typeTLVInitialValue
;
5257 case S_THREAD_LOCAL_INIT_FUNCTION_POINTERS
:
5258 _type
= ld::Atom::typeTLVInitializerPointers
;
5261 if ( strncmp(s
->sectname(), "__gcc_except_tab", 16) == 0 )
5262 _type
= ld::Atom::typeLSDA
;
5263 else if ( this->type() == ld::Section::typeInitializerPointers
)
5264 _type
= ld::Atom::typeInitializerPointers
;
5270 template <typename A
>
5271 bool SymboledSection
<A
>::dontDeadStrip()
5274 case ld::Atom::typeInitializerPointers
:
5275 case ld::Atom::typeTerminatorPointers
:
5278 // model an object file without MH_SUBSECTIONS_VIA_SYMBOLS as one in which nothing can be dead stripped
5279 if ( ! this->_file
.canScatterAtoms() )
5282 return Section
<A
>::dontDeadStrip();
5288 template <typename A
>
5289 uint32_t SymboledSection
<A
>::computeAtomCount(class Parser
<A
>& parser
,
5290 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
5291 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
5293 const pint_t startAddr
= this->_machOSection
->addr();
5294 const pint_t endAddr
= startAddr
+ this->_machOSection
->size();
5295 const uint32_t sectNum
= this->sectionNum(parser
);
5300 const macho_nlist
<P
>* sym
;
5301 while ( it
.next(parser
, *this, sectNum
, startAddr
, endAddr
, &addr
, &size
, &sym
) ) {
5304 //fprintf(stderr, "computeAtomCount(%s,%s) => %d\n", this->segmentName(), this->sectionName(), count);
5308 template <typename A
>
5309 uint32_t SymboledSection
<A
>::appendAtoms(class Parser
<A
>& parser
, uint8_t* p
,
5310 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
5311 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
5313 this->_beginAtoms
= (Atom
<A
>*)p
;
5315 //fprintf(stderr, "SymboledSection::appendAtoms() in section %s\n", this->_machOSection->sectname());
5316 const pint_t startAddr
= this->_machOSection
->addr();
5317 const pint_t endAddr
= startAddr
+ this->_machOSection
->size();
5318 const uint32_t sectNum
= this->sectionNum(parser
);
5323 const macho_nlist
<P
>* label
;
5324 while ( it
.next(parser
, *this, sectNum
, startAddr
, endAddr
, &addr
, &size
, &label
) ) {
5325 Atom
<A
>* allocatedSpace
= (Atom
<A
>*)p
;
5326 // is break because of label or CFI?
5327 if ( label
!= NULL
) {
5328 // The size is computed based on the address of the next label (or the end of the section for the last label)
5329 // If there are two labels at the same address, we want them one to be an alias of the other.
5330 // If the label is at the end of a section, it is has zero size, but is not an alias
5331 const bool isAlias
= ( (size
== 0) && (addr
< endAddr
) );
5332 new (allocatedSpace
) Atom
<A
>(*this, parser
, *label
, size
, isAlias
);
5334 this->_hasAliases
= true;
5335 if ( parser
.altEntryFromSymbol(*label
) )
5336 this->_altEntries
.insert(allocatedSpace
);
5339 ld::Atom::SymbolTableInclusion inclusion
= ld::Atom::symbolTableNotIn
;
5340 ld::Atom::ContentType ctype
= this->contentType();
5341 if ( ctype
== ld::Atom::typeLSDA
)
5342 inclusion
= ld::Atom::symbolTableInWithRandomAutoStripLabel
;
5343 new (allocatedSpace
) Atom
<A
>(*this, "anon", addr
, size
, ld::Atom::definitionRegular
, ld::Atom::combineNever
,
5344 ld::Atom::scopeTranslationUnit
, ctype
, inclusion
,
5345 this->dontDeadStrip(), false, false, this->alignmentForAddress(addr
));
5347 p
+= sizeof(Atom
<A
>);
5351 this->_endAtoms
= (Atom
<A
>*)p
;
5357 ld::Atom::SymbolTableInclusion ImplicitSizeSection
<arm64
>::symbolTableInclusion()
5359 return ld::Atom::symbolTableInWithRandomAutoStripLabel
;
5363 template <typename A
>
5364 ld::Atom::SymbolTableInclusion ImplicitSizeSection
<A
>::symbolTableInclusion()
5366 return ld::Atom::symbolTableNotIn
;
5370 template <typename A
>
5371 uint32_t ImplicitSizeSection
<A
>::computeAtomCount(class Parser
<A
>& parser
,
5372 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
5373 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
5376 const macho_section
<P
>* sect
= this->machoSection();
5377 const pint_t startAddr
= sect
->addr();
5378 const pint_t endAddr
= startAddr
+ sect
->size();
5379 for (pint_t addr
= startAddr
; addr
< endAddr
; addr
+= elementSizeAtAddress(addr
) ) {
5380 if ( useElementAt(parser
, it
, addr
) )
5383 if ( it
.fileHasOverlappingSymbols
&& (sect
->size() != 0) && (this->combine(parser
, startAddr
) == ld::Atom::combineByNameAndContent
) ) {
5384 // if there are multiple labels in this section for the same address, then clone them into multi atoms
5385 pint_t prevSymbolAddr
= (pint_t
)(-1);
5386 uint8_t prevSymbolSectNum
= 0;
5387 bool prevIgnore
= false;
5388 for(uint32_t i
=0; i
< it
.sortedSymbolCount
; ++i
) {
5389 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(it
.sortedSymbolIndexes
[i
]);
5390 const pint_t symbolAddr
= sym
.n_value();
5391 const uint8_t symbolSectNum
= sym
.n_sect();
5392 const bool ignore
= this->ignoreLabel(parser
.nameFromSymbol(sym
));
5393 if ( !ignore
&& !prevIgnore
&& (symbolAddr
== prevSymbolAddr
) && (prevSymbolSectNum
== symbolSectNum
) && (symbolSectNum
== this->sectionNum(parser
)) ) {
5396 prevSymbolAddr
= symbolAddr
;
5397 prevSymbolSectNum
= symbolSectNum
;
5398 prevIgnore
= ignore
;
5404 template <typename A
>
5405 uint32_t ImplicitSizeSection
<A
>::appendAtoms(class Parser
<A
>& parser
, uint8_t* p
,
5406 struct Parser
<A
>::LabelAndCFIBreakIterator
& it
,
5407 const struct Parser
<A
>::CFI_CU_InfoArrays
&)
5409 this->_beginAtoms
= (Atom
<A
>*)p
;
5411 const macho_section
<P
>* sect
= this->machoSection();
5412 const pint_t startAddr
= sect
->addr();
5413 const pint_t endAddr
= startAddr
+ sect
->size();
5414 const uint32_t sectNum
= this->sectionNum(parser
);
5415 //fprintf(stderr, "ImplicitSizeSection::appendAtoms() in section %s\n", sect->sectname());
5419 const macho_nlist
<P
>* foundLabel
;
5420 Atom
<A
>* allocatedSpace
;
5421 while ( it
.next(parser
, *this, sectNum
, startAddr
, endAddr
, &foundAddr
, &size
, &foundLabel
) ) {
5422 if ( foundLabel
!= NULL
) {
5424 pint_t labeledAtomSize
= this->elementSizeAtAddress(foundAddr
);
5425 allocatedSpace
= (Atom
<A
>*)p
;
5426 if ( this->ignoreLabel(parser
.nameFromSymbol(*foundLabel
)) ) {
5428 // <rdar://problem/10018737>
5429 // a size of zero means there is another label at same location
5430 // and we are supposed to ignore this label
5434 //fprintf(stderr, " 0x%08llX make annon, size=%lld\n", (uint64_t)foundAddr, (uint64_t)size);
5435 new (allocatedSpace
) Atom
<A
>(*this, this->unlabeledAtomName(parser
, foundAddr
), foundAddr
,
5436 this->elementSizeAtAddress(foundAddr
), this->definition(),
5437 this->combine(parser
, foundAddr
), this->scopeAtAddress(parser
, foundAddr
),
5438 this->contentType(), this->symbolTableInclusion(),
5439 this->dontDeadStrip(), false, false, this->alignmentForAddress(foundAddr
));
5443 // make named atom for label
5444 //fprintf(stderr, " 0x%08llX make labeled\n", (uint64_t)foundAddr);
5445 new (allocatedSpace
) Atom
<A
>(*this, parser
, *foundLabel
, labeledAtomSize
);
5449 p
+= sizeof(Atom
<A
>);
5450 foundAddr
+= labeledAtomSize
;
5451 size
-= labeledAtomSize
;
5454 // some number of anonymous atoms
5455 for (pint_t addr
= foundAddr
; addr
< (foundAddr
+size
); addr
+= elementSizeAtAddress(addr
) ) {
5456 // make anon atoms for area before label
5457 if ( this->useElementAt(parser
, it
, addr
) ) {
5458 //fprintf(stderr, " 0x%08llX make annon, size=%lld\n", (uint64_t)addr, (uint64_t)elementSizeAtAddress(addr));
5459 allocatedSpace
= (Atom
<A
>*)p
;
5460 new (allocatedSpace
) Atom
<A
>(*this, this->unlabeledAtomName(parser
, addr
), addr
, this->elementSizeAtAddress(addr
),
5461 this->definition(), this->combine(parser
, addr
), this->scopeAtAddress(parser
, addr
),
5462 this->contentType(), this->symbolTableInclusion(),
5463 this->dontDeadStrip(), false, false, this->alignmentForAddress(addr
));
5465 p
+= sizeof(Atom
<A
>);
5470 this->_endAtoms
= (Atom
<A
>*)p
;
5475 template <typename A
>
5476 bool Literal4Section
<A
>::ignoreLabel(const char* label
) const
5478 return (label
[0] == 'L') || (label
[0] == 'l');
5481 template <typename A
>
5482 unsigned long Literal4Section
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5484 const uint32_t* literalContent
= (uint32_t*)atom
->contentPointer();
5485 return *literalContent
;
5488 template <typename A
>
5489 bool Literal4Section
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5490 const ld::IndirectBindingTable
& ind
) const
5492 assert(this->type() == rhs
.section().type());
5493 const uint32_t* literalContent
= (uint32_t*)atom
->contentPointer();
5495 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5496 assert(rhsAtom
!= NULL
);
5497 if ( rhsAtom
!= NULL
) {
5498 const uint32_t* rhsLiteralContent
= (uint32_t*)rhsAtom
->contentPointer();
5499 return (*literalContent
== *rhsLiteralContent
);
5505 template <typename A
>
5506 bool Literal8Section
<A
>::ignoreLabel(const char* label
) const
5508 return (label
[0] == 'L') || (label
[0] == 'l');
5511 template <typename A
>
5512 unsigned long Literal8Section
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5515 const uint64_t* literalContent
= (uint64_t*)atom
->contentPointer();
5516 return *literalContent
;
5518 unsigned long hash
= 5381;
5519 const uint8_t* byteContent
= atom
->contentPointer();
5520 for (int i
=0; i
< 8; ++i
) {
5521 hash
= hash
* 33 + byteContent
[i
];
5527 template <typename A
>
5528 bool Literal8Section
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5529 const ld::IndirectBindingTable
& ind
) const
5531 if ( rhs
.section().type() != ld::Section::typeLiteral8
)
5533 assert(this->type() == rhs
.section().type());
5534 const uint64_t* literalContent
= (uint64_t*)atom
->contentPointer();
5536 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5537 assert(rhsAtom
!= NULL
);
5538 if ( rhsAtom
!= NULL
) {
5539 const uint64_t* rhsLiteralContent
= (uint64_t*)rhsAtom
->contentPointer();
5540 return (*literalContent
== *rhsLiteralContent
);
5545 template <typename A
>
5546 bool Literal16Section
<A
>::ignoreLabel(const char* label
) const
5548 return (label
[0] == 'L') || (label
[0] == 'l');
5551 template <typename A
>
5552 unsigned long Literal16Section
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5554 unsigned long hash
= 5381;
5555 const uint8_t* byteContent
= atom
->contentPointer();
5556 for (int i
=0; i
< 16; ++i
) {
5557 hash
= hash
* 33 + byteContent
[i
];
5562 template <typename A
>
5563 bool Literal16Section
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5564 const ld::IndirectBindingTable
& ind
) const
5566 if ( rhs
.section().type() != ld::Section::typeLiteral16
)
5568 assert(this->type() == rhs
.section().type());
5569 const uint64_t* literalContent
= (uint64_t*)atom
->contentPointer();
5571 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5572 assert(rhsAtom
!= NULL
);
5573 if ( rhsAtom
!= NULL
) {
5574 const uint64_t* rhsLiteralContent
= (uint64_t*)rhsAtom
->contentPointer();
5575 return ((literalContent
[0] == rhsLiteralContent
[0]) && (literalContent
[1] == rhsLiteralContent
[1]));
5582 template <typename A
>
5583 typename
A::P::uint_t CStringSection
<A
>::elementSizeAtAddress(pint_t addr
)
5585 const macho_section
<P
>* sect
= this->machoSection();
5586 const char* stringContent
= (char*)(this->file().fileContent() + sect
->offset() + addr
- sect
->addr());
5587 return strlen(stringContent
) + 1;
5590 template <typename A
>
5591 bool CStringSection
<A
>::useElementAt(Parser
<A
>& parser
, struct Parser
<A
>::LabelAndCFIBreakIterator
& it
, pint_t addr
)
5596 template <typename A
>
5597 bool CStringSection
<A
>::ignoreLabel(const char* label
) const
5599 return (label
[0] == 'L') || (label
[0] == 'l');
5603 template <typename A
>
5604 Atom
<A
>* CStringSection
<A
>::findAtomByAddress(pint_t addr
)
5606 Atom
<A
>* result
= this->findContentAtomByAddress(addr
, this->_beginAtoms
, this->_endAtoms
);
5610 template <typename A
>
5611 unsigned long CStringSection
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5613 unsigned long hash
= 5381;
5614 const char* stringContent
= (char*)atom
->contentPointer();
5615 for (const char* s
= stringContent
; *s
!= '\0'; ++s
) {
5616 hash
= hash
* 33 + *s
;
5622 template <typename A
>
5623 bool CStringSection
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5624 const ld::IndirectBindingTable
& ind
) const
5626 if ( rhs
.section().type() != ld::Section::typeCString
)
5628 assert(this->type() == rhs
.section().type());
5629 assert(strcmp(this->sectionName(), rhs
.section().sectionName())== 0);
5630 assert(strcmp(this->segmentName(), rhs
.section().segmentName())== 0);
5631 const char* stringContent
= (char*)atom
->contentPointer();
5633 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5634 assert(rhsAtom
!= NULL
);
5635 if ( rhsAtom
!= NULL
) {
5636 if ( atom
->_size
!= rhsAtom
->_size
)
5638 const char* rhsStringContent
= (char*)rhsAtom
->contentPointer();
5639 return (strcmp(stringContent
, rhsStringContent
) == 0);
5646 ld::Fixup::Kind NonLazyPointerSection
<x86
>::fixupKind()
5648 return ld::Fixup::kindStoreLittleEndian32
;
5652 ld::Fixup::Kind NonLazyPointerSection
<arm
>::fixupKind()
5654 return ld::Fixup::kindStoreLittleEndian32
;
5658 ld::Fixup::Kind NonLazyPointerSection
<arm64
>::fixupKind()
5660 return ld::Fixup::kindStoreLittleEndian64
;
5665 void NonLazyPointerSection
<x86_64
>::makeFixups(class Parser
<x86_64
>& parser
, const struct Parser
<x86_64
>::CFI_CU_InfoArrays
&)
5667 assert(0 && "x86_64 should not have non-lazy-pointer sections in .o files");
5670 template <typename A
>
5671 void NonLazyPointerSection
<A
>::makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&)
5673 // add references for each NLP atom based on indirect symbol table
5674 const macho_section
<P
>* sect
= this->machoSection();
5675 const pint_t endAddr
= sect
->addr() + sect
->size();
5676 for( pint_t addr
= sect
->addr(); addr
< endAddr
; addr
+= sizeof(pint_t
)) {
5677 typename Parser
<A
>::SourceLocation src
;
5678 typename Parser
<A
>::TargetDesc target
;
5679 src
.atom
= this->findAtomByAddress(addr
);
5680 src
.offsetInAtom
= 0;
5681 uint32_t symIndex
= parser
.symbolIndexFromIndirectSectionAddress(addr
, sect
);
5684 target
.weakImport
= false;
5686 if ( symIndex
== INDIRECT_SYMBOL_LOCAL
) {
5687 // use direct reference for local symbols
5688 const pint_t
* nlpContent
= (pint_t
*)(this->file().fileContent() + sect
->offset() + addr
- sect
->addr());
5689 pint_t targetAddr
= P::getP(*nlpContent
);
5690 target
.atom
= parser
.findAtomByAddress(targetAddr
);
5691 target
.weakImport
= false;
5692 target
.addend
= (targetAddr
- target
.atom
->objectAddress());
5693 // <rdar://problem/8385011> if pointer to thumb function, mask of thumb bit (not an addend of +1)
5694 if ( target
.atom
->isThumb() )
5695 target
.addend
&= (-2);
5696 assert(src
.atom
->combine() == ld::Atom::combineNever
);
5699 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(symIndex
);
5700 // use direct reference for local symbols
5701 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && ((sym
.n_type() & N_EXT
) == 0) ) {
5702 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
5703 assert(src
.atom
->combine() == ld::Atom::combineNever
);
5706 target
.name
= parser
.nameFromSymbol(sym
);
5707 target
.weakImport
= parser
.weakImportFromSymbol(sym
);
5708 assert(src
.atom
->combine() == ld::Atom::combineByNameAndReferences
);
5711 parser
.addFixups(src
, this->fixupKind(), target
);
5715 template <typename A
>
5716 ld::Atom::Combine NonLazyPointerSection
<A
>::combine(Parser
<A
>& parser
, pint_t addr
)
5718 const macho_section
<P
>* sect
= this->machoSection();
5719 uint32_t symIndex
= parser
.symbolIndexFromIndirectSectionAddress(addr
, sect
);
5720 if ( symIndex
== INDIRECT_SYMBOL_LOCAL
)
5721 return ld::Atom::combineNever
;
5723 // don't coalesce non-lazy-pointers to local symbols
5724 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(symIndex
);
5725 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && ((sym
.n_type() & N_EXT
) == 0) )
5726 return ld::Atom::combineNever
;
5728 return ld::Atom::combineByNameAndReferences
;
5731 template <typename A
>
5732 const char* NonLazyPointerSection
<A
>::targetName(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
)
5734 assert(atom
->combine() == ld::Atom::combineByNameAndReferences
);
5735 assert(atom
->fixupCount() == 1);
5736 ld::Fixup::iterator fit
= atom
->fixupsBegin();
5737 const char* name
= NULL
;
5738 switch ( fit
->binding
) {
5739 case ld::Fixup::bindingByNameUnbound
:
5742 case ld::Fixup::bindingByContentBound
:
5743 name
= fit
->u
.target
->name();
5745 case ld::Fixup::bindingsIndirectlyBound
:
5746 name
= ind
.indirectName(fit
->u
.bindingIndex
);
5751 assert(name
!= NULL
);
5755 template <typename A
>
5756 unsigned long NonLazyPointerSection
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5758 assert(atom
->combine() == ld::Atom::combineByNameAndReferences
);
5759 unsigned long hash
= 9508;
5760 for (const char* s
= this->targetName(atom
, ind
); *s
!= '\0'; ++s
) {
5761 hash
= hash
* 33 + *s
;
5766 template <typename A
>
5767 bool NonLazyPointerSection
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5768 const ld::IndirectBindingTable
& indirectBindingTable
) const
5770 if ( rhs
.section().type() != ld::Section::typeNonLazyPointer
)
5772 assert(this->type() == rhs
.section().type());
5773 // there can be many non-lazy pointer in different section names
5774 // we only want to coalesce in same section name
5775 if ( *this != rhs
.section() )
5777 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5778 assert(rhsAtom
!= NULL
);
5779 const char* thisName
= this->targetName(atom
, indirectBindingTable
);
5780 const char* rhsName
= this->targetName(rhsAtom
, indirectBindingTable
);
5781 return (strcmp(thisName
, rhsName
) == 0);
5784 template <typename A
>
5785 ld::Atom::Scope NonLazyPointerSection
<A
>::scopeAtAddress(Parser
<A
>& parser
, pint_t addr
)
5787 const macho_section
<P
>* sect
= this->machoSection();
5788 uint32_t symIndex
= parser
.symbolIndexFromIndirectSectionAddress(addr
, sect
);
5789 if ( symIndex
== INDIRECT_SYMBOL_LOCAL
)
5790 return ld::Atom::scopeTranslationUnit
;
5792 return ld::Atom::scopeLinkageUnit
;
5797 template <typename A
>
5798 ld::Atom::Combine TLVPointerSection
<A
>::combine(Parser
<A
>& parser
, pint_t addr
)
5800 return ld::Atom::combineByNameAndReferences
;
5804 void TLVPointerSection
<arm
>::makeFixups(class Parser
<arm
>& parser
, const struct Parser
<arm
>::CFI_CU_InfoArrays
&)
5806 // add references for each thread local pointer atom based on indirect symbol table
5807 const macho_section
<P
>* sect
= this->machoSection();
5808 const pint_t endAddr
= sect
->addr() + sect
->size();
5809 for (pint_t addr
= sect
->addr(); addr
< endAddr
; addr
+= sizeof(pint_t
)) {
5810 typename Parser
<arm
>::SourceLocation src
;
5811 typename Parser
<arm
>::TargetDesc target
;
5812 src
.atom
= this->findAtomByAddress(addr
);
5813 src
.offsetInAtom
= 0;
5814 uint32_t symIndex
= parser
.symbolIndexFromIndirectSectionAddress(addr
, sect
);
5817 target
.weakImport
= false;
5819 if ( symIndex
== INDIRECT_SYMBOL_LOCAL
) {
5820 throwf("unexpected INDIRECT_SYMBOL_LOCAL in section %s", this->sectionName());
5823 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(symIndex
);
5824 // use direct reference for local symbols
5825 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && ((sym
.n_type() & N_EXT
) == 0) ) {
5826 throwf("unexpected pointer to local symbol in section %s", this->sectionName());
5829 target
.name
= parser
.nameFromSymbol(sym
);
5830 target
.weakImport
= parser
.weakImportFromSymbol(sym
);
5831 assert(src
.atom
->combine() == ld::Atom::combineByNameAndReferences
);
5834 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian32
, target
);
5838 template <typename A
>
5839 void TLVPointerSection
<A
>::makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&)
5841 assert(0 && "should not have thread-local-pointer sections in .o files");
5845 template <typename A
>
5846 const char* TLVPointerSection
<A
>::targetName(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
, bool* isStatic
)
5848 assert(atom
->combine() == ld::Atom::combineByNameAndReferences
);
5849 assert(atom
->fixupCount() == 1);
5851 ld::Fixup::iterator fit
= atom
->fixupsBegin();
5852 const char* name
= NULL
;
5853 switch ( fit
->binding
) {
5854 case ld::Fixup::bindingByNameUnbound
:
5857 case ld::Fixup::bindingByContentBound
:
5858 name
= fit
->u
.target
->name();
5860 case ld::Fixup::bindingsIndirectlyBound
:
5861 name
= ind
.indirectName(fit
->u
.bindingIndex
);
5863 case ld::Fixup::bindingDirectlyBound
:
5864 name
= fit
->u
.target
->name();
5865 *isStatic
= (fit
->u
.target
->scope() == ld::Atom::scopeTranslationUnit
);
5870 assert(name
!= NULL
);
5874 template <typename A
>
5875 unsigned long TLVPointerSection
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5877 assert(atom
->combine() == ld::Atom::combineByNameAndReferences
);
5878 unsigned long hash
= 9508;
5880 for (const char* s
= this->targetName(atom
, ind
, &isStatic
); *s
!= '\0'; ++s
) {
5881 hash
= hash
* 33 + *s
;
5886 template <typename A
>
5887 bool TLVPointerSection
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5888 const ld::IndirectBindingTable
& indirectBindingTable
) const
5890 if ( rhs
.section().type() != ld::Section::typeTLVPointers
)
5892 assert(this->type() == rhs
.section().type());
5893 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5894 assert(rhsAtom
!= NULL
);
5897 const char* thisName
= this->targetName(atom
, indirectBindingTable
, &thisIsStatic
);
5898 const char* rhsName
= this->targetName(rhsAtom
, indirectBindingTable
, &rhsIsStatic
);
5899 return !thisIsStatic
&& !rhsIsStatic
&& (strcmp(thisName
, rhsName
) == 0);
5903 template <typename A
>
5904 const uint8_t* CFStringSection
<A
>::targetContent(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
,
5905 ContentType
* ct
, unsigned int* count
)
5907 *ct
= contentUnknown
;
5908 for (ld::Fixup::iterator fit
=atom
->fixupsBegin(), end
=atom
->fixupsEnd(); fit
!= end
; ++fit
) {
5909 const ld::Atom
* targetAtom
= NULL
;
5910 switch ( fit
->binding
) {
5911 case ld::Fixup::bindingByNameUnbound
:
5912 // ignore reference to ___CFConstantStringClassReference
5913 // we are just looking for reference to backing string data
5914 assert(fit
->offsetInAtom
== 0);
5915 assert(strcmp(fit
->u
.name
, "___CFConstantStringClassReference") == 0);
5917 case ld::Fixup::bindingDirectlyBound
:
5918 case ld::Fixup::bindingByContentBound
:
5919 targetAtom
= fit
->u
.target
;
5921 case ld::Fixup::bindingsIndirectlyBound
:
5922 targetAtom
= ind
.indirectAtom(fit
->u
.bindingIndex
);
5925 assert(0 && "bad binding type");
5927 assert(targetAtom
!= NULL
);
5928 const Atom
<A
>* target
= dynamic_cast<const Atom
<A
>*>(targetAtom
);
5929 if ( targetAtom
->section().type() == ld::Section::typeCString
) {
5931 *count
= targetAtom
->size();
5933 else if ( targetAtom
->section().type() == ld::Section::typeUTF16Strings
) {
5935 *count
= (targetAtom
->size()+1)/2; // round up incase of buggy compiler that has only one trailing zero byte
5938 *ct
= contentUnknown
;
5942 return target
->contentPointer();
5948 template <typename A
>
5949 unsigned long CFStringSection
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
5951 // base hash of CFString on hash of cstring it wraps
5954 unsigned int charCount
;
5955 const uint8_t* content
= this->targetContent(atom
, ind
, &cType
, &charCount
);
5959 for (const char* s
= (char*)content
; *s
!= '\0'; ++s
) {
5960 hash
= hash
* 33 + *s
;
5965 --charCount
; // don't add last 0x0000 to hash because some buggy compilers only have trailing single byte
5966 for (const uint16_t* s
= (uint16_t*)content
; charCount
> 0; ++s
, --charCount
) {
5967 hash
= hash
* 1025 + *s
;
5970 case contentUnknown
:
5971 // <rdar://problem/14134211> For malformed CFStrings, hash to address of atom so they have unique hashes
5972 return ULONG_MAX
- (unsigned long)(atom
);
5978 template <typename A
>
5979 bool CFStringSection
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
5980 const ld::IndirectBindingTable
& indirectBindingTable
) const
5984 if ( rhs
.section().type() != ld::Section::typeCFString
)
5986 assert(this->type() == rhs
.section().type());
5987 assert(strcmp(this->sectionName(), "__cfstring") == 0);
5989 ContentType thisType
;
5990 unsigned int charCount
;
5991 const uint8_t* cstringContent
= this->targetContent(atom
, indirectBindingTable
, &thisType
, &charCount
);
5992 ContentType rhsType
;
5993 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
5994 assert(rhsAtom
!= NULL
);
5995 unsigned int rhsCharCount
;
5996 const uint8_t* rhsStringContent
= this->targetContent(rhsAtom
, indirectBindingTable
, &rhsType
, &rhsCharCount
);
5998 if ( thisType
!= rhsType
)
6001 if ( thisType
== contentUnknown
)
6004 if ( rhsType
== contentUnknown
)
6007 // no need to compare content of pointers are already the same
6008 if ( cstringContent
== rhsStringContent
)
6011 // no need to compare content if size is different
6012 if ( charCount
!= rhsCharCount
)
6015 switch ( thisType
) {
6017 return (strcmp((char*)cstringContent
, (char*)rhsStringContent
) == 0);
6020 const uint16_t* cstringContent16
= (uint16_t*)cstringContent
;
6021 const uint16_t* rhsStringContent16
= (uint16_t*)rhsStringContent
;
6022 for (unsigned int i
= 0; i
< charCount
; ++i
) {
6023 if ( cstringContent16
[i
] != rhsStringContent16
[i
] )
6028 case contentUnknown
:
6035 template <typename A
>
6036 typename
A::P::uint_t ObjC1ClassSection
<A
>::elementSizeAtAddress(pint_t addr
)
6038 // nominal size for each class is 48 bytes, but sometimes the compiler
6039 // over aligns and there is padding after class data
6040 const macho_section
<P
>* sct
= this->machoSection();
6041 uint32_t align
= 1 << sct
->align();
6042 uint32_t size
= ((12 * sizeof(pint_t
)) + align
-1) & (-align
);
6046 template <typename A
>
6047 const char* ObjC1ClassSection
<A
>::unlabeledAtomName(Parser
<A
>& parser
, pint_t addr
)
6049 // 8-bytes into class object is pointer to class name
6050 const macho_section
<P
>* sct
= this->machoSection();
6051 uint32_t classObjcFileOffset
= sct
->offset() - sct
->addr() + addr
;
6052 const uint8_t* mappedFileContent
= this->file().fileContent();
6053 pint_t nameAddr
= P::getP(*((pint_t
*)(mappedFileContent
+classObjcFileOffset
+2*sizeof(pint_t
))));
6055 // find section containing string address to get string bytes
6056 const macho_section
<P
>* const sections
= parser
.firstMachOSection();
6057 const uint32_t sectionCount
= parser
.machOSectionCount();
6058 for (uint32_t i
=0; i
< sectionCount
; ++i
) {
6059 const macho_section
<P
>* aSect
= §ions
[i
];
6060 if ( (aSect
->addr() <= nameAddr
) && (nameAddr
< (aSect
->addr()+aSect
->size())) ) {
6061 assert((aSect
->flags() & SECTION_TYPE
) == S_CSTRING_LITERALS
);
6062 uint32_t nameFileOffset
= aSect
->offset() - aSect
->addr() + nameAddr
;
6063 const char* name
= (char*)mappedFileContent
+ nameFileOffset
;
6064 // spin through symbol table to find absolute symbol corresponding to this class
6065 for (uint32_t s
=0; s
< parser
.symbolCount(); ++s
) {
6066 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(s
);
6067 if ( (sym
.n_type() & N_TYPE
) != N_ABS
)
6069 const char* absName
= parser
.nameFromSymbol(sym
);
6070 if ( strncmp(absName
, ".objc_class_name_", 17) == 0 ) {
6071 if ( strcmp(&absName
[17], name
) == 0 )
6075 assert(0 && "obj class name not found in symbol table");
6078 assert(0 && "obj class name not found");
6079 return "unknown objc class";
6083 template <typename A
>
6084 const char* ObjC2ClassRefsSection
<A
>::targetClassName(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
6086 assert(atom
->fixupCount() == 1);
6087 ld::Fixup::iterator fit
= atom
->fixupsBegin();
6088 const char* className
= NULL
;
6089 switch ( fit
->binding
) {
6090 case ld::Fixup::bindingByNameUnbound
:
6091 className
= fit
->u
.name
;
6093 case ld::Fixup::bindingDirectlyBound
:
6094 case ld::Fixup::bindingByContentBound
:
6095 className
= fit
->u
.target
->name();
6097 case ld::Fixup::bindingsIndirectlyBound
:
6098 className
= ind
.indirectName(fit
->u
.bindingIndex
);
6101 assert(0 && "unsupported binding in objc2 class ref section");
6103 assert(className
!= NULL
);
6108 template <typename A
>
6109 unsigned long ObjC2ClassRefsSection
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
6111 unsigned long hash
= 978;
6112 for (const char* s
= targetClassName(atom
, ind
); *s
!= '\0'; ++s
) {
6113 hash
= hash
* 33 + *s
;
6118 template <typename A
>
6119 bool ObjC2ClassRefsSection
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
6120 const ld::IndirectBindingTable
& indirectBindingTable
) const
6122 assert(this->type() == rhs
.section().type());
6123 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
6124 assert(rhsAtom
!= NULL
);
6125 const char* thisClassName
= targetClassName(atom
, indirectBindingTable
);
6126 const char* rhsClassName
= targetClassName(rhsAtom
, indirectBindingTable
);
6127 return (strcmp(thisClassName
, rhsClassName
) == 0);
6131 template <typename A
>
6132 const char* Objc1ClassReferences
<A
>::targetCString(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
6134 assert(atom
->fixupCount() == 2);
6135 ld::Fixup::iterator fit
= atom
->fixupsBegin();
6136 if ( fit
->kind
== ld::Fixup::kindSetTargetAddress
)
6138 const ld::Atom
* targetAtom
= NULL
;
6139 switch ( fit
->binding
) {
6140 case ld::Fixup::bindingByContentBound
:
6141 targetAtom
= fit
->u
.target
;
6143 case ld::Fixup::bindingsIndirectlyBound
:
6144 targetAtom
= ind
.indirectAtom(fit
->u
.bindingIndex
);
6145 if ( targetAtom
== NULL
) {
6146 fprintf(stderr
, "missing target named %s\n", ind
.indirectName(fit
->u
.bindingIndex
));
6152 assert(targetAtom
!= NULL
);
6153 const Atom
<A
>* target
= dynamic_cast<const Atom
<A
>*>(targetAtom
);
6154 assert(target
!= NULL
);
6155 return (char*)target
->contentPointer();
6159 template <typename A
>
6160 const char* PointerToCStringSection
<A
>::targetCString(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
6162 assert(atom
->fixupCount() == 1);
6163 ld::Fixup::iterator fit
= atom
->fixupsBegin();
6164 const ld::Atom
* targetAtom
= NULL
;
6165 switch ( fit
->binding
) {
6166 case ld::Fixup::bindingByContentBound
:
6167 targetAtom
= fit
->u
.target
;
6169 case ld::Fixup::bindingsIndirectlyBound
:
6170 targetAtom
= ind
.indirectAtom(fit
->u
.bindingIndex
);
6172 case ld::Fixup::bindingDirectlyBound
:
6173 targetAtom
= fit
->u
.target
;
6176 assert(0 && "unsupported reference to selector");
6178 assert(targetAtom
!= NULL
);
6179 const Atom
<A
>* target
= dynamic_cast<const Atom
<A
>*>(targetAtom
);
6180 assert(target
!= NULL
);
6181 assert(target
->contentType() == ld::Atom::typeCString
);
6182 return (char*)target
->contentPointer();
6185 template <typename A
>
6186 unsigned long PointerToCStringSection
<A
>::contentHash(const class Atom
<A
>* atom
,
6187 const ld::IndirectBindingTable
& indirectBindingTable
) const
6189 // make hash from section name and target cstring name
6190 unsigned long hash
= 123;
6191 for (const char* s
= this->sectionName(); *s
!= '\0'; ++s
) {
6192 hash
= hash
* 33 + *s
;
6194 for (const char* s
= this->targetCString(atom
, indirectBindingTable
); *s
!= '\0'; ++s
) {
6195 hash
= hash
* 33 + *s
;
6200 template <typename A
>
6201 bool PointerToCStringSection
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
6202 const ld::IndirectBindingTable
& indirectBindingTable
) const
6204 assert(this->type() == rhs
.section().type());
6205 // there can be pointers-to-cstrings in different section names
6206 // we only want to coalesce in same section name
6207 if ( *this != rhs
.section() )
6210 // get string content for this
6211 const char* cstringContent
= this->targetCString(atom
, indirectBindingTable
);
6212 const Atom
<A
>* rhsAtom
= dynamic_cast<const Atom
<A
>*>(&rhs
);
6213 assert(rhsAtom
!= NULL
);
6214 const char* rhsCstringContent
= this->targetCString(rhsAtom
, indirectBindingTable
);
6216 assert(cstringContent
!= NULL
);
6217 assert(rhsCstringContent
!= NULL
);
6218 return (strcmp(cstringContent
, rhsCstringContent
) == 0);
6223 template <typename A
>
6224 unsigned long UTF16StringSection
<A
>::contentHash(const class Atom
<A
>* atom
, const ld::IndirectBindingTable
& ind
) const
6226 unsigned long hash
= 5381;
6227 const uint16_t* stringContent
= (uint16_t*)atom
->contentPointer();
6228 // some buggy compilers end utf16 data with single byte, so don't use last word in hash computation
6229 unsigned int count
= (atom
->size()/2) - 1;
6230 for (const uint16_t* s
= stringContent
; count
> 0; ++s
, --count
) {
6231 hash
= hash
* 33 + *s
;
6236 template <typename A
>
6237 bool UTF16StringSection
<A
>::canCoalesceWith(const class Atom
<A
>* atom
, const ld::Atom
& rhs
,
6238 const ld::IndirectBindingTable
& ind
) const
6240 if ( rhs
.section().type() != ld::Section::typeUTF16Strings
)
6253 uint32_t Section
<x86_64
>::x86_64PcRelOffset(uint8_t r_type
)
6256 case X86_64_RELOC_SIGNED
:
6258 case X86_64_RELOC_SIGNED_1
:
6260 case X86_64_RELOC_SIGNED_2
:
6262 case X86_64_RELOC_SIGNED_4
:
6270 bool Section
<x86_64
>::addRelocFixup(class Parser
<x86_64
>& parser
, const macho_relocation_info
<P
>* reloc
)
6272 const macho_section
<P
>* sect
= this->machoSection();
6273 if ( sect
== NULL
) {
6274 warning("malformed mach-o, relocations not supported on section %s", this->sectionName());
6277 uint64_t srcAddr
= sect
->addr() + reloc
->r_address();
6278 Parser
<x86_64
>::SourceLocation src
;
6279 Parser
<x86_64
>::TargetDesc target
;
6280 Parser
<x86_64
>::TargetDesc toTarget
;
6281 src
.atom
= this->findAtomByAddress(srcAddr
);
6282 src
.offsetInAtom
= srcAddr
- src
.atom
->_objAddress
;
6283 const uint8_t* fixUpPtr
= file().fileContent() + sect
->offset() + reloc
->r_address();
6284 uint64_t contentValue
= 0;
6285 const macho_relocation_info
<x86_64::P
>* nextReloc
= &reloc
[1];
6286 bool result
= false;
6287 bool useDirectBinding
;
6288 switch ( reloc
->r_length() ) {
6290 contentValue
= *fixUpPtr
;
6293 contentValue
= (int64_t)(int16_t)E::get16(*((uint16_t*)fixUpPtr
));
6296 contentValue
= (int64_t)(int32_t)E::get32(*((uint32_t*)fixUpPtr
));
6299 contentValue
= E::get64(*((uint64_t*)fixUpPtr
));
6304 target
.weakImport
= false;
6306 if ( reloc
->r_extern() ) {
6307 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
6308 // use direct reference for local symbols
6309 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && (((sym
.n_type() & N_EXT
) == 0) || (parser
.nameFromSymbol(sym
)[0] == 'L')) ) {
6310 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
6311 target
.addend
+= contentValue
;
6314 target
.name
= parser
.nameFromSymbol(sym
);
6315 target
.weakImport
= parser
.weakImportFromSymbol(sym
);
6316 target
.addend
= contentValue
;
6318 // cfstrings should always use direct reference to backing store
6319 if ( (this->type() == ld::Section::typeCFString
) && (src
.offsetInAtom
!= 0) ) {
6320 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
6321 target
.addend
= contentValue
;
6325 if ( reloc
->r_pcrel() )
6326 contentValue
+= srcAddr
+ x86_64PcRelOffset(reloc
->r_type());
6327 parser
.findTargetFromAddressAndSectionNum(contentValue
, reloc
->r_symbolnum(), target
);
6329 switch ( reloc
->r_type() ) {
6330 case X86_64_RELOC_UNSIGNED
:
6331 if ( reloc
->r_pcrel() )
6332 throw "pcrel and X86_64_RELOC_UNSIGNED not supported";
6333 switch ( reloc
->r_length() ) {
6336 throw "length < 2 and X86_64_RELOC_UNSIGNED not supported";
6338 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian32
, target
);
6341 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian64
, target
);
6345 case X86_64_RELOC_SIGNED
:
6346 case X86_64_RELOC_SIGNED_1
:
6347 case X86_64_RELOC_SIGNED_2
:
6348 case X86_64_RELOC_SIGNED_4
:
6349 if ( ! reloc
->r_pcrel() )
6350 throw "not pcrel and X86_64_RELOC_SIGNED* not supported";
6351 if ( reloc
->r_length() != 2 )
6352 throw "length != 2 and X86_64_RELOC_SIGNED* not supported";
6353 switch ( reloc
->r_type() ) {
6354 case X86_64_RELOC_SIGNED
:
6355 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32
, target
);
6357 case X86_64_RELOC_SIGNED_1
:
6358 if ( reloc
->r_extern() )
6360 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32_1
, target
);
6362 case X86_64_RELOC_SIGNED_2
:
6363 if ( reloc
->r_extern() )
6365 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32_2
, target
);
6367 case X86_64_RELOC_SIGNED_4
:
6368 if ( reloc
->r_extern() )
6370 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32_4
, target
);
6374 case X86_64_RELOC_BRANCH
:
6375 if ( ! reloc
->r_pcrel() )
6376 throw "not pcrel and X86_64_RELOC_BRANCH not supported";
6377 switch ( reloc
->r_length() ) {
6379 if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_probe$", 16) == 0) ) {
6380 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindStoreX86DtraceCallSiteNop
, false, target
.name
);
6381 parser
.addDtraceExtraInfos(src
, &target
.name
[16]);
6383 else if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_isenabled$", 20) == 0) ) {
6384 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindStoreX86DtraceIsEnableSiteClear
, false, target
.name
);
6385 parser
.addDtraceExtraInfos(src
, &target
.name
[20]);
6388 parser
.addFixups(src
, ld::Fixup::kindStoreX86BranchPCRel32
, target
);
6392 parser
.addFixups(src
, ld::Fixup::kindStoreX86BranchPCRel8
, target
);
6395 throwf("length=%d and X86_64_RELOC_BRANCH not supported", reloc
->r_length());
6398 case X86_64_RELOC_GOT
:
6399 if ( ! reloc
->r_extern() )
6400 throw "not extern and X86_64_RELOC_GOT not supported";
6401 if ( ! reloc
->r_pcrel() )
6402 throw "not pcrel and X86_64_RELOC_GOT not supported";
6403 if ( reloc
->r_length() != 2 )
6404 throw "length != 2 and X86_64_RELOC_GOT not supported";
6405 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32GOT
, target
);
6407 case X86_64_RELOC_GOT_LOAD
:
6408 if ( ! reloc
->r_extern() )
6409 throw "not extern and X86_64_RELOC_GOT_LOAD not supported";
6410 if ( ! reloc
->r_pcrel() )
6411 throw "not pcrel and X86_64_RELOC_GOT_LOAD not supported";
6412 if ( reloc
->r_length() != 2 )
6413 throw "length != 2 and X86_64_RELOC_GOT_LOAD not supported";
6414 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32GOTLoad
, target
);
6416 case X86_64_RELOC_SUBTRACTOR
:
6417 if ( reloc
->r_pcrel() )
6418 throw "X86_64_RELOC_SUBTRACTOR cannot be pc-relative";
6419 if ( reloc
->r_length() < 2 )
6420 throw "X86_64_RELOC_SUBTRACTOR must have r_length of 2 or 3";
6421 if ( !reloc
->r_extern() )
6422 throw "X86_64_RELOC_SUBTRACTOR must have r_extern=1";
6423 if ( nextReloc
->r_type() != X86_64_RELOC_UNSIGNED
)
6424 throw "X86_64_RELOC_SUBTRACTOR must be followed by X86_64_RELOC_UNSIGNED";
6426 if ( nextReloc
->r_pcrel() )
6427 throw "X86_64_RELOC_UNSIGNED following a X86_64_RELOC_SUBTRACTOR cannot be pc-relative";
6428 if ( nextReloc
->r_length() != reloc
->r_length() )
6429 throw "X86_64_RELOC_UNSIGNED following a X86_64_RELOC_SUBTRACTOR must have same r_length";
6430 if ( nextReloc
->r_extern() ) {
6431 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(nextReloc
->r_symbolnum());
6432 // use direct reference for local symbols
6433 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && (((sym
.n_type() & N_EXT
) == 0) || (parser
.nameFromSymbol(sym
)[0] == 'L')) ) {
6434 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), toTarget
);
6435 toTarget
.addend
= contentValue
;
6436 useDirectBinding
= true;
6439 toTarget
.name
= parser
.nameFromSymbol(sym
);
6440 toTarget
.weakImport
= parser
.weakImportFromSymbol(sym
);
6441 toTarget
.addend
= contentValue
;
6442 useDirectBinding
= false;
6446 parser
.findTargetFromAddressAndSectionNum(contentValue
, nextReloc
->r_symbolnum(), toTarget
);
6447 useDirectBinding
= (toTarget
.atom
->scope() == ld::Atom::scopeTranslationUnit
) || ((toTarget
.atom
->combine() == ld::Atom::combineByNameAndContent
) || (toTarget
.atom
->combine() == ld::Atom::combineByNameAndReferences
));
6449 if ( useDirectBinding
) {
6450 if ( (toTarget
.atom
->combine() == ld::Atom::combineByNameAndContent
) || (toTarget
.atom
->combine() == ld::Atom::combineByNameAndReferences
) )
6451 parser
.addFixup(src
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, toTarget
.atom
);
6453 parser
.addFixup(src
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, toTarget
.atom
);
6456 parser
.addFixup(src
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, toTarget
.weakImport
, toTarget
.name
);
6457 parser
.addFixup(src
, ld::Fixup::k2of4
, ld::Fixup::kindAddAddend
, toTarget
.addend
);
6458 if ( target
.atom
== NULL
)
6459 parser
.addFixup(src
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractTargetAddress
, false, target
.name
);
6461 parser
.addFixup(src
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractTargetAddress
, target
.atom
);
6462 if ( reloc
->r_length() == 2 )
6463 parser
.addFixup(src
, ld::Fixup::k4of4
, ld::Fixup::kindStoreLittleEndian32
);
6465 parser
.addFixup(src
, ld::Fixup::k4of4
, ld::Fixup::kindStoreLittleEndian64
);
6467 case X86_64_RELOC_TLV
:
6468 if ( ! reloc
->r_extern() )
6469 throw "not extern and X86_64_RELOC_TLV not supported";
6470 if ( ! reloc
->r_pcrel() )
6471 throw "not pcrel and X86_64_RELOC_TLV not supported";
6472 if ( reloc
->r_length() != 2 )
6473 throw "length != 2 and X86_64_RELOC_TLV not supported";
6474 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32TLVLoad
, target
);
6477 throwf("unknown relocation type %d", reloc
->r_type());
6485 bool Section
<x86
>::addRelocFixup(class Parser
<x86
>& parser
, const macho_relocation_info
<P
>* reloc
)
6487 const macho_section
<P
>* sect
= this->machoSection();
6489 const uint8_t* fixUpPtr
;
6490 uint32_t contentValue
= 0;
6491 ld::Fixup::Kind kind
= ld::Fixup::kindNone
;
6492 Parser
<x86
>::SourceLocation src
;
6493 Parser
<x86
>::TargetDesc target
;
6495 if ( (reloc
->r_address() & R_SCATTERED
) == 0 ) {
6496 srcAddr
= sect
->addr() + reloc
->r_address();
6497 src
.atom
= this->findAtomByAddress(srcAddr
);
6498 src
.offsetInAtom
= srcAddr
- src
.atom
->_objAddress
;
6499 fixUpPtr
= file().fileContent() + sect
->offset() + reloc
->r_address();
6500 switch ( reloc
->r_type() ) {
6501 case GENERIC_RELOC_VANILLA
:
6502 switch ( reloc
->r_length() ) {
6504 contentValue
= (int32_t)(int8_t)*fixUpPtr
;
6505 if ( reloc
->r_pcrel() ) {
6506 kind
= ld::Fixup::kindStoreX86BranchPCRel8
;
6507 contentValue
+= srcAddr
+ sizeof(uint8_t);
6510 throw "r_length=0 and r_pcrel=0 not supported";
6513 contentValue
= (int32_t)(int16_t)E::get16(*((uint16_t*)fixUpPtr
));
6514 if ( reloc
->r_pcrel() ) {
6515 kind
= ld::Fixup::kindStoreX86PCRel16
;
6516 contentValue
+= srcAddr
+ sizeof(uint16_t);
6519 kind
= ld::Fixup::kindStoreLittleEndian16
;
6522 contentValue
= E::get32(*((uint32_t*)fixUpPtr
));
6523 if ( reloc
->r_pcrel() ) {
6524 kind
= ld::Fixup::kindStoreX86BranchPCRel32
;
6525 contentValue
+= srcAddr
+ sizeof(uint32_t);
6528 kind
= ld::Fixup::kindStoreLittleEndian32
;
6531 throw "r_length=3 not supported";
6533 if ( reloc
->r_extern() ) {
6535 const macho_nlist
<P
>& targetSymbol
= parser
.symbolFromIndex(reloc
->r_symbolnum());
6536 target
.name
= parser
.nameFromSymbol(targetSymbol
);
6537 target
.weakImport
= parser
.weakImportFromSymbol(targetSymbol
);
6538 target
.addend
= (int32_t)contentValue
;
6541 parser
.findTargetFromAddressAndSectionNum(contentValue
, reloc
->r_symbolnum(), target
);
6543 if ( (kind
== ld::Fixup::kindStoreX86BranchPCRel32
) && (target
.name
!= NULL
) ) {
6544 if ( strncmp(target
.name
, "___dtrace_probe$", 16) == 0 ) {
6545 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindStoreX86DtraceCallSiteNop
, false, target
.name
);
6546 parser
.addDtraceExtraInfos(src
, &target
.name
[16]);
6549 else if ( strncmp(target
.name
, "___dtrace_isenabled$", 20) == 0 ) {
6550 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindStoreX86DtraceIsEnableSiteClear
, false, target
.name
);
6551 parser
.addDtraceExtraInfos(src
, &target
.name
[20]);
6555 parser
.addFixups(src
, kind
, target
);
6558 case GENERIC_RLEOC_TLV
:
6560 if ( !reloc
->r_extern() )
6561 throw "r_extern=0 and r_type=GENERIC_RLEOC_TLV not supported";
6562 if ( reloc
->r_length() != 2 )
6563 throw "r_length!=2 and r_type=GENERIC_RLEOC_TLV not supported";
6564 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
6565 // use direct reference for local symbols
6566 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && ((sym
.n_type() & N_EXT
) == 0) ) {
6567 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
6571 target
.name
= parser
.nameFromSymbol(sym
);
6572 target
.weakImport
= parser
.weakImportFromSymbol(sym
);
6574 target
.addend
= (int64_t)(int32_t)E::get32(*((uint32_t*)fixUpPtr
));
6575 if ( reloc
->r_pcrel() ) {
6576 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32TLVLoad
, target
);
6579 parser
.addFixups(src
, ld::Fixup::kindStoreX86Abs32TLVLoad
, target
);
6585 throwf("unsupported i386 relocation type (%d)", reloc
->r_type());
6589 // scattered relocation
6590 const macho_scattered_relocation_info
<P
>* sreloc
= (macho_scattered_relocation_info
<P
>*)reloc
;
6591 srcAddr
= sect
->addr() + sreloc
->r_address();
6592 src
.atom
= this->findAtomByAddress(srcAddr
);
6593 assert(src
.atom
!= NULL
);
6594 src
.offsetInAtom
= srcAddr
- src
.atom
->_objAddress
;
6595 fixUpPtr
= file().fileContent() + sect
->offset() + sreloc
->r_address();
6596 uint32_t relocValue
= sreloc
->r_value();
6597 bool result
= false;
6598 // file format allows pair to be scattered or not
6599 const macho_scattered_relocation_info
<P
>* nextSReloc
= &sreloc
[1];
6600 const macho_relocation_info
<P
>* nextReloc
= &reloc
[1];
6601 bool nextRelocIsPair
= false;
6602 uint32_t nextRelocAddress
= 0;
6603 uint32_t nextRelocValue
= 0;
6604 if ( (nextReloc
->r_address() & R_SCATTERED
) == 0 ) {
6605 if ( nextReloc
->r_type() == GENERIC_RELOC_PAIR
) {
6606 nextRelocIsPair
= true;
6607 nextRelocAddress
= nextReloc
->r_address();
6608 result
= true; // iterator should skip next reloc, since we've consumed it here
6612 if ( nextSReloc
->r_type() == GENERIC_RELOC_PAIR
) {
6613 nextRelocIsPair
= true;
6614 nextRelocAddress
= nextSReloc
->r_address();
6615 nextRelocValue
= nextSReloc
->r_value();
6618 switch (sreloc
->r_type()) {
6619 case GENERIC_RELOC_VANILLA
:
6620 // with a scattered relocation we get both the target (sreloc->r_value()) and the target+offset (*fixUpPtr)
6621 target
.atom
= parser
.findAtomByAddress(relocValue
);
6622 if ( sreloc
->r_pcrel() ) {
6623 switch ( sreloc
->r_length() ) {
6625 contentValue
= srcAddr
+ 1 + *fixUpPtr
;
6626 target
.addend
= (int32_t)contentValue
- (int32_t)relocValue
;
6627 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel8
, target
);
6630 contentValue
= srcAddr
+ 2 + LittleEndian::get16(*((uint16_t*)fixUpPtr
));
6631 target
.addend
= (int32_t)contentValue
- (int32_t)relocValue
;
6632 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel16
, target
);
6635 contentValue
= srcAddr
+ 4 + LittleEndian::get32(*((uint32_t*)fixUpPtr
));
6636 target
.addend
= (int32_t)contentValue
- (int32_t)relocValue
;
6637 parser
.addFixups(src
, ld::Fixup::kindStoreX86PCRel32
, target
);
6640 throw "unsupported r_length=3 for scattered pc-rel vanilla reloc";
6645 if ( sreloc
->r_length() != 2 )
6646 throwf("unsupported r_length=%d for scattered vanilla reloc", sreloc
->r_length());
6647 contentValue
= LittleEndian::get32(*((uint32_t*)fixUpPtr
));
6648 target
.addend
= (int32_t)contentValue
- (int32_t)(target
.atom
->objectAddress());
6649 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian32
, target
);
6652 case GENERIC_RELOC_SECTDIFF
:
6653 case GENERIC_RELOC_LOCAL_SECTDIFF
:
6655 if ( !nextRelocIsPair
)
6656 throw "GENERIC_RELOC_SECTDIFF missing following pair";
6657 switch ( sreloc
->r_length() ) {
6660 throw "bad length for GENERIC_RELOC_SECTDIFF";
6662 contentValue
= (int32_t)(int16_t)LittleEndian::get16(*((uint16_t*)fixUpPtr
));
6663 kind
= ld::Fixup::kindStoreLittleEndian16
;
6666 contentValue
= LittleEndian::get32(*((uint32_t*)fixUpPtr
));
6667 kind
= ld::Fixup::kindStoreLittleEndian32
;
6670 Atom
<x86
>* fromAtom
= parser
.findAtomByAddress(nextRelocValue
);
6671 uint32_t offsetInFrom
= nextRelocValue
- fromAtom
->_objAddress
;
6672 parser
.findTargetFromAddress(sreloc
->r_value(), target
);
6673 // check for addend encoded in the section content
6674 int64_t addend
= (int32_t)contentValue
- (int32_t)(sreloc
->r_value() - nextRelocValue
);
6676 // switch binding base on coalescing
6677 if ( target
.atom
== NULL
) {
6678 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, target
.name
);
6680 else if ( target
.atom
->scope() == ld::Atom::scopeTranslationUnit
) {
6681 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, target
.atom
);
6683 else if ( (target
.atom
->combine() == ld::Atom::combineByNameAndContent
) || (target
.atom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
6684 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, target
.atom
);
6687 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, target
.atom
->name());
6689 parser
.addFixup(src
, ld::Fixup::k2of5
, ld::Fixup::kindAddAddend
, target
.addend
);
6690 parser
.addFixup(src
, ld::Fixup::k3of5
, ld::Fixup::kindSubtractTargetAddress
, fromAtom
);
6691 parser
.addFixup(src
, ld::Fixup::k4of5
, ld::Fixup::kindSubtractAddend
, offsetInFrom
-addend
);
6692 parser
.addFixup(src
, ld::Fixup::k5of5
, kind
);
6695 // switch binding base on coalescing
6696 if ( target
.atom
== NULL
) {
6697 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, target
.name
);
6699 else if ( target
.atom
->scope() == ld::Atom::scopeTranslationUnit
) {
6700 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, target
.atom
);
6702 else if ( (target
.atom
->combine() == ld::Atom::combineByNameAndContent
) || (target
.atom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
6703 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, target
.atom
);
6706 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, target
.atom
->name());
6708 parser
.addFixup(src
, ld::Fixup::k2of5
, ld::Fixup::kindAddAddend
, target
.addend
+addend
);
6709 parser
.addFixup(src
, ld::Fixup::k3of5
, ld::Fixup::kindSubtractTargetAddress
, fromAtom
);
6710 parser
.addFixup(src
, ld::Fixup::k4of5
, ld::Fixup::kindSubtractAddend
, offsetInFrom
);
6711 parser
.addFixup(src
, ld::Fixup::k5of5
, kind
);
6724 #if SUPPORT_ARCH_arm_any
6726 bool Section
<arm
>::addRelocFixup(class Parser
<arm
>& parser
, const macho_relocation_info
<P
>* reloc
)
6728 const macho_section
<P
>* sect
= this->machoSection();
6729 bool result
= false;
6733 int32_t displacement
= 0;
6734 uint32_t instruction
= 0;
6735 pint_t contentValue
= 0;
6736 Parser
<arm
>::SourceLocation src
;
6737 Parser
<arm
>::TargetDesc target
;
6738 const macho_relocation_info
<P
>* nextReloc
;
6740 if ( (reloc
->r_address() & R_SCATTERED
) == 0 ) {
6741 bool externSymbolIsThumbDef
= false;
6742 srcAddr
= sect
->addr() + reloc
->r_address();
6743 src
.atom
= this->findAtomByAddress(srcAddr
);
6744 src
.offsetInAtom
= srcAddr
- src
.atom
->_objAddress
;
6745 fixUpPtr
= (uint32_t*)(file().fileContent() + sect
->offset() + reloc
->r_address());
6746 if ( reloc
->r_type() != ARM_RELOC_PAIR
)
6747 instruction
= LittleEndian::get32(*fixUpPtr
);
6748 if ( reloc
->r_extern() ) {
6749 const macho_nlist
<P
>& targetSymbol
= parser
.symbolFromIndex(reloc
->r_symbolnum());
6750 // use direct reference for local symbols
6751 if ( ((targetSymbol
.n_type() & N_TYPE
) == N_SECT
) && (((targetSymbol
.n_type() & N_EXT
) == 0) || (parser
.nameFromSymbol(targetSymbol
)[0] == 'L')) ) {
6752 parser
.findTargetFromAddressAndSectionNum(targetSymbol
.n_value(), targetSymbol
.n_sect(), target
);
6756 target
.name
= parser
.nameFromSymbol(targetSymbol
);
6757 target
.weakImport
= parser
.weakImportFromSymbol(targetSymbol
);
6758 if ( ((targetSymbol
.n_type() & N_TYPE
) == N_SECT
) && (targetSymbol
.n_desc() & N_ARM_THUMB_DEF
) )
6759 externSymbolIsThumbDef
= true;
6762 switch ( reloc
->r_type() ) {
6763 case ARM_RELOC_BR24
:
6764 // Sign-extend displacement
6765 displacement
= (instruction
& 0x00FFFFFF) << 2;
6766 if ( (displacement
& 0x02000000) != 0 )
6767 displacement
|= 0xFC000000;
6768 // The pc added will be +8 from the pc
6770 // If this is BLX add H << 1
6771 if ((instruction
& 0xFE000000) == 0xFA000000)
6772 displacement
+= ((instruction
& 0x01000000) >> 23);
6773 if ( reloc
->r_extern() ) {
6774 dstAddr
= srcAddr
+ displacement
;
6775 // <rdar://problem/16652542> support large .o files
6776 if ( srcAddr
> 0x2000000 ) {
6777 dstAddr
-= ((srcAddr
+ 0x1FFFFFF) & 0xFC000000);
6779 target
.addend
= dstAddr
;
6780 if ( externSymbolIsThumbDef
)
6781 target
.addend
&= -2; // remove thumb bit
6784 dstAddr
= srcAddr
+ displacement
;
6785 parser
.findTargetFromAddressAndSectionNum(dstAddr
, reloc
->r_symbolnum(), target
);
6787 // special case "calls" for dtrace
6788 if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_probe$", 16) == 0) ) {
6789 parser
.addFixup(src
, ld::Fixup::k1of1
,
6790 ld::Fixup::kindStoreARMDtraceCallSiteNop
, false, target
.name
);
6791 parser
.addDtraceExtraInfos(src
, &target
.name
[16]);
6793 else if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_isenabled$", 20) == 0) ) {
6794 parser
.addFixup(src
, ld::Fixup::k1of1
,
6795 ld::Fixup::kindStoreARMDtraceIsEnableSiteClear
, false, target
.name
);
6796 parser
.addDtraceExtraInfos(src
, &target
.name
[20]);
6799 parser
.addFixups(src
, ld::Fixup::kindStoreARMBranch24
, target
);
6802 case ARM_THUMB_RELOC_BR22
:
6803 // thumb2 added two more bits to displacement, complicating the displacement decoding
6805 uint32_t s
= (instruction
>> 10) & 0x1;
6806 uint32_t j1
= (instruction
>> 29) & 0x1;
6807 uint32_t j2
= (instruction
>> 27) & 0x1;
6808 uint32_t imm10
= instruction
& 0x3FF;
6809 uint32_t imm11
= (instruction
>> 16) & 0x7FF;
6810 uint32_t i1
= (j1
== s
);
6811 uint32_t i2
= (j2
== s
);
6812 uint32_t dis
= (s
<< 24) | (i1
<< 23) | (i2
<< 22) | (imm10
<< 12) | (imm11
<< 1);
6816 displacement
= sdis
;
6818 // The pc added will be +4 from the pc
6820 // If the instruction was blx, force the low 2 bits to be clear
6821 dstAddr
= srcAddr
+ displacement
;
6822 if ((instruction
& 0xD0000000) == 0xC0000000)
6823 dstAddr
&= 0xFFFFFFFC;
6825 if ( reloc
->r_extern() ) {
6826 // <rdar://problem/16652542> support large .o files
6827 if ( srcAddr
> 0x1000000 ) {
6828 dstAddr
-= ((srcAddr
+ 0xFFFFFF) & 0xFE000000);
6830 target
.addend
= (int64_t)(int32_t)dstAddr
;
6833 parser
.findTargetFromAddressAndSectionNum(dstAddr
, reloc
->r_symbolnum(), target
);
6835 // special case "calls" for dtrace
6836 if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_probe$", 16) == 0) ) {
6837 parser
.addFixup(src
, ld::Fixup::k1of1
,
6838 ld::Fixup::kindStoreThumbDtraceCallSiteNop
, false, target
.name
);
6839 parser
.addDtraceExtraInfos(src
, &target
.name
[16]);
6841 else if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_isenabled$", 20) == 0) ) {
6842 parser
.addFixup(src
, ld::Fixup::k1of1
,
6843 ld::Fixup::kindStoreThumbDtraceIsEnableSiteClear
, false, target
.name
);
6844 parser
.addDtraceExtraInfos(src
, &target
.name
[20]);
6847 parser
.addFixups(src
, ld::Fixup::kindStoreThumbBranch22
, target
);
6850 case ARM_RELOC_VANILLA
:
6851 if ( reloc
->r_length() != 2 )
6852 throw "bad length for ARM_RELOC_VANILLA";
6853 contentValue
= LittleEndian::get32(*fixUpPtr
);
6854 if ( reloc
->r_extern() ) {
6855 target
.addend
= (int32_t)contentValue
;
6856 if ( externSymbolIsThumbDef
)
6857 target
.addend
&= -2; // remove thumb bit
6860 parser
.findTargetFromAddressAndSectionNum(contentValue
, reloc
->r_symbolnum(), target
);
6861 // possible non-extern relocation turned into by-name ref because target is a weak-def
6862 if ( target
.atom
!= NULL
) {
6863 if ( target
.atom
->isThumb() )
6864 target
.addend
&= -2; // remove thumb bit
6865 // if reference to LSDA, add group subordinate fixup
6866 if ( target
.atom
->contentType() == ld::Atom::typeLSDA
) {
6867 Parser
<arm
>::SourceLocation src2
;
6868 src2
.atom
= src
.atom
;
6869 src2
.offsetInAtom
= 0;
6870 parser
.addFixup(src2
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinateLSDA
, target
.atom
);
6874 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian32
, target
);
6876 case ARM_THUMB_32BIT_BRANCH
:
6877 // silently ignore old unnecessary reloc
6879 case ARM_RELOC_HALF
:
6880 nextReloc
= &reloc
[1];
6881 if ( nextReloc
->r_type() == ARM_RELOC_PAIR
) {
6882 uint32_t instruction16
;
6883 uint32_t other16
= (nextReloc
->r_address() & 0xFFFF);
6885 if ( reloc
->r_length() & 2 ) {
6887 uint32_t i
= ((instruction
& 0x00000400) >> 10);
6888 uint32_t imm4
= (instruction
& 0x0000000F);
6889 uint32_t imm3
= ((instruction
& 0x70000000) >> 28);
6890 uint32_t imm8
= ((instruction
& 0x00FF0000) >> 16);
6891 instruction16
= (imm4
<< 12) | (i
<< 11) | (imm3
<< 8) | imm8
;
6895 uint32_t imm4
= ((instruction
& 0x000F0000) >> 16);
6896 uint32_t imm12
= (instruction
& 0x00000FFF);
6897 instruction16
= (imm4
<< 12) | imm12
;
6899 if ( reloc
->r_length() & 1 ) {
6901 dstAddr
= ((instruction16
<< 16) | other16
);
6902 if ( reloc
->r_extern() ) {
6903 target
.addend
= dstAddr
;
6904 if ( externSymbolIsThumbDef
)
6905 target
.addend
&= -2; // remove thumb bit
6908 parser
.findTargetFromAddress(dstAddr
, target
);
6909 if ( target
.atom
->isThumb() )
6910 target
.addend
&= (-2); // remove thumb bit
6912 parser
.addFixups(src
, (isThumb
? ld::Fixup::kindStoreThumbHigh16
: ld::Fixup::kindStoreARMHigh16
), target
);
6916 dstAddr
= (other16
<< 16) | instruction16
;
6917 if ( reloc
->r_extern() ) {
6918 target
.addend
= dstAddr
;
6919 if ( externSymbolIsThumbDef
)
6920 target
.addend
&= -2; // remove thumb bit
6923 parser
.findTargetFromAddress(dstAddr
, target
);
6924 if ( target
.atom
->isThumb() )
6925 target
.addend
&= (-2); // remove thumb bit
6927 parser
.addFixups(src
, (isThumb
? ld::Fixup::kindStoreThumbLow16
: ld::Fixup::kindStoreARMLow16
), target
);
6932 throw "for ARM_RELOC_HALF, next reloc is not ARM_RELOC_PAIR";
6935 throwf("unknown relocation type %d", reloc
->r_type());
6940 const macho_scattered_relocation_info
<P
>* sreloc
= (macho_scattered_relocation_info
<P
>*)reloc
;
6941 // file format allows pair to be scattered or not
6942 const macho_scattered_relocation_info
<P
>* nextSReloc
= &sreloc
[1];
6943 nextReloc
= &reloc
[1];
6944 srcAddr
= sect
->addr() + sreloc
->r_address();
6945 dstAddr
= sreloc
->r_value();
6946 fixUpPtr
= (uint32_t*)(file().fileContent() + sect
->offset() + sreloc
->r_address());
6947 instruction
= LittleEndian::get32(*fixUpPtr
);
6948 src
.atom
= this->findAtomByAddress(srcAddr
);
6949 src
.offsetInAtom
= srcAddr
- src
.atom
->_objAddress
;
6950 bool nextRelocIsPair
= false;
6951 uint32_t nextRelocAddress
= 0;
6952 uint32_t nextRelocValue
= 0;
6953 if ( (nextReloc
->r_address() & R_SCATTERED
) == 0 ) {
6954 if ( nextReloc
->r_type() == ARM_RELOC_PAIR
) {
6955 nextRelocIsPair
= true;
6956 nextRelocAddress
= nextReloc
->r_address();
6961 if ( nextSReloc
->r_type() == ARM_RELOC_PAIR
) {
6962 nextRelocIsPair
= true;
6963 nextRelocAddress
= nextSReloc
->r_address();
6964 nextRelocValue
= nextSReloc
->r_value();
6968 switch ( sreloc
->r_type() ) {
6969 case ARM_RELOC_VANILLA
:
6970 // with a scattered relocation we get both the target (sreloc->r_value()) and the target+offset (*fixUpPtr)
6971 if ( sreloc
->r_length() != 2 )
6972 throw "bad length for ARM_RELOC_VANILLA";
6973 target
.atom
= parser
.findAtomByAddress(sreloc
->r_value());
6974 if ( target
.atom
== NULL
)
6975 throwf("bad r_value (0x%08X) for ARM_RELOC_VANILLA\n", sreloc
->r_value());
6976 contentValue
= LittleEndian::get32(*fixUpPtr
);
6977 target
.addend
= contentValue
- target
.atom
->_objAddress
;
6978 if ( target
.atom
->isThumb() )
6979 target
.addend
&= -2; // remove thumb bit
6980 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian32
, target
);
6982 case ARM_RELOC_BR24
:
6983 // Sign-extend displacement
6984 displacement
= (instruction
& 0x00FFFFFF) << 2;
6985 if ( (displacement
& 0x02000000) != 0 )
6986 displacement
|= 0xFC000000;
6987 // The pc added will be +8 from the pc
6989 // If this is BLX add H << 1
6990 if ((instruction
& 0xFE000000) == 0xFA000000)
6991 displacement
+= ((instruction
& 0x01000000) >> 23);
6992 target
.atom
= parser
.findAtomByAddress(sreloc
->r_value());
6993 target
.addend
= (int64_t)(srcAddr
+ displacement
) - (int64_t)(target
.atom
->_objAddress
);
6994 parser
.addFixups(src
, ld::Fixup::kindStoreARMBranch24
, target
);
6996 case ARM_THUMB_RELOC_BR22
:
6997 // thumb2 added two more bits to displacement, complicating the displacement decoding
6999 uint32_t s
= (instruction
>> 10) & 0x1;
7000 uint32_t j1
= (instruction
>> 29) & 0x1;
7001 uint32_t j2
= (instruction
>> 27) & 0x1;
7002 uint32_t imm10
= instruction
& 0x3FF;
7003 uint32_t imm11
= (instruction
>> 16) & 0x7FF;
7004 uint32_t i1
= (j1
== s
);
7005 uint32_t i2
= (j2
== s
);
7006 uint32_t dis
= (s
<< 24) | (i1
<< 23) | (i2
<< 22) | (imm10
<< 12) | (imm11
<< 1);
7010 displacement
= sdis
;
7012 // The pc added will be +4 from the pc
7014 dstAddr
= srcAddr
+displacement
;
7015 // If the instruction was blx, force the low 2 bits to be clear
7016 if ((instruction
& 0xF8000000) == 0xE8000000)
7017 dstAddr
&= 0xFFFFFFFC;
7018 target
.atom
= parser
.findAtomByAddress(sreloc
->r_value());
7019 target
.addend
= dstAddr
- target
.atom
->_objAddress
;
7020 parser
.addFixups(src
, ld::Fixup::kindStoreThumbBranch22
, target
);
7022 case ARM_RELOC_SECTDIFF
:
7023 case ARM_RELOC_LOCAL_SECTDIFF
:
7025 if ( ! nextRelocIsPair
)
7026 throw "ARM_RELOC_SECTDIFF missing following pair";
7027 if ( sreloc
->r_length() != 2 )
7028 throw "bad length for ARM_RELOC_SECTDIFF";
7029 contentValue
= LittleEndian::get32(*fixUpPtr
);
7030 Atom
<arm
>* fromAtom
= parser
.findAtomByAddress(nextRelocValue
);
7031 uint32_t offsetInFrom
= nextRelocValue
- fromAtom
->_objAddress
;
7032 uint32_t offsetInTarget
;
7033 Atom
<arm
>* targetAtom
= parser
.findAtomByAddressOrLocalTargetOfStub(sreloc
->r_value(), &offsetInTarget
);
7034 // check for addend encoded in the section content
7035 int64_t addend
= (int32_t)contentValue
- (int32_t)(sreloc
->r_value() - nextRelocValue
);
7036 if ( targetAtom
->isThumb() )
7037 addend
&= -2; // remove thumb bit
7038 // if reference to LSDA, add group subordinate fixup
7039 if ( targetAtom
->contentType() == ld::Atom::typeLSDA
) {
7040 Parser
<arm
>::SourceLocation src2
;
7041 src2
.atom
= src
.atom
;
7042 src2
.offsetInAtom
= 0;
7043 parser
.addFixup(src2
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinateLSDA
, targetAtom
);
7046 // switch binding base on coalescing
7047 if ( targetAtom
->scope() == ld::Atom::scopeTranslationUnit
) {
7048 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, targetAtom
);
7050 else if ( (targetAtom
->combine() == ld::Atom::combineByNameAndContent
) || (targetAtom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
7051 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, targetAtom
);
7054 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, targetAtom
->name());
7056 parser
.addFixup(src
, ld::Fixup::k2of5
, ld::Fixup::kindAddAddend
, offsetInTarget
);
7057 parser
.addFixup(src
, ld::Fixup::k3of5
, ld::Fixup::kindSubtractTargetAddress
, fromAtom
);
7058 parser
.addFixup(src
, ld::Fixup::k4of5
, ld::Fixup::kindSubtractAddend
, offsetInFrom
-addend
);
7059 parser
.addFixup(src
, ld::Fixup::k5of5
, ld::Fixup::kindStoreLittleEndian32
);
7062 if ( targetAtom
->scope() == ld::Atom::scopeTranslationUnit
) {
7063 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, targetAtom
);
7065 else if ( (targetAtom
->combine() == ld::Atom::combineByNameAndContent
) || (targetAtom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
7066 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, targetAtom
);
7069 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, targetAtom
->name());
7071 parser
.addFixup(src
, ld::Fixup::k2of5
, ld::Fixup::kindAddAddend
, (uint32_t)(offsetInTarget
+addend
));
7072 parser
.addFixup(src
, ld::Fixup::k3of5
, ld::Fixup::kindSubtractTargetAddress
, fromAtom
);
7073 parser
.addFixup(src
, ld::Fixup::k4of5
, ld::Fixup::kindSubtractAddend
, offsetInFrom
);
7074 parser
.addFixup(src
, ld::Fixup::k5of5
, ld::Fixup::kindStoreLittleEndian32
);
7078 case ARM_RELOC_HALF_SECTDIFF
:
7079 if ( nextRelocIsPair
) {
7080 instruction
= LittleEndian::get32(*fixUpPtr
);
7081 Atom
<arm
>* fromAtom
= parser
.findAtomByAddress(nextRelocValue
);
7082 uint32_t offsetInFrom
= nextRelocValue
- fromAtom
->_objAddress
;
7083 Atom
<arm
>* targetAtom
= parser
.findAtomByAddress(sreloc
->r_value());
7084 uint32_t offsetInTarget
= sreloc
->r_value() - targetAtom
->_objAddress
;
7085 uint32_t instruction16
;
7086 uint32_t other16
= (nextRelocAddress
& 0xFFFF);
7088 if ( sreloc
->r_length() & 2 ) {
7090 uint32_t i
= ((instruction
& 0x00000400) >> 10);
7091 uint32_t imm4
= (instruction
& 0x0000000F);
7092 uint32_t imm3
= ((instruction
& 0x70000000) >> 28);
7093 uint32_t imm8
= ((instruction
& 0x00FF0000) >> 16);
7094 instruction16
= (imm4
<< 12) | (i
<< 11) | (imm3
<< 8) | imm8
;
7098 uint32_t imm4
= ((instruction
& 0x000F0000) >> 16);
7099 uint32_t imm12
= (instruction
& 0x00000FFF);
7100 instruction16
= (imm4
<< 12) | imm12
;
7102 if ( sreloc
->r_length() & 1 )
7103 dstAddr
= ((instruction16
<< 16) | other16
);
7105 dstAddr
= (other16
<< 16) | instruction16
;
7106 if ( targetAtom
->isThumb() )
7107 dstAddr
&= (-2); // remove thumb bit
7108 int32_t addend
= dstAddr
- (sreloc
->r_value() - nextRelocValue
);
7109 if ( targetAtom
->scope() == ld::Atom::scopeTranslationUnit
) {
7110 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, targetAtom
);
7112 else if ( (targetAtom
->combine() == ld::Atom::combineByNameAndContent
) || (targetAtom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
7113 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, targetAtom
);
7116 parser
.addFixup(src
, ld::Fixup::k1of5
, ld::Fixup::kindSetTargetAddress
, false, targetAtom
->name());
7118 parser
.addFixup(src
, ld::Fixup::k2of5
, ld::Fixup::kindAddAddend
, (uint32_t)offsetInTarget
+addend
);
7119 parser
.addFixup(src
, ld::Fixup::k3of5
, ld::Fixup::kindSubtractTargetAddress
, fromAtom
);
7120 parser
.addFixup(src
, ld::Fixup::k4of5
, ld::Fixup::kindSubtractAddend
, offsetInFrom
);
7121 if ( sreloc
->r_length() & 1 ) {
7123 parser
.addFixup(src
, ld::Fixup::k5of5
, (isThumb
? ld::Fixup::kindStoreThumbHigh16
: ld::Fixup::kindStoreARMHigh16
));
7127 parser
.addFixup(src
, ld::Fixup::k5of5
, (isThumb
? ld::Fixup::kindStoreThumbLow16
: ld::Fixup::kindStoreARMLow16
));
7132 throw "ARM_RELOC_HALF_SECTDIFF reloc missing following pair";
7134 case ARM_RELOC_HALF
:
7135 if ( nextRelocIsPair
) {
7136 instruction
= LittleEndian::get32(*fixUpPtr
);
7137 Atom
<arm
>* targetAtom
= parser
.findAtomByAddress(sreloc
->r_value());
7138 uint32_t instruction16
;
7139 uint32_t other16
= (nextRelocAddress
& 0xFFFF);
7141 if ( sreloc
->r_length() & 2 ) {
7143 uint32_t i
= ((instruction
& 0x00000400) >> 10);
7144 uint32_t imm4
= (instruction
& 0x0000000F);
7145 uint32_t imm3
= ((instruction
& 0x70000000) >> 28);
7146 uint32_t imm8
= ((instruction
& 0x00FF0000) >> 16);
7147 instruction16
= (imm4
<< 12) | (i
<< 11) | (imm3
<< 8) | imm8
;
7151 uint32_t imm4
= ((instruction
& 0x000F0000) >> 16);
7152 uint32_t imm12
= (instruction
& 0x00000FFF);
7153 instruction16
= (imm4
<< 12) | imm12
;
7155 if ( sreloc
->r_length() & 1 )
7156 dstAddr
= ((instruction16
<< 16) | other16
);
7158 dstAddr
= (other16
<< 16) | instruction16
;
7159 if ( targetAtom
->scope() == ld::Atom::scopeTranslationUnit
) {
7160 parser
.addFixup(src
, ld::Fixup::k1of3
, ld::Fixup::kindSetTargetAddress
, targetAtom
);
7162 else if ( (targetAtom
->combine() == ld::Atom::combineByNameAndContent
) || (targetAtom
->combine() == ld::Atom::combineByNameAndReferences
) ) {
7163 parser
.addFixup(src
, ld::Fixup::k1of3
, ld::Fixup::kindSetTargetAddress
, ld::Fixup::bindingByContentBound
, targetAtom
);
7166 parser
.addFixup(src
, ld::Fixup::k1of3
, ld::Fixup::kindSetTargetAddress
, false, targetAtom
->name());
7168 parser
.addFixup(src
, ld::Fixup::k2of3
, ld::Fixup::kindAddAddend
, dstAddr
- targetAtom
->_objAddress
);
7169 if ( sreloc
->r_length() & 1 ) {
7171 parser
.addFixup(src
, ld::Fixup::k3of3
, (isThumb
? ld::Fixup::kindStoreThumbHigh16
: ld::Fixup::kindStoreARMHigh16
));
7175 parser
.addFixup(src
, ld::Fixup::k3of3
, (isThumb
? ld::Fixup::kindStoreThumbLow16
: ld::Fixup::kindStoreARMLow16
));
7180 throw "scattered ARM_RELOC_HALF reloc missing following pair";
7183 throwf("unknown ARM scattered relocation type %d", sreloc
->r_type());
7191 #if SUPPORT_ARCH_arm64
7193 bool Section
<arm64
>::addRelocFixup(class Parser
<arm64
>& parser
, const macho_relocation_info
<P
>* reloc
)
7195 bool result
= false;
7196 Parser
<arm64
>::SourceLocation src
;
7197 Parser
<arm64
>::TargetDesc target
= { NULL
, NULL
, false, 0 };
7198 Parser
<arm64
>::TargetDesc toTarget
;
7199 int32_t prefixRelocAddend
= 0;
7200 if ( reloc
->r_type() == ARM64_RELOC_ADDEND
) {
7201 uint32_t rawAddend
= reloc
->r_symbolnum();
7202 prefixRelocAddend
= rawAddend
;
7203 if ( rawAddend
& 0x00800000 )
7204 prefixRelocAddend
|= 0xFF000000; // sign extend 24-bit signed int to 32-bits
7205 uint32_t addendAddress
= reloc
->r_address();
7206 ++reloc
; //advance to next reloc record
7208 if ( reloc
->r_address() != addendAddress
)
7209 throw "ARM64_RELOC_ADDEND r_address does not match next reloc's r_address";
7211 const macho_section
<P
>* sect
= this->machoSection();
7212 uint64_t srcAddr
= sect
->addr() + reloc
->r_address();
7213 src
.atom
= this->findAtomByAddress(srcAddr
);
7214 src
.offsetInAtom
= srcAddr
- src
.atom
->_objAddress
;
7215 const uint8_t* fixUpPtr
= file().fileContent() + sect
->offset() + reloc
->r_address();
7216 uint64_t contentValue
= 0;
7217 const macho_relocation_info
<arm64::P
>* nextReloc
= &reloc
[1];
7218 bool useDirectBinding
;
7219 uint32_t instruction
;
7220 uint32_t encodedAddend
;
7221 switch ( reloc
->r_length() ) {
7223 contentValue
= *fixUpPtr
;
7226 contentValue
= (int64_t)(int16_t)E::get16(*((uint16_t*)fixUpPtr
));
7229 contentValue
= (int64_t)(int32_t)E::get32(*((uint32_t*)fixUpPtr
));
7232 contentValue
= E::get64(*((uint64_t*)fixUpPtr
));
7235 if ( reloc
->r_extern() ) {
7236 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(reloc
->r_symbolnum());
7237 const char* symbolName
= parser
.nameFromSymbol(sym
);
7238 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && (((sym
.n_type() & N_EXT
) == 0) || (symbolName
[0] == 'L') || (symbolName
[0] == 'l')) ) {
7239 // use direct reference for local symbols
7240 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
7241 //target.addend += contentValue;
7243 else if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && (src
.atom
->_objAddress
<= sym
.n_value()) && (sym
.n_value() < (src
.atom
->_objAddress
+src
.atom
->size())) ) {
7244 // <rdar://problem/13700961> spurious warning when weak function has reference to itself
7245 // use direct reference when atom targets itself
7246 target
.atom
= src
.atom
;
7250 target
.name
= symbolName
;
7251 target
.weakImport
= parser
.weakImportFromSymbol(sym
);
7252 //target.addend = contentValue;
7254 // cfstrings should always use direct reference to backing store
7255 if ( (this->type() == ld::Section::typeCFString
) && (src
.offsetInAtom
!= 0) ) {
7256 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), target
);
7257 //target.addend = contentValue;
7261 if ( reloc
->r_pcrel() )
7262 contentValue
+= srcAddr
;
7263 parser
.findTargetFromAddressAndSectionNum(contentValue
, reloc
->r_symbolnum(), target
);
7265 switch ( reloc
->r_type() ) {
7266 case ARM64_RELOC_UNSIGNED
:
7267 if ( reloc
->r_pcrel() )
7268 throw "pcrel and ARM64_RELOC_UNSIGNED not supported";
7269 if ( reloc
->r_extern() )
7270 target
.addend
= contentValue
;
7271 switch ( reloc
->r_length() ) {
7274 throw "length < 2 and ARM64_RELOC_UNSIGNED not supported";
7276 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian32
, target
);
7279 parser
.addFixups(src
, ld::Fixup::kindStoreLittleEndian64
, target
);
7283 case ARM64_RELOC_BRANCH26
:
7284 if ( ! reloc
->r_pcrel() )
7285 throw "not pcrel and ARM64_RELOC_BRANCH26 not supported";
7286 if ( ! reloc
->r_extern() )
7287 throw "r_extern == 0 and ARM64_RELOC_BRANCH26 not supported";
7288 if ( reloc
->r_length() != 2 )
7289 throw "r_length != 2 and ARM64_RELOC_BRANCH26 not supported";
7290 if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_probe$", 16) == 0) ) {
7291 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindStoreARM64DtraceCallSiteNop
, false, target
.name
);
7292 parser
.addDtraceExtraInfos(src
, &target
.name
[16]);
7294 else if ( (target
.name
!= NULL
) && (strncmp(target
.name
, "___dtrace_isenabled$", 20) == 0) ) {
7295 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindStoreARM64DtraceIsEnableSiteClear
, false, target
.name
);
7296 parser
.addDtraceExtraInfos(src
, &target
.name
[20]);
7299 target
.addend
= prefixRelocAddend
;
7300 instruction
= contentValue
;
7301 encodedAddend
= (instruction
& 0x03FFFFFF) << 2;
7302 if ( encodedAddend
!= 0 ) {
7303 if ( prefixRelocAddend
== 0 ) {
7304 warning("branch26 instruction at 0x%08X has embedded addend. ARM64_RELOC_ADDEND should be used instead", reloc
->r_address());
7305 target
.addend
= encodedAddend
;
7308 throwf("branch26 instruction at 0x%08X has embedded addend and ARM64_RELOC_ADDEND also used", reloc
->r_address());
7311 parser
.addFixups(src
, ld::Fixup::kindStoreARM64Branch26
, target
);
7314 case ARM64_RELOC_PAGE21
:
7315 if ( ! reloc
->r_pcrel() )
7316 throw "not pcrel and ARM64_RELOC_PAGE21 not supported";
7317 if ( ! reloc
->r_extern() )
7318 throw "r_extern == 0 and ARM64_RELOC_PAGE21 not supported";
7319 if ( reloc
->r_length() != 2 )
7320 throw "length != 2 and ARM64_RELOC_PAGE21 not supported";
7321 target
.addend
= prefixRelocAddend
;
7322 instruction
= contentValue
;
7323 encodedAddend
= ((instruction
& 0x60000000) >> 29) | ((instruction
& 0x01FFFFE0) >> 3);
7324 encodedAddend
*= 4096; // internally addend is in bytes, so scale
7325 if ( encodedAddend
!= 0 ) {
7326 if ( prefixRelocAddend
== 0 ) {
7327 warning("adrp instruction at 0x%08X has embedded addend. ARM64_RELOC_ADDEND should be used instead", reloc
->r_address());
7328 target
.addend
= encodedAddend
;
7331 throwf("adrp instruction at 0x%08X has embedded addend and ARM64_RELOC_ADDEND also used", reloc
->r_address());
7334 parser
.addFixups(src
, ld::Fixup::kindStoreARM64Page21
, target
);
7336 case ARM64_RELOC_PAGEOFF12
:
7337 if ( reloc
->r_pcrel() )
7338 throw "pcrel and ARM64_RELOC_PAGEOFF12 not supported";
7339 if ( ! reloc
->r_extern() )
7340 throw "r_extern == 0 and ARM64_RELOC_PAGEOFF12 not supported";
7341 if ( reloc
->r_length() != 2 )
7342 throw "length != 2 and ARM64_RELOC_PAGEOFF12 not supported";
7343 target
.addend
= prefixRelocAddend
;
7344 instruction
= contentValue
;
7345 encodedAddend
= ((instruction
& 0x003FFC00) >> 10);
7346 // internally addend is in bytes. Some instructions have an implicit scale factor
7347 if ( (instruction
& 0x3B000000) == 0x39000000 ) {
7348 switch ( instruction
& 0xC0000000 ) {
7362 if ( encodedAddend
!= 0 ) {
7363 if ( prefixRelocAddend
== 0 ) {
7364 warning("pageoff12 instruction at 0x%08X has embedded addend. ARM64_RELOC_ADDEND should be used instead", reloc
->r_address());
7365 target
.addend
= encodedAddend
;
7368 throwf("pageoff12 instruction at 0x%08X has embedded addend and ARM64_RELOC_ADDEND also used", reloc
->r_address());
7371 parser
.addFixups(src
, ld::Fixup::kindStoreARM64PageOff12
, target
);
7373 case ARM64_RELOC_GOT_LOAD_PAGE21
:
7374 if ( ! reloc
->r_pcrel() )
7375 throw "not pcrel and ARM64_RELOC_GOT_LOAD_PAGE21 not supported";
7376 if ( ! reloc
->r_extern() )
7377 throw "r_extern == 0 and ARM64_RELOC_GOT_LOAD_PAGE21 not supported";
7378 if ( reloc
->r_length() != 2 )
7379 throw "length != 2 and ARM64_RELOC_GOT_LOAD_PAGE21 not supported";
7380 if ( prefixRelocAddend
!= 0 )
7381 throw "ARM64_RELOC_ADDEND followed by ARM64_RELOC_GOT_LOAD_PAGE21 not supported";
7382 instruction
= contentValue
;
7383 target
.addend
= ((instruction
& 0x60000000) >> 29) | ((instruction
& 0x01FFFFE0) >> 3);
7384 if ( target
.addend
!= 0 )
7385 throw "non-zero addend with ARM64_RELOC_GOT_LOAD_PAGE21 is not supported";
7386 parser
.addFixups(src
, ld::Fixup::kindStoreARM64GOTLoadPage21
, target
);
7388 case ARM64_RELOC_GOT_LOAD_PAGEOFF12
:
7389 if ( reloc
->r_pcrel() )
7390 throw "pcrel and ARM64_RELOC_GOT_LOAD_PAGEOFF12 not supported";
7391 if ( ! reloc
->r_extern() )
7392 throw "r_extern == 0 and ARM64_RELOC_GOT_LOAD_PAGEOFF12 not supported";
7393 if ( reloc
->r_length() != 2 )
7394 throw "length != 2 and ARM64_RELOC_GOT_LOAD_PAGEOFF12 not supported";
7395 if ( prefixRelocAddend
!= 0 )
7396 throw "ARM64_RELOC_ADDEND followed by ARM64_RELOC_GOT_LOAD_PAGEOFF12 not supported";
7397 instruction
= contentValue
;
7398 target
.addend
= ((instruction
& 0x003FFC00) >> 10);
7399 parser
.addFixups(src
, ld::Fixup::kindStoreARM64GOTLoadPageOff12
, target
);
7401 case ARM64_RELOC_TLVP_LOAD_PAGE21
:
7402 if ( ! reloc
->r_pcrel() )
7403 throw "not pcrel and ARM64_RELOC_TLVP_LOAD_PAGE21 not supported";
7404 if ( ! reloc
->r_extern() )
7405 throw "r_extern == 0 and ARM64_RELOC_TLVP_LOAD_PAGE21 not supported";
7406 if ( reloc
->r_length() != 2 )
7407 throw "length != 2 and ARM64_RELOC_TLVP_LOAD_PAGE21 not supported";
7408 if ( prefixRelocAddend
!= 0 )
7409 throw "ARM64_RELOC_ADDEND followed by ARM64_RELOC_TLVP_LOAD_PAGE21 not supported";
7410 instruction
= contentValue
;
7411 target
.addend
= ((instruction
& 0x60000000) >> 29) | ((instruction
& 0x01FFFFE0) >> 3);
7412 if ( target
.addend
!= 0 )
7413 throw "non-zero addend with ARM64_RELOC_GOT_LOAD_PAGE21 is not supported";
7414 parser
.addFixups(src
, ld::Fixup::kindStoreARM64TLVPLoadPage21
, target
);
7416 case ARM64_RELOC_TLVP_LOAD_PAGEOFF12
:
7417 if ( reloc
->r_pcrel() )
7418 throw "pcrel and ARM64_RELOC_TLVP_LOAD_PAGEOFF12 not supported";
7419 if ( ! reloc
->r_extern() )
7420 throw "r_extern == 0 and ARM64_RELOC_TLVP_LOAD_PAGEOFF12 not supported";
7421 if ( reloc
->r_length() != 2 )
7422 throw "length != 2 and ARM64_RELOC_TLVP_LOAD_PAGEOFF12 not supported";
7423 if ( prefixRelocAddend
!= 0 )
7424 throw "ARM64_RELOC_ADDEND followed by ARM64_RELOC_TLVP_LOAD_PAGEOFF12 not supported";
7425 instruction
= contentValue
;
7426 target
.addend
= ((instruction
& 0x003FFC00) >> 10);
7427 parser
.addFixups(src
, ld::Fixup::kindStoreARM64TLVPLoadPageOff12
, target
);
7429 case ARM64_RELOC_SUBTRACTOR
:
7430 if ( reloc
->r_pcrel() )
7431 throw "ARM64_RELOC_SUBTRACTOR cannot be pc-relative";
7432 if ( reloc
->r_length() < 2 )
7433 throw "ARM64_RELOC_SUBTRACTOR must have r_length of 2 or 3";
7434 if ( !reloc
->r_extern() )
7435 throw "ARM64_RELOC_SUBTRACTOR must have r_extern=1";
7436 if ( nextReloc
->r_type() != ARM64_RELOC_UNSIGNED
)
7437 throw "ARM64_RELOC_SUBTRACTOR must be followed by ARM64_RELOC_UNSIGNED";
7438 if ( prefixRelocAddend
!= 0 )
7439 throw "ARM64_RELOC_ADDEND followed by ARM64_RELOC_SUBTRACTOR not supported";
7441 if ( nextReloc
->r_pcrel() )
7442 throw "ARM64_RELOC_UNSIGNED following a ARM64_RELOC_SUBTRACTOR cannot be pc-relative";
7443 if ( nextReloc
->r_length() != reloc
->r_length() )
7444 throw "ARM64_RELOC_UNSIGNED following a ARM64_RELOC_SUBTRACTOR must have same r_length";
7445 if ( nextReloc
->r_extern() ) {
7446 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(nextReloc
->r_symbolnum());
7447 // use direct reference for local symbols
7448 if ( ((sym
.n_type() & N_TYPE
) == N_SECT
) && (((sym
.n_type() & N_EXT
) == 0) || (parser
.nameFromSymbol(sym
)[0] == 'L')) ) {
7449 parser
.findTargetFromAddressAndSectionNum(sym
.n_value(), sym
.n_sect(), toTarget
);
7450 toTarget
.addend
= contentValue
;
7451 useDirectBinding
= true;
7454 toTarget
.name
= parser
.nameFromSymbol(sym
);
7455 toTarget
.weakImport
= parser
.weakImportFromSymbol(sym
);
7456 toTarget
.addend
= contentValue
;
7457 useDirectBinding
= false;
7461 parser
.findTargetFromAddressAndSectionNum(contentValue
, nextReloc
->r_symbolnum(), toTarget
);
7462 useDirectBinding
= (toTarget
.atom
->scope() == ld::Atom::scopeTranslationUnit
);
7464 if ( useDirectBinding
)
7465 parser
.addFixup(src
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, toTarget
.atom
);
7467 parser
.addFixup(src
, ld::Fixup::k1of4
, ld::Fixup::kindSetTargetAddress
, toTarget
.weakImport
, toTarget
.name
);
7468 parser
.addFixup(src
, ld::Fixup::k2of4
, ld::Fixup::kindAddAddend
, toTarget
.addend
);
7469 if ( target
.atom
== NULL
)
7470 parser
.addFixup(src
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractTargetAddress
, false, target
.name
);
7472 parser
.addFixup(src
, ld::Fixup::k3of4
, ld::Fixup::kindSubtractTargetAddress
, target
.atom
);
7473 if ( reloc
->r_length() == 2 )
7474 parser
.addFixup(src
, ld::Fixup::k4of4
, ld::Fixup::kindStoreLittleEndian32
);
7476 parser
.addFixup(src
, ld::Fixup::k4of4
, ld::Fixup::kindStoreLittleEndian64
);
7478 case ARM64_RELOC_POINTER_TO_GOT
:
7479 if ( ! reloc
->r_extern() )
7480 throw "r_extern == 0 and ARM64_RELOC_POINTER_TO_GOT not supported";
7481 if ( prefixRelocAddend
!= 0 )
7482 throw "ARM64_RELOC_ADDEND followed by ARM64_RELOC_POINTER_TO_GOT not supported";
7483 if ( reloc
->r_pcrel() ) {
7484 if ( reloc
->r_length() != 2 )
7485 throw "r_length != 2 and r_extern = 1 and ARM64_RELOC_POINTER_TO_GOT not supported";
7486 parser
.addFixups(src
, ld::Fixup::kindStoreARM64PCRelToGOT
, target
);
7489 if ( reloc
->r_length() != 3 )
7490 throw "r_length != 3 and r_extern = 0 and ARM64_RELOC_POINTER_TO_GOT not supported";
7491 parser
.addFixups(src
, ld::Fixup::kindStoreARM64PointerToGOT
, target
);
7495 throwf("unknown relocation type %d", reloc
->r_type());
7502 template <typename A
>
7503 bool ObjC1ClassSection
<A
>::addRelocFixup(class Parser
<A
>& parser
, const macho_relocation_info
<P
>* reloc
)
7506 FixedSizeSection
<A
>::addRelocFixup(parser
, reloc
);
7508 assert(0 && "needs template specialization");
7513 bool ObjC1ClassSection
<x86
>::addRelocFixup(class Parser
<x86
>& parser
, const macho_relocation_info
<x86::P
>* reloc
)
7515 // if this is the reloc for the super class name string, add implicit reference to super class
7516 if ( ((reloc
->r_address() & R_SCATTERED
) == 0) && (reloc
->r_type() == GENERIC_RELOC_VANILLA
) ) {
7517 assert( reloc
->r_length() == 2 );
7518 assert( ! reloc
->r_pcrel() );
7520 const macho_section
<P
>* sect
= this->machoSection();
7521 Parser
<x86
>::SourceLocation src
;
7522 uint32_t srcAddr
= sect
->addr() + reloc
->r_address();
7523 src
.atom
= this->findAtomByAddress(srcAddr
);
7524 src
.offsetInAtom
= srcAddr
- src
.atom
->objectAddress();
7525 if ( src
.offsetInAtom
== 4 ) {
7526 Parser
<x86
>::TargetDesc stringTarget
;
7527 const uint8_t* fixUpPtr
= file().fileContent() + sect
->offset() + reloc
->r_address();
7528 uint32_t contentValue
= LittleEndian::get32(*((uint32_t*)fixUpPtr
));
7529 parser
.findTargetFromAddressAndSectionNum(contentValue
, reloc
->r_symbolnum(), stringTarget
);
7531 assert(stringTarget
.atom
!= NULL
);
7532 assert(stringTarget
.atom
->contentType() == ld::Atom::typeCString
);
7533 const char* superClassBaseName
= (char*)stringTarget
.atom
->rawContentPointer();
7534 char* superClassName
= new char[strlen(superClassBaseName
) + 20];
7535 strcpy(superClassName
, ".objc_class_name_");
7536 strcat(superClassName
, superClassBaseName
);
7538 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindSetTargetAddress
, false, superClassName
);
7542 return FixedSizeSection
<x86
>::addRelocFixup(parser
, reloc
);
7547 template <typename A
>
7548 bool Objc1ClassReferences
<A
>::addRelocFixup(class Parser
<A
>& parser
, const macho_relocation_info
<P
>* reloc
)
7551 PointerToCStringSection
<A
>::addRelocFixup(parser
, reloc
);
7553 assert(0 && "needs template specialization");
7560 bool Objc1ClassReferences
<x86
>::addRelocFixup(class Parser
<x86
>& parser
, const macho_relocation_info
<x86::P
>* reloc
)
7562 // add implict class refs, fixups not usable yet, so look at relocations
7563 assert( (reloc
->r_address() & R_SCATTERED
) == 0 );
7564 assert( reloc
->r_type() == GENERIC_RELOC_VANILLA
);
7565 assert( reloc
->r_length() == 2 );
7566 assert( ! reloc
->r_pcrel() );
7568 const macho_section
<P
>* sect
= this->machoSection();
7569 Parser
<x86
>::SourceLocation src
;
7570 uint32_t srcAddr
= sect
->addr() + reloc
->r_address();
7571 src
.atom
= this->findAtomByAddress(srcAddr
);
7572 src
.offsetInAtom
= srcAddr
- src
.atom
->objectAddress();
7573 Parser
<x86
>::TargetDesc stringTarget
;
7574 const uint8_t* fixUpPtr
= file().fileContent() + sect
->offset() + reloc
->r_address();
7575 uint32_t contentValue
= LittleEndian::get32(*((uint32_t*)fixUpPtr
));
7576 parser
.findTargetFromAddressAndSectionNum(contentValue
, reloc
->r_symbolnum(), stringTarget
);
7578 assert(stringTarget
.atom
!= NULL
);
7579 assert(stringTarget
.atom
->contentType() == ld::Atom::typeCString
);
7580 const char* baseClassName
= (char*)stringTarget
.atom
->rawContentPointer();
7581 char* objcClassName
= new char[strlen(baseClassName
) + 20];
7582 strcpy(objcClassName
, ".objc_class_name_");
7583 strcat(objcClassName
, baseClassName
);
7585 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindSetTargetAddress
, false, objcClassName
);
7588 return PointerToCStringSection
<x86
>::addRelocFixup(parser
, reloc
);
7591 #if SUPPORT_ARCH_arm64
7593 void Section
<arm64
>::addLOH(class Parser
<arm64
>& parser
, int kind
, int count
, const uint64_t addrs
[]) {
7595 case LOH_ARM64_ADRP_ADRP
:
7596 case LOH_ARM64_ADRP_LDR
:
7597 case LOH_ARM64_ADRP_ADD
:
7598 case LOH_ARM64_ADRP_LDR_GOT
:
7600 warning("arm64 Linker Optimiztion Hint %d has wrong number of arguments", kind
);
7602 case LOH_ARM64_ADRP_ADD_LDR
:
7603 case LOH_ARM64_ADRP_LDR_GOT_LDR
:
7604 case LOH_ARM64_ADRP_ADD_STR
:
7605 case LOH_ARM64_ADRP_LDR_GOT_STR
:
7607 warning("arm64 Linker Optimiztion Hint %d has wrong number of arguments", kind
);
7610 // pick lowest address in tuple for use as offsetInAtom
7611 uint64_t lowestAddress
= addrs
[0];
7612 for(int i
=1; i
< count
; ++i
) {
7613 if ( addrs
[i
] < lowestAddress
)
7614 lowestAddress
= addrs
[i
];
7616 // verify all other address are in same atom
7617 Atom
<arm64
>* inAtom
= parser
.findAtomByAddress(lowestAddress
);
7618 const uint64_t atomStartAddr
= inAtom
->objectAddress();
7619 const uint64_t atomEndAddr
= atomStartAddr
+ inAtom
->size();
7620 for(int i
=0; i
< count
; ++i
) {
7621 if ( (addrs
[i
] < atomStartAddr
) || (addrs
[i
] >= atomEndAddr
) ) {
7622 warning("arm64 Linker Optimiztion Hint addresses are not in same atom: 0x%08llX and 0x%08llX",
7623 lowestAddress
, addrs
[i
]);
7624 return; // skip this LOH
7626 if ( (addrs
[i
] & 0x3) != 0 ) {
7627 warning("arm64 Linker Optimiztion Hint address is not 4-byte aligned: 0x%08llX", addrs
[i
]);
7628 return; // skip this LOH
7630 if ( (addrs
[i
] - lowestAddress
) > 0xFFFF ) {
7631 if ( parser
.verboseOptimizationHints() ) {
7632 warning("arm64 Linker Optimiztion Hint addresses are too far apart: 0x%08llX and 0x%08llX",
7633 lowestAddress
, addrs
[i
]);
7635 return; // skip this LOH
7639 // encoded kind, count, and address deltas in 64-bit addend
7640 ld::Fixup::LOH_arm64 extra
;
7642 extra
.info
.kind
= kind
;
7643 extra
.info
.count
= count
-1;
7644 extra
.info
.delta1
= (addrs
[0] - lowestAddress
) >> 2;
7645 extra
.info
.delta2
= (count
> 1) ? ((addrs
[1] - lowestAddress
) >> 2) : 0;
7646 extra
.info
.delta3
= (count
> 2) ? ((addrs
[2] - lowestAddress
) >> 2) : 0;
7647 extra
.info
.delta4
= (count
> 3) ? ((addrs
[3] - lowestAddress
) >> 2) : 0;
7648 typename Parser
<arm64
>::SourceLocation
src(inAtom
, lowestAddress
- inAtom
->objectAddress());
7649 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindLinkerOptimizationHint
, extra
.addend
);
7654 template <typename A
>
7655 void Section
<A
>::addLOH(class Parser
<A
>& parser
, int kind
, int count
, const uint64_t addrs
[]) {
7659 template <typename A
>
7660 void Section
<A
>::makeFixups(class Parser
<A
>& parser
, const struct Parser
<A
>::CFI_CU_InfoArrays
&)
7662 const macho_section
<P
>* sect
= this->machoSection();
7663 if ( sect
->reloff() + (sect
->nreloc() * sizeof(macho_relocation_info
<P
>)) > parser
.fileLength() )
7664 throwf("relocations for section %s/%s extends beyond end of file,", sect
->segname(), Section
<A
>::makeSectionName(sect
) );
7665 const macho_relocation_info
<P
>* relocs
= (macho_relocation_info
<P
>*)(file().fileContent() + sect
->reloff());
7666 const uint32_t relocCount
= sect
->nreloc();
7667 for (uint32_t r
= 0; r
< relocCount
; ++r
) {
7669 if ( this->addRelocFixup(parser
, &relocs
[r
]) )
7672 catch (const char* msg
) {
7673 throwf("in section %s,%s reloc %u: %s", sect
->segname(), Section
<A
>::makeSectionName(sect
), r
, msg
);
7677 // add follow-on fixups if .o file is missing .subsections_via_symbols
7678 if ( this->addFollowOnFixups() ) {
7679 Atom
<A
>* end
= &_endAtoms
[-1];
7680 for(Atom
<A
>* p
= _beginAtoms
; p
< end
; ++p
) {
7681 typename Parser
<A
>::SourceLocation
src(p
, 0);
7682 Atom
<A
>* nextAtom
= &p
[1];
7683 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindNoneFollowOn
, nextAtom
);
7686 else if ( this->type() == ld::Section::typeCode
) {
7687 // if FDE broke text not at a symbol, use followOn to keep code together
7688 Atom
<A
>* end
= &_endAtoms
[-1];
7689 for(Atom
<A
>* p
= _beginAtoms
; p
< end
; ++p
) {
7690 typename Parser
<A
>::SourceLocation
src(p
, 0);
7691 Atom
<A
>* nextAtom
= &p
[1];
7692 if ( (p
->symbolTableInclusion() == ld::Atom::symbolTableIn
) && (nextAtom
->symbolTableInclusion() == ld::Atom::symbolTableNotIn
) ) {
7693 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindNoneFollowOn
, nextAtom
);
7697 if ( !this->_altEntries
.empty() && !this->addFollowOnFixups() ) {
7698 if ( _altEntries
.count(_beginAtoms
) != 0 )
7699 warning("N_ALT_ENTRY bit set on first atom in section %s/%s", sect
->segname(), Section
<A
>::makeSectionName(sect
));
7701 Atom
<A
>* end
= &_endAtoms
[-1];
7702 for(Atom
<A
>* p
= _beginAtoms
; p
< end
; ++p
) {
7703 Atom
<A
>* nextAtom
= &p
[1];
7704 // <rdar://problem/22960070> support alt_entry aliases (alias process already added followOn, don't repeat)
7705 if ( (_altEntries
.count(nextAtom
) != 0) && (p
->_objAddress
!= nextAtom
->_objAddress
) ) {
7706 typename Parser
<A
>::SourceLocation
src(p
, 0);
7707 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindNoneFollowOn
, nextAtom
);
7708 typename Parser
<A
>::SourceLocation
src2(nextAtom
, 0);
7709 parser
.addFixup(src2
, ld::Fixup::k1of1
, ld::Fixup::kindNoneGroupSubordinate
, p
);
7714 // <rdar://problem/9218847> track data-in-code
7715 if ( parser
.hasDataInCodeLabels() && (this->type() == ld::Section::typeCode
) ) {
7716 for (uint32_t i
=0; i
< parser
.symbolCount(); ++i
) {
7717 const macho_nlist
<P
>& sym
= parser
.symbolFromIndex(i
);
7719 if ( (sym
.n_type() & N_STAB
) != 0 )
7721 // ignore non-definitions
7722 if ( (sym
.n_type() & N_TYPE
) != N_SECT
)
7725 // 'L' labels do not denote atom breaks
7726 const char* symbolName
= parser
.nameFromSymbol(sym
);
7727 if ( symbolName
[0] == 'L' ) {
7728 if ( strncmp(symbolName
, "L$start$", 8) == 0 ) {
7729 ld::Fixup::Kind kind
= ld::Fixup::kindNone
;
7730 if ( strncmp(&symbolName
[8], "data$", 5) == 0 )
7731 kind
= ld::Fixup::kindDataInCodeStartData
;
7732 else if ( strncmp(&symbolName
[8], "code$", 5) == 0 )
7733 kind
= ld::Fixup::kindDataInCodeEnd
;
7734 else if ( strncmp(&symbolName
[8], "jt8$", 4) == 0 )
7735 kind
= ld::Fixup::kindDataInCodeStartJT8
;
7736 else if ( strncmp(&symbolName
[8], "jt16$", 4) == 0 )
7737 kind
= ld::Fixup::kindDataInCodeStartJT16
;
7738 else if ( strncmp(&symbolName
[8], "jt32$", 4) == 0 )
7739 kind
= ld::Fixup::kindDataInCodeStartJT32
;
7740 else if ( strncmp(&symbolName
[8], "jta32$", 4) == 0 )
7741 kind
= ld::Fixup::kindDataInCodeStartJTA32
;
7743 warning("unknown L$start$ label %s in file %s", symbolName
, this->file().path());
7744 if ( kind
!= ld::Fixup::kindNone
) {
7745 Atom
<A
>* inAtom
= parser
.findAtomByAddress(sym
.n_value());
7746 typename Parser
<A
>::SourceLocation
src(inAtom
, sym
.n_value() - inAtom
->objectAddress());
7747 parser
.addFixup(src
, ld::Fixup::k1of1
, kind
);
7754 // <rdar://problem/11150575> Handle LC_DATA_IN_CODE in object files
7755 if ( this->type() == ld::Section::typeCode
) {
7756 const pint_t startAddr
= this->_machOSection
->addr();
7757 const pint_t endAddr
= startAddr
+ this->_machOSection
->size();
7758 for ( const macho_data_in_code_entry
<P
>* p
= parser
.dataInCodeStart(); p
!= parser
.dataInCodeEnd(); ++p
) {
7759 if ( (p
->offset() >= startAddr
) && (p
->offset() < endAddr
) ) {
7760 ld::Fixup::Kind kind
= ld::Fixup::kindNone
;
7761 switch ( p
->kind() ) {
7762 case DICE_KIND_DATA
:
7763 kind
= ld::Fixup::kindDataInCodeStartData
;
7765 case DICE_KIND_JUMP_TABLE8
:
7766 kind
= ld::Fixup::kindDataInCodeStartJT8
;
7768 case DICE_KIND_JUMP_TABLE16
:
7769 kind
= ld::Fixup::kindDataInCodeStartJT16
;
7771 case DICE_KIND_JUMP_TABLE32
:
7772 kind
= ld::Fixup::kindDataInCodeStartJT32
;
7774 case DICE_KIND_ABS_JUMP_TABLE32
:
7775 kind
= ld::Fixup::kindDataInCodeStartJTA32
;
7778 kind
= ld::Fixup::kindDataInCodeStartData
;
7779 warning("uknown LC_DATA_IN_CODE kind (%d) at offset 0x%08X", p
->kind(), p
->offset());
7782 Atom
<A
>* inAtom
= parser
.findAtomByAddress(p
->offset());
7783 typename Parser
<A
>::SourceLocation
srcStart(inAtom
, p
->offset() - inAtom
->objectAddress());
7784 parser
.addFixup(srcStart
, ld::Fixup::k1of1
, kind
);
7785 typename Parser
<A
>::SourceLocation
srcEnd(inAtom
, p
->offset() + p
->length() - inAtom
->objectAddress());
7786 parser
.addFixup(srcEnd
, ld::Fixup::k1of1
, ld::Fixup::kindDataInCodeEnd
);
7791 // <rdar://problem/11945700> convert linker optimization hints into internal format
7792 if ( this->type() == ld::Section::typeCode
&& parser
.hasOptimizationHints() ) {
7793 const pint_t startAddr
= this->_machOSection
->addr();
7794 const pint_t endAddr
= startAddr
+ this->_machOSection
->size();
7795 for (const uint8_t* p
= parser
.optimizationHintsStart(); p
< parser
.optimizationHintsEnd(); ) {
7797 int32_t kind
= read_uleb128(&p
, parser
.optimizationHintsEnd());
7798 if ( kind
== 0 ) // padding at end of loh buffer
7801 warning("malformed uleb128 kind in LC_LINKER_OPTIMIZATION_HINTS");
7804 int32_t count
= read_uleb128(&p
, parser
.optimizationHintsEnd());
7805 if ( count
== -1 ) {
7806 warning("malformed uleb128 count in LC_LINKER_OPTIMIZATION_HINTS");
7810 warning("address count > 3 in LC_LINKER_OPTIMIZATION_HINTS");
7813 for (int32_t i
=0; i
< count
; ++i
) {
7814 addrs
[i
] = read_uleb128(&p
, parser
.optimizationHintsEnd());
7816 if ( (startAddr
<= addrs
[0]) && (addrs
[0] < endAddr
) ) {
7817 this->addLOH(parser
, kind
, count
, addrs
);
7818 //fprintf(stderr, "kind=%d", kind);
7819 //for (int32_t i=0; i < count; ++i) {
7820 // fprintf(stderr, ", addr=0x%08llX", addrs[i]);
7822 //fprintf(stderr, "\n");
7828 // add follow-on fixups for aliases
7829 if ( _hasAliases
) {
7830 for(Atom
<A
>* p
= _beginAtoms
; p
< _endAtoms
; ++p
) {
7831 if ( p
->isAlias() && ! this->addFollowOnFixups() ) {
7832 Atom
<A
>* targetOfAlias
= &p
[1];
7833 assert(p
< &_endAtoms
[-1]);
7834 assert(p
->_objAddress
== targetOfAlias
->_objAddress
);
7835 typename Parser
<A
>::SourceLocation
src(p
, 0);
7836 parser
.addFixup(src
, ld::Fixup::k1of1
, ld::Fixup::kindNoneFollowOn
, targetOfAlias
);
7845 // main function used by linker to instantiate ld::Files
7847 ld::relocatable::File
* parse(const uint8_t* fileContent
, uint64_t fileLength
,
7848 const char* path
, time_t modTime
, ld::File::Ordinal ordinal
, const ParserOptions
& opts
)
7850 switch ( opts
.architecture
) {
7851 #if SUPPORT_ARCH_x86_64
7852 case CPU_TYPE_X86_64
:
7853 if ( mach_o::relocatable::Parser
<x86_64
>::validFile(fileContent
) )
7854 return mach_o::relocatable::Parser
<x86_64
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
);
7857 #if SUPPORT_ARCH_i386
7859 if ( mach_o::relocatable::Parser
<x86
>::validFile(fileContent
) )
7860 return mach_o::relocatable::Parser
<x86
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
);
7863 #if SUPPORT_ARCH_arm_any
7865 if ( mach_o::relocatable::Parser
<arm
>::validFile(fileContent
, opts
.objSubtypeMustMatch
, opts
.subType
) )
7866 return mach_o::relocatable::Parser
<arm
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
);
7869 #if SUPPORT_ARCH_arm64
7870 case CPU_TYPE_ARM64
:
7871 if ( mach_o::relocatable::Parser
<arm64
>::validFile(fileContent
, opts
.objSubtypeMustMatch
, opts
.subType
) )
7872 return mach_o::relocatable::Parser
<arm64
>::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, opts
);
7880 // used by archive reader to validate member object file
7882 bool isObjectFile(const uint8_t* fileContent
, uint64_t fileLength
, const ParserOptions
& opts
)
7884 switch ( opts
.architecture
) {
7885 case CPU_TYPE_X86_64
:
7886 return ( mach_o::relocatable::Parser
<x86_64
>::validFile(fileContent
) );
7888 return ( mach_o::relocatable::Parser
<x86
>::validFile(fileContent
) );
7890 return ( mach_o::relocatable::Parser
<arm
>::validFile(fileContent
, opts
.objSubtypeMustMatch
, opts
.subType
) );
7891 case CPU_TYPE_ARM64
:
7892 return ( mach_o::relocatable::Parser
<arm64
>::validFile(fileContent
, opts
.objSubtypeMustMatch
, opts
.subType
) );
7898 // used by linker to infer architecture when no -arch is on command line
7900 bool isObjectFile(const uint8_t* fileContent
, cpu_type_t
* result
, cpu_subtype_t
* subResult
, Options::Platform
* platform
)
7902 if ( mach_o::relocatable::Parser
<x86_64
>::validFile(fileContent
) ) {
7903 *result
= CPU_TYPE_X86_64
;
7904 const macho_header
<Pointer64
<LittleEndian
> >* header
= (const macho_header
<Pointer64
<LittleEndian
> >*)fileContent
;
7905 *subResult
= header
->cpusubtype();
7906 *platform
= Parser
<x86_64
>::findPlatform(header
);
7909 if ( mach_o::relocatable::Parser
<x86
>::validFile(fileContent
) ) {
7910 const macho_header
<Pointer32
<LittleEndian
> >* header
= (const macho_header
<Pointer32
<LittleEndian
> >*)fileContent
;
7911 *result
= CPU_TYPE_I386
;
7912 *subResult
= CPU_SUBTYPE_X86_ALL
;
7913 *platform
= Parser
<x86
>::findPlatform(header
);
7916 if ( mach_o::relocatable::Parser
<arm
>::validFile(fileContent
, false, 0) ) {
7917 const macho_header
<Pointer32
<LittleEndian
> >* header
= (const macho_header
<Pointer32
<LittleEndian
> >*)fileContent
;
7918 *result
= CPU_TYPE_ARM
;
7919 *subResult
= header
->cpusubtype();
7920 *platform
= Parser
<arm
>::findPlatform(header
);
7923 if ( mach_o::relocatable::Parser
<arm64
>::validFile(fileContent
, false, 0) ) {
7924 const macho_header
<Pointer64
<LittleEndian
> >* header
= (const macho_header
<Pointer64
<LittleEndian
> >*)fileContent
;
7925 *result
= CPU_TYPE_ARM64
;
7926 *subResult
= header
->cpusubtype();
7927 *platform
= Parser
<arm64
>::findPlatform(header
);
7934 // used by linker is error messages to describe bad .o file
7936 const char* archName(const uint8_t* fileContent
)
7938 if ( mach_o::relocatable::Parser
<x86_64
>::validFile(fileContent
) ) {
7939 return mach_o::relocatable::Parser
<x86_64
>::fileKind(fileContent
);
7941 if ( mach_o::relocatable::Parser
<x86
>::validFile(fileContent
) ) {
7942 return mach_o::relocatable::Parser
<x86
>::fileKind(fileContent
);
7944 if ( mach_o::relocatable::Parser
<arm
>::validFile(fileContent
, false, 0) ) {
7945 return mach_o::relocatable::Parser
<arm
>::fileKind(fileContent
);
7951 // Used by archive reader when -ObjC option is specified
7953 bool hasObjC2Categories(const uint8_t* fileContent
)
7955 if ( mach_o::relocatable::Parser
<x86_64
>::validFile(fileContent
) ) {
7956 return mach_o::relocatable::Parser
<x86_64
>::hasObjC2Categories(fileContent
);
7958 else if ( mach_o::relocatable::Parser
<arm
>::validFile(fileContent
, false, 0) ) {
7959 return mach_o::relocatable::Parser
<arm
>::hasObjC2Categories(fileContent
);
7961 else if ( mach_o::relocatable::Parser
<x86
>::validFile(fileContent
, false, 0) ) {
7962 return mach_o::relocatable::Parser
<x86
>::hasObjC2Categories(fileContent
);
7964 #if SUPPORT_ARCH_arm64
7965 else if ( mach_o::relocatable::Parser
<arm64
>::validFile(fileContent
, false, 0) ) {
7966 return mach_o::relocatable::Parser
<arm64
>::hasObjC2Categories(fileContent
);
7973 // Used by archive reader when -ObjC option is specified
7975 bool hasObjC1Categories(const uint8_t* fileContent
)
7977 if ( mach_o::relocatable::Parser
<x86
>::validFile(fileContent
, false, 0) ) {
7978 return mach_o::relocatable::Parser
<x86
>::hasObjC1Categories(fileContent
);
7984 // Used by bitcode obfuscator to get a list of non local symbols from object file
7986 bool getNonLocalSymbols(const uint8_t* fileContent
, std::vector
<const char*> &syms
)
7988 if ( mach_o::relocatable::Parser
<x86_64
>::validFile(fileContent
) ) {
7989 return mach_o::relocatable::Parser
<x86_64
>::getNonLocalSymbols(fileContent
, syms
);
7991 else if ( mach_o::relocatable::Parser
<arm
>::validFile(fileContent
, false, 0) ) {
7992 return mach_o::relocatable::Parser
<arm
>::getNonLocalSymbols(fileContent
, syms
);
7994 else if ( mach_o::relocatable::Parser
<x86
>::validFile(fileContent
, false, 0) ) {
7995 return mach_o::relocatable::Parser
<x86
>::getNonLocalSymbols(fileContent
, syms
);
7997 else if ( mach_o::relocatable::Parser
<arm64
>::validFile(fileContent
, false, 0) ) {
7998 return mach_o::relocatable::Parser
<arm64
>::getNonLocalSymbols(fileContent
, syms
);
8005 } // namespace relocatable
8006 } // namespace mach_o