This commit is contained in:
2026-03-24 13:40:31 +00:00
parent 6eda2d21ac
commit c9b9f18b32
5 changed files with 29 additions and 109 deletions
@@ -255,14 +255,14 @@ impl Linker {
patch_u32_at(&mut combined_code, imm_start, &|_| global_func_idx);
}
}
// Relocate intra-function control-flow immediates by module code offset to preserve absolute PCs
// Branches are strictly function-relative. Do NOT relocate.
// The emitter encodes `target_rel = label - func_start` and the verifier enforces it.
OpCode::Jmp | OpCode::JmpIfFalse | OpCode::JmpIfTrue => {
// For branches, immediate must be present and represents rel PC from function start
let _ = imm_u32_opt.ok_or_else(|| LinkError::IncompatibleSymbolSignature(format!(
"Invalid branch immediate at pc {}",
pc - code_offset
)))?;
patch_u32_at(&mut combined_code, imm_start, &|cur| cur + (code_offset as u32));
// Intentionally no patch here.
}
_ => {}
}
@@ -628,16 +628,16 @@ mod tests {
// Module 2's code starts after module 1's code
let module2_offset = code1.len() as u32;
// Verify that the JMP immediate equals original_target (0) + module2_offset
// Verify that the JMP immediate remains function-relative (0), no relocation applied
let jmp_abs_pc = module2_offset as usize + jmp_pc as usize;
let jmp_imm_off = jmp_abs_pc + 2; // skip opcode
let jmp_patched = u32::from_le_bytes(result.rom[jmp_imm_off..jmp_imm_off+4].try_into().unwrap());
assert_eq!(jmp_patched, module2_offset);
assert_eq!(jmp_patched, 0);
// Verify that the conditional JMP immediate was relocated similarly
// Verify that the conditional JMP immediate also remains function-relative (0)
let cjmp_abs_pc = module2_offset as usize + cjmp_pc as usize;
let cjmp_imm_off = cjmp_abs_pc + 2;
let cjmp_patched = u32::from_le_bytes(result.rom[cjmp_imm_off..cjmp_imm_off+4].try_into().unwrap());
assert_eq!(cjmp_patched, module2_offset);
assert_eq!(cjmp_patched, 0);
}
}