blob: ca9512f21706d96b8a087f4aaeeaf19bcd11e57b [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===- MachO.h - MachO object file implementation ---------------*- C++ -*-===//
2//
Andrew Walbran16937d02019-10-22 13:54:20 +01003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01006//
7//===----------------------------------------------------------------------===//
8//
9// This file declares the MachOObjectFile class, which implement the ObjectFile
10// interface for MachO files.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_OBJECT_MACHO_H
15#define LLVM_OBJECT_MACHO_H
16
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/SmallString.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/StringExtras.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/ADT/Triple.h"
23#include "llvm/ADT/iterator_range.h"
24#include "llvm/BinaryFormat/MachO.h"
25#include "llvm/MC/SubtargetFeature.h"
26#include "llvm/Object/Binary.h"
27#include "llvm/Object/ObjectFile.h"
28#include "llvm/Object/SymbolicFile.h"
29#include "llvm/Support/Error.h"
30#include "llvm/Support/Format.h"
31#include "llvm/Support/MemoryBuffer.h"
32#include "llvm/Support/raw_ostream.h"
33#include <cstdint>
34#include <memory>
35#include <string>
36#include <system_error>
37
38namespace llvm {
39namespace object {
40
41/// DiceRef - This is a value type class that represents a single
42/// data in code entry in the table in a Mach-O object file.
43class DiceRef {
44 DataRefImpl DicePimpl;
45 const ObjectFile *OwningObject = nullptr;
46
47public:
48 DiceRef() = default;
49 DiceRef(DataRefImpl DiceP, const ObjectFile *Owner);
50
51 bool operator==(const DiceRef &Other) const;
52 bool operator<(const DiceRef &Other) const;
53
54 void moveNext();
55
56 std::error_code getOffset(uint32_t &Result) const;
57 std::error_code getLength(uint16_t &Result) const;
58 std::error_code getKind(uint16_t &Result) const;
59
60 DataRefImpl getRawDataRefImpl() const;
61 const ObjectFile *getObjectFile() const;
62};
63using dice_iterator = content_iterator<DiceRef>;
64
65/// ExportEntry encapsulates the current-state-of-the-walk used when doing a
66/// non-recursive walk of the trie data structure. This allows you to iterate
67/// across all exported symbols using:
68/// Error Err;
69/// for (const llvm::object::ExportEntry &AnExport : Obj->exports(&Err)) {
70/// }
71/// if (Err) { report error ...
72class ExportEntry {
73public:
74 ExportEntry(Error *Err, const MachOObjectFile *O, ArrayRef<uint8_t> Trie);
75
76 StringRef name() const;
77 uint64_t flags() const;
78 uint64_t address() const;
79 uint64_t other() const;
80 StringRef otherName() const;
81 uint32_t nodeOffset() const;
82
83 bool operator==(const ExportEntry &) const;
84
85 void moveNext();
86
87private:
88 friend class MachOObjectFile;
89
90 void moveToFirst();
91 void moveToEnd();
92 uint64_t readULEB128(const uint8_t *&p, const char **error);
93 void pushDownUntilBottom();
94 void pushNode(uint64_t Offset);
95
96 // Represents a node in the mach-o exports trie.
97 struct NodeState {
98 NodeState(const uint8_t *Ptr);
99
100 const uint8_t *Start;
101 const uint8_t *Current;
102 uint64_t Flags = 0;
103 uint64_t Address = 0;
104 uint64_t Other = 0;
105 const char *ImportName = nullptr;
106 unsigned ChildCount = 0;
107 unsigned NextChildIndex = 0;
108 unsigned ParentStringLength = 0;
109 bool IsExportNode = false;
110 };
111 using NodeList = SmallVector<NodeState, 16>;
112 using node_iterator = NodeList::const_iterator;
113
114 Error *E;
115 const MachOObjectFile *O;
116 ArrayRef<uint8_t> Trie;
117 SmallString<256> CumulativeString;
118 NodeList Stack;
119 bool Done = false;
120
121 iterator_range<node_iterator> nodes() const {
122 return make_range(Stack.begin(), Stack.end());
123 }
124};
125using export_iterator = content_iterator<ExportEntry>;
126
127// Segment info so SegIndex/SegOffset pairs in a Mach-O Bind or Rebase entry
128// can be checked and translated. Only the SegIndex/SegOffset pairs from
129// checked entries are to be used with the segmentName(), sectionName() and
130// address() methods below.
131class BindRebaseSegInfo {
132public:
133 BindRebaseSegInfo(const MachOObjectFile *Obj);
134
135 // Used to check a Mach-O Bind or Rebase entry for errors when iterating.
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100136 const char* checkSegAndOffsets(int32_t SegIndex, uint64_t SegOffset,
137 uint8_t PointerSize, uint32_t Count=1,
138 uint32_t Skip=0);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100139 // Used with valid SegIndex/SegOffset values from checked entries.
140 StringRef segmentName(int32_t SegIndex);
141 StringRef sectionName(int32_t SegIndex, uint64_t SegOffset);
142 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
143
144private:
145 struct SectionInfo {
146 uint64_t Address;
147 uint64_t Size;
148 StringRef SectionName;
149 StringRef SegmentName;
150 uint64_t OffsetInSegment;
151 uint64_t SegmentStartAddress;
152 int32_t SegmentIndex;
153 };
154 const SectionInfo &findSection(int32_t SegIndex, uint64_t SegOffset);
155
156 SmallVector<SectionInfo, 32> Sections;
157 int32_t MaxSegIndex;
158};
159
160/// MachORebaseEntry encapsulates the current state in the decompression of
161/// rebasing opcodes. This allows you to iterate through the compressed table of
162/// rebasing using:
163/// Error Err;
164/// for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable(&Err)) {
165/// }
166/// if (Err) { report error ...
167class MachORebaseEntry {
168public:
169 MachORebaseEntry(Error *Err, const MachOObjectFile *O,
170 ArrayRef<uint8_t> opcodes, bool is64Bit);
171
172 int32_t segmentIndex() const;
173 uint64_t segmentOffset() const;
174 StringRef typeName() const;
175 StringRef segmentName() const;
176 StringRef sectionName() const;
177 uint64_t address() const;
178
179 bool operator==(const MachORebaseEntry &) const;
180
181 void moveNext();
182
183private:
184 friend class MachOObjectFile;
185
186 void moveToFirst();
187 void moveToEnd();
188 uint64_t readULEB128(const char **error);
189
190 Error *E;
191 const MachOObjectFile *O;
192 ArrayRef<uint8_t> Opcodes;
193 const uint8_t *Ptr;
194 uint64_t SegmentOffset = 0;
195 int32_t SegmentIndex = -1;
196 uint64_t RemainingLoopCount = 0;
197 uint64_t AdvanceAmount = 0;
198 uint8_t RebaseType = 0;
199 uint8_t PointerSize;
200 bool Done = false;
201};
202using rebase_iterator = content_iterator<MachORebaseEntry>;
203
204/// MachOBindEntry encapsulates the current state in the decompression of
205/// binding opcodes. This allows you to iterate through the compressed table of
206/// bindings using:
207/// Error Err;
208/// for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable(&Err)) {
209/// }
210/// if (Err) { report error ...
211class MachOBindEntry {
212public:
213 enum class Kind { Regular, Lazy, Weak };
214
215 MachOBindEntry(Error *Err, const MachOObjectFile *O,
216 ArrayRef<uint8_t> Opcodes, bool is64Bit, MachOBindEntry::Kind);
217
218 int32_t segmentIndex() const;
219 uint64_t segmentOffset() const;
220 StringRef typeName() const;
221 StringRef symbolName() const;
222 uint32_t flags() const;
223 int64_t addend() const;
224 int ordinal() const;
225
226 StringRef segmentName() const;
227 StringRef sectionName() const;
228 uint64_t address() const;
229
230 bool operator==(const MachOBindEntry &) const;
231
232 void moveNext();
233
234private:
235 friend class MachOObjectFile;
236
237 void moveToFirst();
238 void moveToEnd();
239 uint64_t readULEB128(const char **error);
240 int64_t readSLEB128(const char **error);
241
242 Error *E;
243 const MachOObjectFile *O;
244 ArrayRef<uint8_t> Opcodes;
245 const uint8_t *Ptr;
246 uint64_t SegmentOffset = 0;
247 int32_t SegmentIndex = -1;
248 StringRef SymbolName;
249 bool LibraryOrdinalSet = false;
250 int Ordinal = 0;
251 uint32_t Flags = 0;
252 int64_t Addend = 0;
253 uint64_t RemainingLoopCount = 0;
254 uint64_t AdvanceAmount = 0;
255 uint8_t BindType = 0;
256 uint8_t PointerSize;
257 Kind TableKind;
258 bool Done = false;
259};
260using bind_iterator = content_iterator<MachOBindEntry>;
261
262class MachOObjectFile : public ObjectFile {
263public:
264 struct LoadCommandInfo {
265 const char *Ptr; // Where in memory the load command is.
266 MachO::load_command C; // The command itself.
267 };
268 using LoadCommandList = SmallVector<LoadCommandInfo, 4>;
269 using load_command_iterator = LoadCommandList::const_iterator;
270
271 static Expected<std::unique_ptr<MachOObjectFile>>
272 create(MemoryBufferRef Object, bool IsLittleEndian, bool Is64Bits,
273 uint32_t UniversalCputype = 0, uint32_t UniversalIndex = 0);
274
275 void moveSymbolNext(DataRefImpl &Symb) const override;
276
277 uint64_t getNValue(DataRefImpl Sym) const;
278 Expected<StringRef> getSymbolName(DataRefImpl Symb) const override;
279
280 // MachO specific.
281 Error checkSymbolTable() const;
282
283 std::error_code getIndirectName(DataRefImpl Symb, StringRef &Res) const;
284 unsigned getSectionType(SectionRef Sec) const;
285
286 Expected<uint64_t> getSymbolAddress(DataRefImpl Symb) const override;
287 uint32_t getSymbolAlignment(DataRefImpl Symb) const override;
288 uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override;
289 Expected<SymbolRef::Type> getSymbolType(DataRefImpl Symb) const override;
290 uint32_t getSymbolFlags(DataRefImpl Symb) const override;
291 Expected<section_iterator> getSymbolSection(DataRefImpl Symb) const override;
292 unsigned getSymbolSectionID(SymbolRef Symb) const;
293 unsigned getSectionID(SectionRef Sec) const;
294
295 void moveSectionNext(DataRefImpl &Sec) const override;
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100296 Expected<StringRef> getSectionName(DataRefImpl Sec) const override;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100297 uint64_t getSectionAddress(DataRefImpl Sec) const override;
298 uint64_t getSectionIndex(DataRefImpl Sec) const override;
299 uint64_t getSectionSize(DataRefImpl Sec) const override;
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100300 Expected<ArrayRef<uint8_t>>
301 getSectionContents(DataRefImpl Sec) const override;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100302 uint64_t getSectionAlignment(DataRefImpl Sec) const override;
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100303 Expected<SectionRef> getSection(unsigned SectionIndex) const;
304 Expected<SectionRef> getSection(StringRef SectionName) const;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100305 bool isSectionCompressed(DataRefImpl Sec) const override;
306 bool isSectionText(DataRefImpl Sec) const override;
307 bool isSectionData(DataRefImpl Sec) const override;
308 bool isSectionBSS(DataRefImpl Sec) const override;
309 bool isSectionVirtual(DataRefImpl Sec) const override;
310 bool isSectionBitcode(DataRefImpl Sec) const override;
311
312 /// When dsymutil generates the companion file, it strips all unnecessary
313 /// sections (e.g. everything in the _TEXT segment) by omitting their body
314 /// and setting the offset in their corresponding load command to zero.
315 ///
316 /// While the load command itself is valid, reading the section corresponds
317 /// to reading the number of bytes specified in the load command, starting
318 /// from offset 0 (i.e. the Mach-O header at the beginning of the file).
319 bool isSectionStripped(DataRefImpl Sec) const override;
320
321 relocation_iterator section_rel_begin(DataRefImpl Sec) const override;
322 relocation_iterator section_rel_end(DataRefImpl Sec) const override;
323
324 relocation_iterator extrel_begin() const;
325 relocation_iterator extrel_end() const;
326 iterator_range<relocation_iterator> external_relocations() const {
327 return make_range(extrel_begin(), extrel_end());
328 }
329
330 relocation_iterator locrel_begin() const;
331 relocation_iterator locrel_end() const;
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100332
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100333 void moveRelocationNext(DataRefImpl &Rel) const override;
334 uint64_t getRelocationOffset(DataRefImpl Rel) const override;
335 symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override;
336 section_iterator getRelocationSection(DataRefImpl Rel) const;
337 uint64_t getRelocationType(DataRefImpl Rel) const override;
338 void getRelocationTypeName(DataRefImpl Rel,
339 SmallVectorImpl<char> &Result) const override;
340 uint8_t getRelocationLength(DataRefImpl Rel) const;
341
342 // MachO specific.
343 std::error_code getLibraryShortNameByIndex(unsigned Index, StringRef &) const;
344 uint32_t getLibraryCount() const;
345
346 section_iterator getRelocationRelocatedSection(relocation_iterator Rel) const;
347
348 // TODO: Would be useful to have an iterator based version
349 // of the load command interface too.
350
351 basic_symbol_iterator symbol_begin() const override;
352 basic_symbol_iterator symbol_end() const override;
353
354 // MachO specific.
Andrew Walbran16937d02019-10-22 13:54:20 +0100355 symbol_iterator getSymbolByIndex(unsigned Index) const;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100356 uint64_t getSymbolIndex(DataRefImpl Symb) const;
357
358 section_iterator section_begin() const override;
359 section_iterator section_end() const override;
360
361 uint8_t getBytesInAddress() const override;
362
363 StringRef getFileFormatName() const override;
364 Triple::ArchType getArch() const override;
365 SubtargetFeatures getFeatures() const override { return SubtargetFeatures(); }
366 Triple getArchTriple(const char **McpuDefault = nullptr) const;
367
368 relocation_iterator section_rel_begin(unsigned Index) const;
369 relocation_iterator section_rel_end(unsigned Index) const;
370
371 dice_iterator begin_dices() const;
372 dice_iterator end_dices() const;
373
374 load_command_iterator begin_load_commands() const;
375 load_command_iterator end_load_commands() const;
376 iterator_range<load_command_iterator> load_commands() const;
377
378 /// For use iterating over all exported symbols.
379 iterator_range<export_iterator> exports(Error &Err) const;
380
381 /// For use examining a trie not in a MachOObjectFile.
382 static iterator_range<export_iterator> exports(Error &Err,
383 ArrayRef<uint8_t> Trie,
384 const MachOObjectFile *O =
385 nullptr);
386
387 /// For use iterating over all rebase table entries.
388 iterator_range<rebase_iterator> rebaseTable(Error &Err);
389
390 /// For use examining rebase opcodes in a MachOObjectFile.
391 static iterator_range<rebase_iterator> rebaseTable(Error &Err,
392 MachOObjectFile *O,
393 ArrayRef<uint8_t> Opcodes,
394 bool is64);
395
396 /// For use iterating over all bind table entries.
397 iterator_range<bind_iterator> bindTable(Error &Err);
398
399 /// For use iterating over all lazy bind table entries.
400 iterator_range<bind_iterator> lazyBindTable(Error &Err);
401
402 /// For use iterating over all weak bind table entries.
403 iterator_range<bind_iterator> weakBindTable(Error &Err);
404
405 /// For use examining bind opcodes in a MachOObjectFile.
406 static iterator_range<bind_iterator> bindTable(Error &Err,
407 MachOObjectFile *O,
408 ArrayRef<uint8_t> Opcodes,
409 bool is64,
410 MachOBindEntry::Kind);
411
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100412 // Given a SegIndex, SegOffset, and PointerSize, verify a valid section exists
413 // that fully contains a pointer at that location. Multiple fixups in a bind
414 // (such as with the BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB opcode) can
415 // be tested via the Count and Skip parameters.
416 //
417 // This is used by MachOBindEntry::moveNext() to validate a MachOBindEntry.
418 const char *BindEntryCheckSegAndOffsets(int32_t SegIndex, uint64_t SegOffset,
419 uint8_t PointerSize, uint32_t Count=1,
420 uint32_t Skip=0) const {
421 return BindRebaseSectionTable->checkSegAndOffsets(SegIndex, SegOffset,
422 PointerSize, Count, Skip);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100423 }
424
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100425 // Given a SegIndex, SegOffset, and PointerSize, verify a valid section exists
426 // that fully contains a pointer at that location. Multiple fixups in a rebase
427 // (such as with the REBASE_OPCODE_DO_*_TIMES* opcodes) can be tested via the
428 // Count and Skip parameters.
429 //
430 // This is used by MachORebaseEntry::moveNext() to validate a MachORebaseEntry
431 const char *RebaseEntryCheckSegAndOffsets(int32_t SegIndex,
432 uint64_t SegOffset,
433 uint8_t PointerSize,
434 uint32_t Count=1,
435 uint32_t Skip=0) const {
436 return BindRebaseSectionTable->checkSegAndOffsets(SegIndex, SegOffset,
437 PointerSize, Count, Skip);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100438 }
439
440 /// For use with the SegIndex of a checked Mach-O Bind or Rebase entry to
441 /// get the segment name.
442 StringRef BindRebaseSegmentName(int32_t SegIndex) const {
443 return BindRebaseSectionTable->segmentName(SegIndex);
444 }
445
446 /// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or
447 /// Rebase entry to get the section name.
448 StringRef BindRebaseSectionName(uint32_t SegIndex, uint64_t SegOffset) const {
449 return BindRebaseSectionTable->sectionName(SegIndex, SegOffset);
450 }
451
452 /// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or
453 /// Rebase entry to get the address.
454 uint64_t BindRebaseAddress(uint32_t SegIndex, uint64_t SegOffset) const {
455 return BindRebaseSectionTable->address(SegIndex, SegOffset);
456 }
457
458 // In a MachO file, sections have a segment name. This is used in the .o
459 // files. They have a single segment, but this field specifies which segment
460 // a section should be put in the final object.
461 StringRef getSectionFinalSegmentName(DataRefImpl Sec) const;
462
463 // Names are stored as 16 bytes. These returns the raw 16 bytes without
464 // interpreting them as a C string.
465 ArrayRef<char> getSectionRawName(DataRefImpl Sec) const;
466 ArrayRef<char> getSectionRawFinalSegmentName(DataRefImpl Sec) const;
467
468 // MachO specific Info about relocations.
469 bool isRelocationScattered(const MachO::any_relocation_info &RE) const;
470 unsigned getPlainRelocationSymbolNum(
471 const MachO::any_relocation_info &RE) const;
472 bool getPlainRelocationExternal(const MachO::any_relocation_info &RE) const;
473 bool getScatteredRelocationScattered(
474 const MachO::any_relocation_info &RE) const;
475 uint32_t getScatteredRelocationValue(
476 const MachO::any_relocation_info &RE) const;
477 uint32_t getScatteredRelocationType(
478 const MachO::any_relocation_info &RE) const;
479 unsigned getAnyRelocationAddress(const MachO::any_relocation_info &RE) const;
480 unsigned getAnyRelocationPCRel(const MachO::any_relocation_info &RE) const;
481 unsigned getAnyRelocationLength(const MachO::any_relocation_info &RE) const;
482 unsigned getAnyRelocationType(const MachO::any_relocation_info &RE) const;
483 SectionRef getAnyRelocationSection(const MachO::any_relocation_info &RE) const;
484
485 // MachO specific structures.
486 MachO::section getSection(DataRefImpl DRI) const;
487 MachO::section_64 getSection64(DataRefImpl DRI) const;
488 MachO::section getSection(const LoadCommandInfo &L, unsigned Index) const;
489 MachO::section_64 getSection64(const LoadCommandInfo &L,unsigned Index) const;
490 MachO::nlist getSymbolTableEntry(DataRefImpl DRI) const;
491 MachO::nlist_64 getSymbol64TableEntry(DataRefImpl DRI) const;
492
493 MachO::linkedit_data_command
494 getLinkeditDataLoadCommand(const LoadCommandInfo &L) const;
495 MachO::segment_command
496 getSegmentLoadCommand(const LoadCommandInfo &L) const;
497 MachO::segment_command_64
498 getSegment64LoadCommand(const LoadCommandInfo &L) const;
499 MachO::linker_option_command
500 getLinkerOptionLoadCommand(const LoadCommandInfo &L) const;
501 MachO::version_min_command
502 getVersionMinLoadCommand(const LoadCommandInfo &L) const;
503 MachO::note_command
504 getNoteLoadCommand(const LoadCommandInfo &L) const;
505 MachO::build_version_command
506 getBuildVersionLoadCommand(const LoadCommandInfo &L) const;
507 MachO::build_tool_version
508 getBuildToolVersion(unsigned index) const;
509 MachO::dylib_command
510 getDylibIDLoadCommand(const LoadCommandInfo &L) const;
511 MachO::dyld_info_command
512 getDyldInfoLoadCommand(const LoadCommandInfo &L) const;
513 MachO::dylinker_command
514 getDylinkerCommand(const LoadCommandInfo &L) const;
515 MachO::uuid_command
516 getUuidCommand(const LoadCommandInfo &L) const;
517 MachO::rpath_command
518 getRpathCommand(const LoadCommandInfo &L) const;
519 MachO::source_version_command
520 getSourceVersionCommand(const LoadCommandInfo &L) const;
521 MachO::entry_point_command
522 getEntryPointCommand(const LoadCommandInfo &L) const;
523 MachO::encryption_info_command
524 getEncryptionInfoCommand(const LoadCommandInfo &L) const;
525 MachO::encryption_info_command_64
526 getEncryptionInfoCommand64(const LoadCommandInfo &L) const;
527 MachO::sub_framework_command
528 getSubFrameworkCommand(const LoadCommandInfo &L) const;
529 MachO::sub_umbrella_command
530 getSubUmbrellaCommand(const LoadCommandInfo &L) const;
531 MachO::sub_library_command
532 getSubLibraryCommand(const LoadCommandInfo &L) const;
533 MachO::sub_client_command
534 getSubClientCommand(const LoadCommandInfo &L) const;
535 MachO::routines_command
536 getRoutinesCommand(const LoadCommandInfo &L) const;
537 MachO::routines_command_64
538 getRoutinesCommand64(const LoadCommandInfo &L) const;
539 MachO::thread_command
540 getThreadCommand(const LoadCommandInfo &L) const;
541
542 MachO::any_relocation_info getRelocation(DataRefImpl Rel) const;
543 MachO::data_in_code_entry getDice(DataRefImpl Rel) const;
544 const MachO::mach_header &getHeader() const;
545 const MachO::mach_header_64 &getHeader64() const;
546 uint32_t
547 getIndirectSymbolTableEntry(const MachO::dysymtab_command &DLC,
548 unsigned Index) const;
549 MachO::data_in_code_entry getDataInCodeTableEntry(uint32_t DataOffset,
550 unsigned Index) const;
551 MachO::symtab_command getSymtabLoadCommand() const;
552 MachO::dysymtab_command getDysymtabLoadCommand() const;
553 MachO::linkedit_data_command getDataInCodeLoadCommand() const;
554 MachO::linkedit_data_command getLinkOptHintsLoadCommand() const;
555 ArrayRef<uint8_t> getDyldInfoRebaseOpcodes() const;
556 ArrayRef<uint8_t> getDyldInfoBindOpcodes() const;
557 ArrayRef<uint8_t> getDyldInfoWeakBindOpcodes() const;
558 ArrayRef<uint8_t> getDyldInfoLazyBindOpcodes() const;
559 ArrayRef<uint8_t> getDyldInfoExportsTrie() const;
560 ArrayRef<uint8_t> getUuid() const;
561
562 StringRef getStringTableData() const;
563 bool is64Bit() const;
564 void ReadULEB128s(uint64_t Index, SmallVectorImpl<uint64_t> &Out) const;
565
566 static StringRef guessLibraryShortName(StringRef Name, bool &isFramework,
567 StringRef &Suffix);
568
569 static Triple::ArchType getArch(uint32_t CPUType);
570 static Triple getArchTriple(uint32_t CPUType, uint32_t CPUSubType,
571 const char **McpuDefault = nullptr,
572 const char **ArchFlag = nullptr);
573 static bool isValidArch(StringRef ArchFlag);
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100574 static ArrayRef<StringRef> getValidArchs();
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100575 static Triple getHostArch();
576
577 bool isRelocatableObject() const override;
578
579 StringRef mapDebugSectionName(StringRef Name) const override;
580
581 bool hasPageZeroSegment() const { return HasPageZeroSegment; }
582
583 static bool classof(const Binary *v) {
584 return v->isMachO();
585 }
586
587 static uint32_t
588 getVersionMinMajor(MachO::version_min_command &C, bool SDK) {
589 uint32_t VersionOrSDK = (SDK) ? C.sdk : C.version;
590 return (VersionOrSDK >> 16) & 0xffff;
591 }
592
593 static uint32_t
594 getVersionMinMinor(MachO::version_min_command &C, bool SDK) {
595 uint32_t VersionOrSDK = (SDK) ? C.sdk : C.version;
596 return (VersionOrSDK >> 8) & 0xff;
597 }
598
599 static uint32_t
600 getVersionMinUpdate(MachO::version_min_command &C, bool SDK) {
601 uint32_t VersionOrSDK = (SDK) ? C.sdk : C.version;
602 return VersionOrSDK & 0xff;
603 }
604
605 static std::string getBuildPlatform(uint32_t platform) {
606 switch (platform) {
607 case MachO::PLATFORM_MACOS: return "macos";
608 case MachO::PLATFORM_IOS: return "ios";
609 case MachO::PLATFORM_TVOS: return "tvos";
610 case MachO::PLATFORM_WATCHOS: return "watchos";
611 case MachO::PLATFORM_BRIDGEOS: return "bridgeos";
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100612 case MachO::PLATFORM_MACCATALYST: return "macCatalyst";
Andrew Walbran16937d02019-10-22 13:54:20 +0100613 case MachO::PLATFORM_IOSSIMULATOR: return "iossimulator";
614 case MachO::PLATFORM_TVOSSIMULATOR: return "tvossimulator";
615 case MachO::PLATFORM_WATCHOSSIMULATOR: return "watchossimulator";
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100616 default:
617 std::string ret;
618 raw_string_ostream ss(ret);
619 ss << format_hex(platform, 8, true);
620 return ss.str();
621 }
622 }
623
624 static std::string getBuildTool(uint32_t tools) {
625 switch (tools) {
626 case MachO::TOOL_CLANG: return "clang";
627 case MachO::TOOL_SWIFT: return "swift";
628 case MachO::TOOL_LD: return "ld";
629 default:
630 std::string ret;
631 raw_string_ostream ss(ret);
632 ss << format_hex(tools, 8, true);
633 return ss.str();
634 }
635 }
636
637 static std::string getVersionString(uint32_t version) {
638 uint32_t major = (version >> 16) & 0xffff;
639 uint32_t minor = (version >> 8) & 0xff;
640 uint32_t update = version & 0xff;
641
642 SmallString<32> Version;
643 Version = utostr(major) + "." + utostr(minor);
644 if (update != 0)
645 Version += "." + utostr(update);
646 return Version.str();
647 }
648
649private:
650 MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian, bool Is64Bits,
651 Error &Err, uint32_t UniversalCputype = 0,
652 uint32_t UniversalIndex = 0);
653
654 uint64_t getSymbolValueImpl(DataRefImpl Symb) const override;
655
656 union {
657 MachO::mach_header_64 Header64;
658 MachO::mach_header Header;
659 };
660 using SectionList = SmallVector<const char*, 1>;
661 SectionList Sections;
662 using LibraryList = SmallVector<const char*, 1>;
663 LibraryList Libraries;
664 LoadCommandList LoadCommands;
665 using LibraryShortName = SmallVector<StringRef, 1>;
666 using BuildToolList = SmallVector<const char*, 1>;
667 BuildToolList BuildTools;
668 mutable LibraryShortName LibrariesShortNames;
669 std::unique_ptr<BindRebaseSegInfo> BindRebaseSectionTable;
670 const char *SymtabLoadCmd = nullptr;
671 const char *DysymtabLoadCmd = nullptr;
672 const char *DataInCodeLoadCmd = nullptr;
673 const char *LinkOptHintsLoadCmd = nullptr;
674 const char *DyldInfoLoadCmd = nullptr;
675 const char *UuidLoadCmd = nullptr;
676 bool HasPageZeroSegment = false;
677};
678
679/// DiceRef
680inline DiceRef::DiceRef(DataRefImpl DiceP, const ObjectFile *Owner)
681 : DicePimpl(DiceP) , OwningObject(Owner) {}
682
683inline bool DiceRef::operator==(const DiceRef &Other) const {
684 return DicePimpl == Other.DicePimpl;
685}
686
687inline bool DiceRef::operator<(const DiceRef &Other) const {
688 return DicePimpl < Other.DicePimpl;
689}
690
691inline void DiceRef::moveNext() {
692 const MachO::data_in_code_entry *P =
693 reinterpret_cast<const MachO::data_in_code_entry *>(DicePimpl.p);
694 DicePimpl.p = reinterpret_cast<uintptr_t>(P + 1);
695}
696
697// Since a Mach-O data in code reference, a DiceRef, can only be created when
698// the OwningObject ObjectFile is a MachOObjectFile a static_cast<> is used for
699// the methods that get the values of the fields of the reference.
700
701inline std::error_code DiceRef::getOffset(uint32_t &Result) const {
702 const MachOObjectFile *MachOOF =
703 static_cast<const MachOObjectFile *>(OwningObject);
704 MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl);
705 Result = Dice.offset;
706 return std::error_code();
707}
708
709inline std::error_code DiceRef::getLength(uint16_t &Result) const {
710 const MachOObjectFile *MachOOF =
711 static_cast<const MachOObjectFile *>(OwningObject);
712 MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl);
713 Result = Dice.length;
714 return std::error_code();
715}
716
717inline std::error_code DiceRef::getKind(uint16_t &Result) const {
718 const MachOObjectFile *MachOOF =
719 static_cast<const MachOObjectFile *>(OwningObject);
720 MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl);
721 Result = Dice.kind;
722 return std::error_code();
723}
724
725inline DataRefImpl DiceRef::getRawDataRefImpl() const {
726 return DicePimpl;
727}
728
729inline const ObjectFile *DiceRef::getObjectFile() const {
730 return OwningObject;
731}
732
733} // end namespace object
734} // end namespace llvm
735
736#endif // LLVM_OBJECT_MACHO_H