]> git.saurik.com Git - apple/ld64.git/blob - src/ld/parsers/macho_relocatable_file.cpp
8a3e7922220a604fa0839a7b1b4a3ec7a7314470
[apple/ld64.git] / src / ld / parsers / macho_relocatable_file.cpp
1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
2 *
3 * Copyright (c) 2009-2010 Apple Inc. All rights reserved.
4 *
5 * @APPLE_LICENSE_HEADER_START@
6 *
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
12 * file.
13 *
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.
21 *
22 * @APPLE_LICENSE_HEADER_END@
23 */
24
25
26 #include <stdint.h>
27 #include <stdlib.h>
28 #include <math.h>
29 #include <unistd.h>
30 #include <fcntl.h>
31 #include <sys/param.h>
32 #include <sys/stat.h>
33 #include <sys/mman.h>
34
35 #include "MachOFileAbstraction.hpp"
36
37 #include "libunwind/DwarfInstructions.hpp"
38 #include "libunwind/AddressSpace.hpp"
39 #include "libunwind/Registers.hpp"
40
41 #include <vector>
42 #include <set>
43 #include <map>
44 #include <algorithm>
45 #include <type_traits>
46
47 #include "dwarf2.h"
48 #include "debugline.h"
49
50 #include "Architectures.hpp"
51 #include "Bitcode.hpp"
52 #include "ld.hpp"
53 #include "macho_relocatable_file.h"
54
55
56
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)));
59
60 namespace mach_o {
61 namespace relocatable {
62
63
64 // forward reference
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;
70
71 template <typename A>
72 class File : public ld::relocatable::File
73 {
74 public:
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),
84 _swiftVersion(0),
85 _cpuSubType(0),
86 _minOSVersion(0),
87 _platform(Options::kPlatformUnknown),
88 _canScatterAtoms(false),
89 _objcHasCategoryClassPropertiesField(false),
90 _srcKind(kSourceUnknown) { }
91 virtual ~File();
92
93 // overrides of ld::File
94 virtual bool forEachAtom(ld::File::AtomHandler&) const;
95 virtual bool justInTimeforEachAtom(const char* name, ld::File::AtomHandler&) const
96 { return false; }
97 virtual uint32_t minOSVersion() const { return _minOSVersion; }
98 virtual uint32_t platform() const { return _platform; }
99
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; }
114
115 virtual const uint8_t* fileContent() const { return _fileContent; }
116 private:
117 friend class Atom<A>;
118 friend class Section<A>;
119 friend class Parser<A>;
120 friend class CFISection<A>::OAS;
121
122 typedef typename A::P P;
123
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;
150 SourceKind _srcKind;
151 ToolVersionList _toolVersions;
152 };
153
154
155 template <typename A>
156 class Section : public ld::Section
157 {
158 public:
159 typedef typename A::P::uint_t pint_t;
160 typedef typename A::P P;
161 typedef typename A::P::E E;
162
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);
186
187 protected:
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) { }
194
195
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);
204
205 File<A>& _file;
206 const macho_section<P>* _machOSection;
207 class Atom<A>* _beginAtoms;
208 class Atom<A>* _endAtoms;
209 bool _hasAliases;
210 std::set<const class Atom<A>*> _altEntries;
211 };
212
213
214 template <typename A>
215 class CFISection : public Section<A>
216 {
217 public:
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);
221
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; }
227
228
229 ///
230 /// ObjectFileAddressSpace is used as a template parameter to UnwindCursor for parsing
231 /// dwarf CFI information in an object file.
232 ///
233 class OAS
234 {
235 public:
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;
240
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()) {}
246
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);
255 private:
256 const void* mappedAddress(pint_t addr);
257
258 CFISection<A>& _ehFrameSection;
259 const uint8_t* _ehFrameContent;
260 pint_t _ehFrameStartAddr;
261 pint_t _ehFrameEndAddr;
262 };
263
264
265 typedef typename A::P::uint_t pint_t;
266 typedef libunwind::CFI_Atom_Info<OAS> CFI_Atom_Info;
267
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();
270
271 static bool bigEndian();
272 private:
273 void addCiePersonalityFixups(class Parser<A>& parser, const CFI_Atom_Info* cieInfo);
274 static void warnFunc(void* ref, uint64_t funcAddr, const char* msg);
275 };
276
277
278 template <typename A>
279 class CUSection : public Section<A>
280 {
281 public:
282 CUSection(Parser<A>& parser, File<A>& f, const macho_section<typename A::P>* s)
283 : Section<A>(f, s) { }
284
285 typedef typename A::P::uint_t pint_t;
286 typedef typename A::P P;
287 typedef typename A::P::E E;
288
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; }
293
294 struct Info {
295 pint_t functionStartAddress;
296 uint32_t functionSymbolIndex;
297 uint32_t rangeLength;
298 uint32_t compactUnwindInfo;
299 const char* personality;
300 pint_t lsdaAddress;
301 Atom<A>* function;
302 Atom<A>* lsda;
303 };
304
305 uint32_t count();
306 void parse(class Parser<A>& parser, uint32_t cnt, Info array[]);
307 static bool encodingMeansUseDwarf(compact_unwind_encoding_t enc);
308
309
310 private:
311
312 const char* personalityName(class Parser<A>& parser, const macho_relocation_info<P>* reloc);
313
314 static int infoSorter(const void* l, const void* r);
315
316 };
317
318
319 template <typename A>
320 class TentativeDefinitionSection : public Section<A>
321 {
322 public:
323 TentativeDefinitionSection(Parser<A>& parser, File<A>& f)
324 : Section<A>(f, "__DATA", "__comm/tent", ld::Section::typeTentativeDefs) {}
325
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&) {}
335 private:
336 typedef typename A::P::uint_t pint_t;
337 typedef typename A::P P;
338 };
339
340
341 template <typename A>
342 class AbsoluteSymbolSection : public Section<A>
343 {
344 public:
345 AbsoluteSymbolSection(Parser<A>& parser, File<A>& f)
346 : Section<A>(f, "__DATA", "__abs", ld::Section::typeAbsoluteSymbols, true) {}
347
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);
360
361 private:
362 typedef typename A::P::uint_t pint_t;
363 typedef typename A::P P;
364 };
365
366
367 template <typename A>
368 class SymboledSection : public Section<A>
369 {
370 public:
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&);
379 protected:
380 typedef typename A::P::uint_t pint_t;
381 typedef typename A::P P;
382
383 ld::Atom::ContentType _type;
384 };
385
386
387 template <typename A>
388 class TLVDefsSection : public SymboledSection<A>
389 {
390 public:
391 TLVDefsSection(Parser<A>& parser, File<A>& f, const macho_section<typename A::P>* s) :
392 SymboledSection<A>(parser, f, s) { }
393
394 typedef typename A::P::uint_t pint_t;
395
396 virtual ld::Atom::Alignment alignmentForAddress(pint_t addr) { return ld::Atom::Alignment(log2(sizeof(pint_t))); }
397
398 private:
399
400 };
401
402
403 template <typename A>
404 class ImplicitSizeSection : public Section<A>
405 {
406 public:
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&);
411 protected:
412 typedef typename A::P::uint_t pint_t;
413 typedef typename A::P P;
414
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'); }
425 };
426
427
428 template <typename A>
429 class FixedSizeSection : public ImplicitSizeSection<A>
430 {
431 public:
432 FixedSizeSection(Parser<A>& parser, File<A>& f, const macho_section<typename A::P>* s)
433 : ImplicitSizeSection<A>(parser, f, s) { }
434 protected:
435 typedef typename A::P::uint_t pint_t;
436 typedef typename A::P P;
437 typedef typename A::P::E E;
438
439 virtual bool useElementAt(Parser<A>& parser,
440 struct Parser<A>::LabelAndCFIBreakIterator& it, pint_t addr)
441 { return true; }
442 };
443
444
445 template <typename A>
446 class Literal4Section : public FixedSizeSection<A>
447 {
448 public:
449 Literal4Section(Parser<A>& parser, File<A>& f, const macho_section<typename A::P>* s)
450 : FixedSizeSection<A>(parser, f, s) {}
451 protected:
452 typedef typename A::P::uint_t pint_t;
453 typedef typename A::P P;
454
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;
463 };
464
465 template <typename A>
466 class Literal8Section : public FixedSizeSection<A>
467 {
468 public:
469 Literal8Section(Parser<A>& parser, File<A>& f, const macho_section<typename A::P>* s)
470 : FixedSizeSection<A>(parser, f, s) {}
471 protected:
472 typedef typename A::P::uint_t pint_t;
473 typedef typename A::P P;
474
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;
483 };
484
485 template <typename A>
486 class Literal16Section : public FixedSizeSection<A>
487 {
488 public:
489 Literal16Section(Parser<A>& parser, File<A>& f, const macho_section<typename A::P>* s)
490 : FixedSizeSection<A>(parser, f, s) {}
491 protected:
492 typedef typename A::P::uint_t pint_t;
493 typedef typename A::P P;
494
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;
503 };
504
505
506 template <typename A>
507 class NonLazyPointerSection : public FixedSizeSection<A>
508 {
509 public:
510 NonLazyPointerSection(Parser<A>& parser, File<A>& f, const macho_section<typename A::P>* s)
511 : FixedSizeSection<A>(parser, f, s) {}
512 protected:
513 typedef typename A::P::uint_t pint_t;
514 typedef typename A::P P;
515
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;
527
528 private:
529 static const char* targetName(const class Atom<A>* atom, const ld::IndirectBindingTable& ind);
530 static ld::Fixup::Kind fixupKind();
531 };
532
533 template <typename A>
534 class TLVPointerSection : public FixedSizeSection<A>
535 {
536 public:
537 TLVPointerSection(Parser<A>& parser, File<A>& f, const macho_section<typename A::P>* s)
538 : FixedSizeSection<A>(parser, f, s) {}
539 protected:
540 typedef typename A::P::uint_t pint_t;
541 typedef typename A::P P;
542
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;
553
554 private:
555 static const char* targetName(const class Atom<A>* atom, const ld::IndirectBindingTable& ind, bool* isStatic);
556 };
557
558
559 template <typename A>
560 class CFStringSection : public FixedSizeSection<A>
561 {
562 public:
563 CFStringSection(Parser<A>& parser, File<A>& f, const macho_section<typename A::P>* s)
564 : FixedSizeSection<A>(parser, f, s) {}
565 protected:
566 typedef typename A::P::uint_t pint_t;
567
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;
576 private:
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);
580 };
581
582
583 template <typename A>
584 class ObjC1ClassSection : public FixedSizeSection<A>
585 {
586 public:
587 ObjC1ClassSection(Parser<A>& parser, File<A>& f, const macho_section<typename A::P>* s)
588 : FixedSizeSection<A>(parser, f, s) {}
589 protected:
590 typedef typename A::P::uint_t pint_t;
591 typedef typename A::P P;
592 typedef typename A::P::E E;
593
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
602 { return 0; }
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>*);
606 };
607
608
609 template <typename A>
610 class ObjC2ClassRefsSection : public FixedSizeSection<A>
611 {
612 public:
613 ObjC2ClassRefsSection(Parser<A>& parser, File<A>& f, const macho_section<typename A::P>* s)
614 : FixedSizeSection<A>(parser, f, s) {}
615 protected:
616 typedef typename A::P::uint_t pint_t;
617
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;
626 private:
627 const char* targetClassName(const class Atom<A>* atom, const ld::IndirectBindingTable& ind) const;
628 };
629
630
631 template <typename A>
632 class ObjC2CategoryListSection : public FixedSizeSection<A>
633 {
634 public:
635 ObjC2CategoryListSection(Parser<A>& parser, File<A>& f, const macho_section<typename A::P>* s)
636 : FixedSizeSection<A>(parser, f, s) {}
637 protected:
638 typedef typename A::P::uint_t pint_t;
639
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; }
646 private:
647 const char* targetClassName(const class Atom<A>* atom, const ld::IndirectBindingTable& ind) const;
648 };
649
650
651 template <typename A>
652 class PointerToCStringSection : public FixedSizeSection<A>
653 {
654 public:
655 PointerToCStringSection(Parser<A>& parser, File<A>& f, const macho_section<typename A::P>* s)
656 : FixedSizeSection<A>(parser, f, s) {}
657 protected:
658 typedef typename A::P::uint_t pint_t;
659
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;
669 };
670
671
672 template <typename A>
673 class Objc1ClassReferences : public PointerToCStringSection<A>
674 {
675 public:
676 Objc1ClassReferences(Parser<A>& parser, File<A>& f, const macho_section<typename A::P>* s)
677 : PointerToCStringSection<A>(parser, f, s) {}
678
679 typedef typename A::P::uint_t pint_t;
680 typedef typename A::P P;
681
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;
685 };
686
687
688 template <typename A>
689 class CStringSection : public ImplicitSizeSection<A>
690 {
691 public:
692 CStringSection(Parser<A>& parser, File<A>& f, const macho_section<typename A::P>* s)
693 : ImplicitSizeSection<A>(parser, f, s) {}
694 protected:
695 typedef typename A::P::uint_t pint_t;
696 typedef typename A::P P;
697
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;
709
710 };
711
712
713 template <typename A>
714 class UTF16StringSection : public SymboledSection<A>
715 {
716 public:
717 UTF16StringSection(Parser<A>& parser, File<A>& f, const macho_section<typename A::P>* s)
718 : SymboledSection<A>(parser, f, s) {}
719 protected:
720 typedef typename A::P::uint_t pint_t;
721 typedef typename A::P P;
722
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;
727 };
728
729
730 //
731 // Atoms in mach-o files
732 //
733 template <typename A>
734 class Atom : public ld::Atom
735 {
736 public:
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);
757
758 private:
759
760 enum { kFixupStartIndexBits = 32,
761 kLineInfoStartIndexBits = 32,
762 kUnwindInfoStartIndexBits = 24,
763 kFixupCountBits = 24,
764 kLineInfoCountBits = 12,
765 kUnwindInfoCountBits = 4
766 }; // must sum to 128
767
768 public:
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;
783
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) )
815 this->setAutoHide();
816 this->verifyAlignment(*sct.machoSection());
817 if ( sct.dontDeadStripIfReferencesLive() )
818 this->setDontDeadStripIfReferencesLive();
819 }
820
821 private:
822 friend class Parser<A>;
823 friend class Section<A>;
824 friend class CStringSection<A>;
825 friend class AbsoluteSymbolSection<A>;
826
827 pint_t _size;
828 pint_t _objAddress;
829 const char* _name;
830 mutable unsigned long _hash;
831
832 uint64_t _fixupsStartIndex : kFixupStartIndexBits,
833 _lineInfoStartIndex : kLineInfoStartIndexBits,
834 _unwindInfoStartIndex : kUnwindInfoStartIndexBits,
835 _fixupsCount : kFixupCountBits,
836 _lineInfoCount : kLineInfoCountBits,
837 _unwindInfoCount : kUnwindInfoCountBits;
838
839 static std::map<const ld::Atom*, const ld::File*> _s_fileOverride;
840 };
841
842 template <typename A>
843 std::map<const ld::Atom*, const ld::File*> Atom<A>::_s_fileOverride;
844
845 template <typename A>
846 void Atom<A>::setFile(const ld::File* f) {
847 _s_fileOverride[this] = f;
848 }
849
850 template <typename A>
851 const ld::File* Atom<A>::file() const
852 {
853 std::map<const ld::Atom*, const ld::File*>::iterator pos = _s_fileOverride.find(this);
854 if ( pos != _s_fileOverride.end() )
855 return pos->second;
856
857 return &sect().file();
858 }
859
860 template <typename A>
861 void Atom<A>::setFixupsRange(uint32_t startIndex, uint32_t count)
862 {
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;
870 }
871
872 template <typename A>
873 void Atom<A>::setUnwindInfoRange(uint32_t startIndex, uint32_t count)
874 {
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;
882 }
883
884 template <typename A>
885 void Atom<A>::extendUnwindInfoRange()
886 {
887 if ( _unwindInfoCount+1 >= (1 << kUnwindInfoCountBits) )
888 throwf("too many compact unwind infos in function %s", this->name());
889 _unwindInfoCount += 1;
890 }
891
892 template <typename A>
893 void Atom<A>::setLineInfoRange(uint32_t startIndex, uint32_t count)
894 {
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;
899 }
900
901 template <typename A>
902 const uint8_t* Atom<A>::contentPointer() const
903 {
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;
909 }
910
911
912 template <typename A>
913 void Atom<A>::copyRawContent(uint8_t buffer[]) const
914 {
915 // copy base bytes
916 if ( this->contentType() == ld::Atom::typeZeroFill ) {
917 bzero(buffer, _size);
918 }
919 else if ( _size != 0 ) {
920 memcpy(buffer, this->contentPointer(), _size);
921 }
922 }
923
924 template <>
925 void Atom<arm>::verifyAlignment(const macho_section<P>&) const
926 {
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());
930 }
931 }
932
933 #if SUPPORT_ARCH_arm64
934 template <>
935 void Atom<arm64>::verifyAlignment(const macho_section<P>& sect) const
936 {
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());
940 }
941 }
942 #endif
943
944
945 template <typename A>
946 void Atom<A>::verifyAlignment(const macho_section<P>&) const
947 {
948 }
949
950
951 class AliasAtom : public ld::Atom
952 {
953 public:
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),
959 _file(file),
960 _name(name),
961 _fixup(0, ld::Fixup::k1of1, ld::Fixup::kindNoneFollowOn, ld::Fixup::bindingByNameUnbound, aliasOfName) { }
962
963 virtual const ld::File* file() const { return _file; }
964 virtual const char* translationUnitSource() const
965 { return NULL; }
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]; }
972
973 private:
974 static ld::Section _s_section;
975
976 const ld::File* _file;
977 const char* _name;
978 ld::Fixup _fixup;
979 };
980
981 ld::Section AliasAtom::_s_section("__LD", "__aliases", ld::Section::typeTempAlias, true);
982
983
984 template <typename A>
985 class Parser
986 {
987 public:
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);
1004 }
1005
1006 typedef typename A::P P;
1007 typedef typename A::P::E E;
1008 typedef typename A::P::uint_t pint_t;
1009
1010 struct SourceLocation {
1011 SourceLocation() {}
1012 SourceLocation(Atom<A>* a, uint32_t o) : atom(a), offsetInAtom(o) {}
1013 Atom<A>* atom;
1014 uint32_t offsetInAtom;
1015 };
1016
1017 struct TargetDesc {
1018 Atom<A>* atom;
1019 const char* name; // only used if targetAtom is NULL
1020 int64_t addend;
1021 bool weakImport; // only used if targetAtom is NULL
1022 };
1023
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(); }
1027
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(); }
1030
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(); }
1033
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(); }
1036
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(); }
1039
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(); }
1042
1043 ld::Fixup fixup;
1044 Atom<A>* atom;
1045 };
1046
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));
1049 }
1050
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));
1053 }
1054
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));
1057 }
1058
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));
1061 }
1062
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));
1065 }
1066
1067 void addFixup(const SourceLocation& src, ld::Fixup::Cluster c, ld::Fixup::Kind k) {
1068 _allFixups.push_back(FixupInAtom(src, c, k));
1069 }
1070
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; }
1104
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; }
1118
1119
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; }
1125
1126
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);
1129
1130
1131
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; }
1143
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;
1149 bool newSection;
1150 uint32_t cfiIndex;
1151 uint32_t symIndex;
1152 };
1153
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;
1163 };
1164
1165
1166
1167 private:
1168 friend class Section<A>;
1169
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};
1176
1177 template <typename P>
1178 struct MachOSectionAndSectionClass
1179 {
1180 const macho_section<P>* sect;
1181 SectionType type;
1182
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();
1187 if ( diff == 0 )
1188 return 0;
1189 if ( diff < 0 )
1190 return -1;
1191 else
1192 return 1;
1193 }
1194 };
1195
1196 struct ParserAndSectionsArray { Parser* parser; const uint32_t* sortedSectionsArray; };
1197
1198
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);
1214
1215 void parseDebugInfo();
1216 void parseStabs();
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);
1226
1227
1228 // filled in by constructor
1229 const uint8_t* _fileContent;
1230 uint32_t _fileLength;
1231 const char* _path;
1232 time_t _modTime;
1233 ld::File::Ordinal _ordinal;
1234
1235 // filled in by parseLoadCommands()
1236 File<A>* _file;
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;
1248 bool _hasUUID;
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;
1253
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;
1273 bool _usingBitcode;
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;
1279 };
1280
1281
1282
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)
1304 {
1305 }
1306
1307
1308 template <>
1309 bool Parser<x86>::validFile(const uint8_t* fileContent, bool, cpu_subtype_t)
1310 {
1311 const macho_header<P>* header = (const macho_header<P>*)fileContent;
1312 if ( header->magic() != MH_MAGIC )
1313 return false;
1314 if ( header->cputype() != CPU_TYPE_I386 )
1315 return false;
1316 if ( header->filetype() != MH_OBJECT )
1317 return false;
1318 return true;
1319 }
1320
1321 template <>
1322 bool Parser<x86_64>::validFile(const uint8_t* fileContent, bool, cpu_subtype_t)
1323 {
1324 const macho_header<P>* header = (const macho_header<P>*)fileContent;
1325 if ( header->magic() != MH_MAGIC_64 )
1326 return false;
1327 if ( header->cputype() != CPU_TYPE_X86_64 )
1328 return false;
1329 if ( header->filetype() != MH_OBJECT )
1330 return false;
1331 return true;
1332 }
1333
1334 template <>
1335 bool Parser<arm>::validFile(const uint8_t* fileContent, bool subtypeMustMatch, cpu_subtype_t subtype)
1336 {
1337 const macho_header<P>* header = (const macho_header<P>*)fileContent;
1338 if ( header->magic() != MH_MAGIC )
1339 return false;
1340 if ( header->cputype() != CPU_TYPE_ARM )
1341 return false;
1342 if ( header->filetype() != MH_OBJECT )
1343 return false;
1344 if ( subtypeMustMatch ) {
1345 if ( (cpu_subtype_t)header->cpusubtype() == subtype )
1346 return true;
1347 // hack until libcc_kext.a is made fat
1348 if ( header->cpusubtype() == CPU_SUBTYPE_ARM_ALL )
1349 return true;
1350 return false;
1351 }
1352 return true;
1353 }
1354
1355
1356 template <>
1357 bool Parser<arm64>::validFile(const uint8_t* fileContent, bool subtypeMustMatch, cpu_subtype_t subtype)
1358 {
1359 const macho_header<P>* header = (const macho_header<P>*)fileContent;
1360 if ( header->magic() != MH_MAGIC_64 )
1361 return false;
1362 if ( header->cputype() != CPU_TYPE_ARM64 )
1363 return false;
1364 if ( header->filetype() != MH_OBJECT )
1365 return false;
1366 return true;
1367 }
1368
1369
1370 template <>
1371 const char* Parser<x86>::fileKind(const uint8_t* fileContent)
1372 {
1373 const macho_header<P>* header = (const macho_header<P>*)fileContent;
1374 if ( header->magic() != MH_MAGIC )
1375 return NULL;
1376 if ( header->cputype() != CPU_TYPE_I386 )
1377 return NULL;
1378 return "i386";
1379 }
1380
1381 template <>
1382 const char* Parser<x86_64>::fileKind(const uint8_t* fileContent)
1383 {
1384 const macho_header<P>* header = (const macho_header<P>*)fileContent;
1385 if ( header->magic() != MH_MAGIC_64 )
1386 return NULL;
1387 if ( header->cputype() != CPU_TYPE_X86_64 )
1388 return NULL;
1389 return "x86_64";
1390 }
1391
1392 template <>
1393 const char* Parser<arm>::fileKind(const uint8_t* fileContent)
1394 {
1395 const macho_header<P>* header = (const macho_header<P>*)fileContent;
1396 if ( header->magic() != MH_MAGIC )
1397 return NULL;
1398 if ( header->cputype() != CPU_TYPE_ARM )
1399 return NULL;
1400 for (const ArchInfo* t=archInfoArray; t->archName != NULL; ++t) {
1401 if ( (t->cpuType == CPU_TYPE_ARM) && ((cpu_subtype_t)header->cpusubtype() == t->cpuSubType) ) {
1402 return t->archName;
1403 }
1404 }
1405 return "arm???";
1406 }
1407
1408 #if SUPPORT_ARCH_arm64
1409 template <>
1410 const char* Parser<arm64>::fileKind(const uint8_t* fileContent)
1411 {
1412 const macho_header<P>* header = (const macho_header<P>*)fileContent;
1413 if ( header->magic() != MH_MAGIC_64 )
1414 return NULL;
1415 if ( header->cputype() != CPU_TYPE_ARM64 )
1416 return NULL;
1417 return "arm64";
1418 }
1419 #endif
1420
1421
1422 template <typename A>
1423 bool Parser<A>::hasObjC2Categories(const uint8_t* fileContent)
1424 {
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 = &sectionsStart[si];
1436 if ( (sect->size() > 0)
1437 && (strcmp(sect->sectname(), "__objc_catlist") == 0)
1438 && (strcmp(sect->segname(), "__DATA") == 0) ) {
1439 return true;
1440 }
1441 }
1442 }
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);
1446 }
1447 return false;
1448 }
1449
1450
1451 template <typename A>
1452 bool Parser<A>::hasObjC1Categories(const uint8_t* fileContent)
1453 {
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 = &sectionsStart[si];
1465 if ( (sect->size() > 0)
1466 && (strcmp(sect->sectname(), "__category") == 0)
1467 && (strcmp(sect->segname(), "__OBJC") == 0) ) {
1468 return true;
1469 }
1470 }
1471 }
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);
1475 }
1476 return false;
1477 }
1478
1479
1480 template <typename A>
1481 bool Parser<A>::getNonLocalSymbols(const uint8_t* fileContent, std::vector<const char*> &syms)
1482 {
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);
1500 }
1501 }
1502 return true;
1503 }
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);
1507 }
1508 return false;
1509 }
1510
1511
1512 template <typename A>
1513 int Parser<A>::pointerSorter(const void* l, const void* r)
1514 {
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);
1519 }
1520
1521 template <typename A>
1522 typename A::P::uint_t Parser<A>::LabelAndCFIBreakIterator::peek(Parser<A>& parser, pint_t startAddr, pint_t endAddr)
1523 {
1524 pint_t symbolAddr;
1525 if ( symIndex < sortedSymbolCount )
1526 symbolAddr = parser.symbolFromIndex(sortedSymbolIndexes[symIndex]).n_value();
1527 else
1528 symbolAddr = endAddr;
1529 pint_t cfiAddr;
1530 if ( cfiIndex < cfiStartsCount )
1531 cfiAddr = cfiStartsArray[cfiIndex];
1532 else
1533 cfiAddr = endAddr;
1534 if ( (cfiAddr < symbolAddr) && (cfiAddr >= startAddr) ) {
1535 if ( cfiAddr < endAddr )
1536 return cfiAddr;
1537 else
1538 return endAddr;
1539 }
1540 else {
1541 if ( symbolAddr < endAddr )
1542 return symbolAddr;
1543 else
1544 return endAddr;
1545 }
1546 }
1547
1548 //
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.
1552 //
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)
1556 {
1557 // may not be a label on start of section, but need atom demarcation there
1558 if ( newSection ) {
1559 newSection = false;
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)) )
1567 break;
1568 }
1569 ++symIndex;
1570 }
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 ) {
1580 // use cfi
1581 ++cfiIndex;
1582 *addr = nextCfiAddr;
1583 *size = peek(parser, startAddr, endAddr) - nextCfiAddr;
1584 *symbol = NULL;
1585 return true;
1586 }
1587 }
1588 *addr = startAddr;
1589 *size = endAddr - startAddr;
1590 *symbol = NULL;
1591 if ( startAddr == endAddr )
1592 return false; // zero size section
1593 else
1594 return true; // whole section is one atom with no label
1595 }
1596 // if also CFI break here, eat it
1597 if ( cfiIndex < cfiStartsCount ) {
1598 if ( cfiStartsArray[cfiIndex] == nextSymbolAddr )
1599 ++cfiIndex;
1600 }
1601 if ( nextSymbolAddr == startAddr ) {
1602 // label at start of section, return it as chunk
1603 ++symIndex;
1604 *addr = startAddr;
1605 *size = peek(parser, startAddr, endAddr) - startAddr;
1606 *symbol = &sym;
1607 return true;
1608 }
1609 // return chunk before first symbol
1610 *addr = startAddr;
1611 *size = nextSymbolAddr - startAddr;
1612 *symbol = NULL;
1613 return true;
1614 }
1615 // no symbols in section, check CFI
1616 if ( cfiIndex < cfiStartsCount ) {
1617 pint_t nextCfiAddr = cfiStartsArray[cfiIndex];
1618 if ( nextCfiAddr < endAddr ) {
1619 // use cfi
1620 ++cfiIndex;
1621 *addr = nextCfiAddr;
1622 *size = peek(parser, startAddr, endAddr) - nextCfiAddr;
1623 *symbol = NULL;
1624 return true;
1625 }
1626 }
1627 // no cfi, so whole section is one chunk
1628 *addr = startAddr;
1629 *size = endAddr - startAddr;
1630 *symbol = NULL;
1631 if ( startAddr == endAddr )
1632 return false; // zero size section
1633 else
1634 return true; // whole section is one atom with no label
1635 }
1636
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 )
1643 return false;
1644 ++symIndex;
1645 if ( nextSymbolAddr < startAddr )
1646 continue;
1647 *addr = nextSymbolAddr;
1648 *size = peek(parser, startAddr, endAddr) - nextSymbolAddr;
1649 *symbol = &sym;
1650 return true;
1651 }
1652 else if ( nextCfiAddr < nextSymbolAddr ) {
1653 if ( nextCfiAddr >= endAddr )
1654 return false;
1655 ++cfiIndex;
1656 if ( nextCfiAddr < startAddr )
1657 continue;
1658 *addr = nextCfiAddr;
1659 *size = peek(parser, startAddr, endAddr) - nextCfiAddr;
1660 *symbol = NULL;
1661 return true;
1662 }
1663 else {
1664 if ( nextCfiAddr >= endAddr )
1665 return false;
1666 ++symIndex;
1667 ++cfiIndex;
1668 if ( nextCfiAddr < startAddr )
1669 continue;
1670 *addr = nextCfiAddr;
1671 *size = peek(parser, startAddr, endAddr) - nextCfiAddr;
1672 *symbol = &sym;
1673 return true;
1674 }
1675 }
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 )
1681 return false;
1682 ++symIndex;
1683 if ( nextSymbolAddr < startAddr )
1684 continue;
1685 *addr = nextSymbolAddr;
1686 *size = peek(parser, startAddr, endAddr) - nextSymbolAddr;
1687 *symbol = &sym;
1688 return true;
1689 }
1690 while ( cfiIndex < cfiStartsCount ) {
1691 pint_t nextCfiAddr = cfiStartsArray[cfiIndex];
1692 if ( nextCfiAddr >= endAddr )
1693 return false;
1694 ++cfiIndex;
1695 if ( nextCfiAddr < startAddr )
1696 continue;
1697 *addr = nextCfiAddr;
1698 *size = peek(parser, startAddr, endAddr) - nextCfiAddr;
1699 *symbol = NULL;
1700 return true;
1701 }
1702 return false;
1703 }
1704
1705 template <>
1706 typename arm::P::uint_t Parser<arm>::realAddr(typename arm::P::uint_t addr)
1707 {
1708 return addr & (-2);
1709 }
1710
1711 template <typename A>
1712 typename A::P::uint_t Parser<A>::realAddr(typename A::P::uint_t addr)
1713 {
1714 return addr;
1715 }
1716
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; \
1724 } \
1725 else \
1726 _name##_count = _actual_count; \
1727 _type _name##_buffer[_name##_stack_count]; \
1728 if ( _name == NULL ) \
1729 _name = _name##_buffer;
1730
1731
1732 template <typename A>
1733 ld::relocatable::File* Parser<A>::parse(const ParserOptions& opts)
1734 {
1735 // create file object
1736 _file = new File<A>(_path, _modTime, _fileContent, _ordinal);
1737
1738 // set sourceKind
1739 _file->_srcKind = opts.srcKind;
1740 // set treatBitcodeAsData
1741 _treateBitcodeAsData = opts.treateBitcodeAsData;
1742 _usingBitcode = opts.usingBitcode;
1743
1744 // respond to -t option
1745 if ( opts.logAllFiles )
1746 printf("%s\n", _path);
1747
1748 _armUsesZeroCostExceptions = opts.armUsesZeroCostExceptions;
1749 _maxDefaultCommonAlignment = opts.maxDefaultCommonAlignment;
1750
1751 // parse start of mach-o file
1752 if ( ! parseLoadCommands(opts.platform, opts.minOSVersion, opts.simulator, opts.ignoreMismatchPlatform) )
1753 return _file;
1754
1755 // make array of
1756 uint32_t sortedSectionIndexes[_machOSectionsCount];
1757 this->makeSortedSectionsArray(sortedSectionIndexes);
1758
1759 // make symbol table sorted by address
1760 this->prescanSymbolTable();
1761 uint32_t sortedSymbolIndexes[_symbolsInSections];
1762 this->makeSortedSymbolsArray(sortedSymbolIndexes, sortedSectionIndexes);
1763
1764 // allocate Section<A> object for each mach-o section
1765 makeSections();
1766
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);
1775
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) )
1781 cuStarts[i] = -1;
1782 else
1783 cuStarts[i] = cuInfoArray[i].functionStartAddress;
1784 if ( cuInfoArray[i].lsdaAddress != 0 )
1785 ++cuLsdaCount;
1786 }
1787
1788
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);
1795
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 )
1807 continue;
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 )
1813 ++cfiStartsCount;
1814 if ( cfiArray[i].u.fdeInfo.lsda.targetAddress != CFI_INVALID_ADDRESS )
1815 ++cfiStartsCount;
1816 }
1817 }
1818 CFI_CU_InfoArrays cfis(cfiArray, countOfCFIs, cuInfoArray, countOfCUs);
1819
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 )
1827 continue;
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;
1832 ++countOfFDEs;
1833 }
1834 }
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 )
1839 continue;
1840 // append to cfiStartsArray if not already in that list
1841 bool found = false;
1842 for(uint32_t j=0; j < cfiStartsArrayCount; ++j) {
1843 if ( cfiStartsArray[j] == cuInfoArray[i].lsdaAddress )
1844 found = true;
1845 }
1846 if ( ! found ) {
1847 cfiStartsArray[cfiStartsArrayCount++] = cuInfoArray[i].lsdaAddress;
1848 }
1849 }
1850 }
1851 if ( cfiStartsArrayCount != 0 ) {
1852 ::qsort(cfiStartsArray, cfiStartsArrayCount, sizeof(pint_t), pointerSorter);
1853 #ifndef NDEBUG
1854 // scan for FDEs claming the same function
1855 for(uint32_t i=1; i < cfiStartsArrayCount; ++i) {
1856 assert( cfiStartsArray[i] != cfiStartsArray[i-1] );
1857 }
1858 #endif
1859 }
1860
1861 Section<A>** sections = _file->_sectionsArray;
1862 uint32_t sectionsCount = _file->_sectionsArrayCount;
1863
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;
1874 }
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;
1878
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;
1888 }
1889 assert( _file->_atomsArrayCount == computedAtomCount && "more atoms allocated than expected");
1890
1891
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);
1896
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>);
1906 }
1907 assert(fixupOffset == _allFixups.size());
1908 _file->_fixups.resize(fixupOffset);
1909
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++;
1915 }
1916
1917 // done with temp vector
1918 _allFixups.clear();
1919
1920 // add unwind info
1921 _file->_unwindInfos.reserve(countOfFDEs+countOfCUs);
1922 for(uint32_t i=0; i < countOfCFIs; ++i) {
1923 if ( cfiArray[i].isCIE )
1924 continue;
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());
1933 }
1934 }
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);
1954 else
1955 warning("__LD,__compact_unwind entries for %s overlap at offset 0x%0X", info->function->name(), lastEnd);
1956 }
1957 lastFunc->extendUnwindInfoRange();
1958 }
1959 else
1960 info->function->setUnwindInfoRange(_file->_unwindInfos.size()-1, 1);
1961 lastFunc = info->function;
1962 lastEnd = ui.startOffset + info->rangeLength;
1963 }
1964 }
1965
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);
1973 }
1974
1975
1976 // parse dwarf debug info to get line info
1977 this->parseDebugInfo();
1978
1979 return _file;
1980 }
1981
1982 static void versionToString(uint32_t value, char buffer[32])
1983 {
1984 if ( value & 0xFF )
1985 sprintf(buffer, "%d.%d.%d", value >> 16, (value >> 8) & 0xFF, value & 0xFF);
1986 else
1987 sprintf(buffer, "%d.%d", value >> 16, (value >> 8) & 0xFF);
1988 }
1989
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; }
1994
1995 template <typename A>
1996 bool Parser<A>::parseLoadCommands(Options::Platform platform, uint32_t linkMinOSVersion, bool simulator, bool ignoreMismatchPlatform)
1997 {
1998 const macho_header<P>* header = (const macho_header<P>*)_fileContent;
1999
2000 // set File attributes
2001 _file->_canScatterAtoms = (header->flags() & MH_SUBSECTIONS_VIA_SYMBOLS);
2002 _file->_cpuSubType = header->cpusubtype();
2003
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 )
2009 return false;
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()) {
2024 case LC_SYMTAB:
2025 {
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();
2039 }
2040 }
2041 }
2042 break;
2043 case LC_DYSYMTAB:
2044 {
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();
2052 }
2053 break;
2054 case LC_UUID:
2055 _hasUUID = true;
2056 break;
2057 case LC_DATA_IN_CODE:
2058 {
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";
2064 }
2065 break;
2066 case LC_LINKER_OPTION:
2067 {
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;
2075 }
2076 if ( buffer > ((char*)cmd + loc->cmdsize()) )
2077 throw "malformed LC_LINKER_OPTION";
2078 }
2079 break;
2080 case LC_LINKER_OPTIMIZATION_HINTS:
2081 {
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";
2087 }
2088 break;
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:
2094 #endif
2095 if ( ignoreMismatchPlatform )
2096 break;
2097 lcPlatform = Options::platformForLoadCommand(cmd->cmd());
2098 _file->_platform = lcPlatform;
2099 _file->_minOSVersion = ((macho_version_min_command<P>*)cmd)->version();
2100 break;
2101 case LC_BUILD_VERSION:
2102 {
2103 const macho_build_version_command<P>* buildVersCmd = (macho_build_version_command<P>*)cmd;
2104 if ( ignoreMismatchPlatform )
2105 break;
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()));
2112 ++entry;
2113 }
2114 }
2115 break;
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;
2120 break;
2121 default:
2122 // ignore unknown load commands
2123 break;
2124 }
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);
2128 }
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;
2134
2135 // Check platform cross-linking.
2136 if ( !ignoreMismatchPlatform ) {
2137 if ( lcPlatform != platform ) {
2138 switch (platform) {
2139 case Options::kPlatformOSX:
2140 case Options::kPlatformiOS:
2141 if ( lcPlatform == Options::kPlatformUnknown )
2142 break;
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.
2147 if (_usingBitcode)
2148 throwf("building for %s%s, but linking in object file built for %s,",
2149 Options::platformName(platform), (simulator ? " simulator" : ""),
2150 Options::platformName(lcPlatform));
2151 else
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));
2156 break;
2157 #if SUPPORT_APPLE_TV
2158 case Options::kPlatform_tvOS:
2159 // Error when using bitcocde, warning otherwise.
2160 if (_usingBitcode)
2161 throwf("building for %s%s, but linking in object file built for %s,",
2162 Options::platformName(platform), (simulator ? " simulator" : ""),
2163 Options::platformName(lcPlatform));
2164 else
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));
2169 break;
2170 #endif
2171 case Options::kPlatformUnknown:
2172 // skip if the target platform is unknown
2173 break;
2174 }
2175 }
2176 if ( linkMinOSVersion && (_file->_minOSVersion > linkMinOSVersion) ) {
2177 char t1[32];
2178 char t2[32];
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);
2183 }
2184 }
2185
2186
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";
2194 return true;
2195 }
2196
2197 template <typename A>
2198 Options::Platform Parser<A>::findPlatform(const macho_header<P>* header)
2199 {
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;
2223 #endif
2224 case LC_BUILD_VERSION:
2225 return (Options::Platform)((macho_build_version_command<P>*)cmd)->platform();
2226 }
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);
2230 }
2231 return Options::kPlatformUnknown;
2232 }
2233
2234
2235 template <typename A>
2236 void Parser<A>::prescanSymbolTable()
2237 {
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);
2244 // ignore stabs
2245 if ( (sym.n_type() & N_STAB) != 0 )
2246 continue;
2247
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;
2254 }
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);
2260 }
2261 }
2262 continue;
2263 }
2264 else if ( ((sym.n_type() & N_TYPE) == N_INDR) && ((sym.n_type() & N_EXT) != 0) ) {
2265 _indirectSymbolCount++;
2266 continue;
2267 }
2268
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 ) {
2274 _AppleObjc = true;
2275 continue;
2276 }
2277 // ignore .objc_class_name_* symbols
2278 if ( strncmp(absName, ".objc_category_name_", 20) == 0 )
2279 continue;
2280 // ignore empty *.eh symbols
2281 if ( strcmp(&absName[strlen(absName)-3], ".eh") == 0 )
2282 continue;
2283 ++_absoluteSymbolCount;
2284 }
2285
2286 // only look at definitions
2287 if ( (sym.n_type() & N_TYPE) != N_SECT )
2288 continue;
2289
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;
2295 continue;
2296 }
2297 // how many def syms in each section
2298 if ( sym.n_sect() > _machOSectionsCount )
2299 throw "bad n_sect in symbol table";
2300
2301 _symbolsInSections++;
2302 }
2303 }
2304
2305 template <typename A>
2306 void Parser<A>::appendAliasAtoms(uint8_t* p)
2307 {
2308 for (uint32_t i=0; i < this->_symbolCount; ++i) {
2309 const macho_nlist<P>& sym = symbolFromIndex(i);
2310 // ignore stabs
2311 if ( (sym.n_type() & N_STAB) != 0 )
2312 continue;
2313
2314 // only look at N_INDR symbols
2315 if ( (sym.n_type() & N_TYPE) != N_INDR )
2316 continue;
2317
2318 // skip non-external aliases
2319 if ( (sym.n_type() & N_EXT) == 0 )
2320 continue;
2321
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);
2328 }
2329 }
2330
2331
2332
2333 template <typename A>
2334 int Parser<A>::sectionIndexSorter(void* extra, const void* l, const void* r)
2335 {
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);
2341
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 );
2351 }
2352 if ( !leftEmpty && !rightEmpty )
2353 throwf("overlapping sections");
2354 // both empty, so chose file order
2355 return ( rightSect - leftSect );
2356 }
2357 else if ( result < 0 )
2358 return -1;
2359 else
2360 return 1;
2361 }
2362
2363 template <typename A>
2364 void Parser<A>::makeSortedSectionsArray(uint32_t array[])
2365 {
2366 const bool log = false;
2367
2368 if ( log ) {
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());
2372 }
2373
2374 // sort by symbol table address
2375 for (uint32_t i=0; i < _machOSectionsCount; ++i)
2376 array[i] = i;
2377 ::qsort_r(array, _machOSectionsCount, sizeof(uint32_t), this, &sectionIndexSorter);
2378
2379 if ( log ) {
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());
2383 }
2384 }
2385
2386
2387
2388 template <typename A>
2389 int Parser<A>::symbolIndexSorter(void* extra, const void* l, const void* r)
2390 {
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() )
2406 return -1;
2407 if ( sortedSectionsArray[i]+1 == rightSym.n_sect() )
2408 return 1;
2409 }
2410 }
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);
2419 }
2420
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 )
2424 return -1;
2425 else
2426 return 1;
2427 }
2428 // if both are global, sort alphabetically. earlier one will be the alias
2429 return ( strcmp(rightName, leftName) );
2430 }
2431 else if ( result < 0 )
2432 return -1;
2433 else
2434 return 1;
2435 }
2436
2437
2438 template <typename A>
2439 void Parser<A>::makeSortedSymbolsArray(uint32_t array[], const uint32_t sectionArray[])
2440 {
2441 const bool log = false;
2442
2443 uint32_t* p = array;
2444 for (uint32_t i=0; i < this->_symbolCount; ++i) {
2445 const macho_nlist<P>& sym = symbolFromIndex(i);
2446 // ignore stabs
2447 if ( (sym.n_type() & N_STAB) != 0 )
2448 continue;
2449
2450 // only look at definitions
2451 if ( (sym.n_type() & N_TYPE) != N_SECT )
2452 continue;
2453
2454 // 'L' labels do not denote atom breaks
2455 const char* symbolName = this->nameFromSymbol(sym);
2456 if ( symbolName[0] == 'L' )
2457 continue;
2458
2459 // how many def syms in each section
2460 if ( sym.n_sect() > _machOSectionsCount )
2461 throw "bad n_sect in symbol table";
2462
2463 // append to array
2464 *p++ = i;
2465 }
2466 assert(p == &array[_symbolsInSections] && "second pass over symbol table yield a different number of symbols");
2467
2468 // sort by symbol table address
2469 ParserAndSectionsArray extra = { this, sectionArray };
2470 ::qsort_r(array, _symbolsInSections, sizeof(uint32_t), &extra, &symbolIndexSorter);
2471
2472
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;
2479 break;
2480 }
2481 }
2482
2483 if ( log ) {
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])) );
2487 }
2488 }
2489
2490 template <typename A>
2491 void Parser<A>::makeSections()
2492 {
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;
2506
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());
2512
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
2527 continue;
2528 }
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;
2534 continue;
2535 }
2536 }
2537 }
2538 if ( strcmp(sect->segname(), "__LLVM") == 0 ) {
2539 // Process bitcode segement
2540 if ( strncmp(sect->sectname(), "__bitcode", 9) == 0 ) {
2541 bitcodeSect = sect;
2542 } else if ( strncmp(sect->sectname(), "__cmdline", 9) == 0 ) {
2543 cmdlineSect = sect;
2544 } else if ( strncmp(sect->sectname(), "__swift_cmdline", 15) == 0 ) {
2545 swiftCmdlineSect = sect;
2546 } else if ( strncmp(sect->sectname(), "__bundle", 8) == 0 ) {
2547 bundleSect = sect;
2548 } else if ( strncmp(sect->sectname(), "__asm", 5) == 0 ) {
2549 bitcodeAsm = true;
2550 }
2551 // If treat the bitcode as data, continue to parse as a normal section.
2552 if ( !_treateBitcodeAsData )
2553 continue;
2554 }
2555 // ignore empty __OBJC sections
2556 if ( (sect->size() == 0) && (strcmp(sect->segname(), "__OBJC") == 0) )
2557 continue;
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
2563 // uint32_t flags;
2564 // };
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
2569 //
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;
2579 else
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());
2586 }
2587 }
2588 else {
2589 warning("can't parse %s/%s section in %s", sect->segname(), Section<A>::makeSectionName(sect), _file->path());
2590 }
2591 continue;
2592 }
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;
2599 }
2600 else
2601 assert(1 && "multiple S_SYMBOL_STUBS sections");
2602 case S_LAZY_SYMBOL_POINTERS:
2603 break;
2604 case S_4BYTE_LITERALS:
2605 totalSectionsSize += sizeof(Literal4Section<A>);
2606 machOSects[count++].type = sectionTypeLiteral4;
2607 break;
2608 case S_8BYTE_LITERALS:
2609 totalSectionsSize += sizeof(Literal8Section<A>);
2610 machOSects[count++].type = sectionTypeLiteral8;
2611 break;
2612 case S_16BYTE_LITERALS:
2613 totalSectionsSize += sizeof(Literal16Section<A>);
2614 machOSects[count++].type = sectionTypeLiteral16;
2615 break;
2616 case S_NON_LAZY_SYMBOL_POINTERS:
2617 totalSectionsSize += sizeof(NonLazyPointerSection<A>);
2618 machOSects[count++].type = sectionTypeNonLazy;
2619 break;
2620 case S_THREAD_LOCAL_VARIABLE_POINTERS:
2621 totalSectionsSize += sizeof(TLVPointerSection<A>);
2622 machOSects[count++].type = sectionTypeTLVPointers;
2623 break;
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;
2628 }
2629 else {
2630 totalSectionsSize += sizeof(PointerToCStringSection<A>);
2631 machOSects[count++].type = sectionTypeCStringPointer;
2632 }
2633 break;
2634 case S_CSTRING_LITERALS:
2635 totalSectionsSize += sizeof(CStringSection<A>);
2636 machOSects[count++].type = sectionTypeCString;
2637 break;
2638 case S_MOD_INIT_FUNC_POINTERS:
2639 case S_MOD_TERM_FUNC_POINTERS:
2640 case S_THREAD_LOCAL_INIT_FUNCTION_POINTERS:
2641 case S_INTERPOSING:
2642 case S_ZEROFILL:
2643 case S_REGULAR:
2644 case S_COALESCED:
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;
2650 }
2651 else if ( (strcmp(sect->segname(), "__DATA") == 0) && (strcmp(sect->sectname(), "__cfstring") == 0) ) {
2652 totalSectionsSize += sizeof(CFStringSection<A>);
2653 machOSects[count++].type = sectionTypeCFString;
2654 }
2655 else if ( (strcmp(sect->segname(), "__TEXT") == 0) && (strcmp(sect->sectname(), "__ustring") == 0) ) {
2656 totalSectionsSize += sizeof(UTF16StringSection<A>);
2657 machOSects[count++].type = sectionTypeUTF16Strings;
2658 }
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;
2662 }
2663 else if ( (strcmp(sect->segname(), "__DATA") == 0) && (strcmp(sect->sectname(), "__objc_catlist") == 0) ) {
2664 totalSectionsSize += sizeof(ObjC2CategoryListSection<A>);
2665 machOSects[count++].type = typeObjC2CategoryList;
2666 }
2667 else if ( _AppleObjc && (strcmp(sect->segname(), "__OBJC") == 0) && (strcmp(sect->sectname(), "__class") == 0) ) {
2668 totalSectionsSize += sizeof(ObjC1ClassSection<A>);
2669 machOSects[count++].type = sectionTypeObjC1Classes;
2670 }
2671 else {
2672 totalSectionsSize += sizeof(SymboledSection<A>);
2673 machOSects[count++].type = sectionTypeSymboled;
2674 }
2675 break;
2676 case S_THREAD_LOCAL_VARIABLES:
2677 totalSectionsSize += sizeof(TLVDefsSection<A>);
2678 machOSects[count++].type = sectionTypeTLVDefs;
2679 break;
2680 default:
2681 throwf("unknown section type %d", sect->flags() & SECTION_TYPE);
2682 }
2683 }
2684
2685 // Create bitcode
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()));
2693 else
2694 throwf("Object file with bitcode missing cmdline options: %s", _file->path());
2695 }
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));
2700
2701 // sort by address (mach-o object files don't aways have sections sorted)
2702 ::qsort(machOSects, count, sizeof(MachOSectionAndSectionClass<P>), MachOSectionAndSectionClass<P>::sorter);
2703
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;
2708 }
2709
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;
2714 }
2715
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:
2725 break;
2726 case sectionTypeLiteral4:
2727 *objects++ = new (space) Literal4Section<A>(*this, *_file, machOSects[i].sect);
2728 space += sizeof(Literal4Section<A>);
2729 break;
2730 case sectionTypeLiteral8:
2731 *objects++ = new (space) Literal8Section<A>(*this, *_file, machOSects[i].sect);
2732 space += sizeof(Literal8Section<A>);
2733 break;
2734 case sectionTypeLiteral16:
2735 *objects++ = new (space) Literal16Section<A>(*this, *_file, machOSects[i].sect);
2736 space += sizeof(Literal16Section<A>);
2737 break;
2738 case sectionTypeNonLazy:
2739 *objects++ = new (space) NonLazyPointerSection<A>(*this, *_file, machOSects[i].sect);
2740 space += sizeof(NonLazyPointerSection<A>);
2741 break;
2742 case sectionTypeTLVPointers:
2743 *objects++ = new (space) TLVPointerSection<A>(*this, *_file, machOSects[i].sect);
2744 space += sizeof(TLVPointerSection<A>);
2745 break;
2746 case sectionTypeCFI:
2747 _EHFrameSection = new (space) CFISection<A>(*this, *_file, machOSects[i].sect);
2748 *objects++ = _EHFrameSection;
2749 space += sizeof(CFISection<A>);
2750 break;
2751 case sectionTypeCString:
2752 *objects++ = new (space) CStringSection<A>(*this, *_file, machOSects[i].sect);
2753 space += sizeof(CStringSection<A>);
2754 break;
2755 case sectionTypeCStringPointer:
2756 *objects++ = new (space) PointerToCStringSection<A>(*this, *_file, machOSects[i].sect);
2757 space += sizeof(PointerToCStringSection<A>);
2758 break;
2759 case sectionTypeObjC1ClassRefs:
2760 *objects++ = new (space) Objc1ClassReferences<A>(*this, *_file, machOSects[i].sect);
2761 space += sizeof(Objc1ClassReferences<A>);
2762 break;
2763 case sectionTypeUTF16Strings:
2764 *objects++ = new (space) UTF16StringSection<A>(*this, *_file, machOSects[i].sect);
2765 space += sizeof(UTF16StringSection<A>);
2766 break;
2767 case sectionTypeCFString:
2768 *objects++ = new (space) CFStringSection<A>(*this, *_file, machOSects[i].sect);
2769 space += sizeof(CFStringSection<A>);
2770 break;
2771 case sectionTypeObjC2ClassRefs:
2772 *objects++ = new (space) ObjC2ClassRefsSection<A>(*this, *_file, machOSects[i].sect);
2773 space += sizeof(ObjC2ClassRefsSection<A>);
2774 break;
2775 case typeObjC2CategoryList:
2776 *objects++ = new (space) ObjC2CategoryListSection<A>(*this, *_file, machOSects[i].sect);
2777 space += sizeof(ObjC2CategoryListSection<A>);
2778 break;
2779 case sectionTypeObjC1Classes:
2780 *objects++ = new (space) ObjC1ClassSection<A>(*this, *_file, machOSects[i].sect);
2781 space += sizeof(ObjC1ClassSection<A>);
2782 break;
2783 case sectionTypeSymboled:
2784 *objects++ = new (space) SymboledSection<A>(*this, *_file, machOSects[i].sect);
2785 space += sizeof(SymboledSection<A>);
2786 break;
2787 case sectionTypeTLVDefs:
2788 *objects++ = new (space) TLVDefsSection<A>(*this, *_file, machOSects[i].sect);
2789 space += sizeof(TLVDefsSection<A>);
2790 break;
2791 case sectionTypeCompactUnwind:
2792 _compactUnwindSection = new (space) CUSection<A>(*this, *_file, machOSects[i].sect);
2793 *objects++ = _compactUnwindSection;
2794 space += sizeof(CUSection<A>);
2795 break;
2796 case sectionTypeTentativeDefinitions:
2797 *objects++ = new (space) TentativeDefinitionSection<A>(*this, *_file);
2798 space += sizeof(TentativeDefinitionSection<A>);
2799 break;
2800 case sectionTypeAbsoluteSymbols:
2801 _absoluteSection = new (space) AbsoluteSymbolSection<A>(*this, *_file);
2802 *objects++ = _absoluteSection;
2803 space += sizeof(AbsoluteSymbolSection<A>);
2804 break;
2805 default:
2806 throw "internal error uknown SectionType";
2807 }
2808 }
2809 }
2810
2811
2812 template <typename A>
2813 Section<A>* Parser<A>::sectionForAddress(typename A::P::uint_t addr)
2814 {
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];
2821 }
2822 }
2823 }
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];
2832 }
2833 }
2834 }
2835
2836 throwf("sectionForAddress(0x%llX) address not in any section", (uint64_t)addr);
2837 }
2838
2839 template <typename A>
2840 Section<A>* Parser<A>::sectionForNum(unsigned int num)
2841 {
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];
2848 }
2849 }
2850 throwf("sectionForNum(%u) section number not for any section", num);
2851 }
2852
2853 template <typename A>
2854 Atom<A>* Parser<A>::findAtomByAddress(pint_t addr)
2855 {
2856 Section<A>* section = this->sectionForAddress(addr);
2857 return section->findAtomByAddress(addr);
2858 }
2859
2860 template <typename A>
2861 Atom<A>* Parser<A>::findAtomByAddressOrNullIfStub(pint_t addr)
2862 {
2863 if ( hasStubsSection() && (_stubsMachOSection->addr() <= addr) && (addr < (_stubsMachOSection->addr()+_stubsMachOSection->size())) )
2864 return NULL;
2865 return findAtomByAddress(addr);
2866 }
2867
2868 template <typename A>
2869 Atom<A>* Parser<A>::findAtomByAddressOrLocalTargetOfStub(pint_t addr, uint32_t* offsetInAtom)
2870 {
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) );
2878 *offsetInAtom = 0;
2879 return this->findAtomByName(this->nameFromSymbol(sym));
2880 }
2881 Atom<A>* target = this->findAtomByAddress(addr);
2882 *offsetInAtom = addr - target->_objAddress;
2883 return target;
2884 }
2885
2886 template <typename A>
2887 Atom<A>* Parser<A>::findAtomByName(const char* name)
2888 {
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 )
2893 return atom;
2894 p += sizeof(Atom<A>);
2895 }
2896 return NULL;
2897 }
2898
2899 template <typename A>
2900 void Parser<A>::findTargetFromAddress(pint_t addr, TargetDesc& target)
2901 {
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);
2907 target.atom = NULL;
2908 target.name = this->nameFromSymbol(sym);
2909 target.weakImport = this->weakImportFromSymbol(sym);
2910 target.addend = 0;
2911 return;
2912 }
2913 Section<A>* section = this->sectionForAddress(addr);
2914 target.atom = section->findAtomByAddress(addr);
2915 target.addend = addr - target.atom->_objAddress;
2916 target.weakImport = false;
2917 target.name = NULL;
2918 }
2919
2920 template <typename A>
2921 void Parser<A>::findTargetFromAddress(pint_t baseAddr, pint_t addr, TargetDesc& target)
2922 {
2923 findTargetFromAddress(baseAddr, target);
2924 target.addend = addr - target.atom->_objAddress;
2925 }
2926
2927 template <typename A>
2928 void Parser<A>::findTargetFromAddressAndSectionNum(pint_t addr, unsigned int sectNum, TargetDesc& target)
2929 {
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 ) {
2935 target.name = NULL;
2936 target.weakImport = false;
2937 target.addend = 0;
2938 return;
2939 }
2940 }
2941 throwf("R_ABS reloc but no absolute symbol at target address");
2942 }
2943
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);
2952 }
2953 else {
2954 target.atom = NULL;
2955 target.name = this->nameFromSymbol(sym);
2956 target.weakImport = this->weakImportFromSymbol(sym);
2957 target.addend = 0;
2958 }
2959 return;
2960 }
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;
2973 target.name = NULL;
2974 return;
2975 }
2976 else if ( a >= sectEnd ) {
2977 target.atom = section->findAtomByAddress(sectEnd-1);
2978 target.addend = a - sectEnd;
2979 target.weakImport = false;
2980 target.name = NULL;
2981 return;
2982 }
2983 }
2984 assert(target.atom != NULL);
2985 target.addend = addr - target.atom->_objAddress;
2986 target.weakImport = false;
2987 target.name = NULL;
2988 }
2989
2990 template <typename A>
2991 void Parser<A>::addDtraceExtraInfos(const SourceLocation& src, const char* providerName)
2992 {
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);
3003 }
3004 }
3005 }
3006 }
3007 }
3008
3009 template <typename A>
3010 const char* Parser<A>::scanSymbolTableForAddress(uint64_t addr)
3011 {
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);
3016 // ignore stabs
3017 if ( (sym.n_type() & N_STAB) != 0 )
3018 continue;
3019
3020 // only look at definitions
3021 if ( (sym.n_type() & N_TYPE) != N_SECT )
3022 continue;
3023
3024 // return with exact match
3025 if ( sym.n_value() == addr ) {
3026 const char* name = nameFromSymbol(sym);
3027 if ( strncmp(name, "ltmp", 4) != 0 )
3028 return name;
3029 // treat 'ltmp*' labels as close match
3030 closestSymAddr = sym.n_value();
3031 closestSymName = name;
3032 }
3033
3034 // record closest seen so far
3035 if ( (sym.n_value() < addr) && ((sym.n_value() > closestSymAddr) || (closestSymName == NULL)) )
3036 closestSymName = nameFromSymbol(sym);
3037 }
3038
3039 return (closestSymName != NULL) ? closestSymName : "unknown";
3040 }
3041
3042
3043 template <typename A>
3044 void Parser<A>::addFixups(const SourceLocation& src, ld::Fixup::Kind setKind, const TargetDesc& target)
3045 {
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;
3052 combined = true;
3053 switch ( setKind ) {
3054 case ld::Fixup::kindStoreLittleEndian32:
3055 firstKind = ld::Fixup::kindStoreTargetAddressLittleEndian32;
3056 break;
3057 case ld::Fixup::kindStoreLittleEndian64:
3058 firstKind = ld::Fixup::kindStoreTargetAddressLittleEndian64;
3059 break;
3060 case ld::Fixup::kindStoreBigEndian32:
3061 firstKind = ld::Fixup::kindStoreTargetAddressBigEndian32;
3062 break;
3063 case ld::Fixup::kindStoreBigEndian64:
3064 firstKind = ld::Fixup::kindStoreTargetAddressBigEndian64;
3065 break;
3066 case ld::Fixup::kindStoreX86BranchPCRel32:
3067 firstKind = ld::Fixup::kindStoreTargetAddressX86BranchPCRel32;
3068 break;
3069 case ld::Fixup::kindStoreX86PCRel32:
3070 firstKind = ld::Fixup::kindStoreTargetAddressX86PCRel32;
3071 break;
3072 case ld::Fixup::kindStoreX86PCRel32GOTLoad:
3073 firstKind = ld::Fixup::kindStoreTargetAddressX86PCRel32GOTLoad;
3074 break;
3075 case ld::Fixup::kindStoreX86PCRel32TLVLoad:
3076 firstKind = ld::Fixup::kindStoreTargetAddressX86PCRel32TLVLoad;
3077 break;
3078 case ld::Fixup::kindStoreX86Abs32TLVLoad:
3079 firstKind = ld::Fixup::kindStoreTargetAddressX86Abs32TLVLoad;
3080 break;
3081 case ld::Fixup::kindStoreARMBranch24:
3082 firstKind = ld::Fixup::kindStoreTargetAddressARMBranch24;
3083 break;
3084 case ld::Fixup::kindStoreThumbBranch22:
3085 firstKind = ld::Fixup::kindStoreTargetAddressThumbBranch22;
3086 break;
3087 #if SUPPORT_ARCH_arm64
3088 case ld::Fixup::kindStoreARM64Branch26:
3089 firstKind = ld::Fixup::kindStoreTargetAddressARM64Branch26;
3090 break;
3091 case ld::Fixup::kindStoreARM64Page21:
3092 firstKind = ld::Fixup::kindStoreTargetAddressARM64Page21;
3093 break;
3094 case ld::Fixup::kindStoreARM64PageOff12:
3095 firstKind = ld::Fixup::kindStoreTargetAddressARM64PageOff12;
3096 break;
3097 case ld::Fixup::kindStoreARM64GOTLoadPage21:
3098 firstKind = ld::Fixup::kindStoreTargetAddressARM64GOTLoadPage21;
3099 break;
3100 case ld::Fixup::kindStoreARM64GOTLoadPageOff12:
3101 firstKind = ld::Fixup::kindStoreTargetAddressARM64GOTLoadPageOff12;
3102 break;
3103 case ld::Fixup::kindStoreARM64TLVPLoadPage21:
3104 firstKind = ld::Fixup::kindStoreTargetAddressARM64TLVPLoadPage21;
3105 break;
3106 case ld::Fixup::kindStoreARM64TLVPLoadPageOff12:
3107 firstKind = ld::Fixup::kindStoreTargetAddressARM64TLVPLoadPageOff12;
3108 break;
3109 #endif
3110 default:
3111 combined = false;
3112 cl = ld::Fixup::k1of2;
3113 break;
3114 }
3115 }
3116
3117 if ( target.atom != NULL ) {
3118 if ( target.atom->scope() == ld::Atom::scopeTranslationUnit ) {
3119 addFixup(src, cl, firstKind, target.atom);
3120 }
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);
3123 }
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);
3127 }
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);
3131 }
3132 else {
3133 // change direct fixup to by-name fixup
3134 addFixup(src, cl, firstKind, false, target.atom->name());
3135 }
3136 }
3137 else {
3138 addFixup(src, cl, firstKind, target.weakImport, target.name);
3139 }
3140 if ( target.addend == 0 ) {
3141 if ( ! combined )
3142 addFixup(src, ld::Fixup::k2of2, setKind);
3143 }
3144 else {
3145 addFixup(src, ld::Fixup::k2of3, ld::Fixup::kindAddAddend, target.addend);
3146 addFixup(src, ld::Fixup::k3of3, setKind);
3147 }
3148 }
3149
3150 template <typename A>
3151 void Parser<A>::addFixups(const SourceLocation& src, ld::Fixup::Kind kind, const TargetDesc& target, const TargetDesc& picBase)
3152 {
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);
3157 }
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);
3160 }
3161 else {
3162 addFixup(src, cl, ld::Fixup::kindSetTargetAddress, false, target.atom->name());
3163 }
3164 }
3165 else {
3166 addFixup(src, cl, ld::Fixup::kindSetTargetAddress, target.weakImport, target.name);
3167 }
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);
3173 }
3174 else {
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);
3179 }
3180 }
3181
3182
3183
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&)
3188 {
3189 return parser.tentativeDefinitionCount();
3190 }
3191
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&)
3196 {
3197 this->_beginAtoms = (Atom<A>*)p;
3198 uint32_t count = 0;
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) )
3211 ++alignP2;
3212 // <rdar://problem/24871389> limit default alignment of large commons
3213 if ( alignP2 > parser.maxDefaultCommonAlignment() )
3214 alignP2 = parser.maxDefaultCommonAlignment();
3215 }
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>);
3222 ++count;
3223 }
3224 }
3225 this->_endAtoms = (Atom<A>*)p;
3226 return count;
3227 }
3228
3229
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&)
3234 {
3235 return parser.absoluteSymbolCount();
3236 }
3237
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&)
3242 {
3243 this->_beginAtoms = (Atom<A>*)p;
3244 uint32_t count = 0;
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 )
3248 continue;
3249 const char* absName = parser.nameFromSymbol(sym);
3250 // ignore .objc_class_name_* symbols
3251 if ( strncmp(absName, ".objc_class_name_", 17) == 0 )
3252 continue;
3253 // ignore .objc_class_name_* symbols
3254 if ( strncmp(absName, ".objc_category_name_", 20) == 0 )
3255 continue;
3256 // ignore empty *.eh symbols
3257 if ( strcmp(&absName[strlen(absName)-3], ".eh") == 0 )
3258 continue;
3259
3260 Atom<A>* allocatedSpace = (Atom<A>*)p;
3261 new (allocatedSpace) Atom<A>(*this, parser, sym, 0);
3262 p += sizeof(Atom<A>);
3263 ++count;
3264 }
3265 this->_endAtoms = (Atom<A>*)p;
3266 return count;
3267 }
3268
3269 template <typename A>
3270 Atom<A>* AbsoluteSymbolSection<A>::findAbsAtomForValue(typename A::P::uint_t value)
3271 {
3272 Atom<A>* end = this->_endAtoms;
3273 for(Atom<A>* p = this->_beginAtoms; p < end; ++p) {
3274 if ( p->_objAddress == value )
3275 return p;
3276 }
3277 return NULL;
3278 }
3279
3280
3281 template <typename A>
3282 uint32_t Parser<A>::indirectSymbol(uint32_t indirectIndex)
3283 {
3284 if ( indirectIndex >= _indirectTableCount )
3285 throw "indirect symbol index out of range";
3286 return E::get32(_indirectTable[indirectIndex]);
3287 }
3288
3289 template <typename A>
3290 const macho_nlist<typename A::P>& Parser<A>::symbolFromIndex(uint32_t index)
3291 {
3292 if ( index > _symbolCount )
3293 throw "symbol index out of range";
3294 return _symbols[index];
3295 }
3296
3297 template <typename A>
3298 const macho_section<typename A::P>* Parser<A>::machOSectionFromSectionIndex(uint32_t index)
3299 {
3300 if ( index >= _machOSectionsCount )
3301 throw "section index out of range";
3302 return &_sectionsStart[index];
3303 }
3304
3305 template <typename A>
3306 uint32_t Parser<A>::symbolIndexFromIndirectSectionAddress(pint_t addr, const macho_section<P>* sect)
3307 {
3308 uint32_t elementSize = 0;
3309 switch ( sect->flags() & SECTION_TYPE ) {
3310 case S_SYMBOL_STUBS:
3311 elementSize = sect->reserved2();
3312 break;
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);
3317 break;
3318 default:
3319 throw "section does not use indirect symbol table";
3320 }
3321 uint32_t indexInSection = (addr - sect->addr()) / elementSize;
3322 uint32_t indexIntoIndirectTable = sect->reserved1() + indexInSection;
3323 return this->indirectSymbol(indexIntoIndirectTable);
3324 }
3325
3326
3327
3328 template <typename A>
3329 const char* Parser<A>::nameFromSymbol(const macho_nlist<P>& sym)
3330 {
3331 return &_strings[sym.n_strx()];
3332 }
3333
3334 template <typename A>
3335 ld::Atom::Scope Parser<A>::scopeFromSymbol(const macho_nlist<P>& sym)
3336 {
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;
3343 else
3344 return ld::Atom::scopeGlobal;
3345 }
3346
3347 template <typename A>
3348 ld::Atom::Definition Parser<A>::definitionFromSymbol(const macho_nlist<P>& sym)
3349 {
3350 switch ( sym.n_type() & N_TYPE ) {
3351 case N_ABS:
3352 return ld::Atom::definitionAbsolute;
3353 case N_SECT:
3354 return ld::Atom::definitionRegular;
3355 case N_UNDF:
3356 if ( sym.n_value() != 0 )
3357 return ld::Atom::definitionTentative;
3358 }
3359 throw "definitionFromSymbol() bad symbol";
3360 }
3361
3362 template <typename A>
3363 ld::Atom::Combine Parser<A>::combineFromSymbol(const macho_nlist<P>& sym)
3364 {
3365 if ( sym.n_desc() & N_WEAK_DEF )
3366 return ld::Atom::combineByName;
3367 else
3368 return ld::Atom::combineNever;
3369 }
3370
3371
3372 template <typename A>
3373 ld::Atom::SymbolTableInclusion Parser<A>::inclusionFromSymbol(const macho_nlist<P>& sym)
3374 {
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;
3384 else
3385 return ld::Atom::symbolTableIn;
3386 }
3387
3388 template <typename A>
3389 bool Parser<A>::dontDeadStripFromSymbol(const macho_nlist<P>& sym)
3390 {
3391 return ( (sym.n_desc() & (N_NO_DEAD_STRIP|REFERENCED_DYNAMICALLY)) != 0 );
3392 }
3393
3394 template <typename A>
3395 bool Parser<A>::isThumbFromSymbol(const macho_nlist<P>& sym)
3396 {
3397 return ( sym.n_desc() & N_ARM_THUMB_DEF );
3398 }
3399
3400 template <typename A>
3401 bool Parser<A>::weakImportFromSymbol(const macho_nlist<P>& sym)
3402 {
3403 return ( ((sym.n_type() & N_TYPE) == N_UNDF) && ((sym.n_desc() & N_WEAK_REF) != 0) );
3404 }
3405
3406 template <typename A>
3407 bool Parser<A>::resolverFromSymbol(const macho_nlist<P>& sym)
3408 {
3409 return ( sym.n_desc() & N_SYMBOL_RESOLVER );
3410 }
3411
3412 template <typename A>
3413 bool Parser<A>::altEntryFromSymbol(const macho_nlist<P>& sym)
3414 {
3415 return ( sym.n_desc() & N_ALT_ENTRY );
3416 }
3417
3418
3419 /* Skip over a LEB128 value (signed or unsigned). */
3420 static void
3421 skip_leb128 (const uint8_t ** offset, const uint8_t * end)
3422 {
3423 while (*offset != end && **offset >= 0x80)
3424 (*offset)++;
3425 if (*offset != end)
3426 (*offset)++;
3427 }
3428
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. */
3431 static uint64_t
3432 read_uleb128 (const uint8_t ** offset, const uint8_t * end)
3433 {
3434 uint64_t result = 0;
3435 int bit = 0;
3436
3437 do {
3438 uint64_t b;
3439
3440 if (*offset == end)
3441 return (uint64_t) -1;
3442
3443 b = **offset & 0x7f;
3444
3445 if (bit >= 64 || b << bit >> bit != b)
3446 result = (uint64_t) -1;
3447 else
3448 result |= b << bit, bit += 7;
3449 } while (*(*offset)++ >= 0x80);
3450 return result;
3451 }
3452
3453
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)
3458 {
3459 int64_t sz=0;
3460
3461 switch (form)
3462 {
3463 case DW_FORM_addr:
3464 sz = addr_size;
3465 break;
3466
3467 case DW_FORM_block2:
3468 if (end - *offset < 2)
3469 return false;
3470 sz = 2 + A::P::E::get16(*(uint16_t*)offset);
3471 break;
3472
3473 case DW_FORM_block4:
3474 if (end - *offset < 4)
3475 return false;
3476 sz = 2 + A::P::E::get32(*(uint32_t*)offset);
3477 break;
3478
3479 case DW_FORM_data2:
3480 case DW_FORM_ref2:
3481 sz = 2;
3482 break;
3483
3484 case DW_FORM_data4:
3485 case DW_FORM_ref4:
3486 sz = 4;
3487 break;
3488
3489 case DW_FORM_data8:
3490 case DW_FORM_ref8:
3491 sz = 8;
3492 break;
3493
3494 case DW_FORM_string:
3495 while (*offset != end && **offset)
3496 ++*offset;
3497 case DW_FORM_data1:
3498 case DW_FORM_flag:
3499 case DW_FORM_ref1:
3500 sz = 1;
3501 break;
3502
3503 case DW_FORM_block:
3504 sz = read_uleb128 (offset, end);
3505 break;
3506
3507 case DW_FORM_block1:
3508 if (*offset == end)
3509 return false;
3510 sz = 1 + **offset;
3511 break;
3512
3513 case DW_FORM_sdata:
3514 case DW_FORM_udata:
3515 case DW_FORM_ref_udata:
3516 skip_leb128 (offset, end);
3517 return true;
3518
3519 case DW_FORM_strp:
3520 case DW_FORM_ref_addr:
3521 sz = 4;
3522 break;
3523
3524 case DW_FORM_sec_offset:
3525 sz = sizeof(typename A::P::uint_t);
3526 break;
3527
3528 case DW_FORM_exprloc:
3529 sz = read_uleb128 (offset, end);
3530 break;
3531
3532 case DW_FORM_flag_present:
3533 sz = 0;
3534 break;
3535
3536 case DW_FORM_ref_sig8:
3537 sz = 8;
3538 break;
3539
3540 default:
3541 return false;
3542 }
3543 if (end - *offset < sz)
3544 return false;
3545 *offset += sz;
3546 return true;
3547 }
3548
3549
3550 template <typename A>
3551 const char* Parser<A>::getDwarfString(uint64_t form, const uint8_t*& di)
3552 {
3553 uint32_t offset;
3554 const char* dwarfStrings;
3555 const char* result = NULL;
3556 switch (form) {
3557 case DW_FORM_string:
3558 result = (const char*)di;
3559 di += strlen(result) + 1;
3560 break;
3561 case DW_FORM_strp:
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];
3566 else
3567 warning("dwarf DW_FORM_strp (offset=0x%08X) is too big in %s", offset, this->_path);
3568 di += 4;
3569 break;
3570 default:
3571 warning("unknown dwarf string encoding (form=%lld) in %s", form, this->_path);
3572 break;
3573 }
3574 return result;
3575 }
3576
3577 template <typename A>
3578 uint64_t Parser<A>::getDwarfOffset(uint64_t form, const uint8_t*& di, bool dwarf64)
3579 {
3580 if ( form == DW_FORM_sec_offset )
3581 form = (dwarf64 ? DW_FORM_data8 : DW_FORM_data4);
3582 uint64_t result = -1;
3583 switch (form) {
3584 case DW_FORM_data4:
3585 result = A::P::E::get32(*(uint32_t*)di);
3586 di += 4;
3587 break;
3588 case DW_FORM_data8:
3589 result = A::P::E::get64(*(uint64_t*)di);
3590 di += 8;
3591 break;
3592 default:
3593 warning("unknown dwarf DW_FORM_ for DW_AT_stmt_list in %s", this->_path);
3594 }
3595 return result;
3596 }
3597
3598
3599 template <typename A>
3600 struct AtomAndLineInfo {
3601 Atom<A>* atom;
3602 ld::Atom::LineInfo info;
3603 };
3604
3605
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)
3611 {
3612 const char* colon;
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
3617 // not a constant)
3618 return (stabStr != NULL) && (stabStr[0] != '+') && (stabStr[0] != '-')
3619 && ((colon = strchr(stabStr, ':')) != NULL)
3620 && (colon[1] == 'c') && (colon[2] == '=');
3621 }
3622
3623
3624 template <typename A>
3625 void Parser<A>::parseDebugInfo()
3626 {
3627 // check for dwarf __debug_info section
3628 if ( _file->_dwarfDebugInfoSect == NULL ) {
3629 // if no DWARF debug info, look for stabs
3630 this->parseStabs();
3631 return;
3632 }
3633 if ( _file->_dwarfDebugInfoSect->size() == 0 )
3634 return;
3635
3636 uint64_t stmtList;
3637 const char* tuDir;
3638 const char* tuName;
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;
3644 return;
3645 }
3646 if ( (tuName != NULL) && (tuName[0] == '/') ) {
3647 _file->_dwarfTranslationUnitPath = tuName;
3648 }
3649 else if ( (tuDir != NULL) && (tuName != NULL) ) {
3650 asprintf((char**)&(_file->_dwarfTranslationUnitPath), "%s/%s", tuDir, tuName);
3651 }
3652 else if ( tuDir == NULL ) {
3653 _file->_dwarfTranslationUnitPath = tuName;
3654 }
3655 else {
3656 _file->_dwarfTranslationUnitPath = NULL;
3657 }
3658
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))
3683 continue;
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;
3687 }
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;
3691 }
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();
3698 }
3699 else {
3700 // do slow look up of atom by address
3701 try {
3702 curAtom = this->findAtomByAddress(result.pc);
3703 }
3704 catch (...) {
3705 // in case of bug in debug info, don't abort link, just limp on
3706 curAtom = NULL;
3707 }
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);
3715 if ( alt == NULL )
3716 continue; // ignore spurious debug info for stubs
3717 if ( result.pc <= alt->objectAddress() + alt->size() ) {
3718 curAtom = alt;
3719 curAtomOffset = result.pc - alt->objectAddress();
3720 curAtomAddress = alt->objectAddress();
3721 curAtomSize = alt->size();
3722 }
3723 else {
3724 curAtomOffset = result.pc - curAtom->objectAddress();
3725 curAtomAddress = curAtom->objectAddress();
3726 curAtomSize = curAtom->size();
3727 }
3728 }
3729 else {
3730 curAtomOffset = result.pc - curAtom->objectAddress();
3731 curAtomAddress = curAtom->objectAddress();
3732 curAtomSize = curAtom->size();
3733 }
3734 }
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;
3740 }
3741 else {
3742 filename = pos->second;
3743 }
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();
3755 }
3756 if ( result.end_of_sequence ) {
3757 curAtom = NULL;
3758 }
3759 }
3760 line_free(lines);
3761 }
3762 }
3763 }
3764 }
3765
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>);
3775 }
3776 assert(liOffset == entries.size());
3777 _file->_lineInfos.resize(liOffset);
3778
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++;
3784 }
3785
3786 // done with temp vector
3787 entries.clear();
3788 }
3789
3790 template <typename A>
3791 void Parser<A>::parseStabs()
3792 {
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;
3805 stab.atom = NULL;
3806 stab.type = type;
3807 stab.other = sym.n_sect();
3808 stab.desc = sym.n_desc();
3809 stab.value = sym.n_value();
3810 stab.string = NULL;
3811 switch (state) {
3812 case start:
3813 switch (type) {
3814 case N_BNSYM:
3815 // beginning of function block
3816 state = inBeginEnd;
3817 // fall into case to lookup atom by addresss
3818 case N_LCSYM:
3819 case N_STSYM:
3820 currentAtomAddress = sym.n_value();
3821 currentAtom = this->findAtomByAddress(currentAtomAddress);
3822 if ( currentAtom != NULL ) {
3823 stab.atom = currentAtom;
3824 stab.string = symString;
3825 }
3826 else {
3827 fprintf(stderr, "can't find atom for stabs BNSYM at %08llX in %s",
3828 (uint64_t)sym.n_value(), _path);
3829 }
3830 break;
3831 case N_SO:
3832 case N_OSO:
3833 case N_OPT:
3834 case N_LSYM:
3835 case N_RSYM:
3836 case N_PSYM:
3837 case N_AST:
3838 // not associated with an atom, just copy
3839 stab.string = symString;
3840 break;
3841 case N_GSYM:
3842 {
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);
3851 symName[0] = '_';
3852 symName[nameLen+1] = '\0';
3853 currentAtom = this->findAtomByName(symName);
3854 if ( currentAtom != NULL ) {
3855 stab.atom = currentAtom;
3856 stab.string = symString;
3857 }
3858 }
3859 else {
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;
3865 }
3866 }
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);
3871 useStab = false;
3872 }
3873 break;
3874 }
3875 case N_FUN:
3876 if ( isConstFunStabs(symString) ) {
3877 // constant not associated with a function
3878 stab.string = symString;
3879 }
3880 else {
3881 // old style stabs without BNSYM
3882 state = inFun;
3883 currentAtomAddress = sym.n_value();
3884 currentAtom = this->findAtomByAddress(currentAtomAddress);
3885 if ( currentAtom != NULL ) {
3886 stab.atom = currentAtom;
3887 stab.string = symString;
3888 }
3889 else {
3890 warning("can't find atom for stabs FUN at %08llX in %s",
3891 (uint64_t)currentAtomAddress, _path);
3892 }
3893 }
3894 break;
3895 case N_SOL:
3896 case N_SLINE:
3897 stab.string = symString;
3898 // old stabs
3899 break;
3900 case N_BINCL:
3901 case N_EINCL:
3902 case N_EXCL:
3903 stab.string = symString;
3904 // -gfull built .o file
3905 break;
3906 default:
3907 warning("unknown stabs type 0x%X in %s", type, _path);
3908 }
3909 break;
3910 case inBeginEnd:
3911 stab.atom = currentAtom;
3912 switch (type) {
3913 case N_ENSYM:
3914 state = start;
3915 currentAtom = NULL;
3916 break;
3917 case N_LCSYM:
3918 case N_STSYM:
3919 {
3920 Atom<A>* nestedAtom = this->findAtomByAddress(sym.n_value());
3921 if ( nestedAtom != NULL ) {
3922 stab.atom = nestedAtom;
3923 stab.string = symString;
3924 }
3925 else {
3926 warning("can't find atom for stabs 0x%X at %08llX in %s",
3927 type, (uint64_t)sym.n_value(), _path);
3928 }
3929 break;
3930 }
3931 case N_LBRAC:
3932 case N_RBRAC:
3933 case N_SLINE:
3934 // adjust value to be offset in atom
3935 stab.value -= currentAtomAddress;
3936 default:
3937 stab.string = symString;
3938 break;
3939 }
3940 break;
3941 case inFun:
3942 switch (type) {
3943 case N_FUN:
3944 if ( isConstFunStabs(symString) ) {
3945 stab.atom = currentAtom;
3946 stab.string = symString;
3947 }
3948 else {
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;
3956 }
3957 else {
3958 warning("can't find atom for stabs FUN at %08llX in %s",
3959 (uint64_t)currentAtomAddress, _path);
3960 }
3961 }
3962 else {
3963 // found ending stab, switch back to start state
3964 stab.string = symString;
3965 stab.atom = currentAtom;
3966 state = start;
3967 currentAtom = NULL;
3968 }
3969 }
3970 break;
3971 case N_LBRAC:
3972 case N_RBRAC:
3973 case N_SLINE:
3974 // adjust value to be offset in atom
3975 stab.value -= currentAtomAddress;
3976 stab.atom = currentAtom;
3977 break;
3978 case N_SO:
3979 stab.string = symString;
3980 state = start;
3981 break;
3982 default:
3983 stab.atom = currentAtom;
3984 stab.string = symString;
3985 break;
3986 }
3987 break;
3988 }
3989 // add to list of stabs for this .o file
3990 if ( useStab )
3991 _file->_stabs.push_back(stab);
3992 }
3993 }
3994 }
3995
3996
3997
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.
4003 //
4004 // At present this assumes that there's only one compilation unit DIE.
4005 //
4006 template <typename A>
4007 bool Parser<A>::read_comp_unit(const char ** name, const char ** comp_dir,
4008 uint64_t *stmt_list)
4009 {
4010 const uint8_t * debug_info;
4011 const uint8_t * debug_abbrev;
4012 const uint8_t * di;
4013 const uint8_t * next_cu;
4014 const uint8_t * da;
4015 const uint8_t * end;
4016 const uint8_t * enda;
4017 uint64_t sz;
4018 uint16_t vers;
4019 uint64_t abbrev_base;
4020 uint64_t abbrev;
4021 uint8_t address_size;
4022 bool dwarf64;
4023
4024 *name = NULL;
4025 *comp_dir = NULL;
4026 *stmt_list = (uint64_t) -1;
4027
4028 if ( (_file->_dwarfDebugInfoSect == NULL) || (_file->_dwarfDebugAbbrevSect == NULL) )
4029 return false;
4030
4031 if (_file->_dwarfDebugInfoSect->size() < 12)
4032 /* Too small to be a real debug_info section. */
4033 return false;
4034
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;
4038
4039 while ((uint64_t)(next_cu - debug_info) < _file->_dwarfDebugInfoSect->size()) {
4040 di = next_cu;
4041 sz = A::P::E::get32(*(uint32_t*)di);
4042 di += 4;
4043 dwarf64 = sz == 0xffffffff;
4044 if (dwarf64)
4045 sz = A::P::E::get64(*(uint64_t*)di), di += 8;
4046 else if (sz > 0xffffff00)
4047 /* Unknown dwarf format. */
4048 return false;
4049
4050 /* Verify claimed size. */
4051 if (sz + (di - debug_info) > _file->_dwarfDebugInfoSect->size() || sz <= (dwarf64 ? 23 : 11))
4052 return false;
4053
4054 next_cu = di + sz;
4055
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. */
4060 return false;
4061 di += 2;
4062
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;
4066
4067 if (abbrev_base > _file->_dwarfDebugAbbrevSect->size())
4068 return false;
4069 da = debug_abbrev + abbrev_base;
4070 enda = debug_abbrev + _file->_dwarfDebugAbbrevSect->size();
4071
4072 address_size = *di++;
4073
4074 /* Find the abbrev number we're looking for. */
4075 end = di + sz;
4076 abbrev = read_uleb128 (&di, end);
4077 if (abbrev == (uint64_t) -1)
4078 return false;
4079
4080 /* Skip through the debug_abbrev section looking for that abbrev. */
4081 for (;;)
4082 {
4083 uint64_t this_abbrev = read_uleb128 (&da, enda);
4084 uint64_t attr;
4085
4086 if (this_abbrev == abbrev)
4087 /* This is almost always taken. */
4088 break;
4089 skip_leb128 (&da, enda); /* Skip the tag. */
4090 if (da == enda)
4091 return false;
4092 da++; /* Skip the DW_CHILDREN_* value. */
4093
4094 do {
4095 attr = read_uleb128 (&da, enda);
4096 skip_leb128 (&da, enda);
4097 } while (attr != 0 && attr != (uint64_t) -1);
4098 if (attr != 0)
4099 return false;
4100 }
4101
4102 /* Check that the abbrev is one for a DW_TAG_compile_unit. */
4103 if (read_uleb128 (&da, enda) != DW_TAG_compile_unit)
4104 return false;
4105 if (da == enda)
4106 return false;
4107 da++; /* Skip the DW_CHILDREN_* value. */
4108
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) {
4113
4114 uint64_t attr = read_uleb128 (&da, enda);
4115 uint64_t form = read_uleb128 (&da, enda);
4116
4117 if (attr == (uint64_t) -1)
4118 return false;
4119 else if (attr == 0)
4120 return true;
4121 if (form == DW_FORM_indirect)
4122 form = read_uleb128 (&di, end);
4123
4124 switch (attr) {
4125 case DW_AT_name:
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;
4133 break;
4134 case DW_AT_comp_dir:
4135 *comp_dir = getDwarfString(form, di);
4136 break;
4137 case DW_AT_stmt_list:
4138 *stmt_list = getDwarfOffset(form, di, dwarf64);
4139 break;
4140 default:
4141 if (! skip_form (&di, end, form, address_size, dwarf64))
4142 return false;
4143 }
4144 }
4145 }
4146 return false;
4147 }
4148
4149
4150
4151 template <typename A>
4152 File<A>::~File()
4153 {
4154 free(_sectionsArray);
4155 free(_atomsArray);
4156 }
4157
4158 template <typename A>
4159 const char* File<A>::translationUnitSource() const
4160 {
4161 return _dwarfTranslationUnitPath;
4162 }
4163
4164 template <typename A>
4165 bool File<A>::forEachAtom(ld::File::AtomHandler& handler) const
4166 {
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>);
4172 }
4173 p = _aliasAtomsArray;
4174 for(int i=_aliasAtomsArrayCount; i > 0; --i) {
4175 handler.doAtom(*((AliasAtom*)p));
4176 p += sizeof(AliasAtom);
4177 }
4178
4179 return (_atomsArrayCount != 0) || (_aliasAtomsArrayCount != 0);
4180 }
4181
4182 template <typename A>
4183 const char* Section<A>::makeSegmentName(const macho_section<typename A::P>* sect)
4184 {
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 )
4189 return name;
4190 char* tmp = new char[17];
4191 strlcpy(tmp, name, 17);
4192 return tmp;
4193 }
4194
4195 template <typename A>
4196 const char* Section<A>::makeSectionName(const macho_section<typename A::P>* sect)
4197 {
4198 const char* name = sect->sectname();
4199 if ( strlen(name) < 16 )
4200 return name;
4201
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";
4223
4224 char* tmp = new char[17];
4225 strlcpy(tmp, name, 17);
4226 return tmp;
4227 }
4228
4229 template <typename A>
4230 bool Section<A>::readable(const macho_section<typename A::P>* sect)
4231 {
4232 return true;
4233 }
4234
4235 template <typename A>
4236 bool Section<A>::writable(const macho_section<typename A::P>* sect)
4237 {
4238 // mach-o .o files do not contain segment permissions
4239 // we just know TEXT is special
4240 return ( strcmp(sect->segname(), "__TEXT") != 0 );
4241 }
4242
4243 template <typename A>
4244 bool Section<A>::exectuable(const macho_section<typename A::P>* sect)
4245 {
4246 // mach-o .o files do not contain segment permissions
4247 // we just know TEXT is special
4248 return ( strcmp(sect->segname(), "__TEXT") == 0 );
4249 }
4250
4251
4252 template <typename A>
4253 ld::Section::Type Section<A>::sectionType(const macho_section<typename A::P>* sect)
4254 {
4255 switch ( sect->flags() & SECTION_TYPE ) {
4256 case S_ZEROFILL:
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;
4261 else
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;
4279 case S_INTERPOSING:
4280 return ld::Section::typeUnclassified;
4281 case S_16BYTE_LITERALS:
4282 return ld::Section::typeLiteral16;
4283 case S_REGULAR:
4284 case S_COALESCED:
4285 if ( sect->flags() & S_ATTR_PURE_INSTRUCTIONS ) {
4286 return ld::Section::typeCode;
4287 }
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;
4299 }
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;
4311 }
4312 else if ( strcmp(sect->segname(), "__OBJC") == 0 ) {
4313 if ( strcmp(sect->sectname(), "__class") == 0 )
4314 return ld::Section::typeObjC1Classes;
4315 }
4316 break;
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;
4327 }
4328 return ld::Section::typeUnclassified;
4329 }
4330
4331
4332 template <typename A>
4333 Atom<A>* Section<A>::findContentAtomByAddress(pint_t addr, class Atom<A>* start, class Atom<A>* end)
4334 {
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)
4345 return pivot;
4346 // address in "end" label (but not in alias)
4347 if ( (pivot->_size == 0) && (addr == atomEndAddr) && !pivot->isAlias() )
4348 return pivot;
4349 }
4350 if ( addr >= atomEndAddr ) {
4351 // key > pivot
4352 // move base to atom after pivot
4353 base = &pivot[1];
4354 --n;
4355 }
4356 else {
4357 // key < pivot
4358 // keep same base
4359 }
4360 }
4361 return NULL;
4362 }
4363
4364 template <typename A>
4365 ld::Atom::Alignment Section<A>::alignmentForAddress(pint_t addr)
4366 {
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);
4372 }
4373
4374 template <typename A>
4375 uint32_t Section<A>::sectionNum(class Parser<A>& parser) const
4376 {
4377 if ( _machOSection == NULL )
4378 return 0;
4379 else
4380 return 1 + (this->_machOSection - parser.firstMachOSection());
4381 }
4382
4383 // arm does not have zero cost exceptions
4384 template <>
4385 uint32_t CFISection<arm>::cfiCount(Parser<arm>& parser)
4386 {
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());
4392 }
4393 return 0;
4394 }
4395
4396 template <typename A>
4397 uint32_t CFISection<A>::cfiCount(Parser<A>& parser)
4398 {
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());
4403 }
4404
4405 template <typename A>
4406 void CFISection<A>::warnFunc(void* ref, uint64_t funcAddr, const char* msg)
4407 {
4408 Parser<A>* parser = (Parser<A>*)ref;
4409 if ( ! parser->warnUnwindConversionProblems() )
4410 return;
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);
4415 }
4416 else {
4417 warning("could not create compact unwind: %s", msg);
4418 }
4419 }
4420
4421 template <>
4422 bool CFISection<x86_64>::needsRelocating()
4423 {
4424 return true;
4425 }
4426
4427 template <>
4428 bool CFISection<arm64>::needsRelocating()
4429 {
4430 return true;
4431 }
4432
4433
4434 template <typename A>
4435 bool CFISection<A>::needsRelocating()
4436 {
4437 return false;
4438 }
4439
4440 template <>
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)
4444 {
4445 const uint32_t sectionSize = this->_machOSection->size();
4446 // copy __eh_frame data to buffer
4447 memcpy(buffer, file().fileContent() + this->_machOSection->offset(), sectionSize);
4448
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) {
4453 uint64_t value = 0;
4454 switch ( reloc->r_type() ) {
4455 case X86_64_RELOC_SUBTRACTOR:
4456 value = 0 - parser.symbolFromIndex(reloc->r_symbolnum()).n_value();
4457 ++reloc;
4458 if ( reloc->r_extern() )
4459 value += parser.symbolFromIndex(reloc->r_symbolnum()).n_value();
4460 break;
4461 case X86_64_RELOC_UNSIGNED:
4462 value = parser.symbolFromIndex(reloc->r_symbolnum()).n_value();
4463 break;
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();
4468 break;
4469 default:
4470 fprintf(stderr, "CFISection::cfiParse() unexpected relocation type at r_address=0x%08X\n", reloc->r_address());
4471 break;
4472 }
4473 if ( reloc->r_address() > sectionSize )
4474 throwf("malformed __eh_frame relocation, offset (0x%08X) is beyond end of section,", reloc->r_address());
4475 uint64_t* p64;
4476 uint32_t* p32;
4477 switch ( reloc->r_length() ) {
4478 case 3:
4479 p64 = (uint64_t*)&buffer[reloc->r_address()];
4480 E::set64(*p64, value + E::get64(*p64));
4481 break;
4482 case 2:
4483 p32 = (uint32_t*)&buffer[reloc->r_address()];
4484 E::set32(*p32, value + E::get32(*p32));
4485 break;
4486 default:
4487 fprintf(stderr, "CFISection::cfiParse() unexpected relocation size at r_address=0x%08X\n", reloc->r_address());
4488 break;
4489 }
4490 }
4491
4492 // create ObjectAddressSpace object for use by libunwind
4493 OAS oas(*this, buffer);
4494
4495 // use libuwind to parse __eh_frame data into array of CFI_Atom_Info
4496 const char* msg;
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);
4501 if ( msg != NULL )
4502 throwf("malformed __eh_frame section: %s", msg);
4503 }
4504
4505 template <>
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)
4509 {
4510 // create ObjectAddressSpace object for use by libunwind
4511 OAS oas(*this, (uint8_t*)this->file().fileContent()+this->_machOSection->offset());
4512
4513 // use libuwind to parse __eh_frame data into array of CFI_Atom_Info
4514 const char* msg;
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);
4519 if ( msg != NULL )
4520 throwf("malformed __eh_frame section: %s", msg);
4521 }
4522
4523
4524
4525
4526 template <>
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)
4530 {
4531 if ( !parser.armUsesZeroCostExceptions() ) {
4532 // most arm do not use zero cost exceptions
4533 assert(count == 0);
4534 return;
4535 }
4536 // create ObjectAddressSpace object for use by libunwind
4537 OAS oas(*this, (uint8_t*)this->file().fileContent()+this->_machOSection->offset());
4538
4539 // use libuwind to parse __eh_frame data into array of CFI_Atom_Info
4540 const char* msg;
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);
4545 if ( msg != NULL )
4546 throwf("malformed __eh_frame section: %s", msg);
4547 }
4548
4549
4550
4551
4552 template <>
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)
4556 {
4557 // copy __eh_frame data to buffer
4558 const uint32_t sectionSize = this->_machOSection->size();
4559 memcpy(buffer, file().fileContent() + this->_machOSection->offset(), sectionSize);
4560
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);
4569 uint64_t value = 0;
4570 switch ( reloc->r_type() ) {
4571 case ARM64_RELOC_SUBTRACTOR:
4572 value = 0 - parser.symbolFromIndex(reloc->r_symbolnum()).n_value();
4573 ++reloc;
4574 if ( reloc->r_extern() )
4575 value += parser.symbolFromIndex(reloc->r_symbolnum()).n_value();
4576 break;
4577 case ARM64_RELOC_UNSIGNED:
4578 value = parser.symbolFromIndex(reloc->r_symbolnum()).n_value();
4579 break;
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();
4584 addend32 = 0;
4585 addend64 = 0;
4586 break;
4587 default:
4588 fprintf(stderr, "CFISection::cfiParse() unexpected relocation type at r_address=0x%08X\n", reloc->r_address());
4589 break;
4590 }
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() ) {
4594 case 3:
4595 E::set64(*p64, value + addend64);
4596 break;
4597 case 2:
4598 E::set32(*p32, value + addend32);
4599 break;
4600 default:
4601 fprintf(stderr, "CFISection::cfiParse() unexpected relocation size at r_address=0x%08X\n", reloc->r_address());
4602 break;
4603 }
4604 }
4605
4606
4607 // create ObjectAddressSpace object for use by libunwind
4608 OAS oas(*this, buffer);
4609
4610 // use libuwind to parse __eh_frame data into array of CFI_Atom_Info
4611 const char* msg;
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);
4616 if ( msg != NULL )
4617 throwf("malformed __eh_frame section: %s", msg);
4618 }
4619
4620
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)
4625 {
4626 return cfis.cfiCount;
4627 }
4628
4629
4630
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)
4635 {
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>);
4647 }
4648 this->_endAtoms = (Atom<A>*)p;
4649 return cfis.cfiCount;
4650 }
4651
4652
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; }
4657
4658 template <>
4659 void CFISection<x86_64>::addCiePersonalityFixups(class Parser<x86_64>& parser, const CFI_Atom_Info* cieInfo)
4660 {
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);
4669
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);
4675 }
4676 else if ( personalityEncoding != 0 ) {
4677 throwf("unsupported address encoding (%02X) of personality function in CIE",
4678 personalityEncoding);
4679 }
4680 }
4681
4682 template <>
4683 void CFISection<x86>::addCiePersonalityFixups(class Parser<x86>& parser, const CFI_Atom_Info* cieInfo)
4684 {
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);
4693
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);
4698 }
4699 else if ( personalityEncoding != 0 ) {
4700 throwf("unsupported address encoding (%02X) of personality function in CIE", personalityEncoding);
4701 }
4702 }
4703
4704 #if SUPPORT_ARCH_arm64
4705 template <>
4706 void CFISection<arm64>::addCiePersonalityFixups(class Parser<arm64>& parser, const CFI_Atom_Info* cieInfo)
4707 {
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);
4716
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);
4721 }
4722 else if ( personalityEncoding != 0 ) {
4723 throwf("unsupported address encoding (%02X) of personality function in CIE",
4724 personalityEncoding);
4725 }
4726 }
4727 #endif
4728
4729
4730 template <>
4731 void CFISection<arm>::addCiePersonalityFixups(class Parser<arm>& parser, const CFI_Atom_Info* cieInfo)
4732 {
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);
4741
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);
4746 }
4747 else if ( personalityEncoding != 0 ) {
4748 throwf("unsupported address encoding (%02X) of personality function in CIE", personalityEncoding);
4749 }
4750 }
4751
4752
4753
4754 template <typename A>
4755 void CFISection<A>::addCiePersonalityFixups(class Parser<A>& parser, const CFI_Atom_Info* cieInfo)
4756 {
4757 assert(0 && "addCiePersonalityFixups() not implemented for arch");
4758 }
4759
4760 template <typename A>
4761 void CFISection<A>::makeFixups(class Parser<A>& parser, const struct Parser<A>::CFI_CU_InfoArrays& cfis)
4762 {
4763 ld::Fixup::Kind store32 = bigEndian() ? ld::Fixup::kindStoreBigEndian32 : ld::Fixup::kindStoreLittleEndian32;
4764 ld::Fixup::Kind store64 = bigEndian() ? ld::Fixup::kindStoreBigEndian64 : ld::Fixup::kindStoreLittleEndian64;
4765
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) {
4769 if ( p->isCIE ) {
4770 // add reference to personality function if used
4771 if ( p->u.cieInfo.personality.targetAddress != CFI_INVALID_ADDRESS ) {
4772 this->addCiePersonalityFixups(parser, p);
4773 }
4774 }
4775 else {
4776 // find FDE Atom
4777 Atom<A>* fdeAtom = this->findAtomByAddress(p->address);
4778 // find function Atom
4779 Atom<A>* functionAtom = parser.findAtomByAddress(p->u.fdeInfo.function.targetAddress);
4780 // find CIE Atom
4781 Atom<A>* cieAtom = this->findAtomByAddress(p->u.fdeInfo.cie.targetAddress);
4782 // find LSDA Atom
4783 Atom<A>* lsdaAtom = NULL;
4784 if ( p->u.fdeInfo.lsda.targetAddress != CFI_INVALID_ADDRESS ) {
4785 lsdaAtom = parser.findAtomByAddress(p->u.fdeInfo.lsda.targetAddress);
4786 }
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);
4793
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);
4803 break;
4804 }
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);
4811 break;
4812 default:
4813 throw "unsupported encoding in FDE of pointer to function";
4814 }
4815
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);
4826 break;
4827 }
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);
4834 break;
4835 default:
4836 throw "unsupported encoding in FDE of pointer to LSDA";
4837 }
4838 }
4839
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);
4843
4844 // LSDA is in group lead by function atom
4845 if ( lsdaAtom != NULL ) {
4846 parser.addFixup(fdeSrc, ld::Fixup::k1of1, ld::Fixup::kindNoneGroupSubordinateLSDA, lsdaAtom);
4847 }
4848 }
4849 }
4850 }
4851
4852
4853
4854
4855 template <typename A>
4856 const void* CFISection<A>::OAS::mappedAddress(pint_t addr)
4857 {
4858 if ( (_ehFrameStartAddr <= addr) && (addr < _ehFrameEndAddr) )
4859 return &_ehFrameContent[addr-_ehFrameStartAddr];
4860 else {
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();
4870 }
4871 }
4872 }
4873 throwf("__eh_frame parsing problem. Can't find target of reference to address 0x%08llX", (uint64_t)addr);
4874 }
4875 }
4876
4877
4878 template <typename A>
4879 uint64_t CFISection<A>::OAS::getULEB128(pint_t& logicalAddr, pint_t end)
4880 {
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);
4886 return result;
4887 }
4888
4889 template <typename A>
4890 int64_t CFISection<A>::OAS::getSLEB128(pint_t& logicalAddr, pint_t end)
4891 {
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);
4897 return result;
4898 }
4899
4900 template <typename A>
4901 typename A::P::uint_t CFISection<A>::OAS::getEncodedP(pint_t& addr, pint_t end, uint8_t encoding)
4902 {
4903 pint_t startAddr = addr;
4904 pint_t p = addr;
4905 pint_t result;
4906
4907 // first get value
4908 switch (encoding & 0x0F) {
4909 case DW_EH_PE_ptr:
4910 result = getP(addr);
4911 p += sizeof(pint_t);
4912 addr = (pint_t)p;
4913 break;
4914 case DW_EH_PE_uleb128:
4915 result = getULEB128(addr, end);
4916 break;
4917 case DW_EH_PE_udata2:
4918 result = get16(addr);
4919 p += 2;
4920 addr = (pint_t)p;
4921 break;
4922 case DW_EH_PE_udata4:
4923 result = get32(addr);
4924 p += 4;
4925 addr = (pint_t)p;
4926 break;
4927 case DW_EH_PE_udata8:
4928 result = get64(addr);
4929 p += 8;
4930 addr = (pint_t)p;
4931 break;
4932 case DW_EH_PE_sleb128:
4933 result = getSLEB128(addr, end);
4934 break;
4935 case DW_EH_PE_sdata2:
4936 result = (int16_t)get16(addr);
4937 p += 2;
4938 addr = (pint_t)p;
4939 break;
4940 case DW_EH_PE_sdata4:
4941 result = (int32_t)get32(addr);
4942 p += 4;
4943 addr = (pint_t)p;
4944 break;
4945 case DW_EH_PE_sdata8:
4946 result = get64(addr);
4947 p += 8;
4948 addr = (pint_t)p;
4949 break;
4950 default:
4951 throwf("ObjectFileAddressSpace<A>::getEncodedP() encoding 0x%08X not supported", encoding);
4952 }
4953
4954 // then add relative offset
4955 switch ( encoding & 0x70 ) {
4956 case DW_EH_PE_absptr:
4957 // do nothing
4958 break;
4959 case DW_EH_PE_pcrel:
4960 result += startAddr;
4961 break;
4962 case DW_EH_PE_textrel:
4963 throw "DW_EH_PE_textrel pointer encoding not supported";
4964 break;
4965 case DW_EH_PE_datarel:
4966 throw "DW_EH_PE_datarel pointer encoding not supported";
4967 break;
4968 case DW_EH_PE_funcrel:
4969 throw "DW_EH_PE_funcrel pointer encoding not supported";
4970 break;
4971 case DW_EH_PE_aligned:
4972 throw "DW_EH_PE_aligned pointer encoding not supported";
4973 break;
4974 default:
4975 throwf("ObjectFileAddressSpace<A>::getEncodedP() encoding 0x%08X not supported", encoding);
4976 break;
4977 }
4978
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);
4984
4985 return result;
4986 }
4987
4988 template <>
4989 const char* CUSection<x86_64>::personalityName(class Parser<x86_64>& parser, const macho_relocation_info<x86_64::P>* reloc)
4990 {
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);
4995 }
4996 else {
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);
5002 return name;
5003 }
5004 }
5005
5006 template <>
5007 const char* CUSection<x86>::personalityName(class Parser<x86>& parser, const macho_relocation_info<x86::P>* reloc)
5008 {
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);
5013 }
5014 else {
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);
5023 return name;
5024 }
5025 else {
5026 uint32_t symIndex = parser.symbolIndexFromIndirectSectionAddress(nlPointerAddr, nlSection->machoSection());
5027 const macho_nlist<P>& nlSymbol = parser.symbolFromIndex(symIndex);
5028 return parser.nameFromSymbol(nlSymbol);
5029 }
5030 }
5031 }
5032
5033 #if SUPPORT_ARCH_arm64
5034 template <>
5035 const char* CUSection<arm64>::personalityName(class Parser<arm64>& parser, const macho_relocation_info<arm64::P>* reloc)
5036 {
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);
5041 }
5042 else {
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);
5050 return name;
5051 }
5052 }
5053 #endif
5054
5055
5056 #if SUPPORT_ARCH_arm_any
5057 template <>
5058 const char* CUSection<arm>::personalityName(class Parser<arm>& parser, const macho_relocation_info<arm::P>* reloc)
5059 {
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);
5064 }
5065 else {
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);
5074 return name;
5075 }
5076 else {
5077 uint32_t symIndex = parser.symbolIndexFromIndirectSectionAddress(nlPointerAddr, nlSection->machoSection());
5078 const macho_nlist<P>& nlSymbol = parser.symbolFromIndex(symIndex);
5079 return parser.nameFromSymbol(nlSymbol);
5080 }
5081 }
5082 }
5083 #endif
5084
5085
5086 template <typename A>
5087 const char* CUSection<A>::personalityName(class Parser<A>& parser, const macho_relocation_info<P>* reloc)
5088 {
5089 return NULL;
5090 }
5091
5092 template <>
5093 bool CUSection<x86>::encodingMeansUseDwarf(compact_unwind_encoding_t enc)
5094 {
5095 return ((enc & UNWIND_X86_MODE_MASK) == UNWIND_X86_MODE_DWARF);
5096 }
5097
5098 template <>
5099 bool CUSection<x86_64>::encodingMeansUseDwarf(compact_unwind_encoding_t enc)
5100 {
5101 return ((enc & UNWIND_X86_64_MODE_MASK) == UNWIND_X86_64_MODE_DWARF);
5102 }
5103
5104 #if SUPPORT_ARCH_arm_any
5105 template <>
5106 bool CUSection<arm>::encodingMeansUseDwarf(compact_unwind_encoding_t enc)
5107 {
5108 return ((enc & UNWIND_ARM_MODE_MASK) == UNWIND_ARM_MODE_DWARF);
5109 }
5110 #endif
5111
5112 #if SUPPORT_ARCH_arm64
5113 template <>
5114 bool CUSection<arm64>::encodingMeansUseDwarf(compact_unwind_encoding_t enc)
5115 {
5116 return ((enc & UNWIND_ARM64_MODE_MASK) == UNWIND_ARM64_MODE_DWARF);
5117 }
5118 #endif
5119
5120
5121 template <typename A>
5122 int CUSection<A>::infoSorter(const void* l, const void* r)
5123 {
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);
5129 else
5130 return (left->functionSymbolIndex - right->functionSymbolIndex);
5131 }
5132
5133 template <typename A>
5134 void CUSection<A>::parse(class Parser<A>& parser, uint32_t cnt, Info array[])
5135 {
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;
5148 info->lsda = 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;
5153 }
5154 }
5155
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 )
5162 continue;
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);
5170 }
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();
5176 else
5177 warning("unexpected extern relocation to lsda in __compact_unwind section");
5178 }
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();
5183 }
5184 else {
5185 warning("unexpected extern relocation in __compact_unwind section");
5186 }
5187 }
5188 else {
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);
5192 }
5193 }
5194 }
5195
5196 // sort array by function start address so unwind infos will be contiguous for a given function
5197 ::qsort(array, cnt, sizeof(Info), infoSorter);
5198 }
5199
5200 template <typename A>
5201 uint32_t CUSection<A>::count()
5202 {
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";
5206
5207 return machoSect->size() / sizeof(macho_compact_unwind_entry<P>);
5208 }
5209
5210 template <typename A>
5211 void CUSection<A>::makeFixups(class Parser<A>& parser, const struct Parser<A>::CFI_CU_InfoArrays& cus)
5212 {
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);
5224 }
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);
5229 }
5230 }
5231
5232 }
5233
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)
5237 {
5238 switch ( s->flags() & SECTION_TYPE ) {
5239 case S_ZEROFILL:
5240 _type = ld::Atom::typeZeroFill;
5241 break;
5242 case S_MOD_INIT_FUNC_POINTERS:
5243 _type = ld::Atom::typeInitializerPointers;
5244 break;
5245 case S_MOD_TERM_FUNC_POINTERS:
5246 _type = ld::Atom::typeTerminatorPointers;
5247 break;
5248 case S_THREAD_LOCAL_VARIABLES:
5249 _type = ld::Atom::typeTLV;
5250 break;
5251 case S_THREAD_LOCAL_ZEROFILL:
5252 _type = ld::Atom::typeTLVZeroFill;
5253 break;
5254 case S_THREAD_LOCAL_REGULAR:
5255 _type = ld::Atom::typeTLVInitialValue;
5256 break;
5257 case S_THREAD_LOCAL_INIT_FUNCTION_POINTERS:
5258 _type = ld::Atom::typeTLVInitializerPointers;
5259 break;
5260 case S_REGULAR:
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;
5265 break;
5266 }
5267 }
5268
5269
5270 template <typename A>
5271 bool SymboledSection<A>::dontDeadStrip()
5272 {
5273 switch ( _type ) {
5274 case ld::Atom::typeInitializerPointers:
5275 case ld::Atom::typeTerminatorPointers:
5276 return true;
5277 default:
5278 // model an object file without MH_SUBSECTIONS_VIA_SYMBOLS as one in which nothing can be dead stripped
5279 if ( ! this->_file.canScatterAtoms() )
5280 return true;
5281 // call inherited
5282 return Section<A>::dontDeadStrip();
5283 }
5284 return false;
5285 }
5286
5287
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&)
5292 {
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);
5296
5297 uint32_t count = 0;
5298 pint_t addr;
5299 pint_t size;
5300 const macho_nlist<P>* sym;
5301 while ( it.next(parser, *this, sectNum, startAddr, endAddr, &addr, &size, &sym) ) {
5302 ++count;
5303 }
5304 //fprintf(stderr, "computeAtomCount(%s,%s) => %d\n", this->segmentName(), this->sectionName(), count);
5305 return count;
5306 }
5307
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&)
5312 {
5313 this->_beginAtoms = (Atom<A>*)p;
5314
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);
5319
5320 uint32_t count = 0;
5321 pint_t addr;
5322 pint_t size;
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);
5333 if ( isAlias )
5334 this->_hasAliases = true;
5335 if ( parser.altEntryFromSymbol(*label) )
5336 this->_altEntries.insert(allocatedSpace);
5337 }
5338 else {
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));
5346 }
5347 p += sizeof(Atom<A>);
5348 ++count;
5349 }
5350
5351 this->_endAtoms = (Atom<A>*)p;
5352 return count;
5353 }
5354
5355
5356 template <>
5357 ld::Atom::SymbolTableInclusion ImplicitSizeSection<arm64>::symbolTableInclusion()
5358 {
5359 return ld::Atom::symbolTableInWithRandomAutoStripLabel;
5360 }
5361
5362
5363 template <typename A>
5364 ld::Atom::SymbolTableInclusion ImplicitSizeSection<A>::symbolTableInclusion()
5365 {
5366 return ld::Atom::symbolTableNotIn;
5367 }
5368
5369
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&)
5374 {
5375 uint32_t count = 0;
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) )
5381 ++count;
5382 }
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)) ) {
5394 ++count;
5395 }
5396 prevSymbolAddr = symbolAddr;
5397 prevSymbolSectNum = symbolSectNum;
5398 prevIgnore = ignore;
5399 }
5400 }
5401 return count;
5402 }
5403
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&)
5408 {
5409 this->_beginAtoms = (Atom<A>*)p;
5410
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());
5416 uint32_t count = 0;
5417 pint_t foundAddr;
5418 pint_t size;
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 ) {
5423 bool skip = false;
5424 pint_t labeledAtomSize = this->elementSizeAtAddress(foundAddr);
5425 allocatedSpace = (Atom<A>*)p;
5426 if ( this->ignoreLabel(parser.nameFromSymbol(*foundLabel)) ) {
5427 if ( size == 0 ) {
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
5431 skip = true;
5432 }
5433 else {
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));
5440 }
5441 }
5442 else {
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);
5446 }
5447 if ( !skip ) {
5448 ++count;
5449 p += sizeof(Atom<A>);
5450 foundAddr += labeledAtomSize;
5451 size -= labeledAtomSize;
5452 }
5453 }
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));
5464 ++count;
5465 p += sizeof(Atom<A>);
5466 }
5467 }
5468 }
5469
5470 this->_endAtoms = (Atom<A>*)p;
5471
5472 return count;
5473 }
5474
5475 template <typename A>
5476 bool Literal4Section<A>::ignoreLabel(const char* label) const
5477 {
5478 return (label[0] == 'L') || (label[0] == 'l');
5479 }
5480
5481 template <typename A>
5482 unsigned long Literal4Section<A>::contentHash(const class Atom<A>* atom, const ld::IndirectBindingTable& ind) const
5483 {
5484 const uint32_t* literalContent = (uint32_t*)atom->contentPointer();
5485 return *literalContent;
5486 }
5487
5488 template <typename A>
5489 bool Literal4Section<A>::canCoalesceWith(const class Atom<A>* atom, const ld::Atom& rhs,
5490 const ld::IndirectBindingTable& ind) const
5491 {
5492 assert(this->type() == rhs.section().type());
5493 const uint32_t* literalContent = (uint32_t*)atom->contentPointer();
5494
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);
5500 }
5501 return false;
5502 }
5503
5504
5505 template <typename A>
5506 bool Literal8Section<A>::ignoreLabel(const char* label) const
5507 {
5508 return (label[0] == 'L') || (label[0] == 'l');
5509 }
5510
5511 template <typename A>
5512 unsigned long Literal8Section<A>::contentHash(const class Atom<A>* atom, const ld::IndirectBindingTable& ind) const
5513 {
5514 #if __LP64__
5515 const uint64_t* literalContent = (uint64_t*)atom->contentPointer();
5516 return *literalContent;
5517 #else
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];
5522 }
5523 return hash;
5524 #endif
5525 }
5526
5527 template <typename A>
5528 bool Literal8Section<A>::canCoalesceWith(const class Atom<A>* atom, const ld::Atom& rhs,
5529 const ld::IndirectBindingTable& ind) const
5530 {
5531 if ( rhs.section().type() != ld::Section::typeLiteral8 )
5532 return false;
5533 assert(this->type() == rhs.section().type());
5534 const uint64_t* literalContent = (uint64_t*)atom->contentPointer();
5535
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);
5541 }
5542 return false;
5543 }
5544
5545 template <typename A>
5546 bool Literal16Section<A>::ignoreLabel(const char* label) const
5547 {
5548 return (label[0] == 'L') || (label[0] == 'l');
5549 }
5550
5551 template <typename A>
5552 unsigned long Literal16Section<A>::contentHash(const class Atom<A>* atom, const ld::IndirectBindingTable& ind) const
5553 {
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];
5558 }
5559 return hash;
5560 }
5561
5562 template <typename A>
5563 bool Literal16Section<A>::canCoalesceWith(const class Atom<A>* atom, const ld::Atom& rhs,
5564 const ld::IndirectBindingTable& ind) const
5565 {
5566 if ( rhs.section().type() != ld::Section::typeLiteral16 )
5567 return false;
5568 assert(this->type() == rhs.section().type());
5569 const uint64_t* literalContent = (uint64_t*)atom->contentPointer();
5570
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]));
5576 }
5577 return false;
5578 }
5579
5580
5581
5582 template <typename A>
5583 typename A::P::uint_t CStringSection<A>::elementSizeAtAddress(pint_t addr)
5584 {
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;
5588 }
5589
5590 template <typename A>
5591 bool CStringSection<A>::useElementAt(Parser<A>& parser, struct Parser<A>::LabelAndCFIBreakIterator& it, pint_t addr)
5592 {
5593 return true;
5594 }
5595
5596 template <typename A>
5597 bool CStringSection<A>::ignoreLabel(const char* label) const
5598 {
5599 return (label[0] == 'L') || (label[0] == 'l');
5600 }
5601
5602
5603 template <typename A>
5604 Atom<A>* CStringSection<A>::findAtomByAddress(pint_t addr)
5605 {
5606 Atom<A>* result = this->findContentAtomByAddress(addr, this->_beginAtoms, this->_endAtoms);
5607 return result;
5608 }
5609
5610 template <typename A>
5611 unsigned long CStringSection<A>::contentHash(const class Atom<A>* atom, const ld::IndirectBindingTable& ind) const
5612 {
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;
5617 }
5618 return hash;
5619 }
5620
5621
5622 template <typename A>
5623 bool CStringSection<A>::canCoalesceWith(const class Atom<A>* atom, const ld::Atom& rhs,
5624 const ld::IndirectBindingTable& ind) const
5625 {
5626 if ( rhs.section().type() != ld::Section::typeCString )
5627 return false;
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();
5632
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 )
5637 return false;
5638 const char* rhsStringContent = (char*)rhsAtom->contentPointer();
5639 return (strcmp(stringContent, rhsStringContent) == 0);
5640 }
5641 return false;
5642 }
5643
5644
5645 template <>
5646 ld::Fixup::Kind NonLazyPointerSection<x86>::fixupKind()
5647 {
5648 return ld::Fixup::kindStoreLittleEndian32;
5649 }
5650
5651 template <>
5652 ld::Fixup::Kind NonLazyPointerSection<arm>::fixupKind()
5653 {
5654 return ld::Fixup::kindStoreLittleEndian32;
5655 }
5656
5657 template <>
5658 ld::Fixup::Kind NonLazyPointerSection<arm64>::fixupKind()
5659 {
5660 return ld::Fixup::kindStoreLittleEndian64;
5661 }
5662
5663
5664 template <>
5665 void NonLazyPointerSection<x86_64>::makeFixups(class Parser<x86_64>& parser, const struct Parser<x86_64>::CFI_CU_InfoArrays&)
5666 {
5667 assert(0 && "x86_64 should not have non-lazy-pointer sections in .o files");
5668 }
5669
5670 template <typename A>
5671 void NonLazyPointerSection<A>::makeFixups(class Parser<A>& parser, const struct Parser<A>::CFI_CU_InfoArrays&)
5672 {
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);
5682 target.atom = NULL;
5683 target.name = NULL;
5684 target.weakImport = false;
5685 target.addend = 0;
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);
5697 }
5698 else {
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);
5704 }
5705 else {
5706 target.name = parser.nameFromSymbol(sym);
5707 target.weakImport = parser.weakImportFromSymbol(sym);
5708 assert(src.atom->combine() == ld::Atom::combineByNameAndReferences);
5709 }
5710 }
5711 parser.addFixups(src, this->fixupKind(), target);
5712 }
5713 }
5714
5715 template <typename A>
5716 ld::Atom::Combine NonLazyPointerSection<A>::combine(Parser<A>& parser, pint_t addr)
5717 {
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;
5722
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;
5727
5728 return ld::Atom::combineByNameAndReferences;
5729 }
5730
5731 template <typename A>
5732 const char* NonLazyPointerSection<A>::targetName(const class Atom<A>* atom, const ld::IndirectBindingTable& ind)
5733 {
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:
5740 name = fit->u.name;
5741 break;
5742 case ld::Fixup::bindingByContentBound:
5743 name = fit->u.target->name();
5744 break;
5745 case ld::Fixup::bindingsIndirectlyBound:
5746 name = ind.indirectName(fit->u.bindingIndex);
5747 break;
5748 default:
5749 assert(0);
5750 }
5751 assert(name != NULL);
5752 return name;
5753 }
5754
5755 template <typename A>
5756 unsigned long NonLazyPointerSection<A>::contentHash(const class Atom<A>* atom, const ld::IndirectBindingTable& ind) const
5757 {
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;
5762 }
5763 return hash;
5764 }
5765
5766 template <typename A>
5767 bool NonLazyPointerSection<A>::canCoalesceWith(const class Atom<A>* atom, const ld::Atom& rhs,
5768 const ld::IndirectBindingTable& indirectBindingTable) const
5769 {
5770 if ( rhs.section().type() != ld::Section::typeNonLazyPointer )
5771 return false;
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() )
5776 return false;
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);
5782 }
5783
5784 template <typename A>
5785 ld::Atom::Scope NonLazyPointerSection<A>::scopeAtAddress(Parser<A>& parser, pint_t addr)
5786 {
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;
5791 else
5792 return ld::Atom::scopeLinkageUnit;
5793 }
5794
5795
5796
5797 template <typename A>
5798 ld::Atom::Combine TLVPointerSection<A>::combine(Parser<A>& parser, pint_t addr)
5799 {
5800 return ld::Atom::combineByNameAndReferences;
5801 }
5802
5803 template <>
5804 void TLVPointerSection<arm>::makeFixups(class Parser<arm>& parser, const struct Parser<arm>::CFI_CU_InfoArrays&)
5805 {
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);
5815 target.atom = NULL;
5816 target.name = NULL;
5817 target.weakImport = false;
5818 target.addend = 0;
5819 if ( symIndex == INDIRECT_SYMBOL_LOCAL ) {
5820 throwf("unexpected INDIRECT_SYMBOL_LOCAL in section %s", this->sectionName());
5821 }
5822 else {
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());
5827 }
5828 else {
5829 target.name = parser.nameFromSymbol(sym);
5830 target.weakImport = parser.weakImportFromSymbol(sym);
5831 assert(src.atom->combine() == ld::Atom::combineByNameAndReferences);
5832 }
5833 }
5834 parser.addFixups(src, ld::Fixup::kindStoreLittleEndian32, target);
5835 }
5836 }
5837
5838 template <typename A>
5839 void TLVPointerSection<A>::makeFixups(class Parser<A>& parser, const struct Parser<A>::CFI_CU_InfoArrays&)
5840 {
5841 assert(0 && "should not have thread-local-pointer sections in .o files");
5842 }
5843
5844
5845 template <typename A>
5846 const char* TLVPointerSection<A>::targetName(const class Atom<A>* atom, const ld::IndirectBindingTable& ind, bool* isStatic)
5847 {
5848 assert(atom->combine() == ld::Atom::combineByNameAndReferences);
5849 assert(atom->fixupCount() == 1);
5850 *isStatic = false;
5851 ld::Fixup::iterator fit = atom->fixupsBegin();
5852 const char* name = NULL;
5853 switch ( fit->binding ) {
5854 case ld::Fixup::bindingByNameUnbound:
5855 name = fit->u.name;
5856 break;
5857 case ld::Fixup::bindingByContentBound:
5858 name = fit->u.target->name();
5859 break;
5860 case ld::Fixup::bindingsIndirectlyBound:
5861 name = ind.indirectName(fit->u.bindingIndex);
5862 break;
5863 case ld::Fixup::bindingDirectlyBound:
5864 name = fit->u.target->name();
5865 *isStatic = (fit->u.target->scope() == ld::Atom::scopeTranslationUnit);
5866 break;
5867 default:
5868 assert(0);
5869 }
5870 assert(name != NULL);
5871 return name;
5872 }
5873
5874 template <typename A>
5875 unsigned long TLVPointerSection<A>::contentHash(const class Atom<A>* atom, const ld::IndirectBindingTable& ind) const
5876 {
5877 assert(atom->combine() == ld::Atom::combineByNameAndReferences);
5878 unsigned long hash = 9508;
5879 bool isStatic;
5880 for (const char* s = this->targetName(atom, ind, &isStatic); *s != '\0'; ++s) {
5881 hash = hash * 33 + *s;
5882 }
5883 return hash;
5884 }
5885
5886 template <typename A>
5887 bool TLVPointerSection<A>::canCoalesceWith(const class Atom<A>* atom, const ld::Atom& rhs,
5888 const ld::IndirectBindingTable& indirectBindingTable) const
5889 {
5890 if ( rhs.section().type() != ld::Section::typeTLVPointers )
5891 return false;
5892 assert(this->type() == rhs.section().type());
5893 const Atom<A>* rhsAtom = dynamic_cast<const Atom<A>*>(&rhs);
5894 assert(rhsAtom != NULL);
5895 bool thisIsStatic;
5896 bool rhsIsStatic;
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);
5900 }
5901
5902
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)
5906 {
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);
5916 break;
5917 case ld::Fixup::bindingDirectlyBound:
5918 case ld::Fixup::bindingByContentBound:
5919 targetAtom = fit->u.target;
5920 break;
5921 case ld::Fixup::bindingsIndirectlyBound:
5922 targetAtom = ind.indirectAtom(fit->u.bindingIndex);
5923 break;
5924 default:
5925 assert(0 && "bad binding type");
5926 }
5927 assert(targetAtom != NULL);
5928 const Atom<A>* target = dynamic_cast<const Atom<A>*>(targetAtom);
5929 if ( targetAtom->section().type() == ld::Section::typeCString ) {
5930 *ct = contentUTF8;
5931 *count = targetAtom->size();
5932 }
5933 else if ( targetAtom->section().type() == ld::Section::typeUTF16Strings ) {
5934 *ct = contentUTF16;
5935 *count = (targetAtom->size()+1)/2; // round up incase of buggy compiler that has only one trailing zero byte
5936 }
5937 else {
5938 *ct = contentUnknown;
5939 *count = 0;
5940 return NULL;
5941 }
5942 return target->contentPointer();
5943 }
5944 assert(0);
5945 return NULL;
5946 }
5947
5948 template <typename A>
5949 unsigned long CFStringSection<A>::contentHash(const class Atom<A>* atom, const ld::IndirectBindingTable& ind) const
5950 {
5951 // base hash of CFString on hash of cstring it wraps
5952 ContentType cType;
5953 unsigned long hash;
5954 unsigned int charCount;
5955 const uint8_t* content = this->targetContent(atom, ind, &cType, &charCount);
5956 switch ( cType ) {
5957 case contentUTF8:
5958 hash = 9408;
5959 for (const char* s = (char*)content; *s != '\0'; ++s) {
5960 hash = hash * 33 + *s;
5961 }
5962 return hash;
5963 case contentUTF16:
5964 hash = 407955;
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;
5968 }
5969 return hash;
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);
5973 }
5974 return 0;
5975 }
5976
5977
5978 template <typename A>
5979 bool CFStringSection<A>::canCoalesceWith(const class Atom<A>* atom, const ld::Atom& rhs,
5980 const ld::IndirectBindingTable& indirectBindingTable) const
5981 {
5982 if ( atom == &rhs )
5983 return true;
5984 if ( rhs.section().type() != ld::Section::typeCFString)
5985 return false;
5986 assert(this->type() == rhs.section().type());
5987 assert(strcmp(this->sectionName(), "__cfstring") == 0);
5988
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);
5997
5998 if ( thisType != rhsType )
5999 return false;
6000
6001 if ( thisType == contentUnknown )
6002 return false;
6003
6004 if ( rhsType == contentUnknown )
6005 return false;
6006
6007 // no need to compare content of pointers are already the same
6008 if ( cstringContent == rhsStringContent )
6009 return true;
6010
6011 // no need to compare content if size is different
6012 if ( charCount != rhsCharCount )
6013 return false;
6014
6015 switch ( thisType ) {
6016 case contentUTF8:
6017 return (strcmp((char*)cstringContent, (char*)rhsStringContent) == 0);
6018 case contentUTF16:
6019 {
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] )
6024 return false;
6025 }
6026 return true;
6027 }
6028 case contentUnknown:
6029 return false;
6030 }
6031 return false;
6032 }
6033
6034
6035 template <typename A>
6036 typename A::P::uint_t ObjC1ClassSection<A>::elementSizeAtAddress(pint_t addr)
6037 {
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);
6043 return size;
6044 }
6045
6046 template <typename A>
6047 const char* ObjC1ClassSection<A>::unlabeledAtomName(Parser<A>& parser, pint_t addr)
6048 {
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))));
6054
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 = &sections[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 )
6068 continue;
6069 const char* absName = parser.nameFromSymbol(sym);
6070 if ( strncmp(absName, ".objc_class_name_", 17) == 0 ) {
6071 if ( strcmp(&absName[17], name) == 0 )
6072 return absName;
6073 }
6074 }
6075 assert(0 && "obj class name not found in symbol table");
6076 }
6077 }
6078 assert(0 && "obj class name not found");
6079 return "unknown objc class";
6080 }
6081
6082
6083 template <typename A>
6084 const char* ObjC2ClassRefsSection<A>::targetClassName(const class Atom<A>* atom, const ld::IndirectBindingTable& ind) const
6085 {
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;
6092 break;
6093 case ld::Fixup::bindingDirectlyBound:
6094 case ld::Fixup::bindingByContentBound:
6095 className = fit->u.target->name();
6096 break;
6097 case ld::Fixup::bindingsIndirectlyBound:
6098 className = ind.indirectName(fit->u.bindingIndex);
6099 break;
6100 default:
6101 assert(0 && "unsupported binding in objc2 class ref section");
6102 }
6103 assert(className != NULL);
6104 return className;
6105 }
6106
6107
6108 template <typename A>
6109 unsigned long ObjC2ClassRefsSection<A>::contentHash(const class Atom<A>* atom, const ld::IndirectBindingTable& ind) const
6110 {
6111 unsigned long hash = 978;
6112 for (const char* s = targetClassName(atom, ind); *s != '\0'; ++s) {
6113 hash = hash * 33 + *s;
6114 }
6115 return hash;
6116 }
6117
6118 template <typename A>
6119 bool ObjC2ClassRefsSection<A>::canCoalesceWith(const class Atom<A>* atom, const ld::Atom& rhs,
6120 const ld::IndirectBindingTable& indirectBindingTable) const
6121 {
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);
6128 }
6129
6130
6131 template <typename A>
6132 const char* Objc1ClassReferences<A>::targetCString(const class Atom<A>* atom, const ld::IndirectBindingTable& ind) const
6133 {
6134 assert(atom->fixupCount() == 2);
6135 ld::Fixup::iterator fit = atom->fixupsBegin();
6136 if ( fit->kind == ld::Fixup::kindSetTargetAddress )
6137 ++fit;
6138 const ld::Atom* targetAtom = NULL;
6139 switch ( fit->binding ) {
6140 case ld::Fixup::bindingByContentBound:
6141 targetAtom = fit->u.target;
6142 break;
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));
6147 }
6148 break;
6149 default:
6150 assert(0);
6151 }
6152 assert(targetAtom != NULL);
6153 const Atom<A>* target = dynamic_cast<const Atom<A>*>(targetAtom);
6154 assert(target != NULL);
6155 return (char*)target->contentPointer();
6156 }
6157
6158
6159 template <typename A>
6160 const char* PointerToCStringSection<A>::targetCString(const class Atom<A>* atom, const ld::IndirectBindingTable& ind) const
6161 {
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;
6168 break;
6169 case ld::Fixup::bindingsIndirectlyBound:
6170 targetAtom = ind.indirectAtom(fit->u.bindingIndex);
6171 break;
6172 case ld::Fixup::bindingDirectlyBound:
6173 targetAtom = fit->u.target;
6174 break;
6175 default:
6176 assert(0 && "unsupported reference to selector");
6177 }
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();
6183 }
6184
6185 template <typename A>
6186 unsigned long PointerToCStringSection<A>::contentHash(const class Atom<A>* atom,
6187 const ld::IndirectBindingTable& indirectBindingTable) const
6188 {
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;
6193 }
6194 for (const char* s = this->targetCString(atom, indirectBindingTable); *s != '\0'; ++s) {
6195 hash = hash * 33 + *s;
6196 }
6197 return hash;
6198 }
6199
6200 template <typename A>
6201 bool PointerToCStringSection<A>::canCoalesceWith(const class Atom<A>* atom, const ld::Atom& rhs,
6202 const ld::IndirectBindingTable& indirectBindingTable) const
6203 {
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() )
6208 return false;
6209
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);
6215
6216 assert(cstringContent != NULL);
6217 assert(rhsCstringContent != NULL);
6218 return (strcmp(cstringContent, rhsCstringContent) == 0);
6219 }
6220
6221
6222
6223 template <typename A>
6224 unsigned long UTF16StringSection<A>::contentHash(const class Atom<A>* atom, const ld::IndirectBindingTable& ind) const
6225 {
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;
6232 }
6233 return hash;
6234 }
6235
6236 template <typename A>
6237 bool UTF16StringSection<A>::canCoalesceWith(const class Atom<A>* atom, const ld::Atom& rhs,
6238 const ld::IndirectBindingTable& ind) const
6239 {
6240 if ( rhs.section().type() != ld::Section::typeUTF16Strings )
6241 return false;
6242 assert(0);
6243 return false;
6244 }
6245
6246
6247
6248
6249
6250
6251
6252 template <>
6253 uint32_t Section<x86_64>::x86_64PcRelOffset(uint8_t r_type)
6254 {
6255 switch ( r_type ) {
6256 case X86_64_RELOC_SIGNED:
6257 return 4;
6258 case X86_64_RELOC_SIGNED_1:
6259 return 5;
6260 case X86_64_RELOC_SIGNED_2:
6261 return 6;
6262 case X86_64_RELOC_SIGNED_4:
6263 return 8;
6264 }
6265 return 0;
6266 }
6267
6268
6269 template <>
6270 bool Section<x86_64>::addRelocFixup(class Parser<x86_64>& parser, const macho_relocation_info<P>* reloc)
6271 {
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());
6275 return false;
6276 }
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() ) {
6289 case 0:
6290 contentValue = *fixUpPtr;
6291 break;
6292 case 1:
6293 contentValue = (int64_t)(int16_t)E::get16(*((uint16_t*)fixUpPtr));
6294 break;
6295 case 2:
6296 contentValue = (int64_t)(int32_t)E::get32(*((uint32_t*)fixUpPtr));
6297 break;
6298 case 3:
6299 contentValue = E::get64(*((uint64_t*)fixUpPtr));
6300 break;
6301 }
6302 target.atom = NULL;
6303 target.name = NULL;
6304 target.weakImport = false;
6305 target.addend = 0;
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;
6312 }
6313 else {
6314 target.name = parser.nameFromSymbol(sym);
6315 target.weakImport = parser.weakImportFromSymbol(sym);
6316 target.addend = contentValue;
6317 }
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;
6322 }
6323 }
6324 else {
6325 if ( reloc->r_pcrel() )
6326 contentValue += srcAddr + x86_64PcRelOffset(reloc->r_type());
6327 parser.findTargetFromAddressAndSectionNum(contentValue, reloc->r_symbolnum(), target);
6328 }
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() ) {
6334 case 0:
6335 case 1:
6336 throw "length < 2 and X86_64_RELOC_UNSIGNED not supported";
6337 case 2:
6338 parser.addFixups(src, ld::Fixup::kindStoreLittleEndian32, target);
6339 break;
6340 case 3:
6341 parser.addFixups(src, ld::Fixup::kindStoreLittleEndian64, target);
6342 break;
6343 }
6344 break;
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);
6356 break;
6357 case X86_64_RELOC_SIGNED_1:
6358 if ( reloc->r_extern() )
6359 target.addend += 1;
6360 parser.addFixups(src, ld::Fixup::kindStoreX86PCRel32_1, target);
6361 break;
6362 case X86_64_RELOC_SIGNED_2:
6363 if ( reloc->r_extern() )
6364 target.addend += 2;
6365 parser.addFixups(src, ld::Fixup::kindStoreX86PCRel32_2, target);
6366 break;
6367 case X86_64_RELOC_SIGNED_4:
6368 if ( reloc->r_extern() )
6369 target.addend += 4;
6370 parser.addFixups(src, ld::Fixup::kindStoreX86PCRel32_4, target);
6371 break;
6372 }
6373 break;
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() ) {
6378 case 2:
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]);
6382 }
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]);
6386 }
6387 else {
6388 parser.addFixups(src, ld::Fixup::kindStoreX86BranchPCRel32, target);
6389 }
6390 break;
6391 case 0:
6392 parser.addFixups(src, ld::Fixup::kindStoreX86BranchPCRel8, target);
6393 break;
6394 default:
6395 throwf("length=%d and X86_64_RELOC_BRANCH not supported", reloc->r_length());
6396 }
6397 break;
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);
6406 break;
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);
6415 break;
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";
6425 result = true;
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;
6437 }
6438 else {
6439 toTarget.name = parser.nameFromSymbol(sym);
6440 toTarget.weakImport = parser.weakImportFromSymbol(sym);
6441 toTarget.addend = contentValue;
6442 useDirectBinding = false;
6443 }
6444 }
6445 else {
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));
6448 }
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);
6452 else
6453 parser.addFixup(src, ld::Fixup::k1of4, ld::Fixup::kindSetTargetAddress, toTarget.atom);
6454 }
6455 else
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);
6460 else
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);
6464 else
6465 parser.addFixup(src, ld::Fixup::k4of4, ld::Fixup::kindStoreLittleEndian64);
6466 break;
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);
6475 break;
6476 default:
6477 throwf("unknown relocation type %d", reloc->r_type());
6478 }
6479 return result;
6480 }
6481
6482
6483
6484 template <>
6485 bool Section<x86>::addRelocFixup(class Parser<x86>& parser, const macho_relocation_info<P>* reloc)
6486 {
6487 const macho_section<P>* sect = this->machoSection();
6488 uint32_t srcAddr;
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;
6494
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() ) {
6503 case 0:
6504 contentValue = (int32_t)(int8_t)*fixUpPtr;
6505 if ( reloc->r_pcrel() ) {
6506 kind = ld::Fixup::kindStoreX86BranchPCRel8;
6507 contentValue += srcAddr + sizeof(uint8_t);
6508 }
6509 else
6510 throw "r_length=0 and r_pcrel=0 not supported";
6511 break;
6512 case 1:
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);
6517 }
6518 else
6519 kind = ld::Fixup::kindStoreLittleEndian16;
6520 break;
6521 case 2:
6522 contentValue = E::get32(*((uint32_t*)fixUpPtr));
6523 if ( reloc->r_pcrel() ) {
6524 kind = ld::Fixup::kindStoreX86BranchPCRel32;
6525 contentValue += srcAddr + sizeof(uint32_t);
6526 }
6527 else
6528 kind = ld::Fixup::kindStoreLittleEndian32;
6529 break;
6530 case 3:
6531 throw "r_length=3 not supported";
6532 }
6533 if ( reloc->r_extern() ) {
6534 target.atom = NULL;
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;
6539 }
6540 else {
6541 parser.findTargetFromAddressAndSectionNum(contentValue, reloc->r_symbolnum(), target);
6542 }
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]);
6547 return false;
6548 }
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]);
6552 return false;
6553 }
6554 }
6555 parser.addFixups(src, kind, target);
6556 return false;
6557 break;
6558 case GENERIC_RLEOC_TLV:
6559 {
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);
6568 }
6569 else {
6570 target.atom = NULL;
6571 target.name = parser.nameFromSymbol(sym);
6572 target.weakImport = parser.weakImportFromSymbol(sym);
6573 }
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);
6577 }
6578 else {
6579 parser.addFixups(src, ld::Fixup::kindStoreX86Abs32TLVLoad, target);
6580 }
6581 return false;
6582 }
6583 break;
6584 default:
6585 throwf("unsupported i386 relocation type (%d)", reloc->r_type());
6586 }
6587 }
6588 else {
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
6609 }
6610 }
6611 else {
6612 if ( nextSReloc->r_type() == GENERIC_RELOC_PAIR ) {
6613 nextRelocIsPair = true;
6614 nextRelocAddress = nextSReloc->r_address();
6615 nextRelocValue = nextSReloc->r_value();
6616 }
6617 }
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() ) {
6624 case 0:
6625 contentValue = srcAddr + 1 + *fixUpPtr;
6626 target.addend = (int32_t)contentValue - (int32_t)relocValue;
6627 parser.addFixups(src, ld::Fixup::kindStoreX86PCRel8, target);
6628 break;
6629 case 1:
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);
6633 break;
6634 case 2:
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);
6638 break;
6639 case 3:
6640 throw "unsupported r_length=3 for scattered pc-rel vanilla reloc";
6641 break;
6642 }
6643 }
6644 else {
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);
6650 }
6651 break;
6652 case GENERIC_RELOC_SECTDIFF:
6653 case GENERIC_RELOC_LOCAL_SECTDIFF:
6654 {
6655 if ( !nextRelocIsPair )
6656 throw "GENERIC_RELOC_SECTDIFF missing following pair";
6657 switch ( sreloc->r_length() ) {
6658 case 0:
6659 case 3:
6660 throw "bad length for GENERIC_RELOC_SECTDIFF";
6661 case 1:
6662 contentValue = (int32_t)(int16_t)LittleEndian::get16(*((uint16_t*)fixUpPtr));
6663 kind = ld::Fixup::kindStoreLittleEndian16;
6664 break;
6665 case 2:
6666 contentValue = LittleEndian::get32(*((uint32_t*)fixUpPtr));
6667 kind = ld::Fixup::kindStoreLittleEndian32;
6668 break;
6669 }
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);
6675 if ( addend < 0 ) {
6676 // switch binding base on coalescing
6677 if ( target.atom == NULL ) {
6678 parser.addFixup(src, ld::Fixup::k1of5, ld::Fixup::kindSetTargetAddress, false, target.name);
6679 }
6680 else if ( target.atom->scope() == ld::Atom::scopeTranslationUnit ) {
6681 parser.addFixup(src, ld::Fixup::k1of5, ld::Fixup::kindSetTargetAddress, target.atom);
6682 }
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);
6685 }
6686 else {
6687 parser.addFixup(src, ld::Fixup::k1of5, ld::Fixup::kindSetTargetAddress, false, target.atom->name());
6688 }
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);
6693 }
6694 else {
6695 // switch binding base on coalescing
6696 if ( target.atom == NULL ) {
6697 parser.addFixup(src, ld::Fixup::k1of5, ld::Fixup::kindSetTargetAddress, false, target.name);
6698 }
6699 else if ( target.atom->scope() == ld::Atom::scopeTranslationUnit ) {
6700 parser.addFixup(src, ld::Fixup::k1of5, ld::Fixup::kindSetTargetAddress, target.atom);
6701 }
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);
6704 }
6705 else {
6706 parser.addFixup(src, ld::Fixup::k1of5, ld::Fixup::kindSetTargetAddress, false, target.atom->name());
6707 }
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);
6712 }
6713 }
6714 break;
6715 }
6716 return result;
6717 }
6718 }
6719
6720
6721
6722
6723
6724 #if SUPPORT_ARCH_arm_any
6725 template <>
6726 bool Section<arm>::addRelocFixup(class Parser<arm>& parser, const macho_relocation_info<P>* reloc)
6727 {
6728 const macho_section<P>* sect = this->machoSection();
6729 bool result = false;
6730 uint32_t srcAddr;
6731 uint32_t dstAddr;
6732 uint32_t* fixUpPtr;
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;
6739
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);
6753 }
6754 else {
6755 target.atom = NULL;
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;
6760 }
6761 }
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
6769 displacement += 8;
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);
6778 }
6779 target.addend = dstAddr;
6780 if ( externSymbolIsThumbDef )
6781 target.addend &= -2; // remove thumb bit
6782 }
6783 else {
6784 dstAddr = srcAddr + displacement;
6785 parser.findTargetFromAddressAndSectionNum(dstAddr, reloc->r_symbolnum(), target);
6786 }
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]);
6792 }
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]);
6797 }
6798 else {
6799 parser.addFixups(src, ld::Fixup::kindStoreARMBranch24, target);
6800 }
6801 break;
6802 case ARM_THUMB_RELOC_BR22:
6803 // thumb2 added two more bits to displacement, complicating the displacement decoding
6804 {
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);
6813 int32_t sdis = dis;
6814 if ( s )
6815 sdis |= 0xFE000000;
6816 displacement = sdis;
6817 }
6818 // The pc added will be +4 from the pc
6819 displacement += 4;
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;
6824
6825 if ( reloc->r_extern() ) {
6826 // <rdar://problem/16652542> support large .o files
6827 if ( srcAddr > 0x1000000 ) {
6828 dstAddr -= ((srcAddr + 0xFFFFFF) & 0xFE000000);
6829 }
6830 target.addend = (int64_t)(int32_t)dstAddr;
6831 }
6832 else {
6833 parser.findTargetFromAddressAndSectionNum(dstAddr, reloc->r_symbolnum(), target);
6834 }
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]);
6840 }
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]);
6845 }
6846 else {
6847 parser.addFixups(src, ld::Fixup::kindStoreThumbBranch22, target);
6848 }
6849 break;
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
6858 }
6859 else {
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);
6871 }
6872 }
6873 }
6874 parser.addFixups(src, ld::Fixup::kindStoreLittleEndian32, target);
6875 break;
6876 case ARM_THUMB_32BIT_BRANCH:
6877 // silently ignore old unnecessary reloc
6878 break;
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);
6884 bool isThumb;
6885 if ( reloc->r_length() & 2 ) {
6886 isThumb = true;
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;
6892 }
6893 else {
6894 isThumb = false;
6895 uint32_t imm4 = ((instruction & 0x000F0000) >> 16);
6896 uint32_t imm12 = (instruction & 0x00000FFF);
6897 instruction16 = (imm4 << 12) | imm12;
6898 }
6899 if ( reloc->r_length() & 1 ) {
6900 // high 16
6901 dstAddr = ((instruction16 << 16) | other16);
6902 if ( reloc->r_extern() ) {
6903 target.addend = dstAddr;
6904 if ( externSymbolIsThumbDef )
6905 target.addend &= -2; // remove thumb bit
6906 }
6907 else {
6908 parser.findTargetFromAddress(dstAddr, target);
6909 if ( target.atom->isThumb() )
6910 target.addend &= (-2); // remove thumb bit
6911 }
6912 parser.addFixups(src, (isThumb ? ld::Fixup::kindStoreThumbHigh16 : ld::Fixup::kindStoreARMHigh16), target);
6913 }
6914 else {
6915 // low 16
6916 dstAddr = (other16 << 16) | instruction16;
6917 if ( reloc->r_extern() ) {
6918 target.addend = dstAddr;
6919 if ( externSymbolIsThumbDef )
6920 target.addend &= -2; // remove thumb bit
6921 }
6922 else {
6923 parser.findTargetFromAddress(dstAddr, target);
6924 if ( target.atom->isThumb() )
6925 target.addend &= (-2); // remove thumb bit
6926 }
6927 parser.addFixups(src, (isThumb ? ld::Fixup::kindStoreThumbLow16 : ld::Fixup::kindStoreARMLow16), target);
6928 }
6929 result = true;
6930 }
6931 else
6932 throw "for ARM_RELOC_HALF, next reloc is not ARM_RELOC_PAIR";
6933 break;
6934 default:
6935 throwf("unknown relocation type %d", reloc->r_type());
6936 break;
6937 }
6938 }
6939 else {
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();
6957 result = true;
6958 }
6959 }
6960 else {
6961 if ( nextSReloc->r_type() == ARM_RELOC_PAIR ) {
6962 nextRelocIsPair = true;
6963 nextRelocAddress = nextSReloc->r_address();
6964 nextRelocValue = nextSReloc->r_value();
6965 result = true;
6966 }
6967 }
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);
6981 break;
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
6988 displacement += 8;
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);
6995 break;
6996 case ARM_THUMB_RELOC_BR22:
6997 // thumb2 added two more bits to displacement, complicating the displacement decoding
6998 {
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);
7007 int32_t sdis = dis;
7008 if ( s )
7009 sdis |= 0xFE000000;
7010 displacement = sdis;
7011 }
7012 // The pc added will be +4 from the pc
7013 displacement += 4;
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);
7021 break;
7022 case ARM_RELOC_SECTDIFF:
7023 case ARM_RELOC_LOCAL_SECTDIFF:
7024 {
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);
7044 }
7045 if ( addend < 0 ) {
7046 // switch binding base on coalescing
7047 if ( targetAtom->scope() == ld::Atom::scopeTranslationUnit ) {
7048 parser.addFixup(src, ld::Fixup::k1of5, ld::Fixup::kindSetTargetAddress, targetAtom);
7049 }
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);
7052 }
7053 else {
7054 parser.addFixup(src, ld::Fixup::k1of5, ld::Fixup::kindSetTargetAddress, false, targetAtom->name());
7055 }
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);
7060 }
7061 else {
7062 if ( targetAtom->scope() == ld::Atom::scopeTranslationUnit ) {
7063 parser.addFixup(src, ld::Fixup::k1of5, ld::Fixup::kindSetTargetAddress, targetAtom);
7064 }
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);
7067 }
7068 else {
7069 parser.addFixup(src, ld::Fixup::k1of5, ld::Fixup::kindSetTargetAddress, false, targetAtom->name());
7070 }
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);
7075 }
7076 }
7077 break;
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);
7087 bool isThumb;
7088 if ( sreloc->r_length() & 2 ) {
7089 isThumb = true;
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;
7095 }
7096 else {
7097 isThumb = false;
7098 uint32_t imm4 = ((instruction & 0x000F0000) >> 16);
7099 uint32_t imm12 = (instruction & 0x00000FFF);
7100 instruction16 = (imm4 << 12) | imm12;
7101 }
7102 if ( sreloc->r_length() & 1 )
7103 dstAddr = ((instruction16 << 16) | other16);
7104 else
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);
7111 }
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);
7114 }
7115 else {
7116 parser.addFixup(src, ld::Fixup::k1of5, ld::Fixup::kindSetTargetAddress, false, targetAtom->name());
7117 }
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 ) {
7122 // high 16
7123 parser.addFixup(src, ld::Fixup::k5of5, (isThumb ? ld::Fixup::kindStoreThumbHigh16 : ld::Fixup::kindStoreARMHigh16));
7124 }
7125 else {
7126 // low 16
7127 parser.addFixup(src, ld::Fixup::k5of5, (isThumb ? ld::Fixup::kindStoreThumbLow16 : ld::Fixup::kindStoreARMLow16));
7128 }
7129 result = true;
7130 }
7131 else
7132 throw "ARM_RELOC_HALF_SECTDIFF reloc missing following pair";
7133 break;
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);
7140 bool isThumb;
7141 if ( sreloc->r_length() & 2 ) {
7142 isThumb = true;
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;
7148 }
7149 else {
7150 isThumb = false;
7151 uint32_t imm4 = ((instruction & 0x000F0000) >> 16);
7152 uint32_t imm12 = (instruction & 0x00000FFF);
7153 instruction16 = (imm4 << 12) | imm12;
7154 }
7155 if ( sreloc->r_length() & 1 )
7156 dstAddr = ((instruction16 << 16) | other16);
7157 else
7158 dstAddr = (other16 << 16) | instruction16;
7159 if ( targetAtom->scope() == ld::Atom::scopeTranslationUnit ) {
7160 parser.addFixup(src, ld::Fixup::k1of3, ld::Fixup::kindSetTargetAddress, targetAtom);
7161 }
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);
7164 }
7165 else {
7166 parser.addFixup(src, ld::Fixup::k1of3, ld::Fixup::kindSetTargetAddress, false, targetAtom->name());
7167 }
7168 parser.addFixup(src, ld::Fixup::k2of3, ld::Fixup::kindAddAddend, dstAddr - targetAtom->_objAddress);
7169 if ( sreloc->r_length() & 1 ) {
7170 // high 16
7171 parser.addFixup(src, ld::Fixup::k3of3, (isThumb ? ld::Fixup::kindStoreThumbHigh16 : ld::Fixup::kindStoreARMHigh16));
7172 }
7173 else {
7174 // low 16
7175 parser.addFixup(src, ld::Fixup::k3of3, (isThumb ? ld::Fixup::kindStoreThumbLow16 : ld::Fixup::kindStoreARMLow16));
7176 }
7177 result = true;
7178 }
7179 else
7180 throw "scattered ARM_RELOC_HALF reloc missing following pair";
7181 break;
7182 default:
7183 throwf("unknown ARM scattered relocation type %d", sreloc->r_type());
7184 }
7185 }
7186 return result;
7187 }
7188 #endif
7189
7190
7191 #if SUPPORT_ARCH_arm64
7192 template <>
7193 bool Section<arm64>::addRelocFixup(class Parser<arm64>& parser, const macho_relocation_info<P>* reloc)
7194 {
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
7207 result = true;
7208 if ( reloc->r_address() != addendAddress )
7209 throw "ARM64_RELOC_ADDEND r_address does not match next reloc's r_address";
7210 }
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() ) {
7222 case 0:
7223 contentValue = *fixUpPtr;
7224 break;
7225 case 1:
7226 contentValue = (int64_t)(int16_t)E::get16(*((uint16_t*)fixUpPtr));
7227 break;
7228 case 2:
7229 contentValue = (int64_t)(int32_t)E::get32(*((uint32_t*)fixUpPtr));
7230 break;
7231 case 3:
7232 contentValue = E::get64(*((uint64_t*)fixUpPtr));
7233 break;
7234 }
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;
7242 }
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;
7247 target.name = NULL;
7248 }
7249 else {
7250 target.name = symbolName;
7251 target.weakImport = parser.weakImportFromSymbol(sym);
7252 //target.addend = contentValue;
7253 }
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;
7258 }
7259 }
7260 else {
7261 if ( reloc->r_pcrel() )
7262 contentValue += srcAddr;
7263 parser.findTargetFromAddressAndSectionNum(contentValue, reloc->r_symbolnum(), target);
7264 }
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() ) {
7272 case 0:
7273 case 1:
7274 throw "length < 2 and ARM64_RELOC_UNSIGNED not supported";
7275 case 2:
7276 parser.addFixups(src, ld::Fixup::kindStoreLittleEndian32, target);
7277 break;
7278 case 3:
7279 parser.addFixups(src, ld::Fixup::kindStoreLittleEndian64, target);
7280 break;
7281 }
7282 break;
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]);
7293 }
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]);
7297 }
7298 else {
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;
7306 }
7307 else {
7308 throwf("branch26 instruction at 0x%08X has embedded addend and ARM64_RELOC_ADDEND also used", reloc->r_address());
7309 }
7310 }
7311 parser.addFixups(src, ld::Fixup::kindStoreARM64Branch26, target);
7312 }
7313 break;
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;
7329 }
7330 else {
7331 throwf("adrp instruction at 0x%08X has embedded addend and ARM64_RELOC_ADDEND also used", reloc->r_address());
7332 }
7333 }
7334 parser.addFixups(src, ld::Fixup::kindStoreARM64Page21, target);
7335 break;
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 ) {
7349 case 0x00000000:
7350 break;
7351 case 0x40000000:
7352 encodedAddend *= 2;
7353 break;
7354 case 0x80000000:
7355 encodedAddend *= 4;
7356 break;
7357 case 0xC0000000:
7358 encodedAddend *= 8;
7359 break;
7360 }
7361 }
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;
7366 }
7367 else {
7368 throwf("pageoff12 instruction at 0x%08X has embedded addend and ARM64_RELOC_ADDEND also used", reloc->r_address());
7369 }
7370 }
7371 parser.addFixups(src, ld::Fixup::kindStoreARM64PageOff12, target);
7372 break;
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);
7387 break;
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);
7400 break;
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);
7415 break;
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);
7428 break;
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";
7440 result = true;
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;
7452 }
7453 else {
7454 toTarget.name = parser.nameFromSymbol(sym);
7455 toTarget.weakImport = parser.weakImportFromSymbol(sym);
7456 toTarget.addend = contentValue;
7457 useDirectBinding = false;
7458 }
7459 }
7460 else {
7461 parser.findTargetFromAddressAndSectionNum(contentValue, nextReloc->r_symbolnum(), toTarget);
7462 useDirectBinding = (toTarget.atom->scope() == ld::Atom::scopeTranslationUnit);
7463 }
7464 if ( useDirectBinding )
7465 parser.addFixup(src, ld::Fixup::k1of4, ld::Fixup::kindSetTargetAddress, toTarget.atom);
7466 else
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);
7471 else
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);
7475 else
7476 parser.addFixup(src, ld::Fixup::k4of4, ld::Fixup::kindStoreLittleEndian64);
7477 break;
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);
7487 }
7488 else {
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);
7492 }
7493 break;
7494 default:
7495 throwf("unknown relocation type %d", reloc->r_type());
7496 }
7497 return result;
7498 }
7499 #endif
7500
7501
7502 template <typename A>
7503 bool ObjC1ClassSection<A>::addRelocFixup(class Parser<A>& parser, const macho_relocation_info<P>* reloc)
7504 {
7505 // inherited
7506 FixedSizeSection<A>::addRelocFixup(parser, reloc);
7507
7508 assert(0 && "needs template specialization");
7509 return false;
7510 }
7511
7512 template <>
7513 bool ObjC1ClassSection<x86>::addRelocFixup(class Parser<x86>& parser, const macho_relocation_info<x86::P>* reloc)
7514 {
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() );
7519
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);
7530
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);
7537
7538 parser.addFixup(src, ld::Fixup::k1of1, ld::Fixup::kindSetTargetAddress, false, superClassName);
7539 }
7540 }
7541 // inherited
7542 return FixedSizeSection<x86>::addRelocFixup(parser, reloc);
7543 }
7544
7545
7546
7547 template <typename A>
7548 bool Objc1ClassReferences<A>::addRelocFixup(class Parser<A>& parser, const macho_relocation_info<P>* reloc)
7549 {
7550 // inherited
7551 PointerToCStringSection<A>::addRelocFixup(parser, reloc);
7552
7553 assert(0 && "needs template specialization");
7554 return false;
7555 }
7556
7557
7558
7559 template <>
7560 bool Objc1ClassReferences<x86>::addRelocFixup(class Parser<x86>& parser, const macho_relocation_info<x86::P>* reloc)
7561 {
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() );
7567
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);
7577
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);
7584
7585 parser.addFixup(src, ld::Fixup::k1of1, ld::Fixup::kindSetTargetAddress, false, objcClassName);
7586
7587 // inherited
7588 return PointerToCStringSection<x86>::addRelocFixup(parser, reloc);
7589 }
7590
7591 #if SUPPORT_ARCH_arm64
7592 template <>
7593 void Section<arm64>::addLOH(class Parser<arm64>& parser, int kind, int count, const uint64_t addrs[]) {
7594 switch (kind) {
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:
7599 if ( count != 2 )
7600 warning("arm64 Linker Optimiztion Hint %d has wrong number of arguments", kind);
7601 break;
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:
7606 if ( count != 3 )
7607 warning("arm64 Linker Optimiztion Hint %d has wrong number of arguments", kind);
7608 }
7609
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];
7615 }
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
7625 }
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
7629 }
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]);
7634 }
7635 return; // skip this LOH
7636 }
7637 }
7638
7639 // encoded kind, count, and address deltas in 64-bit addend
7640 ld::Fixup::LOH_arm64 extra;
7641 extra.addend = 0;
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);
7650 }
7651 #endif
7652
7653
7654 template <typename A>
7655 void Section<A>::addLOH(class Parser<A>& parser, int kind, int count, const uint64_t addrs[]) {
7656
7657 }
7658
7659 template <typename A>
7660 void Section<A>::makeFixups(class Parser<A>& parser, const struct Parser<A>::CFI_CU_InfoArrays&)
7661 {
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) {
7668 try {
7669 if ( this->addRelocFixup(parser, &relocs[r]) )
7670 ++r; // skip next
7671 }
7672 catch (const char* msg) {
7673 throwf("in section %s,%s reloc %u: %s", sect->segname(), Section<A>::makeSectionName(sect), r, msg);
7674 }
7675 }
7676
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);
7684 }
7685 }
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);
7694 }
7695 }
7696 }
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));
7700
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);
7710 }
7711 }
7712 }
7713
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);
7718 // ignore stabs
7719 if ( (sym.n_type() & N_STAB) != 0 )
7720 continue;
7721 // ignore non-definitions
7722 if ( (sym.n_type() & N_TYPE) != N_SECT )
7723 continue;
7724
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;
7742 else
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);
7748 }
7749 }
7750 }
7751 }
7752 }
7753
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;
7764 break;
7765 case DICE_KIND_JUMP_TABLE8:
7766 kind = ld::Fixup::kindDataInCodeStartJT8;
7767 break;
7768 case DICE_KIND_JUMP_TABLE16:
7769 kind = ld::Fixup::kindDataInCodeStartJT16;
7770 break;
7771 case DICE_KIND_JUMP_TABLE32:
7772 kind = ld::Fixup::kindDataInCodeStartJT32;
7773 break;
7774 case DICE_KIND_ABS_JUMP_TABLE32:
7775 kind = ld::Fixup::kindDataInCodeStartJTA32;
7776 break;
7777 default:
7778 kind = ld::Fixup::kindDataInCodeStartData;
7779 warning("uknown LC_DATA_IN_CODE kind (%d) at offset 0x%08X", p->kind(), p->offset());
7780 break;
7781 }
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);
7787 }
7788 }
7789 }
7790
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(); ) {
7796 uint64_t addrs[4];
7797 int32_t kind = read_uleb128(&p, parser.optimizationHintsEnd());
7798 if ( kind == 0 ) // padding at end of loh buffer
7799 break;
7800 if ( kind == -1 ) {
7801 warning("malformed uleb128 kind in LC_LINKER_OPTIMIZATION_HINTS");
7802 break;
7803 }
7804 int32_t count = read_uleb128(&p, parser.optimizationHintsEnd());
7805 if ( count == -1 ) {
7806 warning("malformed uleb128 count in LC_LINKER_OPTIMIZATION_HINTS");
7807 break;
7808 }
7809 if ( count > 3 ) {
7810 warning("address count > 3 in LC_LINKER_OPTIMIZATION_HINTS");
7811 break;
7812 }
7813 for (int32_t i=0; i < count; ++i) {
7814 addrs[i] = read_uleb128(&p, parser.optimizationHintsEnd());
7815 }
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]);
7821 //}
7822 //fprintf(stderr, "\n");
7823 }
7824 }
7825 }
7826
7827
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);
7837 }
7838 }
7839 }
7840 }
7841
7842
7843
7844 //
7845 // main function used by linker to instantiate ld::Files
7846 //
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)
7849 {
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);
7855 break;
7856 #endif
7857 #if SUPPORT_ARCH_i386
7858 case CPU_TYPE_I386:
7859 if ( mach_o::relocatable::Parser<x86>::validFile(fileContent) )
7860 return mach_o::relocatable::Parser<x86>::parse(fileContent, fileLength, path, modTime, ordinal, opts);
7861 break;
7862 #endif
7863 #if SUPPORT_ARCH_arm_any
7864 case CPU_TYPE_ARM:
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);
7867 break;
7868 #endif
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);
7873 break;
7874 #endif
7875 }
7876 return NULL;
7877 }
7878
7879 //
7880 // used by archive reader to validate member object file
7881 //
7882 bool isObjectFile(const uint8_t* fileContent, uint64_t fileLength, const ParserOptions& opts)
7883 {
7884 switch ( opts.architecture ) {
7885 case CPU_TYPE_X86_64:
7886 return ( mach_o::relocatable::Parser<x86_64>::validFile(fileContent) );
7887 case CPU_TYPE_I386:
7888 return ( mach_o::relocatable::Parser<x86>::validFile(fileContent) );
7889 case CPU_TYPE_ARM:
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) );
7893 }
7894 return false;
7895 }
7896
7897 //
7898 // used by linker to infer architecture when no -arch is on command line
7899 //
7900 bool isObjectFile(const uint8_t* fileContent, cpu_type_t* result, cpu_subtype_t* subResult, Options::Platform* platform)
7901 {
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);
7907 return true;
7908 }
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);
7914 return true;
7915 }
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);
7921 return true;
7922 }
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);
7928 return true;
7929 }
7930 return false;
7931 }
7932
7933 //
7934 // used by linker is error messages to describe bad .o file
7935 //
7936 const char* archName(const uint8_t* fileContent)
7937 {
7938 if ( mach_o::relocatable::Parser<x86_64>::validFile(fileContent) ) {
7939 return mach_o::relocatable::Parser<x86_64>::fileKind(fileContent);
7940 }
7941 if ( mach_o::relocatable::Parser<x86>::validFile(fileContent) ) {
7942 return mach_o::relocatable::Parser<x86>::fileKind(fileContent);
7943 }
7944 if ( mach_o::relocatable::Parser<arm>::validFile(fileContent, false, 0) ) {
7945 return mach_o::relocatable::Parser<arm>::fileKind(fileContent);
7946 }
7947 return NULL;
7948 }
7949
7950 //
7951 // Used by archive reader when -ObjC option is specified
7952 //
7953 bool hasObjC2Categories(const uint8_t* fileContent)
7954 {
7955 if ( mach_o::relocatable::Parser<x86_64>::validFile(fileContent) ) {
7956 return mach_o::relocatable::Parser<x86_64>::hasObjC2Categories(fileContent);
7957 }
7958 else if ( mach_o::relocatable::Parser<arm>::validFile(fileContent, false, 0) ) {
7959 return mach_o::relocatable::Parser<arm>::hasObjC2Categories(fileContent);
7960 }
7961 else if ( mach_o::relocatable::Parser<x86>::validFile(fileContent, false, 0) ) {
7962 return mach_o::relocatable::Parser<x86>::hasObjC2Categories(fileContent);
7963 }
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);
7967 }
7968 #endif
7969 return false;
7970 }
7971
7972 //
7973 // Used by archive reader when -ObjC option is specified
7974 //
7975 bool hasObjC1Categories(const uint8_t* fileContent)
7976 {
7977 if ( mach_o::relocatable::Parser<x86>::validFile(fileContent, false, 0) ) {
7978 return mach_o::relocatable::Parser<x86>::hasObjC1Categories(fileContent);
7979 }
7980 return false;
7981 }
7982
7983 //
7984 // Used by bitcode obfuscator to get a list of non local symbols from object file
7985 //
7986 bool getNonLocalSymbols(const uint8_t* fileContent, std::vector<const char*> &syms)
7987 {
7988 if ( mach_o::relocatable::Parser<x86_64>::validFile(fileContent) ) {
7989 return mach_o::relocatable::Parser<x86_64>::getNonLocalSymbols(fileContent, syms);
7990 }
7991 else if ( mach_o::relocatable::Parser<arm>::validFile(fileContent, false, 0) ) {
7992 return mach_o::relocatable::Parser<arm>::getNonLocalSymbols(fileContent, syms);
7993 }
7994 else if ( mach_o::relocatable::Parser<x86>::validFile(fileContent, false, 0) ) {
7995 return mach_o::relocatable::Parser<x86>::getNonLocalSymbols(fileContent, syms);
7996 }
7997 else if ( mach_o::relocatable::Parser<arm64>::validFile(fileContent, false, 0) ) {
7998 return mach_o::relocatable::Parser<arm64>::getNonLocalSymbols(fileContent, syms);
7999 }
8000 return false;
8001 }
8002
8003
8004
8005 } // namespace relocatable
8006 } // namespace mach_o
8007
8008