Files
faumaray bba5c8a39a initial commit
Signed-off-by: Aleksey Selihov <faumaray@gmail.com>
2026-05-22 02:40:32 +03:00

817 lines
35 KiB
C++

#include "elf_synth.hpp"
#include "elf64.hpp"
#include "format/reloc_ir.hpp"
#include <cstring>
#include <sstream>
#include <unordered_map>
#include <unordered_set>
namespace voidlibc::loader {
namespace {
constexpr std::uint64_t kPageSize = 0x1000;
constexpr std::uint64_t align_up(std::uint64_t v, std::uint64_t a) {
return (v + (a - 1)) & ~(a - 1);
}
// Lay out as five segments:
// PT_LOAD R @ 0x0000 — Ehdr + Phdrs + .dynsym + .dynstr + .hash + [.rela.dyn] + [.rela.plt]
// PT_LOAD RX @ 0x1000 — [PLT stubs] + code
// PT_LOAD RW @ next page — [data blob] + [.got] + [.got.plt] + .dynamic
// PT_DYNAMIC — overlays the RW PT_LOAD
// PT_GNU_STACK — zero-size; tells the loader the stack is RW (not RWX)
constexpr std::uint16_t kPhdrCount = 5;
void write32le(std::vector<std::uint8_t>& buf, std::uint64_t off, std::int32_t v) {
std::uint32_t u;
std::memcpy(&u, &v, 4);
buf[off + 0] = static_cast<std::uint8_t>(u);
buf[off + 1] = static_cast<std::uint8_t>(u >> 8);
buf[off + 2] = static_cast<std::uint8_t>(u >> 16);
buf[off + 3] = static_cast<std::uint8_t>(u >> 24);
}
// Apply all portable reloc IR entries to the combined buffer.
//
// combined = [PLT stubs (plt_size bytes)] [.text + .rodata (code blob)]
// sym_id_to_got_vaddr = sym_id → run-time vaddr of its .got slot (external GOTPCREL only)
bool apply_relocs_combined(
std::vector<std::uint8_t>& combined,
const std::vector<voidlibc::format::RelocEntry>& relocs,
const std::vector<InternalSymbol>& internal_syms,
const std::vector<DataSymbol>& data_syms,
const std::unordered_map<std::uint32_t, std::uint32_t>& import_to_plt,
const std::unordered_map<std::uint32_t, std::uint64_t>& sym_id_to_got_vaddr,
std::uint64_t plt_size,
std::uint64_t code_vaddr,
std::uint64_t data_vaddr,
std::string& error) {
using namespace voidlibc::format;
std::unordered_map<std::uint32_t, std::uint64_t> sym_offset;
sym_offset.reserve(internal_syms.size());
for (const auto& s : internal_syms)
sym_offset.emplace(s.sym_id, s.code_offset);
std::unordered_map<std::uint32_t, std::uint64_t> data_sym_offset;
data_sym_offset.reserve(data_syms.size());
for (const auto& s : data_syms)
data_sym_offset.emplace(s.sym_id, s.data_offset);
auto patch32 = [&](std::uint64_t combined_off, std::int64_t v) -> bool {
if (combined_off + 4 > combined.size()) {
std::ostringstream os;
os << "reloc patch at 0x" << std::hex << combined_off
<< " out of range (combined size 0x" << combined.size() << ")";
error = os.str();
return false;
}
write32le(combined, combined_off, static_cast<std::int32_t>(v));
return true;
};
for (const auto& r : relocs) {
const std::uint64_t combined_off = plt_size + r.dst_offset;
switch (r.op) {
case RelocOp::PC32:
case RelocOp::PC32_1: case RelocOp::PC32_2:
case RelocOp::PC32_4: case RelocOp::PC32_5: {
std::int64_t bias = 0;
if (r.op == RelocOp::PC32_1) bias = -1;
else if (r.op == RelocOp::PC32_2) bias = -2;
else if (r.op == RelocOp::PC32_4) bias = -4;
else if (r.op == RelocOp::PC32_5) bias = -5;
// Try code blob first.
auto it = sym_offset.find(r.sym_id);
if (it != sym_offset.end()) {
const std::uint64_t target_combined = plt_size + it->second;
const std::int64_t disp =
static_cast<std::int64_t>(target_combined)
- static_cast<std::int64_t>(combined_off)
+ r.addend + bias;
if (!patch32(combined_off, disp)) return false;
break;
}
// Try data blob (cross-segment, vaddr-based).
auto dit = data_sym_offset.find(r.sym_id);
if (dit != data_sym_offset.end()) {
const std::int64_t disp =
static_cast<std::int64_t>(data_vaddr + dit->second)
- static_cast<std::int64_t>(code_vaddr + combined_off)
+ r.addend + bias;
if (!patch32(combined_off, disp)) return false;
break;
}
{
std::ostringstream os;
os << "PC32 reloc at 0x" << std::hex << r.dst_offset
<< " references unknown sym_id " << std::dec << r.sym_id;
error = os.str();
return false;
}
}
case RelocOp::PLT32: {
// Cross-object merge: if the sym is now defined internally,
// treat as a direct PC32 call (no PLT stub needed).
auto sit = sym_offset.find(r.sym_id);
if (sit != sym_offset.end()) {
const std::uint64_t target = plt_size + sit->second;
const std::int64_t disp =
static_cast<std::int64_t>(target)
- static_cast<std::int64_t>(combined_off)
+ r.addend;
if (!patch32(combined_off, disp)) return false;
break;
}
// External symbol — route through PLT stub.
auto it = import_to_plt.find(r.sym_id);
if (it == import_to_plt.end()) {
std::ostringstream os;
os << "PLT32 reloc at 0x" << std::hex << r.dst_offset
<< " references unknown import sym_id " << std::dec << r.sym_id;
error = os.str();
return false;
}
const std::uint64_t plt_stub = static_cast<std::uint64_t>(it->second + 1) * 16;
const std::int64_t disp =
static_cast<std::int64_t>(plt_stub)
+ r.addend
- static_cast<std::int64_t>(combined_off);
if (!patch32(combined_off, disp)) return false;
break;
}
case RelocOp::GotPC32:
case RelocOp::GotPC32X:
case RelocOp::GotPC32XRex: {
// Check for internal sym — relax if possible.
const bool relaxable =
(r.op == RelocOp::GotPC32X || r.op == RelocOp::GotPC32XRex);
auto it_code = sym_offset.find(r.sym_id);
auto it_data = data_sym_offset.find(r.sym_id);
const bool is_internal =
(it_code != sym_offset.end() || it_data != data_sym_offset.end());
if (is_internal && relaxable) {
// Relax movq sym@GOTPCREL(%rip), %reg → leaq sym(%rip), %reg
// Instruction layout: [REX] opcode(0x8B) ModRM disp32
// ^-1 ^combined_off
// Opcode is at combined_off-2; ModRM is at combined_off-1.
if (combined_off < 3 || combined[combined_off - 2] != 0x8B) {
std::ostringstream os;
os << "GotPC32(X)Xrex relaxation at 0x" << std::hex << r.dst_offset
<< ": expected 0x8B opcode at -2, got 0x"
<< static_cast<unsigned>(combined[combined_off - 2]);
error = os.str();
return false;
}
combined[combined_off - 2] = 0x8D; // MOV → LEA
std::int64_t disp;
if (it_code != sym_offset.end()) {
const std::uint64_t target = plt_size + it_code->second;
disp = static_cast<std::int64_t>(target)
- static_cast<std::int64_t>(combined_off)
+ r.addend;
} else {
disp = static_cast<std::int64_t>(data_vaddr + it_data->second)
- static_cast<std::int64_t>(code_vaddr + combined_off)
+ r.addend;
}
if (!patch32(combined_off, disp)) return false;
break;
}
// External sym — use the pre-allocated .got slot.
auto git = sym_id_to_got_vaddr.find(r.sym_id);
if (git == sym_id_to_got_vaddr.end()) {
std::ostringstream os;
os << "GOTPCREL reloc at 0x" << std::hex << r.dst_offset
<< " sym_id " << std::dec << r.sym_id
<< " has no GOT slot (internal sym must use relaxable form)";
error = os.str();
return false;
}
const std::int64_t disp =
static_cast<std::int64_t>(git->second)
- static_cast<std::int64_t>(code_vaddr + combined_off)
+ r.addend;
if (!patch32(combined_off, disp)) return false;
break;
}
case RelocOp::Abs64:
error = "Abs64 reloc not yet supported (needs R_X86_64_RELATIVE)";
return false;
case RelocOp::Abs32:
case RelocOp::Abs32Signed:
error = "Abs32 reloc not yet supported";
return false;
case RelocOp::TlsLE: case RelocOp::TlsIE:
case RelocOp::TlsGD: case RelocOp::TlsLD:
error = "TLS reloc not yet supported";
return false;
}
}
return true;
}
// Emit PLT[0] (bootstrap) and PLT[1..nimports] into combined[0..plt_size).
void fill_plt_stubs(std::vector<std::uint8_t>& combined,
std::uint64_t code_vaddr,
std::uint64_t gotplt_vaddr,
std::size_t nimports) {
if (nimports == 0) return;
// PLT[0]: bootstrap — pushq *GOT[1](%rip) ; jmpq *GOT[2](%rip) ; nop
{
const std::uint64_t plt0_vaddr = code_vaddr;
combined[0] = 0xff; combined[1] = 0x35;
const std::int32_t d1 = static_cast<std::int32_t>(
(gotplt_vaddr + 8) - (plt0_vaddr + 6));
write32le(combined, 2, d1);
combined[6] = 0xff; combined[7] = 0x25;
const std::int32_t d2 = static_cast<std::int32_t>(
(gotplt_vaddr + 16) - (plt0_vaddr + 12));
write32le(combined, 8, d2);
combined[12] = 0x0f; combined[13] = 0x1f;
combined[14] = 0x40; combined[15] = 0x00;
}
// PLT[i+1]: per-import stub
for (std::size_t i = 0; i < nimports; ++i) {
const std::uint64_t stub_off = static_cast<std::uint64_t>(1 + i) * 16;
const std::uint64_t stub_vaddr = code_vaddr + stub_off;
combined[stub_off + 0] = 0xff;
combined[stub_off + 1] = 0x25;
const std::int32_t dg = static_cast<std::int32_t>(
(gotplt_vaddr + (3 + i) * 8) - (stub_vaddr + 6));
write32le(combined, stub_off + 2, dg);
combined[stub_off + 6] = 0x68;
write32le(combined, stub_off + 7,
static_cast<std::int32_t>(static_cast<std::uint32_t>(i)));
combined[stub_off + 11] = 0xe9;
const std::int32_t dp = static_cast<std::int32_t>(
static_cast<std::int64_t>(code_vaddr)
- static_cast<std::int64_t>(stub_vaddr + 16));
write32le(combined, stub_off + 12, dp);
}
}
} // anonymous namespace
ElfSynthOutput synthesize_elf(const ElfSynthInput& input) {
ElfSynthOutput out{};
if (input.code.empty()) {
out.ok = false;
out.error = "elf_synth: code is empty";
return out;
}
// --- Classify imports: PLT (function calls) vs GOT data (extern variables) ---
// A sym_id referenced via PLT32 gets a PLT stub.
// A sym_id referenced via GotPC32* and not internal gets a .got slot + GLOB_DAT.
//
// Build quick lookup sets for internal and data symbols.
std::unordered_set<std::uint32_t> internal_sym_ids;
for (const auto& s : input.internal_symbols) internal_sym_ids.insert(s.sym_id);
std::unordered_set<std::uint32_t> data_sym_ids;
for (const auto& s : input.data_symbols) data_sym_ids.insert(s.sym_id);
// PLT-needed imports (referenced via PLT32 reloc).
std::unordered_map<std::uint32_t, std::uint32_t> import_to_plt;
// GOT-data imports (external sym referenced via GotPC32*; slot index within .got).
std::unordered_map<std::uint32_t, std::uint32_t> got_data_import_to_slot;
{
std::uint32_t plt_idx = 0;
std::uint32_t got_slot = 0;
using format::RelocOp;
for (const auto& r : input.relocs) {
if (r.op == RelocOp::PLT32) {
// Skip syms that are internally defined (cross-object resolution).
if (!internal_sym_ids.count(r.sym_id) &&
!data_sym_ids.count(r.sym_id) &&
!import_to_plt.count(r.sym_id))
import_to_plt.emplace(r.sym_id, plt_idx++);
} else if (r.op == RelocOp::GotPC32 ||
r.op == RelocOp::GotPC32X ||
r.op == RelocOp::GotPC32XRex) {
// Only external (non-internal, non-data) syms need GOT slots.
if (!internal_sym_ids.count(r.sym_id) &&
!data_sym_ids.count(r.sym_id) &&
!got_data_import_to_slot.count(r.sym_id)) {
got_data_import_to_slot.emplace(r.sym_id, got_slot++);
}
}
}
}
const std::size_t nimports = import_to_plt.size(); // PLT stubs
const std::uint32_t ngot_data = static_cast<std::uint32_t>(got_data_import_to_slot.size());
// --- Build combined buffer: [PLT stubs][.text + .rodata] ---
const std::uint64_t plt_size = nimports > 0
? static_cast<std::uint64_t>(1 + nimports) * 16
: 0;
std::vector<std::uint8_t> combined(plt_size + input.code.size(), 0);
std::memcpy(combined.data() + plt_size, input.code.data(), input.code.size());
// --- Compute key vaddrs before reloc patching ---
// RX segment: code_vaddr = kPageSize
// RW segment: starts at next page after RX
const std::uint64_t data_blob_size = input.data_blob.size();
const std::uint64_t rw_start_prelim =
align_up(kPageSize + plt_size + input.code.size(), kPageSize);
const std::uint64_t data_vaddr = rw_start_prelim; // data blob is first in RW
// .got (GLOB_DAT slots) comes after data blob (8-byte aligned).
const std::uint64_t got_data_vaddr_prelim =
align_up(rw_start_prelim + data_blob_size, 8);
// Build sym_id → GOT slot vaddr map for apply_relocs_combined.
std::unordered_map<std::uint32_t, std::uint64_t> sym_id_to_got_vaddr;
for (const auto& [sym_id, slot_idx] : got_data_import_to_slot)
sym_id_to_got_vaddr.emplace(sym_id, got_data_vaddr_prelim + slot_idx * 8);
// --- Apply relocs ---
if (!input.relocs.empty()) {
std::string reloc_err;
if (!apply_relocs_combined(combined, input.relocs,
input.internal_symbols, input.data_symbols,
import_to_plt,
sym_id_to_got_vaddr,
plt_size,
kPageSize, // code_vaddr
data_vaddr,
reloc_err)) {
out.ok = false;
out.error = "elf_synth: " + reloc_err;
return out;
}
}
// --- Build .dynstr ---
std::vector<char> dynstr;
dynstr.push_back('\0');
std::vector<std::uint32_t> export_name_offs;
export_name_offs.reserve(input.exports.size());
for (const auto& e : input.exports) {
export_name_offs.push_back(static_cast<std::uint32_t>(dynstr.size()));
dynstr.insert(dynstr.end(), e.name.begin(), e.name.end());
dynstr.push_back('\0');
}
// All imports (PLT + GOT data) get dynstr entries.
std::vector<std::uint32_t> import_name_offs;
import_name_offs.reserve(input.imports.size());
for (const auto& im : input.imports) {
import_name_offs.push_back(static_cast<std::uint32_t>(dynstr.size()));
dynstr.insert(dynstr.end(), im.name.begin(), im.name.end());
dynstr.push_back('\0');
}
// DT_NEEDED entries: one per distinct import library.
// When input.needed_libs is set explicitly (--need), use that verbatim.
// Otherwise derive from import.library fields; fall back to libc.so.6 if
// we have imports but no per-import library information.
std::vector<std::uint32_t> needed_name_offs;
{
std::vector<std::string> libs;
if (!input.needed_libs.empty()) {
libs = input.needed_libs;
} else {
// Collect unique libraries in insertion order.
std::vector<std::string> seen_order;
std::unordered_map<std::string, bool> seen;
for (const auto& im : input.imports) {
const std::string& lib = im.library.empty() ? std::string{"libc.so.6"} : im.library;
if (seen.emplace(lib, true).second)
seen_order.push_back(lib);
}
libs = std::move(seen_order);
if (libs.empty() && !input.imports.empty())
libs.push_back("libc.so.6");
}
for (const auto& lib : libs) {
needed_name_offs.push_back(static_cast<std::uint32_t>(dynstr.size()));
dynstr.insert(dynstr.end(), lib.begin(), lib.end());
dynstr.push_back('\0');
}
}
std::uint32_t soname_off = 0;
if (!input.soname.empty()) {
soname_off = static_cast<std::uint32_t>(dynstr.size());
dynstr.insert(dynstr.end(), input.soname.begin(), input.soname.end());
dynstr.push_back('\0');
}
// Build sym_id → .dynsym index map for all imports (needed for GLOB_DAT r_info).
const std::size_t nexports = input.exports.size();
const std::size_t nall_imports = input.imports.size();
std::unordered_map<std::uint32_t, std::uint32_t> sym_id_to_dynsym;
for (std::size_t i = 0; i < nall_imports; ++i)
sym_id_to_dynsym[input.imports[i].sym_id] =
static_cast<std::uint32_t>(1 + nexports + i);
// --- Build GNU symbol versioning tables (Phase C) ---
// Assign local version indices starting at 2 for unique (library, version_name) pairs.
// Index 0 = VER_NDX_LOCAL, 1 = VER_NDX_GLOBAL (unversioned), 2+ = requirements.
struct VerEntry {
std::string library;
std::string version_name;
std::uint32_t hash = 0;
std::uint16_t flags = 0;
std::uint16_t index = 0; // assigned version index
};
std::vector<VerEntry> ver_entries; // unique versioned requirements, in order
// per-import version index (parallel to input.imports); 1 if unversioned
std::vector<std::uint16_t> import_ver_idx(nall_imports, 1);
const bool needs_versioning = [&] {
for (const auto& im : input.imports)
if (!im.version_name.empty()) return true;
return false;
}();
if (needs_versioning) {
std::uint16_t next_idx = 2;
std::unordered_map<std::string, std::uint16_t> ver_key_to_idx;
for (std::size_t i = 0; i < nall_imports; ++i) {
const auto& im = input.imports[i];
if (im.version_name.empty()) continue;
const std::string key = im.library + '\0' + im.version_name;
auto [it, inserted] = ver_key_to_idx.emplace(key, next_idx);
if (inserted) {
VerEntry ve;
ve.library = im.library.empty() ? "libc.so.6" : im.library;
ve.version_name = im.version_name;
ve.hash = im.version_hash;
ve.flags = im.version_flags;
ve.index = next_idx++;
ver_entries.push_back(std::move(ve));
}
import_ver_idx[i] = it->second;
}
}
// Build .gnu.version bytes: one uint16_t per dynsym entry.
// [0]=local(0), [1..nexports]=global(1), [nexports+1..]=per-import index.
std::vector<std::uint8_t> gnu_version_bytes;
// Build .gnu.version_r bytes: grouped by library.
std::vector<std::uint8_t> gnu_verneed_bytes;
std::uint32_t n_verneed = 0; // number of Verneed records (for DT_VERNEEDNUM)
if (needs_versioning) {
const std::uint64_t ndynsym_val = 1u + nexports + nall_imports;
gnu_version_bytes.resize(ndynsym_val * 2, 0);
// [0] stays 0 (VER_NDX_LOCAL for null sym); exports get 1 (VER_NDX_GLOBAL).
for (std::uint64_t i = 0; i < nexports; ++i) {
std::uint16_t vi = 1;
std::memcpy(gnu_version_bytes.data() + (1 + i) * 2, &vi, 2);
}
for (std::size_t i = 0; i < nall_imports; ++i) {
std::uint16_t vi = import_ver_idx[i];
std::memcpy(gnu_version_bytes.data() + (1 + nexports + i) * 2, &vi, 2);
}
// Align to 8 bytes.
while (gnu_version_bytes.size() % 8) gnu_version_bytes.push_back(0);
// Build .gnu.version_r: group VerEntries by library.
// Use the dynstr already being built. We need to add library + version names
// to dynstr now, so we interleave the strtab build here.
// Collect unique (library) groups preserving insertion order.
std::vector<std::string> vn_libs_order;
std::unordered_map<std::string, std::vector<std::size_t>> vn_lib_to_entries;
for (std::size_t i = 0; i < ver_entries.size(); ++i) {
auto [it, inserted] = vn_lib_to_entries.emplace(ver_entries[i].library,
std::vector<std::size_t>{});
if (inserted) vn_libs_order.push_back(ver_entries[i].library);
it->second.push_back(i);
}
n_verneed = static_cast<std::uint32_t>(vn_libs_order.size());
// Pre-compute strtab offsets for all strings we'll add.
// Note: dynstr is still being built so these come after DT_NEEDED/soname entries.
struct VnStrings { std::uint32_t lib_off; std::vector<std::uint32_t> ver_offs; };
std::vector<VnStrings> vn_strs;
for (const auto& lib : vn_libs_order) {
VnStrings vs;
vs.lib_off = static_cast<std::uint32_t>(dynstr.size());
dynstr.insert(dynstr.end(), lib.begin(), lib.end()); dynstr.push_back('\0');
for (std::size_t ei : vn_lib_to_entries[lib]) {
vs.ver_offs.push_back(static_cast<std::uint32_t>(dynstr.size()));
const std::string& vn = ver_entries[ei].version_name;
dynstr.insert(dynstr.end(), vn.begin(), vn.end()); dynstr.push_back('\0');
}
vn_strs.push_back(std::move(vs));
}
// Now build the raw Verneed + Vernaux binary blob.
for (std::size_t li = 0; li < vn_libs_order.size(); ++li) {
const auto& lib = vn_libs_order[li];
const auto& idxs = vn_lib_to_entries[lib];
const auto& vstrs = vn_strs[li];
const bool last_lib = (li + 1 == vn_libs_order.size());
Verneed vn{};
vn.vn_version = 1;
vn.vn_cnt = static_cast<std::uint16_t>(idxs.size());
vn.vn_file = vstrs.lib_off;
vn.vn_aux = sizeof(Verneed);
vn.vn_next = last_lib ? 0u
: static_cast<std::uint32_t>(sizeof(Verneed) + idxs.size() * sizeof(Vernaux));
const std::size_t vn_off = gnu_verneed_bytes.size();
gnu_verneed_bytes.resize(vn_off + sizeof(Verneed), 0);
std::memcpy(gnu_verneed_bytes.data() + vn_off, &vn, sizeof(vn));
for (std::size_t ai = 0; ai < idxs.size(); ++ai) {
const auto& ve = ver_entries[idxs[ai]];
const bool last_aux = (ai + 1 == idxs.size());
Vernaux va{};
va.vna_hash = ve.hash;
va.vna_flags = ve.flags;
va.vna_other = ve.index;
va.vna_name = vstrs.ver_offs[ai];
va.vna_next = last_aux ? 0u : static_cast<std::uint32_t>(sizeof(Vernaux));
const std::size_t va_off = gnu_verneed_bytes.size();
gnu_verneed_bytes.resize(va_off + sizeof(Vernaux), 0);
std::memcpy(gnu_verneed_bytes.data() + va_off, &va, sizeof(va));
}
}
while (gnu_verneed_bytes.size() % 8) gnu_verneed_bytes.push_back(0);
}
// --- Plan segment 0 (RO) layout ---
const std::uint64_t phdr_off = sizeof(Ehdr);
const std::uint64_t phdr_size = static_cast<std::uint64_t>(kPhdrCount) * sizeof(Phdr);
const std::uint64_t ndynsym = 1u + nexports + nall_imports;
const std::uint64_t dynsym_off = phdr_off + phdr_size;
const std::uint64_t dynsym_size = ndynsym * sizeof(Sym);
const std::uint64_t dynstr_off = dynsym_off + dynsym_size;
const std::uint64_t dynstr_size = dynstr.size();
const std::uint32_t nbuckets = 1;
const std::uint32_t nchain = static_cast<std::uint32_t>(ndynsym);
const std::uint64_t hash_off = align_up(dynstr_off + dynstr_size, 8);
const std::uint64_t hash_size = (2u + nbuckets + nchain) * sizeof(std::uint32_t);
// .rela.dyn — R_X86_64_GLOB_DAT for each external GOTPCREL import.
const std::uint64_t reladyn_off = align_up(hash_off + hash_size, 8);
const std::uint64_t reladyn_size = ngot_data * sizeof(Rela);
const std::uint64_t relaplt_off = align_up(reladyn_off + reladyn_size, 8);
const std::uint64_t relaplt_size = nimports * sizeof(Rela);
// .gnu.version (SHT_GNU_versym) — only emitted when needs_versioning.
const std::uint64_t gnuver_off = align_up(relaplt_off + relaplt_size, 2);
const std::uint64_t gnuver_size = gnu_version_bytes.size();
// .gnu.version_r (SHT_GNU_verneed)
const std::uint64_t gnuvnr_off = align_up(gnuver_off + gnuver_size, 8);
const std::uint64_t gnuvnr_size = gnu_verneed_bytes.size();
const std::uint64_t seg0_filesz = gnuvnr_off + gnuvnr_size;
if (seg0_filesz > kPageSize) {
out.ok = false;
out.error = "elf_synth: RO segment exceeds one page; "
"split layout not yet supported";
return out;
}
// --- Plan segment 1 (RX) layout ---
const std::uint64_t code_off = kPageSize;
const std::uint64_t code_size = combined.size();
const std::uint64_t code_vaddr = kPageSize;
// --- Plan segment 2 (RW) layout: [data blob] [.got] [.got.plt] [.dynamic] ---
const std::uint64_t rw_start = align_up(code_off + code_size, kPageSize);
const std::uint64_t data_off = rw_start;
const std::uint64_t got_data_off = align_up(data_off + data_blob_size, 8);
const std::uint64_t got_data_size = ngot_data * sizeof(std::uint64_t);
const std::uint64_t gotplt_off = align_up(got_data_off + got_data_size, 8);
const std::uint64_t gotplt_size = nimports > 0
? (3u + nimports) * sizeof(std::uint64_t)
: 0;
const std::uint64_t dyn_off = align_up(gotplt_off + gotplt_size, 8);
const std::uint64_t gotplt_vaddr = gotplt_off; // file_offset == vaddr
// Verify consistency: got_data_off must equal got_data_vaddr_prelim.
// (Both compute align_up(rw_start + data_blob_size, 8).)
// Fill PLT stubs now that we know gotplt_vaddr.
fill_plt_stubs(combined, code_vaddr, gotplt_vaddr, nimports);
// --- Build .dynamic ---
std::vector<Dyn> dyn;
auto add_dyn = [&](std::int64_t tag, std::uint64_t val) {
dyn.push_back(Dyn{tag, val});
};
add_dyn(kDtHash, hash_off);
add_dyn(kDtStrtab, dynstr_off);
add_dyn(kDtSymtab, dynsym_off);
add_dyn(kDtStrsz, dynstr_size);
add_dyn(kDtSyment, sizeof(Sym));
if (soname_off) add_dyn(kDtSoname, soname_off);
for (std::uint32_t off : needed_name_offs)
add_dyn(kDtNeeded, off);
if (ngot_data > 0) {
add_dyn(kDtRela, reladyn_off);
add_dyn(kDtRelaSz, reladyn_size);
add_dyn(kDtRelaEnt, sizeof(Rela));
}
if (nimports > 0) {
add_dyn(kDtPltGot, gotplt_vaddr);
add_dyn(kDtPltRelSz, relaplt_size);
add_dyn(kDtPltRel, static_cast<std::uint64_t>(kDtRela));
add_dyn(kDtJmpRel, relaplt_off);
}
if (needs_versioning) {
add_dyn(kDtVersym, gnuver_off);
add_dyn(kDtVerneed, gnuvnr_off);
add_dyn(kDtVerneedNum, static_cast<std::uint64_t>(n_verneed));
}
add_dyn(kDtFlags, static_cast<std::uint64_t>(kDfBindNow));
add_dyn(kDtFlags1, static_cast<std::uint64_t>(kDf1Now));
add_dyn(kDtNull, 0);
const std::uint64_t dyn_size = dyn.size() * sizeof(Dyn);
const std::uint64_t file_size = dyn_off + dyn_size;
// --- Emit file ---
out.bytes.assign(file_size, 0);
auto write_at = [&](std::uint64_t off, const void* src, std::uint64_t n) {
std::memcpy(out.bytes.data() + off, src, n);
};
// Ehdr
Ehdr eh{};
eh.e_ident[0] = kElfMag0; eh.e_ident[1] = kElfMag1;
eh.e_ident[2] = kElfMag2; eh.e_ident[3] = kElfMag3;
eh.e_ident[4] = kElfClass64;
eh.e_ident[5] = kElfData2LSB;
eh.e_ident[6] = kElfVersionCurrent;
eh.e_ident[7] = kElfOsAbiSysV;
eh.e_type = kEtDyn;
eh.e_machine = kEmX86_64;
eh.e_version = kEvCurrent;
eh.e_entry = 0;
eh.e_phoff = phdr_off;
eh.e_shoff = 0;
eh.e_flags = 0;
eh.e_ehsize = sizeof(Ehdr);
eh.e_phentsize = sizeof(Phdr);
eh.e_phnum = kPhdrCount;
eh.e_shentsize = 0;
eh.e_shnum = 0;
eh.e_shstrndx = 0;
write_at(0, &eh, sizeof(eh));
// Phdrs
Phdr phdrs[kPhdrCount] = {};
phdrs[0].p_type = kPtLoad; phdrs[0].p_flags = kPfR;
phdrs[0].p_offset = 0; phdrs[0].p_vaddr = 0; phdrs[0].p_paddr = 0;
phdrs[0].p_filesz = seg0_filesz; phdrs[0].p_memsz = seg0_filesz;
phdrs[0].p_align = kPageSize;
phdrs[1].p_type = kPtLoad; phdrs[1].p_flags = kPfR | kPfX;
phdrs[1].p_offset = code_off; phdrs[1].p_vaddr = code_vaddr; phdrs[1].p_paddr = code_vaddr;
phdrs[1].p_filesz = code_size; phdrs[1].p_memsz = code_size;
phdrs[1].p_align = kPageSize;
phdrs[2].p_type = kPtLoad; phdrs[2].p_flags = kPfR | kPfW;
phdrs[2].p_offset = rw_start; phdrs[2].p_vaddr = rw_start; phdrs[2].p_paddr = rw_start;
phdrs[2].p_filesz = dyn_off + dyn_size - rw_start;
phdrs[2].p_memsz = phdrs[2].p_filesz;
phdrs[2].p_align = kPageSize;
phdrs[3].p_type = kPtDynamic; phdrs[3].p_flags = kPfR | kPfW;
phdrs[3].p_offset = dyn_off; phdrs[3].p_vaddr = dyn_off; phdrs[3].p_paddr = dyn_off;
phdrs[3].p_filesz = dyn_size; phdrs[3].p_memsz = dyn_size;
phdrs[3].p_align = 8;
phdrs[4].p_type = kPtGnuStack; phdrs[4].p_flags = kPfR | kPfW;
phdrs[4].p_align = 16;
write_at(phdr_off, phdrs, sizeof(phdrs));
// .dynsym: [0]=undef, [1..nexports]=exports, [nexports+1..]=all imports
{
std::vector<Sym> syms(ndynsym);
syms[0] = Sym{};
for (std::size_t i = 0; i < nexports; ++i) {
const auto& e = input.exports[i];
Sym s{};
s.st_name = export_name_offs[i];
s.st_info = st_info(e.weak ? kStbWeak : kStbGlobal,
e.is_function ? kSttFunc : kSttObject);
s.st_shndx = 1;
s.st_value = code_vaddr + plt_size + e.code_offset;
s.st_size = e.size;
syms[i + 1] = s;
}
for (std::size_t i = 0; i < nall_imports; ++i) {
Sym s{};
s.st_name = import_name_offs[i];
s.st_info = st_info(kStbGlobal, kSttObject); // may be func or obj; RTLD doesn't care
s.st_shndx = kShnUndef;
s.st_value = 0;
s.st_size = 0;
syms[nexports + 1 + i] = s;
}
write_at(dynsym_off, syms.data(), dynsym_size);
}
// .dynstr
write_at(dynstr_off, dynstr.data(), dynstr_size);
// .hash — single-bucket chain through all exported symbols
{
std::vector<std::uint32_t> hash_tab(2 + nbuckets + nchain, 0);
hash_tab[0] = nbuckets;
hash_tab[1] = nchain;
if (nexports > 0) {
hash_tab[2] = 1;
for (std::uint32_t i = 1; i + 1 < static_cast<std::uint32_t>(nexports + 1); ++i)
hash_tab[2 + nbuckets + i] = i + 1;
}
write_at(hash_off, hash_tab.data(), hash_size);
}
// .rela.dyn — R_X86_64_GLOB_DAT for each external GOTPCREL import
if (ngot_data > 0) {
std::vector<Rela> rela_dyn;
rela_dyn.reserve(ngot_data);
for (const auto& [sym_id, slot_idx] : got_data_import_to_slot) {
const std::uint64_t got_slot_vaddr = got_data_off + slot_idx * 8;
const auto dsym_it = sym_id_to_dynsym.find(sym_id);
if (dsym_it == sym_id_to_dynsym.end()) {
out.ok = false;
out.error = "elf_synth: GOT import sym_id not in .dynsym";
return out;
}
Rela r{};
r.r_offset = got_slot_vaddr;
r.r_info = (static_cast<std::uint64_t>(dsym_it->second) << 32) | kRX86_64_GlobDat;
r.r_addend = 0;
rela_dyn.push_back(r);
}
write_at(reladyn_off, rela_dyn.data(), reladyn_size);
}
// .gnu.version + .gnu.version_r (emitted only when needs_versioning)
if (needs_versioning) {
if (!gnu_version_bytes.empty())
write_at(gnuver_off, gnu_version_bytes.data(), gnu_version_bytes.size());
if (!gnu_verneed_bytes.empty())
write_at(gnuvnr_off, gnu_verneed_bytes.data(), gnu_verneed_bytes.size());
}
// .rela.plt — R_X86_64_JUMP_SLOT for each PLT import
if (nimports > 0) {
// Build ordered list of PLT imports (import_to_plt maps sym_id → index).
std::vector<const ImportedSymbol*> plt_syms(nimports);
for (const auto& im : input.imports) {
auto it = import_to_plt.find(im.sym_id);
if (it != import_to_plt.end())
plt_syms[it->second] = &im;
}
std::vector<Rela> rela_plt(nimports);
for (std::size_t i = 0; i < nimports; ++i) {
const std::uint64_t got_slot = gotplt_vaddr + (3 + i) * sizeof(std::uint64_t);
const std::uint64_t dsym_idx = sym_id_to_dynsym.at(plt_syms[i]->sym_id);
rela_plt[i].r_offset = got_slot;
rela_plt[i].r_info = (dsym_idx << 32) | kRX86_64_JumpSlot;
rela_plt[i].r_addend = 0;
}
write_at(relaplt_off, rela_plt.data(), relaplt_size);
}
// Code (PLT stubs + patched .text + .rodata)
write_at(code_off, combined.data(), code_size);
// Data blob (.data + .bss zeros)
if (!input.data_blob.empty())
write_at(data_off, input.data_blob.data(), data_blob_size);
// .got (GLOB_DAT slots) — zeroed (RTLD fills with GLOB_DAT at load time)
// out.bytes is already zero-initialised, nothing to write.
// .got.plt — zeroed; RTLD fills with JUMP_SLOT targets (DF_BIND_NOW / RTLD_NOW).
// out.bytes is already zero-initialised.
// .dynamic
write_at(dyn_off, dyn.data(), dyn_size);
out.code_vaddr = code_vaddr + plt_size;
return out;
}
} // namespace voidlibc::loader