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