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

465 lines
17 KiB
C++

#include "internal.h"
#include "format/reloc_ir.hpp"
#include "format/vlc_format.hpp"
#if defined(__linux__)
# include "loader/common/elf_synth.hpp"
# include "loader/linux/handoff.hpp"
# include <dlfcn.h>
#elif defined(__APPLE__)
# include "loader/macos/macho_synth.hpp"
# include "loader/macos/handoff.hpp"
# include <dlfcn.h>
#elif defined(_WIN32)
# include "loader/windows/pe_synth.hpp"
# include "loader/windows/handoff.hpp"
# include <filesystem>
#else
# error "libvoid: unsupported platform"
#endif
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <string>
#include <vector>
namespace {
using namespace voidlibc::format;
thread_local std::string g_last_error;
void set_error(std::string msg) {
g_last_error = std::move(msg);
}
#if defined(__linux__)
constexpr TargetOS kHostOS = TargetOS::Linux;
#elif defined(__APPLE__)
constexpr TargetOS kHostOS = TargetOS::MacOS;
#elif defined(_WIN32)
constexpr TargetOS kHostOS = TargetOS::Windows;
#endif
bool read_all(const char* path, std::vector<std::uint8_t>& out) {
std::ifstream in(path, std::ios::binary | std::ios::ate);
if (!in) {
set_error(std::string("cannot open: ") + path);
return false;
}
const auto size = static_cast<std::streamsize>(in.tellg());
in.seekg(0, std::ios::beg);
out.resize(static_cast<std::size_t>(size));
in.read(reinterpret_cast<char*>(out.data()), size);
if (!in) {
set_error("short read");
return false;
}
return true;
}
struct ParsedVlc {
FileHeader hdr;
std::vector<SectionEntry> sections;
std::vector<SymbolEntry> symbols;
std::vector<char> name_pool;
std::vector<std::vector<RelocEntry>> section_relocs;
};
bool parse_vlc(const std::vector<std::uint8_t>& data, ParsedVlc& p) {
if (data.size() < sizeof(FileHeader)) {
set_error(".vlc too small for header");
return false;
}
std::memcpy(&p.hdr, data.data(), sizeof(FileHeader));
if (p.hdr.magic != kMagic) {
set_error("bad magic; not a .vlc");
return false;
}
if (p.hdr.version_major != kVersionMajor) {
set_error("unsupported version");
return false;
}
if (p.hdr.arch != TargetArch::X86_64) {
set_error("unsupported architecture");
return false;
}
if (p.hdr.file_size != data.size()) {
set_error("header file_size disagrees with on-disk size");
return false;
}
const std::uint64_t sd_end =
p.hdr.section_dir_off
+ static_cast<std::uint64_t>(p.hdr.section_count) * sizeof(SectionEntry);
if (sd_end > data.size()) {
set_error("section directory truncated");
return false;
}
p.sections.resize(p.hdr.section_count);
if (p.hdr.section_count > 0) {
std::memcpy(p.sections.data(),
data.data() + p.hdr.section_dir_off,
p.sections.size() * sizeof(SectionEntry));
}
if (p.hdr.symtab_size > 0) {
if (p.hdr.symtab_off + p.hdr.symtab_size > data.size()) {
set_error("symtab truncated");
return false;
}
SymbolTableHeader sth{};
if (p.hdr.symtab_size < sizeof(sth)) {
set_error("symtab smaller than its header");
return false;
}
std::memcpy(&sth, data.data() + p.hdr.symtab_off, sizeof(sth));
const std::uint64_t entries_off = p.hdr.symtab_off + sizeof(sth);
const std::uint64_t entries_size =
static_cast<std::uint64_t>(sth.entry_count) * sizeof(SymbolEntry);
const std::uint64_t pool_off = entries_off + entries_size;
const std::uint64_t pool_size = sth.name_pool_size;
if (entries_off + entries_size + pool_size
> p.hdr.symtab_off + p.hdr.symtab_size) {
set_error("symtab fields exceed symtab_size");
return false;
}
p.symbols.resize(sth.entry_count);
if (sth.entry_count > 0) {
std::memcpy(p.symbols.data(),
data.data() + entries_off,
entries_size);
}
p.name_pool.assign(
reinterpret_cast<const char*>(data.data() + pool_off),
reinterpret_cast<const char*>(data.data() + pool_off + pool_size));
}
p.section_relocs.resize(p.sections.size());
for (std::size_t si = 0; si < p.sections.size(); ++si) {
const auto& sec = p.sections[si];
if (sec.reloc_size == 0) continue;
if (sec.reloc_off + sec.reloc_size > data.size()) {
set_error("reloc chunk truncated");
return false;
}
if (sec.reloc_size < sizeof(RelocChunk)) {
set_error("reloc chunk smaller than its header");
return false;
}
RelocChunk rc{};
std::memcpy(&rc, data.data() + sec.reloc_off, sizeof(rc));
const std::uint64_t entries_off = sec.reloc_off + sizeof(rc);
const std::uint64_t entries_size =
static_cast<std::uint64_t>(rc.entry_count) * sizeof(RelocEntry);
if (entries_off + entries_size > sec.reloc_off + sec.reloc_size) {
set_error("reloc entries exceed chunk size");
return false;
}
p.section_relocs[si].resize(rc.entry_count);
if (rc.entry_count > 0) {
std::memcpy(p.section_relocs[si].data(),
data.data() + entries_off,
entries_size);
}
}
return true;
}
const SectionEntry* find_section(const ParsedVlc& p, TargetOS os) {
for (const auto& s : p.sections) {
if (s.target_os == os) return &s;
}
return nullptr;
}
std::string name_from_pool(const ParsedVlc& p,
std::uint32_t off,
std::uint32_t len) {
if (len == 0 || off + len > p.name_pool.size()) return {};
return std::string(p.name_pool.data() + off, len);
}
} // namespace
namespace voidlibc::detail {
void* load_vlc(const char* path, bool allow_exec) {
g_last_error.clear();
if (!path) { set_error("null path"); return nullptr; }
std::vector<std::uint8_t> bytes;
if (!read_all(path, bytes)) return nullptr;
ParsedVlc p{};
if (!parse_vlc(bytes, p)) return nullptr;
const bool is_exec = flag_set(p.hdr.flags, ContainerFlags::Executable);
const bool is_stat = flag_set(p.hdr.flags, ContainerFlags::StaticLibrary);
if (is_stat) {
set_error(std::string(path) +
": this is a static archive (.vla), not loadable at runtime — "
"link with voidlink instead");
return nullptr;
}
if (is_exec && !allow_exec) {
set_error(std::string(path) +
": this is an executable .vlc, not a shared library — "
"use voidloader to run it");
return nullptr;
}
const SectionEntry* sec = find_section(p, kHostOS);
if (!sec) {
set_error("no matching OS section in .vlc");
return nullptr;
}
if (sec->code_off + sec->code_size > bytes.size()) {
set_error("code section truncated");
return nullptr;
}
if (sec->kind == SectionKind::NativeBlob) {
#if defined(__linux__)
std::vector<std::uint8_t> blob(bytes.data() + sec->code_off,
bytes.data() + sec->code_off + sec->code_size);
const auto loaded = voidlibc::loader::linux_handoff::dlopen_buffer(blob);
if (!loaded.ok) { set_error(loaded.error); return nullptr; }
return loaded.dl_handle;
#elif defined(__APPLE__)
std::vector<std::uint8_t> blob(bytes.data() + sec->code_off,
bytes.data() + sec->code_off + sec->code_size);
const auto loaded = voidlibc::loader::macos_handoff::dlopen_buffer(blob);
if (!loaded.ok) { set_error(loaded.error); return nullptr; }
return loaded.dl_handle;
#elif defined(_WIN32)
std::vector<std::uint8_t> blob(bytes.data() + sec->code_off,
bytes.data() + sec->code_off + sec->code_size);
const auto loaded = voidlibc::loader::windows_handoff::load_pe_buffer(blob);
if (!loaded.ok) { set_error(loaded.error); return nullptr; }
return loaded.handle;
#endif
}
const auto vlc_sec_index = static_cast<std::uint16_t>(sec - p.sections.data());
struct SymInfo {
std::string name;
std::uint64_t value = 0;
std::uint64_t size = 0;
std::uint32_t sym_id = 0;
bool exported = false;
bool is_data = false;
bool is_func = false;
bool weak = false;
bool defined = false;
bool imported = false;
};
std::vector<SymInfo> sym_infos;
sym_infos.reserve(p.symbols.size());
for (std::uint32_t i = 0; i < p.symbols.size(); ++i) {
const auto& sym = p.symbols[i];
SymInfo s{};
s.name = name_from_pool(p, sym.name_off, sym.name_len);
s.sym_id = i;
s.value = sym.value;
s.size = sym.size;
s.exported = (sym.flags & static_cast<std::uint8_t>(SymbolFlags::Exported)) != 0;
s.is_data = (sym.flags & static_cast<std::uint8_t>(SymbolFlags::DataSection)) != 0;
s.weak = (sym.flags & static_cast<std::uint8_t>(SymbolFlags::Weak)) != 0;
s.is_func = sym.kind == SymbolKind::Function;
s.defined = sym.section_index != kSymUndefined && sym.section_index == vlc_sec_index;
s.imported = sym.section_index == kSymUndefined;
if (s.name.empty() && !s.defined && !s.imported) continue;
sym_infos.push_back(std::move(s));
}
std::vector<voidlibc::format::RelocEntry> relocs;
if (!p.section_relocs[vlc_sec_index].empty())
relocs = p.section_relocs[vlc_sec_index];
#if defined(__linux__)
{
voidlibc::loader::ElfSynthInput input{};
input.code.assign(bytes.data() + sec->code_off,
bytes.data() + sec->code_off + sec->code_size);
if (sec->data_size > 0) {
if (sec->data_off + sec->data_size > bytes.size()) {
set_error("data blob truncated"); return nullptr;
}
input.data_blob.assign(bytes.data() + sec->data_off,
bytes.data() + sec->data_off + sec->data_size);
}
input.relocs = relocs;
for (const auto& s : sym_infos) {
if (s.exported && s.defined && !s.is_data) {
voidlibc::loader::ExportedSymbol e{};
e.name = s.name; e.code_offset = s.value; e.size = s.size;
e.is_function = s.is_func; e.weak = s.weak;
input.exports.push_back(std::move(e));
}
if (s.defined && !s.is_data) {
voidlibc::loader::InternalSymbol is{};
is.sym_id = s.sym_id; is.code_offset = s.value; is.name = s.name;
input.internal_symbols.push_back(std::move(is));
}
if (s.defined && s.is_data) {
voidlibc::loader::DataSymbol ds{};
ds.sym_id = s.sym_id; ds.data_offset = s.value; ds.name = s.name;
input.data_symbols.push_back(std::move(ds));
}
if (s.imported && !s.name.empty()) {
voidlibc::loader::ImportedSymbol im{};
im.sym_id = s.sym_id; im.name = s.name;
input.imports.push_back(std::move(im));
}
}
if (input.exports.empty()) { set_error("no exported symbols"); return nullptr; }
const auto synth = voidlibc::loader::synthesize_elf(input);
if (!synth.ok) { set_error(synth.error); return nullptr; }
const auto loaded = voidlibc::loader::linux_handoff::dlopen_buffer(synth.bytes);
if (!loaded.ok) { set_error(loaded.error); return nullptr; }
return loaded.dl_handle;
}
#elif defined(__APPLE__)
{
voidlibc::loader::macos::MachoSynthInput input{};
input.code.assign(bytes.data() + sec->code_off,
bytes.data() + sec->code_off + sec->code_size);
if (sec->data_size > 0) {
if (sec->data_off + sec->data_size > bytes.size()) {
set_error("data blob truncated"); return nullptr;
}
input.data_blob.assign(bytes.data() + sec->data_off,
bytes.data() + sec->data_off + sec->data_size);
}
input.relocs = relocs;
for (const auto& s : sym_infos) {
if (s.exported && s.defined && !s.is_data) {
voidlibc::loader::macos::MachoExportedSymbol e{};
e.name = s.name; e.code_offset = s.value; e.size = s.size;
e.is_function = s.is_func; e.weak = s.weak;
input.exports.push_back(std::move(e));
}
if (s.defined && !s.is_data) {
voidlibc::loader::macos::MachoInternalSymbol is{};
is.sym_id = s.sym_id; is.code_offset = s.value; is.name = s.name;
input.internal_symbols.push_back(std::move(is));
}
if (s.defined && s.is_data) {
voidlibc::loader::macos::MachoDataSymbol ds{};
ds.sym_id = s.sym_id; ds.data_offset = s.value; ds.name = s.name;
input.data_symbols.push_back(std::move(ds));
}
if (s.imported && !s.name.empty()) {
voidlibc::loader::macos::MachoImportedSymbol im{};
im.sym_id = s.sym_id; im.name = s.name;
input.imports.push_back(std::move(im));
}
}
if (input.exports.empty()) { set_error("no exported symbols"); return nullptr; }
const auto synth = voidlibc::loader::macos::synthesize_macho(input);
if (!synth.ok) { set_error(synth.error); return nullptr; }
const auto loaded = voidlibc::loader::macos_handoff::dlopen_buffer(synth.bytes);
if (!loaded.ok) { set_error(loaded.error); return nullptr; }
return loaded.dl_handle;
}
#elif defined(_WIN32)
voidlibc::loader::windows::PeSynthInput input{};
input.code.assign(bytes.data() + sec->code_off,
bytes.data() + sec->code_off + sec->code_size);
if (sec->data_size > 0) {
if (sec->data_off + sec->data_size > bytes.size()) {
set_error("data blob truncated"); return nullptr;
}
input.data_blob.assign(bytes.data() + sec->data_off,
bytes.data() + sec->data_off + sec->data_size);
}
input.relocs = relocs;
input.dll_name = std::filesystem::path(path).filename().string();
for (const auto& s : sym_infos) {
if (s.exported && s.defined && !s.is_data) {
voidlibc::loader::windows::WinExportedSymbol e{};
e.name = s.name; e.code_offset = s.value; e.size = s.size;
e.is_function = s.is_func;
input.exports.push_back(std::move(e));
}
if (s.defined && !s.is_data) {
voidlibc::loader::windows::WinInternalSymbol is{};
is.sym_id = s.sym_id; is.code_offset = s.value; is.name = s.name;
input.internal_symbols.push_back(std::move(is));
}
if (s.defined && s.is_data) {
voidlibc::loader::windows::WinDataSymbol ds{};
ds.sym_id = s.sym_id; ds.data_offset = s.value; ds.name = s.name;
input.data_symbols.push_back(std::move(ds));
}
if (s.imported && !s.name.empty()) {
voidlibc::loader::windows::WinImportedSymbol im{};
im.sym_id = s.sym_id; im.name = s.name;
input.imports.push_back(std::move(im));
}
}
if (input.exports.empty()) { set_error("no exported symbols"); return nullptr; }
const auto synth = voidlibc::loader::windows::synthesize_pe(input);
if (!synth.ok) { set_error(synth.error); return nullptr; }
const auto loaded = voidlibc::loader::windows_handoff::load_pe_buffer(synth.bytes);
if (!loaded.ok) { set_error(loaded.error); return nullptr; }
return loaded.handle;
#endif
}
} // namespace voidlibc::detail
// ---------------------------------------------------------------------------
// dlopen / dlerror interposers (Linux/macOS only; Windows uses LoadLibrary)
// ---------------------------------------------------------------------------
#if defined(__linux__) || defined(__APPLE__)
static constexpr std::uint8_t kVlcMagic[4] = {
static_cast<std::uint8_t>('V'),
static_cast<std::uint8_t>('L'),
static_cast<std::uint8_t>('C'),
static_cast<std::uint8_t>('\0')
};
static bool sniff_vlc(const char* path) {
std::FILE* f = std::fopen(path, "rb");
if (!f) return false;
std::uint8_t hdr[4] = {};
const bool got = std::fread(hdr, 1, 4, f) == 4;
std::fclose(f);
return got && std::memcmp(hdr, kVlcMagic, 4) == 0;
}
extern "C" void* dlopen(const char* path, int flags) {
using real_t = void* (*)(const char*, int);
static real_t real = reinterpret_cast<real_t>(::dlsym(RTLD_NEXT, "dlopen"));
if (!path || !sniff_vlc(path))
return real(path, flags);
return voidlibc::detail::load_vlc(path, /*allow_exec=*/false);
}
extern "C" char* dlerror() {
using real_t = char* (*)();
static real_t real = reinterpret_cast<real_t>(::dlsym(RTLD_NEXT, "dlerror"));
if (!g_last_error.empty()) {
// Mimic POSIX dlerror: return message then clear, so next call returns NULL.
static thread_local char buf[1024];
std::strncpy(buf, g_last_error.c_str(), sizeof(buf) - 1);
buf[sizeof(buf) - 1] = '\0';
g_last_error.clear();
return buf;
}
return real();
}
#endif // __linux__ || __APPLE__