initial commit

Signed-off-by: Aleksey Selihov <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-05-22 02:40:32 +03:00
commit bba5c8a39a
109 files changed
+14085

No files matched your search

+26
View File
@@ -0,0 +1,26 @@
add_executable(voidlink
main.cpp
writer.cpp
reader.cpp
builder.cpp
elf_reader.cpp
coff_reader.cpp
macho_reader.cpp
reloc_lowering.cpp
merge.cpp
symlib_table.cpp
# Synthesis: produce native blobs at pack time so ldd/file work on .vlc
${CMAKE_SOURCE_DIR}/loader/common/elf_synth.cpp
${CMAKE_SOURCE_DIR}/loader/windows/pe_synth.cpp
${CMAKE_SOURCE_DIR}/loader/macos/macho_synth.cpp
)
target_link_libraries(voidlink PRIVATE voidlibc_format)
target_include_directories(voidlink PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_SOURCE_DIR}
)
install(TARGETS voidlink
EXPORT VoidLibCTargets
RUNTIME DESTINATION bin
)
+257
View File
@@ -0,0 +1,257 @@
#include "builder.hpp"
#include "writer.hpp"
#include <cstring>
#include <fstream>
namespace voidlibc::voidlink {
using namespace voidlibc::format;
std::uint32_t ContainerBuilder::add_symbol(SymbolSpec spec) {
const auto id = static_cast<std::uint32_t>(symbols_.size());
symbols_.push_back(std::move(spec));
return id;
}
void ContainerBuilder::add_section(SectionSpec section) {
sections_.push_back(std::move(section));
}
namespace {
constexpr std::uint64_t align_up(std::uint64_t v, std::uint64_t a) {
return (v + (a - 1)) & ~(a - 1);
}
struct LayoutPlan {
std::uint64_t header_off = 0;
std::uint64_t section_dir_off = 0;
std::uint64_t symtab_off = 0;
std::uint64_t symtab_size = 0;
std::vector<std::uint64_t> reloc_offs;
std::vector<std::uint64_t> code_offs;
std::vector<std::uint64_t> data_offs; // writable data blob offsets
std::uint64_t file_size = 0;
// Computed name-pool data so the writer doesn't recompute it.
std::vector<char> name_pool;
std::vector<SymbolEntry> sym_entries;
};
void plan_layout(const std::vector<SymbolSpec>& symbols,
const std::vector<SectionSpec>& sections,
LayoutPlan& plan) {
plan.header_off = 0;
plan.section_dir_off = sizeof(FileHeader);
const auto sec_dir_end =
plan.section_dir_off + sections.size() * sizeof(SectionEntry);
// --- Symbol table: header + entries + name pool ---
plan.symtab_off = align_up(sec_dir_end, 8);
auto append_name = [&](std::string_view s,
std::uint32_t& off,
std::uint32_t& len) {
if (s.empty()) { off = 0; len = 0; return; }
off = static_cast<std::uint32_t>(plan.name_pool.size());
len = static_cast<std::uint32_t>(s.size());
plan.name_pool.insert(plan.name_pool.end(), s.begin(), s.end());
};
plan.sym_entries.reserve(symbols.size());
for (const auto& s : symbols) {
SymbolEntry e{};
append_name(s.name, e.name_off, e.name_len);
append_name(s.itanium_name, e.itanium_name_off, e.itanium_name_len);
append_name(s.msvc_name, e.msvc_name_off, e.msvc_name_len);
e.value = s.value;
e.size = s.size;
e.section_index = s.section_index;
e.kind = s.kind;
std::uint8_t flags = 0;
if (s.exported) flags |= static_cast<std::uint8_t>(SymbolFlags::Exported);
if (s.weak) flags |= static_cast<std::uint8_t>(SymbolFlags::Weak);
if (s.hidden) flags |= static_cast<std::uint8_t>(SymbolFlags::Hidden);
if (s.data_section) flags |= static_cast<std::uint8_t>(SymbolFlags::DataSection);
e.flags = flags;
e.reserved = 0;
plan.sym_entries.push_back(e);
}
const auto symtab_body =
sizeof(SymbolTableHeader)
+ plan.sym_entries.size() * sizeof(SymbolEntry)
+ plan.name_pool.size();
plan.symtab_size = symtab_body;
std::uint64_t cursor = align_up(plan.symtab_off + symtab_body, 8);
// --- Per-section reloc chunks (NativeBlob sections have none) ---
plan.reloc_offs.reserve(sections.size());
for (const auto& sec : sections) {
if (sec.kind == SectionKind::NativeBlob || sec.relocs.empty()) {
plan.reloc_offs.push_back(0);
} else {
plan.reloc_offs.push_back(cursor);
cursor = align_up(cursor + sizeof(RelocChunk)
+ sec.relocs.size() * sizeof(RelocEntry), 16);
}
}
// --- Per-section code ---
plan.code_offs.reserve(sections.size());
for (const auto& sec : sections) {
cursor = align_up(cursor, 16);
plan.code_offs.push_back(cursor);
cursor += sec.code.size();
}
// --- Per-section writable data blob (optional) ---
plan.data_offs.reserve(sections.size());
for (const auto& sec : sections) {
if (!sec.data.empty()) {
cursor = align_up(cursor, 16);
plan.data_offs.push_back(cursor);
cursor += sec.data.size();
} else {
plan.data_offs.push_back(0);
}
}
plan.file_size = cursor;
}
} // namespace
WriteResult ContainerBuilder::write(const std::filesystem::path& out_path) const {
LayoutPlan plan;
plan_layout(symbols_, sections_, plan);
std::ofstream out(out_path, std::ios::binary | std::ios::trunc);
if (!out) {
return {false, "could not open output: " + out_path.string()};
}
auto seek = [&](std::uint64_t off) {
out.seekp(static_cast<std::streamoff>(off));
};
auto write_raw = [&](const void* p, std::size_t n) {
out.write(reinterpret_cast<const char*>(p), static_cast<std::streamsize>(n));
};
auto pad_to = [&](std::uint64_t off) {
const auto cur = static_cast<std::uint64_t>(out.tellp());
if (cur < off) {
std::vector<char> zeros(off - cur, 0);
write_raw(zeros.data(), zeros.size());
}
};
// --- FileHeader ---
FileHeader hdr{};
hdr.magic = kMagic;
hdr.version_major = kVersionMajor;
hdr.version_minor = kVersionMinor;
std::uint32_t flags = static_cast<std::uint32_t>(ContainerFlags::None);
if (is_executable_) flags |= static_cast<std::uint32_t>(ContainerFlags::Executable);
if (is_static_library_) flags |= static_cast<std::uint32_t>(ContainerFlags::StaticLibrary);
// Set HasDynamicImports if any symbol is an import (undefined section).
for (const auto& sym : symbols_) {
if (sym.section_index == kSymUndefined) {
flags |= static_cast<std::uint32_t>(ContainerFlags::HasDynamicImports);
break;
}
}
hdr.flags = flags;
hdr.arch = TargetArch::X86_64;
hdr.reserved = 0;
hdr.section_count = static_cast<std::uint32_t>(sections_.size());
hdr.section_dir_off = plan.section_dir_off;
hdr.symtab_off = plan.symtab_off;
hdr.symtab_size = plan.symtab_size;
hdr.imports_off = plan.symtab_off; // placeholder until M1
hdr.imports_size = 0;
hdr.exports_off = plan.symtab_off; // placeholder until M1
hdr.exports_size = 0;
hdr.file_size = plan.file_size;
seek(0);
write_raw(&hdr, sizeof(hdr));
// --- Section directory ---
seek(plan.section_dir_off);
for (std::size_t i = 0; i < sections_.size(); ++i) {
const auto& s = sections_[i];
SectionEntry e{};
e.target_os = s.target_os;
e.kind = s.kind;
e.reserved1 = 0;
e.code_off = plan.code_offs[i];
e.code_size = s.code.size();
if (s.kind == SectionKind::NativeBlob || s.relocs.empty()) {
e.reloc_off = 0;
e.reloc_size = 0;
} else {
e.reloc_off = plan.reloc_offs[i];
e.reloc_size = sizeof(RelocChunk) + s.relocs.size() * sizeof(RelocEntry);
}
e.data_off = plan.data_offs[i];
e.data_size = s.data.size();
e.entry_offset = s.entry_offset;
write_raw(&e, sizeof(e));
}
// --- Symbol table ---
pad_to(plan.symtab_off);
SymbolTableHeader sth{};
sth.entry_count = static_cast<std::uint32_t>(plan.sym_entries.size());
sth.name_pool_size = static_cast<std::uint32_t>(plan.name_pool.size());
write_raw(&sth, sizeof(sth));
if (!plan.sym_entries.empty()) {
write_raw(plan.sym_entries.data(),
plan.sym_entries.size() * sizeof(SymbolEntry));
}
if (!plan.name_pool.empty()) {
write_raw(plan.name_pool.data(), plan.name_pool.size());
}
// --- Per-section reloc chunks (skipped for NativeBlob sections) ---
for (std::size_t i = 0; i < sections_.size(); ++i) {
const auto& s = sections_[i];
if (s.kind == SectionKind::NativeBlob || plan.reloc_offs[i] == 0) continue;
pad_to(plan.reloc_offs[i]);
RelocChunk rc{};
rc.target_os = s.target_os;
rc.reserved0 = 0;
rc.entry_count = static_cast<std::uint32_t>(s.relocs.size());
write_raw(&rc, sizeof(rc));
if (!s.relocs.empty()) {
write_raw(s.relocs.data(),
s.relocs.size() * sizeof(RelocEntry));
}
}
// --- Per-section code ---
for (std::size_t i = 0; i < sections_.size(); ++i) {
pad_to(plan.code_offs[i]);
if (!sections_[i].code.empty()) {
write_raw(sections_[i].code.data(), sections_[i].code.size());
}
}
// --- Per-section writable data blob ---
for (std::size_t i = 0; i < sections_.size(); ++i) {
if (plan.data_offs[i] != 0) {
pad_to(plan.data_offs[i]);
write_raw(sections_[i].data.data(), sections_[i].data.size());
}
}
pad_to(plan.file_size);
if (!out) {
return {false, "write failed"};
}
return {true, {}};
}
} // namespace voidlibc::voidlink
+80
View File
@@ -0,0 +1,80 @@
#pragma once
#include "format/reloc_ir.hpp"
#include "format/vlc_format.hpp"
#include "writer.hpp"
#include <cstdint>
#include <filesystem>
#include <string>
#include <vector>
namespace voidlibc::voidlink {
struct SymbolSpec {
std::string name; // canonical (C) name
std::string itanium_name; // empty if not C++ Itanium
std::string msvc_name; // empty if not C++ MSVC
voidlibc::format::SymbolKind kind = voidlibc::format::SymbolKind::Function;
std::uint64_t value = 0; // offset within owning blob (code or data)
std::uint64_t size = 0;
std::uint16_t section_index = voidlibc::format::kSymUndefined;
bool exported = true;
bool weak = false;
bool hidden = false;
bool data_section = false; // lives in data blob, not code blob
// For undefined (imported) symbols: which host library provides this symbol.
// Populated by voidlink at synthesis time from symlib_table or --symlib overrides.
// Empty means "use per-OS default libc".
std::string library;
// GNU symbol version requirement forwarded from input .o (SHT_GNU_versym + verneed).
// Empty version_name means no version requirement (emit VER_NDX_GLOBAL in .gnu.version).
std::string version_name;
std::uint32_t version_hash = 0;
std::uint16_t version_flags = 0;
};
struct SectionSpec {
voidlibc::format::TargetOS target_os;
voidlibc::format::SectionKind kind = voidlibc::format::SectionKind::RawCode;
std::vector<std::uint8_t> code; // raw PIC code (RawCode) or native blob (NativeBlob)
std::vector<voidlibc::format::RelocEntry> relocs; // empty when kind == NativeBlob
std::uint64_t entry_offset = 0;
std::vector<std::uint8_t> data; // .data + .bss zeros (RW); unused for NativeBlob
};
class ContainerBuilder {
public:
// Mark the container as an executable with the given entry symbol name.
// Exactly one section should have entry_offset != 0 to match this.
void set_executable(std::string entry_symbol) {
is_executable_ = true;
entry_symbol_ = std::move(entry_symbol);
}
void set_static_library() {
is_static_library_ = true;
}
// Returns the assigned symbol id (index into the symbol table).
std::uint32_t add_symbol(SymbolSpec spec);
void add_section(SectionSpec section);
std::uint32_t symbol_count() const { return static_cast<std::uint32_t>(symbols_.size()); }
std::uint16_t section_count() const { return static_cast<std::uint16_t>(sections_.size()); }
// Serialize to disk. Lays out: FileHeader → section directory →
// symbol table → per-section reloc chunks → per-section code →
// per-section debug. file_size is computed.
WriteResult write(const std::filesystem::path& out_path) const;
private:
std::vector<SymbolSpec> symbols_;
std::vector<SectionSpec> sections_;
bool is_executable_ = false;
bool is_static_library_ = false;
std::string entry_symbol_;
};
} // namespace voidlibc::voidlink
+318
View File
@@ -0,0 +1,318 @@
#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
+83
View File
@@ -0,0 +1,83 @@
#pragma once
#include <cstdint>
#include <filesystem>
#include <string>
#include <variant>
#include <vector>
// IMAGE_REL_AMD64_* relocation type constants (stored in ParsedRelocation.type).
// These are distinct from R_X86_64_* values; lower_coff_text() handles them.
namespace voidlibc::voidlink::coff {
constexpr std::uint32_t kRelocAbsolute = 0x0000;
constexpr std::uint32_t kRelocAddr64 = 0x0001;
constexpr std::uint32_t kRelocAddr32 = 0x0002;
constexpr std::uint32_t kRelocAddr32NB = 0x0003;
constexpr std::uint32_t kRelocRel32 = 0x0004;
constexpr std::uint32_t kRelocRel32_1 = 0x0005;
constexpr std::uint32_t kRelocRel32_2 = 0x0006;
constexpr std::uint32_t kRelocRel32_3 = 0x0007;
constexpr std::uint32_t kRelocRel32_4 = 0x0008;
constexpr std::uint32_t kRelocRel32_5 = 0x0009;
constexpr std::uint32_t kRelocSection = 0x000A;
constexpr std::uint32_t kRelocSecRel = 0x000B;
// Normalized bind values (same integers as ELF STB_*; reused for compatibility
// with lower_coff_text which operates on the same ParsedObject fields).
constexpr std::uint8_t kBindLocal = 0; // STB_LOCAL
constexpr std::uint8_t kBindGlobal = 1; // STB_GLOBAL
constexpr std::uint8_t kBindWeak = 2; // STB_WEAK
// Normalized type values (same integers as ELF STT_*).
constexpr std::uint8_t kTypeNone = 0;
constexpr std::uint8_t kTypeObject = 1;
constexpr std::uint8_t kTypeFunc = 2;
constexpr std::uint8_t kTypeSection = 3;
// Section characteristics flags.
constexpr std::uint32_t kScnCntCode = 0x00000020;
constexpr std::uint32_t kScnCntInitData = 0x00000040;
constexpr std::uint32_t kScnCntUninitData = 0x00000080;
constexpr std::uint32_t kScnLnkComdat = 0x00001000;
constexpr std::uint32_t kScnMemExecute = 0x20000000;
constexpr std::uint32_t kScnMemRead = 0x40000000;
constexpr std::uint32_t kScnMemWrite = 0x80000000u;
struct ParsedSymbol {
std::string name;
std::uint64_t value = 0; // offset within its section
std::uint64_t size = 0; // usually unknown in COFF
std::uint32_t section_index = 0; // 0 = undefined (SHN_UNDEF analogue)
std::uint8_t bind = 0; // kBind*
std::uint8_t type = 0; // kType*
bool defined = false;
};
struct ParsedRelocation {
std::uint64_t offset = 0; // byte offset within the target section
std::uint32_t sym_index = 0; // index into ParsedObject::symbols
std::uint32_t type = 0; // kReloc*
std::int64_t addend = 0; // inline addend read from code bytes
};
struct ParsedSection {
std::string name;
std::uint32_t characteristics = 0;
std::vector<std::uint8_t> bytes;
std::uint64_t mem_size = 0;
std::vector<ParsedRelocation> relocs;
};
struct ParsedObject {
std::vector<ParsedSection> sections;
std::vector<ParsedSymbol> symbols;
// Primary .text section index (first executable section with that name).
std::size_t text_index = static_cast<std::size_t>(-1);
};
using ParseResult = std::variant<ParsedObject, std::string /*error*/>;
ParseResult parse_coff_object(const std::filesystem::path& path);
} // namespace voidlibc::voidlink::coff
+265
View File
@@ -0,0 +1,265 @@
#include "elf_reader.hpp"
#include "loader/common/elf64.hpp"
#include <cstring>
#include <fstream>
#include <sstream>
namespace voidlibc::voidlink::elf {
using namespace voidlibc::loader;
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 size = static_cast<std::streamsize>(in.tellg());
in.seekg(0, std::ios::beg);
out.resize(static_cast<std::size_t>(size));
in.read(reinterpret_cast<char*>(out.data()), size);
return static_cast<bool>(in);
}
template <typename T>
bool read_struct(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;
}
} // namespace
ParseResult parse_elf64_object(const std::filesystem::path& path) {
std::vector<std::uint8_t> buf;
if (!read_file(path, buf)) {
return err("cannot read " + path.string());
}
if (buf.size() < sizeof(Ehdr)) {
return err("file too small for ELF header");
}
Ehdr eh{};
std::memcpy(&eh, buf.data(), sizeof(eh));
if (!(eh.e_ident[0] == kElfMag0 && eh.e_ident[1] == kElfMag1
&& eh.e_ident[2] == kElfMag2 && eh.e_ident[3] == kElfMag3)) {
return err("not an ELF file");
}
if (eh.e_ident[4] != kElfClass64) return err("not ELF64");
if (eh.e_ident[5] != kElfData2LSB) return err("not little-endian");
if (eh.e_machine != kEmX86_64) return err("not x86_64");
if (eh.e_type != kEtRel) return err("not a relocatable object (ET_REL)");
if (eh.e_shentsize != sizeof(Shdr)) return err("bad sh_entsize");
if (eh.e_shnum == 0) return err("no sections");
// Section table
if (eh.e_shoff + static_cast<std::uint64_t>(eh.e_shnum) * sizeof(Shdr) > buf.size()) {
return err("section table truncated");
}
std::vector<Shdr> sh(eh.e_shnum);
std::memcpy(sh.data(), buf.data() + eh.e_shoff, sh.size() * sizeof(Shdr));
if (eh.e_shstrndx >= sh.size()) return err("bad e_shstrndx");
const auto& shstr_sec = sh[eh.e_shstrndx];
if (shstr_sec.sh_offset + shstr_sec.sh_size > buf.size()) {
return err("shstrtab out of bounds");
}
const char* shstr =
reinterpret_cast<const char*>(buf.data() + shstr_sec.sh_offset);
const std::size_t shstr_size = shstr_sec.sh_size;
auto section_name = [&](std::uint32_t name_off) -> std::string {
if (name_off >= shstr_size) return {};
return std::string(shstr + name_off);
};
ParsedObject obj{};
obj.sections.reserve(sh.size());
// First pass: materialize sections.
for (std::size_t i = 0; i < sh.size(); ++i) {
const auto& s = sh[i];
ParsedSection ps{};
ps.name = section_name(s.sh_name);
ps.type = s.sh_type;
ps.flags = s.sh_flags;
ps.file_offset = s.sh_offset;
ps.size_in_file = (s.sh_type == kShtNobits) ? 0 : s.sh_size;
ps.mem_size = s.sh_size; // always the memory footprint
if (ps.size_in_file > 0) {
if (s.sh_offset + s.sh_size > buf.size()) {
std::ostringstream os;
os << "section " << ps.name << " truncated";
return err(os.str());
}
ps.bytes.assign(buf.data() + s.sh_offset,
buf.data() + s.sh_offset + s.sh_size);
}
if (ps.name == ".text" && s.sh_type == kShtProgbits) {
obj.text_index = i;
}
obj.sections.push_back(std::move(ps));
}
// Second pass: walk .symtab, materialize symbols using .strtab.
// Track which .symtab section we used so .rela.* parsing can map
// its symbol indices into ParsedObject::symbols.
std::size_t symtab_section_index = static_cast<std::size_t>(-1);
std::size_t symbols_base = 0; // first symbol index from this .symtab
for (std::size_t i = 0; i < sh.size(); ++i) {
const auto& s = sh[i];
if (s.sh_type != kShtSymtab) continue;
if (s.sh_entsize != sizeof(Sym)) {
return err(".symtab entry size mismatch");
}
if (s.sh_link >= sh.size()) {
return err(".symtab points at out-of-range strtab");
}
const auto& strtab = sh[s.sh_link];
if (strtab.sh_type != kShtStrtab) {
return err(".symtab sh_link not strtab");
}
if (strtab.sh_offset + strtab.sh_size > buf.size()) {
return err(".strtab out of bounds");
}
const char* strs =
reinterpret_cast<const char*>(buf.data() + strtab.sh_offset);
const std::size_t strs_size = strtab.sh_size;
auto str = [&](std::uint32_t off) -> std::string {
if (off >= strs_size) return {};
return std::string(strs + off);
};
const std::size_t nsyms = s.sh_size / sizeof(Sym);
std::vector<Sym> syms(nsyms);
std::memcpy(syms.data(), buf.data() + s.sh_offset, s.sh_size);
symbols_base = obj.symbols.size();
symtab_section_index = i;
obj.symbols.reserve(obj.symbols.size() + nsyms);
for (const auto& sm : syms) {
ParsedSymbol p{};
p.name = str(sm.st_name);
p.value = sm.st_value;
p.size = sm.st_size;
p.section_index = sm.st_shndx;
p.bind = st_bind(sm.st_info);
p.type = st_type(sm.st_info);
p.defined = sm.st_shndx != kShnUndef;
obj.symbols.push_back(std::move(p));
}
break; // exactly one .symtab in well-formed ET_REL
}
// Third pass: GNU versym + verneed. Forward version requirements for undefined symbols.
// SHT_GNU_versym (sh_link = symtab idx): one uint16_t per symtab entry; assigns version index.
// SHT_GNU_verneed (sh_link = strtab idx): chain of Verneed + Vernaux with version metadata.
//
// We parse verneed first to build an index→VersionRequirement map, then apply versym.
{
using voidlibc::loader::kShtGnuVerneed;
using voidlibc::loader::kShtGnuVersym;
using voidlibc::loader::Verneed;
using voidlibc::loader::Vernaux;
// Find and parse SHT_GNU_verneed.
for (std::size_t i = 0; i < sh.size(); ++i) {
if (sh[i].sh_type != kShtGnuVerneed) continue;
if (sh[i].sh_link >= sh.size()) break;
const auto& vn_strtab_hdr = sh[sh[i].sh_link];
if (vn_strtab_hdr.sh_offset + vn_strtab_hdr.sh_size > buf.size()) break;
if (sh[i].sh_offset + sh[i].sh_size > buf.size()) break;
const char* vn_str = reinterpret_cast<const char*>(
buf.data() + vn_strtab_hdr.sh_offset);
const std::size_t vn_str_sz = vn_strtab_hdr.sh_size;
auto safe_str = [&](std::uint32_t off) -> std::string {
if (off >= vn_str_sz) return {};
return std::string(vn_str + off);
};
const std::uint8_t* base = buf.data() + sh[i].sh_offset;
const std::uint8_t* end = base + sh[i].sh_size;
const std::uint32_t n_vn = sh[i].sh_info; // number of Verneed entries
const std::uint8_t* ptr = base;
for (std::uint32_t vi = 0; vi < n_vn && ptr + sizeof(Verneed) <= end; ++vi) {
Verneed vn{};
std::memcpy(&vn, ptr, sizeof(vn));
const std::string lib_name = safe_str(vn.vn_file);
const std::uint8_t* aux = ptr + vn.vn_aux;
for (std::uint16_t ai = 0; ai < vn.vn_cnt && aux + sizeof(Vernaux) <= end; ++ai) {
Vernaux va{};
std::memcpy(&va, aux, sizeof(va));
VersionRequirement vr{};
vr.index = va.vna_other;
vr.hash = va.vna_hash;
vr.flags = va.vna_flags;
vr.version_name = safe_str(va.vna_name);
vr.library = lib_name;
obj.version_reqs.push_back(std::move(vr));
if (va.vna_next == 0) break;
aux += va.vna_next;
}
if (vn.vn_next == 0) break;
ptr += vn.vn_next;
}
break;
}
// Find and apply SHT_GNU_versym linked to our symtab.
for (std::size_t i = 0; i < sh.size(); ++i) {
if (sh[i].sh_type != kShtGnuVersym) continue;
if (sh[i].sh_link != symtab_section_index) continue;
if (sh[i].sh_offset + sh[i].sh_size > buf.size()) break;
const std::size_t n = sh[i].sh_size / 2;
const std::uint16_t* versym = reinterpret_cast<const std::uint16_t*>(
buf.data() + sh[i].sh_offset);
for (std::size_t j = 0; j < n && symbols_base + j < obj.symbols.size(); ++j)
obj.symbols[symbols_base + j].version_index = versym[j];
break;
}
}
// Fourth pass: SHT_RELA sections. Each one's sh_info is the target
// section index (the section being relocated); sh_link is the symtab.
for (std::size_t i = 0; i < sh.size(); ++i) {
const auto& s = sh[i];
if (s.sh_type != kShtRela) continue;
if (s.sh_entsize != sizeof(Rela)) {
return err(".rela.* entry size mismatch");
}
if (s.sh_link != symtab_section_index) {
return err(".rela.* sh_link does not match .symtab we parsed");
}
if (s.sh_info >= obj.sections.size()) {
return err(".rela.* sh_info out of range");
}
if (s.sh_offset + s.sh_size > buf.size()) {
return err(".rela.* out of bounds");
}
const std::size_t nrelas = s.sh_size / sizeof(Rela);
std::vector<Rela> rels(nrelas);
std::memcpy(rels.data(), buf.data() + s.sh_offset, s.sh_size);
auto& target = obj.sections[s.sh_info];
target.relocs.reserve(target.relocs.size() + nrelas);
for (const auto& r : rels) {
ParsedRelocation pr{};
pr.offset = r.r_offset;
pr.sym_index = static_cast<std::uint32_t>(
symbols_base + r_sym(r.r_info));
pr.type = r_type(r.r_info);
pr.addend = r.r_addend;
target.relocs.push_back(pr);
}
}
return obj;
}
} // namespace voidlibc::voidlink::elf
+61
View File
@@ -0,0 +1,61 @@
#pragma once
#include <cstdint>
#include <filesystem>
#include <string>
#include <variant>
#include <vector>
namespace voidlibc::voidlink::elf {
struct ParsedSymbol {
std::string name;
std::uint64_t value = 0; // offset within its section
std::uint64_t size = 0;
std::uint16_t section_index = 0; // 0 = SHN_UNDEF
std::uint8_t bind = 0; // STB_*
std::uint8_t type = 0; // STT_*
bool defined = false; // false iff section_index == SHN_UNDEF
// Version index from .gnu.version (SHT_GNU_versym): 0=absent, 1=global, 2+=versioned.
std::uint16_t version_index = 0;
};
struct ParsedRelocation {
std::uint64_t offset = 0; // byte offset within the target section
std::uint32_t sym_index = 0; // index into ParsedObject::symbols
std::uint32_t type = 0; // R_X86_64_*
std::int64_t addend = 0;
};
struct ParsedSection {
std::string name;
std::uint32_t type = 0;
std::uint64_t flags = 0;
std::vector<std::uint8_t> bytes;
std::uint64_t file_offset = 0;
std::uint64_t size_in_file = 0; // 0 for NOBITS (BSS)
std::uint64_t mem_size = 0; // sh_size; for BSS: memory footprint
std::vector<ParsedRelocation> relocs; // relocs applied TO this section
};
// One entry per unique version index found in SHT_GNU_verneed.
struct VersionRequirement {
std::uint16_t index; // vna_other (version index referenced in .gnu.version)
std::uint32_t hash; // vna_hash
std::uint16_t flags; // vna_flags
std::string version_name; // e.g., "GLIBC_2.14"
std::string library; // DT_NEEDED name from parent Verneed, e.g., "libc.so.6"
};
struct ParsedObject {
std::vector<ParsedSection> sections;
std::vector<ParsedSymbol> symbols;
std::vector<VersionRequirement> version_reqs; // from .gnu.version_r
std::size_t text_index = static_cast<std::size_t>(-1);
};
using ParseResult = std::variant<ParsedObject, std::string /*error*/>;
ParseResult parse_elf64_object(const std::filesystem::path& path);
} // namespace voidlibc::voidlink::elf
+324
View File
@@ -0,0 +1,324 @@
#include "macho_reader.hpp"
#include <cstring>
#include <fstream>
#include <vector>
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<std::size_t>(f.tellg());
f.seekg(0);
std::vector<std::uint8_t> buf(fsz);
f.read(reinterpret_cast<char*>(buf.data()), static_cast<std::streamsize>(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<std::uint32_t>(ri_raw.r_address),
length);
ParsedRelocation pr;
pr.offset = static_cast<std::uint64_t>(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<const char*>(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<std::size_t>(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<std::size_t>(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<std::size_t>(-1))
return ParseError{"no __text section found"};
return obj;
}
} // namespace voidlibc::voidlink::macho
+76
View File
@@ -0,0 +1,76 @@
#pragma once
#include <cstdint>
#include <filesystem>
#include <string>
#include <variant>
#include <vector>
namespace voidlibc::voidlink::macho {
// Mach-O magic (64-bit little-endian, x86_64 or ARM64)
inline constexpr std::uint32_t kMagic64 = 0xFEEDFACFu;
inline constexpr std::uint32_t kCpuX86_64 = 0x01000007u;
inline constexpr std::uint32_t kMhObject = 0x1u;
// Relocation types for x86_64
inline constexpr std::uint32_t kRelocUnsigned = 0; // abs64 / abs32
inline constexpr std::uint32_t kRelocSigned = 1; // PC32 (inline addend is signed, includes -4)
inline constexpr std::uint32_t kRelocBranch = 2; // PC32 (call/jmp)
inline constexpr std::uint32_t kRelocGotLoad = 3; // GOTPCREL (movq via GOT)
inline constexpr std::uint32_t kRelocGot = 4; // GOT reference
inline constexpr std::uint32_t kRelocSubtractor = 5; // pair: SUBTRACTOR followed by UNSIGNED
inline constexpr std::uint32_t kRelocSigned1 = 6; // PC32 with extra -1 skew
inline constexpr std::uint32_t kRelocSigned2 = 7; // PC32 with extra -2 skew
inline constexpr std::uint32_t kRelocSigned4 = 8; // PC32 with extra -4 skew
inline constexpr std::uint32_t kRelocTls = 9; // thread-local
// nlist_64 type byte
inline constexpr std::uint8_t kNTypeStab = 0xE0;
inline constexpr std::uint8_t kNTypeMask = 0x0E;
inline constexpr std::uint8_t kNTypeUndef = 0x00;
inline constexpr std::uint8_t kNTypeSect = 0x0E;
inline constexpr std::uint8_t kNExternal = 0x01;
struct ParsedSymbol {
std::string name;
std::uint64_t value = 0; // section-relative offset (N_SECT) or 0 (N_UNDF)
std::uint32_t section_index = 0; // 1-based Mach-O section ordinal; 0 = undefined
std::uint8_t bind = 0; // 0=local, 1=global, 2=weak
std::uint8_t type = 0; // 0=notype, 2=func
bool defined = false;
};
struct ParsedRelocation {
std::uint64_t offset = 0;
std::uint32_t sym_index = 0; // index into ParsedObject::symbols (extern) or section ordinal (local)
std::uint32_t type = 0; // kReloc* constant
std::int64_t addend = 0; // inline addend (read from the target bytes)
bool is_extern = false;
bool is_pcrel = false;
std::uint32_t length = 0; // 0=byte, 1=short, 2=long, 3=quad
};
struct ParsedSection {
std::string segname; // e.g. "__TEXT"
std::string sectname; // e.g. "__text"
std::vector<std::uint8_t> bytes;
std::uint64_t mem_size = 0;
std::uint64_t addr = 0; // section vmaddr in the .o file (used for layout delta)
std::uint32_t align_exp = 0; // log2 of section alignment
std::uint32_t flags = 0;
std::vector<ParsedRelocation> relocs;
};
struct ParsedObject {
std::vector<ParsedSection> sections; // indexed by 1-based section ordinal - 1
std::vector<ParsedSymbol> symbols;
std::size_t text_index = static_cast<std::size_t>(-1);
};
struct ParseError { std::string message; };
using ParseResult = std::variant<ParsedObject, ParseError>;
ParseResult parse_macho_object(const std::filesystem::path& path);
} // namespace voidlibc::voidlink::macho
+1099
View File
File diff suppressed because it is too large. Load diff
+143
View File
@@ -0,0 +1,143 @@
#include "merge.hpp"
#include "format/vlc_format.hpp"
#include <sstream>
#include <unordered_map>
namespace voidlibc::voidlink {
namespace {
constexpr std::uint64_t align_up(std::uint64_t v, std::uint64_t a) {
return (v + (a - 1)) & ~(a - 1);
}
} // namespace
std::variant<LoweredText, std::string>
merge_lowered(std::vector<LoweredText> objects) {
if (objects.empty())
return std::string("merge_lowered: no objects to merge");
if (objects.size() == 1)
return std::move(objects[0]);
using format::kSymUndefined;
const std::size_t N = objects.size();
LoweredText merged{};
merged.section.target_os = objects[0].section.target_os;
merged.section.entry_offset = 0;
// --- Step 1: Compute blob starts and build merged code/data blobs ---
std::vector<std::uint64_t> code_starts(N), data_starts(N);
for (std::size_t oi = 0; oi < N; ++oi) {
const auto& sec = objects[oi].section;
code_starts[oi] =
align_up(static_cast<std::uint64_t>(merged.section.code.size()), 16);
merged.section.code.resize(static_cast<std::size_t>(code_starts[oi]), 0);
merged.section.code.insert(merged.section.code.end(),
sec.code.begin(), sec.code.end());
data_starts[oi] =
align_up(static_cast<std::uint64_t>(merged.section.data.size()), 8);
merged.section.data.resize(static_cast<std::size_t>(data_starts[oi]), 0);
merged.section.data.insert(merged.section.data.end(),
sec.data.begin(), sec.data.end());
}
// --- Step 2a: Intern all defined symbols from all objects ---
// Named defined symbols are deduplicated (first strong definition wins).
// Anonymous defined symbols (empty name, e.g. section symbols) are always unique.
std::unordered_map<std::string, std::uint32_t> name_to_global;
// Per-object local sym_id → global sym_id map.
std::vector<std::unordered_map<std::uint32_t, std::uint32_t>> l2g(N);
for (std::size_t oi = 0; oi < N; ++oi) {
const auto& syms = objects[oi].symbols;
for (std::uint32_t li = 0; li < static_cast<std::uint32_t>(syms.size()); ++li) {
const auto& sym = syms[li];
if (sym.section_index == kSymUndefined) continue; // imports handled below
std::uint32_t gid;
// Local symbols (not exported, not weak) are never deduplicated
// across objects — GCC emits many per-TU local names like .LC0,
// .LC1 that are distinct even when identically spelled.
const bool is_local = !sym.exported && !sym.weak;
if (sym.name.empty() || is_local) {
// Anonymous or local: always a new unique entry.
gid = static_cast<std::uint32_t>(merged.symbols.size());
} else {
auto it = name_to_global.find(sym.name);
if (it != name_to_global.end()) {
// Duplicate name: strong+strong = error; weak is overridden by strong.
const auto& existing = merged.symbols[it->second];
if (!sym.weak && !existing.weak) {
return "merge_lowered: duplicate strong definition of '" + sym.name + "'";
}
if (!sym.weak && existing.weak) {
// New strong definition overrides weak — update in place.
auto& ms = merged.symbols[it->second];
ms = sym;
ms.value += sym.data_section ? data_starts[oi] : code_starts[oi];
}
// If existing is strong and new is weak, keep existing.
l2g[oi][li] = it->second;
continue;
}
gid = static_cast<std::uint32_t>(merged.symbols.size());
name_to_global[sym.name] = gid;
}
SymbolSpec adjusted = sym;
adjusted.value += sym.data_section ? data_starts[oi] : code_starts[oi];
merged.symbols.push_back(std::move(adjusted));
l2g[oi][li] = gid;
}
}
// --- Step 2b: Intern all imports, resolving cross-object references ---
for (std::size_t oi = 0; oi < N; ++oi) {
const auto& syms = objects[oi].symbols;
for (std::uint32_t li = 0; li < static_cast<std::uint32_t>(syms.size()); ++li) {
const auto& sym = syms[li];
if (sym.section_index != kSymUndefined) continue; // defined, already handled
if (l2g[oi].count(li)) continue; // already mapped (shouldn't happen)
auto it = name_to_global.find(sym.name);
if (it != name_to_global.end()) {
// Resolved internally — maps to the defining global entry.
l2g[oi][li] = it->second;
} else {
// Genuinely external import — add once.
std::uint32_t gid = static_cast<std::uint32_t>(merged.symbols.size());
name_to_global[sym.name] = gid;
merged.symbols.push_back(sym); // section_index remains kSymUndefined
l2g[oi][li] = gid;
}
}
}
// --- Step 3: Merge relocs with adjusted offsets and global sym_ids ---
for (std::size_t oi = 0; oi < N; ++oi) {
for (auto r : objects[oi].section.relocs) {
r.dst_offset += static_cast<std::uint32_t>(code_starts[oi]);
auto it = l2g[oi].find(r.sym_id);
if (it == l2g[oi].end()) {
std::ostringstream os;
os << "merge_lowered: object " << oi
<< " reloc at 0x" << std::hex << (r.dst_offset - code_starts[oi])
<< " references unmapped sym_id " << std::dec << r.sym_id;
return os.str();
}
r.sym_id = it->second;
merged.section.relocs.push_back(r);
}
}
return std::move(merged);
}
} // namespace voidlibc::voidlink
+26
View File
@@ -0,0 +1,26 @@
#pragma once
#include "reloc_lowering.hpp"
#include <string>
#include <variant>
#include <vector>
namespace voidlibc::voidlink {
// Merge N independently-lowered objects into a single LoweredText.
//
// Code blobs are concatenated (16-byte aligned between objects).
// Data blobs are concatenated (8-byte aligned between objects).
// Symbol tables are unified: named defined symbols are deduplicated by name;
// anonymous defined symbols (e.g. section symbols) each get their own entry.
// Imports that are defined in any of the input objects are resolved internally
// — their sym_ids map to the defining object's global symbol entry.
// Truly external imports (undefined in all input objects) are kept as imports.
//
// Reloc dst_offsets are adjusted by the owning object's code_start.
// Reloc sym_ids are remapped to global symbol table indices.
std::variant<LoweredText, std::string>
merge_lowered(std::vector<LoweredText> objects);
} // namespace voidlibc::voidlink
+177
View File
@@ -0,0 +1,177 @@
#include "reader.hpp"
#include <cstdio>
#include <fstream>
#include <sstream>
#include <vector>
namespace voidlibc::voidlink {
using namespace voidlibc::format;
ReadResult read_container(const std::filesystem::path& in_path) {
std::error_code ec;
const auto file_size = std::filesystem::file_size(in_path, ec);
if (ec) {
return ReadError{"stat failed: " + ec.message()};
}
if (file_size < sizeof(FileHeader)) {
return ReadError{"file too small to be a VoidLibC file"};
}
std::ifstream in(in_path, std::ios::binary);
if (!in) {
return ReadError{"could not open " + in_path.string()};
}
Container c{};
in.read(reinterpret_cast<char*>(&c.header), sizeof(c.header));
if (!in) {
return ReadError{"short read on header"};
}
if (c.header.magic != kMagic) {
return ReadError{"bad magic; not a VoidLibC file"};
}
if (c.header.version_major != kVersionMajor) {
std::ostringstream os;
os << "unsupported major version " << c.header.version_major;
return ReadError{os.str()};
}
if (c.header.arch != TargetArch::X86_64) {
return ReadError{"unsupported architecture (MVP is x86_64-only)"};
}
if (c.header.file_size != file_size) {
std::ostringstream os;
os << "header file_size " << c.header.file_size
<< " disagrees with on-disk size " << file_size;
return ReadError{os.str()};
}
c.actual_file_size = file_size;
c.path = in_path;
return c;
}
static const char* os_name(TargetOS os) {
switch (os) {
case TargetOS::Linux: return "linux";
case TargetOS::Windows: return "windows";
case TargetOS::MacOS: return "macos";
case TargetOS::Unknown: return "unknown";
}
return "?";
}
[[maybe_unused]] static auto silence_unused_os_name = &os_name;
void dump_container(const Container& c) {
const auto& h = c.header;
const bool is_exec = flag_set(h.flags, ContainerFlags::Executable);
const bool is_stat = flag_set(h.flags, ContainerFlags::StaticLibrary);
std::printf("magic : 0x%08x (VLC\\0)\n", h.magic);
std::printf("type : %s (%s)\n",
is_stat ? "static library" : is_exec ? "executable" : "shared library",
infer_extension(h.flags));
std::printf("version : %u.%u\n", h.version_major, h.version_minor);
const bool has_dyn = flag_set(h.flags, ContainerFlags::HasDynamicImports);
std::printf("linkage : %s\n", has_dyn ? "dynamic" : "static");
std::printf("flags : 0x%08x%s%s%s%s\n", h.flags,
flag_set(h.flags, ContainerFlags::HasDebug) ? " HasDebug" : "",
flag_set(h.flags, ContainerFlags::HasCppExports) ? " HasCppExports" : "",
has_dyn ? " HasDynamicImports" : "",
is_stat ? " StaticLibrary" : "");
std::printf("arch : %s\n",
h.arch == TargetArch::X86_64 ? "x86_64" : "unknown");
std::printf("section_count : %u\n", h.section_count);
std::printf("section_dir_off : %llu\n",
static_cast<unsigned long long>(h.section_dir_off));
std::printf("symtab : off=%llu size=%llu\n",
static_cast<unsigned long long>(h.symtab_off),
static_cast<unsigned long long>(h.symtab_size));
std::printf("imports : off=%llu size=%llu\n",
static_cast<unsigned long long>(h.imports_off),
static_cast<unsigned long long>(h.imports_size));
std::printf("exports : off=%llu size=%llu\n",
static_cast<unsigned long long>(h.exports_off),
static_cast<unsigned long long>(h.exports_size));
std::printf("file_size : %llu (on disk: %llu)\n",
static_cast<unsigned long long>(h.file_size),
static_cast<unsigned long long>(c.actual_file_size));
if (c.path.empty() || h.section_count == 0) return;
std::ifstream f(c.path, std::ios::binary);
if (!f) return;
// Per-section details
f.seekg(static_cast<std::streamoff>(h.section_dir_off));
std::vector<SectionEntry> sects(h.section_count);
f.read(reinterpret_cast<char*>(sects.data()),
static_cast<std::streamsize>(h.section_count * sizeof(SectionEntry)));
if (!f) return;
std::printf("sections:\n");
for (std::uint32_t i = 0; i < h.section_count; ++i) {
const auto& s = sects[i];
const char* osn =
(s.target_os == TargetOS::Linux) ? "linux" :
(s.target_os == TargetOS::Windows) ? "windows" :
(s.target_os == TargetOS::MacOS) ? "macos" : "unknown";
const char* kind =
(s.kind == SectionKind::NativeBlob) ? "NativeBlob" : "RawCode ";
std::printf(" [%u] %-7s %s code=@%llu+%llu",
i, osn, kind,
static_cast<unsigned long long>(s.code_off),
static_cast<unsigned long long>(s.code_size));
if (s.data_size > 0)
std::printf(" data=@%llu+%llu",
static_cast<unsigned long long>(s.data_off),
static_cast<unsigned long long>(s.data_size));
if (s.entry_offset > 0)
std::printf(" entry=+%llu", static_cast<unsigned long long>(s.entry_offset));
std::printf("\n");
}
// Symbol table
if (h.symtab_size < sizeof(SymbolTableHeader)) return;
f.seekg(static_cast<std::streamoff>(h.symtab_off));
SymbolTableHeader sth{};
f.read(reinterpret_cast<char*>(&sth), sizeof(sth));
if (!f || sth.entry_count == 0) return;
std::vector<SymbolEntry> syms(sth.entry_count);
f.read(reinterpret_cast<char*>(syms.data()),
static_cast<std::streamsize>(sth.entry_count * sizeof(SymbolEntry)));
std::string pool(sth.name_pool_size, '\0');
f.read(pool.data(), static_cast<std::streamsize>(sth.name_pool_size));
if (!f) return;
auto name_of = [&](const SymbolEntry& e) -> std::string {
if (e.name_off + e.name_len > sth.name_pool_size) return "?";
return pool.substr(e.name_off, e.name_len);
};
std::vector<std::string> exports_list, imports_list;
for (const auto& sym : syms) {
if (sym.section_index == kSymUndefined)
imports_list.push_back(name_of(sym));
else if (sym.flags & static_cast<std::uint8_t>(SymbolFlags::Exported))
exports_list.push_back(name_of(sym));
}
auto print_names = [](const char* label, const std::vector<std::string>& names) {
constexpr std::size_t kMax = 8;
std::printf(" %-8s (%zu):", label, names.size());
for (std::size_t i = 0; i < std::min(names.size(), kMax); ++i)
std::printf(" %s", names[i].c_str());
if (names.size() > kMax)
std::printf(" ... +%zu more", names.size() - kMax);
std::printf("\n");
};
std::printf("symbols (%u total):\n", sth.entry_count);
if (!exports_list.empty()) print_names("exports", exports_list);
if (!imports_list.empty()) print_names("imports", imports_list);
}
} // namespace voidlibc::voidlink
+27
View File
@@ -0,0 +1,27 @@
#pragma once
#include "format/vlc_format.hpp"
#include <filesystem>
#include <string>
#include <variant>
namespace voidlibc::voidlink {
struct ReadError {
std::string message;
};
struct Container {
voidlibc::format::FileHeader header;
std::uint64_t actual_file_size = 0;
std::filesystem::path path;
};
using ReadResult = std::variant<Container, ReadError>;
ReadResult read_container(const std::filesystem::path& in_path);
void dump_container(const Container& c);
} // namespace voidlibc::voidlink
+850
View File
@@ -0,0 +1,850 @@
#include "reloc_lowering.hpp"
#include "format/reloc_ir.hpp"
#include "format/vlc_format.hpp"
#include "loader/common/elf64.hpp"
#include <algorithm>
#include <cstring>
#include <sstream>
#include <unordered_map>
namespace voidlibc::voidlink {
using namespace voidlibc::format;
using voidlibc::loader::kRX86_64_None;
using voidlibc::loader::kRX86_64_64;
using voidlibc::loader::kRX86_64_PC32;
using voidlibc::loader::kRX86_64_PLT32;
using voidlibc::loader::kRX86_64_32;
using voidlibc::loader::kRX86_64_32S;
using voidlibc::loader::kRX86_64_GOTPCREL;
using voidlibc::loader::kRX86_64_GOTPCRELX;
using voidlibc::loader::kRX86_64_REX_GOTPCRELX;
using voidlibc::loader::kShtProgbits;
using voidlibc::loader::kShtNobits;
namespace {
constexpr std::uint8_t kStbLocal = 0;
constexpr std::uint8_t kStbGlobal = 1;
constexpr std::uint8_t kStbWeak = 2;
constexpr std::uint8_t kSttNotype = 0;
constexpr std::uint8_t kSttObject = 1;
constexpr std::uint8_t kSttFunc = 2;
constexpr std::uint8_t kSttSection = 3;
// .text.startup, .text.hot, .text.unlikely, .text.N comdat sections, etc.
// These are code sections that GCC emits separately from .text. They get
// merged into the RX code blob with their relocs processed identically.
bool is_text_companion_section(const std::string& name) {
return name.rfind(".text.", 0) == 0;
}
// .rodata and all .rodata.* sections — read-only data merged into RX blob.
// Only PC32 relocs from .text to these are expected (string literals, etc.);
// they are base-invariant so no separate reloc processing is needed here.
bool is_rodata_companion_section(const std::string& name) {
return name.rfind(".rodata", 0) == 0;
}
// .bss, .bss.*, .data, .data.* (excluding .data.rel.*) — writable data blob.
bool is_data_section(const std::string& name) {
if (name == ".bss" || name.rfind(".bss.", 0) == 0) return true;
if (name == ".data") return true;
if (name.rfind(".data.", 0) == 0 && name.rfind(".data.rel", 0) != 0) return true;
return false;
}
constexpr std::uint64_t align_up(std::uint64_t v, std::uint64_t a) {
return (v + (a - 1)) & ~(a - 1);
}
struct Lowering {
LoweredText out;
// ELF .symtab index → portable symbol id in out.symbols.
std::unordered_map<std::uint32_t, std::uint32_t> elf_to_portable;
// ELF section index → byte offset within the merged code blob.
// Used for: .rodata.* companions AND .text.* companions.
std::unordered_map<std::size_t, std::uint64_t> section_blob_start;
// ELF section index → byte offset within the data blob (.data/.bss).
std::unordered_map<std::size_t, std::uint64_t> data_section_blob_start;
std::string error;
std::uint32_t intern(const elf::ParsedObject& obj,
std::size_t text_idx,
std::uint32_t elf_sym) {
if (auto it = elf_to_portable.find(elf_sym);
it != elf_to_portable.end()) {
return it->second;
}
const auto& s = obj.symbols[elf_sym];
SymbolSpec ss{};
ss.name = s.name;
ss.kind = (s.type == kSttObject) ? SymbolKind::Object
: SymbolKind::Function;
ss.size = s.size;
ss.weak = (s.bind == kStbWeak);
if (s.defined && s.section_index == text_idx) {
// Symbol lives in .text (primary text section).
ss.section_index = 0;
ss.value = s.value;
ss.exported = (s.bind == kStbGlobal || s.bind == kStbWeak);
} else if (s.defined) {
auto it = section_blob_start.find(s.section_index);
if (it != section_blob_start.end()) {
ss.section_index = 0;
ss.value = it->second + s.value;
// .text.* companions CAN export symbols (e.g. main in .text.startup).
// .rodata.* companions do not export addressable symbols.
const auto& sec_name = obj.sections[s.section_index].name;
ss.exported = is_text_companion_section(sec_name)
&& (s.bind == kStbGlobal || s.bind == kStbWeak);
} else {
auto dit = data_section_blob_start.find(s.section_index);
if (dit != data_section_blob_start.end()) {
ss.section_index = 0;
ss.value = dit->second + s.value;
ss.exported = false;
ss.data_section = true;
} else {
std::ostringstream os;
os << "symbol '" << s.name
<< "' defined in unsupported section (idx "
<< s.section_index << ")";
error = os.str();
return 0;
}
}
} else {
// External import.
ss.section_index = kSymUndefined;
ss.value = 0;
ss.exported = false;
// Forward version requirement (version_index > 1 means versioned).
if (s.version_index > 1) {
for (const auto& vr : obj.version_reqs) {
if (vr.index == s.version_index) {
ss.version_name = vr.version_name;
ss.version_hash = vr.hash;
ss.version_flags = vr.flags;
break;
}
}
}
}
const auto id = static_cast<std::uint32_t>(out.symbols.size());
out.symbols.push_back(std::move(ss));
elf_to_portable.emplace(elf_sym, id);
return id;
}
// Process relocations from one section (the source section's relocs
// reference symbols in the global .symtab). blob_start is the byte offset
// of that section's content within the merged code blob.
bool process_relocs(const elf::ParsedObject& obj,
std::size_t text_idx,
const std::vector<elf::ParsedRelocation>& relocs,
std::uint64_t blob_start) {
for (const auto& r : relocs) {
if (r.sym_index >= obj.symbols.size()) {
std::ostringstream os;
os << "reloc at 0x" << std::hex << r.offset
<< " references out-of-range sym " << std::dec << r.sym_index;
error = os.str();
return false;
}
const auto& referenced = obj.symbols[r.sym_index];
// Section symbols for supported sections.
if (referenced.type == kSttSection) {
if (referenced.section_index == text_idx) {
// .text section symbol — OK.
} else if (section_blob_start.count(referenced.section_index)) {
// .rodata.* or .text.* companion — OK.
} else if (data_section_blob_start.count(referenced.section_index)) {
// .data/.bss — OK.
} else {
std::ostringstream os;
os << "reloc at 0x" << std::hex << r.offset
<< " references section symbol for unsupported section"
<< " (idx " << std::dec << referenced.section_index << ")";
error = os.str();
return false;
}
}
const std::uint32_t sym_id = intern(obj, text_idx, r.sym_index);
if (!error.empty()) return false;
const bool is_external = !referenced.defined;
RelocEntry e{};
e.reserved = 0;
e.dst_offset = static_cast<std::uint32_t>(blob_start + r.offset);
e.sym_id = sym_id;
e.addend = static_cast<std::int32_t>(r.addend);
switch (r.type) {
case kRX86_64_None:
continue;
case kRX86_64_PC32:
if (is_external) {
std::ostringstream os;
os << "R_X86_64_PC32 against external symbol '"
<< referenced.name << "' at 0x" << std::hex << r.offset
<< "; use PLT32 for function calls";
error = os.str();
return false;
}
e.op = RelocOp::PC32;
break;
case kRX86_64_PLT32:
e.op = is_external ? RelocOp::PLT32 : RelocOp::PC32;
break;
case kRX86_64_64:
e.op = RelocOp::Abs64;
break;
case kRX86_64_32:
e.op = RelocOp::Abs32;
break;
case kRX86_64_32S:
e.op = RelocOp::Abs32Signed;
break;
case kRX86_64_GOTPCREL:
e.op = RelocOp::GotPC32;
break;
case kRX86_64_GOTPCRELX:
e.op = RelocOp::GotPC32X;
break;
case kRX86_64_REX_GOTPCRELX:
e.op = RelocOp::GotPC32XRex;
break;
default: {
std::ostringstream os;
os << "unsupported R_X86_64_" << r.type
<< " at offset 0x" << std::hex << r.offset;
error = os.str();
return false;
}
}
out.section.relocs.push_back(e);
}
return true;
}
};
} // namespace
std::variant<LoweredText, std::string>
lower_elf_text(const elf::ParsedObject& obj, TargetOS target_os) {
if (obj.text_index == static_cast<std::size_t>(-1)) {
return std::string("no .text section in object");
}
const auto& text = obj.sections[obj.text_index];
Lowering L;
L.out.section.target_os = target_os;
L.out.section.entry_offset = 0;
// --- Build the merged code blob ---
//
// Layout: [.text] [.text.* companions (16-byte aligned)] [.rodata.* companions (16-byte aligned)]
//
// .text.* (e.g. .text.startup, .text.hot): code emitted by GCC for specific
// function groups. Their relocs must also be processed.
// .rodata.*: read-only data (string literals, const tables). PC32 relocs
// from .text to .rodata are base-invariant — no separate reloc processing.
L.out.section.code = text.bytes;
// Append .text.* companions first.
for (std::size_t si = 0; si < obj.sections.size(); ++si) {
if (si == obj.text_index) continue;
const auto& sec = obj.sections[si];
if (!is_text_companion_section(sec.name)) continue;
if (sec.type != kShtProgbits) continue;
if (sec.bytes.empty()) continue;
const std::uint64_t aligned =
align_up(static_cast<std::uint64_t>(L.out.section.code.size()), 16);
L.out.section.code.resize(static_cast<std::size_t>(aligned), 0);
L.section_blob_start[si] = aligned;
L.out.section.code.insert(L.out.section.code.end(),
sec.bytes.begin(), sec.bytes.end());
}
// Append .rodata.* companions.
for (std::size_t si = 0; si < obj.sections.size(); ++si) {
if (si == obj.text_index) continue;
const auto& sec = obj.sections[si];
if (!is_rodata_companion_section(sec.name)) continue;
if (sec.type != kShtProgbits) continue;
if (sec.bytes.empty()) continue;
const std::uint64_t aligned =
align_up(static_cast<std::uint64_t>(L.out.section.code.size()), 16);
L.out.section.code.resize(static_cast<std::size_t>(aligned), 0);
L.section_blob_start[si] = aligned;
L.out.section.code.insert(L.out.section.code.end(),
sec.bytes.begin(), sec.bytes.end());
}
// --- Build the data blob: [.data] [.bss zeros] ---
{
std::vector<std::uint8_t> data_blob;
for (std::size_t si = 0; si < obj.sections.size(); ++si) {
if (si == obj.text_index) continue;
const auto& sec = obj.sections[si];
if (!is_data_section(sec.name)) continue;
const std::uint64_t aligned =
align_up(static_cast<std::uint64_t>(data_blob.size()), 8);
data_blob.resize(static_cast<std::size_t>(aligned), 0);
L.data_section_blob_start[si] = aligned;
if (sec.type == kShtNobits) {
data_blob.resize(static_cast<std::size_t>(aligned + sec.mem_size), 0);
} else {
data_blob.insert(data_blob.end(), sec.bytes.begin(), sec.bytes.end());
}
}
L.out.section.data = std::move(data_blob);
}
// --- Pre-intern all globally-visible function symbols ---
// Covers .text and all .text.* companions (e.g. main in .text.startup).
for (std::uint32_t i = 0; i < obj.symbols.size(); ++i) {
const auto& s = obj.symbols[i];
if (!s.defined) continue;
const bool in_text = (s.section_index == obj.text_index);
const bool in_text_comp = !in_text
&& L.section_blob_start.count(s.section_index)
&& is_text_companion_section(obj.sections[s.section_index].name);
if (!in_text && !in_text_comp) continue;
if (s.bind == kStbLocal) continue;
if (s.type != kSttFunc && s.type != kSttNotype) continue;
(void)L.intern(obj, obj.text_index, i);
if (!L.error.empty()) return L.error;
}
// --- Process relocs from .text ---
if (!L.process_relocs(obj, obj.text_index, text.relocs, 0)) {
return L.error;
}
// --- Process relocs from .text.* companions ---
for (std::size_t si = 0; si < obj.sections.size(); ++si) {
const auto& sec = obj.sections[si];
if (!is_text_companion_section(sec.name)) continue;
if (sec.relocs.empty()) continue;
auto it = L.section_blob_start.find(si);
if (it == L.section_blob_start.end()) continue;
if (!L.process_relocs(obj, obj.text_index, sec.relocs, it->second)) {
return L.error;
}
}
// --- Process relocs from .rodata.* companions ---
// GCC places switch-statement jump tables in .rodata with R_X86_64_PC32
// entries that point back into .text (the case labels). Without applying
// these, table entries remain zero and indirect jumps go to wrong targets.
for (std::size_t si = 0; si < obj.sections.size(); ++si) {
const auto& sec = obj.sections[si];
if (!is_rodata_companion_section(sec.name)) continue;
if (sec.relocs.empty()) continue;
auto it = L.section_blob_start.find(si);
if (it == L.section_blob_start.end()) continue;
if (!L.process_relocs(obj, obj.text_index, sec.relocs, it->second)) {
return L.error;
}
}
return std::move(L.out);
}
// ---------------------------------------------------------------------------
// COFF lowering
namespace {
constexpr std::uint64_t coff_align_up(std::uint64_t v, std::uint64_t a) {
return (v + (a - 1)) & ~(a - 1);
}
bool is_coff_code_section(const coff::ParsedSection& s) {
return (s.characteristics & coff::kScnCntCode) != 0
&& (s.characteristics & coff::kScnMemExecute) != 0;
}
bool is_coff_rdata_section(const coff::ParsedSection& s) {
return (s.characteristics & coff::kScnCntInitData) != 0
&& (s.characteristics & coff::kScnMemRead) != 0
&& (s.characteristics & coff::kScnMemWrite) == 0;
}
bool is_coff_data_section(const coff::ParsedSection& s) {
const bool init = (s.characteristics & coff::kScnCntInitData) != 0;
const bool uninit = (s.characteristics & coff::kScnCntUninitData) != 0;
const bool write = (s.characteristics & coff::kScnMemWrite) != 0;
return (init || uninit) && write;
}
struct CoffLowering {
LoweredText out;
std::unordered_map<std::uint32_t, std::uint32_t> coff_to_portable; // sym_idx → portable id
// section_index (0-based) → blob start in code blob (for code+rdata sections)
std::unordered_map<std::size_t, std::uint64_t> code_sec_blob_start;
// section_index → blob start in data blob (for .data/.bss sections)
std::unordered_map<std::size_t, std::uint64_t> data_sec_blob_start;
std::string error;
std::uint32_t intern(const coff::ParsedObject& obj,
std::size_t text_sec_idx,
std::uint32_t coff_sym) {
if (auto it = coff_to_portable.find(coff_sym);
it != coff_to_portable.end())
return it->second;
const auto& s = obj.symbols[coff_sym];
SymbolSpec ss{};
ss.name = s.name;
ss.size = s.size;
ss.weak = (s.bind == coff::kBindWeak);
ss.kind = (s.type == coff::kTypeFunc) ? SymbolKind::Function
: SymbolKind::Object;
if (s.defined) {
const std::size_t sec0 = static_cast<std::size_t>(s.section_index - 1);
if (sec0 == text_sec_idx) {
ss.section_index = 0;
ss.value = s.value;
ss.exported = (s.bind == coff::kBindGlobal || s.bind == coff::kBindWeak);
} else if (auto it = code_sec_blob_start.find(sec0);
it != code_sec_blob_start.end()) {
ss.section_index = 0;
ss.value = it->second + s.value;
ss.exported = is_coff_code_section(obj.sections[sec0])
&& (s.bind == coff::kBindGlobal || s.bind == coff::kBindWeak);
} else if (auto it = data_sec_blob_start.find(sec0);
it != data_sec_blob_start.end()) {
ss.section_index = 0;
ss.value = it->second + s.value;
ss.exported = false;
ss.data_section = true;
} else {
std::ostringstream os;
os << "symbol '" << s.name
<< "' in unsupported section (idx " << sec0 << ")";
error = os.str();
return 0;
}
} else {
// External import.
ss.section_index = kSymUndefined;
ss.value = 0;
ss.exported = false;
}
const auto id = static_cast<std::uint32_t>(out.symbols.size());
out.symbols.push_back(std::move(ss));
coff_to_portable.emplace(coff_sym, id);
return id;
}
bool process_relocs(const coff::ParsedObject& obj,
std::size_t text_sec_idx,
const std::vector<coff::ParsedRelocation>& relocs,
std::uint64_t blob_start) {
using coff::kRelocRel32;
using coff::kRelocRel32_1; using coff::kRelocRel32_2;
using coff::kRelocRel32_4; using coff::kRelocRel32_5;
using coff::kRelocAddr64;
using coff::kRelocAddr32; using coff::kRelocAddr32NB;
for (const auto& r : relocs) {
if (r.sym_index >= obj.symbols.size()) {
std::ostringstream os;
os << "COFF reloc at 0x" << std::hex << r.offset
<< " references out-of-range sym " << std::dec << r.sym_index;
error = os.str();
return false;
}
const auto& sym = obj.symbols[r.sym_index];
const std::uint32_t pid = intern(obj, text_sec_idx, r.sym_index);
if (!error.empty()) return false;
RelocEntry e{};
e.reserved = 0;
e.dst_offset = static_cast<std::uint32_t>(blob_start + r.offset);
e.sym_id = pid;
switch (r.type) {
case kRelocRel32:
// COFF REL32: value = S + inline - (P+4).
// Portable PC32: value = S - P + addend, where addend = inline - 4.
e.op = RelocOp::PC32;
e.addend = static_cast<std::int32_t>(r.addend - 4);
break;
case kRelocRel32_1:
e.op = RelocOp::PC32_1;
e.addend = static_cast<std::int32_t>(r.addend - 4);
break;
case kRelocRel32_2:
e.op = RelocOp::PC32_2;
e.addend = static_cast<std::int32_t>(r.addend - 4);
break;
case coff::kRelocRel32_3:
// No dedicated PC32_3 opcode; treat as PC32 with adjusted addend.
e.op = RelocOp::PC32;
e.addend = static_cast<std::int32_t>(r.addend - 7);
break;
case kRelocRel32_4:
e.op = RelocOp::PC32_4;
e.addend = static_cast<std::int32_t>(r.addend - 4);
break;
case kRelocRel32_5:
e.op = RelocOp::PC32_5;
e.addend = static_cast<std::int32_t>(r.addend - 4);
break;
case kRelocAddr64:
e.op = RelocOp::Abs64;
e.addend = static_cast<std::int32_t>(r.addend);
break;
case kRelocAddr32:
e.op = RelocOp::Abs32;
e.addend = static_cast<std::int32_t>(r.addend);
break;
case kRelocAddr32NB:
// Relative to image base — only meaningful in PE context.
// Silently skip for portable IR (VLC is PIC; these don't appear in code).
continue;
default: {
// Skip SECTION / SECREL / unknown types.
(void)sym;
continue;
}
}
out.section.relocs.push_back(e);
}
return true;
}
};
} // namespace
std::variant<LoweredText, std::string>
lower_coff_text(const coff::ParsedObject& obj,
voidlibc::format::TargetOS target_os) {
if (obj.text_index == static_cast<std::size_t>(-1))
return std::string("no executable .text section in COFF object");
const std::size_t text_si = obj.text_index;
const auto& text_sec = obj.sections[text_si];
CoffLowering L;
L.out.section.target_os = target_os;
L.out.section.entry_offset = 0;
// --- Build merged code blob: [.text][companion code+rdata sections (16-aligned)] ---
L.out.section.code = text_sec.bytes;
// Append additional code sections (.text$... COMDAT sections and .rdata).
for (std::size_t si = 0; si < obj.sections.size(); ++si) {
if (si == text_si) continue;
const auto& sec = obj.sections[si];
const bool is_code = is_coff_code_section(sec);
const bool is_rdata = is_coff_rdata_section(sec);
if (!is_code && !is_rdata) continue;
if (sec.bytes.empty() && sec.mem_size == 0) continue;
const std::uint64_t aligned =
coff_align_up(static_cast<std::uint64_t>(L.out.section.code.size()), 16);
L.out.section.code.resize(static_cast<std::size_t>(aligned), 0);
L.code_sec_blob_start[si] = aligned;
L.out.section.code.insert(L.out.section.code.end(),
sec.bytes.begin(), sec.bytes.end());
// Pad to mem_size if bytes < mem_size.
if (sec.mem_size > sec.bytes.size()) {
L.out.section.code.resize(
L.out.section.code.size() + (sec.mem_size - sec.bytes.size()), 0);
}
}
// --- Build data blob: [.data][.bss] (8-byte aligned between items) ---
{
std::vector<std::uint8_t> data_blob;
for (std::size_t si = 0; si < obj.sections.size(); ++si) {
if (si == text_si) continue;
const auto& sec = obj.sections[si];
if (!is_coff_data_section(sec)) continue;
const std::uint64_t aligned =
coff_align_up(static_cast<std::uint64_t>(data_blob.size()), 8);
data_blob.resize(static_cast<std::size_t>(aligned), 0);
L.data_sec_blob_start[si] = aligned;
if (sec.bytes.empty()) {
data_blob.resize(data_blob.size() + sec.mem_size, 0);
} else {
data_blob.insert(data_blob.end(), sec.bytes.begin(), sec.bytes.end());
if (sec.mem_size > sec.bytes.size())
data_blob.resize(data_blob.size() + (sec.mem_size - sec.bytes.size()), 0);
}
}
L.out.section.data = std::move(data_blob);
}
// --- Pre-intern exported symbols from .text and companion code sections ---
for (std::uint32_t i = 0; i < obj.symbols.size(); ++i) {
const auto& s = obj.symbols[i];
if (!s.defined) continue;
if (s.bind == coff::kBindLocal) continue;
const std::size_t sec0 = static_cast<std::size_t>(s.section_index - 1);
const bool in_text = (sec0 == text_si);
const bool in_code_c = !in_text && L.code_sec_blob_start.count(sec0)
&& is_coff_code_section(obj.sections[sec0]);
if (!in_text && !in_code_c) continue;
if (s.type != coff::kTypeFunc && s.type != coff::kTypeNone) continue;
(void)L.intern(obj, text_si, i);
if (!L.error.empty()) return L.error;
}
// --- Process relocs from .text ---
if (!L.process_relocs(obj, text_si, text_sec.relocs, 0))
return L.error;
// --- Process relocs from companion sections ---
for (std::size_t si = 0; si < obj.sections.size(); ++si) {
if (si == text_si) continue;
const auto& sec = obj.sections[si];
if (sec.relocs.empty()) continue;
auto it = L.code_sec_blob_start.find(si);
if (it == L.code_sec_blob_start.end()) continue;
if (!L.process_relocs(obj, text_si, sec.relocs, it->second))
return L.error;
}
return std::move(L.out);
}
// ===========================================================================
// Mach-O (x86-64 macOS) lowering
// ===========================================================================
namespace {
using namespace voidlibc::voidlink::macho;
struct MachoLowering {
LoweredText out;
std::string error;
// Maps Mach-O 1-based section ordinal → byte offset within the merged code blob.
std::unordered_map<std::uint32_t, std::uint64_t> sec_blob_start;
// Maps Mach-O 1-based section ordinal → .o section vmaddr (for non-extern delta patching).
std::unordered_map<std::uint32_t, std::uint64_t> sec_o_addr;
std::unordered_map<std::uint32_t, std::uint32_t> sym_id_map;
std::uint32_t intern_sym(const ParsedObject& obj, std::uint32_t macho_idx) {
auto it = sym_id_map.find(macho_idx);
if (it != sym_id_map.end()) return it->second;
const auto& s = obj.symbols[macho_idx];
SymbolSpec ss{};
ss.name = s.name;
ss.exported = (s.bind == 1 && s.defined);
ss.section_index = kSymUndefined;
if (s.defined && s.section_index >= 1
&& static_cast<std::size_t>(s.section_index - 1) < obj.sections.size()) {
auto bit = sec_blob_start.find(static_cast<std::uint32_t>(s.section_index));
ss.value = s.value + (bit != sec_blob_start.end() ? bit->second : 0);
ss.section_index = 0;
}
ss.kind = (s.type == 2) ? SymbolKind::Function : SymbolKind::Object;
const auto id = static_cast<std::uint32_t>(out.symbols.size());
out.symbols.push_back(std::move(ss));
sym_id_map[macho_idx] = id;
return id;
}
bool process_relocs(const ParsedObject& obj,
const std::vector<macho::ParsedRelocation>& relocs,
std::uint64_t blob_offset) {
for (std::size_t ri = 0; ri < relocs.size(); ++ri) {
const auto& r = relocs[ri];
if (!r.is_extern) {
// Non-extern (section-relative) PC-rel relocs: the inline displacement was
// computed by the assembler using the .o section layout. Our blob layout may
// differ (different alignment padding), so patch the delta in.
if (r.is_pcrel && r.length == 2 &&
(r.type == kRelocSigned || r.type == kRelocBranch ||
r.type == kRelocSigned1 || r.type == kRelocSigned2 ||
r.type == kRelocSigned4)) {
// r.sym_index is a 1-based section ordinal (not a symbol index).
const std::uint32_t sec_ord = r.sym_index;
auto bit = sec_blob_start.find(sec_ord);
auto ait = sec_o_addr.find(sec_ord);
if (bit != sec_blob_start.end() && ait != sec_o_addr.end()) {
const std::int64_t delta = static_cast<std::int64_t>(bit->second)
- static_cast<std::int64_t>(ait->second);
if (delta != 0) {
const std::uint64_t patch = blob_offset + r.offset;
if (patch + 4 <= out.section.code.size()) {
std::int32_t cur = 0;
std::memcpy(&cur, out.section.code.data() + patch, 4);
cur += static_cast<std::int32_t>(delta);
std::memcpy(out.section.code.data() + patch, &cur, 4);
}
}
}
} else if (r.type == kRelocSubtractor && ri + 1 < relocs.size()) {
++ri; // skip the paired UNSIGNED
}
continue;
}
if (r.sym_index >= obj.symbols.size()) {
error = "reloc sym_index out of range";
return false;
}
RelocEntry re{};
re.dst_offset = static_cast<std::uint32_t>(blob_offset + r.offset);
re.sym_id = intern_sym(obj, r.sym_index);
switch (r.type) {
case kRelocSigned:
// Signed PC32 to an external symbol: treat as direct PC32 (data or func).
re.op = RelocOp::PC32;
re.addend = static_cast<std::int32_t>(r.addend);
break;
case kRelocBranch:
// Branch (call/jmp) to an external symbol → PLT stub (same as ELF PLT32).
re.op = RelocOp::PLT32;
re.addend = static_cast<std::int32_t>(r.addend);
break;
case kRelocGotLoad:
case kRelocGot:
re.op = RelocOp::GotPC32;
re.addend = static_cast<std::int32_t>(r.addend);
break;
case kRelocUnsigned:
re.op = (r.length == 3) ? RelocOp::Abs64 : RelocOp::Abs32;
re.addend = static_cast<std::int32_t>(r.addend);
break;
case kRelocSigned1:
re.op = RelocOp::PC32;
re.addend = static_cast<std::int32_t>(r.addend) - 1;
break;
case kRelocSigned2:
re.op = RelocOp::PC32;
re.addend = static_cast<std::int32_t>(r.addend) - 2;
break;
case kRelocSigned4:
re.op = RelocOp::PC32;
re.addend = static_cast<std::int32_t>(r.addend) - 4;
break;
case kRelocSubtractor:
if (ri + 1 < relocs.size()) ++ri;
continue;
case kRelocTls:
re.op = RelocOp::TlsGD;
re.addend = 0;
break;
default:
error = "unhandled Mach-O reloc type " + std::to_string(r.type);
return false;
}
out.section.relocs.push_back(re);
}
return true;
}
};
} // anonymous namespace
std::variant<LoweredText, std::string>
lower_macho_text(const macho::ParsedObject& obj,
voidlibc::format::TargetOS target_os) {
if (obj.text_index == static_cast<std::size_t>(-1))
return std::string{"no __text section"};
MachoLowering L;
L.out.section.target_os = target_os;
const auto& text_sec = obj.sections[obj.text_index];
L.sec_blob_start[static_cast<std::uint32_t>(obj.text_index + 1)] = 0;
L.sec_o_addr[static_cast<std::uint32_t>(obj.text_index + 1)] = text_sec.addr;
L.out.section.code = text_sec.bytes;
// Append read-only companion sections (__const, __cstring, etc.).
for (std::size_t si = 0; si < obj.sections.size(); ++si) {
if (si == obj.text_index) continue;
const auto& sec = obj.sections[si];
const bool is_ro = (sec.sectname == "__const")
|| (sec.sectname == "__rodata")
|| (sec.sectname == "__cstring")
|| sec.sectname.rfind("__literal", 0) == 0
|| sec.sectname.rfind("__gcc_except", 0) == 0;
if (!is_ro) continue;
// Align to max(16, section's natural alignment) to match the section's own alignment
// so that non-extern SIGNED reloc deltas stay zero when the .o already aligns to ≤16.
const std::uint64_t align = std::max(std::uint64_t(16),
std::uint64_t(1) << sec.align_exp);
while (L.out.section.code.size() % align != 0) L.out.section.code.push_back(0);
L.sec_blob_start[static_cast<std::uint32_t>(si + 1)] = L.out.section.code.size();
L.sec_o_addr[static_cast<std::uint32_t>(si + 1)] = sec.addr;
L.out.section.code.insert(L.out.section.code.end(),
sec.bytes.begin(), sec.bytes.end());
}
// Writable sections → data blob.
for (std::size_t si = 0; si < obj.sections.size(); ++si) {
if (si == obj.text_index) continue;
const auto& sec = obj.sections[si];
const bool is_rw = (sec.sectname == "__data")
|| (sec.sectname == "__bss")
|| (sec.sectname == "__common")
|| sec.sectname.rfind("__thread_", 0) == 0;
if (!is_rw) continue;
while (L.out.section.data.size() % 16 != 0) L.out.section.data.push_back(0);
const std::uint64_t off =
static_cast<std::uint64_t>(L.out.section.code.size())
+ L.out.section.data.size();
L.sec_blob_start[static_cast<std::uint32_t>(si + 1)] = off;
L.sec_o_addr[static_cast<std::uint32_t>(si + 1)] = sec.addr;
L.out.section.data.insert(L.out.section.data.end(),
sec.bytes.begin(), sec.bytes.end());
if (sec.mem_size > sec.bytes.size())
L.out.section.data.resize(
L.out.section.data.size() + (sec.mem_size - sec.bytes.size()), 0);
}
// Intern all named symbols.
for (std::uint32_t si = 0; si < obj.symbols.size(); ++si) {
if (!obj.symbols[si].name.empty()) L.intern_sym(obj, si);
}
if (!L.process_relocs(obj, text_sec.relocs, 0)) return L.error;
for (std::size_t si = 0; si < obj.sections.size(); ++si) {
if (si == obj.text_index) continue;
const auto& sec = obj.sections[si];
if (sec.relocs.empty()) continue;
auto bit = L.sec_blob_start.find(static_cast<std::uint32_t>(si + 1));
if (bit == L.sec_blob_start.end()) continue;
if (!L.process_relocs(obj, sec.relocs, bit->second)) return L.error;
}
return std::move(L.out);
}
} // namespace voidlibc::voidlink
+37
View File
@@ -0,0 +1,37 @@
#pragma once
#include "builder.hpp"
#include "coff_reader.hpp"
#include "elf_reader.hpp"
#include "macho_reader.hpp"
#include <string>
#include <variant>
namespace voidlibc::voidlink {
struct LoweredText {
SectionSpec section; // code + relocs (portable IR)
std::vector<SymbolSpec> symbols; // unified: exports first, then imports
};
// Lower the .text section of an ELF .o into a portable VoidLibC
// SectionSpec + unified SymbolSpec list.
std::variant<LoweredText, std::string>
lower_elf_text(const elf::ParsedObject& obj,
voidlibc::format::TargetOS target_os);
// Lower a COFF .obj (x86-64 Windows) into portable VoidLibC representation.
// Handles IMAGE_REL_AMD64_REL32 / REL32_1..5 / ADDR64 and produces the same
// LoweredText as lower_elf_text() so that fuse / pack-elf work uniformly.
std::variant<LoweredText, std::string>
lower_coff_text(const coff::ParsedObject& obj,
voidlibc::format::TargetOS target_os);
// Lower a Mach-O .o (x86-64 macOS) into portable VoidLibC representation.
// Handles X86_64_RELOC_SIGNED / BRANCH / UNSIGNED / GOT_LOAD / SUBTRACTOR.
std::variant<LoweredText, std::string>
lower_macho_text(const macho::ParsedObject& obj,
voidlibc::format::TargetOS target_os);
} // namespace voidlibc::voidlink
File diff suppressed because it is too large. Load diff
+20
View File
@@ -0,0 +1,20 @@
#pragma once
// Per-OS symbol → import library table.
// Source of truth: data/symlib_{linux,windows,macos}.txt
#include "format/vlc_format.hpp"
#include <string_view>
namespace voidlibc::voidlink {
// Returns the import library for `name` on the given OS.
// Checks the builtin table; returns "" if not found (caller should use the
// per-OS default: libc.so.6 / ucrtbase.dll / /usr/lib/libSystem.B.dylib).
std::string_view library_for(voidlibc::format::TargetOS os, std::string_view name);
// Returns the per-OS default import library used as a fallback when no
// table entry is found.
std::string_view default_library(voidlibc::format::TargetOS os);
} // namespace voidlibc::voidlink
+46
View File
@@ -0,0 +1,46 @@
#include "writer.hpp"
#include "format/vlc_format.hpp"
#include <fstream>
namespace voidlibc::voidlink {
using namespace voidlibc::format;
WriteResult write_empty(const std::filesystem::path& out_path) {
std::ofstream out(out_path, std::ios::binary | std::ios::trunc);
if (!out) {
return {false, "could not open output: " + out_path.string()};
}
FileHeader hdr{};
hdr.magic = kMagic;
hdr.version_major = kVersionMajor;
hdr.version_minor = kVersionMinor;
hdr.flags = static_cast<std::uint32_t>(ContainerFlags::None);
hdr.arch = TargetArch::X86_64;
hdr.reserved = 0;
hdr.section_count = 0;
// Everything after the header is empty; point offsets at the end of
// the header so a reader walking pointers lands on valid, zero-size
// regions instead of stale zeros.
const std::uint64_t tail = sizeof(FileHeader);
hdr.section_dir_off = tail;
hdr.symtab_off = tail;
hdr.symtab_size = 0;
hdr.imports_off = tail;
hdr.imports_size = 0;
hdr.exports_off = tail;
hdr.exports_size = 0;
hdr.file_size = tail;
out.write(reinterpret_cast<const char*>(&hdr), sizeof(hdr));
if (!out) {
return {false, "write failed"};
}
return {true, {}};
}
} // namespace voidlibc::voidlink
+17
View File
@@ -0,0 +1,17 @@
#pragma once
#include <filesystem>
#include <string>
namespace voidlibc::voidlink {
struct WriteResult {
bool ok = false;
std::string error;
};
// Writes a syntactically-valid .vlc containing no sections, no symbols,
// no imports, no exports. Used for M0 round-trip testing of the format.
WriteResult write_empty(const std::filesystem::path& out_path);
} // namespace voidlibc::voidlink