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

851 lines
35 KiB
C++

#include "reloc_lowering.hpp"
#include "format/reloc_ir.hpp"
#include "format/vlc_format.hpp"
#include "loader/common/elf64.hpp"
#include <algorithm>
#include <cstring>
#include <sstream>
#include <unordered_map>
namespace voidlibc::voidlink {
using namespace voidlibc::format;
using voidlibc::loader::kRX86_64_None;
using voidlibc::loader::kRX86_64_64;
using voidlibc::loader::kRX86_64_PC32;
using voidlibc::loader::kRX86_64_PLT32;
using voidlibc::loader::kRX86_64_32;
using voidlibc::loader::kRX86_64_32S;
using voidlibc::loader::kRX86_64_GOTPCREL;
using voidlibc::loader::kRX86_64_GOTPCRELX;
using voidlibc::loader::kRX86_64_REX_GOTPCRELX;
using voidlibc::loader::kShtProgbits;
using voidlibc::loader::kShtNobits;
namespace {
constexpr std::uint8_t kStbLocal = 0;
constexpr std::uint8_t kStbGlobal = 1;
constexpr std::uint8_t kStbWeak = 2;
constexpr std::uint8_t kSttNotype = 0;
constexpr std::uint8_t kSttObject = 1;
constexpr std::uint8_t kSttFunc = 2;
constexpr std::uint8_t kSttSection = 3;
// .text.startup, .text.hot, .text.unlikely, .text.N comdat sections, etc.
// These are code sections that GCC emits separately from .text. They get
// merged into the RX code blob with their relocs processed identically.
bool is_text_companion_section(const std::string& name) {
return name.rfind(".text.", 0) == 0;
}
// .rodata and all .rodata.* sections — read-only data merged into RX blob.
// Only PC32 relocs from .text to these are expected (string literals, etc.);
// they are base-invariant so no separate reloc processing is needed here.
bool is_rodata_companion_section(const std::string& name) {
return name.rfind(".rodata", 0) == 0;
}
// .bss, .bss.*, .data, .data.* (excluding .data.rel.*) — writable data blob.
bool is_data_section(const std::string& name) {
if (name == ".bss" || name.rfind(".bss.", 0) == 0) return true;
if (name == ".data") return true;
if (name.rfind(".data.", 0) == 0 && name.rfind(".data.rel", 0) != 0) return true;
return false;
}
constexpr std::uint64_t align_up(std::uint64_t v, std::uint64_t a) {
return (v + (a - 1)) & ~(a - 1);
}
struct Lowering {
LoweredText out;
// ELF .symtab index → portable symbol id in out.symbols.
std::unordered_map<std::uint32_t, std::uint32_t> elf_to_portable;
// ELF section index → byte offset within the merged code blob.
// Used for: .rodata.* companions AND .text.* companions.
std::unordered_map<std::size_t, std::uint64_t> section_blob_start;
// ELF section index → byte offset within the data blob (.data/.bss).
std::unordered_map<std::size_t, std::uint64_t> data_section_blob_start;
std::string error;
std::uint32_t intern(const elf::ParsedObject& obj,
std::size_t text_idx,
std::uint32_t elf_sym) {
if (auto it = elf_to_portable.find(elf_sym);
it != elf_to_portable.end()) {
return it->second;
}
const auto& s = obj.symbols[elf_sym];
SymbolSpec ss{};
ss.name = s.name;
ss.kind = (s.type == kSttObject) ? SymbolKind::Object
: SymbolKind::Function;
ss.size = s.size;
ss.weak = (s.bind == kStbWeak);
if (s.defined && s.section_index == text_idx) {
// Symbol lives in .text (primary text section).
ss.section_index = 0;
ss.value = s.value;
ss.exported = (s.bind == kStbGlobal || s.bind == kStbWeak);
} else if (s.defined) {
auto it = section_blob_start.find(s.section_index);
if (it != section_blob_start.end()) {
ss.section_index = 0;
ss.value = it->second + s.value;
// .text.* companions CAN export symbols (e.g. main in .text.startup).
// .rodata.* companions do not export addressable symbols.
const auto& sec_name = obj.sections[s.section_index].name;
ss.exported = is_text_companion_section(sec_name)
&& (s.bind == kStbGlobal || s.bind == kStbWeak);
} else {
auto dit = data_section_blob_start.find(s.section_index);
if (dit != data_section_blob_start.end()) {
ss.section_index = 0;
ss.value = dit->second + s.value;
ss.exported = false;
ss.data_section = true;
} else {
std::ostringstream os;
os << "symbol '" << s.name
<< "' defined in unsupported section (idx "
<< s.section_index << ")";
error = os.str();
return 0;
}
}
} else {
// External import.
ss.section_index = kSymUndefined;
ss.value = 0;
ss.exported = false;
// Forward version requirement (version_index > 1 means versioned).
if (s.version_index > 1) {
for (const auto& vr : obj.version_reqs) {
if (vr.index == s.version_index) {
ss.version_name = vr.version_name;
ss.version_hash = vr.hash;
ss.version_flags = vr.flags;
break;
}
}
}
}
const auto id = static_cast<std::uint32_t>(out.symbols.size());
out.symbols.push_back(std::move(ss));
elf_to_portable.emplace(elf_sym, id);
return id;
}
// Process relocations from one section (the source section's relocs
// reference symbols in the global .symtab). blob_start is the byte offset
// of that section's content within the merged code blob.
bool process_relocs(const elf::ParsedObject& obj,
std::size_t text_idx,
const std::vector<elf::ParsedRelocation>& relocs,
std::uint64_t blob_start) {
for (const auto& r : relocs) {
if (r.sym_index >= obj.symbols.size()) {
std::ostringstream os;
os << "reloc at 0x" << std::hex << r.offset
<< " references out-of-range sym " << std::dec << r.sym_index;
error = os.str();
return false;
}
const auto& referenced = obj.symbols[r.sym_index];
// Section symbols for supported sections.
if (referenced.type == kSttSection) {
if (referenced.section_index == text_idx) {
// .text section symbol — OK.
} else if (section_blob_start.count(referenced.section_index)) {
// .rodata.* or .text.* companion — OK.
} else if (data_section_blob_start.count(referenced.section_index)) {
// .data/.bss — OK.
} else {
std::ostringstream os;
os << "reloc at 0x" << std::hex << r.offset
<< " references section symbol for unsupported section"
<< " (idx " << std::dec << referenced.section_index << ")";
error = os.str();
return false;
}
}
const std::uint32_t sym_id = intern(obj, text_idx, r.sym_index);
if (!error.empty()) return false;
const bool is_external = !referenced.defined;
RelocEntry e{};
e.reserved = 0;
e.dst_offset = static_cast<std::uint32_t>(blob_start + r.offset);
e.sym_id = sym_id;
e.addend = static_cast<std::int32_t>(r.addend);
switch (r.type) {
case kRX86_64_None:
continue;
case kRX86_64_PC32:
if (is_external) {
std::ostringstream os;
os << "R_X86_64_PC32 against external symbol '"
<< referenced.name << "' at 0x" << std::hex << r.offset
<< "; use PLT32 for function calls";
error = os.str();
return false;
}
e.op = RelocOp::PC32;
break;
case kRX86_64_PLT32:
e.op = is_external ? RelocOp::PLT32 : RelocOp::PC32;
break;
case kRX86_64_64:
e.op = RelocOp::Abs64;
break;
case kRX86_64_32:
e.op = RelocOp::Abs32;
break;
case kRX86_64_32S:
e.op = RelocOp::Abs32Signed;
break;
case kRX86_64_GOTPCREL:
e.op = RelocOp::GotPC32;
break;
case kRX86_64_GOTPCRELX:
e.op = RelocOp::GotPC32X;
break;
case kRX86_64_REX_GOTPCRELX:
e.op = RelocOp::GotPC32XRex;
break;
default: {
std::ostringstream os;
os << "unsupported R_X86_64_" << r.type
<< " at offset 0x" << std::hex << r.offset;
error = os.str();
return false;
}
}
out.section.relocs.push_back(e);
}
return true;
}
};
} // namespace
std::variant<LoweredText, std::string>
lower_elf_text(const elf::ParsedObject& obj, TargetOS target_os) {
if (obj.text_index == static_cast<std::size_t>(-1)) {
return std::string("no .text section in object");
}
const auto& text = obj.sections[obj.text_index];
Lowering L;
L.out.section.target_os = target_os;
L.out.section.entry_offset = 0;
// --- Build the merged code blob ---
//
// Layout: [.text] [.text.* companions (16-byte aligned)] [.rodata.* companions (16-byte aligned)]
//
// .text.* (e.g. .text.startup, .text.hot): code emitted by GCC for specific
// function groups. Their relocs must also be processed.
// .rodata.*: read-only data (string literals, const tables). PC32 relocs
// from .text to .rodata are base-invariant — no separate reloc processing.
L.out.section.code = text.bytes;
// Append .text.* companions first.
for (std::size_t si = 0; si < obj.sections.size(); ++si) {
if (si == obj.text_index) continue;
const auto& sec = obj.sections[si];
if (!is_text_companion_section(sec.name)) continue;
if (sec.type != kShtProgbits) continue;
if (sec.bytes.empty()) continue;
const std::uint64_t aligned =
align_up(static_cast<std::uint64_t>(L.out.section.code.size()), 16);
L.out.section.code.resize(static_cast<std::size_t>(aligned), 0);
L.section_blob_start[si] = aligned;
L.out.section.code.insert(L.out.section.code.end(),
sec.bytes.begin(), sec.bytes.end());
}
// Append .rodata.* companions.
for (std::size_t si = 0; si < obj.sections.size(); ++si) {
if (si == obj.text_index) continue;
const auto& sec = obj.sections[si];
if (!is_rodata_companion_section(sec.name)) continue;
if (sec.type != kShtProgbits) continue;
if (sec.bytes.empty()) continue;
const std::uint64_t aligned =
align_up(static_cast<std::uint64_t>(L.out.section.code.size()), 16);
L.out.section.code.resize(static_cast<std::size_t>(aligned), 0);
L.section_blob_start[si] = aligned;
L.out.section.code.insert(L.out.section.code.end(),
sec.bytes.begin(), sec.bytes.end());
}
// --- Build the data blob: [.data] [.bss zeros] ---
{
std::vector<std::uint8_t> data_blob;
for (std::size_t si = 0; si < obj.sections.size(); ++si) {
if (si == obj.text_index) continue;
const auto& sec = obj.sections[si];
if (!is_data_section(sec.name)) continue;
const std::uint64_t aligned =
align_up(static_cast<std::uint64_t>(data_blob.size()), 8);
data_blob.resize(static_cast<std::size_t>(aligned), 0);
L.data_section_blob_start[si] = aligned;
if (sec.type == kShtNobits) {
data_blob.resize(static_cast<std::size_t>(aligned + sec.mem_size), 0);
} else {
data_blob.insert(data_blob.end(), sec.bytes.begin(), sec.bytes.end());
}
}
L.out.section.data = std::move(data_blob);
}
// --- Pre-intern all globally-visible function symbols ---
// Covers .text and all .text.* companions (e.g. main in .text.startup).
for (std::uint32_t i = 0; i < obj.symbols.size(); ++i) {
const auto& s = obj.symbols[i];
if (!s.defined) continue;
const bool in_text = (s.section_index == obj.text_index);
const bool in_text_comp = !in_text
&& L.section_blob_start.count(s.section_index)
&& is_text_companion_section(obj.sections[s.section_index].name);
if (!in_text && !in_text_comp) continue;
if (s.bind == kStbLocal) continue;
if (s.type != kSttFunc && s.type != kSttNotype) continue;
(void)L.intern(obj, obj.text_index, i);
if (!L.error.empty()) return L.error;
}
// --- Process relocs from .text ---
if (!L.process_relocs(obj, obj.text_index, text.relocs, 0)) {
return L.error;
}
// --- Process relocs from .text.* companions ---
for (std::size_t si = 0; si < obj.sections.size(); ++si) {
const auto& sec = obj.sections[si];
if (!is_text_companion_section(sec.name)) continue;
if (sec.relocs.empty()) continue;
auto it = L.section_blob_start.find(si);
if (it == L.section_blob_start.end()) continue;
if (!L.process_relocs(obj, obj.text_index, sec.relocs, it->second)) {
return L.error;
}
}
// --- Process relocs from .rodata.* companions ---
// GCC places switch-statement jump tables in .rodata with R_X86_64_PC32
// entries that point back into .text (the case labels). Without applying
// these, table entries remain zero and indirect jumps go to wrong targets.
for (std::size_t si = 0; si < obj.sections.size(); ++si) {
const auto& sec = obj.sections[si];
if (!is_rodata_companion_section(sec.name)) continue;
if (sec.relocs.empty()) continue;
auto it = L.section_blob_start.find(si);
if (it == L.section_blob_start.end()) continue;
if (!L.process_relocs(obj, obj.text_index, sec.relocs, it->second)) {
return L.error;
}
}
return std::move(L.out);
}
// ---------------------------------------------------------------------------
// COFF lowering
namespace {
constexpr std::uint64_t coff_align_up(std::uint64_t v, std::uint64_t a) {
return (v + (a - 1)) & ~(a - 1);
}
bool is_coff_code_section(const coff::ParsedSection& s) {
return (s.characteristics & coff::kScnCntCode) != 0
&& (s.characteristics & coff::kScnMemExecute) != 0;
}
bool is_coff_rdata_section(const coff::ParsedSection& s) {
return (s.characteristics & coff::kScnCntInitData) != 0
&& (s.characteristics & coff::kScnMemRead) != 0
&& (s.characteristics & coff::kScnMemWrite) == 0;
}
bool is_coff_data_section(const coff::ParsedSection& s) {
const bool init = (s.characteristics & coff::kScnCntInitData) != 0;
const bool uninit = (s.characteristics & coff::kScnCntUninitData) != 0;
const bool write = (s.characteristics & coff::kScnMemWrite) != 0;
return (init || uninit) && write;
}
struct CoffLowering {
LoweredText out;
std::unordered_map<std::uint32_t, std::uint32_t> coff_to_portable; // sym_idx → portable id
// section_index (0-based) → blob start in code blob (for code+rdata sections)
std::unordered_map<std::size_t, std::uint64_t> code_sec_blob_start;
// section_index → blob start in data blob (for .data/.bss sections)
std::unordered_map<std::size_t, std::uint64_t> data_sec_blob_start;
std::string error;
std::uint32_t intern(const coff::ParsedObject& obj,
std::size_t text_sec_idx,
std::uint32_t coff_sym) {
if (auto it = coff_to_portable.find(coff_sym);
it != coff_to_portable.end())
return it->second;
const auto& s = obj.symbols[coff_sym];
SymbolSpec ss{};
ss.name = s.name;
ss.size = s.size;
ss.weak = (s.bind == coff::kBindWeak);
ss.kind = (s.type == coff::kTypeFunc) ? SymbolKind::Function
: SymbolKind::Object;
if (s.defined) {
const std::size_t sec0 = static_cast<std::size_t>(s.section_index - 1);
if (sec0 == text_sec_idx) {
ss.section_index = 0;
ss.value = s.value;
ss.exported = (s.bind == coff::kBindGlobal || s.bind == coff::kBindWeak);
} else if (auto it = code_sec_blob_start.find(sec0);
it != code_sec_blob_start.end()) {
ss.section_index = 0;
ss.value = it->second + s.value;
ss.exported = is_coff_code_section(obj.sections[sec0])
&& (s.bind == coff::kBindGlobal || s.bind == coff::kBindWeak);
} else if (auto it = data_sec_blob_start.find(sec0);
it != data_sec_blob_start.end()) {
ss.section_index = 0;
ss.value = it->second + s.value;
ss.exported = false;
ss.data_section = true;
} else {
std::ostringstream os;
os << "symbol '" << s.name
<< "' in unsupported section (idx " << sec0 << ")";
error = os.str();
return 0;
}
} else {
// External import.
ss.section_index = kSymUndefined;
ss.value = 0;
ss.exported = false;
}
const auto id = static_cast<std::uint32_t>(out.symbols.size());
out.symbols.push_back(std::move(ss));
coff_to_portable.emplace(coff_sym, id);
return id;
}
bool process_relocs(const coff::ParsedObject& obj,
std::size_t text_sec_idx,
const std::vector<coff::ParsedRelocation>& relocs,
std::uint64_t blob_start) {
using coff::kRelocRel32;
using coff::kRelocRel32_1; using coff::kRelocRel32_2;
using coff::kRelocRel32_4; using coff::kRelocRel32_5;
using coff::kRelocAddr64;
using coff::kRelocAddr32; using coff::kRelocAddr32NB;
for (const auto& r : relocs) {
if (r.sym_index >= obj.symbols.size()) {
std::ostringstream os;
os << "COFF reloc at 0x" << std::hex << r.offset
<< " references out-of-range sym " << std::dec << r.sym_index;
error = os.str();
return false;
}
const auto& sym = obj.symbols[r.sym_index];
const std::uint32_t pid = intern(obj, text_sec_idx, r.sym_index);
if (!error.empty()) return false;
RelocEntry e{};
e.reserved = 0;
e.dst_offset = static_cast<std::uint32_t>(blob_start + r.offset);
e.sym_id = pid;
switch (r.type) {
case kRelocRel32:
// COFF REL32: value = S + inline - (P+4).
// Portable PC32: value = S - P + addend, where addend = inline - 4.
e.op = RelocOp::PC32;
e.addend = static_cast<std::int32_t>(r.addend - 4);
break;
case kRelocRel32_1:
e.op = RelocOp::PC32_1;
e.addend = static_cast<std::int32_t>(r.addend - 4);
break;
case kRelocRel32_2:
e.op = RelocOp::PC32_2;
e.addend = static_cast<std::int32_t>(r.addend - 4);
break;
case coff::kRelocRel32_3:
// No dedicated PC32_3 opcode; treat as PC32 with adjusted addend.
e.op = RelocOp::PC32;
e.addend = static_cast<std::int32_t>(r.addend - 7);
break;
case kRelocRel32_4:
e.op = RelocOp::PC32_4;
e.addend = static_cast<std::int32_t>(r.addend - 4);
break;
case kRelocRel32_5:
e.op = RelocOp::PC32_5;
e.addend = static_cast<std::int32_t>(r.addend - 4);
break;
case kRelocAddr64:
e.op = RelocOp::Abs64;
e.addend = static_cast<std::int32_t>(r.addend);
break;
case kRelocAddr32:
e.op = RelocOp::Abs32;
e.addend = static_cast<std::int32_t>(r.addend);
break;
case kRelocAddr32NB:
// Relative to image base — only meaningful in PE context.
// Silently skip for portable IR (VLC is PIC; these don't appear in code).
continue;
default: {
// Skip SECTION / SECREL / unknown types.
(void)sym;
continue;
}
}
out.section.relocs.push_back(e);
}
return true;
}
};
} // namespace
std::variant<LoweredText, std::string>
lower_coff_text(const coff::ParsedObject& obj,
voidlibc::format::TargetOS target_os) {
if (obj.text_index == static_cast<std::size_t>(-1))
return std::string("no executable .text section in COFF object");
const std::size_t text_si = obj.text_index;
const auto& text_sec = obj.sections[text_si];
CoffLowering L;
L.out.section.target_os = target_os;
L.out.section.entry_offset = 0;
// --- Build merged code blob: [.text][companion code+rdata sections (16-aligned)] ---
L.out.section.code = text_sec.bytes;
// Append additional code sections (.text$... COMDAT sections and .rdata).
for (std::size_t si = 0; si < obj.sections.size(); ++si) {
if (si == text_si) continue;
const auto& sec = obj.sections[si];
const bool is_code = is_coff_code_section(sec);
const bool is_rdata = is_coff_rdata_section(sec);
if (!is_code && !is_rdata) continue;
if (sec.bytes.empty() && sec.mem_size == 0) continue;
const std::uint64_t aligned =
coff_align_up(static_cast<std::uint64_t>(L.out.section.code.size()), 16);
L.out.section.code.resize(static_cast<std::size_t>(aligned), 0);
L.code_sec_blob_start[si] = aligned;
L.out.section.code.insert(L.out.section.code.end(),
sec.bytes.begin(), sec.bytes.end());
// Pad to mem_size if bytes < mem_size.
if (sec.mem_size > sec.bytes.size()) {
L.out.section.code.resize(
L.out.section.code.size() + (sec.mem_size - sec.bytes.size()), 0);
}
}
// --- Build data blob: [.data][.bss] (8-byte aligned between items) ---
{
std::vector<std::uint8_t> data_blob;
for (std::size_t si = 0; si < obj.sections.size(); ++si) {
if (si == text_si) continue;
const auto& sec = obj.sections[si];
if (!is_coff_data_section(sec)) continue;
const std::uint64_t aligned =
coff_align_up(static_cast<std::uint64_t>(data_blob.size()), 8);
data_blob.resize(static_cast<std::size_t>(aligned), 0);
L.data_sec_blob_start[si] = aligned;
if (sec.bytes.empty()) {
data_blob.resize(data_blob.size() + sec.mem_size, 0);
} else {
data_blob.insert(data_blob.end(), sec.bytes.begin(), sec.bytes.end());
if (sec.mem_size > sec.bytes.size())
data_blob.resize(data_blob.size() + (sec.mem_size - sec.bytes.size()), 0);
}
}
L.out.section.data = std::move(data_blob);
}
// --- Pre-intern exported symbols from .text and companion code sections ---
for (std::uint32_t i = 0; i < obj.symbols.size(); ++i) {
const auto& s = obj.symbols[i];
if (!s.defined) continue;
if (s.bind == coff::kBindLocal) continue;
const std::size_t sec0 = static_cast<std::size_t>(s.section_index - 1);
const bool in_text = (sec0 == text_si);
const bool in_code_c = !in_text && L.code_sec_blob_start.count(sec0)
&& is_coff_code_section(obj.sections[sec0]);
if (!in_text && !in_code_c) continue;
if (s.type != coff::kTypeFunc && s.type != coff::kTypeNone) continue;
(void)L.intern(obj, text_si, i);
if (!L.error.empty()) return L.error;
}
// --- Process relocs from .text ---
if (!L.process_relocs(obj, text_si, text_sec.relocs, 0))
return L.error;
// --- Process relocs from companion sections ---
for (std::size_t si = 0; si < obj.sections.size(); ++si) {
if (si == text_si) continue;
const auto& sec = obj.sections[si];
if (sec.relocs.empty()) continue;
auto it = L.code_sec_blob_start.find(si);
if (it == L.code_sec_blob_start.end()) continue;
if (!L.process_relocs(obj, text_si, sec.relocs, it->second))
return L.error;
}
return std::move(L.out);
}
// ===========================================================================
// Mach-O (x86-64 macOS) lowering
// ===========================================================================
namespace {
using namespace voidlibc::voidlink::macho;
struct MachoLowering {
LoweredText out;
std::string error;
// Maps Mach-O 1-based section ordinal → byte offset within the merged code blob.
std::unordered_map<std::uint32_t, std::uint64_t> sec_blob_start;
// Maps Mach-O 1-based section ordinal → .o section vmaddr (for non-extern delta patching).
std::unordered_map<std::uint32_t, std::uint64_t> sec_o_addr;
std::unordered_map<std::uint32_t, std::uint32_t> sym_id_map;
std::uint32_t intern_sym(const ParsedObject& obj, std::uint32_t macho_idx) {
auto it = sym_id_map.find(macho_idx);
if (it != sym_id_map.end()) return it->second;
const auto& s = obj.symbols[macho_idx];
SymbolSpec ss{};
ss.name = s.name;
ss.exported = (s.bind == 1 && s.defined);
ss.section_index = kSymUndefined;
if (s.defined && s.section_index >= 1
&& static_cast<std::size_t>(s.section_index - 1) < obj.sections.size()) {
auto bit = sec_blob_start.find(static_cast<std::uint32_t>(s.section_index));
ss.value = s.value + (bit != sec_blob_start.end() ? bit->second : 0);
ss.section_index = 0;
}
ss.kind = (s.type == 2) ? SymbolKind::Function : SymbolKind::Object;
const auto id = static_cast<std::uint32_t>(out.symbols.size());
out.symbols.push_back(std::move(ss));
sym_id_map[macho_idx] = id;
return id;
}
bool process_relocs(const ParsedObject& obj,
const std::vector<macho::ParsedRelocation>& relocs,
std::uint64_t blob_offset) {
for (std::size_t ri = 0; ri < relocs.size(); ++ri) {
const auto& r = relocs[ri];
if (!r.is_extern) {
// Non-extern (section-relative) PC-rel relocs: the inline displacement was
// computed by the assembler using the .o section layout. Our blob layout may
// differ (different alignment padding), so patch the delta in.
if (r.is_pcrel && r.length == 2 &&
(r.type == kRelocSigned || r.type == kRelocBranch ||
r.type == kRelocSigned1 || r.type == kRelocSigned2 ||
r.type == kRelocSigned4)) {
// r.sym_index is a 1-based section ordinal (not a symbol index).
const std::uint32_t sec_ord = r.sym_index;
auto bit = sec_blob_start.find(sec_ord);
auto ait = sec_o_addr.find(sec_ord);
if (bit != sec_blob_start.end() && ait != sec_o_addr.end()) {
const std::int64_t delta = static_cast<std::int64_t>(bit->second)
- static_cast<std::int64_t>(ait->second);
if (delta != 0) {
const std::uint64_t patch = blob_offset + r.offset;
if (patch + 4 <= out.section.code.size()) {
std::int32_t cur = 0;
std::memcpy(&cur, out.section.code.data() + patch, 4);
cur += static_cast<std::int32_t>(delta);
std::memcpy(out.section.code.data() + patch, &cur, 4);
}
}
}
} else if (r.type == kRelocSubtractor && ri + 1 < relocs.size()) {
++ri; // skip the paired UNSIGNED
}
continue;
}
if (r.sym_index >= obj.symbols.size()) {
error = "reloc sym_index out of range";
return false;
}
RelocEntry re{};
re.dst_offset = static_cast<std::uint32_t>(blob_offset + r.offset);
re.sym_id = intern_sym(obj, r.sym_index);
switch (r.type) {
case kRelocSigned:
// Signed PC32 to an external symbol: treat as direct PC32 (data or func).
re.op = RelocOp::PC32;
re.addend = static_cast<std::int32_t>(r.addend);
break;
case kRelocBranch:
// Branch (call/jmp) to an external symbol → PLT stub (same as ELF PLT32).
re.op = RelocOp::PLT32;
re.addend = static_cast<std::int32_t>(r.addend);
break;
case kRelocGotLoad:
case kRelocGot:
re.op = RelocOp::GotPC32;
re.addend = static_cast<std::int32_t>(r.addend);
break;
case kRelocUnsigned:
re.op = (r.length == 3) ? RelocOp::Abs64 : RelocOp::Abs32;
re.addend = static_cast<std::int32_t>(r.addend);
break;
case kRelocSigned1:
re.op = RelocOp::PC32;
re.addend = static_cast<std::int32_t>(r.addend) - 1;
break;
case kRelocSigned2:
re.op = RelocOp::PC32;
re.addend = static_cast<std::int32_t>(r.addend) - 2;
break;
case kRelocSigned4:
re.op = RelocOp::PC32;
re.addend = static_cast<std::int32_t>(r.addend) - 4;
break;
case kRelocSubtractor:
if (ri + 1 < relocs.size()) ++ri;
continue;
case kRelocTls:
re.op = RelocOp::TlsGD;
re.addend = 0;
break;
default:
error = "unhandled Mach-O reloc type " + std::to_string(r.type);
return false;
}
out.section.relocs.push_back(re);
}
return true;
}
};
} // anonymous namespace
std::variant<LoweredText, std::string>
lower_macho_text(const macho::ParsedObject& obj,
voidlibc::format::TargetOS target_os) {
if (obj.text_index == static_cast<std::size_t>(-1))
return std::string{"no __text section"};
MachoLowering L;
L.out.section.target_os = target_os;
const auto& text_sec = obj.sections[obj.text_index];
L.sec_blob_start[static_cast<std::uint32_t>(obj.text_index + 1)] = 0;
L.sec_o_addr[static_cast<std::uint32_t>(obj.text_index + 1)] = text_sec.addr;
L.out.section.code = text_sec.bytes;
// Append read-only companion sections (__const, __cstring, etc.).
for (std::size_t si = 0; si < obj.sections.size(); ++si) {
if (si == obj.text_index) continue;
const auto& sec = obj.sections[si];
const bool is_ro = (sec.sectname == "__const")
|| (sec.sectname == "__rodata")
|| (sec.sectname == "__cstring")
|| sec.sectname.rfind("__literal", 0) == 0
|| sec.sectname.rfind("__gcc_except", 0) == 0;
if (!is_ro) continue;
// Align to max(16, section's natural alignment) to match the section's own alignment
// so that non-extern SIGNED reloc deltas stay zero when the .o already aligns to ≤16.
const std::uint64_t align = std::max(std::uint64_t(16),
std::uint64_t(1) << sec.align_exp);
while (L.out.section.code.size() % align != 0) L.out.section.code.push_back(0);
L.sec_blob_start[static_cast<std::uint32_t>(si + 1)] = L.out.section.code.size();
L.sec_o_addr[static_cast<std::uint32_t>(si + 1)] = sec.addr;
L.out.section.code.insert(L.out.section.code.end(),
sec.bytes.begin(), sec.bytes.end());
}
// Writable sections → data blob.
for (std::size_t si = 0; si < obj.sections.size(); ++si) {
if (si == obj.text_index) continue;
const auto& sec = obj.sections[si];
const bool is_rw = (sec.sectname == "__data")
|| (sec.sectname == "__bss")
|| (sec.sectname == "__common")
|| sec.sectname.rfind("__thread_", 0) == 0;
if (!is_rw) continue;
while (L.out.section.data.size() % 16 != 0) L.out.section.data.push_back(0);
const std::uint64_t off =
static_cast<std::uint64_t>(L.out.section.code.size())
+ L.out.section.data.size();
L.sec_blob_start[static_cast<std::uint32_t>(si + 1)] = off;
L.sec_o_addr[static_cast<std::uint32_t>(si + 1)] = sec.addr;
L.out.section.data.insert(L.out.section.data.end(),
sec.bytes.begin(), sec.bytes.end());
if (sec.mem_size > sec.bytes.size())
L.out.section.data.resize(
L.out.section.data.size() + (sec.mem_size - sec.bytes.size()), 0);
}
// Intern all named symbols.
for (std::uint32_t si = 0; si < obj.symbols.size(); ++si) {
if (!obj.symbols[si].name.empty()) L.intern_sym(obj, si);
}
if (!L.process_relocs(obj, text_sec.relocs, 0)) return L.error;
for (std::size_t si = 0; si < obj.sections.size(); ++si) {
if (si == obj.text_index) continue;
const auto& sec = obj.sections[si];
if (sec.relocs.empty()) continue;
auto bit = L.sec_blob_start.find(static_cast<std::uint32_t>(si + 1));
if (bit == L.sec_blob_start.end()) continue;
if (!L.process_relocs(obj, sec.relocs, bit->second)) return L.error;
}
return std::move(L.out);
}
} // namespace voidlibc::voidlink