This commit is contained in:
2026-03-24 13:40:31 +00:00
parent c56256f63e
commit 5941cd7248
10 changed files with 194 additions and 161 deletions
+50 -25
View File
@@ -2,6 +2,7 @@ use crate::building::output::CompiledModule;
use crate::building::plan::BuildStep;
use prometeu_bytecode::opcode::OpCode;
use prometeu_bytecode::layout;
use prometeu_bytecode::opcode_spec::OpCodeSpecExt;
use prometeu_bytecode::{ConstantPoolEntry, DebugInfo};
use std::collections::HashMap;
use prometeu_abi::virtual_machine::{ProgramImage, Value};
@@ -219,51 +220,46 @@ impl Linker {
};
pos += 2;
let imm_len = opcode.spec().imm_bytes as usize;
match opcode {
OpCode::PushConst => {
if pos + 4 <= end {
if pos + imm_len <= end && imm_len == 4 {
let local_idx = u32::from_le_bytes(combined_code[pos..pos+4].try_into().unwrap()) as usize;
if let Some(&global_idx) = local_to_global_const.get(local_idx) {
combined_code[pos..pos+4].copy_from_slice(&global_idx.to_le_bytes());
}
pos += 4;
}
pos += imm_len;
}
OpCode::Call => {
if pos + 4 <= end {
if pos + imm_len <= end && imm_len == 4 {
let local_func_idx = u32::from_le_bytes(combined_code[pos..pos+4].try_into().unwrap());
// Check if this PC was already patched by an import.
// If it wasn't, it's an internal call that needs relocation.
// `import.relocation_pcs` holds the PC at the start of the CALL immediate (after opcode),
// and here `pos` currently points exactly at that immediate.
let reloc_pc = (pos - code_offset) as u32;
let is_import = module.imports.iter().any(|imp| imp.relocation_pcs.contains(&reloc_pc));
if !is_import {
let global_func_idx = module_function_offsets[i] + local_func_idx;
combined_code[pos..pos+4].copy_from_slice(&global_func_idx.to_le_bytes());
}
pos += 4;
}
pos += imm_len;
}
// Do NOT relocate intra-function control flow. Branch immediates are
// function-relative by contract and must remain untouched by the linker.
// Relocate intra-function control-flow immediates by module code offset to preserve absolute PCs
OpCode::Jmp | OpCode::JmpIfFalse | OpCode::JmpIfTrue => {
// Just skip the immediate
pos += 4;
if pos + imm_len <= end && imm_len == 4 {
patch_u32_at(&mut combined_code, pos, &|cur| cur + (code_offset as u32));
}
pos += imm_len;
}
OpCode::PushI32 | OpCode::PushBounded | OpCode::GetGlobal | OpCode::SetGlobal | OpCode::GetLocal | OpCode::SetLocal
| OpCode::PopN | OpCode::Syscall | OpCode::GateLoad | OpCode::GateStore => {
pos += 4;
_ => {
// Generic advance using canonical immediate length.
pos += imm_len;
}
OpCode::PushI64 | OpCode::PushF64 | OpCode::Alloc => {
pos += 8;
}
OpCode::PushBool => {
pos += 1;
}
_ => {}
}
}
}
@@ -299,6 +295,9 @@ impl Linker {
// "name@offset+len", alinhar apenas o `code_len` de `combined_functions[idx]` a esses
// valores (os offsets do DebugInfo são locais ao módulo antes do link). Mantemos o
// `code_offset` já realocado durante o PASS 1.
// Track which function metas received a precise code_len from DebugInfo
let mut has_precise_len: Vec<bool> = vec![false; combined_functions.len()];
for (idx, name) in &combined_function_names {
if let Some((base, rest)) = name.split_once('@') {
let mut parts = rest.split('+');
@@ -308,6 +307,7 @@ impl Linker {
let old_off = meta.code_offset;
let old_len = meta.code_len;
meta.code_len = len;
has_precise_len[*idx as usize] = true;
eprintln!(
"[Linker][debug] Align len idx={} name={} -> code_offset {} (kept) | code_len {} -> {}",
idx, base, old_off, old_len, len
@@ -318,11 +318,30 @@ impl Linker {
}
}
// Recalcular code_len de todas as funções no código combinado com base no deslocamento da próxima função
// (end exclusivo). Isso garante que o fim efetivo da função seja exatamente o início da próxima
// no buffer combinado, evitando divergências em saltos para o fim da função.
// Use rotina canônica compartilhada para recalcular os comprimentos das funções
layout::recompute_function_lengths_in_place(&mut combined_functions, combined_code.len());
// Ensure DebugInfo also contains plain base names alongside enriched names for easy lookup.
// For any entry of form "name@off+len", also add (idx, "name") if missing.
let mut plain_names_to_add: Vec<(u32, String)> = Vec::new();
for (idx, name) in &combined_function_names {
if let Some((base, _)) = name.split_once('@') {
let already_has_plain = combined_function_names.iter().any(|(i, n)| i == idx && n == base);
if !already_has_plain {
plain_names_to_add.push((*idx, base.to_string()));
}
}
}
combined_function_names.extend(plain_names_to_add);
// Recompute code_len ONLY for functions that did NOT receive a precise length from DebugInfo.
// This preserves exact ends emitted by the compiler while still filling lengths for functions
// that lack enriched annotations.
let total_len = combined_code.len();
for i in 0..combined_functions.len() {
if !has_precise_len.get(i).copied().unwrap_or(false) {
let start = combined_functions[i].code_offset as usize;
let end = layout::function_end_from_next(&combined_functions, i, total_len);
combined_functions[i].code_len = end.saturating_sub(start) as u32;
}
}
// Removido padding específico de `frame`; o emissor passou a garantir que o label de término
// esteja no ponto exato do fim do corpo, e, quando necessário, insere NOPs reais antes do fim.
@@ -343,6 +362,12 @@ impl Linker {
let combined_debug_info = if combined_pc_to_span.is_empty() && combined_function_names.is_empty() {
None
} else {
// Ensure entry-point name mapping is present for easy lookup in DebugInfo
if let Some(frame_idx) = final_exports.get("frame") {
if !combined_function_names.iter().any(|(i, n)| i == frame_idx && n == "frame") {
combined_function_names.push((*frame_idx, "frame".to_string()));
}
}
Some(DebugInfo {
pc_to_span: combined_pc_to_span,
function_names: combined_function_names,
@@ -248,6 +248,7 @@ mod tests {
#[test]
fn test_framesync_injected_end_to_end() {
use prometeu_bytecode::opcode::OpCode;
use prometeu_bytecode::opcode_spec::OpCodeSpecExt;
let dir = tempdir().unwrap();
let project_dir = dir.path().to_path_buf();
fs::create_dir_all(project_dir.join("src/main/modules")).unwrap();
@@ -282,25 +283,9 @@ mod tests {
// Decode sequentially: each instruction is a u16 opcode (LE) followed by operands.
// We'll walk forward and record the sequence of opcodes, ignoring operands based on known sizes.
fn operand_size(op: u16) -> usize {
match op {
x if x == OpCode::PushConst as u16 => 4,
x if x == OpCode::PushI64 as u16 => 8,
x if x == OpCode::PushF64 as u16 => 8,
x if x == OpCode::PushBool as u16 => 1,
x if x == OpCode::PushI32 as u16 => 4,
x if x == OpCode::PushBounded as u16 => 4,
x if x == OpCode::Jmp as u16 => 4,
x if x == OpCode::JmpIfFalse as u16 => 4,
x if x == OpCode::JmpIfTrue as u16 => 4,
x if x == OpCode::GetLocal as u16 => 4,
x if x == OpCode::SetLocal as u16 => 4,
x if x == OpCode::GetGlobal as u16 => 4,
x if x == OpCode::SetGlobal as u16 => 4,
x if x == OpCode::Alloc as u16 => 8, // type_id (u32) + slots (u32)
x if x == OpCode::Syscall as u16 => 4,
x if x == OpCode::GateLoad as u16 => 4,
x if x == OpCode::GateStore as u16 => 4,
_ => 0,
match OpCode::try_from(op) {
Ok(opc) => opc.spec().imm_bytes as usize,
Err(_) => 0,
}
}