719 lines · cpp
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-exception6//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 memcpy20 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(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(SecIndex)) {100 TempSec.relocations.reserve(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(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, DWARF);144 if (SecName == "__debug_aranges")145 return dumpDebugARanges(DCtx, DWARF);146 if (SecName == "__debug_info") {147 dumpDebugInfo(DCtx, DWARF);148 return Error::success();149 }150 if (SecName == "__debug_line") {151 dumpDebugLines(DCtx, DWARF);152 return Error::success();153 }154 if (SecName.starts_with("__debug_pub")) {155 // FIXME: We should extract pub-section dumpers from this function.156 dumpDebugPubSections(DCtx, DWARF);157 return Error::success();158 }159 if (SecName == "__debug_ranges")160 return dumpDebugRanges(DCtx, DWARF);161 if (SecName == "__debug_str")162 return dumpDebugStrings(DCtx, DWARF);163 return createStringError(errc::not_supported,164 "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("__DATA"))187 S->content =188 yaml::BinaryRef(Obj.getSectionContents(Sec.offset, Sec.size));189 190 if (SecName.starts_with("__debug_")) {191 // If the DWARF section cannot be successfully parsed, emit raw content192 // instead of an entry in the DWARF section of the YAML.193 if (Error Err = dumpDebugSection(SecName, *DWARFCtx, Y.DWARF))194 consumeError(std::move(Err));195 else196 S->content.reset();197 }198 Sections.push_back(std::move(*S));199 } else200 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, 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, 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(Start, 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((void *)&BV, Curr, sizeof(MachO::build_tool_version));283 if (Obj.isLittleEndian() != sys::IsLittleEndianHost)284 MachO::swapStruct(BV);285 LC.Tools.push_back(BV);286 }287 return Start + NTools * sizeof(MachO::build_tool_version);288}289 290Expected<std::unique_ptr<MachOYAML::Object>> MachODumper::dump() {291 auto Y = std::make_unique<MachOYAML::Object>();292 Y->IsLittleEndian = Obj.isLittleEndian();293 dumpHeader(Y);294 if (Error Err = dumpLoadCommands(Y))295 return std::move(Err);296 if (RawSegment & ::RawSegments::linkedit)297 Y->RawLinkEditSegment =298 yaml::BinaryRef(Obj.getSegmentContents("__LINKEDIT"));299 else300 dumpLinkEdit(Y);301 302 return std::move(Y);303}304 305void MachODumper::dumpHeader(std::unique_ptr<MachOYAML::Object> &Y) {306 Y->Header.magic = Obj.getHeader().magic;307 Y->Header.cputype = Obj.getHeader().cputype;308 Y->Header.cpusubtype = Obj.getHeader().cpusubtype;309 Y->Header.filetype = Obj.getHeader().filetype;310 Y->Header.ncmds = Obj.getHeader().ncmds;311 Y->Header.sizeofcmds = Obj.getHeader().sizeofcmds;312 Y->Header.flags = Obj.getHeader().flags;313 Y->Header.reserved = 0;314}315 316Error MachODumper::dumpLoadCommands(std::unique_ptr<MachOYAML::Object> &Y) {317 for (auto LoadCmd : Obj.load_commands()) {318 MachOYAML::LoadCommand LC;319 const char *EndPtr = LoadCmd.Ptr;320 switch (LoadCmd.C.cmd) {321 default:322 memcpy((void *)&(LC.Data.load_command_data), LoadCmd.Ptr,323 sizeof(MachO::load_command));324 if (Obj.isLittleEndian() != sys::IsLittleEndianHost)325 MachO::swapStruct(LC.Data.load_command_data);326 if (Expected<const char *> ExpectedEndPtr =327 processLoadCommandData<MachO::load_command>(LC, LoadCmd, *Y))328 EndPtr = *ExpectedEndPtr;329 else330 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 347void 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 dumpChainedFixups(Y);359 dumpDataInCode(Y);360}361 362void MachODumper::dumpFunctionStarts(std::unique_ptr<MachOYAML::Object> &Y) {363 MachOYAML::LinkEditData &LEData = Y->LinkEdit;364 365 auto FunctionStarts = Obj.getFunctionStarts();366 llvm::append_range(LEData.FunctionStarts, FunctionStarts);367}368 369void MachODumper::dumpRebaseOpcodes(std::unique_ptr<MachOYAML::Object> &Y) {370 MachOYAML::LinkEditData &LEData = Y->LinkEdit;371 372 auto RebaseOpcodes = Obj.getDyldInfoRebaseOpcodes();373 for (auto OpCode = RebaseOpcodes.begin(); OpCode != RebaseOpcodes.end();374 ++OpCode) {375 MachOYAML::RebaseOpcode RebaseOp;376 RebaseOp.Opcode =377 static_cast<MachO::RebaseOpcode>(*OpCode & MachO::REBASE_OPCODE_MASK);378 RebaseOp.Imm = *OpCode & MachO::REBASE_IMMEDIATE_MASK;379 380 unsigned Count;381 uint64_t ULEB = 0;382 383 switch (RebaseOp.Opcode) {384 case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB:385 386 ULEB = decodeULEB128(OpCode + 1, &Count);387 RebaseOp.ExtraData.push_back(ULEB);388 OpCode += Count;389 [[fallthrough]];390 // Intentionally no break here -- This opcode has two ULEB values391 case MachO::REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:392 case MachO::REBASE_OPCODE_ADD_ADDR_ULEB:393 case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES:394 case MachO::REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB:395 396 ULEB = decodeULEB128(OpCode + 1, &Count);397 RebaseOp.ExtraData.push_back(ULEB);398 OpCode += Count;399 break;400 default:401 break;402 }403 404 LEData.RebaseOpcodes.push_back(RebaseOp);405 406 if (RebaseOp.Opcode == MachO::REBASE_OPCODE_DONE)407 break;408 }409}410 411StringRef ReadStringRef(const uint8_t *Start) {412 const uint8_t *Itr = Start;413 for (; *Itr; ++Itr)414 ;415 return StringRef(reinterpret_cast<const char *>(Start), Itr - Start);416}417 418void MachODumper::dumpBindOpcodes(419 std::vector<MachOYAML::BindOpcode> &BindOpcodes,420 ArrayRef<uint8_t> OpcodeBuffer, bool Lazy) {421 for (auto OpCode = OpcodeBuffer.begin(); OpCode != OpcodeBuffer.end();422 ++OpCode) {423 MachOYAML::BindOpcode BindOp;424 BindOp.Opcode =425 static_cast<MachO::BindOpcode>(*OpCode & MachO::BIND_OPCODE_MASK);426 BindOp.Imm = *OpCode & MachO::BIND_IMMEDIATE_MASK;427 428 unsigned Count;429 uint64_t ULEB = 0;430 int64_t SLEB = 0;431 432 switch (BindOp.Opcode) {433 case MachO::BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:434 ULEB = decodeULEB128(OpCode + 1, &Count);435 BindOp.ULEBExtraData.push_back(ULEB);436 OpCode += Count;437 [[fallthrough]];438 // Intentionally no break here -- this opcode has two ULEB values439 440 case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:441 case MachO::BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:442 case MachO::BIND_OPCODE_ADD_ADDR_ULEB:443 case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:444 ULEB = decodeULEB128(OpCode + 1, &Count);445 BindOp.ULEBExtraData.push_back(ULEB);446 OpCode += Count;447 break;448 449 case MachO::BIND_OPCODE_SET_ADDEND_SLEB:450 SLEB = decodeSLEB128(OpCode + 1, &Count);451 BindOp.SLEBExtraData.push_back(SLEB);452 OpCode += Count;453 break;454 455 case MachO::BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:456 BindOp.Symbol = ReadStringRef(OpCode + 1);457 OpCode += BindOp.Symbol.size() + 1;458 break;459 default:460 break;461 }462 463 BindOpcodes.push_back(BindOp);464 465 // Lazy bindings have DONE opcodes between operations, so we need to keep466 // processing after a DONE.467 if (!Lazy && BindOp.Opcode == MachO::BIND_OPCODE_DONE)468 break;469 }470}471 472/*!473 * /brief processes a node from the export trie, and its children.474 *475 * To my knowledge there is no documentation of the encoded format of this data476 * other than in the heads of the Apple linker engineers. To that end hopefully477 * this comment and the implementation below can serve to light the way for478 * anyone crazy enough to come down this path in the future.479 *480 * This function reads and preserves the trie structure of the export trie. To481 * my knowledge there is no code anywhere else that reads the data and preserves482 * the Trie. LD64 (sources available at opensource.apple.com) has a similar483 * implementation that parses the export trie into a vector. That code as well484 * as LLVM's libObject MachO implementation were the basis for this.485 *486 * The export trie is an encoded trie. The node serialization is a bit awkward.487 * The below pseudo-code is the best description I've come up with for it.488 *489 * struct SerializedNode {490 * ULEB128 TerminalSize;491 * struct TerminalData { <-- This is only present if TerminalSize > 0492 * ULEB128 Flags;493 * ULEB128 Address; <-- Present if (! Flags & REEXPORT )494 * ULEB128 Other; <-- Present if ( Flags & REEXPORT ||495 * Flags & STUB_AND_RESOLVER )496 * char[] ImportName; <-- Present if ( Flags & REEXPORT )497 * }498 * uint8_t ChildrenCount;499 * Pair<char[], ULEB128> ChildNameOffsetPair[ChildrenCount];500 * SerializedNode Children[ChildrenCount]501 * }502 *503 * Terminal nodes are nodes that represent actual exports. They can appear504 * anywhere in the tree other than at the root; they do not need to be leaf505 * nodes. When reading the data out of the trie this routine reads it in-order,506 * but it puts the child names and offsets directly into the child nodes. This507 * results in looping over the children twice during serialization and508 * de-serialization, but it makes the YAML representation more human readable.509 *510 * Below is an example of the graph from a "Hello World" executable:511 *512 * -------513 * | '' |514 * -------515 * |516 * -------517 * | '_' |518 * -------519 * |520 * |----------------------------------------|521 * | |522 * ------------------------ ---------------------523 * | '_mh_execute_header' | | 'main' |524 * | Flags: 0x00000000 | | Flags: 0x00000000 |525 * | Addr: 0x00000000 | | Addr: 0x00001160 |526 * ------------------------ ---------------------527 *528 * This graph represents the trie for the exports "__mh_execute_header" and529 * "_main". In the graph only the "_main" and "__mh_execute_header" nodes are530 * terminal.531*/532 533const uint8_t *processExportNode(const uint8_t *Start, const uint8_t *CurrPtr,534 const uint8_t *const End,535 MachOYAML::ExportEntry &Entry) {536 if (CurrPtr >= End)537 return CurrPtr;538 unsigned Count = 0;539 Entry.TerminalSize = decodeULEB128(CurrPtr, &Count);540 CurrPtr += Count;541 if (Entry.TerminalSize != 0) {542 Entry.Flags = decodeULEB128(CurrPtr, &Count);543 CurrPtr += Count;544 if (Entry.Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT) {545 Entry.Address = 0;546 Entry.Other = decodeULEB128(CurrPtr, &Count);547 CurrPtr += Count;548 Entry.ImportName = std::string(reinterpret_cast<const char *>(CurrPtr));549 } else {550 Entry.Address = decodeULEB128(CurrPtr, &Count);551 CurrPtr += Count;552 if (Entry.Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {553 Entry.Other = decodeULEB128(CurrPtr, &Count);554 CurrPtr += Count;555 } else556 Entry.Other = 0;557 }558 }559 uint8_t childrenCount = *CurrPtr++;560 if (childrenCount == 0)561 return CurrPtr;562 563 Entry.Children.insert(Entry.Children.begin(), (size_t)childrenCount,564 MachOYAML::ExportEntry());565 for (auto &Child : Entry.Children) {566 Child.Name = std::string(reinterpret_cast<const char *>(CurrPtr));567 CurrPtr += Child.Name.length() + 1;568 Child.NodeOffset = decodeULEB128(CurrPtr, &Count);569 CurrPtr += Count;570 }571 for (auto &Child : Entry.Children) {572 CurrPtr = processExportNode(Start, Start + Child.NodeOffset, End, Child);573 }574 return CurrPtr;575}576 577void MachODumper::dumpExportTrie(std::unique_ptr<MachOYAML::Object> &Y) {578 MachOYAML::LinkEditData &LEData = Y->LinkEdit;579 // The exports trie can be in LC_DYLD_INFO or LC_DYLD_EXPORTS_TRIE580 auto ExportsTrie = Obj.getDyldInfoExportsTrie();581 if (ExportsTrie.empty())582 ExportsTrie = Obj.getDyldExportsTrie();583 processExportNode(ExportsTrie.begin(), ExportsTrie.begin(), ExportsTrie.end(),584 LEData.ExportTrie);585}586 587template <typename nlist_t>588MachOYAML::NListEntry constructNameList(const nlist_t &nlist) {589 MachOYAML::NListEntry NL;590 NL.n_strx = nlist.n_strx;591 NL.n_type = nlist.n_type;592 NL.n_sect = nlist.n_sect;593 NL.n_desc = nlist.n_desc;594 NL.n_value = nlist.n_value;595 return NL;596}597 598void MachODumper::dumpSymbols(std::unique_ptr<MachOYAML::Object> &Y) {599 MachOYAML::LinkEditData &LEData = Y->LinkEdit;600 601 for (auto Symbol : Obj.symbols()) {602 MachOYAML::NListEntry NLE =603 Obj.is64Bit()604 ? constructNameList<MachO::nlist_64>(605 Obj.getSymbol64TableEntry(Symbol.getRawDataRefImpl()))606 : constructNameList<MachO::nlist>(607 Obj.getSymbolTableEntry(Symbol.getRawDataRefImpl()));608 LEData.NameList.push_back(NLE);609 }610 611 StringRef RemainingTable = Obj.getStringTableData();612 while (RemainingTable.size() > 0) {613 auto SymbolPair = RemainingTable.split('\0');614 RemainingTable = SymbolPair.second;615 LEData.StringTable.push_back(SymbolPair.first);616 }617}618 619void MachODumper::dumpIndirectSymbols(std::unique_ptr<MachOYAML::Object> &Y) {620 MachOYAML::LinkEditData &LEData = Y->LinkEdit;621 622 MachO::dysymtab_command DLC = Obj.getDysymtabLoadCommand();623 for (unsigned i = 0; i < DLC.nindirectsyms; ++i)624 LEData.IndirectSymbols.push_back(Obj.getIndirectSymbolTableEntry(DLC, i));625}626 627void MachODumper::dumpChainedFixups(std::unique_ptr<MachOYAML::Object> &Y) {628 MachOYAML::LinkEditData &LEData = Y->LinkEdit;629 630 for (const auto &LC : Y->LoadCommands) {631 if (LC.Data.load_command_data.cmd == llvm::MachO::LC_DYLD_CHAINED_FIXUPS) {632 const MachO::linkedit_data_command &DC =633 LC.Data.linkedit_data_command_data;634 if (DC.dataoff) {635 assert(DC.dataoff < Obj.getData().size());636 assert(DC.dataoff + DC.datasize <= Obj.getData().size());637 const char *Bytes = Obj.getData().data() + DC.dataoff;638 llvm::append_range(LEData.ChainedFixups, ArrayRef(Bytes, DC.datasize));639 }640 break;641 }642 }643}644 645void MachODumper::dumpDataInCode(std::unique_ptr<MachOYAML::Object> &Y) {646 MachOYAML::LinkEditData &LEData = Y->LinkEdit;647 648 MachO::linkedit_data_command DIC = Obj.getDataInCodeLoadCommand();649 uint32_t NumEntries = DIC.datasize / sizeof(MachO::data_in_code_entry);650 for (uint32_t Idx = 0; Idx < NumEntries; ++Idx) {651 MachO::data_in_code_entry DICE =652 Obj.getDataInCodeTableEntry(DIC.dataoff, Idx);653 MachOYAML::DataInCodeEntry Entry{DICE.offset, DICE.length, DICE.kind};654 LEData.DataInCode.emplace_back(Entry);655 }656}657 658Error macho2yaml(raw_ostream &Out, const object::MachOObjectFile &Obj,659 unsigned RawSegments) {660 std::unique_ptr<DWARFContext> DCtx = DWARFContext::create(Obj);661 MachODumper Dumper(Obj, std::move(DCtx), RawSegments);662 Expected<std::unique_ptr<MachOYAML::Object>> YAML = Dumper.dump();663 if (!YAML)664 return YAML.takeError();665 666 yaml::YamlObjectFile YAMLFile;667 YAMLFile.MachO = std::move(YAML.get());668 669 yaml::Output Yout(Out);670 Yout << YAMLFile;671 return Error::success();672}673 674Error macho2yaml(raw_ostream &Out, const object::MachOUniversalBinary &Obj,675 unsigned RawSegments) {676 yaml::YamlObjectFile YAMLFile;677 YAMLFile.FatMachO.reset(new MachOYAML::UniversalBinary());678 MachOYAML::UniversalBinary &YAML = *YAMLFile.FatMachO;679 YAML.Header.magic = Obj.getMagic();680 YAML.Header.nfat_arch = Obj.getNumberOfObjects();681 682 for (auto Slice : Obj.objects()) {683 MachOYAML::FatArch arch;684 arch.cputype = Slice.getCPUType();685 arch.cpusubtype = Slice.getCPUSubType();686 arch.offset = Slice.getOffset();687 arch.size = Slice.getSize();688 arch.align = Slice.getAlign();689 arch.reserved = Slice.getReserved();690 YAML.FatArchs.push_back(arch);691 692 auto SliceObj = Slice.getAsObjectFile();693 if (!SliceObj)694 return SliceObj.takeError();695 696 std::unique_ptr<DWARFContext> DCtx = DWARFContext::create(*SliceObj.get());697 MachODumper Dumper(*SliceObj.get(), std::move(DCtx), RawSegments);698 Expected<std::unique_ptr<MachOYAML::Object>> YAMLObj = Dumper.dump();699 if (!YAMLObj)700 return YAMLObj.takeError();701 YAML.Slices.push_back(*YAMLObj.get());702 }703 704 yaml::Output Yout(Out);705 Yout << YAML;706 return Error::success();707}708 709Error macho2yaml(raw_ostream &Out, const object::Binary &Binary,710 unsigned RawSegments) {711 if (const auto *MachOObj = dyn_cast<object::MachOUniversalBinary>(&Binary))712 return macho2yaml(Out, *MachOObj, RawSegments);713 714 if (const auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Binary))715 return macho2yaml(Out, *MachOObj, RawSegments);716 717 llvm_unreachable("unexpected Mach-O file format");718}719