319 lines
12 KiB
C++
319 lines
12 KiB
C++
#include "coff_reader.hpp"
|
|
|
|
#include <cstring>
|
|
#include <fstream>
|
|
#include <sstream>
|
|
|
|
namespace voidlibc::voidlink::coff {
|
|
|
|
namespace {
|
|
|
|
std::string err(std::string s) { return s; }
|
|
|
|
bool read_file(const std::filesystem::path& path, std::vector<std::uint8_t>& out) {
|
|
std::ifstream in(path, std::ios::binary | std::ios::ate);
|
|
if (!in) return false;
|
|
const auto sz = static_cast<std::streamsize>(in.tellg());
|
|
in.seekg(0, std::ios::beg);
|
|
out.resize(static_cast<std::size_t>(sz));
|
|
in.read(reinterpret_cast<char*>(out.data()), sz);
|
|
return static_cast<bool>(in);
|
|
}
|
|
|
|
template<typename T>
|
|
bool read_at(const std::vector<std::uint8_t>& buf, std::size_t off, T& out) {
|
|
if (off + sizeof(T) > buf.size()) return false;
|
|
std::memcpy(&out, buf.data() + off, sizeof(T));
|
|
return true;
|
|
}
|
|
|
|
// COFF on-disk structures (packed, little-endian).
|
|
#pragma pack(push, 1)
|
|
|
|
struct FileHeader {
|
|
std::uint16_t Machine;
|
|
std::uint16_t NumberOfSections;
|
|
std::uint32_t TimeDateStamp;
|
|
std::uint32_t PointerToSymbolTable;
|
|
std::uint32_t NumberOfSymbols;
|
|
std::uint16_t SizeOfOptionalHeader;
|
|
std::uint16_t Characteristics;
|
|
};
|
|
static_assert(sizeof(FileHeader) == 20);
|
|
|
|
struct SectionHeader {
|
|
char Name[8];
|
|
std::uint32_t VirtualSize;
|
|
std::uint32_t VirtualAddress;
|
|
std::uint32_t SizeOfRawData;
|
|
std::uint32_t PointerToRawData;
|
|
std::uint32_t PointerToRelocations;
|
|
std::uint32_t PointerToLinenumbers;
|
|
std::uint16_t NumberOfRelocations;
|
|
std::uint16_t NumberOfLinenumbers;
|
|
std::uint32_t Characteristics;
|
|
};
|
|
static_assert(sizeof(SectionHeader) == 40);
|
|
|
|
struct Symbol {
|
|
union {
|
|
char ShortName[8];
|
|
struct { std::uint32_t Zeros; std::uint32_t Offset; } LongName;
|
|
} N;
|
|
std::uint32_t Value;
|
|
std::int16_t SectionNumber;
|
|
std::uint16_t Type;
|
|
std::uint8_t StorageClass;
|
|
std::uint8_t NumberOfAuxSymbols;
|
|
};
|
|
static_assert(sizeof(Symbol) == 18);
|
|
|
|
struct Relocation {
|
|
std::uint32_t VirtualAddress;
|
|
std::uint32_t SymbolTableIndex;
|
|
std::uint16_t Type;
|
|
};
|
|
static_assert(sizeof(Relocation) == 10);
|
|
|
|
#pragma pack(pop)
|
|
|
|
constexpr std::uint16_t kMachineAmd64 = 0x8664;
|
|
|
|
// COFF symbol storage classes
|
|
constexpr std::uint8_t kStorExternal = 2;
|
|
constexpr std::uint8_t kStorStatic = 3;
|
|
constexpr std::uint8_t kStorWeakExternal = 105;
|
|
|
|
// Extract section name (may use string-table indirection for >8-char names).
|
|
std::string section_name(const SectionHeader& sh,
|
|
const char* strtab, std::size_t strtab_size) {
|
|
if (sh.Name[0] == '/') {
|
|
// Long name: "/<offset>" into string table.
|
|
char buf[9] = {};
|
|
std::memcpy(buf, sh.Name + 1, 7);
|
|
const auto off = static_cast<std::size_t>(std::strtoul(buf, nullptr, 10));
|
|
if (strtab && off < strtab_size)
|
|
return std::string(strtab + off);
|
|
}
|
|
// Short name (up to 8 chars, NOT necessarily null-terminated).
|
|
const std::size_t len = strnlen(sh.Name, 8);
|
|
return std::string(sh.Name, len);
|
|
}
|
|
|
|
// Extract symbol name.
|
|
std::string symbol_name(const Symbol& sym,
|
|
const char* strtab, std::size_t strtab_size) {
|
|
if (sym.N.LongName.Zeros == 0) {
|
|
const auto off = static_cast<std::size_t>(sym.N.LongName.Offset);
|
|
if (strtab && off < strtab_size)
|
|
return std::string(strtab + off);
|
|
return {};
|
|
}
|
|
const std::size_t len = strnlen(sym.N.ShortName, 8);
|
|
return std::string(sym.N.ShortName, len);
|
|
}
|
|
|
|
// Read an inline addend from the code: 4 bytes for 32-bit relocs, 8 for 64-bit.
|
|
std::int64_t read_inline4(const std::vector<std::uint8_t>& sec_bytes, std::uint32_t off) {
|
|
if (off + 4 > sec_bytes.size()) return 0;
|
|
std::int32_t v;
|
|
std::memcpy(&v, sec_bytes.data() + off, 4);
|
|
return v;
|
|
}
|
|
std::int64_t read_inline8(const std::vector<std::uint8_t>& sec_bytes, std::uint32_t off) {
|
|
if (off + 8 > sec_bytes.size()) return 0;
|
|
std::int64_t v;
|
|
std::memcpy(&v, sec_bytes.data() + off, 8);
|
|
return v;
|
|
}
|
|
|
|
} // namespace
|
|
|
|
ParseResult parse_coff_object(const std::filesystem::path& path) {
|
|
std::vector<std::uint8_t> buf;
|
|
if (!read_file(path, buf))
|
|
return err("cannot read " + path.string());
|
|
|
|
FileHeader fh{};
|
|
if (!read_at(buf, 0, fh))
|
|
return err("file too small for COFF header");
|
|
|
|
if (fh.Machine != kMachineAmd64)
|
|
return err("not an x86-64 COFF object (machine 0x"
|
|
+ [&]{ std::ostringstream o; o << std::hex << fh.Machine; return o.str(); }() + ")");
|
|
|
|
if (fh.SizeOfOptionalHeader != 0)
|
|
return err("file has optional header — expected a .obj (ET_REL equivalent), not a PE image");
|
|
|
|
// Section headers follow the file header.
|
|
const std::size_t shdrs_off = sizeof(FileHeader);
|
|
if (shdrs_off + fh.NumberOfSections * sizeof(SectionHeader) > buf.size())
|
|
return err("section header table truncated");
|
|
|
|
// String table starts right after the symbol table.
|
|
const std::size_t symtab_off = fh.PointerToSymbolTable;
|
|
const std::size_t symtab_bytes = fh.NumberOfSymbols * sizeof(Symbol);
|
|
const std::size_t strtab_off = symtab_off + symtab_bytes;
|
|
std::uint32_t strtab_size32 = 0;
|
|
const char* strtab = nullptr;
|
|
std::size_t strtab_size = 0;
|
|
if (strtab_off + 4 <= buf.size()) {
|
|
std::memcpy(&strtab_size32, buf.data() + strtab_off, 4);
|
|
strtab_size = static_cast<std::size_t>(strtab_size32);
|
|
if (strtab_off + strtab_size <= buf.size())
|
|
strtab = reinterpret_cast<const char*>(buf.data() + strtab_off);
|
|
}
|
|
|
|
ParsedObject obj;
|
|
obj.sections.resize(fh.NumberOfSections);
|
|
|
|
// First pass: read sections.
|
|
for (std::uint16_t i = 0; i < fh.NumberOfSections; ++i) {
|
|
SectionHeader sh{};
|
|
std::memcpy(&sh, buf.data() + shdrs_off + i * sizeof(SectionHeader), sizeof(sh));
|
|
|
|
auto& ps = obj.sections[i];
|
|
ps.name = section_name(sh, strtab, strtab_size);
|
|
ps.characteristics = sh.Characteristics;
|
|
ps.mem_size = sh.SizeOfRawData; // for BSS: SizeOfRawData=0, VirtualSize has the size
|
|
|
|
// BSS: SizeOfRawData==0 but VirtualSize may be non-zero.
|
|
if (sh.SizeOfRawData == 0) {
|
|
ps.mem_size = sh.VirtualSize;
|
|
} else if (sh.PointerToRawData != 0) {
|
|
if (sh.PointerToRawData + sh.SizeOfRawData > buf.size()) {
|
|
std::ostringstream os;
|
|
os << "section " << ps.name << " raw data out of range";
|
|
return err(os.str());
|
|
}
|
|
ps.bytes.assign(buf.data() + sh.PointerToRawData,
|
|
buf.data() + sh.PointerToRawData + sh.SizeOfRawData);
|
|
}
|
|
|
|
// Identify primary .text section.
|
|
if (ps.name == ".text"
|
|
&& (ps.characteristics & kScnCntCode)
|
|
&& obj.text_index == static_cast<std::size_t>(-1)) {
|
|
obj.text_index = i;
|
|
}
|
|
}
|
|
|
|
// Second pass: read symbol table.
|
|
// COFF symbols are 18 bytes each; auxiliary symbol records follow inline.
|
|
// Symbol table index used by relocs maps directly to obj.symbols indices,
|
|
// so we keep a parallel "coff_idx → obj_sym_idx" map.
|
|
std::vector<std::uint32_t> coff_to_obj(fh.NumberOfSymbols,
|
|
static_cast<std::uint32_t>(-1));
|
|
if (symtab_off != 0 && symtab_bytes <= buf.size() - symtab_off) {
|
|
std::uint32_t ci = 0;
|
|
while (ci < fh.NumberOfSymbols) {
|
|
Symbol sym{};
|
|
std::memcpy(&sym, buf.data() + symtab_off + ci * sizeof(Symbol), sizeof(sym));
|
|
|
|
const std::uint32_t obj_idx = static_cast<std::uint32_t>(obj.symbols.size());
|
|
coff_to_obj[ci] = obj_idx;
|
|
// Also map auxiliary record indices to the same obj symbol (they may be
|
|
// referenced by some relocs, though rarely).
|
|
for (std::uint8_t a = 0; a < sym.NumberOfAuxSymbols && ci + 1 + a < fh.NumberOfSymbols; ++a)
|
|
coff_to_obj[ci + 1 + a] = obj_idx;
|
|
|
|
ParsedSymbol ps{};
|
|
ps.name = symbol_name(sym, strtab, strtab_size);
|
|
ps.value = sym.Value;
|
|
ps.size = 0; // COFF doesn't store symbol size in the base record
|
|
|
|
const bool is_absolute = (sym.SectionNumber == -1);
|
|
const bool is_undef = (sym.SectionNumber == 0);
|
|
const bool is_debug = (sym.SectionNumber == -2);
|
|
(void)is_debug;
|
|
|
|
if (!is_undef && !is_absolute) {
|
|
const int sec1 = static_cast<int>(sym.SectionNumber) - 1;
|
|
if (sec1 >= 0 && sec1 < fh.NumberOfSections) {
|
|
ps.section_index = static_cast<std::uint32_t>(sec1 + 1);
|
|
ps.defined = true;
|
|
}
|
|
}
|
|
|
|
// Normalize bind / type.
|
|
if (sym.StorageClass == kStorExternal)
|
|
ps.bind = kBindGlobal;
|
|
else if (sym.StorageClass == kStorWeakExternal)
|
|
ps.bind = kBindWeak;
|
|
else
|
|
ps.bind = kBindLocal;
|
|
|
|
// COFF type: high byte = complex type (0=none, 1=pointer, 2=function, 3=array)
|
|
// low byte = base type
|
|
// type >> 4 = 2 means "function".
|
|
if ((sym.Type >> 4) == 2)
|
|
ps.type = kTypeFunc;
|
|
else if (sym.StorageClass == kStorStatic && sym.Value == 0 && sym.NumberOfAuxSymbols > 0)
|
|
ps.type = kTypeSection; // section symbol
|
|
else
|
|
ps.type = kTypeNone;
|
|
|
|
obj.symbols.push_back(std::move(ps));
|
|
ci += 1 + sym.NumberOfAuxSymbols;
|
|
}
|
|
}
|
|
|
|
// Third pass: read relocations (stored per section).
|
|
for (std::uint16_t i = 0; i < fh.NumberOfSections; ++i) {
|
|
SectionHeader sh{};
|
|
std::memcpy(&sh, buf.data() + shdrs_off + i * sizeof(SectionHeader), sizeof(sh));
|
|
|
|
if (sh.NumberOfRelocations == 0 || sh.PointerToRelocations == 0)
|
|
continue;
|
|
|
|
const std::size_t relocs_off = sh.PointerToRelocations;
|
|
const std::size_t nrelocs = sh.NumberOfRelocations;
|
|
if (relocs_off + nrelocs * sizeof(Relocation) > buf.size()) {
|
|
std::ostringstream os;
|
|
os << "section " << obj.sections[i].name << " relocations out of range";
|
|
return err(os.str());
|
|
}
|
|
|
|
auto& sec = obj.sections[i];
|
|
sec.relocs.reserve(nrelocs);
|
|
for (std::size_t ri = 0; ri < nrelocs; ++ri) {
|
|
Relocation r{};
|
|
std::memcpy(&r, buf.data() + relocs_off + ri * sizeof(Relocation), sizeof(r));
|
|
|
|
if (r.SymbolTableIndex >= fh.NumberOfSymbols)
|
|
continue;
|
|
|
|
const std::uint32_t obj_sym_idx = coff_to_obj[r.SymbolTableIndex];
|
|
if (obj_sym_idx == static_cast<std::uint32_t>(-1))
|
|
continue;
|
|
|
|
ParsedRelocation pr{};
|
|
pr.offset = r.VirtualAddress;
|
|
pr.sym_index = obj_sym_idx;
|
|
pr.type = r.Type;
|
|
|
|
// Read inline addend from the code bytes.
|
|
switch (r.Type) {
|
|
case kRelocAddr64:
|
|
pr.addend = read_inline8(sec.bytes, r.VirtualAddress);
|
|
break;
|
|
case kRelocRel32: case kRelocRel32_1: case kRelocRel32_2:
|
|
case kRelocRel32_3: case kRelocRel32_4: case kRelocRel32_5:
|
|
case kRelocAddr32: case kRelocAddr32NB:
|
|
case kRelocSecRel:
|
|
pr.addend = read_inline4(sec.bytes, r.VirtualAddress);
|
|
break;
|
|
default:
|
|
pr.addend = 0;
|
|
break;
|
|
}
|
|
|
|
sec.relocs.push_back(pr);
|
|
}
|
|
}
|
|
|
|
return obj;
|
|
}
|
|
|
|
} // namespace voidlibc::voidlink::coff
|