1 //===- MachO.h - MachO object file implementation ---------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file declares the MachOObjectFile class, which implement the ObjectFile
11 // interface for MachO files.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_OBJECT_MACHO_H
16 #define LLVM_OBJECT_MACHO_H
17
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Object/ObjectFile.h"
22 #include "llvm/Support/MachO.h"
23
24 namespace llvm {
25 namespace object {
26
27 /// DiceRef - This is a value type class that represents a single
28 /// data in code entry in the table in a Mach-O object file.
29 class DiceRef {
30 DataRefImpl DicePimpl;
31 const ObjectFile *OwningObject;
32
33 public:
DiceRef()34 DiceRef() : OwningObject(nullptr) { }
35
36 DiceRef(DataRefImpl DiceP, const ObjectFile *Owner);
37
38 bool operator==(const DiceRef &Other) const;
39 bool operator<(const DiceRef &Other) const;
40
41 void moveNext();
42
43 std::error_code getOffset(uint32_t &Result) const;
44 std::error_code getLength(uint16_t &Result) const;
45 std::error_code getKind(uint16_t &Result) const;
46
47 DataRefImpl getRawDataRefImpl() const;
48 const ObjectFile *getObjectFile() const;
49 };
50 typedef content_iterator<DiceRef> dice_iterator;
51
52 /// ExportEntry encapsulates the current-state-of-the-walk used when doing a
53 /// non-recursive walk of the trie data structure. This allows you to iterate
54 /// across all exported symbols using:
55 /// for (const llvm::object::ExportEntry &AnExport : Obj->exports()) {
56 /// }
57 class ExportEntry {
58 public:
59 ExportEntry(ArrayRef<uint8_t> Trie);
60
61 StringRef name() const;
62 uint64_t flags() const;
63 uint64_t address() const;
64 uint64_t other() const;
65 StringRef otherName() const;
66 uint32_t nodeOffset() const;
67
68 bool operator==(const ExportEntry &) const;
69
70 void moveNext();
71
72 private:
73 friend class MachOObjectFile;
74 void moveToFirst();
75 void moveToEnd();
76 uint64_t readULEB128(const uint8_t *&p);
77 void pushDownUntilBottom();
78 void pushNode(uint64_t Offset);
79
80 // Represents a node in the mach-o exports trie.
81 struct NodeState {
82 NodeState(const uint8_t *Ptr);
83 const uint8_t *Start;
84 const uint8_t *Current;
85 uint64_t Flags;
86 uint64_t Address;
87 uint64_t Other;
88 const char *ImportName;
89 unsigned ChildCount;
90 unsigned NextChildIndex;
91 unsigned ParentStringLength;
92 bool IsExportNode;
93 };
94
95 ArrayRef<uint8_t> Trie;
96 SmallString<256> CumulativeString;
97 SmallVector<NodeState, 16> Stack;
98 bool Malformed;
99 bool Done;
100 };
101 typedef content_iterator<ExportEntry> export_iterator;
102
103 /// MachORebaseEntry encapsulates the current state in the decompression of
104 /// rebasing opcodes. This allows you to iterate through the compressed table of
105 /// rebasing using:
106 /// for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
107 /// }
108 class MachORebaseEntry {
109 public:
110 MachORebaseEntry(ArrayRef<uint8_t> opcodes, bool is64Bit);
111
112 uint32_t segmentIndex() const;
113 uint64_t segmentOffset() const;
114 StringRef typeName() const;
115
116 bool operator==(const MachORebaseEntry &) const;
117
118 void moveNext();
119
120 private:
121 friend class MachOObjectFile;
122 void moveToFirst();
123 void moveToEnd();
124 uint64_t readULEB128();
125
126 ArrayRef<uint8_t> Opcodes;
127 const uint8_t *Ptr;
128 uint64_t SegmentOffset;
129 uint32_t SegmentIndex;
130 uint64_t RemainingLoopCount;
131 uint64_t AdvanceAmount;
132 uint8_t RebaseType;
133 uint8_t PointerSize;
134 bool Malformed;
135 bool Done;
136 };
137 typedef content_iterator<MachORebaseEntry> rebase_iterator;
138
139 /// MachOBindEntry encapsulates the current state in the decompression of
140 /// binding opcodes. This allows you to iterate through the compressed table of
141 /// bindings using:
142 /// for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
143 /// }
144 class MachOBindEntry {
145 public:
146 enum class Kind { Regular, Lazy, Weak };
147
148 MachOBindEntry(ArrayRef<uint8_t> Opcodes, bool is64Bit, MachOBindEntry::Kind);
149
150 uint32_t segmentIndex() const;
151 uint64_t segmentOffset() const;
152 StringRef typeName() const;
153 StringRef symbolName() const;
154 uint32_t flags() const;
155 int64_t addend() const;
156 int ordinal() const;
157
158 bool operator==(const MachOBindEntry &) const;
159
160 void moveNext();
161
162 private:
163 friend class MachOObjectFile;
164 void moveToFirst();
165 void moveToEnd();
166 uint64_t readULEB128();
167 int64_t readSLEB128();
168
169 ArrayRef<uint8_t> Opcodes;
170 const uint8_t *Ptr;
171 uint64_t SegmentOffset;
172 uint32_t SegmentIndex;
173 StringRef SymbolName;
174 int Ordinal;
175 uint32_t Flags;
176 int64_t Addend;
177 uint64_t RemainingLoopCount;
178 uint64_t AdvanceAmount;
179 uint8_t BindType;
180 uint8_t PointerSize;
181 Kind TableKind;
182 bool Malformed;
183 bool Done;
184 };
185 typedef content_iterator<MachOBindEntry> bind_iterator;
186
187 class MachOObjectFile : public ObjectFile {
188 public:
189 struct LoadCommandInfo {
190 const char *Ptr; // Where in memory the load command is.
191 MachO::load_command C; // The command itself.
192 };
193 typedef SmallVector<LoadCommandInfo, 4> LoadCommandList;
194 typedef LoadCommandList::const_iterator load_command_iterator;
195
196 MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian, bool Is64Bits,
197 std::error_code &EC);
198
199 void moveSymbolNext(DataRefImpl &Symb) const override;
200
201 uint64_t getNValue(DataRefImpl Sym) const;
202 ErrorOr<StringRef> getSymbolName(DataRefImpl Symb) const override;
203
204 // MachO specific.
205 std::error_code getIndirectName(DataRefImpl Symb, StringRef &Res) const;
206 unsigned getSectionType(SectionRef Sec) const;
207
208 ErrorOr<uint64_t> getSymbolAddress(DataRefImpl Symb) const override;
209 uint32_t getSymbolAlignment(DataRefImpl Symb) const override;
210 uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override;
211 SymbolRef::Type getSymbolType(DataRefImpl Symb) const override;
212 uint32_t getSymbolFlags(DataRefImpl Symb) const override;
213 std::error_code getSymbolSection(DataRefImpl Symb,
214 section_iterator &Res) const override;
215 unsigned getSymbolSectionID(SymbolRef Symb) const;
216 unsigned getSectionID(SectionRef Sec) const;
217
218 void moveSectionNext(DataRefImpl &Sec) const override;
219 std::error_code getSectionName(DataRefImpl Sec,
220 StringRef &Res) const override;
221 uint64_t getSectionAddress(DataRefImpl Sec) const override;
222 uint64_t getSectionSize(DataRefImpl Sec) const override;
223 std::error_code getSectionContents(DataRefImpl Sec,
224 StringRef &Res) const override;
225 uint64_t getSectionAlignment(DataRefImpl Sec) const override;
226 bool isSectionText(DataRefImpl Sec) const override;
227 bool isSectionData(DataRefImpl Sec) const override;
228 bool isSectionBSS(DataRefImpl Sec) const override;
229 bool isSectionVirtual(DataRefImpl Sec) const override;
230 relocation_iterator section_rel_begin(DataRefImpl Sec) const override;
231 relocation_iterator section_rel_end(DataRefImpl Sec) const override;
232
233 void moveRelocationNext(DataRefImpl &Rel) const override;
234 uint64_t getRelocationOffset(DataRefImpl Rel) const override;
235 symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override;
236 section_iterator getRelocationSection(DataRefImpl Rel) const;
237 uint64_t getRelocationType(DataRefImpl Rel) const override;
238 void getRelocationTypeName(DataRefImpl Rel,
239 SmallVectorImpl<char> &Result) const override;
240 uint8_t getRelocationLength(DataRefImpl Rel) const;
241
242 // MachO specific.
243 std::error_code getLibraryShortNameByIndex(unsigned Index, StringRef &) const;
244
245 section_iterator getRelocationRelocatedSection(relocation_iterator Rel) const;
246
247 // TODO: Would be useful to have an iterator based version
248 // of the load command interface too.
249
250 basic_symbol_iterator symbol_begin_impl() const override;
251 basic_symbol_iterator symbol_end_impl() const override;
252
253 // MachO specific.
254 basic_symbol_iterator getSymbolByIndex(unsigned Index) const;
255
256 section_iterator section_begin() const override;
257 section_iterator section_end() const override;
258
259 uint8_t getBytesInAddress() const override;
260
261 StringRef getFileFormatName() const override;
262 unsigned getArch() const override;
263 Triple getArch(const char **McpuDefault, Triple *ThumbTriple) const;
264
265 relocation_iterator section_rel_begin(unsigned Index) const;
266 relocation_iterator section_rel_end(unsigned Index) const;
267
268 dice_iterator begin_dices() const;
269 dice_iterator end_dices() const;
270
271 load_command_iterator begin_load_commands() const;
272 load_command_iterator end_load_commands() const;
273 iterator_range<load_command_iterator> load_commands() const;
274
275 /// For use iterating over all exported symbols.
276 iterator_range<export_iterator> exports() const;
277
278 /// For use examining a trie not in a MachOObjectFile.
279 static iterator_range<export_iterator> exports(ArrayRef<uint8_t> Trie);
280
281 /// For use iterating over all rebase table entries.
282 iterator_range<rebase_iterator> rebaseTable() const;
283
284 /// For use examining rebase opcodes not in a MachOObjectFile.
285 static iterator_range<rebase_iterator> rebaseTable(ArrayRef<uint8_t> Opcodes,
286 bool is64);
287
288 /// For use iterating over all bind table entries.
289 iterator_range<bind_iterator> bindTable() const;
290
291 /// For use iterating over all lazy bind table entries.
292 iterator_range<bind_iterator> lazyBindTable() const;
293
294 /// For use iterating over all lazy bind table entries.
295 iterator_range<bind_iterator> weakBindTable() const;
296
297 /// For use examining bind opcodes not in a MachOObjectFile.
298 static iterator_range<bind_iterator> bindTable(ArrayRef<uint8_t> Opcodes,
299 bool is64,
300 MachOBindEntry::Kind);
301
302
303 // In a MachO file, sections have a segment name. This is used in the .o
304 // files. They have a single segment, but this field specifies which segment
305 // a section should be put in in the final object.
306 StringRef getSectionFinalSegmentName(DataRefImpl Sec) const;
307
308 // Names are stored as 16 bytes. These returns the raw 16 bytes without
309 // interpreting them as a C string.
310 ArrayRef<char> getSectionRawName(DataRefImpl Sec) const;
311 ArrayRef<char> getSectionRawFinalSegmentName(DataRefImpl Sec) const;
312
313 // MachO specific Info about relocations.
314 bool isRelocationScattered(const MachO::any_relocation_info &RE) const;
315 unsigned getPlainRelocationSymbolNum(
316 const MachO::any_relocation_info &RE) const;
317 bool getPlainRelocationExternal(const MachO::any_relocation_info &RE) const;
318 bool getScatteredRelocationScattered(
319 const MachO::any_relocation_info &RE) const;
320 uint32_t getScatteredRelocationValue(
321 const MachO::any_relocation_info &RE) const;
322 uint32_t getScatteredRelocationType(
323 const MachO::any_relocation_info &RE) const;
324 unsigned getAnyRelocationAddress(const MachO::any_relocation_info &RE) const;
325 unsigned getAnyRelocationPCRel(const MachO::any_relocation_info &RE) const;
326 unsigned getAnyRelocationLength(const MachO::any_relocation_info &RE) const;
327 unsigned getAnyRelocationType(const MachO::any_relocation_info &RE) const;
328 SectionRef getAnyRelocationSection(const MachO::any_relocation_info &RE) const;
329
330 // MachO specific structures.
331 MachO::section getSection(DataRefImpl DRI) const;
332 MachO::section_64 getSection64(DataRefImpl DRI) const;
333 MachO::section getSection(const LoadCommandInfo &L, unsigned Index) const;
334 MachO::section_64 getSection64(const LoadCommandInfo &L,unsigned Index) const;
335 MachO::nlist getSymbolTableEntry(DataRefImpl DRI) const;
336 MachO::nlist_64 getSymbol64TableEntry(DataRefImpl DRI) const;
337
338 MachO::linkedit_data_command
339 getLinkeditDataLoadCommand(const LoadCommandInfo &L) const;
340 MachO::segment_command
341 getSegmentLoadCommand(const LoadCommandInfo &L) const;
342 MachO::segment_command_64
343 getSegment64LoadCommand(const LoadCommandInfo &L) const;
344 MachO::linker_option_command
345 getLinkerOptionLoadCommand(const LoadCommandInfo &L) const;
346 MachO::version_min_command
347 getVersionMinLoadCommand(const LoadCommandInfo &L) const;
348 MachO::dylib_command
349 getDylibIDLoadCommand(const LoadCommandInfo &L) const;
350 MachO::dyld_info_command
351 getDyldInfoLoadCommand(const LoadCommandInfo &L) const;
352 MachO::dylinker_command
353 getDylinkerCommand(const LoadCommandInfo &L) const;
354 MachO::uuid_command
355 getUuidCommand(const LoadCommandInfo &L) const;
356 MachO::rpath_command
357 getRpathCommand(const LoadCommandInfo &L) const;
358 MachO::source_version_command
359 getSourceVersionCommand(const LoadCommandInfo &L) const;
360 MachO::entry_point_command
361 getEntryPointCommand(const LoadCommandInfo &L) const;
362 MachO::encryption_info_command
363 getEncryptionInfoCommand(const LoadCommandInfo &L) const;
364 MachO::encryption_info_command_64
365 getEncryptionInfoCommand64(const LoadCommandInfo &L) const;
366 MachO::sub_framework_command
367 getSubFrameworkCommand(const LoadCommandInfo &L) const;
368 MachO::sub_umbrella_command
369 getSubUmbrellaCommand(const LoadCommandInfo &L) const;
370 MachO::sub_library_command
371 getSubLibraryCommand(const LoadCommandInfo &L) const;
372 MachO::sub_client_command
373 getSubClientCommand(const LoadCommandInfo &L) const;
374 MachO::routines_command
375 getRoutinesCommand(const LoadCommandInfo &L) const;
376 MachO::routines_command_64
377 getRoutinesCommand64(const LoadCommandInfo &L) const;
378 MachO::thread_command
379 getThreadCommand(const LoadCommandInfo &L) const;
380
381 MachO::any_relocation_info getRelocation(DataRefImpl Rel) const;
382 MachO::data_in_code_entry getDice(DataRefImpl Rel) const;
383 const MachO::mach_header &getHeader() const;
384 const MachO::mach_header_64 &getHeader64() const;
385 uint32_t
386 getIndirectSymbolTableEntry(const MachO::dysymtab_command &DLC,
387 unsigned Index) const;
388 MachO::data_in_code_entry getDataInCodeTableEntry(uint32_t DataOffset,
389 unsigned Index) const;
390 MachO::symtab_command getSymtabLoadCommand() const;
391 MachO::dysymtab_command getDysymtabLoadCommand() const;
392 MachO::linkedit_data_command getDataInCodeLoadCommand() const;
393 MachO::linkedit_data_command getLinkOptHintsLoadCommand() const;
394 ArrayRef<uint8_t> getDyldInfoRebaseOpcodes() const;
395 ArrayRef<uint8_t> getDyldInfoBindOpcodes() const;
396 ArrayRef<uint8_t> getDyldInfoWeakBindOpcodes() const;
397 ArrayRef<uint8_t> getDyldInfoLazyBindOpcodes() const;
398 ArrayRef<uint8_t> getDyldInfoExportsTrie() const;
399 ArrayRef<uint8_t> getUuid() const;
400
401 StringRef getStringTableData() const;
402 bool is64Bit() const;
403 void ReadULEB128s(uint64_t Index, SmallVectorImpl<uint64_t> &Out) const;
404
405 static StringRef guessLibraryShortName(StringRef Name, bool &isFramework,
406 StringRef &Suffix);
407
408 static Triple::ArchType getArch(uint32_t CPUType);
409 static Triple getArch(uint32_t CPUType, uint32_t CPUSubType,
410 const char **McpuDefault = nullptr);
411 static Triple getThumbArch(uint32_t CPUType, uint32_t CPUSubType,
412 const char **McpuDefault = nullptr);
413 static Triple getArch(uint32_t CPUType, uint32_t CPUSubType,
414 const char **McpuDefault, Triple *ThumbTriple);
415 static bool isValidArch(StringRef ArchFlag);
416 static Triple getHostArch();
417
418 bool isRelocatableObject() const override;
419
hasPageZeroSegment()420 bool hasPageZeroSegment() const { return HasPageZeroSegment; }
421
classof(const Binary * v)422 static bool classof(const Binary *v) {
423 return v->isMachO();
424 }
425
426 private:
427 uint64_t getSymbolValueImpl(DataRefImpl Symb) const override;
428
429 union {
430 MachO::mach_header_64 Header64;
431 MachO::mach_header Header;
432 };
433 typedef SmallVector<const char*, 1> SectionList;
434 SectionList Sections;
435 typedef SmallVector<const char*, 1> LibraryList;
436 LibraryList Libraries;
437 LoadCommandList LoadCommands;
438 typedef SmallVector<StringRef, 1> LibraryShortName;
439 mutable LibraryShortName LibrariesShortNames;
440 const char *SymtabLoadCmd;
441 const char *DysymtabLoadCmd;
442 const char *DataInCodeLoadCmd;
443 const char *LinkOptHintsLoadCmd;
444 const char *DyldInfoLoadCmd;
445 const char *UuidLoadCmd;
446 bool HasPageZeroSegment;
447 };
448
449 /// DiceRef
DiceRef(DataRefImpl DiceP,const ObjectFile * Owner)450 inline DiceRef::DiceRef(DataRefImpl DiceP, const ObjectFile *Owner)
451 : DicePimpl(DiceP) , OwningObject(Owner) {}
452
453 inline bool DiceRef::operator==(const DiceRef &Other) const {
454 return DicePimpl == Other.DicePimpl;
455 }
456
457 inline bool DiceRef::operator<(const DiceRef &Other) const {
458 return DicePimpl < Other.DicePimpl;
459 }
460
moveNext()461 inline void DiceRef::moveNext() {
462 const MachO::data_in_code_entry *P =
463 reinterpret_cast<const MachO::data_in_code_entry *>(DicePimpl.p);
464 DicePimpl.p = reinterpret_cast<uintptr_t>(P + 1);
465 }
466
467 // Since a Mach-O data in code reference, a DiceRef, can only be created when
468 // the OwningObject ObjectFile is a MachOObjectFile a static_cast<> is used for
469 // the methods that get the values of the fields of the reference.
470
getOffset(uint32_t & Result)471 inline std::error_code DiceRef::getOffset(uint32_t &Result) const {
472 const MachOObjectFile *MachOOF =
473 static_cast<const MachOObjectFile *>(OwningObject);
474 MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl);
475 Result = Dice.offset;
476 return std::error_code();
477 }
478
getLength(uint16_t & Result)479 inline std::error_code DiceRef::getLength(uint16_t &Result) const {
480 const MachOObjectFile *MachOOF =
481 static_cast<const MachOObjectFile *>(OwningObject);
482 MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl);
483 Result = Dice.length;
484 return std::error_code();
485 }
486
getKind(uint16_t & Result)487 inline std::error_code DiceRef::getKind(uint16_t &Result) const {
488 const MachOObjectFile *MachOOF =
489 static_cast<const MachOObjectFile *>(OwningObject);
490 MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl);
491 Result = Dice.kind;
492 return std::error_code();
493 }
494
getRawDataRefImpl()495 inline DataRefImpl DiceRef::getRawDataRefImpl() const {
496 return DicePimpl;
497 }
498
getObjectFile()499 inline const ObjectFile *DiceRef::getObjectFile() const {
500 return OwningObject;
501 }
502
503 }
504 }
505
506 #endif
507
508