1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
//! Runtime compilation and execution
//!
//! Runtime code generation (JIT compilation) using ras,
//! with optional sandboxing for secure execution.
pub mod c_abi_dynamic;
pub mod compiler;
pub mod executor;
#[cfg(feature = "encoder")]
pub mod macro_helpers;
pub mod sandbox;
pub use compiler::RuntimeCompiler;
pub use executor::execute_jit_function;
#[cfg(feature = "encoder")]
pub use macro_helpers::compile_lir_internal;
pub use sandbox::{Sandbox, SandboxConfig};
use crate::error::LaminaError;
use crate::mir::Module as MirModule;
use lamina_platform::{TargetArchitecture, TargetOperatingSystem};
/// Runtime compilation result
pub struct RuntimeResult {
/// Executable memory containing compiled code
pub memory: ExecutableMemory,
/// Function pointer (unsafe - caller must ensure signature matches)
pub function_ptr: *const u8,
}
// Re-export ras types for convenience
pub use ras::{ExecutableMemory, RasRuntime};
/// Compile MIR module to executable memory using runtime compilation
pub fn compile_to_runtime(
_module: &MirModule,
_target_arch: TargetArchitecture,
_target_os: TargetOperatingSystem,
_function_name: Option<&str>,
) -> Result<RuntimeResult, LaminaError> {
#[cfg(feature = "encoder")]
{
use ras::assembler::RasAssembler;
crate::mir_codegen::validate_module_call_parameters(_module, _target_arch)?;
// Keep JIT output quiet by default (release-friendly). Enable with `LAMINA_JIT_DEBUG=1`.
let jit_debug = std::env::var_os("LAMINA_JIT_DEBUG").is_some();
let mut assembler = RasAssembler::new(_target_arch, _target_os).map_err(|e| {
LaminaError::ValidationError(format!("Failed to create assembler: {}", e))
})?;
// Always compile all functions (needed for internal function calls)
let (code, function_offsets) = assembler
.compile_mir_to_binary_function(_module, None)
.map_err(|e| {
LaminaError::ValidationError(format!("Runtime compilation failed: {}", e))
})?;
// Find the function offset for the requested function
let function_offset = if let Some(name) = _function_name {
let offset = function_offsets
.get::<str>(name)
.or_else(|| {
if let Some(stripped) = name.strip_prefix('@') {
function_offsets.get(stripped)
} else {
function_offsets.get(&format!("@{}", name))
}
})
.copied();
if jit_debug {
eprintln!(
"[JIT-DEBUG] Function '{}' offset: {:?}, available: {:?}",
name,
offset,
function_offsets.keys().collect::<Vec<_>>()
);
}
offset
} else {
// If no function name specified, use the first function (offset 0)
Some(0)
};
// Allocate writable memory
let mut memory = ExecutableMemory::allocate_writable(code.len()).map_err(|e| {
LaminaError::ValidationError(format!("Memory allocation failed: {}", e))
})?;
// Write code
memory
.write_code(&code)
.map_err(|e| LaminaError::ValidationError(format!("Failed to write code: {}", e)))?;
// Make executable
memory.make_executable().map_err(|e| {
LaminaError::ValidationError(format!("Failed to make memory executable: {}", e))
})?;
// Get function pointer, adjusting for function offset if specified
let base_ptr = memory.code_start();
let function_ptr = if let Some(offset) = function_offset {
// Ensure offset is 4-byte aligned for AArch64
#[cfg(target_arch = "aarch64")]
{
if offset % 4 != 0 {
return Err(LaminaError::ValidationError(format!(
"Function offset {} is not 4-byte aligned (required for AArch64)",
offset
)));
}
}
let adjusted = (base_ptr as usize + offset) as *const u8;
if jit_debug {
eprintln!(
"[JIT-DEBUG] Function pointer: base={:p}, offset={}, adjusted={:p}",
base_ptr, offset, adjusted
);
}
// Debug: Print first few instruction bytes at the function pointer
#[cfg(target_arch = "aarch64")]
{
if jit_debug {
unsafe {
let remaining = code.len().saturating_sub(offset);
let bytes =
std::slice::from_raw_parts(adjusted, std::cmp::min(128, remaining));
eprintln!(
"[JIT-DEBUG] First 32 bytes at function: {:02x?}",
bytes.iter().take(32).collect::<Vec<_>>()
);
// Check alignment
if !(adjusted as usize).is_multiple_of(4) {
eprintln!(
"[JIT-DEBUG][WARNING] Function pointer is not 4-byte aligned! Address: {:p}, alignment: {} bytes",
adjusted,
(adjusted as usize) % 4
);
} else {
eprintln!("[JIT-DEBUG] Function pointer is 4-byte aligned");
}
// Check last 4 bytes for RET instruction (should be c0 03 5f d6 for ret x30)
if bytes.len() >= 4 {
let last_4 = &bytes[bytes.len().saturating_sub(4)..];
eprintln!(
"[JIT-DEBUG] Last 4 bytes (RET instruction): {:02x?}",
last_4
);
let ret_inst =
u32::from_le_bytes([last_4[0], last_4[1], last_4[2], last_4[3]]);
eprintln!(
"[JIT-DEBUG] RET instruction value: 0x{:08x} (expected: 0xd65f03c0 for ret x30)",
ret_inst
);
}
// Decode first few instructions
eprintln!("[JIT-DEBUG] Decoding first 16 instructions (64 bytes):");
for i in 0..std::cmp::min(16, bytes.len() / 4) {
let inst_bytes = &bytes[i * 4..(i + 1) * 4];
let inst = u32::from_le_bytes([
inst_bytes[0],
inst_bytes[1],
inst_bytes[2],
inst_bytes[3],
]);
// Decode instruction type
let opcode = (inst >> 26) & 0x3F;
let opcode_top = (inst >> 28) & 0xF;
let bits_29_27 = (inst >> 27) & 0x7;
let bits_25_24 = (inst >> 24) & 0x3;
let inst_type = if (inst >> 25) & 0x7F == 0b1101011 {
// RET/BR: [31:25]=1101011, [24]=0, [23:21]=010
"RET/BR"
} else if opcode == 0b100101 {
"BL"
} else if opcode_top == 0b00 && (inst >> 27) & 0x1 == 1 {
// STP/LDP: [31:30]=00, [27]=1
if (inst >> 28) & 0x1 == 0 {
"STP"
} else {
"LDP"
}
} else if opcode_top == 0b00 && (inst >> 27) & 0x1 == 0 {
// LDP (post-index): [31:30]=00, [28]=1, [27]=0
if (inst >> 28) & 0x1 == 1 {
"LDP"
} else {
"STP"
}
} else if bits_29_27 == 0b010
&& (inst >> 23) & 0x3F == 0b100010
&& opcode_top != 0b00
{
// ADD/SUB (immediate): [29:27]=010, [28:23]=100010, but not LDP/STP
if (inst >> 30) & 0x1 == 0 {
"ADD(imm)"
} else {
"SUB(imm)"
}
} else if bits_29_27 == 0b001
&& (inst >> 23) & 0x3F == 0b010110
&& (inst >> 30) & 0x3 == 0b10
{
// ADD (register, shifted register): [31:30]=10, [29:27]=001, [28:24]=01011, [23:22]=00
// This is ADD with no shift
"ADD(reg)"
} else if bits_29_27 == 0b010
&& (inst >> 23) & 0x3F == 0b100010
&& (inst >> 30) & 0x3 == 0b10
{
// ADD/SUB (register, extended): [31:30]=10, [29:27]=010, [28:23]=100010
if (inst >> 30) & 0x1 == 0 {
"ADD(reg,ext)"
} else {
"SUB(reg,ext)"
}
} else if bits_29_27 == 0b010 && (inst >> 23) & 0x3F == 0b100101 {
// MOVZ/MOVK: [29:27]=010, [28:23]=100101
if (inst >> 21) & 0x3 == 0b00 {
"MOVZ"
} else {
"MOVK"
}
} else if bits_29_27 == 0b111 && (inst >> 26) & 0x1 == 0 {
// STR/LDR unscaled immediate: [29:27]=111, [26]=0
if bits_25_24 == 0b00 {
"STR(unscaled)"
} else if bits_25_24 == 0b01 {
"LDR(unscaled)"
} else {
"STR/LDR(scaled)"
}
} else if bits_29_27 == 0b001
&& (inst >> 23) & 0x3F == 0b010100
&& (inst >> 30) & 0x3 == 0b11
{
// EOR/XOR (register): [31:30]=11, [29:27]=001, [28:23]=010100
"EOR/XOR"
} else if (inst >> 31) & 0x1 == 1 && (inst >> 29) & 0x3 == 0b01 {
"MOV/ORR"
} else {
"UNKNOWN"
};
eprintln!(" [{}] 0x{:08x} ({})", i, inst, inst_type);
}
}
}
}
adjusted
} else {
if jit_debug {
eprintln!(
"[JIT-DEBUG] Function pointer: base={:p}, no offset",
base_ptr
);
}
base_ptr
};
Ok(RuntimeResult {
memory,
function_ptr,
})
}
#[cfg(not(feature = "encoder"))]
{
Err(LaminaError::ValidationError(
"Runtime compilation requires the 'encoder' feature to be enabled".to_string(),
))
}
}