// 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 #include #include 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& v, std::uint32_t off, std::uint16_t x) { v[off] = static_cast(x); v[off+1] = static_cast(x >> 8); } static void w32(std::vector& v, std::uint32_t off, std::uint32_t x) { v[off] = static_cast(x); v[off+1] = static_cast(x >> 8); v[off+2] = static_cast(x >> 16); v[off+3] = static_cast(x >> 24); } static void w64(std::vector& v, std::uint32_t off, std::uint64_t x) { w32(v, off, static_cast(x)); w32(v, off+4, static_cast(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& 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(input.imports.size()); const std::uint32_t nexports = static_cast(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 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 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 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 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(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 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 import_indices; // indices into input.imports }; std::vector dll_groups; std::unordered_map 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(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 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 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 import_name_rvas(nimports); for (std::uint32_t i = 0; i < nimports; ++i) { const std::uint32_t name_off = static_cast(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 dll_name_rvas(ndlls); for (std::uint32_t d = 0; d < ndlls; ++d) { const std::uint32_t off = static_cast(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(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(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(rdata.size()); rdata.resize(rdata.size() + nexports * 4, 0); // function RVA array const std::uint32_t exp_name_rvas_off = static_cast(rdata.size()); rdata.resize(rdata.size() + nexports * 4, 0); // name RVA array const std::uint32_t exp_ordinals_off = static_cast(rdata.size()); rdata.resize(rdata.size() + nexports * 2, 0); // ordinal array // Export name strings. std::vector exp_name_rva(nexports); for (std::uint32_t i = 0; i < nexports; ++i) { exp_name_rva[i] = rdata_rva_of(static_cast(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(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(rdata.size()); rdata.resize(rdata.size() + 40, 0); const std::uint32_t rdata_vsz = static_cast(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(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(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(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(text_raw.size())) { reloc_error = "reloc patch out of range"; return false; } const std::int32_t v32 = static_cast(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(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(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(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(thunk_va) - static_cast(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(sym_va_val) - static_cast(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(thunk_va) - static_cast(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( code_vaddr + it->second) - static_cast(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(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(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 // RIP at time of dispatch = stub_va + 6. const std::int64_t disp = static_cast(iat_entry_va) - static_cast(stub_va + 6); text_raw[stub_off + 0] = 0xFF; text_raw[stub_off + 1] = 0x25; std::int32_t disp32 = static_cast(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(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(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(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