#include "macho_reader.hpp" #include #include #include namespace voidlibc::voidlink::macho { namespace { // --------------------------------------------------------------------------- // On-disk Mach-O structures (packed, little-endian) // --------------------------------------------------------------------------- struct MachHeader64 { std::uint32_t magic; std::uint32_t cputype; std::uint32_t cpusubtype; std::uint32_t filetype; std::uint32_t ncmds; std::uint32_t sizeofcmds; std::uint32_t flags; std::uint32_t reserved; }; struct LoadCommand { std::uint32_t cmd; std::uint32_t cmdsize; }; struct SegmentCommand64 { std::uint32_t cmd; std::uint32_t cmdsize; char segname[16]; std::uint64_t vmaddr; std::uint64_t vmsize; std::uint64_t fileoff; std::uint64_t filesize; std::uint32_t maxprot; std::uint32_t initprot; std::uint32_t nsects; std::uint32_t flags; }; struct Section64 { char sectname[16]; char segname[16]; std::uint64_t addr; std::uint64_t size; std::uint32_t offset; std::uint32_t align; std::uint32_t reloff; std::uint32_t nreloc; std::uint32_t flags; std::uint32_t reserved1; std::uint32_t reserved2; std::uint32_t reserved3; }; struct SymtabCommand { std::uint32_t cmd; std::uint32_t cmdsize; std::uint32_t symoff; std::uint32_t nsyms; std::uint32_t stroff; std::uint32_t strsize; }; struct NList64 { std::uint32_t n_strx; std::uint8_t n_type; std::uint8_t n_sect; std::uint16_t n_desc; std::uint64_t n_value; }; // Relocation info (compact 8-byte form; bit 31 of r_address → scattered, but // x86_64 object files never use scattered relocations). struct RelocationInfo { std::int32_t r_address; std::uint32_t r_info; // [23:0]=symbolnum, [24]=pcrel, [26:25]=length, [27]=extern, [31:28]=type }; // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- static std::string trim_null(const char* s, std::size_t maxlen) { std::size_t len = 0; while (len < maxlen && s[len]) ++len; return std::string(s, len); } static std::int64_t read_inline_addend(const std::uint8_t* data, std::size_t file_size, std::uint64_t sec_offset, std::uint32_t reloc_offset, std::uint32_t length) { const std::uint64_t pos = sec_offset + reloc_offset; if (length == 2 && pos + 4 <= file_size) { std::int32_t v = 0; std::memcpy(&v, data + pos, 4); return v; } if (length == 3 && pos + 8 <= file_size) { std::int64_t v = 0; std::memcpy(&v, data + pos, 8); return v; } return 0; } } // namespace // --------------------------------------------------------------------------- // Public parser // --------------------------------------------------------------------------- ParseResult parse_macho_object(const std::filesystem::path& path) { std::ifstream f(path, std::ios::binary | std::ios::ate); if (!f) return ParseError{"cannot open: " + path.string()}; const auto fsz = static_cast(f.tellg()); f.seekg(0); std::vector buf(fsz); f.read(reinterpret_cast(buf.data()), static_cast(fsz)); if (!f) return ParseError{"read failed: " + path.string()}; if (fsz < sizeof(MachHeader64)) return ParseError{"file too small"}; MachHeader64 hdr{}; std::memcpy(&hdr, buf.data(), sizeof(hdr)); if (hdr.magic != kMagic64) return ParseError{"not a 64-bit little-endian Mach-O"}; if (hdr.cputype != kCpuX86_64) return ParseError{"not x86_64 (cputype=0x" + std::to_string(hdr.cputype) + ")"}; if (hdr.filetype != kMhObject) return ParseError{"not an object file (filetype=" + std::to_string(hdr.filetype) + ")"}; ParsedObject obj; std::uint32_t strtab_off = 0, strtab_size = 0; std::uint32_t symtab_off = 0, nsyms = 0; // Walk load commands. std::size_t lc_pos = sizeof(MachHeader64); for (std::uint32_t ci = 0; ci < hdr.ncmds; ++ci) { if (lc_pos + sizeof(LoadCommand) > fsz) return ParseError{"load command truncated"}; LoadCommand lc{}; std::memcpy(&lc, buf.data() + lc_pos, sizeof(lc)); if (lc.cmdsize < sizeof(LoadCommand) || lc_pos + lc.cmdsize > fsz) return ParseError{"bad load command size"}; if (lc.cmd == 0x19 /* LC_SEGMENT_64 */) { if (lc.cmdsize < sizeof(SegmentCommand64)) return ParseError{"LC_SEGMENT_64 too small"}; SegmentCommand64 seg{}; std::memcpy(&seg, buf.data() + lc_pos, sizeof(seg)); const std::size_t sec_base = lc_pos + sizeof(SegmentCommand64); for (std::uint32_t si = 0; si < seg.nsects; ++si) { const std::size_t sec_off = sec_base + si * sizeof(Section64); if (sec_off + sizeof(Section64) > fsz) return ParseError{"section header truncated"}; Section64 sec{}; std::memcpy(&sec, buf.data() + sec_off, sizeof(sec)); ParsedSection ps; ps.segname = trim_null(sec.segname, 16); ps.sectname = trim_null(sec.sectname, 16); ps.flags = sec.flags; ps.mem_size = sec.size; ps.addr = sec.addr; ps.align_exp = sec.align; // Read section data. if (sec.offset > 0 && sec.size > 0) { if (sec.offset + sec.size > fsz) return ParseError{"section data truncated: " + ps.sectname}; ps.bytes.assign(buf.data() + sec.offset, buf.data() + sec.offset + sec.size); } else { ps.bytes.assign(sec.size, 0); // BSS-like } // Read relocations for this section. if (sec.nreloc > 0) { if (sec.reloff + sec.nreloc * sizeof(RelocationInfo) > fsz) return ParseError{"reloc table truncated"}; for (std::uint32_t ri = 0; ri < sec.nreloc; ++ri) { RelocationInfo ri_raw{}; std::memcpy(&ri_raw, buf.data() + sec.reloff + ri * sizeof(RelocationInfo), sizeof(ri_raw)); // Scattered relocs (bit31 set) are not used on x86_64. if (ri_raw.r_address < 0) return ParseError{"scattered reloc in x86_64 object (unexpected)"}; const std::uint32_t sym_num = ri_raw.r_info & 0x00FFFFFFu; const bool is_pcrel = (ri_raw.r_info >> 24) & 1; const std::uint32_t length = (ri_raw.r_info >> 25) & 3; const bool is_extern = (ri_raw.r_info >> 27) & 1; const std::uint32_t rtype = (ri_raw.r_info >> 28) & 0xFu; // Read inline addend from the section bytes. const auto addend = read_inline_addend( buf.data(), fsz, sec.offset, static_cast(ri_raw.r_address), length); ParsedRelocation pr; pr.offset = static_cast(ri_raw.r_address); pr.sym_index = sym_num; pr.type = rtype; pr.addend = addend; pr.is_extern = is_extern; pr.is_pcrel = is_pcrel; pr.length = length; ps.relocs.push_back(pr); } } obj.sections.push_back(std::move(ps)); } } else if (lc.cmd == 0x02 /* LC_SYMTAB */) { if (lc.cmdsize < sizeof(SymtabCommand)) return ParseError{"LC_SYMTAB too small"}; SymtabCommand sc{}; std::memcpy(&sc, buf.data() + lc_pos, sizeof(sc)); symtab_off = sc.symoff; nsyms = sc.nsyms; strtab_off = sc.stroff; strtab_size = sc.strsize; } lc_pos += lc.cmdsize; } // Parse symbol table. if (nsyms > 0) { if (symtab_off + nsyms * sizeof(NList64) > fsz) return ParseError{"symbol table truncated"}; if (strtab_off + strtab_size > fsz) return ParseError{"string table truncated"}; const char* strtab = reinterpret_cast(buf.data() + strtab_off); for (std::uint32_t si = 0; si < nsyms; ++si) { NList64 nl{}; std::memcpy(&nl, buf.data() + symtab_off + si * sizeof(NList64), sizeof(nl)); // Skip debug/stab entries. if (nl.n_type & kNTypeStab) continue; ParsedSymbol ps; // Name: index into string table (n_strx=0 means empty name). if (nl.n_strx > 0 && nl.n_strx < strtab_size) { // Mach-O symbol names have a leading underscore by convention; // strip it so callers see C names. const char* raw = strtab + nl.n_strx; if (raw[0] == '_') ++raw; ps.name = raw; } const std::uint8_t ntype = nl.n_type & kNTypeMask; ps.defined = (ntype == kNTypeSect); ps.section_index = ps.defined ? nl.n_sect : 0; // 1-based ps.value = nl.n_value; // In .o files, n_value for N_SECT is the address within the // section's vm range; for object files that start at 0, this IS // the section-relative offset. // Subtract the section's vmaddr to get a real section offset. if (ps.defined && nl.n_sect >= 1 && static_cast(nl.n_sect - 1) < obj.sections.size()) { // We don't have vmaddr stored in ParsedSection yet; for .o // files the vmaddr is usually 0 per section, so n_value IS // the offset. Store it as-is; lower_macho_text will verify. } // External bit determines visibility. if (nl.n_type & kNExternal) { ps.bind = 1; // global } else { ps.bind = 0; // local } // Type: check if N_SECT symbol is in a text section (code). if (ps.defined && nl.n_sect >= 1 && static_cast(nl.n_sect - 1) < obj.sections.size()) { const auto& sec = obj.sections[nl.n_sect - 1]; const bool in_text = (sec.sectname == "__text") || (sec.flags & 0x00000400u) /* some_instructions */ || (sec.flags & 0x80000000u) /* pure_instructions */; ps.type = in_text ? 2 : 0; // 2 = kTypeFunc } // Undefined (import) symbols. if (!ps.defined && (nl.n_type & kNExternal)) { ps.bind = 1; } obj.symbols.push_back(std::move(ps)); } } // Locate the primary __text section. for (std::size_t i = 0; i < obj.sections.size(); ++i) { if (obj.sections[i].sectname == "__text") { obj.text_index = i; break; } } if (obj.text_index == static_cast(-1)) return ParseError{"no __text section found"}; return obj; } } // namespace voidlibc::voidlink::macho