commit
bba5c8a39a
109 files changed
+14085
No files matched your search
@@ -0,0 +1,4 @@
|
||||
add_subdirectory(common)
|
||||
add_subdirectory(linux)
|
||||
add_subdirectory(windows)
|
||||
add_subdirectory(macos)
|
||||
@@ -0,0 +1,14 @@
|
||||
add_library(voidlibc_loader_common STATIC
|
||||
elf_synth.cpp
|
||||
)
|
||||
target_include_directories(voidlibc_loader_common PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_SOURCE_DIR}>
|
||||
$<BUILD_INTERFACE:${CMAKE_SOURCE_DIR}/loader>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
target_link_libraries(voidlibc_loader_common PUBLIC voidlibc_format)
|
||||
set_target_properties(voidlibc_loader_common PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
||||
install(TARGETS voidlibc_loader_common
|
||||
EXPORT VoidLibCTargets
|
||||
ARCHIVE DESTINATION lib
|
||||
)
|
||||
@@ -0,0 +1,216 @@
|
||||
#pragma once
|
||||
|
||||
// Minimal x86_64 ELF64 definitions, in-tree to avoid <elf.h> noise.
|
||||
// Only the subset we synthesize is here.
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace voidlibc::loader {
|
||||
|
||||
inline constexpr std::uint8_t kElfMag0 = 0x7F;
|
||||
inline constexpr std::uint8_t kElfMag1 = 'E';
|
||||
inline constexpr std::uint8_t kElfMag2 = 'L';
|
||||
inline constexpr std::uint8_t kElfMag3 = 'F';
|
||||
|
||||
inline constexpr std::uint8_t kElfClass64 = 2;
|
||||
inline constexpr std::uint8_t kElfData2LSB = 1;
|
||||
inline constexpr std::uint8_t kElfVersionCurrent = 1;
|
||||
inline constexpr std::uint8_t kElfOsAbiSysV = 0;
|
||||
|
||||
inline constexpr std::uint16_t kEtRel = 1;
|
||||
inline constexpr std::uint16_t kEtDyn = 3;
|
||||
inline constexpr std::uint16_t kEmX86_64 = 62;
|
||||
inline constexpr std::uint32_t kEvCurrent = 1;
|
||||
|
||||
// Section header types
|
||||
inline constexpr std::uint32_t kShtNull = 0;
|
||||
inline constexpr std::uint32_t kShtProgbits = 1;
|
||||
inline constexpr std::uint32_t kShtSymtab = 2;
|
||||
inline constexpr std::uint32_t kShtStrtab = 3;
|
||||
inline constexpr std::uint32_t kShtRela = 4;
|
||||
inline constexpr std::uint32_t kShtNobits = 8;
|
||||
inline constexpr std::uint32_t kShtRel = 9;
|
||||
inline constexpr std::uint32_t kShtGnuVerdef = 0x6FFFFFFDu; // .gnu.version_d
|
||||
inline constexpr std::uint32_t kShtGnuVerneed = 0x6FFFFFFEu; // .gnu.version_r
|
||||
inline constexpr std::uint32_t kShtGnuVersym = 0x6FFFFFFFu; // .gnu.version
|
||||
|
||||
// Section header flags
|
||||
inline constexpr std::uint64_t kShfWrite = 0x1;
|
||||
inline constexpr std::uint64_t kShfAlloc = 0x2;
|
||||
inline constexpr std::uint64_t kShfExecinstr = 0x4;
|
||||
|
||||
// x86_64 relocation types (subset)
|
||||
inline constexpr std::uint32_t kRX86_64_None = 0;
|
||||
inline constexpr std::uint32_t kRX86_64_64 = 1;
|
||||
inline constexpr std::uint32_t kRX86_64_PC32 = 2;
|
||||
inline constexpr std::uint32_t kRX86_64_GOT32 = 3;
|
||||
inline constexpr std::uint32_t kRX86_64_PLT32 = 4;
|
||||
inline constexpr std::uint32_t kRX86_64_GOTPCREL = 9;
|
||||
inline constexpr std::uint32_t kRX86_64_32 = 10;
|
||||
inline constexpr std::uint32_t kRX86_64_32S = 11;
|
||||
inline constexpr std::uint32_t kRX86_64_GOTPCRELX = 41;
|
||||
inline constexpr std::uint32_t kRX86_64_REX_GOTPCRELX = 42;
|
||||
|
||||
inline constexpr std::uint32_t r_sym(std::uint64_t info) { return static_cast<std::uint32_t>(info >> 32); }
|
||||
inline constexpr std::uint32_t r_type(std::uint64_t info) { return static_cast<std::uint32_t>(info & 0xFFFFFFFFu); }
|
||||
|
||||
// Phdr p_type
|
||||
inline constexpr std::uint32_t kPtLoad = 1;
|
||||
inline constexpr std::uint32_t kPtDynamic = 2;
|
||||
inline constexpr std::uint32_t kPtPhdr = 6;
|
||||
inline constexpr std::uint32_t kPtGnuStack = 0x6474E551; // GNU non-exec stack marker
|
||||
|
||||
// Phdr p_flags
|
||||
inline constexpr std::uint32_t kPfX = 1;
|
||||
inline constexpr std::uint32_t kPfW = 2;
|
||||
inline constexpr std::uint32_t kPfR = 4;
|
||||
|
||||
// Sym st_info bind/type
|
||||
inline constexpr std::uint8_t kStbLocal = 0;
|
||||
inline constexpr std::uint8_t kStbGlobal = 1;
|
||||
inline constexpr std::uint8_t kStbWeak = 2;
|
||||
inline constexpr std::uint8_t kSttNotype = 0;
|
||||
inline constexpr std::uint8_t kSttObject = 1;
|
||||
inline constexpr std::uint8_t kSttFunc = 2;
|
||||
|
||||
inline constexpr std::uint8_t st_info(std::uint8_t bind, std::uint8_t type) {
|
||||
return static_cast<std::uint8_t>((bind << 4) | (type & 0xF));
|
||||
}
|
||||
|
||||
inline constexpr std::uint16_t kShnUndef = 0;
|
||||
inline constexpr std::uint16_t kShnAbs = 0xFFF1;
|
||||
|
||||
// x86_64 dynamic relocation types
|
||||
inline constexpr std::uint32_t kRX86_64_GlobDat = 6;
|
||||
inline constexpr std::uint32_t kRX86_64_JumpSlot = 7;
|
||||
inline constexpr std::uint32_t kRX86_64_Relative = 8;
|
||||
|
||||
// Dynamic tags
|
||||
inline constexpr std::int64_t kDtNull = 0;
|
||||
inline constexpr std::int64_t kDtNeeded = 1;
|
||||
inline constexpr std::int64_t kDtPltRelSz = 2;
|
||||
inline constexpr std::int64_t kDtPltGot = 3;
|
||||
inline constexpr std::int64_t kDtHash = 4;
|
||||
inline constexpr std::int64_t kDtStrtab = 5;
|
||||
inline constexpr std::int64_t kDtSymtab = 6;
|
||||
inline constexpr std::int64_t kDtRela = 7; // also used as DT_PLTREL value
|
||||
inline constexpr std::int64_t kDtRelaSz = 8;
|
||||
inline constexpr std::int64_t kDtRelaEnt = 9;
|
||||
inline constexpr std::int64_t kDtStrsz = 10;
|
||||
inline constexpr std::int64_t kDtSyment = 11;
|
||||
inline constexpr std::int64_t kDtSoname = 14;
|
||||
inline constexpr std::int64_t kDtPltRel = 20; // DT_PLTREL (type of PLT relocs)
|
||||
inline constexpr std::int64_t kDtJmpRel = 23; // DT_JMPREL (vaddr of .rela.plt)
|
||||
inline constexpr std::int64_t kDtFlags = 30;
|
||||
inline constexpr std::int64_t kDtFlags1 = 0x6FFFFFFB;
|
||||
inline constexpr std::int64_t kDtVersym = 0x6FFFFFF0;
|
||||
inline constexpr std::int64_t kDtVerneed = 0x6FFFFFFE;
|
||||
inline constexpr std::int64_t kDtVerneedNum = 0x6FFFFFFF;
|
||||
inline constexpr std::int64_t kDfBindNow = 0x8;
|
||||
inline constexpr std::int64_t kDf1Now = 0x1;
|
||||
|
||||
#pragma pack(push, 1)
|
||||
|
||||
struct Ehdr {
|
||||
std::uint8_t e_ident[16];
|
||||
std::uint16_t e_type;
|
||||
std::uint16_t e_machine;
|
||||
std::uint32_t e_version;
|
||||
std::uint64_t e_entry;
|
||||
std::uint64_t e_phoff;
|
||||
std::uint64_t e_shoff;
|
||||
std::uint32_t e_flags;
|
||||
std::uint16_t e_ehsize;
|
||||
std::uint16_t e_phentsize;
|
||||
std::uint16_t e_phnum;
|
||||
std::uint16_t e_shentsize;
|
||||
std::uint16_t e_shnum;
|
||||
std::uint16_t e_shstrndx;
|
||||
};
|
||||
static_assert(sizeof(Ehdr) == 64);
|
||||
|
||||
struct Phdr {
|
||||
std::uint32_t p_type;
|
||||
std::uint32_t p_flags;
|
||||
std::uint64_t p_offset;
|
||||
std::uint64_t p_vaddr;
|
||||
std::uint64_t p_paddr;
|
||||
std::uint64_t p_filesz;
|
||||
std::uint64_t p_memsz;
|
||||
std::uint64_t p_align;
|
||||
};
|
||||
static_assert(sizeof(Phdr) == 56);
|
||||
|
||||
struct Shdr {
|
||||
std::uint32_t sh_name;
|
||||
std::uint32_t sh_type;
|
||||
std::uint64_t sh_flags;
|
||||
std::uint64_t sh_addr;
|
||||
std::uint64_t sh_offset;
|
||||
std::uint64_t sh_size;
|
||||
std::uint32_t sh_link;
|
||||
std::uint32_t sh_info;
|
||||
std::uint64_t sh_addralign;
|
||||
std::uint64_t sh_entsize;
|
||||
};
|
||||
static_assert(sizeof(Shdr) == 64);
|
||||
|
||||
struct Sym {
|
||||
std::uint32_t st_name;
|
||||
std::uint8_t st_info;
|
||||
std::uint8_t st_other;
|
||||
std::uint16_t st_shndx;
|
||||
std::uint64_t st_value;
|
||||
std::uint64_t st_size;
|
||||
};
|
||||
static_assert(sizeof(Sym) == 24);
|
||||
|
||||
inline constexpr std::uint8_t st_bind(std::uint8_t info) { return info >> 4; }
|
||||
inline constexpr std::uint8_t st_type(std::uint8_t info) { return info & 0xF; }
|
||||
|
||||
struct Rela {
|
||||
std::uint64_t r_offset;
|
||||
std::uint64_t r_info;
|
||||
std::int64_t r_addend;
|
||||
};
|
||||
static_assert(sizeof(Rela) == 24);
|
||||
|
||||
struct Dyn {
|
||||
std::int64_t d_tag;
|
||||
std::uint64_t d_val; // unioned with d_ptr in real ELF; same size
|
||||
};
|
||||
static_assert(sizeof(Dyn) == 16);
|
||||
|
||||
struct Verneed {
|
||||
std::uint16_t vn_version; // = 1
|
||||
std::uint16_t vn_cnt; // number of Vernaux entries
|
||||
std::uint32_t vn_file; // strtab offset to library name
|
||||
std::uint32_t vn_aux; // byte offset from this Verneed to first Vernaux
|
||||
std::uint32_t vn_next; // byte offset to next Verneed (0 = last)
|
||||
};
|
||||
static_assert(sizeof(Verneed) == 16);
|
||||
|
||||
struct Vernaux {
|
||||
std::uint32_t vna_hash; // ELF hash of version name
|
||||
std::uint16_t vna_flags; // 0 or VER_FLG_WEAK
|
||||
std::uint16_t vna_other; // version index (assigned locally)
|
||||
std::uint32_t vna_name; // strtab offset to version name
|
||||
std::uint32_t vna_next; // byte offset to next Vernaux (0 = last)
|
||||
};
|
||||
static_assert(sizeof(Vernaux) == 16);
|
||||
|
||||
#pragma pack(pop)
|
||||
|
||||
// SysV ELF hash, per the ELF gABI.
|
||||
inline std::uint32_t elf_hash(const char* name) {
|
||||
std::uint32_t h = 0;
|
||||
while (*name) {
|
||||
h = (h << 4) + static_cast<std::uint8_t>(*name++);
|
||||
const std::uint32_t g = h & 0xF0000000u;
|
||||
if (g) h ^= g >> 24;
|
||||
h &= ~g;
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
} // namespace voidlibc::loader
|
||||
@@ -0,0 +1,816 @@
|
||||
#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
|
||||
@@ -0,0 +1,77 @@
|
||||
#pragma once
|
||||
|
||||
#include "format/reloc_ir.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace voidlibc::loader {
|
||||
|
||||
struct ExportedSymbol {
|
||||
std::string name; // C-name (null-terminated when written)
|
||||
std::uint64_t code_offset; // offset into the code blob
|
||||
std::uint64_t size; // 0 if unknown
|
||||
bool is_function = true;
|
||||
bool weak = false;
|
||||
};
|
||||
|
||||
// For Slice 1B the synthesizer needs to resolve internal relocations
|
||||
// at synthesis time (PC-relative). Each `InternalSymbol` is a defined
|
||||
// symbol referenced by a relocation, identified by `sym_id` matching
|
||||
// the relocation's sym_id, and located at `code_offset` within the
|
||||
// code blob.
|
||||
struct InternalSymbol {
|
||||
std::uint32_t sym_id = 0;
|
||||
std::uint64_t code_offset = 0;
|
||||
std::string name; // for error messages
|
||||
};
|
||||
|
||||
// External (undefined) symbol resolved by the native linker via .rela.plt.
|
||||
struct ImportedSymbol {
|
||||
std::uint32_t sym_id = 0;
|
||||
std::string name;
|
||||
std::string library; // DT_NEEDED soname that provides this symbol; "" → default libc
|
||||
// GNU symbol version requirement forwarded from input .o (SHT_GNU_verneed).
|
||||
// Empty version_name → emit VER_NDX_GLOBAL (1) in .gnu.version; no .gnu.version_r entry.
|
||||
std::string version_name;
|
||||
std::uint32_t version_hash = 0;
|
||||
std::uint16_t version_flags = 0;
|
||||
};
|
||||
|
||||
// Writable symbol in the data blob (mapped in the RW segment).
|
||||
// PC32 relocs from .text to data symbols are patched using vaddr arithmetic.
|
||||
struct DataSymbol {
|
||||
std::uint32_t sym_id = 0;
|
||||
std::uint64_t data_offset = 0; // byte offset within data_blob
|
||||
std::string name;
|
||||
};
|
||||
|
||||
struct ElfSynthInput {
|
||||
std::vector<std::uint8_t> code;
|
||||
std::vector<ExportedSymbol> exports;
|
||||
std::vector<voidlibc::format::RelocEntry> relocs;
|
||||
std::vector<InternalSymbol> internal_symbols;
|
||||
std::vector<ImportedSymbol> imports;
|
||||
std::vector<std::uint8_t> data_blob; // .data + .bss (RW)
|
||||
std::vector<DataSymbol> data_symbols;
|
||||
std::string soname;
|
||||
// Explicit DT_NEEDED entries for the synthesized ELF's .dynamic section.
|
||||
// Empty = no host dependencies (statically linked VLC, ldd shows "statically linked").
|
||||
// Set via voidlink --need <soname> at pack time.
|
||||
std::vector<std::string> needed_libs;
|
||||
};
|
||||
|
||||
struct ElfSynthOutput {
|
||||
std::vector<std::uint8_t> bytes; // synthesized in-memory ELF64 DSO
|
||||
std::uint64_t code_vaddr = 0; // base vaddr where code is mapped
|
||||
std::string error; // empty on success
|
||||
bool ok = true;
|
||||
};
|
||||
|
||||
// Produce a valid in-memory ELF64 DSO (ET_DYN, EM_X86_64) that dlopen
|
||||
// will accept. Single contiguous .text + .dynsym/.dynstr/.hash/.dynamic.
|
||||
// No relocations, imports, or section headers — enough for M1 export.
|
||||
ElfSynthOutput synthesize_elf(const ElfSynthInput& input);
|
||||
|
||||
} // namespace voidlibc::loader
|
||||
@@ -0,0 +1,13 @@
|
||||
# Placeholder; the Linux handoff source is added in the next task.
|
||||
add_library(voidlibc_loader_linux STATIC
|
||||
handoff.cpp
|
||||
)
|
||||
target_link_libraries(voidlibc_loader_linux
|
||||
PUBLIC voidlibc_loader_common
|
||||
PRIVATE ${CMAKE_DL_LIBS}
|
||||
)
|
||||
set_target_properties(voidlibc_loader_linux PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
||||
install(TARGETS voidlibc_loader_linux
|
||||
EXPORT VoidLibCTargets
|
||||
ARCHIVE DESTINATION lib
|
||||
)
|
||||
@@ -0,0 +1,136 @@
|
||||
#include "handoff.hpp"
|
||||
|
||||
#ifdef __linux__
|
||||
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
#include <dlfcn.h>
|
||||
#include <fcntl.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
|
||||
namespace voidlibc::loader::linux_handoff {
|
||||
|
||||
namespace {
|
||||
|
||||
int memfd_create_sys(const char* name, unsigned int flags) {
|
||||
// glibc has memfd_create() but only in recent versions; go via
|
||||
// syscall to keep this independent of host libc feature levels.
|
||||
return static_cast<int>(::syscall(SYS_memfd_create, name, flags));
|
||||
}
|
||||
|
||||
bool write_all(int fd, const std::uint8_t* p, std::size_t n) {
|
||||
while (n > 0) {
|
||||
const auto w = ::write(fd, p, n);
|
||||
if (w < 0) {
|
||||
if (errno == EINTR) continue;
|
||||
return false;
|
||||
}
|
||||
if (w == 0) return false;
|
||||
p += static_cast<std::size_t>(w);
|
||||
n -= static_cast<std::size_t>(w);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string errno_msg(const char* where) {
|
||||
char buf[256];
|
||||
std::snprintf(buf, sizeof(buf), "%s: %s", where, std::strerror(errno));
|
||||
return std::string(buf);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
LoadResult dlopen_buffer(const std::vector<std::uint8_t>& elf_bytes,
|
||||
const char* debug_name) {
|
||||
LoadResult r{};
|
||||
|
||||
int fd = memfd_create_sys(debug_name ? debug_name : "voidlibc.elf", 0);
|
||||
bool used_tmpfile = false;
|
||||
char tmpl[] = "/tmp/voidlibc.elf.XXXXXX";
|
||||
if (fd < 0) {
|
||||
// Fallback: O_TMPFILE on /tmp (kernel < 3.17 won't have memfd).
|
||||
fd = ::open("/tmp",
|
||||
O_TMPFILE | O_RDWR | O_EXCL,
|
||||
S_IRUSR | S_IWUSR | S_IXUSR);
|
||||
if (fd < 0) {
|
||||
// Final fallback: a named temp file we manually unlink.
|
||||
fd = ::mkstemp(tmpl);
|
||||
if (fd < 0) {
|
||||
r.error = errno_msg("memfd/tmpfile open");
|
||||
return r;
|
||||
}
|
||||
used_tmpfile = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!write_all(fd, elf_bytes.data(), elf_bytes.size())) {
|
||||
r.error = errno_msg("write elf bytes");
|
||||
::close(fd);
|
||||
if (used_tmpfile) ::unlink(tmpl);
|
||||
return r;
|
||||
}
|
||||
|
||||
// dlopen via /proc/self/fd/N — this works for memfds and unnamed
|
||||
// O_TMPFILE files.
|
||||
char path[64];
|
||||
std::snprintf(path, sizeof(path), "/proc/self/fd/%d", fd);
|
||||
|
||||
// Use RTLD_NEXT to bypass the libvoid dlopen interposer (which shadows
|
||||
// dlopen in the consumer binary) and call the real OS dlopen directly.
|
||||
using real_dlopen_t = void* (*)(const char*, int);
|
||||
static real_dlopen_t real_dlopen =
|
||||
reinterpret_cast<real_dlopen_t>(::dlsym(RTLD_NEXT, "dlopen"));
|
||||
|
||||
// RTLD_NOW catches resolution failures at load time; cleaner errors
|
||||
// than RTLD_LAZY where a missing symbol surfaces on first call.
|
||||
void* h = real_dlopen(path, RTLD_NOW);
|
||||
if (!h) {
|
||||
const char* dl = ::dlerror();
|
||||
r.error = std::string("dlopen: ") + (dl ? dl : "unknown");
|
||||
::close(fd);
|
||||
if (used_tmpfile) ::unlink(tmpl);
|
||||
return r;
|
||||
}
|
||||
|
||||
// Once dlopen has mapped the segments, we can close the fd. The
|
||||
// mappings remain valid until dlclose. Same for O_TMPFILE (and the
|
||||
// mkstemp fallback, where we already-unlinked-via-fd-only-open).
|
||||
::close(fd);
|
||||
if (used_tmpfile) ::unlink(tmpl);
|
||||
|
||||
r.dl_handle = h;
|
||||
r.ok = true;
|
||||
return r;
|
||||
}
|
||||
|
||||
void* sym(void* handle, const char* name) {
|
||||
if (!handle || !name) return nullptr;
|
||||
return ::dlsym(handle, name);
|
||||
}
|
||||
|
||||
int close_(void* handle) {
|
||||
if (!handle) return 0;
|
||||
return ::dlclose(handle);
|
||||
}
|
||||
|
||||
} // namespace voidlibc::loader::linux_handoff
|
||||
|
||||
#else // stub for non-Linux builds so the target compiles on all platforms
|
||||
|
||||
namespace voidlibc::loader::linux_handoff {
|
||||
|
||||
LoadResult dlopen_buffer(const std::vector<std::uint8_t>&, const char*) {
|
||||
return {{}, "linux_handoff not available on this platform", false};
|
||||
}
|
||||
void* sym(void*, const char*) { return nullptr; }
|
||||
int close_(void*) { return 0; }
|
||||
|
||||
} // namespace voidlibc::loader::linux_handoff
|
||||
|
||||
#endif // __linux__
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace voidlibc::loader::linux_handoff {
|
||||
|
||||
struct LoadResult {
|
||||
void* dl_handle = nullptr; // opaque handle from dlopen
|
||||
std::string error; // empty on success
|
||||
bool ok = false;
|
||||
};
|
||||
|
||||
// Take a synthesized ELF DSO buffer, place it in a memfd (or fallback
|
||||
// temp file), and dlopen it. Returns the raw dlopen handle. Callers
|
||||
// own it and must dlclose() it.
|
||||
LoadResult dlopen_buffer(const std::vector<std::uint8_t>& elf_bytes,
|
||||
const char* debug_name = "voidlibc.elf");
|
||||
|
||||
// Thin wrappers so the caller never includes <dlfcn.h>.
|
||||
void* sym(void* handle, const char* name);
|
||||
int close_(void* handle);
|
||||
|
||||
} // namespace voidlibc::loader::linux_handoff
|
||||
@@ -0,0 +1,15 @@
|
||||
add_library(voidlibc_loader_macos STATIC
|
||||
macho_synth.cpp
|
||||
handoff.cpp
|
||||
)
|
||||
target_link_libraries(voidlibc_loader_macos
|
||||
PUBLIC voidlibc_loader_common
|
||||
)
|
||||
if(APPLE)
|
||||
target_link_libraries(voidlibc_loader_macos PRIVATE ${CMAKE_DL_LIBS})
|
||||
endif()
|
||||
set_target_properties(voidlibc_loader_macos PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
||||
install(TARGETS voidlibc_loader_macos
|
||||
EXPORT VoidLibCTargets
|
||||
ARCHIVE DESTINATION lib
|
||||
)
|
||||
@@ -0,0 +1,76 @@
|
||||
#include "handoff.hpp"
|
||||
|
||||
#ifdef __APPLE__
|
||||
|
||||
#include <cerrno>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <dlfcn.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace voidlibc::loader::macos_handoff {
|
||||
|
||||
LoadResult dlopen_buffer(const std::vector<std::uint8_t>& blob) {
|
||||
LoadResult res{};
|
||||
|
||||
// Write blob to a temp file, dlopen it, then unlink.
|
||||
// macOS dyld requires a path — no memfd_create equivalent.
|
||||
char tmp[256];
|
||||
const char* tmpdir = ::getenv("TMPDIR");
|
||||
if (!tmpdir || !*tmpdir) tmpdir = "/tmp";
|
||||
std::snprintf(tmp, sizeof(tmp), "%s/voidlib.%d.XXXXXX.dylib", tmpdir, static_cast<int>(::getpid()));
|
||||
|
||||
const int fd = ::mkstemps(tmp, 6 /* len(".dylib") */);
|
||||
if (fd < 0) { res.error = std::string("mkstemps: ") + std::strerror(errno); return res; }
|
||||
|
||||
const std::uint8_t* p = blob.data();
|
||||
std::size_t remaining = blob.size();
|
||||
while (remaining > 0) {
|
||||
const ssize_t n = ::write(fd, p, remaining);
|
||||
if (n <= 0) {
|
||||
::close(fd); ::unlink(tmp);
|
||||
res.error = std::string("write: ") + std::strerror(errno); return res;
|
||||
}
|
||||
p += n; remaining -= static_cast<std::size_t>(n);
|
||||
}
|
||||
::close(fd);
|
||||
|
||||
// chmod +x so dyld will map it as executable
|
||||
::chmod(tmp, 0755);
|
||||
|
||||
void* handle = ::dlopen(tmp, RTLD_NOW | RTLD_LOCAL);
|
||||
::unlink(tmp);
|
||||
if (!handle) {
|
||||
res.error = ::dlerror() ? ::dlerror() : "dlopen failed";
|
||||
return res;
|
||||
}
|
||||
res.dl_handle = handle;
|
||||
res.ok = true;
|
||||
return res;
|
||||
}
|
||||
|
||||
void* sym(void* handle, const char* name) {
|
||||
if (!handle || !name) return nullptr;
|
||||
return ::dlsym(handle, name);
|
||||
}
|
||||
|
||||
int close_(void* handle) {
|
||||
if (!handle) return 0;
|
||||
return ::dlclose(handle);
|
||||
}
|
||||
|
||||
} // namespace voidlibc::loader::macos_handoff
|
||||
|
||||
#else // stub compilation so non-macOS hosts can include this TU
|
||||
|
||||
namespace voidlibc::loader::macos_handoff {
|
||||
|
||||
LoadResult dlopen_buffer(const std::vector<std::uint8_t>&) {
|
||||
return {{}, "macos_handoff not available on this platform", false};
|
||||
}
|
||||
void* sym(void*, const char*) { return nullptr; }
|
||||
int close_(void*) { return 0; }
|
||||
|
||||
} // namespace voidlibc::loader::macos_handoff
|
||||
|
||||
#endif // __APPLE__
|
||||
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace voidlibc::loader::macos_handoff {
|
||||
|
||||
struct LoadResult {
|
||||
void* dl_handle = nullptr;
|
||||
std::string error;
|
||||
bool ok = false;
|
||||
};
|
||||
|
||||
// Write `blob` to a per-process temp file under $TMPDIR and call dlopen on it.
|
||||
// The temp file is unlinked after dlopen succeeds (the mapping keeps the data alive).
|
||||
// Returns a native dlopen handle on success.
|
||||
LoadResult dlopen_buffer(const std::vector<std::uint8_t>& blob);
|
||||
|
||||
void* sym(void* handle, const char* name);
|
||||
int close_(void* handle);
|
||||
|
||||
} // namespace voidlibc::loader::macos_handoff
|
||||
@@ -0,0 +1,677 @@
|
||||
#include "macho_synth.hpp"
|
||||
|
||||
#include <cstring>
|
||||
#include <sstream>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
|
||||
namespace voidlibc::loader::macos {
|
||||
|
||||
namespace {
|
||||
|
||||
// ── On-disk structs (x86_64 LE host = no byte-swap needed) ─────────────────
|
||||
|
||||
constexpr std::uint32_t kMhMagic64 = 0xFEEDFACFu;
|
||||
constexpr std::int32_t kCpuTypeX86_64 = 0x01000007;
|
||||
constexpr std::int32_t kCpuSubX86All = 3;
|
||||
constexpr std::uint32_t kMhDylib = 6;
|
||||
// DYLDLINK | TWOLEVEL | NO_REEXPORTED_DYLIBS
|
||||
constexpr std::uint32_t kMhFlags = 0x00100084u;
|
||||
|
||||
constexpr std::uint32_t kLcSegment64 = 0x19u;
|
||||
constexpr std::uint32_t kLcDyldInfoOnly = 0x80000022u;
|
||||
constexpr std::uint32_t kLcSymtab = 0x02u;
|
||||
constexpr std::uint32_t kLcDysymtab = 0x0bu;
|
||||
constexpr std::uint32_t kLcIdDylib = 0x0du;
|
||||
constexpr std::uint32_t kLcLoadDylib = 0x0cu;
|
||||
constexpr std::uint32_t kLcVersionMinMacOS = 0x24u;
|
||||
|
||||
constexpr std::int32_t kVmProtR = 0x1;
|
||||
constexpr std::int32_t kVmProtW = 0x2;
|
||||
constexpr std::int32_t kVmProtX = 0x4;
|
||||
|
||||
constexpr std::uint32_t kSAttrPureInstr = 0x80000000u;
|
||||
constexpr std::uint32_t kSAttrSomeInstr = 0x00000400u;
|
||||
constexpr std::uint32_t kSSymbolStubs = 0x00000008u;
|
||||
constexpr std::uint32_t kSNonLazySymPtrs = 0x00000006u;
|
||||
|
||||
constexpr std::uint8_t kNExt = 0x01u;
|
||||
constexpr std::uint8_t kNSect = 0x0eu;
|
||||
constexpr std::uint8_t kNUndf = 0x00u;
|
||||
|
||||
constexpr std::uint8_t kBindOpDone = 0x00u;
|
||||
constexpr std::uint8_t kBindOpSetDylibOrdinalImm = 0x10u;
|
||||
constexpr std::uint8_t kBindOpSetSymbolFlags = 0x40u;
|
||||
constexpr std::uint8_t kBindOpSetTypeImm = 0x50u;
|
||||
constexpr std::uint8_t kBindOpSetSegAndOff = 0x70u;
|
||||
constexpr std::uint8_t kBindOpDoBind = 0x90u;
|
||||
constexpr std::uint8_t kBindTypePointer = 1u;
|
||||
|
||||
constexpr std::uint64_t kPageSize = 0x1000u;
|
||||
|
||||
#pragma pack(push, 1)
|
||||
|
||||
struct MachHeader64 {
|
||||
std::uint32_t magic, cputype_u, cpusubtype_u, filetype;
|
||||
std::uint32_t ncmds, sizeofcmds, flags, reserved;
|
||||
};
|
||||
static_assert(sizeof(MachHeader64) == 32);
|
||||
|
||||
struct SegCmd64 {
|
||||
std::uint32_t cmd, cmdsize;
|
||||
char segname[16];
|
||||
std::uint64_t vmaddr, vmsize, fileoff, filesize;
|
||||
std::int32_t maxprot, initprot;
|
||||
std::uint32_t nsects, flags;
|
||||
};
|
||||
static_assert(sizeof(SegCmd64) == 72); // segment_command_64 is 72 bytes (not 64)
|
||||
|
||||
struct Sec64 {
|
||||
char sectname[16], segname[16];
|
||||
std::uint64_t addr, size;
|
||||
std::uint32_t offset, align, reloff, nreloc, flags, reserved1, reserved2, reserved3;
|
||||
};
|
||||
static_assert(sizeof(Sec64) == 80);
|
||||
|
||||
struct DyldInfoCmd {
|
||||
std::uint32_t cmd, cmdsize;
|
||||
std::uint32_t rebase_off, rebase_size;
|
||||
std::uint32_t bind_off, bind_size;
|
||||
std::uint32_t weak_bind_off, weak_bind_size;
|
||||
std::uint32_t lazy_bind_off, lazy_bind_size;
|
||||
std::uint32_t export_off, export_size;
|
||||
};
|
||||
static_assert(sizeof(DyldInfoCmd) == 48);
|
||||
|
||||
struct SymtabCmd { std::uint32_t cmd, cmdsize, symoff, nsyms, stroff, strsize; };
|
||||
static_assert(sizeof(SymtabCmd) == 24);
|
||||
|
||||
struct DysymtabCmd {
|
||||
std::uint32_t cmd, cmdsize;
|
||||
std::uint32_t ilocalsym, nlocalsym, iextdefsym, nextdefsym, iundefsym, nundefsym;
|
||||
std::uint32_t tocoff, ntoc, modtaboff, nmodtab, extrefsymoff, nextrefsyms;
|
||||
std::uint32_t indirectsymoff, nindirectsyms, extreloff, nextrel, locreloff, nlocrel;
|
||||
};
|
||||
static_assert(sizeof(DysymtabCmd) == 80);
|
||||
|
||||
struct NList64 {
|
||||
std::uint32_t n_strx; std::uint8_t n_type, n_sect; std::uint16_t n_desc;
|
||||
std::uint64_t n_value;
|
||||
};
|
||||
static_assert(sizeof(NList64) == 16);
|
||||
|
||||
struct VersionMinCmd {
|
||||
std::uint32_t cmd, cmdsize, version, sdk;
|
||||
};
|
||||
static_assert(sizeof(VersionMinCmd) == 16);
|
||||
|
||||
#pragma pack(pop)
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
static constexpr std::uint64_t align_up(std::uint64_t v, std::uint64_t a) {
|
||||
return (v + (a-1)) & ~(a-1);
|
||||
}
|
||||
|
||||
static void push_uleb(std::vector<std::uint8_t>& b, std::uint64_t v) {
|
||||
do {
|
||||
std::uint8_t byte = v & 0x7f;
|
||||
v >>= 7;
|
||||
if (v) byte |= 0x80;
|
||||
b.push_back(byte);
|
||||
} while (v);
|
||||
}
|
||||
|
||||
// Fixed 2-byte ULEB128 (covers 0..16383, enough for any trie offset in MVP).
|
||||
static void push_uleb2(std::vector<std::uint8_t>& b, std::uint64_t v) {
|
||||
b.push_back(static_cast<std::uint8_t>((v & 0x7f) | 0x80));
|
||||
b.push_back(static_cast<std::uint8_t>((v >> 7) & 0x7f));
|
||||
}
|
||||
|
||||
static 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] = u & 0xff; buf[off+1] = (u >> 8) & 0xff;
|
||||
buf[off+2] = (u >> 16) & 0xff; buf[off+3] = (u >> 24) & 0xff;
|
||||
}
|
||||
|
||||
static void set_name(char (&out)[16], const char* src) {
|
||||
std::memset(out, 0, 16);
|
||||
std::strncpy(out, src, 16);
|
||||
}
|
||||
|
||||
// Flat export trie: root → one leaf per symbol (full symbol name as edge label).
|
||||
// `sym_vmaddr` = symbol vmaddr from image base (= text_sect_vmaddr + code_offset).
|
||||
static std::vector<std::uint8_t> build_export_trie(
|
||||
const std::vector<MachoExportedSymbol>& exports,
|
||||
std::uint64_t text_sect_vmaddr) {
|
||||
if (exports.empty()) return {0, 0};
|
||||
|
||||
struct Leaf { std::string name; std::vector<std::uint8_t> bytes; };
|
||||
std::vector<Leaf> leaves;
|
||||
for (const auto& e : exports) {
|
||||
Leaf lf; lf.name = e.name;
|
||||
std::vector<std::uint8_t> td;
|
||||
push_uleb(td, 0); // flags = regular
|
||||
push_uleb(td, text_sect_vmaddr + e.code_offset); // vmaddr from image base
|
||||
push_uleb(lf.bytes, td.size()); // terminal_size
|
||||
lf.bytes.insert(lf.bytes.end(), td.begin(), td.end());
|
||||
lf.bytes.push_back(0); // num_children
|
||||
leaves.push_back(std::move(lf));
|
||||
}
|
||||
|
||||
// Root node size with 2-byte fixed ULEBs for child offsets:
|
||||
// 1 (terminal_size=0) + 1 (num_children) + Σ(name.size()+1+2) per child
|
||||
std::size_t root_sz = 2;
|
||||
for (const auto& lf : leaves) root_sz += lf.name.size() + 1 + 2;
|
||||
|
||||
std::vector<std::size_t> leaf_offs;
|
||||
std::size_t cursor = root_sz;
|
||||
for (const auto& lf : leaves) { leaf_offs.push_back(cursor); cursor += lf.bytes.size(); }
|
||||
|
||||
std::vector<std::uint8_t> trie;
|
||||
trie.push_back(0); // not terminal
|
||||
trie.push_back(static_cast<std::uint8_t>(exports.size())); // num_children
|
||||
for (std::size_t i = 0; i < exports.size(); ++i) {
|
||||
const auto& lf = leaves[i];
|
||||
trie.insert(trie.end(), lf.name.begin(), lf.name.end());
|
||||
trie.push_back(0);
|
||||
push_uleb2(trie, leaf_offs[i]);
|
||||
}
|
||||
for (const auto& lf : leaves)
|
||||
trie.insert(trie.end(), lf.bytes.begin(), lf.bytes.end());
|
||||
|
||||
while (trie.size() % 8) trie.push_back(0);
|
||||
return trie;
|
||||
}
|
||||
|
||||
// Non-lazy bind opcodes. Each import gets one slot in __nl_symbol_ptr.
|
||||
// Slots [0..nstubs-1] = function call stubs; slots [nstubs..] = GOT data.
|
||||
// lib_ordinals: dylib install name → 1-based LC_LOAD_DYLIB ordinal.
|
||||
static std::vector<std::uint8_t> build_bind_opcodes(
|
||||
const std::vector<const MachoImportedSymbol*>& ordered_imports,
|
||||
const std::unordered_map<std::string, int>& lib_ordinals,
|
||||
std::uint32_t data_seg_idx,
|
||||
std::uint64_t nl_sym_off_in_data_seg) {
|
||||
if (ordered_imports.empty()) return {kBindOpDone};
|
||||
static constexpr const char* kDefaultLib = "/usr/lib/libSystem.B.dylib";
|
||||
std::vector<std::uint8_t> buf;
|
||||
for (std::size_t i = 0; i < ordered_imports.size(); ++i) {
|
||||
if (!ordered_imports[i]) continue;
|
||||
const auto& im = *ordered_imports[i];
|
||||
const std::string& lib = im.library.empty() ? kDefaultLib : im.library;
|
||||
auto oit = lib_ordinals.find(lib);
|
||||
const int ordinal = (oit != lib_ordinals.end()) ? oit->second : 1;
|
||||
buf.push_back(kBindOpSetDylibOrdinalImm | static_cast<std::uint8_t>(ordinal & 0xf));
|
||||
buf.push_back(kBindOpSetSymbolFlags | 0);
|
||||
buf.insert(buf.end(), im.name.begin(), im.name.end());
|
||||
buf.push_back(0);
|
||||
buf.push_back(kBindOpSetTypeImm | kBindTypePointer);
|
||||
buf.push_back(kBindOpSetSegAndOff | (data_seg_idx & 0xf));
|
||||
push_uleb(buf, nl_sym_off_in_data_seg + i * 8);
|
||||
buf.push_back(kBindOpDoBind);
|
||||
}
|
||||
buf.push_back(kBindOpDone);
|
||||
while (buf.size() % 8) buf.push_back(0);
|
||||
return buf;
|
||||
}
|
||||
|
||||
} // anonymous namespace
|
||||
|
||||
MachoSynthOutput synthesize_macho(const MachoSynthInput& input) {
|
||||
MachoSynthOutput out{};
|
||||
if (input.code.empty()) {
|
||||
out.ok = false; out.error = "macho_synth: code is empty"; return out;
|
||||
}
|
||||
|
||||
// ── Classify imports ────────────────────────────────────────────────────
|
||||
std::unordered_set<std::uint32_t> internal_ids, data_ids;
|
||||
for (const auto& s : input.internal_symbols) internal_ids.insert(s.sym_id);
|
||||
for (const auto& s : input.data_symbols) data_ids.insert(s.sym_id);
|
||||
|
||||
// PLT32 → stub; GotPC32* (external) → nl_symbol_ptr GOT slot
|
||||
std::unordered_map<std::uint32_t, std::uint32_t> imp_to_stub, imp_to_got;
|
||||
{
|
||||
std::uint32_t si = 0, gi = 0;
|
||||
using format::RelocOp;
|
||||
for (const auto& r : input.relocs) {
|
||||
if (r.op == RelocOp::PLT32 &&
|
||||
!internal_ids.count(r.sym_id) && !data_ids.count(r.sym_id) &&
|
||||
!imp_to_stub.count(r.sym_id))
|
||||
imp_to_stub[r.sym_id] = si++;
|
||||
else if ((r.op == RelocOp::GotPC32 || r.op == RelocOp::GotPC32X ||
|
||||
r.op == RelocOp::GotPC32XRex) &&
|
||||
!internal_ids.count(r.sym_id) && !data_ids.count(r.sym_id) &&
|
||||
!imp_to_got.count(r.sym_id))
|
||||
imp_to_got[r.sym_id] = gi++;
|
||||
}
|
||||
}
|
||||
const auto nstubs = static_cast<std::uint32_t>(imp_to_stub.size());
|
||||
const auto ngot = static_cast<std::uint32_t>(imp_to_got.size());
|
||||
const auto n_nlsym = nstubs + ngot;
|
||||
|
||||
// ── Load command sizes ──────────────────────────────────────────────────
|
||||
const std::uint32_t ntext_sects = (nstubs > 0) ? 2u : 1u;
|
||||
const bool has_data_blob = !input.data_blob.empty();
|
||||
const bool has_nlsym = (n_nlsym > 0);
|
||||
const bool has_data_seg = has_data_blob || has_nlsym;
|
||||
const auto ndata_sects = static_cast<std::uint32_t>(
|
||||
(has_data_blob ? 1u : 0u) + (has_nlsym ? 1u : 0u));
|
||||
|
||||
const std::string dylib_name = input.soname.empty()
|
||||
? "/usr/local/lib/libvoid_module.dylib" : input.soname;
|
||||
const std::uint32_t iddylib_sz = static_cast<std::uint32_t>(
|
||||
align_up(8u + 16u + dylib_name.size() + 1u, 4u));
|
||||
|
||||
std::vector<std::string> needed_libs;
|
||||
if (!input.needed_libs.empty()) {
|
||||
needed_libs = input.needed_libs;
|
||||
} else if (nstubs > 0 || ngot > 0) {
|
||||
// Collect unique libraries in insertion order from per-import library fields.
|
||||
std::unordered_map<std::string, bool> seen;
|
||||
for (const auto& im : input.imports) {
|
||||
const std::string& lib = im.library.empty()
|
||||
? "/usr/lib/libSystem.B.dylib" : im.library;
|
||||
if (seen.emplace(lib, true).second)
|
||||
needed_libs.push_back(lib);
|
||||
}
|
||||
if (needed_libs.empty())
|
||||
needed_libs.push_back("/usr/lib/libSystem.B.dylib");
|
||||
}
|
||||
|
||||
// 1-based ordinal map (ordinal 1 = first LC_LOAD_DYLIB).
|
||||
std::unordered_map<std::string, int> lib_ordinal;
|
||||
for (std::size_t i = 0; i < needed_libs.size(); ++i)
|
||||
lib_ordinal[needed_libs[i]] = static_cast<int>(i + 1);
|
||||
|
||||
std::vector<std::uint32_t> loaddylib_szs;
|
||||
for (const auto& lib : needed_libs)
|
||||
loaddylib_szs.push_back(static_cast<std::uint32_t>(
|
||||
align_up(8u + 16u + lib.size() + 1u, 4u)));
|
||||
|
||||
std::uint32_t total_lc_sz = 0;
|
||||
total_lc_sz += sizeof(SegCmd64) + ntext_sects * sizeof(Sec64); // __TEXT
|
||||
if (has_data_seg)
|
||||
total_lc_sz += sizeof(SegCmd64) + ndata_sects * sizeof(Sec64); // __DATA
|
||||
total_lc_sz += sizeof(SegCmd64); // __LINKEDIT
|
||||
total_lc_sz += sizeof(DyldInfoCmd);
|
||||
total_lc_sz += sizeof(SymtabCmd);
|
||||
total_lc_sz += sizeof(DysymtabCmd);
|
||||
total_lc_sz += iddylib_sz;
|
||||
for (std::uint32_t sz : loaddylib_szs) total_lc_sz += sz;
|
||||
total_lc_sz += sizeof(VersionMinCmd);
|
||||
|
||||
const std::uint64_t hdr_lc_sz = sizeof(MachHeader64) + total_lc_sz;
|
||||
|
||||
// ── Vmaddr layout ────────────────────────────────────────────────────────
|
||||
// __TEXT: vmaddr=0, fileoff=0; vmaddr == fileoff throughout.
|
||||
const std::uint64_t text_sect_va = align_up(hdr_lc_sz, 16);
|
||||
const std::uint64_t text_sect_sz = input.code.size();
|
||||
const std::uint64_t stubs_va = align_up(text_sect_va + text_sect_sz, 2);
|
||||
const std::uint64_t stubs_sz = nstubs * 6;
|
||||
const std::uint64_t text_seg_end = stubs_va + stubs_sz;
|
||||
|
||||
const std::uint64_t data_seg_va = align_up(text_seg_end, kPageSize);
|
||||
const std::uint64_t data_sect_va = data_seg_va;
|
||||
const std::uint64_t data_sect_sz = input.data_blob.size();
|
||||
const std::uint64_t nlsym_va = align_up(data_sect_va + data_sect_sz, 8);
|
||||
const std::uint64_t nlsym_sz = n_nlsym * 8;
|
||||
const std::uint64_t data_seg_end = nlsym_va + nlsym_sz;
|
||||
|
||||
const std::uint64_t linkedit_va = has_data_seg
|
||||
? align_up(data_seg_end, kPageSize)
|
||||
: align_up(text_seg_end, kPageSize);
|
||||
|
||||
// ── Build LINKEDIT content ───────────────────────────────────────────────
|
||||
|
||||
// Bind imports: stubs first [0..nstubs-1], then GOT data [nstubs..nstubs+ngot-1].
|
||||
std::vector<const MachoImportedSymbol*> stub_order(nstubs, nullptr);
|
||||
std::vector<const MachoImportedSymbol*> got_order(ngot, nullptr);
|
||||
for (const auto& im : input.imports) {
|
||||
auto sit = imp_to_stub.find(im.sym_id);
|
||||
if (sit != imp_to_stub.end()) stub_order[sit->second] = &im;
|
||||
auto git = imp_to_got.find(im.sym_id);
|
||||
if (git != imp_to_got.end()) got_order[git->second] = &im;
|
||||
}
|
||||
std::vector<const MachoImportedSymbol*> bind_order;
|
||||
bind_order.insert(bind_order.end(), stub_order.begin(), stub_order.end());
|
||||
bind_order.insert(bind_order.end(), got_order.begin(), got_order.end());
|
||||
|
||||
const std::uint32_t data_seg_idx = has_data_seg ? 1u : 0u; // 0-based
|
||||
const std::uint64_t nlsym_off_in_data = nlsym_va - data_seg_va;
|
||||
auto bind_bytes = build_bind_opcodes(bind_order, lib_ordinal, data_seg_idx, nlsym_off_in_data);
|
||||
|
||||
auto export_trie = build_export_trie(input.exports, text_sect_va);
|
||||
|
||||
// Symbol table: extdef (exports) then undef (imports).
|
||||
std::vector<char> strtab; strtab.push_back(0);
|
||||
std::vector<NList64> nlist;
|
||||
|
||||
const std::uint32_t iextdefsym = 0;
|
||||
for (const auto& e : input.exports) {
|
||||
NList64 n{};
|
||||
n.n_strx = static_cast<std::uint32_t>(strtab.size());
|
||||
strtab.insert(strtab.end(), e.name.begin(), e.name.end()); strtab.push_back(0);
|
||||
n.n_type = kNExt | kNSect;
|
||||
n.n_sect = 1; // 1-based: __text is section 1
|
||||
n.n_value = text_sect_va + e.code_offset;
|
||||
nlist.push_back(n);
|
||||
}
|
||||
const std::uint32_t iundefsym = static_cast<std::uint32_t>(nlist.size());
|
||||
for (const auto& im : input.imports) {
|
||||
NList64 n{};
|
||||
n.n_strx = static_cast<std::uint32_t>(strtab.size());
|
||||
strtab.insert(strtab.end(), im.name.begin(), im.name.end()); strtab.push_back(0);
|
||||
n.n_type = kNExt | kNUndf;
|
||||
n.n_sect = 0; // NO_SECT
|
||||
nlist.push_back(n);
|
||||
}
|
||||
while (strtab.size() % 4) strtab.push_back(0);
|
||||
|
||||
// LINKEDIT offsets
|
||||
std::uint64_t li = linkedit_va;
|
||||
const std::uint64_t bind_off = li; li += bind_bytes.size();
|
||||
const std::uint64_t exp_off = li; li += export_trie.size();
|
||||
li = align_up(li, 8);
|
||||
const std::uint64_t sym_off = li; li += nlist.size() * sizeof(NList64);
|
||||
li = align_up(li, 4);
|
||||
const std::uint64_t str_off = li; li += strtab.size();
|
||||
const std::uint64_t linkedit_filesz = li - linkedit_va;
|
||||
|
||||
// ── Apply reloc IR to code blob ─────────────────────────────────────────
|
||||
std::vector<std::uint8_t> code_buf(input.code);
|
||||
|
||||
// Build stub bytes (6-byte JMP stubs → nl_symbol_ptr slots).
|
||||
// Each stub: FF 25 <disp32> (jmpq *slot(%rip))
|
||||
// Stubs use slots [0..nstubs-1] in nl_symbol_ptr.
|
||||
std::vector<std::uint8_t> stub_buf(stubs_sz, 0);
|
||||
for (std::uint32_t i = 0; i < nstubs; ++i) {
|
||||
const std::uint64_t stub_va = stubs_va + i * 6;
|
||||
const std::uint64_t slot_va = nlsym_va + i * 8;
|
||||
const std::int32_t disp = static_cast<std::int32_t>(
|
||||
static_cast<std::int64_t>(slot_va) - static_cast<std::int64_t>(stub_va + 6));
|
||||
stub_buf[i*6 + 0] = 0xff; stub_buf[i*6 + 1] = 0x25;
|
||||
std::uint32_t u; std::memcpy(&u, &disp, 4);
|
||||
stub_buf[i*6 + 2] = u & 0xff; stub_buf[i*6 + 3] = (u >> 8) & 0xff;
|
||||
stub_buf[i*6 + 4] = (u >> 16) & 0xff; stub_buf[i*6 + 5] = (u >> 24) & 0xff;
|
||||
}
|
||||
|
||||
// vmaddr maps
|
||||
std::unordered_map<std::uint32_t, std::uint64_t> sym_va, dat_va;
|
||||
for (const auto& s : input.internal_symbols) sym_va[s.sym_id] = text_sect_va + s.code_offset;
|
||||
for (const auto& s : input.data_symbols) dat_va[s.sym_id] = data_sect_va + s.data_offset;
|
||||
|
||||
using format::RelocOp;
|
||||
for (const auto& r : input.relocs) {
|
||||
const std::uint64_t coff = r.dst_offset;
|
||||
if (coff + 4 > code_buf.size()) {
|
||||
out.ok = false;
|
||||
std::ostringstream os;
|
||||
os << "macho_synth: reloc at 0x" << std::hex << coff << " out of range";
|
||||
out.error = os.str(); return out;
|
||||
}
|
||||
const std::uint64_t site_va = text_sect_va + coff;
|
||||
std::int64_t disp = 0; bool patched = false;
|
||||
|
||||
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;
|
||||
auto ic = sym_va.find(r.sym_id);
|
||||
if (ic != sym_va.end()) {
|
||||
disp = static_cast<std::int64_t>(ic->second)
|
||||
- static_cast<std::int64_t>(site_va + 4) + r.addend + bias;
|
||||
patched = true; break;
|
||||
}
|
||||
auto id = dat_va.find(r.sym_id);
|
||||
if (id != dat_va.end()) {
|
||||
disp = static_cast<std::int64_t>(id->second)
|
||||
- static_cast<std::int64_t>(site_va + 4) + r.addend + bias;
|
||||
patched = true; break;
|
||||
}
|
||||
out.ok = false;
|
||||
{ std::ostringstream os;
|
||||
os << "PC32: sym_id " << r.sym_id << " not found"; out.error = os.str(); }
|
||||
return out;
|
||||
}
|
||||
case RelocOp::PLT32: {
|
||||
auto ic = sym_va.find(r.sym_id);
|
||||
if (ic != sym_va.end()) {
|
||||
disp = static_cast<std::int64_t>(ic->second)
|
||||
- static_cast<std::int64_t>(site_va + 4) + r.addend;
|
||||
patched = true; break;
|
||||
}
|
||||
auto sit = imp_to_stub.find(r.sym_id);
|
||||
if (sit != imp_to_stub.end()) {
|
||||
const std::uint64_t sv = stubs_va + sit->second * 6;
|
||||
disp = static_cast<std::int64_t>(sv)
|
||||
- static_cast<std::int64_t>(site_va + 4) + r.addend;
|
||||
patched = true; break;
|
||||
}
|
||||
out.ok = false;
|
||||
{ std::ostringstream os;
|
||||
os << "PLT32: sym_id " << r.sym_id << " not found"; out.error = os.str(); }
|
||||
return out;
|
||||
}
|
||||
case RelocOp::GotPC32:
|
||||
case RelocOp::GotPC32X:
|
||||
case RelocOp::GotPC32XRex: {
|
||||
const bool relax = r.op == RelocOp::GotPC32X || r.op == RelocOp::GotPC32XRex;
|
||||
auto ic = sym_va.find(r.sym_id);
|
||||
auto id = dat_va.find(r.sym_id);
|
||||
if ((ic != sym_va.end() || id != dat_va.end()) && relax) {
|
||||
if (coff < 2 || code_buf[coff-1] != 0x8b) {
|
||||
out.ok = false; out.error = "GOTPCREL relax: expected MOV"; return out;
|
||||
}
|
||||
code_buf[coff-1] = 0x8d;
|
||||
std::uint64_t tv = (ic != sym_va.end()) ? ic->second : id->second;
|
||||
disp = static_cast<std::int64_t>(tv)
|
||||
- static_cast<std::int64_t>(site_va + 4) + r.addend;
|
||||
patched = true; break;
|
||||
}
|
||||
auto git = imp_to_got.find(r.sym_id);
|
||||
if (git != imp_to_got.end()) {
|
||||
const std::uint64_t sv = nlsym_va + (nstubs + git->second) * 8;
|
||||
disp = static_cast<std::int64_t>(sv)
|
||||
- static_cast<std::int64_t>(site_va + 4) + r.addend;
|
||||
patched = true; break;
|
||||
}
|
||||
out.ok = false;
|
||||
{ std::ostringstream os;
|
||||
os << "GOTPCREL: sym_id " << r.sym_id << " not found"; out.error = os.str(); }
|
||||
return out;
|
||||
}
|
||||
case RelocOp::Abs64: case RelocOp::Abs32: case RelocOp::Abs32Signed:
|
||||
out.ok = false; out.error = "Abs reloc not yet supported in macho_synth"; return out;
|
||||
case RelocOp::TlsLE: case RelocOp::TlsIE: case RelocOp::TlsGD: case RelocOp::TlsLD:
|
||||
out.ok = false; out.error = "TLS not yet supported in macho_synth"; return out;
|
||||
}
|
||||
|
||||
if (patched) write32le(code_buf, coff, static_cast<std::int32_t>(disp));
|
||||
}
|
||||
|
||||
// ── Emit file ────────────────────────────────────────────────────────────
|
||||
const std::uint64_t file_sz = li;
|
||||
out.bytes.assign(file_sz, 0);
|
||||
|
||||
auto write_at = [&](std::uint64_t off, const void* src, std::uint64_t n) {
|
||||
std::memcpy(out.bytes.data() + off, src, n);
|
||||
};
|
||||
|
||||
// -- Mach header --
|
||||
std::uint32_t ncmds = 0;
|
||||
ncmds++; if (has_data_seg) ncmds++; ncmds++; // segments
|
||||
ncmds += 4; // DyldInfo, Symtab, Dysymtab, VersionMin
|
||||
ncmds++; // ID_DYLIB
|
||||
ncmds += static_cast<std::uint32_t>(needed_libs.size());
|
||||
|
||||
MachHeader64 mh{};
|
||||
mh.magic = kMhMagic64;
|
||||
mh.cputype_u = static_cast<std::uint32_t>(kCpuTypeX86_64);
|
||||
mh.cpusubtype_u = static_cast<std::uint32_t>(kCpuSubX86All);
|
||||
mh.filetype = kMhDylib;
|
||||
mh.ncmds = ncmds;
|
||||
mh.sizeofcmds = total_lc_sz;
|
||||
mh.flags = kMhFlags;
|
||||
write_at(0, &mh, sizeof(mh));
|
||||
|
||||
std::uint64_t lc = sizeof(MachHeader64);
|
||||
auto emit = [&](const void* p, std::uint32_t n) { write_at(lc, p, n); lc += n; };
|
||||
|
||||
// __TEXT segment
|
||||
{
|
||||
const std::uint32_t text_cmd_sz = sizeof(SegCmd64) + ntext_sects * sizeof(Sec64);
|
||||
SegCmd64 seg{};
|
||||
seg.cmd = kLcSegment64; seg.cmdsize = text_cmd_sz;
|
||||
set_name(seg.segname, "__TEXT");
|
||||
seg.vmsize = seg.filesize = align_up(text_seg_end, kPageSize);
|
||||
seg.maxprot = kVmProtR | kVmProtX; seg.initprot = kVmProtR | kVmProtX;
|
||||
seg.nsects = ntext_sects;
|
||||
emit(&seg, sizeof(seg));
|
||||
|
||||
Sec64 ts{};
|
||||
set_name(ts.sectname, "__text"); set_name(ts.segname, "__TEXT");
|
||||
ts.addr = text_sect_va; ts.size = text_sect_sz;
|
||||
ts.offset = static_cast<std::uint32_t>(text_sect_va);
|
||||
ts.align = 4; // 2^4 = 16
|
||||
ts.flags = kSAttrPureInstr | kSAttrSomeInstr;
|
||||
emit(&ts, sizeof(ts));
|
||||
|
||||
if (nstubs > 0) {
|
||||
Sec64 ss{};
|
||||
set_name(ss.sectname, "__stubs"); set_name(ss.segname, "__TEXT");
|
||||
ss.addr = stubs_va; ss.size = stubs_sz;
|
||||
ss.offset = static_cast<std::uint32_t>(stubs_va);
|
||||
ss.align = 1; // 2^1 = 2
|
||||
ss.flags = kSSymbolStubs | kSAttrSomeInstr | kSAttrPureInstr;
|
||||
ss.reserved2 = 6; // stub entry size
|
||||
emit(&ss, sizeof(ss));
|
||||
}
|
||||
}
|
||||
|
||||
// __DATA segment
|
||||
if (has_data_seg) {
|
||||
const std::uint32_t data_cmd_sz = sizeof(SegCmd64) + ndata_sects * sizeof(Sec64);
|
||||
SegCmd64 seg{};
|
||||
seg.cmd = kLcSegment64; seg.cmdsize = data_cmd_sz;
|
||||
set_name(seg.segname, "__DATA");
|
||||
seg.vmaddr = seg.fileoff = data_seg_va;
|
||||
seg.vmsize = seg.filesize = align_up(data_seg_end - data_seg_va, kPageSize);
|
||||
seg.maxprot = kVmProtR | kVmProtW; seg.initprot = kVmProtR | kVmProtW;
|
||||
seg.nsects = ndata_sects;
|
||||
emit(&seg, sizeof(seg));
|
||||
|
||||
if (has_data_blob) {
|
||||
Sec64 ds{};
|
||||
set_name(ds.sectname, "__data"); set_name(ds.segname, "__DATA");
|
||||
ds.addr = data_sect_va; ds.size = data_sect_sz;
|
||||
ds.offset = static_cast<std::uint32_t>(data_sect_va);
|
||||
ds.align = 3;
|
||||
emit(&ds, sizeof(ds));
|
||||
}
|
||||
if (has_nlsym) {
|
||||
Sec64 ns{};
|
||||
set_name(ns.sectname, "__nl_symbol_ptr"); set_name(ns.segname, "__DATA");
|
||||
ns.addr = nlsym_va; ns.size = nlsym_sz;
|
||||
ns.offset = static_cast<std::uint32_t>(nlsym_va);
|
||||
ns.align = 3;
|
||||
ns.flags = kSNonLazySymPtrs;
|
||||
emit(&ns, sizeof(ns));
|
||||
}
|
||||
}
|
||||
|
||||
// __LINKEDIT segment
|
||||
{
|
||||
SegCmd64 seg{};
|
||||
seg.cmd = kLcSegment64; seg.cmdsize = sizeof(SegCmd64);
|
||||
set_name(seg.segname, "__LINKEDIT");
|
||||
seg.vmaddr = seg.fileoff = linkedit_va;
|
||||
seg.vmsize = seg.filesize = align_up(linkedit_filesz, kPageSize);
|
||||
seg.maxprot = kVmProtR; seg.initprot = kVmProtR;
|
||||
emit(&seg, sizeof(seg));
|
||||
}
|
||||
|
||||
// LC_DYLD_INFO_ONLY
|
||||
{
|
||||
DyldInfoCmd dc{};
|
||||
dc.cmd = kLcDyldInfoOnly; dc.cmdsize = sizeof(dc);
|
||||
dc.bind_off = static_cast<std::uint32_t>(bind_off);
|
||||
dc.bind_size = static_cast<std::uint32_t>(bind_bytes.size());
|
||||
dc.export_off = static_cast<std::uint32_t>(exp_off);
|
||||
dc.export_size = static_cast<std::uint32_t>(export_trie.size());
|
||||
emit(&dc, sizeof(dc));
|
||||
}
|
||||
|
||||
// LC_SYMTAB
|
||||
{
|
||||
SymtabCmd sc{};
|
||||
sc.cmd = kLcSymtab; sc.cmdsize = sizeof(sc);
|
||||
sc.symoff = static_cast<std::uint32_t>(sym_off);
|
||||
sc.nsyms = static_cast<std::uint32_t>(nlist.size());
|
||||
sc.stroff = static_cast<std::uint32_t>(str_off);
|
||||
sc.strsize = static_cast<std::uint32_t>(strtab.size());
|
||||
emit(&sc, sizeof(sc));
|
||||
}
|
||||
|
||||
// LC_DYSYMTAB
|
||||
{
|
||||
DysymtabCmd dc{};
|
||||
dc.cmd = kLcDysymtab; dc.cmdsize = sizeof(dc);
|
||||
dc.iextdefsym = iextdefsym;
|
||||
dc.nextdefsym = iundefsym - iextdefsym;
|
||||
dc.iundefsym = iundefsym;
|
||||
dc.nundefsym = static_cast<std::uint32_t>(nlist.size()) - iundefsym;
|
||||
emit(&dc, sizeof(dc));
|
||||
}
|
||||
|
||||
// LC_ID_DYLIB
|
||||
{
|
||||
std::vector<std::uint8_t> lc_buf(iddylib_sz, 0);
|
||||
auto* u = reinterpret_cast<std::uint32_t*>(lc_buf.data());
|
||||
u[0] = kLcIdDylib; u[1] = iddylib_sz;
|
||||
u[2] = 8u + 16u; // name offset from cmd start
|
||||
u[3] = 0; u[4] = 0x00010000u; u[5] = 0x00010000u;
|
||||
std::memcpy(lc_buf.data() + 8 + 16, dylib_name.c_str(), dylib_name.size());
|
||||
emit(lc_buf.data(), iddylib_sz);
|
||||
}
|
||||
|
||||
// LC_LOAD_DYLIB entries
|
||||
for (std::size_t i = 0; i < needed_libs.size(); ++i) {
|
||||
const std::uint32_t sz = loaddylib_szs[i];
|
||||
std::vector<std::uint8_t> lc_buf(sz, 0);
|
||||
auto* u = reinterpret_cast<std::uint32_t*>(lc_buf.data());
|
||||
u[0] = kLcLoadDylib; u[1] = sz;
|
||||
u[2] = 8u + 16u; u[3] = 0; u[4] = 0x00010000u; u[5] = 0x00010000u;
|
||||
std::memcpy(lc_buf.data() + 8 + 16, needed_libs[i].c_str(), needed_libs[i].size());
|
||||
emit(lc_buf.data(), sz);
|
||||
}
|
||||
|
||||
// LC_VERSION_MIN_MACOSX
|
||||
{
|
||||
VersionMinCmd vc{};
|
||||
vc.cmd = kLcVersionMinMacOS; vc.cmdsize = sizeof(vc);
|
||||
vc.version = 0x000c0000u; // 12.0.0
|
||||
vc.sdk = 0x000c0000u;
|
||||
emit(&vc, sizeof(vc));
|
||||
}
|
||||
|
||||
// -- Section data --
|
||||
write_at(text_sect_va, code_buf.data(), code_buf.size());
|
||||
if (stubs_sz > 0) write_at(stubs_va, stub_buf.data(), stub_buf.size());
|
||||
if (has_data_blob) write_at(data_sect_va, input.data_blob.data(), input.data_blob.size());
|
||||
// __nl_symbol_ptr: zeroed — dyld fills via bind opcodes
|
||||
|
||||
// -- LINKEDIT data --
|
||||
if (!bind_bytes.empty()) write_at(bind_off, bind_bytes.data(), bind_bytes.size());
|
||||
write_at(exp_off, export_trie.data(), export_trie.size());
|
||||
if (!nlist.empty()) write_at(sym_off, nlist.data(), nlist.size() * sizeof(NList64));
|
||||
write_at(str_off, strtab.data(), strtab.size());
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace voidlibc::loader::macos
|
||||
@@ -0,0 +1,62 @@
|
||||
#pragma once
|
||||
|
||||
#include "format/reloc_ir.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace voidlibc::loader::macos {
|
||||
|
||||
struct MachoExportedSymbol {
|
||||
std::string name;
|
||||
std::uint64_t code_offset = 0;
|
||||
std::uint64_t size = 0;
|
||||
bool is_function = true;
|
||||
bool weak = false;
|
||||
};
|
||||
|
||||
struct MachoImportedSymbol {
|
||||
std::uint32_t sym_id = 0;
|
||||
std::string name;
|
||||
std::string library; // dylib install name; "" → /usr/lib/libSystem.B.dylib
|
||||
};
|
||||
|
||||
struct MachoInternalSymbol {
|
||||
std::uint32_t sym_id = 0;
|
||||
std::uint64_t code_offset = 0;
|
||||
std::string name;
|
||||
};
|
||||
|
||||
struct MachoDataSymbol {
|
||||
std::uint32_t sym_id = 0;
|
||||
std::uint64_t data_offset = 0;
|
||||
std::string name;
|
||||
};
|
||||
|
||||
struct MachoSynthInput {
|
||||
std::vector<std::uint8_t> code;
|
||||
std::vector<MachoExportedSymbol> exports;
|
||||
std::vector<voidlibc::format::RelocEntry> relocs;
|
||||
std::vector<MachoInternalSymbol> internal_symbols;
|
||||
std::vector<MachoImportedSymbol> imports;
|
||||
std::vector<std::uint8_t> data_blob;
|
||||
std::vector<MachoDataSymbol> data_symbols;
|
||||
std::string soname;
|
||||
// Explicit LC_LOAD_DYLIB entries. Empty + imports present → defaults to
|
||||
// /usr/lib/libSystem.B.dylib. Empty + no imports → static (no NEEDED).
|
||||
std::vector<std::string> needed_libs;
|
||||
};
|
||||
|
||||
struct MachoSynthOutput {
|
||||
std::vector<std::uint8_t> bytes;
|
||||
std::string error;
|
||||
bool ok = true;
|
||||
};
|
||||
|
||||
// Produce a minimal Mach-O64 dylib (MH_DYLIB, x86_64) that dlopen will accept.
|
||||
// Layout: __TEXT (header+LCs+code+stubs) / __DATA (data+nl_symbol_ptr) / __LINKEDIT.
|
||||
// Non-lazy binding via LC_DYLD_INFO_ONLY bind opcodes; no lazy stubs.
|
||||
MachoSynthOutput synthesize_macho(const MachoSynthInput& input);
|
||||
|
||||
} // namespace voidlibc::loader::macos
|
||||
@@ -0,0 +1,10 @@
|
||||
add_library(voidlibc_loader_windows STATIC
|
||||
pe_synth.cpp
|
||||
handoff.cpp
|
||||
)
|
||||
target_include_directories(voidlibc_loader_windows PUBLIC
|
||||
${CMAKE_SOURCE_DIR}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/..
|
||||
)
|
||||
target_link_libraries(voidlibc_loader_windows PUBLIC voidlibc_format)
|
||||
set_target_properties(voidlibc_loader_windows PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
||||
@@ -0,0 +1,73 @@
|
||||
#include "handoff.hpp"
|
||||
|
||||
#ifdef _WIN32
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#else
|
||||
// Stub for non-Windows builds (so the file compiles everywhere).
|
||||
#include <cstdio>
|
||||
#endif
|
||||
|
||||
namespace voidlibc::loader::windows_handoff {
|
||||
|
||||
LoadResult load_pe_buffer(const std::vector<std::uint8_t>& bytes) {
|
||||
#ifdef _WIN32
|
||||
// Write bytes to a temp file, load it, then delete the file.
|
||||
char tmp_path[MAX_PATH];
|
||||
char tmp_dir[MAX_PATH];
|
||||
GetTempPathA(MAX_PATH, tmp_dir);
|
||||
GetTempFileNameA(tmp_dir, "vlc", 0, tmp_path);
|
||||
|
||||
// Write PE bytes.
|
||||
HANDLE fh = CreateFileA(tmp_path, GENERIC_WRITE, 0, nullptr,
|
||||
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (fh == INVALID_HANDLE_VALUE) {
|
||||
return {nullptr, "CreateFile failed for temp PE", false};
|
||||
}
|
||||
DWORD written = 0;
|
||||
BOOL ok = WriteFile(fh, bytes.data(),
|
||||
static_cast<DWORD>(bytes.size()), &written, nullptr);
|
||||
CloseHandle(fh);
|
||||
if (!ok || written != bytes.size()) {
|
||||
DeleteFileA(tmp_path);
|
||||
return {nullptr, "WriteFile failed for temp PE", false};
|
||||
}
|
||||
|
||||
// Load the DLL.
|
||||
HMODULE mod = LoadLibraryExA(tmp_path, nullptr, LOAD_WITH_ALTERED_SEARCH_PATH);
|
||||
DeleteFileA(tmp_path); // safe to delete once mapped
|
||||
|
||||
if (!mod) {
|
||||
char msg[256];
|
||||
std::snprintf(msg, sizeof(msg),
|
||||
"LoadLibraryEx failed (error %lu)", GetLastError());
|
||||
return {nullptr, msg, false};
|
||||
}
|
||||
return {static_cast<void*>(mod), {}, true};
|
||||
#else
|
||||
(void)bytes;
|
||||
return {nullptr, "load_pe_buffer: not implemented on non-Windows", false};
|
||||
#endif
|
||||
}
|
||||
|
||||
void* get_proc(void* handle, const char* name) {
|
||||
#ifdef _WIN32
|
||||
return reinterpret_cast<void*>(
|
||||
GetProcAddress(static_cast<HMODULE>(handle), name));
|
||||
#else
|
||||
(void)handle; (void)name;
|
||||
return nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
void unload(void* handle) {
|
||||
#ifdef _WIN32
|
||||
FreeLibrary(static_cast<HMODULE>(handle));
|
||||
#else
|
||||
(void)handle;
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace voidlibc::loader::windows_handoff
|
||||
@@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <cstdint>
|
||||
|
||||
namespace voidlibc::loader::windows_handoff {
|
||||
|
||||
struct LoadResult {
|
||||
void* handle = nullptr; // opaque OS handle (HMODULE on Windows)
|
||||
std::string error;
|
||||
bool ok = true;
|
||||
};
|
||||
|
||||
// Write `bytes` to a temp file and load it via LoadLibraryEx (Windows) /
|
||||
// dlopen from a temp file (stub for non-Windows builds so the code compiles
|
||||
// everywhere). The temp file is deleted once the DLL is loaded.
|
||||
LoadResult load_pe_buffer(const std::vector<std::uint8_t>& bytes);
|
||||
|
||||
// Resolve a symbol from a handle returned by load_pe_buffer.
|
||||
void* get_proc(void* handle, const char* name);
|
||||
|
||||
// Unload a handle returned by load_pe_buffer.
|
||||
void unload(void* handle);
|
||||
|
||||
} // namespace voidlibc::loader::windows_handoff
|
||||
@@ -0,0 +1,571 @@
|
||||
// Minimal PE64 DLL synthesizer.
|
||||
//
|
||||
// Layout produced (all RVAs relative to image base 0x10000000):
|
||||
//
|
||||
// File offset 0x000 : DOS stub + PE signature
|
||||
// File offset 0x040 : PE signature "PE\0\0"
|
||||
// File offset 0x044 : IMAGE_FILE_HEADER (20 bytes)
|
||||
// File offset 0x058 : IMAGE_OPTIONAL_HEADER64 (240 bytes)
|
||||
// File offset 0x148 : Section table (N × 40 bytes)
|
||||
// File offset 0x200 : .text raw data (code + thunk stubs, file-aligned 0x200)
|
||||
// File offset ... : .rdata raw data (export dir, import dir, IAT, names)
|
||||
// File offset ... : .data raw data (data blob — writable; omitted if empty)
|
||||
//
|
||||
// Virtual layout (section-aligned 0x1000):
|
||||
// VA 0x1000 : .text (RX)
|
||||
// VA ... : .rdata (R)
|
||||
// VA ... : .data (RW, omitted if empty)
|
||||
//
|
||||
// Import thunks (JMP QWORD PTR [IAT_entry+rip]) live at the START of .text
|
||||
// (index 0..nimports-1, 6 bytes each, padded to 16-byte stride).
|
||||
// Code blob follows at offset = nimports * 16.
|
||||
|
||||
#include "pe_synth.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace voidlibc::loader::windows {
|
||||
|
||||
namespace {
|
||||
|
||||
using format::RelocOp;
|
||||
|
||||
constexpr std::uint16_t kMachineAmd64 = 0x8664;
|
||||
constexpr std::uint16_t kCharDll = 0x2000;
|
||||
constexpr std::uint16_t kCharExecutable= 0x0002;
|
||||
constexpr std::uint16_t kCharLargeAddr = 0x0020;
|
||||
constexpr std::uint16_t kMagicPE64 = 0x020B;
|
||||
constexpr std::uint32_t kFileAlign = 0x200;
|
||||
constexpr std::uint32_t kSecAlign = 0x1000;
|
||||
constexpr std::uint64_t kImageBase = 0x10000000ULL;
|
||||
|
||||
constexpr std::uint32_t align_up(std::uint32_t v, std::uint32_t a) {
|
||||
return (v + a - 1) & ~(a - 1);
|
||||
}
|
||||
|
||||
// Write helpers (little-endian).
|
||||
static void w16(std::vector<std::uint8_t>& v, std::uint32_t off, std::uint16_t x) {
|
||||
v[off] = static_cast<std::uint8_t>(x);
|
||||
v[off+1] = static_cast<std::uint8_t>(x >> 8);
|
||||
}
|
||||
static void w32(std::vector<std::uint8_t>& v, std::uint32_t off, std::uint32_t x) {
|
||||
v[off] = static_cast<std::uint8_t>(x);
|
||||
v[off+1] = static_cast<std::uint8_t>(x >> 8);
|
||||
v[off+2] = static_cast<std::uint8_t>(x >> 16);
|
||||
v[off+3] = static_cast<std::uint8_t>(x >> 24);
|
||||
}
|
||||
static void w64(std::vector<std::uint8_t>& v, std::uint32_t off, std::uint64_t x) {
|
||||
w32(v, off, static_cast<std::uint32_t>(x));
|
||||
w32(v, off+4, static_cast<std::uint32_t>(x >> 32));
|
||||
}
|
||||
struct SectionDesc {
|
||||
char name[9] = {}; // up to 8 chars + NUL
|
||||
std::uint32_t rva = 0;
|
||||
std::uint32_t vsize = 0; // virtual size
|
||||
std::uint32_t foff = 0; // file offset of raw data
|
||||
std::uint32_t fsize = 0; // raw data size (file-aligned)
|
||||
std::uint32_t chars = 0; // IMAGE_SCN_* flags
|
||||
};
|
||||
|
||||
void write_section_header(std::vector<std::uint8_t>& out,
|
||||
std::uint32_t at,
|
||||
const SectionDesc& s) {
|
||||
// Pad name to 8 chars.
|
||||
std::memcpy(out.data() + at, s.name, 8);
|
||||
w32(out, at + 8, s.vsize);
|
||||
w32(out, at + 12, s.rva);
|
||||
w32(out, at + 20, s.fsize); // SizeOfRawData
|
||||
w32(out, at + 16, s.foff); // PointerToRawData
|
||||
w32(out, at + 24, 0); // PointerToRelocations
|
||||
w32(out, at + 28, 0); // PointerToLinenumbers
|
||||
w16(out, at + 32, 0); // NumberOfRelocations
|
||||
w16(out, at + 34, 0); // NumberOfLinenumbers
|
||||
w32(out, at + 36, s.chars);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
PeSynthOutput synthesize_pe(const PeSynthInput& input) {
|
||||
PeSynthOutput out;
|
||||
|
||||
const std::uint32_t nimports = static_cast<std::uint32_t>(input.imports.size());
|
||||
const std::uint32_t nexports = static_cast<std::uint32_t>(input.exports.size());
|
||||
|
||||
// Each import gets a 6-byte thunk (JMP [rip+X]) padded to 16 bytes.
|
||||
const std::uint32_t thunk_stride = 16;
|
||||
const std::uint32_t thunks_size = nimports * thunk_stride;
|
||||
|
||||
// --- Build .text content: [thunks][code blob] ---
|
||||
std::vector<std::uint8_t> text_raw(thunks_size + input.code.size(), 0);
|
||||
std::memcpy(text_raw.data() + thunks_size, input.code.data(), input.code.size());
|
||||
|
||||
// sym_id → import index (0-based) for PLT-like thunks.
|
||||
std::unordered_map<std::uint32_t, std::uint32_t> import_to_thunk;
|
||||
{
|
||||
std::uint32_t idx = 0;
|
||||
for (const auto& imp : input.imports)
|
||||
import_to_thunk.emplace(imp.sym_id, idx++);
|
||||
}
|
||||
|
||||
// sym_id → code offset (within code blob, relative to code blob start).
|
||||
std::unordered_map<std::uint32_t, std::uint64_t> sym_code_offset;
|
||||
for (const auto& s : input.internal_symbols)
|
||||
sym_code_offset.emplace(s.sym_id, s.code_offset);
|
||||
|
||||
// sym_id → data blob offset.
|
||||
std::unordered_map<std::uint32_t, std::uint64_t> sym_data_offset;
|
||||
for (const auto& s : input.data_symbols)
|
||||
sym_data_offset.emplace(s.sym_id, s.data_offset);
|
||||
|
||||
// --- Section layout planning ---
|
||||
// .text: VA 0x1000, RX
|
||||
// .rdata: VA immediately after .text (section-aligned), R
|
||||
// .data: VA immediately after .rdata (section-aligned), RW (omitted if empty)
|
||||
const std::uint32_t text_rva = kSecAlign; // 0x1000
|
||||
const std::uint32_t text_vsz = static_cast<std::uint32_t>(text_raw.size());
|
||||
const std::uint32_t rdata_rva = align_up(text_rva + text_vsz, kSecAlign);
|
||||
|
||||
// --- Build .rdata: export table, import descriptors, IAT, name strings ---
|
||||
// We'll assemble it as a flat buffer, keeping track of RVAs.
|
||||
std::vector<std::uint8_t> rdata;
|
||||
auto rdata_rva_of = [&](std::uint32_t rdata_off) {
|
||||
return rdata_rva + rdata_off;
|
||||
};
|
||||
|
||||
// Partition imports by DLL (stable insertion order preserves import_to_thunk order).
|
||||
// Each group has: its DLL name + the set of imports from that DLL.
|
||||
struct DllGroup {
|
||||
std::string dll_name;
|
||||
std::vector<std::uint32_t> import_indices; // indices into input.imports
|
||||
};
|
||||
std::vector<DllGroup> dll_groups;
|
||||
std::unordered_map<std::string, std::size_t> dll_index;
|
||||
{
|
||||
const std::string default_dll = input.dll_name.empty() ? "ucrtbase.dll" : input.dll_name;
|
||||
for (std::uint32_t i = 0; i < nimports; ++i) {
|
||||
const std::string& dll = input.imports[i].library.empty()
|
||||
? default_dll : input.imports[i].library;
|
||||
auto [it, inserted] = dll_index.emplace(dll, dll_groups.size());
|
||||
if (inserted) dll_groups.push_back({dll, {}});
|
||||
dll_groups[it->second].import_indices.push_back(i);
|
||||
}
|
||||
}
|
||||
const std::uint32_t ndlls = static_cast<std::uint32_t>(dll_groups.size());
|
||||
|
||||
// IAT layout: [grp0_entries][grp0_null] [grp1_entries][grp1_null] ...
|
||||
// Total = (nimports + ndlls) * 8 bytes.
|
||||
const std::uint32_t iat_off = 0;
|
||||
const std::uint32_t iat_size = (nimports + ndlls) * 8;
|
||||
rdata.resize(iat_size, 0);
|
||||
|
||||
// INT: same layout as IAT, placed after IAT.
|
||||
const std::uint32_t int_off = iat_size;
|
||||
const std::uint32_t int_size = (nimports + ndlls) * 8;
|
||||
rdata.resize(rdata.size() + int_size, 0);
|
||||
|
||||
// Compute per-import global slot index (position in the flat IAT).
|
||||
// import_to_thunk already maps sym_id → original index; we need
|
||||
// sym_id → IAT-slot-for-thunk.
|
||||
std::vector<std::uint32_t> import_iat_slot(nimports); // index → IAT slot
|
||||
{
|
||||
std::uint32_t slot = 0;
|
||||
for (const auto& g : dll_groups) {
|
||||
for (std::uint32_t idx : g.import_indices)
|
||||
import_iat_slot[idx] = slot++;
|
||||
++slot; // null terminator slot
|
||||
}
|
||||
}
|
||||
// Rebuild import_to_thunk using IAT slot (thunk #i JMPs through IAT[import_iat_slot[i]]).
|
||||
// The existing import_to_thunk maps sym_id → import_index (0-based insertion order).
|
||||
// We need sym_id → IAT_slot for the .rdata reloc in thunk patching below.
|
||||
std::unordered_map<std::uint32_t, std::uint32_t> sym_to_iat_slot;
|
||||
for (std::uint32_t i = 0; i < nimports; ++i)
|
||||
sym_to_iat_slot[input.imports[i].sym_id] = import_iat_slot[i];
|
||||
|
||||
// Hint+name table (IMAGE_IMPORT_BY_NAME records).
|
||||
std::vector<std::uint32_t> import_name_rvas(nimports);
|
||||
for (std::uint32_t i = 0; i < nimports; ++i) {
|
||||
const std::uint32_t name_off = static_cast<std::uint32_t>(rdata.size());
|
||||
rdata.push_back(0); rdata.push_back(0); // hint = 0
|
||||
const auto& name = input.imports[i].name;
|
||||
rdata.insert(rdata.end(), name.begin(), name.end());
|
||||
rdata.push_back(0);
|
||||
if (rdata.size() & 1) rdata.push_back(0);
|
||||
import_name_rvas[i] = rdata_rva_of(name_off);
|
||||
}
|
||||
|
||||
// Fill IAT and INT entries per group.
|
||||
{
|
||||
std::uint32_t slot = 0;
|
||||
for (const auto& g : dll_groups) {
|
||||
for (std::uint32_t idx : g.import_indices) {
|
||||
w64(rdata, iat_off + slot * 8, import_name_rvas[idx]);
|
||||
w64(rdata, int_off + slot * 8, import_name_rvas[idx]);
|
||||
++slot;
|
||||
}
|
||||
++slot; // null terminator already zero
|
||||
}
|
||||
}
|
||||
|
||||
// Import descriptor table: one IMAGE_IMPORT_DESCRIPTOR (20 bytes) per DLL + null.
|
||||
// DLL names first (so we know their RVAs).
|
||||
std::vector<std::uint32_t> dll_name_rvas(ndlls);
|
||||
for (std::uint32_t d = 0; d < ndlls; ++d) {
|
||||
const std::uint32_t off = static_cast<std::uint32_t>(rdata.size());
|
||||
rdata.insert(rdata.end(), dll_groups[d].dll_name.begin(), dll_groups[d].dll_name.end());
|
||||
rdata.push_back(0);
|
||||
if (rdata.size() & 1) rdata.push_back(0);
|
||||
dll_name_rvas[d] = rdata_rva_of(off);
|
||||
}
|
||||
|
||||
const std::uint32_t imp_desc_off = static_cast<std::uint32_t>(rdata.size());
|
||||
// (ndlls + 1) descriptors (last = null terminator).
|
||||
rdata.resize(rdata.size() + (ndlls + 1) * 20, 0);
|
||||
{
|
||||
std::uint32_t slot = 0;
|
||||
for (std::uint32_t d = 0; d < ndlls; ++d) {
|
||||
const std::uint32_t at = imp_desc_off + d * 20;
|
||||
const std::uint32_t grp_iat_rva = rdata_rva_of(iat_off + slot * 8);
|
||||
const std::uint32_t grp_int_rva = rdata_rva_of(int_off + slot * 8);
|
||||
w32(rdata, at + 0, grp_int_rva); // OriginalFirstThunk (INT)
|
||||
w32(rdata, at + 4, 0); // TimeDateStamp
|
||||
w32(rdata, at + 8, 0); // ForwarderChain
|
||||
w32(rdata, at + 12, dll_name_rvas[d]); // Name
|
||||
w32(rdata, at + 16, grp_iat_rva); // FirstThunk (IAT)
|
||||
slot += static_cast<std::uint32_t>(dll_groups[d].import_indices.size()) + 1; // +1 null
|
||||
}
|
||||
// Last descriptor = null (already zero).
|
||||
}
|
||||
|
||||
// Export directory (IMAGE_EXPORT_DIRECTORY, 40 bytes).
|
||||
const std::uint32_t exp_fn_rvas_off = static_cast<std::uint32_t>(rdata.size());
|
||||
rdata.resize(rdata.size() + nexports * 4, 0); // function RVA array
|
||||
|
||||
const std::uint32_t exp_name_rvas_off = static_cast<std::uint32_t>(rdata.size());
|
||||
rdata.resize(rdata.size() + nexports * 4, 0); // name RVA array
|
||||
|
||||
const std::uint32_t exp_ordinals_off = static_cast<std::uint32_t>(rdata.size());
|
||||
rdata.resize(rdata.size() + nexports * 2, 0); // ordinal array
|
||||
|
||||
// Export name strings.
|
||||
std::vector<std::uint32_t> exp_name_rva(nexports);
|
||||
for (std::uint32_t i = 0; i < nexports; ++i) {
|
||||
exp_name_rva[i] = rdata_rva_of(static_cast<std::uint32_t>(rdata.size()));
|
||||
const auto& nm = input.exports[i].name;
|
||||
rdata.insert(rdata.end(), nm.begin(), nm.end());
|
||||
rdata.push_back(0);
|
||||
}
|
||||
if (rdata.size() & 1) rdata.push_back(0);
|
||||
|
||||
// Export DLL name string.
|
||||
const std::uint32_t exp_dll_name_off = static_cast<std::uint32_t>(rdata.size());
|
||||
rdata.insert(rdata.end(), input.dll_name.begin(), input.dll_name.end());
|
||||
rdata.push_back(0);
|
||||
|
||||
// IMAGE_EXPORT_DIRECTORY.
|
||||
const std::uint32_t exp_dir_off = static_cast<std::uint32_t>(rdata.size());
|
||||
rdata.resize(rdata.size() + 40, 0);
|
||||
|
||||
const std::uint32_t rdata_vsz = static_cast<std::uint32_t>(rdata.size());
|
||||
const std::uint32_t data_rva = align_up(rdata_rva + rdata_vsz, kSecAlign);
|
||||
|
||||
// --- Determine section count ---
|
||||
const bool has_data = !input.data_blob.empty();
|
||||
const int nsec = has_data ? 3 : 2;
|
||||
|
||||
// --- Headers ---
|
||||
// File layout: headers (0x200 file-aligned), .text, .rdata, [.data]
|
||||
const std::uint32_t hdrs_size = align_up(
|
||||
0x148 + static_cast<std::uint32_t>(nsec) * 40, kFileAlign);
|
||||
|
||||
const std::uint32_t text_foff = hdrs_size;
|
||||
const std::uint32_t text_fsz = align_up(text_vsz, kFileAlign);
|
||||
const std::uint32_t rdata_foff = text_foff + text_fsz;
|
||||
const std::uint32_t rdata_fsz = align_up(rdata_vsz, kFileAlign);
|
||||
const std::uint32_t data_foff = rdata_foff + rdata_fsz;
|
||||
const std::uint32_t data_vsz = static_cast<std::uint32_t>(input.data_blob.size());
|
||||
const std::uint32_t data_fsz = has_data ? align_up(data_vsz, kFileAlign) : 0;
|
||||
|
||||
const std::uint32_t image_size = has_data
|
||||
? align_up(data_rva + data_vsz, kSecAlign)
|
||||
: align_up(rdata_rva + rdata_vsz, kSecAlign);
|
||||
|
||||
const std::uint32_t total_file = data_foff + data_fsz;
|
||||
out.bytes.assign(total_file, 0);
|
||||
auto& img = out.bytes;
|
||||
|
||||
// DOS header.
|
||||
img[0] = 'M'; img[1] = 'Z';
|
||||
w32(img, 0x3C, 0x40); // e_lfanew
|
||||
|
||||
// PE signature.
|
||||
img[0x40] = 'P'; img[0x41] = 'E';
|
||||
|
||||
// COFF File Header at 0x44.
|
||||
const std::uint32_t fhdr = 0x44;
|
||||
w16(img, fhdr + 0, kMachineAmd64);
|
||||
w16(img, fhdr + 2, static_cast<std::uint16_t>(nsec));
|
||||
w32(img, fhdr + 4, 0); // TimeDateStamp
|
||||
w32(img, fhdr + 8, 0); // PointerToSymbolTable
|
||||
w32(img, fhdr + 12, 0); // NumberOfSymbols
|
||||
w16(img, fhdr + 16, 240); // SizeOfOptionalHeader
|
||||
w16(img, fhdr + 18, kCharExecutable | kCharDll | kCharLargeAddr);
|
||||
|
||||
// Optional Header at 0x58.
|
||||
const std::uint32_t ohdr = 0x58;
|
||||
w16(img, ohdr + 0, kMagicPE64);
|
||||
img[ohdr + 2] = 14; img[ohdr + 3] = 0; // MajorLinkerVersion, MinorLinkerVersion
|
||||
w32(img, ohdr + 4, text_fsz); // SizeOfCode
|
||||
w32(img, ohdr + 8, rdata_fsz + data_fsz); // SizeOfInitializedData
|
||||
w32(img, ohdr + 12, 0); // SizeOfUninitializedData
|
||||
w32(img, ohdr + 16, 0); // AddressOfEntryPoint (DLL: 0 is fine)
|
||||
w32(img, ohdr + 20, text_rva); // BaseOfCode
|
||||
w64(img, ohdr + 24, kImageBase); // ImageBase
|
||||
w32(img, ohdr + 32, kSecAlign); // SectionAlignment
|
||||
w32(img, ohdr + 36, kFileAlign); // FileAlignment
|
||||
w16(img, ohdr + 40, 6); w16(img, ohdr + 42, 0); // OS version 6.0
|
||||
w16(img, ohdr + 44, 0); w16(img, ohdr + 46, 0); // Image version
|
||||
w16(img, ohdr + 48, 6); w16(img, ohdr + 50, 0); // Subsystem version 6.0
|
||||
w32(img, ohdr + 52, 0); // Win32VersionValue
|
||||
w32(img, ohdr + 56, image_size); // SizeOfImage
|
||||
w32(img, ohdr + 60, hdrs_size); // SizeOfHeaders
|
||||
w32(img, ohdr + 64, 0); // CheckSum
|
||||
w16(img, ohdr + 68, 3); // Subsystem = WINDOWS_CUI
|
||||
w16(img, ohdr + 70, 0x8160); // DllCharacteristics (ASLR, NX, ...)
|
||||
w64(img, ohdr + 72, 0x100000); // SizeOfStackReserve
|
||||
w64(img, ohdr + 80, 0x1000); // SizeOfStackCommit
|
||||
w64(img, ohdr + 88, 0x100000); // SizeOfHeapReserve
|
||||
w64(img, ohdr + 96, 0x1000); // SizeOfHeapCommit
|
||||
w32(img, ohdr + 104, 0); // LoaderFlags
|
||||
w32(img, ohdr + 108, 16); // NumberOfRvaAndSizes
|
||||
|
||||
// Data directories (at ohdr+112, 8 bytes each: RVA + Size).
|
||||
const std::uint32_t dd = ohdr + 112;
|
||||
// [0] Export directory.
|
||||
w32(img, dd + 0, rdata_rva_of(exp_dir_off));
|
||||
w32(img, dd + 4, 40);
|
||||
// [1] Import directory.
|
||||
if (nimports > 0) {
|
||||
w32(img, dd + 8, rdata_rva_of(imp_desc_off));
|
||||
w32(img, dd + 12, (ndlls + 1) * 20);
|
||||
// [12] IAT.
|
||||
w32(img, dd + 96, rdata_rva_of(iat_off));
|
||||
w32(img, dd + 100, iat_size);
|
||||
}
|
||||
|
||||
// Section headers.
|
||||
const std::uint32_t shdrs = 0x148;
|
||||
{
|
||||
SectionDesc s;
|
||||
std::memcpy(s.name, ".text\0\0\0", 8);
|
||||
s.rva = text_rva; s.vsize = text_vsz;
|
||||
s.foff = text_foff; s.fsize = text_fsz;
|
||||
s.chars = 0x60000020; // CNT_CODE | MEM_EXECUTE | MEM_READ
|
||||
write_section_header(img, shdrs, s);
|
||||
}
|
||||
{
|
||||
SectionDesc s;
|
||||
std::memcpy(s.name, ".rdata\0\0", 8);
|
||||
s.rva = rdata_rva; s.vsize = rdata_vsz;
|
||||
s.foff = rdata_foff; s.fsize = rdata_fsz;
|
||||
s.chars = 0x40000040; // CNT_INITIALIZED_DATA | MEM_READ
|
||||
write_section_header(img, shdrs + 40, s);
|
||||
}
|
||||
if (has_data) {
|
||||
SectionDesc s;
|
||||
std::memcpy(s.name, ".data\0\0\0", 8);
|
||||
s.rva = data_rva; s.vsize = data_vsz;
|
||||
s.foff = data_foff; s.fsize = data_fsz;
|
||||
s.chars = 0xC0000040; // CNT_INITIALIZED_DATA | MEM_READ | MEM_WRITE
|
||||
write_section_header(img, shdrs + 80, s);
|
||||
}
|
||||
|
||||
// --- Apply relocations into text_raw ---
|
||||
// code_vaddr = kImageBase + text_rva + thunks_size (start of code blob)
|
||||
// data_vaddr = kImageBase + data_rva
|
||||
// iat_vaddr = kImageBase + rdata_rva + iat_off
|
||||
const std::uint64_t code_vaddr = kImageBase + text_rva + thunks_size;
|
||||
const std::uint64_t data_vaddr = kImageBase + data_rva;
|
||||
const std::uint64_t iat_vaddr = kImageBase + rdata_rva + iat_off;
|
||||
|
||||
std::string reloc_error;
|
||||
for (const auto& r : input.relocs) {
|
||||
// dst_offset is within the code blob; in text_raw it is at thunks_size + r.dst_offset.
|
||||
const std::uint32_t raw_off = thunks_size + r.dst_offset;
|
||||
// Virtual address of the patch site.
|
||||
const std::uint64_t P = kImageBase + text_rva + raw_off;
|
||||
|
||||
auto patch32 = [&](std::int64_t v) -> bool {
|
||||
if (raw_off + 4 > static_cast<std::uint32_t>(text_raw.size())) {
|
||||
reloc_error = "reloc patch out of range";
|
||||
return false;
|
||||
}
|
||||
const std::int32_t v32 = static_cast<std::int32_t>(v);
|
||||
std::memcpy(text_raw.data() + raw_off, &v32, 4);
|
||||
return true;
|
||||
};
|
||||
auto patch64 = [&](std::int64_t v) -> bool {
|
||||
if (raw_off + 8 > static_cast<std::uint32_t>(text_raw.size())) {
|
||||
reloc_error = "reloc64 patch out of range";
|
||||
return false;
|
||||
}
|
||||
std::memcpy(text_raw.data() + raw_off, &v, 8);
|
||||
return true;
|
||||
};
|
||||
|
||||
// Helper: find symbol's runtime virtual address.
|
||||
auto sym_va = [&](std::uint32_t sym_id, std::int64_t addend,
|
||||
std::uint64_t& va_out) -> bool {
|
||||
if (auto it = sym_code_offset.find(sym_id); it != sym_code_offset.end()) {
|
||||
va_out = code_vaddr + it->second + static_cast<std::uint64_t>(addend);
|
||||
return true;
|
||||
}
|
||||
if (auto it = sym_data_offset.find(sym_id); it != sym_data_offset.end()) {
|
||||
va_out = data_vaddr + it->second + static_cast<std::uint64_t>(addend);
|
||||
return true;
|
||||
}
|
||||
reloc_error = "sym_id not found for reloc";
|
||||
return false;
|
||||
};
|
||||
|
||||
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;
|
||||
|
||||
// Check for thunk call (PLT-like through IAT).
|
||||
if (auto it = import_to_thunk.find(r.sym_id);
|
||||
it != import_to_thunk.end()) {
|
||||
const std::uint64_t thunk_va =
|
||||
kImageBase + text_rva + it->second * thunk_stride;
|
||||
const std::int64_t disp = static_cast<std::int64_t>(thunk_va)
|
||||
- static_cast<std::int64_t>(P) + r.addend + bias;
|
||||
if (!patch32(disp)) goto done;
|
||||
break;
|
||||
}
|
||||
// Internal sym or data sym.
|
||||
{
|
||||
std::uint64_t sym_va_val = 0;
|
||||
if (auto it = sym_code_offset.find(r.sym_id);
|
||||
it != sym_code_offset.end()) {
|
||||
sym_va_val = code_vaddr + it->second;
|
||||
} else if (auto it = sym_data_offset.find(r.sym_id);
|
||||
it != sym_data_offset.end()) {
|
||||
sym_va_val = data_vaddr + it->second;
|
||||
} else {
|
||||
reloc_error = "PC32: unknown sym_id";
|
||||
goto done;
|
||||
}
|
||||
const std::int64_t disp = static_cast<std::int64_t>(sym_va_val)
|
||||
- static_cast<std::int64_t>(P) + r.addend + bias;
|
||||
if (!patch32(disp)) goto done;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case RelocOp::PLT32: {
|
||||
// Route through import thunk if external, otherwise treat as PC32.
|
||||
if (auto it = import_to_thunk.find(r.sym_id);
|
||||
it != import_to_thunk.end()) {
|
||||
const std::uint64_t thunk_va =
|
||||
kImageBase + text_rva + it->second * thunk_stride;
|
||||
const std::int64_t disp = static_cast<std::int64_t>(thunk_va)
|
||||
- static_cast<std::int64_t>(P) + r.addend;
|
||||
if (!patch32(disp)) goto done;
|
||||
break;
|
||||
}
|
||||
if (auto it = sym_code_offset.find(r.sym_id);
|
||||
it != sym_code_offset.end()) {
|
||||
const std::int64_t disp = static_cast<std::int64_t>(
|
||||
code_vaddr + it->second) - static_cast<std::int64_t>(P) + r.addend;
|
||||
if (!patch32(disp)) goto done;
|
||||
break;
|
||||
}
|
||||
reloc_error = "PLT32: unknown sym_id";
|
||||
goto done;
|
||||
}
|
||||
case RelocOp::Abs64: {
|
||||
std::uint64_t va = 0;
|
||||
if (!sym_va(r.sym_id, r.addend, va)) goto done;
|
||||
if (!patch64(static_cast<std::int64_t>(va))) goto done;
|
||||
break;
|
||||
}
|
||||
case RelocOp::Abs32: case RelocOp::Abs32Signed: {
|
||||
std::uint64_t va = 0;
|
||||
if (!sym_va(r.sym_id, r.addend, va)) goto done;
|
||||
if (!patch32(static_cast<std::int64_t>(va))) goto done;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
// Skip GOT/TLS opcodes — not expected in freestanding COFF objects.
|
||||
break;
|
||||
}
|
||||
}
|
||||
done:
|
||||
if (!reloc_error.empty()) {
|
||||
out.ok = false;
|
||||
out.error = "pe_synth reloc: " + reloc_error;
|
||||
return out;
|
||||
}
|
||||
|
||||
// --- Fill import thunk stubs: JMP QWORD PTR [RIP + disp32] ---
|
||||
// Each stub is at text_rva + i * thunk_stride in the image.
|
||||
// The IAT entry is at rdata_rva + iat_off + import_iat_slot[i] * 8
|
||||
// (the IAT is partitioned per DLL with null terminators, so i != slot).
|
||||
for (std::uint32_t i = 0; i < nimports; ++i) {
|
||||
const std::uint32_t stub_off = i * thunk_stride;
|
||||
const std::uint64_t stub_va = kImageBase + text_rva + stub_off;
|
||||
const std::uint64_t iat_entry_va = iat_vaddr + import_iat_slot[i] * 8;
|
||||
// JMP QWORD PTR [RIP + disp]: FF 25 <disp32>
|
||||
// RIP at time of dispatch = stub_va + 6.
|
||||
const std::int64_t disp = static_cast<std::int64_t>(iat_entry_va)
|
||||
- static_cast<std::int64_t>(stub_va + 6);
|
||||
text_raw[stub_off + 0] = 0xFF;
|
||||
text_raw[stub_off + 1] = 0x25;
|
||||
std::int32_t disp32 = static_cast<std::int32_t>(disp);
|
||||
std::memcpy(text_raw.data() + stub_off + 2, &disp32, 4);
|
||||
// bytes 6-15: NOP padding
|
||||
std::fill(text_raw.begin() + stub_off + 6,
|
||||
text_raw.begin() + stub_off + thunk_stride,
|
||||
static_cast<std::uint8_t>(0x90));
|
||||
}
|
||||
|
||||
// --- Fill export directory ---
|
||||
for (std::uint32_t i = 0; i < nexports; ++i) {
|
||||
// Function RVA = thunks_size + code_offset.
|
||||
const std::uint32_t fn_rva =
|
||||
text_rva + thunks_size
|
||||
+ static_cast<std::uint32_t>(input.exports[i].code_offset);
|
||||
w32(rdata, exp_fn_rvas_off + i * 4, fn_rva);
|
||||
w32(rdata, exp_name_rvas_off + i * 4, exp_name_rva[i]);
|
||||
w16(rdata, exp_ordinals_off + i * 2, static_cast<std::uint16_t>(i));
|
||||
}
|
||||
{
|
||||
const std::uint32_t at = exp_dir_off;
|
||||
w32(rdata, at + 0, 0); // Characteristics
|
||||
w32(rdata, at + 4, 0); // TimeDateStamp
|
||||
w16(rdata, at + 8, 0); w16(rdata, at + 10, 0); // Version
|
||||
w32(rdata, at + 12, rdata_rva_of(exp_dll_name_off)); // Name
|
||||
w32(rdata, at + 16, 1); // Base (ordinal base)
|
||||
w32(rdata, at + 20, nexports); // NumberOfFunctions
|
||||
w32(rdata, at + 24, nexports); // NumberOfNames
|
||||
w32(rdata, at + 28, rdata_rva_of(exp_fn_rvas_off)); // AddressOfFunctions
|
||||
w32(rdata, at + 32, rdata_rva_of(exp_name_rvas_off));// AddressOfNames
|
||||
w32(rdata, at + 36, rdata_rva_of(exp_ordinals_off)); // AddressOfNameOrdinals
|
||||
}
|
||||
|
||||
// --- Copy sections into final image ---
|
||||
std::memcpy(img.data() + text_foff, text_raw.data(), text_raw.size());
|
||||
std::memcpy(img.data() + rdata_foff, rdata.data(), rdata.size());
|
||||
if (has_data)
|
||||
std::memcpy(img.data() + data_foff, input.data_blob.data(), input.data_blob.size());
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace voidlibc::loader::windows
|
||||
@@ -0,0 +1,60 @@
|
||||
#pragma once
|
||||
|
||||
#include "format/reloc_ir.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace voidlibc::loader::windows {
|
||||
|
||||
struct WinExportedSymbol {
|
||||
std::string name;
|
||||
std::uint64_t code_offset;
|
||||
std::uint64_t size;
|
||||
bool is_function = true;
|
||||
};
|
||||
|
||||
struct WinImportedSymbol {
|
||||
std::uint32_t sym_id = 0;
|
||||
std::string name;
|
||||
std::string library; // DLL name (e.g. "KERNEL32.DLL"); "" → default ucrtbase.dll
|
||||
};
|
||||
|
||||
struct WinInternalSymbol {
|
||||
std::uint32_t sym_id = 0;
|
||||
std::uint64_t code_offset = 0;
|
||||
std::string name;
|
||||
};
|
||||
|
||||
struct WinDataSymbol {
|
||||
std::uint32_t sym_id = 0;
|
||||
std::uint64_t data_offset = 0;
|
||||
std::string name;
|
||||
};
|
||||
|
||||
struct PeSynthInput {
|
||||
std::vector<std::uint8_t> code; // [.text] + [.rdata] blob
|
||||
std::vector<WinExportedSymbol> exports;
|
||||
std::vector<voidlibc::format::RelocEntry> relocs;
|
||||
std::vector<WinInternalSymbol> internal_symbols;
|
||||
std::vector<WinImportedSymbol> imports;
|
||||
std::vector<std::uint8_t> data_blob; // [.data] + [.bss]
|
||||
std::vector<WinDataSymbol> data_symbols;
|
||||
std::string dll_name; // suggested file name
|
||||
};
|
||||
|
||||
struct PeSynthOutput {
|
||||
std::vector<std::uint8_t> bytes; // complete PE image bytes
|
||||
std::string error;
|
||||
bool ok = true;
|
||||
};
|
||||
|
||||
// Produce a minimal PE64 DLL image (IMAGE_FILE_DLL, Machine=0x8664) that
|
||||
// LoadLibraryEx will accept on Windows x64. Exports all symbols in
|
||||
// input.exports; resolves imported symbols via an IAT pointing into a
|
||||
// synthetic ".voidlib" import descriptor (the voidlib shim resolves these
|
||||
// at load time against the calling process's symbol space).
|
||||
PeSynthOutput synthesize_pe(const PeSynthInput& input);
|
||||
|
||||
} // namespace voidlibc::loader::windows
|
||||
Reference in new issue
Block a user