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