lua_vm/dump.rs
1//! Pre-compiled Lua chunk serializer.
2//!
3//! Ported from `ldump.c`. Writes a `LuaProto` to a byte sink in the standard
4//! Lua 5.4 bytecode format.
5
6#[allow(unused_imports)]
7use crate::prelude::*;
8use std::collections::HashMap;
9use std::mem::size_of;
10
11use crate::state::LuaState;
12use lua_types::proto::LuaProto;
13use lua_types::{GcRef, LuaError, LuaString, LuaValue, LuaVersion};
14
15// ── Constants from lundump.h ─────────────────────────────────────────────────
16
17// dumpLiteral expands to dumpBlock(D, s, sizeof(s) - sizeof(char)).
18// sizeof("\x1bLua") = 5; minus 1 = 4 bytes, no NUL terminator.
19// b"\x1bLua" is &[u8; 4] in Rust — no NUL — so direct use is correct.
20const LUA_SIGNATURE: &[u8] = b"\x1bLua";
21
22// With LUA_VERSION_NUM = 504:
23// (504 / 100) * 16 + 504 % 100 = 5 * 16 + 4 = 84 = 0x54
24const LUA_VERSION_NUM_DUMP_54: i32 = 504;
25const LUAC_VERSION_54: u8 =
26 ((LUA_VERSION_NUM_DUMP_54 / 100) * 16 + LUA_VERSION_NUM_DUMP_54 % 100) as u8;
27const LUAC_VERSION_55: u8 = 0x55;
28
29const LUAC_FORMAT: u8 = 0;
30
31// sizeof("\x19\x93\r\n\x1a\n") = 7; minus 1 = 6 bytes written.
32// b"\x19\x93\r\n\x1a\n" is &[u8; 6].
33const LUAC_DATA: &[u8] = b"\x19\x93\r\n\x1a\n";
34
35const LUAC_INT: i64 = 0x5678;
36
37const LUAC_NUM: f64 = 370.5;
38
39const LUAC_INT_55: i64 = -0x5678;
40
41const LUAC_INST_55: u32 = 0x12345678;
42
43const LUAC_NUM_55: f64 = -370.5;
44
45const LUAC_VERSION_51: u8 = 0x51;
46
47const LUAC_VERSION_52: u8 = 0x52;
48
49const LUAC_VERSION_53: u8 = 0x53;
50
51/// Legacy (5.1/5.2/5.3) header byte: `sizeof(int)` = 4.
52const C_INT_SIZE: u8 = size_of::<i32>() as u8;
53
54/// Legacy (5.1/5.2/5.3) header byte: `sizeof(size_t)`, the build target's pointer width.
55const C_SIZET_SIZE: u8 = size_of::<usize>() as u8;
56
57/// Legacy (5.1/5.2) endianness flag: 1 = little-endian (the build target).
58const LUAC_ENDIAN_LITTLE: u8 = 1;
59
60/// Legacy (5.1/5.2) integral flag: 0 = `lua_Number` is floating-point.
61const LUAC_INTEGRAL_FLOAT: u8 = 0;
62
63const INSTRUCTION_SIZE: u8 = size_of::<u32>() as u8;
64
65const LUA_INTEGER_SIZE: u8 = size_of::<i64>() as u8;
66
67const LUA_NUMBER_SIZE: u8 = size_of::<f64>() as u8;
68
69// ── DumpState ────────────────────────────────────────────────────────────────
70
71/// Internal state threaded through every dump operation.
72///
73/// `lua_State *L` is removed — it was used only for `lua_lock`/`lua_unlock`, which are
74/// no-ops in the default Lua build and have no equivalent here. `void *data` is folded into
75/// the writer closure. `int status` is replaced by `Result<(), LuaError>` propagated with `?`.
76struct DumpState<'a> {
77 /// Byte-sink callback. C original: `lua_Writer writer` + `void *data` (combined)
78 /// into a bare byte-slice callback here.
79 writer: &'a mut dyn FnMut(&[u8]) -> Result<(), LuaError>,
80 /// When true, strip all debug information from the output.
81 strip: bool,
82 version: LuaVersion,
83 /// 5.5 only: each string already written, mapped to its 1-based index,
84 /// so a repeat is written as a reference (`ldump.c` `D->h`/`D->nstr`).
85 saved_strings: HashMap<Vec<u8>, usize>,
86}
87
88impl<'a> DumpState<'a> {
89 // ── Low-level write primitives ────────────────────────────────────────────
90
91 /// Write raw bytes to the output stream.
92 ///
93 /// C accumulates errors in `D->status` and skips subsequent writes once
94 /// non-zero; here, `Result<(), LuaError>` short-circuits via `?` instead.
95 /// `lua_lock`/`lua_unlock` are no-ops in the default build and have no
96 /// equivalent here.
97 fn dump_block(&mut self, data: &[u8]) -> Result<(), LuaError> {
98 if !data.is_empty() {
99 (self.writer)(data)?;
100 }
101 Ok(())
102 }
103
104 /// Write one byte.
105 ///
106 /// C body: `lu_byte x = (lu_byte)y; dumpVar(D, x);`
107 /// (`dumpVar(D,x)` expands to `dumpVector(D,&x,1)` expands to `dumpBlock(D,&x,sizeof(x))`)
108 fn dump_byte(&mut self, y: u8) -> Result<(), LuaError> {
109 self.dump_block(&[y])
110 }
111
112 /// Write a `size_t` using Lua's variable-length encoding.
113 ///
114 ///
115 /// Encoding (big-endian 7-bit groups, **last** byte marked with MSB = 1):
116 /// - Each byte holds 7 payload bits.
117 /// - Bytes are written most-significant group first.
118 /// - The final byte (least-significant group) has its MSB set as an end marker.
119 ///
120 /// This differs from standard LEB128, which marks the *continuation* bytes rather than
121 /// the terminating byte.
122 ///
123 fn dump_size(&mut self, mut x: usize) -> Result<(), LuaError> {
124 // DIBS = (usize::BITS + 6) / 7; on 64-bit = (64+6)/7 = 10.
125 const DIBS: usize = (usize::BITS as usize + 6) / 7;
126 let mut buff = [0u8; DIBS];
127 let mut n: usize = 0;
128
129 loop {
130 n += 1;
131 buff[DIBS - n] = (x & 0x7f) as u8; // fill buffer in reverse order
132 x >>= 7;
133 if x == 0 {
134 break;
135 }
136 }
137
138 // The byte at buff[DIBS-1] is the first byte placed (least-significant group).
139 // Setting its MSB marks it as the terminal byte of the encoding.
140 buff[DIBS - 1] |= 0x80;
141
142 self.dump_block(&buff[DIBS - n..])
143 }
144
145 /// Write an `int` as a variable-length size.
146 ///
147 /// C implicitly casts `int` → `size_t`. All call sites pass non-negative values
148 /// (line numbers, instruction counts, vector lengths); a debug assertion guards this.
149 fn dump_int(&mut self, x: i32) -> Result<(), LuaError> {
150 debug_assert!(
151 x >= 0,
152 "dump_int: negative value {} cast to usize would wrap",
153 x
154 );
155 self.dump_size(x as usize)
156 }
157
158 /// Write a `lua_Number` (f64) in the platform's native byte order.
159 ///
160 ///
161 /// `dumpVar(D,x)` expands to `dumpBlock(D, &x, sizeof(lua_Number))` — 8 bytes, native order.
162 /// `to_ne_bytes()` replicates native-endian serialisation. The bytecode header's `LUAC_NUM`
163 /// sentinel (370.5) lets `lundump` detect byte-order mismatches at load time.
164 fn dump_number(&mut self, x: f64) -> Result<(), LuaError> {
165 self.dump_block(&x.to_ne_bytes())
166 }
167
168 /// Write a `lua_Integer` (i64) in the platform's native byte order.
169 ///
170 fn dump_integer(&mut self, x: i64) -> Result<(), LuaError> {
171 self.dump_block(&x.to_ne_bytes())
172 }
173
174 fn dump_raw_i32(&mut self, x: i32) -> Result<(), LuaError> {
175 self.dump_block(&x.to_ne_bytes())
176 }
177
178 fn dump_raw_u32(&mut self, x: u32) -> Result<(), LuaError> {
179 self.dump_block(&x.to_ne_bytes())
180 }
181
182 // ── Mid-level serialisers ─────────────────────────────────────────────────
183
184 /// Write an interned or long string, or a null sentinel (encoded size = 0).
185 ///
186 /// Encoding: `dumpSize(len + 1)` followed by `len` raw bytes; size 0 means null/absent.
187 ///
188 /// 5.5 writes each distinct string once: a repeat, and the null sentinel,
189 /// are `dumpSize(0)` followed by the saved string's index (0 for null).
190 fn dump_string(&mut self, s: Option<&GcRef<LuaString>>) -> Result<(), LuaError> {
191 if self.version == LuaVersion::V55 {
192 return self.dump_string_55(s);
193 }
194 match s {
195 None => self.dump_size(0),
196
197 Some(s) => {
198 let bytes = s.as_bytes(); // tsslen → .len(); getstr → .as_bytes()
199 self.dump_size(bytes.len() + 1)?;
200 self.dump_block(bytes)
201 }
202 }
203 }
204
205 fn dump_string_55(&mut self, s: Option<&GcRef<LuaString>>) -> Result<(), LuaError> {
206 let Some(s) = s else {
207 self.dump_size(0)?;
208 return self.dump_size(0);
209 };
210 let bytes = s.as_bytes();
211 if let Some(&idx) = self.saved_strings.get(bytes) {
212 self.dump_size(0)?;
213 return self.dump_size(idx);
214 }
215 self.dump_size(bytes.len() + 1)?;
216 self.dump_block(bytes)?;
217 let idx = self.saved_strings.len() + 1;
218 self.saved_strings.insert(bytes.to_vec(), idx);
219 Ok(())
220 }
221
222 /// Write the bytecode instruction array.
223 ///
224 /// `f->sizecode` has no counterpart here — `Vec::len()` covers it.
225 fn dump_code(&mut self, proto: &LuaProto) -> Result<(), LuaError> {
226 self.dump_int(proto.code.len() as i32)?;
227
228 // dumpVector writes n * sizeof(Instruction) = n * 4 bytes in native byte order.
229 for instr in &proto.code {
230 self.dump_block(&instr.0.to_ne_bytes())?;
231 }
232 Ok(())
233 }
234
235 /// Write the constant pool.
236 ///
237 /// Each constant is written as: one tag byte (`ttypetag`), followed by the payload
238 /// (float: 8 bytes; integer: 8 bytes; string: variable-length; nil/bool: nothing).
239 ///
240 /// `f->sizek` has no counterpart here — `Vec::len()` covers it.
241 fn dump_constants(&mut self, proto: &LuaProto) -> Result<(), LuaError> {
242 let n = proto.k.len();
243 self.dump_int(n as i32)?;
244
245 for constant in &proto.k {
246 // Returns the C-side tag byte: bits 0-3 base type, bits 4-5 variant, bit 6 collectable.
247 let tag = constant.full_type_tag();
248 self.dump_byte(tag)?;
249
250 match constant {
251 LuaValue::Float(f) => {
252 self.dump_number(*f)?;
253 }
254 LuaValue::Int(i) => {
255 self.dump_integer(*i)?;
256 }
257 LuaValue::Str(s) => {
258 self.dump_string(Some(s))?;
259 }
260 LuaValue::Nil | LuaValue::Bool(_) => {
261 // Only the tag byte is written; nil and booleans carry no additional payload.
262 debug_assert!(
263 matches!(constant, LuaValue::Nil | LuaValue::Bool(_)),
264 "dump_constants: default branch reached for unexpected variant"
265 );
266 }
267 _ => {
268 // In C the default branch asserts nil/false/true only. Any
269 // other variant here indicates a malformed proto.
270 debug_assert!(
271 false,
272 "dump_constants: unexpected LuaValue variant in constant pool"
273 );
274 }
275 }
276 }
277 Ok(())
278 }
279
280 /// Write nested function prototypes (sub-functions defined inside `proto`).
281 ///
282 ///
283 /// `f->sizep` has no counterpart here — `Vec::len()` covers it.
284 /// The parent's source string is passed down so that children with identical source
285 /// origins can omit the redundant source name (see `dump_function`).
286 fn dump_protos(&mut self, proto: &LuaProto) -> Result<(), LuaError> {
287 let n = proto.p.len();
288 self.dump_int(n as i32)?;
289
290 for sub in &proto.p {
291 // sub: &GcRef<LuaProto>; deref coercion (&GcRef<LuaProto> → &LuaProto)
292 // applies since GcRef<T>: Deref<Target=T>.
293 self.dump_function(sub, proto.source.as_ref())?;
294 }
295 Ok(())
296 }
297
298 /// Write upvalue descriptors (instack / idx / kind for each upvalue slot).
299 ///
300 /// `f->sizeupvalues` has no counterpart here — `Vec::len()` covers it.
301 /// `Upvaldesc.instack` is `bool` here; cast to `u8` for the wire format.
302 fn dump_upvalues(&mut self, proto: &LuaProto) -> Result<(), LuaError> {
303 let n = proto.upvalues.len();
304 self.dump_int(n as i32)?;
305
306 for upval in &proto.upvalues {
307 self.dump_byte(upval.instack as u8)?;
308 self.dump_byte(upval.idx)?;
309 self.dump_byte(upval.kind)?;
310 }
311 Ok(())
312 }
313
314 /// Write debug information: per-instruction line deltas, absolute line records,
315 /// local-variable lifetimes, and upvalue names.
316 ///
317 /// All counts are written as zero when `self.strip` is true.
318 ///
319 /// All `f->size*` fields have no counterpart here — `Vec::len()` covers them.
320 fn dump_debug(&mut self, proto: &LuaProto) -> Result<(), LuaError> {
321 let n_lineinfo = if self.strip { 0 } else { proto.lineinfo.len() };
322 self.dump_int(n_lineinfo as i32)?;
323
324 // lineinfo is Vec<i8> (ls_byte in C). C writes them as raw bytes (sizeof(i8)=1).
325 // Cast each i8 to u8 (same bit pattern) before writing.
326 let lineinfo_bytes: Vec<u8> = proto.lineinfo[..n_lineinfo]
327 .iter()
328 .map(|&b| b as u8)
329 .collect();
330 self.dump_block(&lineinfo_bytes)?;
331
332 let n_absline = if self.strip {
333 0
334 } else {
335 proto.abslineinfo.len()
336 };
337 self.dump_int(n_absline as i32)?;
338
339 for abs in proto.abslineinfo.iter().take(n_absline) {
340 // AbsLineInfo.pc and .line are i32; non-negative in valid bytecode.
341 self.dump_int(abs.pc)?;
342 self.dump_int(abs.line)?;
343 }
344
345 let n_locvars = if self.strip { 0 } else { proto.locvars.len() };
346 self.dump_int(n_locvars as i32)?;
347
348 for locvar in proto.locvars.iter().take(n_locvars) {
349 self.dump_string(Some(&locvar.varname))?;
350 self.dump_int(locvar.startpc)?;
351 self.dump_int(locvar.endpc)?;
352 }
353
354 // (Re-uses upvalues.len() for the name-writing pass — separate from dumpUpvalues
355 // which wrote structural descriptors; here we write debug names.)
356 let n_upval_names = if self.strip { 0 } else { proto.upvalues.len() };
357 self.dump_int(n_upval_names as i32)?;
358
359 for upval in proto.upvalues.iter().take(n_upval_names) {
360 // C's `TString *name` can be NULL when an upvalue is unnamed (e.g.
361 // in bytecode compiled without debug info); `UpvalDesc.name` here
362 // is `Option<GcRef<LuaString>>` for the same reason.
363 self.dump_string(upval.name.as_ref())?;
364 }
365 Ok(())
366 }
367
368 /// Write a complete function prototype: source name, header bytes, code, constants,
369 /// upvalue descriptors, nested prototypes, and debug information.
370 ///
371 /// `psource` is the parent function's source string. When `f->source == psource` (pointer
372 /// equality — Lua interns short strings so identical source names share an object), the
373 /// source is written as null (size 0) to avoid duplication. The top-level call passes
374 /// `None` to force writing the source.
375 ///
376 /// `f->source == psource` is a C pointer comparison exploiting string interning;
377 /// here `GcRef::ptr_eq` gives the same identity check. `is_vararg` is `bool`
378 /// here; cast to `u8` for the wire format.
379 fn dump_function(
380 &mut self,
381 proto: &LuaProto,
382 psource: Option<&GcRef<LuaString>>,
383 ) -> Result<(), LuaError> {
384 // Pointer-equality check: same interned string object means same source file.
385 let same_source = match (psource, proto.source.as_ref()) {
386 (Some(ps), Some(src)) => GcRef::ptr_eq(src, ps),
387 _ => false,
388 };
389
390 if self.strip || same_source {
391 self.dump_string(None)?;
392 } else {
393 self.dump_string(proto.source.as_ref())?;
394 }
395
396 self.dump_int(proto.linedefined)?;
397 self.dump_int(proto.lastlinedefined)?;
398 self.dump_byte(proto.numparams)?;
399 self.dump_byte(proto.is_vararg as u8)?;
400 self.dump_byte(proto.maxstacksize)?;
401
402 self.dump_code(proto)?;
403 self.dump_constants(proto)?;
404 self.dump_upvalues(proto)?;
405 self.dump_protos(proto)?;
406 self.dump_debug(proto)?;
407 Ok(())
408 }
409
410 /// Write the binary chunk header.
411 ///
412 /// The header allows `lundump` (and external tools) to verify the bytecode format,
413 /// platform word sizes, and byte order before attempting to load the chunk.
414 ///
415 fn dump_header(&mut self) -> Result<(), LuaError> {
416 // dumpLiteral(D,s) = dumpBlock(D, s, sizeof(s) - sizeof(char))
417 // b"\x1bLua" is &[u8; 4] (no NUL terminator in Rust byte literals), matching the
418 // C expansion of sizeof("\x1bLua")-1 = 4 bytes.
419 self.dump_block(LUA_SIGNATURE)?;
420
421 match self.version {
422 LuaVersion::V51 => {
423 self.dump_byte(LUAC_VERSION_51)?;
424 self.dump_byte(LUAC_FORMAT)?;
425 self.dump_byte(LUAC_ENDIAN_LITTLE)?;
426 self.dump_byte(C_INT_SIZE)?;
427 self.dump_byte(C_SIZET_SIZE)?;
428 self.dump_byte(INSTRUCTION_SIZE)?;
429 self.dump_byte(LUA_NUMBER_SIZE)?;
430 self.dump_byte(LUAC_INTEGRAL_FLOAT)?;
431 }
432 LuaVersion::V52 => {
433 self.dump_byte(LUAC_VERSION_52)?;
434 self.dump_byte(LUAC_FORMAT)?;
435 self.dump_byte(LUAC_ENDIAN_LITTLE)?;
436 self.dump_byte(C_INT_SIZE)?;
437 self.dump_byte(C_SIZET_SIZE)?;
438 self.dump_byte(INSTRUCTION_SIZE)?;
439 self.dump_byte(LUA_NUMBER_SIZE)?;
440 self.dump_byte(LUAC_INTEGRAL_FLOAT)?;
441 self.dump_block(LUAC_DATA)?;
442 }
443 LuaVersion::V53 => {
444 self.dump_byte(LUAC_VERSION_53)?;
445 self.dump_byte(LUAC_FORMAT)?;
446 self.dump_block(LUAC_DATA)?;
447 self.dump_byte(C_INT_SIZE)?;
448 self.dump_byte(C_SIZET_SIZE)?;
449 self.dump_byte(INSTRUCTION_SIZE)?;
450 self.dump_byte(LUA_INTEGER_SIZE)?;
451 self.dump_byte(LUA_NUMBER_SIZE)?;
452 self.dump_integer(LUAC_INT)?;
453 self.dump_number(LUAC_NUM)?;
454 }
455 LuaVersion::V55 => {
456 self.dump_byte(LUAC_VERSION_55)?;
457 self.dump_byte(LUAC_FORMAT)?;
458 self.dump_block(LUAC_DATA)?;
459 self.dump_byte(size_of::<i32>() as u8)?;
460 self.dump_raw_i32(LUAC_INT_55 as i32)?;
461
462 self.dump_byte(INSTRUCTION_SIZE)?;
463 self.dump_raw_u32(LUAC_INST_55)?;
464
465 self.dump_byte(LUA_INTEGER_SIZE)?;
466 self.dump_integer(LUAC_INT_55)?;
467
468 self.dump_byte(LUA_NUMBER_SIZE)?;
469 self.dump_number(LUAC_NUM_55)?;
470 }
471 _ => {
472 self.dump_byte(LUAC_VERSION_54)?;
473 self.dump_byte(LUAC_FORMAT)?;
474 self.dump_block(LUAC_DATA)?;
475 self.dump_byte(INSTRUCTION_SIZE)?;
476 self.dump_byte(LUA_INTEGER_SIZE)?;
477 self.dump_byte(LUA_NUMBER_SIZE)?;
478 self.dump_integer(LUAC_INT)?;
479 self.dump_number(LUAC_NUM)?;
480 }
481 }
482
483 Ok(())
484 }
485}
486
487// ── Public entry point ───────────────────────────────────────────────────────
488
489/// Serialize a compiled Lua function prototype as a precompiled bytecode chunk.
490///
491/// The `writer` callback receives successive slices of the serialised bytes and returns
492/// `Err(LuaError)` to abort. `strip` omits debug info (line numbers, local names, etc.)
493/// from the output.
494///
495/// C's `lua_Writer w` (fn pointer) + `void *data` (userdata) are collapsed
496/// into a single `impl FnMut(&[u8]) -> Result<(), LuaError>` closure here —
497/// the callback + context pair. Return type changes from `int` (0 = ok,
498/// non-zero = writer error) to `Result<(), LuaError>`.
499pub(crate) fn dump(
500 state: &LuaState,
501 proto: &GcRef<LuaProto>,
502 writer: &mut dyn FnMut(&[u8]) -> Result<(), LuaError>,
503 strip: bool,
504) -> Result<(), LuaError> {
505 let mut d = DumpState {
506 writer,
507 strip,
508 version: state.global().lua_version,
509 saved_strings: HashMap::new(),
510 };
511
512 d.dump_header()?;
513
514 // f->sizeupvalues has no counterpart here — Vec::len() covers it, and is
515 // bounded by MAXUPVAL = 255, so truncation via `as u8` is safe for
516 // well-formed prototypes.
517 d.dump_byte(proto.upvalues.len() as u8)?;
518
519 // psource = None forces the top-level function to always write its source name.
520 // Deref coercion: &GcRef<LuaProto> → &LuaProto (via Deref<Target=LuaProto> on GcRef/Rc).
521 d.dump_function(proto, None)?;
522
523 Ok(())
524}