1//===------ macho2yaml.cpp - obj2yaml conversion tool -----------*- C++ -*-===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8
9#include "obj2yaml.h"
10#include "llvm/DebugInfo/DWARF/DWARFContext.h"
11#include "llvm/Object/MachOUniversal.h"
12#include "llvm/ObjectYAML/DWARFYAML.h"
13#include "llvm/ObjectYAML/ObjectYAML.h"
14#include "llvm/Support/Errc.h"
15#include "llvm/Support/Error.h"
16#include "llvm/Support/ErrorHandling.h"
17#include "llvm/Support/LEB128.h"
18
19#include <string.h> // for memcpy
20
21using namespace llvm;
22
23class MachODumper {
24
25 template <typename StructType>
26 Expected<const char *> processLoadCommandData(
27 MachOYAML::LoadCommand &LC,
28 const llvm::object::MachOObjectFile::LoadCommandInfo &LoadCmd,
29 MachOYAML::Object &Y);
30
31 const object::MachOObjectFile &Obj;
32 std::unique_ptr<DWARFContext> DWARFCtx;
33 unsigned RawSegment;
34 void dumpHeader(std::unique_ptr<MachOYAML::Object> &Y);
35 Error dumpLoadCommands(std::unique_ptr<MachOYAML::Object> &Y);
36 void dumpLinkEdit(std::unique_ptr<MachOYAML::Object> &Y);
37 void dumpRebaseOpcodes(std::unique_ptr<MachOYAML::Object> &Y);
38 void dumpFunctionStarts(std::unique_ptr<MachOYAML::Object> &Y);
39 void dumpBindOpcodes(std::vector<MachOYAML::BindOpcode> &BindOpcodes,
40 ArrayRef<uint8_t> OpcodeBuffer, bool Lazy = false);
41 void dumpExportTrie(std::unique_ptr<MachOYAML::Object> &Y);
42 void dumpSymbols(std::unique_ptr<MachOYAML::Object> &Y);
43 void dumpIndirectSymbols(std::unique_ptr<MachOYAML::Object> &Y);
44 void dumpChainedFixups(std::unique_ptr<MachOYAML::Object> &Y);
45 void dumpDataInCode(std::unique_ptr<MachOYAML::Object> &Y);
46
47 template <typename SectionType>
48 Expected<MachOYAML::Section> constructSectionCommon(SectionType Sec,
49 size_t SecIndex);
50 template <typename SectionType>
51 Expected<MachOYAML::Section> constructSection(SectionType Sec,
52 size_t SecIndex);
53 template <typename SectionType, typename SegmentType>
54 Expected<const char *>
55 extractSections(const llvm::object::MachOObjectFile::LoadCommandInfo &LoadCmd,
56 std::vector<MachOYAML::Section> &Sections,
57 MachOYAML::Object &Y);
58
59public:
60 MachODumper(const object::MachOObjectFile &O,
61 std::unique_ptr<DWARFContext> DCtx, unsigned RawSegments)
62 : Obj(O), DWARFCtx(std::move(DCtx)), RawSegment(RawSegments) {}
63 Expected<std::unique_ptr<MachOYAML::Object>> dump();
64};
65
66#define HANDLE_LOAD_COMMAND(LCName, LCValue, LCStruct) \
67 case MachO::LCName: \
68 memcpy((void *)&(LC.Data.LCStruct##_data), LoadCmd.Ptr, \
69 sizeof(MachO::LCStruct)); \
70 if (Obj.isLittleEndian() != sys::IsLittleEndianHost) \
71 MachO::swapStruct(LC.Data.LCStruct##_data); \
72 if (Expected<const char *> ExpectedEndPtr = \
73 processLoadCommandData<MachO::LCStruct>(LC, LoadCmd, *Y.get())) \
74 EndPtr = *ExpectedEndPtr; \
75 else \
76 return ExpectedEndPtr.takeError(); \
77 break;
78
79template <typename SectionType>
80Expected<MachOYAML::Section>
81MachODumper::constructSectionCommon(SectionType Sec, size_t SecIndex) {
82 MachOYAML::Section TempSec;
83 memcpy(reinterpret_cast<void *>(&TempSec.sectname[0]), &Sec.sectname[0], 16);
84 memcpy(reinterpret_cast<void *>(&TempSec.segname[0]), &Sec.segname[0], 16);
85 TempSec.addr = Sec.addr;
86 TempSec.size = Sec.size;
87 TempSec.offset = Sec.offset;
88 TempSec.align = Sec.align;
89 TempSec.reloff = Sec.reloff;
90 TempSec.nreloc = Sec.nreloc;
91 TempSec.flags = Sec.flags;
92 TempSec.reserved1 = Sec.reserved1;
93 TempSec.reserved2 = Sec.reserved2;
94 TempSec.reserved3 = 0;
95 if (!MachO::isVirtualSection(type: Sec.flags & MachO::SECTION_TYPE))
96 TempSec.content =
97 yaml::BinaryRef(Obj.getSectionContents(Sec.offset, Sec.size));
98
99 if (Expected<object::SectionRef> SecRef = Obj.getSection(SectionIndex: SecIndex)) {
100 TempSec.relocations.reserve(n: TempSec.nreloc);
101 for (const object::RelocationRef &Reloc : SecRef->relocations()) {
102 const object::DataRefImpl Rel = Reloc.getRawDataRefImpl();
103 const MachO::any_relocation_info RE = Obj.getRelocation(Rel);
104 MachOYAML::Relocation R;
105 R.address = Obj.getAnyRelocationAddress(RE);
106 R.is_pcrel = Obj.getAnyRelocationPCRel(RE);
107 R.length = Obj.getAnyRelocationLength(RE);
108 R.type = Obj.getAnyRelocationType(RE);
109 R.is_scattered = Obj.isRelocationScattered(RE);
110 R.symbolnum = (R.is_scattered ? 0 : Obj.getPlainRelocationSymbolNum(RE));
111 R.is_extern =
112 (R.is_scattered ? false : Obj.getPlainRelocationExternal(RE));
113 R.value = (R.is_scattered ? Obj.getScatteredRelocationValue(RE) : 0);
114 TempSec.relocations.push_back(x: R);
115 }
116 } else {
117 return SecRef.takeError();
118 }
119 return TempSec;
120}
121
122template <>
123Expected<MachOYAML::Section> MachODumper::constructSection(MachO::section Sec,
124 size_t SecIndex) {
125 Expected<MachOYAML::Section> TempSec = constructSectionCommon(Sec, SecIndex);
126 if (TempSec)
127 TempSec->reserved3 = 0;
128 return TempSec;
129}
130
131template <>
132Expected<MachOYAML::Section>
133MachODumper::constructSection(MachO::section_64 Sec, size_t SecIndex) {
134 Expected<MachOYAML::Section> TempSec = constructSectionCommon(Sec, SecIndex);
135 if (TempSec)
136 TempSec->reserved3 = Sec.reserved3;
137 return TempSec;
138}
139
140static Error dumpDebugSection(StringRef SecName, DWARFContext &DCtx,
141 DWARFYAML::Data &DWARF) {
142 if (SecName == "__debug_abbrev")
143 return dumpDebugAbbrev(DCtx, Y&: DWARF);
144 if (SecName == "__debug_aranges")
145 return dumpDebugARanges(DCtx, Y&: DWARF);
146 if (SecName == "__debug_info") {
147 dumpDebugInfo(DCtx, Y&: DWARF);
148 return Error::success();
149 }
150 if (SecName == "__debug_line") {
151 dumpDebugLines(DCtx, Y&: DWARF);
152 return Error::success();
153 }
154 if (SecName.starts_with(Prefix: "__debug_pub")) {
155 // FIXME: We should extract pub-section dumpers from this function.
156 dumpDebugPubSections(DCtx, Y&: DWARF);
157 return Error::success();
158 }
159 if (SecName == "__debug_ranges")
160 return dumpDebugRanges(DCtx, Y&: DWARF);
161 if (SecName == "__debug_str")
162 return dumpDebugStrings(DCtx, Y&: DWARF);
163 return createStringError(EC: errc::not_supported,
164 S: "dumping " + SecName + " section is not supported");
165}
166
167template <typename SectionType, typename SegmentType>
168Expected<const char *> MachODumper::extractSections(
169 const llvm::object::MachOObjectFile::LoadCommandInfo &LoadCmd,
170 std::vector<MachOYAML::Section> &Sections, MachOYAML::Object &Y) {
171 auto End = LoadCmd.Ptr + LoadCmd.C.cmdsize;
172 const SectionType *Curr =
173 reinterpret_cast<const SectionType *>(LoadCmd.Ptr + sizeof(SegmentType));
174 for (; reinterpret_cast<const void *>(Curr) < End; Curr++) {
175 SectionType Sec;
176 memcpy((void *)&Sec, Curr, sizeof(SectionType));
177 if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
178 MachO::swapStruct(Sec);
179 // For MachO section indices start from 1.
180 if (Expected<MachOYAML::Section> S =
181 constructSection(Sec, Sections.size() + 1)) {
182 StringRef SecName(S->sectname);
183
184 // Copy data sections if requested.
185 if ((RawSegment & ::RawSegments::data) &&
186 StringRef(S->segname).starts_with(Prefix: "__DATA"))
187 S->content =
188 yaml::BinaryRef(Obj.getSectionContents(Sec.offset, Sec.size));
189
190 if (SecName.starts_with(Prefix: "__debug_")) {
191 // If the DWARF section cannot be successfully parsed, emit raw content
192 // instead of an entry in the DWARF section of the YAML.
193 if (Error Err = dumpDebugSection(SecName, DCtx&: *DWARFCtx, DWARF&: Y.DWARF))
194 consumeError(Err: std::move(Err));
195 else
196 S->content.reset();
197 }
198 Sections.push_back(x: std::move(*S));
199 } else
200 return S.takeError();
201 }
202 return reinterpret_cast<const char *>(Curr);
203}
204
205template <typename StructType>
206Expected<const char *> MachODumper::processLoadCommandData(
207 MachOYAML::LoadCommand &LC,
208 const llvm::object::MachOObjectFile::LoadCommandInfo &LoadCmd,
209 MachOYAML::Object &Y) {
210 return LoadCmd.Ptr + sizeof(StructType);
211}
212
213template <>
214Expected<const char *>
215MachODumper::processLoadCommandData<MachO::segment_command>(
216 MachOYAML::LoadCommand &LC,
217 const llvm::object::MachOObjectFile::LoadCommandInfo &LoadCmd,
218 MachOYAML::Object &Y) {
219 return extractSections<MachO::section, MachO::segment_command>(
220 LoadCmd, Sections&: LC.Sections, Y);
221}
222
223template <>
224Expected<const char *>
225MachODumper::processLoadCommandData<MachO::segment_command_64>(
226 MachOYAML::LoadCommand &LC,
227 const llvm::object::MachOObjectFile::LoadCommandInfo &LoadCmd,
228 MachOYAML::Object &Y) {
229 return extractSections<MachO::section_64, MachO::segment_command_64>(
230 LoadCmd, Sections&: LC.Sections, Y);
231}
232
233template <typename StructType>
234const char *
235readString(MachOYAML::LoadCommand &LC,
236 const llvm::object::MachOObjectFile::LoadCommandInfo &LoadCmd) {
237 auto Start = LoadCmd.Ptr + sizeof(StructType);
238 auto MaxSize = LoadCmd.C.cmdsize - sizeof(StructType);
239 auto Size = strnlen(string: Start, maxlen: MaxSize);
240 LC.Content = StringRef(Start, Size).str();
241 return Start + Size;
242}
243
244template <>
245Expected<const char *>
246MachODumper::processLoadCommandData<MachO::dylib_command>(
247 MachOYAML::LoadCommand &LC,
248 const llvm::object::MachOObjectFile::LoadCommandInfo &LoadCmd,
249 MachOYAML::Object &Y) {
250 return readString<MachO::dylib_command>(LC, LoadCmd);
251}
252
253template <>
254Expected<const char *>
255MachODumper::processLoadCommandData<MachO::dylinker_command>(
256 MachOYAML::LoadCommand &LC,
257 const llvm::object::MachOObjectFile::LoadCommandInfo &LoadCmd,
258 MachOYAML::Object &Y) {
259 return readString<MachO::dylinker_command>(LC, LoadCmd);
260}
261
262template <>
263Expected<const char *>
264MachODumper::processLoadCommandData<MachO::rpath_command>(
265 MachOYAML::LoadCommand &LC,
266 const llvm::object::MachOObjectFile::LoadCommandInfo &LoadCmd,
267 MachOYAML::Object &Y) {
268 return readString<MachO::rpath_command>(LC, LoadCmd);
269}
270
271template <>
272Expected<const char *>
273MachODumper::processLoadCommandData<MachO::build_version_command>(
274 MachOYAML::LoadCommand &LC,
275 const llvm::object::MachOObjectFile::LoadCommandInfo &LoadCmd,
276 MachOYAML::Object &Y) {
277 auto Start = LoadCmd.Ptr + sizeof(MachO::build_version_command);
278 auto NTools = LC.Data.build_version_command_data.ntools;
279 for (unsigned i = 0; i < NTools; ++i) {
280 auto Curr = Start + i * sizeof(MachO::build_tool_version);
281 MachO::build_tool_version BV;
282 memcpy(dest: (void *)&BV, src: Curr, n: sizeof(MachO::build_tool_version));
283 if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
284 MachO::swapStruct(C&: BV);
285 LC.Tools.push_back(x: BV);
286 }
287 return Start + NTools * sizeof(MachO::build_tool_version);
288}
289
290template <>
291Expected<const char *>
292MachODumper::processLoadCommandData<MachO::target_triple_command>(
293 MachOYAML::LoadCommand &LC,
294 const llvm::object::MachOObjectFile::LoadCommandInfo &LoadCmd,
295 MachOYAML::Object &Y) {
296 return readString<MachO::target_triple_command>(LC, LoadCmd);
297}
298
299Expected<std::unique_ptr<MachOYAML::Object>> MachODumper::dump() {
300 auto Y = std::make_unique<MachOYAML::Object>();
301 Y->IsLittleEndian = Obj.isLittleEndian();
302 dumpHeader(Y);
303 if (Error Err = dumpLoadCommands(Y))
304 return std::move(Err);
305 if (RawSegment & ::RawSegments::linkedit)
306 Y->RawLinkEditSegment =
307 yaml::BinaryRef(Obj.getSegmentContents(SegmentName: "__LINKEDIT"));
308 else
309 dumpLinkEdit(Y);
310
311 return std::move(Y);
312}
313
314void MachODumper::dumpHeader(std::unique_ptr<MachOYAML::Object> &Y) {
315 Y->Header.magic = Obj.getHeader().magic;
316 Y->Header.cputype = Obj.getHeader().cputype;
317 Y->Header.cpusubtype = Obj.getHeader().cpusubtype;
318 Y->Header.filetype = Obj.getHeader().filetype;
319 Y->Header.ncmds = Obj.getHeader().ncmds;
320 Y->Header.sizeofcmds = Obj.getHeader().sizeofcmds;
321 Y->Header.flags = Obj.getHeader().flags;
322 Y->Header.reserved = 0;
323}
324
325Error MachODumper::dumpLoadCommands(std::unique_ptr<MachOYAML::Object> &Y) {
326 for (auto LoadCmd : Obj.load_commands()) {
327 MachOYAML::LoadCommand LC;
328 const char *EndPtr = LoadCmd.Ptr;
329 switch (LoadCmd.C.cmd) {
330 default:
331 memcpy(dest: (void *)&(LC.Data.load_command_data), src: LoadCmd.Ptr,
332 n: sizeof(MachO::load_command));
333 if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
334 MachO::swapStruct(lc&: LC.Data.load_command_data);
335 if (Expected<const char *> ExpectedEndPtr =
336 processLoadCommandData<MachO::load_command>(LC, LoadCmd, Y&: *Y))
337 EndPtr = *ExpectedEndPtr;
338 else
339 return ExpectedEndPtr.takeError();
340 break;
341#include "llvm/BinaryFormat/MachO.def"
342 }
343 auto RemainingBytes = LoadCmd.C.cmdsize - (EndPtr - LoadCmd.Ptr);
344 if (!std::all_of(first: EndPtr, last: &EndPtr[RemainingBytes],
345 pred: [](const char C) { return C == 0; })) {
346 LC.PayloadBytes.insert(position: LC.PayloadBytes.end(), first: EndPtr,
347 last: &EndPtr[RemainingBytes]);
348 RemainingBytes = 0;
349 }
350 LC.ZeroPadBytes = RemainingBytes;
351 Y->LoadCommands.push_back(x: std::move(LC));
352 }
353 return Error::success();
354}
355
356void MachODumper::dumpLinkEdit(std::unique_ptr<MachOYAML::Object> &Y) {
357 dumpRebaseOpcodes(Y);
358 dumpBindOpcodes(BindOpcodes&: Y->LinkEdit.BindOpcodes, OpcodeBuffer: Obj.getDyldInfoBindOpcodes());
359 dumpBindOpcodes(BindOpcodes&: Y->LinkEdit.WeakBindOpcodes,
360 OpcodeBuffer: Obj.getDyldInfoWeakBindOpcodes());
361 dumpBindOpcodes(BindOpcodes&: Y->LinkEdit.LazyBindOpcodes, OpcodeBuffer: Obj.getDyldInfoLazyBindOpcodes(),
362 Lazy: true);
363 dumpExportTrie(Y);
364 dumpSymbols(Y);
365 dumpIndirectSymbols(Y);
366 dumpFunctionStarts(Y);
367 dumpChainedFixups(Y);
368 dumpDataInCode(Y);
369}
370
371void MachODumper::dumpFunctionStarts(std::unique_ptr<MachOYAML::Object> &Y) {
372 MachOYAML::LinkEditData &LEData = Y->LinkEdit;
373
374 auto FunctionStarts = Obj.getFunctionStarts();
375 llvm::append_range(C&: LEData.FunctionStarts, R&: FunctionStarts);
376}
377
378void MachODumper::dumpRebaseOpcodes(std::unique_ptr<MachOYAML::Object> &Y) {
379 MachOYAML::LinkEditData &LEData = Y->LinkEdit;
380
381 auto RebaseOpcodes = Obj.getDyldInfoRebaseOpcodes();
382 for (auto OpCode = RebaseOpcodes.begin(); OpCode != RebaseOpcodes.end();
383 ++OpCode) {
384 MachOYAML::RebaseOpcode RebaseOp;
385 RebaseOp.Opcode =
386 static_cast<MachO::RebaseOpcode>(*OpCode & MachO::REBASE_OPCODE_MASK);
387 RebaseOp.Imm = *OpCode & MachO::REBASE_IMMEDIATE_MASK;
388
389 unsigned Count;
390 uint64_t ULEB = 0;
391
392 switch (RebaseOp.Opcode) {
393 case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB:
394
395 ULEB = decodeULEB128(p: OpCode + 1, n: &Count);
396 RebaseOp.ExtraData.push_back(x: ULEB);
397 OpCode += Count;
398 [[fallthrough]];
399 // Intentionally no break here -- This opcode has two ULEB values
400 case MachO::REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
401 case MachO::REBASE_OPCODE_ADD_ADDR_ULEB:
402 case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES:
403 case MachO::REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB:
404
405 ULEB = decodeULEB128(p: OpCode + 1, n: &Count);
406 RebaseOp.ExtraData.push_back(x: ULEB);
407 OpCode += Count;
408 break;
409 default:
410 break;
411 }
412
413 LEData.RebaseOpcodes.push_back(x: RebaseOp);
414
415 if (RebaseOp.Opcode == MachO::REBASE_OPCODE_DONE)
416 break;
417 }
418}
419
420StringRef ReadStringRef(const uint8_t *Start) {
421 const uint8_t *Itr = Start;
422 for (; *Itr; ++Itr)
423 ;
424 return StringRef(reinterpret_cast<const char *>(Start), Itr - Start);
425}
426
427void MachODumper::dumpBindOpcodes(
428 std::vector<MachOYAML::BindOpcode> &BindOpcodes,
429 ArrayRef<uint8_t> OpcodeBuffer, bool Lazy) {
430 for (auto OpCode = OpcodeBuffer.begin(); OpCode != OpcodeBuffer.end();
431 ++OpCode) {
432 MachOYAML::BindOpcode BindOp;
433 BindOp.Opcode =
434 static_cast<MachO::BindOpcode>(*OpCode & MachO::BIND_OPCODE_MASK);
435 BindOp.Imm = *OpCode & MachO::BIND_IMMEDIATE_MASK;
436
437 unsigned Count;
438 uint64_t ULEB = 0;
439 int64_t SLEB = 0;
440
441 switch (BindOp.Opcode) {
442 case MachO::BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
443 ULEB = decodeULEB128(p: OpCode + 1, n: &Count);
444 BindOp.ULEBExtraData.push_back(x: ULEB);
445 OpCode += Count;
446 [[fallthrough]];
447 // Intentionally no break here -- this opcode has two ULEB values
448
449 case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
450 case MachO::BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
451 case MachO::BIND_OPCODE_ADD_ADDR_ULEB:
452 case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
453 ULEB = decodeULEB128(p: OpCode + 1, n: &Count);
454 BindOp.ULEBExtraData.push_back(x: ULEB);
455 OpCode += Count;
456 break;
457
458 case MachO::BIND_OPCODE_SET_ADDEND_SLEB:
459 SLEB = decodeSLEB128(p: OpCode + 1, n: &Count);
460 BindOp.SLEBExtraData.push_back(x: SLEB);
461 OpCode += Count;
462 break;
463
464 case MachO::BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
465 BindOp.Symbol = ReadStringRef(Start: OpCode + 1);
466 OpCode += BindOp.Symbol.size() + 1;
467 break;
468 default:
469 break;
470 }
471
472 BindOpcodes.push_back(x: BindOp);
473
474 // Lazy bindings have DONE opcodes between operations, so we need to keep
475 // processing after a DONE.
476 if (!Lazy && BindOp.Opcode == MachO::BIND_OPCODE_DONE)
477 break;
478 }
479}
480
481/*!
482 * /brief processes a node from the export trie, and its children.
483 *
484 * To my knowledge there is no documentation of the encoded format of this data
485 * other than in the heads of the Apple linker engineers. To that end hopefully
486 * this comment and the implementation below can serve to light the way for
487 * anyone crazy enough to come down this path in the future.
488 *
489 * This function reads and preserves the trie structure of the export trie. To
490 * my knowledge there is no code anywhere else that reads the data and preserves
491 * the Trie. LD64 (sources available at opensource.apple.com) has a similar
492 * implementation that parses the export trie into a vector. That code as well
493 * as LLVM's libObject MachO implementation were the basis for this.
494 *
495 * The export trie is an encoded trie. The node serialization is a bit awkward.
496 * The below pseudo-code is the best description I've come up with for it.
497 *
498 * struct SerializedNode {
499 * ULEB128 TerminalSize;
500 * struct TerminalData { <-- This is only present if TerminalSize > 0
501 * ULEB128 Flags;
502 * ULEB128 Address; <-- Present if (! Flags & REEXPORT )
503 * ULEB128 Other; <-- Present if ( Flags & REEXPORT ||
504 * Flags & STUB_AND_RESOLVER )
505 * char[] ImportName; <-- Present if ( Flags & REEXPORT )
506 * }
507 * uint8_t ChildrenCount;
508 * Pair<char[], ULEB128> ChildNameOffsetPair[ChildrenCount];
509 * SerializedNode Children[ChildrenCount]
510 * }
511 *
512 * Terminal nodes are nodes that represent actual exports. They can appear
513 * anywhere in the tree other than at the root; they do not need to be leaf
514 * nodes. When reading the data out of the trie this routine reads it in-order,
515 * but it puts the child names and offsets directly into the child nodes. This
516 * results in looping over the children twice during serialization and
517 * de-serialization, but it makes the YAML representation more human readable.
518 *
519 * Below is an example of the graph from a "Hello World" executable:
520 *
521 * -------
522 * | '' |
523 * -------
524 * |
525 * -------
526 * | '_' |
527 * -------
528 * |
529 * |----------------------------------------|
530 * | |
531 * ------------------------ ---------------------
532 * | '_mh_execute_header' | | 'main' |
533 * | Flags: 0x00000000 | | Flags: 0x00000000 |
534 * | Addr: 0x00000000 | | Addr: 0x00001160 |
535 * ------------------------ ---------------------
536 *
537 * This graph represents the trie for the exports "__mh_execute_header" and
538 * "_main". In the graph only the "_main" and "__mh_execute_header" nodes are
539 * terminal.
540*/
541
542const uint8_t *processExportNode(const uint8_t *Start, const uint8_t *CurrPtr,
543 const uint8_t *const End,
544 MachOYAML::ExportEntry &Entry) {
545 if (CurrPtr >= End)
546 return CurrPtr;
547 unsigned Count = 0;
548 Entry.TerminalSize = decodeULEB128(p: CurrPtr, n: &Count);
549 CurrPtr += Count;
550 if (Entry.TerminalSize != 0) {
551 Entry.Flags = decodeULEB128(p: CurrPtr, n: &Count);
552 CurrPtr += Count;
553 if (Entry.Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT) {
554 Entry.Address = 0;
555 Entry.Other = decodeULEB128(p: CurrPtr, n: &Count);
556 CurrPtr += Count;
557 Entry.ImportName = std::string(reinterpret_cast<const char *>(CurrPtr));
558 } else {
559 Entry.Address = decodeULEB128(p: CurrPtr, n: &Count);
560 CurrPtr += Count;
561 if (Entry.Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {
562 Entry.Other = decodeULEB128(p: CurrPtr, n: &Count);
563 CurrPtr += Count;
564 } else
565 Entry.Other = 0;
566 }
567 }
568 uint8_t childrenCount = *CurrPtr++;
569 if (childrenCount == 0)
570 return CurrPtr;
571
572 Entry.Children.insert(position: Entry.Children.begin(), n: (size_t)childrenCount,
573 x: MachOYAML::ExportEntry());
574 for (auto &Child : Entry.Children) {
575 Child.Name = std::string(reinterpret_cast<const char *>(CurrPtr));
576 CurrPtr += Child.Name.length() + 1;
577 Child.NodeOffset = decodeULEB128(p: CurrPtr, n: &Count);
578 CurrPtr += Count;
579 }
580 for (auto &Child : Entry.Children) {
581 CurrPtr = processExportNode(Start, CurrPtr: Start + Child.NodeOffset, End, Entry&: Child);
582 }
583 return CurrPtr;
584}
585
586void MachODumper::dumpExportTrie(std::unique_ptr<MachOYAML::Object> &Y) {
587 MachOYAML::LinkEditData &LEData = Y->LinkEdit;
588 // The exports trie can be in LC_DYLD_INFO or LC_DYLD_EXPORTS_TRIE
589 auto ExportsTrie = Obj.getDyldInfoExportsTrie();
590 if (ExportsTrie.empty())
591 ExportsTrie = Obj.getDyldExportsTrie();
592 processExportNode(Start: ExportsTrie.begin(), CurrPtr: ExportsTrie.begin(), End: ExportsTrie.end(),
593 Entry&: LEData.ExportTrie);
594}
595
596template <typename nlist_t>
597MachOYAML::NListEntry constructNameList(const nlist_t &nlist) {
598 MachOYAML::NListEntry NL;
599 NL.n_strx = nlist.n_strx;
600 NL.n_type = nlist.n_type;
601 NL.n_sect = nlist.n_sect;
602 NL.n_desc = nlist.n_desc;
603 NL.n_value = nlist.n_value;
604 return NL;
605}
606
607void MachODumper::dumpSymbols(std::unique_ptr<MachOYAML::Object> &Y) {
608 MachOYAML::LinkEditData &LEData = Y->LinkEdit;
609
610 for (auto Symbol : Obj.symbols()) {
611 MachOYAML::NListEntry NLE =
612 Obj.is64Bit()
613 ? constructNameList<MachO::nlist_64>(
614 nlist: Obj.getSymbol64TableEntry(DRI: Symbol.getRawDataRefImpl()))
615 : constructNameList<MachO::nlist>(
616 nlist: Obj.getSymbolTableEntry(DRI: Symbol.getRawDataRefImpl()));
617 LEData.NameList.push_back(x: NLE);
618 }
619
620 StringRef RemainingTable = Obj.getStringTableData();
621 while (RemainingTable.size() > 0) {
622 auto SymbolPair = RemainingTable.split(Separator: '\0');
623 RemainingTable = SymbolPair.second;
624 LEData.StringTable.push_back(x: SymbolPair.first);
625 }
626}
627
628void MachODumper::dumpIndirectSymbols(std::unique_ptr<MachOYAML::Object> &Y) {
629 MachOYAML::LinkEditData &LEData = Y->LinkEdit;
630
631 MachO::dysymtab_command DLC = Obj.getDysymtabLoadCommand();
632 for (unsigned i = 0; i < DLC.nindirectsyms; ++i)
633 LEData.IndirectSymbols.push_back(x: Obj.getIndirectSymbolTableEntry(DLC, Index: i));
634}
635
636void MachODumper::dumpChainedFixups(std::unique_ptr<MachOYAML::Object> &Y) {
637 MachOYAML::LinkEditData &LEData = Y->LinkEdit;
638
639 for (const auto &LC : Y->LoadCommands) {
640 if (LC.Data.load_command_data.cmd == llvm::MachO::LC_DYLD_CHAINED_FIXUPS) {
641 const MachO::linkedit_data_command &DC =
642 LC.Data.linkedit_data_command_data;
643 if (DC.dataoff) {
644 assert(DC.dataoff < Obj.getData().size());
645 assert(DC.dataoff + DC.datasize <= Obj.getData().size());
646 const char *Bytes = Obj.getData().data() + DC.dataoff;
647 llvm::append_range(C&: LEData.ChainedFixups, R: ArrayRef(Bytes, DC.datasize));
648 }
649 break;
650 }
651 }
652}
653
654void MachODumper::dumpDataInCode(std::unique_ptr<MachOYAML::Object> &Y) {
655 MachOYAML::LinkEditData &LEData = Y->LinkEdit;
656
657 MachO::linkedit_data_command DIC = Obj.getDataInCodeLoadCommand();
658 uint32_t NumEntries = DIC.datasize / sizeof(MachO::data_in_code_entry);
659 for (uint32_t Idx = 0; Idx < NumEntries; ++Idx) {
660 MachO::data_in_code_entry DICE =
661 Obj.getDataInCodeTableEntry(DataOffset: DIC.dataoff, Index: Idx);
662 MachOYAML::DataInCodeEntry Entry{.Offset: DICE.offset, .Length: DICE.length, .Kind: DICE.kind};
663 LEData.DataInCode.emplace_back(args&: Entry);
664 }
665}
666
667Error macho2yaml(raw_ostream &Out, const object::MachOObjectFile &Obj,
668 unsigned RawSegments) {
669 std::unique_ptr<DWARFContext> DCtx = DWARFContext::create(Obj);
670 MachODumper Dumper(Obj, std::move(DCtx), RawSegments);
671 Expected<std::unique_ptr<MachOYAML::Object>> YAML = Dumper.dump();
672 if (!YAML)
673 return YAML.takeError();
674
675 yaml::YamlObjectFile YAMLFile;
676 YAMLFile.MachO = std::move(YAML.get());
677
678 yaml::Output Yout(Out);
679 Yout << YAMLFile;
680 return Error::success();
681}
682
683Error macho2yaml(raw_ostream &Out, const object::MachOUniversalBinary &Obj,
684 unsigned RawSegments) {
685 yaml::YamlObjectFile YAMLFile;
686 YAMLFile.FatMachO.reset(p: new MachOYAML::UniversalBinary());
687 MachOYAML::UniversalBinary &YAML = *YAMLFile.FatMachO;
688 YAML.Header.magic = Obj.getMagic();
689 YAML.Header.nfat_arch = Obj.getNumberOfObjects();
690
691 for (auto Slice : Obj.objects()) {
692 MachOYAML::FatArch arch;
693 arch.cputype = Slice.getCPUType();
694 arch.cpusubtype = Slice.getCPUSubType();
695 arch.offset = Slice.getOffset();
696 arch.size = Slice.getSize();
697 arch.align = Slice.getAlign();
698 arch.reserved = Slice.getReserved();
699 YAML.FatArchs.push_back(x: arch);
700
701 auto SliceObj = Slice.getAsObjectFile();
702 if (!SliceObj)
703 return SliceObj.takeError();
704
705 std::unique_ptr<DWARFContext> DCtx = DWARFContext::create(Obj: *SliceObj.get());
706 MachODumper Dumper(*SliceObj.get(), std::move(DCtx), RawSegments);
707 Expected<std::unique_ptr<MachOYAML::Object>> YAMLObj = Dumper.dump();
708 if (!YAMLObj)
709 return YAMLObj.takeError();
710 YAML.Slices.push_back(x: *YAMLObj.get());
711 }
712
713 yaml::Output Yout(Out);
714 Yout << YAML;
715 return Error::success();
716}
717
718Error macho2yaml(raw_ostream &Out, const object::Binary &Binary,
719 unsigned RawSegments) {
720 if (const auto *MachOObj = dyn_cast<object::MachOUniversalBinary>(Val: &Binary))
721 return macho2yaml(Out, Obj: *MachOObj, RawSegments);
722
723 if (const auto *MachOObj = dyn_cast<object::MachOObjectFile>(Val: &Binary))
724 return macho2yaml(Out, Obj: *MachOObj, RawSegments);
725
726 llvm_unreachable("unexpected Mach-O file format");
727}
728