Skip to main content

lua_vm/
undump.rs

1//! Load precompiled Lua chunks.
2//!
3//! The binary chunk format matches the reference C implementation
4//! (`lundump.c`/`lundump.h`) byte-for-byte, so `string.dump` output and
5//! precompiled chunks stay interchangeable with stock Lua.
6//!
7//! The public entry point is [`undump`], which reads a binary Lua chunk from
8//! a [`ZIO`] stream and returns a Lua closure ready to call.
9
10#[allow(unused_imports)]
11use crate::prelude::*;
12use crate::state::LuaState;
13use crate::zio::ZIO;
14use lua_types::error::LuaError;
15use lua_types::value::LuaValue;
16
17use lua_types::closure::LuaLClosure;
18use lua_types::gc::GcRef;
19use lua_types::opcode::Instruction;
20use lua_types::proto::{AbsLineInfo, LocalVar, LuaProto, UpvalDesc};
21use lua_types::string::LuaString;
22use lua_types::LuaVersion;
23
24// ── Constants (from lundump.h) ─────────────────────────────────────────────
25
26/// Six-byte data marker in the chunk header used to catch conversion errors.
27const LUAC_DATA: &[u8] = b"\x19\x93\r\n\x1a\n";
28
29/// Reference integer written in the header to detect integer endianness/size
30/// mismatches.
31const LUAC_INT: i64 = 0x5678;
32
33/// Reference float written in the header to detect float format mismatches.
34const LUAC_NUM: f64 = 370.5;
35
36const LUAC_INT_55: i64 = -0x5678;
37
38const LUAC_INST_55: u32 = 0x12345678;
39
40const LUAC_NUM_55: f64 = -370.5;
41
42// LUA_VERSION_NUM = 504 → ((5 * 16) + 4) = 0x54 = 84
43/// One-byte version tag: upper nibble = major, lower nibble = minor.
44const LUAC_VERSION_51: u8 = 0x51;
45const LUAC_VERSION_52: u8 = 0x52;
46const LUAC_VERSION_53: u8 = 0x53;
47const LUAC_VERSION_54: u8 = 0x54;
48const LUAC_VERSION_55: u8 = 0x55;
49
50const LUAC_FORMAT: u8 = 0;
51
52const LUA_SIGNATURE: &[u8] = b"\x1bLua";
53
54const MAX_SHORT_LEN: usize = 40;
55
56// ── Constant-pool type tags (from lobject.h makevariant) ───────────────────
57//
58// These are the byte values written by ldump.c into the constants array.
59// makevariant(t, v) = t | (v << 4).
60//
61// The byte values used in the binary format are the raw tag integers from
62// lobject.h, distinct from LuaValue's variant tags. Defined here as u8
63// constants so the match in load_constants is self-documenting.
64
65const TAG_NIL: u8 = 0x00;
66const TAG_FALSE: u8 = 0x01;
67const TAG_TRUE: u8 = 0x11;
68const TAG_INT: u8 = 0x03;
69const TAG_FLOAT: u8 = 0x13;
70const TAG_SHORT_STR: u8 = 0x04;
71const TAG_LONG_STR: u8 = 0x14;
72
73// ── LoadState ──────────────────────────────────────────────────────────────
74
75/// Loader state bundled for convenience: Lua state, input stream, and the
76/// chunk name used in error messages.
77///
78/// Always stack-allocated inside [`undump`] and never escapes the call.
79struct LoadState<'a> {
80    state: &'a mut LuaState,
81    z: &'a mut ZIO,
82    /// 5.5 only: strings loaded so far, in order, for back-references
83    /// (`lundump.c` `S->h`/`S->nstr`).
84    saved_strings: Vec<GcRef<LuaString>>,
85}
86
87// ── Error helper ───────────────────────────────────────────────────────────
88
89/// Build a syntax error for a malformed binary chunk.
90///
91/// Returns a `LuaError` for the caller to propagate with `?`, rather than
92/// throwing via `longjmp` as the C reference does.
93fn load_error(_s: &LoadState<'_>, why: &'static str) -> LuaError {
94    LuaError::syntax(format_args!("bad binary format ({})", why))
95}
96
97// ── Low-level I/O ──────────────────────────────────────────────────────────
98
99/// Read exactly `buf.len()` bytes from the stream into `buf`.
100///
101/// `ZIO::read` returns the number of bytes NOT read (0 = success).
102fn load_block(s: &mut LoadState<'_>, buf: &mut [u8]) -> Result<(), LuaError> {
103    if s.z.read(s.state, buf)? != 0 {
104        return Err(load_error(s, "truncated chunk"));
105    }
106    Ok(())
107}
108
109/// Read a single byte from the stream.
110fn load_byte(s: &mut LoadState<'_>) -> Result<u8, LuaError> {
111    let b = s.z.getc(s.state)?;
112    if b == crate::zio::EOZ {
113        return Err(load_error(s, "truncated chunk"));
114    }
115    Ok(b as u8)
116}
117
118/// Read a variable-length unsigned integer (7 bits per byte, big-endian,
119/// MSB-first continuation flag).
120///
121/// The encoding terminates when a byte with the high bit set is seen (the
122/// *last* byte has bit 7 = 1) — the opposite of the more common LEB128, where
123/// the continuation bit means "more follows".
124fn load_unsigned(s: &mut LoadState<'_>, limit: usize) -> Result<usize, LuaError> {
125    let mut x: usize = 0;
126    let limit = limit >> 7;
127    loop {
128        let b = load_byte(s)? as usize;
129        if x >= limit {
130            return Err(load_error(s, "integer overflow"));
131        }
132        x = (x << 7) | (b & 0x7f);
133        if (b & 0x80) != 0 {
134            break;
135        }
136    }
137    Ok(x)
138}
139
140/// Read a `size_t`-sized unsigned value.
141fn load_size(s: &mut LoadState<'_>) -> Result<usize, LuaError> {
142    load_unsigned(s, usize::MAX)
143}
144
145/// Read a signed `int`-sized value.
146fn load_int(s: &mut LoadState<'_>) -> Result<i32, LuaError> {
147    let v = load_unsigned(s, i32::MAX as usize)?;
148    Ok(v as i32)
149}
150
151/// Read a `lua_Number` (f64) as eight raw native-endian bytes.
152///
153/// The binary format is host-endian for these fields; the header check
154/// verifies endianness compatibility via the `LUAC_INT` and `LUAC_NUM`
155/// sentinels.
156fn load_number(s: &mut LoadState<'_>) -> Result<f64, LuaError> {
157    let mut buf = [0u8; 8];
158    load_block(s, &mut buf)?;
159    Ok(f64::from_ne_bytes(buf))
160}
161
162/// Read a `lua_Integer` (i64) as eight raw native-endian bytes. Same
163/// endianness reasoning as [`load_number`].
164fn load_integer(s: &mut LoadState<'_>) -> Result<i64, LuaError> {
165    let mut buf = [0u8; 8];
166    load_block(s, &mut buf)?;
167    Ok(i64::from_ne_bytes(buf))
168}
169
170fn load_raw_i32(s: &mut LoadState<'_>) -> Result<i32, LuaError> {
171    let mut buf = [0u8; 4];
172    load_block(s, &mut buf)?;
173    Ok(i32::from_ne_bytes(buf))
174}
175
176fn load_raw_u32(s: &mut LoadState<'_>) -> Result<u32, LuaError> {
177    let mut buf = [0u8; 4];
178    load_block(s, &mut buf)?;
179    Ok(u32::from_ne_bytes(buf))
180}
181
182// ── String loading ─────────────────────────────────────────────────────────
183
184/// Load a nullable string.  Returns `None` if the stored size is zero.
185///
186/// The Lua binary format stores `actual_length + 1` so that size=0 is the
187/// null-string sentinel. After reading `raw_size`, the actual byte count is
188/// `raw_size - 1`.
189///
190/// Long strings are interned through the same `intern_str` path as short
191/// strings; C creates long strings directly via `luaS_createlngstrobj`
192/// without interning them.
193///
194/// The `_proto` parameter corresponds to C's `Proto *p`, used there only for
195/// the `luaC_objbarrier(L, p, ts)` write barrier. That barrier is not invoked
196/// here.
197fn load_string_n(
198    s: &mut LoadState<'_>,
199    _proto: &LuaProto,
200) -> Result<Option<GcRef<LuaString>>, LuaError> {
201    let v55 = s.state.global().lua_version == LuaVersion::V55;
202    let raw_size = load_size(s)?;
203    if raw_size == 0 {
204        if !v55 {
205            return Ok(None);
206        }
207        let idx = load_size(s)?;
208        if idx == 0 {
209            return Ok(None);
210        }
211        return match s.saved_strings.get(idx - 1) {
212            Some(ts) => Ok(Some(ts.clone())),
213            None => Err(load_error(s, "invalid string index")),
214        };
215    }
216    let size = raw_size - 1;
217
218    // Read the raw bytes regardless of short/long distinction.
219    let mut buf = vec![0u8; size];
220
221    if size <= MAX_SHORT_LEN {
222        load_block(s, &mut buf)?;
223    } else {
224        load_block(s, &mut buf)?;
225    }
226
227    let ts = s.state.intern_str(&buf)?;
228    if v55 {
229        s.saved_strings.push(ts.clone());
230    }
231
232    Ok(Some(ts))
233}
234
235/// Load a non-nullable string; error if the stream encodes a null string.
236fn load_string(s: &mut LoadState<'_>, proto: &LuaProto) -> Result<GcRef<LuaString>, LuaError> {
237    match load_string_n(s, proto)? {
238        Some(ts) => Ok(ts),
239        None => Err(load_error(s, "bad format for constant string")),
240    }
241}
242
243// ── Proto-field loaders ────────────────────────────────────────────────────
244
245/// Load the bytecode instruction array into a prototype.
246///
247/// Reads `n` raw 4-byte words in native-endian order, consistent with how
248/// [`load_number`] and [`load_integer`] work.
249fn load_code(s: &mut LoadState<'_>, f: &mut LuaProto) -> Result<(), LuaError> {
250    let n = load_int(s)? as usize;
251    let mut code = Vec::with_capacity(n);
252    for _ in 0..n {
253        let mut buf = [0u8; 4];
254        load_block(s, &mut buf)?;
255        code.push(Instruction(u32::from_ne_bytes(buf)));
256    }
257    f.code = code;
258    Ok(())
259}
260
261/// Load the constant pool into a prototype.
262///
263/// Reads the tag byte for each constant, then its payload if any.
264fn load_constants(s: &mut LoadState<'_>, f: &mut LuaProto) -> Result<(), LuaError> {
265    let n = load_int(s)? as usize;
266    let mut k = Vec::with_capacity(n);
267
268    for _ in 0..n {
269        let t = load_byte(s)?;
270        let val = match t {
271            TAG_NIL => LuaValue::Nil,
272            TAG_FALSE => LuaValue::Bool(false),
273            TAG_TRUE => LuaValue::Bool(true),
274            TAG_FLOAT => LuaValue::Float(load_number(s)?),
275            TAG_INT => LuaValue::Int(load_integer(s)?),
276
277            TAG_SHORT_STR | TAG_LONG_STR => {
278                let ts = load_string(s, f)?;
279                LuaValue::Str(ts)
280            }
281
282            _ => {
283                debug_assert!(false, "unknown constant type tag {:#04x}", t);
284                LuaValue::Nil
285            }
286        };
287        k.push(val);
288    }
289
290    f.k = k;
291    Ok(())
292}
293
294/// Load nested function prototypes into a prototype.
295///
296/// C creates the proto first, as a GC anchor, then fills it. Here a default
297/// `LuaProto` is built, filled, then wrapped in a `GcRef`.
298fn load_protos(s: &mut LoadState<'_>, f: &mut LuaProto) -> Result<(), LuaError> {
299    let n = load_int(s)? as usize;
300    let mut protos = Vec::with_capacity(n);
301
302    for _ in 0..n {
303        let mut sub = LuaProto::placeholder();
304
305        // Pass parent source as fallback.
306        let parent_source = f.source.clone();
307        load_function(s, &mut sub, parent_source)?;
308
309        // A `LuaProto` is populated field-by-field through a `&mut` local and
310        // then wrapped, because `GcRef` exposes only `Deref` (no `DerefMut`):
311        // the canonical `state.new_proto()` would hand back a placeholder that
312        // cannot be filled in place. The direct `GcRef::new` path is kept for
313        // that reason, but `mark_gc_check_needed` is invoked here so a
314        // precompiled-chunk load registers its allocations with the collector
315        // exactly as `state.new_proto()` would (issue #276).
316        s.state.mark_gc_check_needed();
317        let sub_ref = GcRef::new(sub);
318        sub_ref.account_buffer(sub_ref.buffer_bytes() as isize);
319        protos.push(sub_ref);
320    }
321
322    f.p = protos;
323    Ok(())
324}
325
326/// Load upvalue descriptors into a prototype.
327///
328/// C fills upvalue names first (`NULL`) for GC safety, then names are
329/// attached separately. Here `UpvalDesc` values are built with `name: None`
330/// and filled in later by [`load_debug`], which is why `UpvalDesc.name` is
331/// `Option<GcRef<LuaString>>` rather than a bare `GcRef<LuaString>`.
332fn load_upvalues(s: &mut LoadState<'_>, f: &mut LuaProto) -> Result<(), LuaError> {
333    let n = load_int(s)? as usize;
334
335    let mut upvalues = Vec::with_capacity(n);
336    for _ in 0..n {
337        let instack_raw = load_byte(s)?;
338        let idx = load_byte(s)?;
339        let kind = load_byte(s)?;
340
341        upvalues.push(UpvalDesc {
342            name: None, // filled by load_debug
343            instack: instack_raw != 0,
344            idx,
345            kind,
346        });
347    }
348
349    f.upvalues = upvalues;
350    Ok(())
351}
352
353/// Load debug information into a prototype.
354///
355/// `lineinfo` is `ls_byte` (a signed byte) in C; each byte is read as `u8`
356/// then cast to `i8`, which is safe since the two share the same in-memory
357/// representation. `LocalVar.varname` and `UpvalDesc.name` are both
358/// `Option<GcRef<LuaString>>` here because `loadStringN` can return `None`;
359/// see also the note on [`load_upvalues`].
360fn load_debug(s: &mut LoadState<'_>, f: &mut LuaProto) -> Result<(), LuaError> {
361    let n = load_int(s)? as usize;
362    let mut lineinfo = vec![0i8; n];
363    for item in lineinfo.iter_mut() {
364        *item = load_byte(s)? as i8;
365    }
366    f.lineinfo = lineinfo;
367
368    let n = load_int(s)? as usize;
369    let mut abslineinfo = Vec::with_capacity(n);
370    for _ in 0..n {
371        abslineinfo.push(AbsLineInfo {
372            pc: load_int(s)?,
373            line: load_int(s)?,
374        });
375    }
376    f.abslineinfo = abslineinfo;
377
378    let n = load_int(s)? as usize;
379
380    let mut locvars = Vec::with_capacity(n);
381    for _ in 0..n {
382        let varname = load_string_n(s, f)?;
383        let startpc = load_int(s)?;
384        let endpc = load_int(s)?;
385        let varname = match varname {
386            Some(v) => v,
387            None => s.state.new_string(b"")?,
388        };
389        locvars.push(LocalVar {
390            varname,
391            startpc,
392            endpc,
393        });
394    }
395    f.locvars = locvars;
396
397    // If n == 0 there is no upvalue name info (stripped).
398    let has_names = load_int(s)?;
399    if has_names != 0 {
400        let n_upvals = f.upvalues.len();
401        for i in 0..n_upvals {
402            let name = load_string_n(s, f)?;
403            f.upvalues[i].name = name;
404        }
405    }
406
407    Ok(())
408}
409
410// ── Function loader ────────────────────────────────────────────────────────
411
412/// Load a complete function prototype from the stream.
413///
414/// `psource` is `None` at the top level; a nested prototype with no source of
415/// its own inherits the parent's, expressed here by falling back to
416/// `psource` when `loadStringN` returns `None`.
417fn load_function(
418    s: &mut LoadState<'_>,
419    f: &mut LuaProto,
420    psource: Option<GcRef<LuaString>>,
421) -> Result<(), LuaError> {
422    let source = load_string_n(s, f)?;
423    f.source = source.or(psource);
424
425    f.linedefined = load_int(s)?;
426    f.lastlinedefined = load_int(s)?;
427    f.numparams = load_byte(s)?;
428    f.is_vararg = load_byte(s)? != 0;
429    f.maxstacksize = load_byte(s)?;
430    load_code(s, f)?;
431    reconstruct_vararg_table_reg(f);
432    load_constants(s, f)?;
433    load_upvalues(s, f)?;
434    load_protos(s, f)?;
435    load_debug(s, f)?;
436
437    Ok(())
438}
439
440/// Recover `LuaProto.vararg_table_reg` from the loaded bytecode instead of from
441/// the wire format, so a precompiled chunk keeps Lua 5.5 named-vararg aliasing
442/// (`function f(...t)`) without lua-rs's `string.dump` output diverging from
443/// C's bytecode layout (which the structural oracle compares).
444///
445/// A named-vararg function emits exactly one `OP_VARARGPACK` (opcode 84) at
446/// entry; its A operand is the register holding the shared vararg table. Its
447/// k bit records whether the table must be materialized.
448fn reconstruct_vararg_table_reg(f: &mut LuaProto) {
449    const OP_VARARGPACK: u32 = 84;
450    const OPCODE_MASK: u32 = 0x7F;
451    const POS_K: u32 = 15;
452    if let Some((reg, needed)) = f.code.iter().find_map(|inst| {
453        let raw = inst.raw();
454        (raw & OPCODE_MASK == OP_VARARGPACK).then(|| {
455            let reg = ((raw >> 7) & 0xFF) as u8;
456            let needed = ((raw >> POS_K) & 1) != 0;
457            (reg, needed)
458        })
459    }) {
460        f.vararg_table_reg = Some(reg);
461        f.vararg_table_needed = needed;
462    }
463}
464
465// ── Header validation ──────────────────────────────────────────────────────
466
467/// Verify that the next `expected.len()` bytes in the stream match `expected`.
468fn check_literal(
469    s: &mut LoadState<'_>,
470    expected: &[u8],
471    msg: &'static str,
472) -> Result<(), LuaError> {
473    let mut buf = vec![0u8; expected.len()];
474    load_block(s, &mut buf)?;
475    if buf != expected {
476        return Err(load_error(s, msg));
477    }
478    Ok(())
479}
480
481/// Verify that the next byte in the stream equals `expected_size`. `tname` is
482/// always a Rust type-name string literal (ASCII) from the call sites.
483fn fcheck_size(
484    s: &mut LoadState<'_>,
485    expected_size: usize,
486    tname: &'static str,
487) -> Result<(), LuaError> {
488    let b = load_byte(s)? as usize;
489    if b != expected_size {
490        return Err(LuaError::syntax(format_args!("{} size mismatch", tname)));
491    }
492    Ok(())
493}
494
495/// Validate the binary chunk header.
496///
497/// The three fixed-size checks below cover `Instruction` (4 bytes, u32),
498/// `lua_Integer` (8 bytes, i64), and `lua_Number` (8 bytes, f64).
499///
500/// The first byte of `LUA_SIGNATURE` (`\x1b`) is already consumed by the
501/// caller before `check_header` is invoked, so only bytes 1.. of the
502/// signature (`"Lua"`) are checked here.
503fn check_header(s: &mut LoadState<'_>) -> Result<(), LuaError> {
504    // Skip LUA_SIGNATURE[0] (\x1b) — already consumed by the caller.
505    check_literal(s, &LUA_SIGNATURE[1..], "not a binary chunk")?;
506
507    let version = s.state.global().lua_version;
508    let expected_version = match version {
509        LuaVersion::V51 => LUAC_VERSION_51,
510        LuaVersion::V52 => LUAC_VERSION_52,
511        LuaVersion::V53 => LUAC_VERSION_53,
512        LuaVersion::V55 => LUAC_VERSION_55,
513        _ => LUAC_VERSION_54,
514    };
515    let ver = load_byte(s)?;
516    if ver != expected_version {
517        return Err(load_error(s, "version mismatch"));
518    }
519
520    let fmt = load_byte(s)?;
521    if fmt != LUAC_FORMAT {
522        return Err(load_error(s, "format mismatch"));
523    }
524
525    match version {
526        LuaVersion::V51 => {
527            check_legacy_sizes(s)?;
528        }
529        LuaVersion::V52 => {
530            check_legacy_sizes(s)?;
531            check_literal(s, LUAC_DATA, "corrupted chunk")?;
532        }
533        LuaVersion::V53 => {
534            check_literal(s, LUAC_DATA, "corrupted chunk")?;
535            fcheck_size(s, size_of::<i32>(), "int")?;
536            fcheck_size(s, size_of::<usize>(), "size_t")?;
537            fcheck_size(s, 4, "Instruction")?;
538            fcheck_size(s, 8, "lua_Integer")?;
539            fcheck_size(s, 8, "lua_Number")?;
540            if load_integer(s)? != LUAC_INT {
541                return Err(load_error(s, "integer format mismatch"));
542            }
543            if load_number(s)? != LUAC_NUM {
544                return Err(load_error(s, "float format mismatch"));
545            }
546        }
547        LuaVersion::V55 => {
548            check_literal(s, LUAC_DATA, "corrupted chunk")?;
549            fcheck_size(s, 4, "int")?;
550            if load_raw_i32(s)? != LUAC_INT_55 as i32 {
551                return Err(load_error(s, "int format mismatch"));
552            }
553
554            fcheck_size(s, 4, "instruction")?;
555            if load_raw_u32(s)? != LUAC_INST_55 {
556                return Err(load_error(s, "instruction format mismatch"));
557            }
558
559            fcheck_size(s, 8, "Lua integer")?;
560            if load_integer(s)? != LUAC_INT_55 {
561                return Err(load_error(s, "Lua integer format mismatch"));
562            }
563
564            fcheck_size(s, 8, "Lua number")?;
565            if load_number(s)? != LUAC_NUM_55 {
566                return Err(load_error(s, "Lua number format mismatch"));
567            }
568        }
569        _ => {
570            check_literal(s, LUAC_DATA, "corrupted chunk")?;
571            fcheck_size(s, 4, "Instruction")?;
572
573            fcheck_size(s, 8, "lua_Integer")?;
574
575            fcheck_size(s, 8, "lua_Number")?;
576
577            let int_check = load_integer(s)?;
578            if int_check != LUAC_INT {
579                return Err(load_error(s, "integer format mismatch"));
580            }
581
582            let num_check = load_number(s)?;
583            if num_check != LUAC_NUM {
584                return Err(load_error(s, "float format mismatch"));
585            }
586        }
587    }
588
589    Ok(())
590}
591
592/// Validate the 5.1/5.2 endianness + size + integral-flag block: endian = 1
593/// (little), `sizeof(int)` = 4, `sizeof(size_t)`, `sizeof(Instruction)` = 4,
594/// `sizeof(lua_Number)` = 8, integral = 0. These versions have no integer
595/// subtype, so there is no `lua_Integer` size byte and no `LUAC_INT`/`LUAC_NUM`
596/// sentinel.
597fn check_legacy_sizes(s: &mut LoadState<'_>) -> Result<(), LuaError> {
598    if load_byte(s)? != 1 {
599        return Err(load_error(s, "endianness mismatch"));
600    }
601    fcheck_size(s, size_of::<i32>(), "int")?;
602    fcheck_size(s, size_of::<usize>(), "size_t")?;
603    fcheck_size(s, 4, "Instruction")?;
604    fcheck_size(s, 8, "lua_Number")?;
605    if load_byte(s)? != 0 {
606        return Err(load_error(s, "number format mismatch"));
607    }
608    Ok(())
609}
610
611// ── Public entry point ─────────────────────────────────────────────────────
612
613/// Load a precompiled Lua chunk and return the top-level Lua closure.
614///
615/// This is the Rust equivalent of `luaU_undump` — the single public function
616/// exported by `lundump.c`.
617///
618/// # Parameters
619/// - `state` — the Lua thread state.
620/// - `z` — input stream positioned at the start of the binary chunk
621///   (the first byte `\x1b` of `LUA_SIGNATURE` must still be present).
622/// - `name` — chunk name for error messages.  Stripped per Lua convention:
623///   - `@…` → filename (strip `@`)
624///   - `=…` → literal name (strip `=`)
625///   - starts with `\x1b` → `"binary string"`
626///   - otherwise used as-is.
627///
628/// Unlike the C reference — which anchors the half-built closure on the stack
629/// (`setclLvalue2s` + `luaD_inctop`) so a mid-load emergency collection cannot
630/// sweep it — no stack anchoring is needed here: `protected_parser` stops the
631/// collector for the entire load window, and the closure is returned by value
632/// (`do_.rs::f_parser` pushes it onto the stack after undump returns, which is
633/// the real anchor point). `luai_verifycode`, a no-op in the default C build,
634/// has no equivalent call here.
635pub(crate) fn undump(
636    state: &mut LuaState,
637    z: &mut ZIO,
638    _name: &[u8],
639) -> Result<GcRef<LuaLClosure>, LuaError> {
640    let mut s = LoadState {
641        state,
642        z,
643        saved_strings: Vec::new(),
644    };
645
646    check_header(&mut s)?;
647
648    // Reads the number of upvalues for the top-level closure.
649    let nupvalues = load_byte(&mut s)? as usize;
650
651    let mut proto = LuaProto::placeholder();
652
653    load_function(&mut s, &mut proto, None)?;
654
655    // Build-then-wrap the top proto (see the note in `load_protos` on why the
656    // direct `GcRef::new` path is kept and `mark_gc_check_needed` fired here).
657    s.state.mark_gc_check_needed();
658    let proto_ref = GcRef::new(proto);
659    proto_ref.account_buffer(proto_ref.buffer_bytes() as isize);
660
661    debug_assert_eq!(
662        nupvalues,
663        proto_ref.upvalues.len(),
664        "upvalue count mismatch between closure header and prototype"
665    );
666
667    // Route the closure through the canonical constructor: it fires
668    // `mark_gc_check_needed`, fills the `nupvalues` upvalue slots with fresh
669    // closed nil upvalues (Rust's `Cell<GcRef<UpVal>>` slots are non-nullable,
670    // so C's `luaF_newLclosure`-with-NULL-slots followed by a later
671    // `luaF_initupvals` fill collapses into this one construction step), and
672    // accounts the closure's owned buffer (issue #276).
673    let cl_ref = s.state.new_lclosure(proto_ref, nupvalues);
674
675    Ok(cl_ref)
676}