Skip to main content

ruau_bytecode/
codec.rs

1//! Luau bytecode decoder and encoder.
2
3use std::fmt;
4
5use crate::{
6    opcodes::{ConstantTag, FeedbackType, Opcode},
7    types::{
8        BytecodeChunk, ClassShape, Constant, DebugInfo, DebugLocal, FeedbackSlot, Instruction,
9        LineInfo, Proto, TableEntry, TypeInfo, UserdataTypeMapping, code_word_count,
10    },
11};
12
13/// Bytecode decode failure.
14#[derive(Clone, Debug, Eq, PartialEq)]
15pub struct DecodeError {
16    message: String,
17}
18
19impl DecodeError {
20    fn new(message: impl Into<String>) -> Self {
21        Self {
22            message: message.into(),
23        }
24    }
25}
26
27impl fmt::Display for DecodeError {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        f.write_str(&self.message)
30    }
31}
32
33impl std::error::Error for DecodeError {}
34
35/// Bytecode encode failure.
36#[derive(Clone, Debug, Eq, PartialEq)]
37pub struct EncodeError {
38    message: String,
39}
40
41impl EncodeError {
42    fn new(message: impl Into<String>) -> Self {
43        Self {
44            message: message.into(),
45        }
46    }
47}
48
49impl fmt::Display for EncodeError {
50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51        f.write_str(&self.message)
52    }
53}
54
55impl std::error::Error for EncodeError {}
56
57/// Decodes one Luau bytecode blob into a chunk.
58pub fn decode_chunk(bytes: &[u8]) -> Result<BytecodeChunk, DecodeError> {
59    let mut reader = Reader::new(bytes);
60    let version = reader.u8("bytecode version")?;
61    if version == 0 {
62        return Ok(BytecodeChunk::Error {
63            message: bytes[1..].to_vec(),
64        });
65    }
66    if !(3..=11).contains(&version) {
67        return Err(DecodeError::new(format!(
68            "unsupported bytecode version {version}"
69        )));
70    }
71    let type_version = reader.u8("type encoding version")?;
72    if !(1..=3).contains(&type_version) {
73        return Err(DecodeError::new(format!(
74            "unsupported bytecode type encoding version {type_version}"
75        )));
76    }
77
78    let strings = decode_string_table(&mut reader)?;
79    let mut userdata_type_mappings = Vec::new();
80    loop {
81        let type_index = reader.u8("userdata type mapping index")?;
82        if type_index == 0 {
83            break;
84        }
85        let name = reader.var_u32("userdata type name")?;
86        userdata_type_mappings.push(UserdataTypeMapping { type_index, name });
87    }
88
89    let proto_count = reader.var_u32("proto count")?;
90    let mut protos = Vec::with_capacity(reader.cap(proto_count));
91    for _ in 0..proto_count {
92        protos.push(decode_proto(&mut reader, version)?);
93    }
94    let main_proto = reader.var_u32("main proto id")?;
95    if !reader.is_eof() {
96        return Err(DecodeError::new(format!(
97            "trailing {} byte(s) after main proto",
98            reader.remaining()
99        )));
100    }
101
102    Ok(BytecodeChunk::Valid {
103        bytecode_version: version,
104        type_version,
105        strings,
106        userdata_type_mappings,
107        userdata_mapping_terminator: 0,
108        protos,
109        main_proto,
110    })
111}
112
113fn decode_string_table(reader: &mut Reader<'_>) -> Result<Vec<Vec<u8>>, DecodeError> {
114    let count = reader.var_u32("string count")?;
115    let mut strings = Vec::with_capacity(reader.cap(count));
116    for index in 0..count {
117        let len = reader.var_u32("string length")? as usize;
118        let bytes = reader.bytes(len, &format!("string table entry {}", index + 1))?;
119        strings.push(bytes.to_vec());
120    }
121    Ok(strings)
122}
123
124fn decode_proto(reader: &mut Reader<'_>, version: u8) -> Result<Proto, DecodeError> {
125    let max_stack_size = reader.u8("proto max stack size")?;
126    let num_params = reader.u8("proto parameter count")?;
127    let num_upvalues = reader.u8("proto upvalue count")?;
128    let is_vararg = reader.u8("proto vararg flag")?;
129    let flags = reader.u8("proto flags")?;
130    let type_info = decode_type_info(reader)?;
131
132    let code_words = reader.var_u32("instruction word count")?;
133    let mut word_index = 0;
134    let mut code = Vec::new();
135    while word_index < code_words {
136        let header = reader.u32("instruction header")?;
137        word_index += 1;
138        let opcode = Opcode::from_byte((header & 0xff) as u8).ok_or_else(|| {
139            DecodeError::new(format!(
140                "unknown opcode {} at word {}",
141                header & 0xff,
142                word_index - 1
143            ))
144        })?;
145        let aux_count = opcode.instruction_len() - 1;
146        if word_index + aux_count as u32 > code_words {
147            return Err(DecodeError::new(format!(
148                "{opcode:?} at word {} requires {aux_count} AUX word(s), past code size {code_words}",
149                word_index - 1
150            )));
151        }
152        let aux = if aux_count == 1 {
153            word_index += 1;
154            Some(reader.u32("instruction aux")?)
155        } else {
156            None
157        };
158        code.push(
159            Instruction::from_words(header, aux)
160                .ok_or_else(|| DecodeError::new("opcode disappeared during decode"))?,
161        );
162    }
163
164    let constant_count = reader.var_u32("constant count")?;
165    let mut constants = Vec::with_capacity(reader.cap(constant_count));
166    for _ in 0..constant_count {
167        constants.push(decode_constant(reader)?);
168    }
169
170    let child_count = reader.var_u32("child proto count")?;
171    let mut child_protos = Vec::with_capacity(reader.cap(child_count));
172    for _ in 0..child_count {
173        child_protos.push(reader.var_u32("child proto id")?);
174    }
175
176    let line_defined = reader.var_u32("line defined")?;
177    let debug_name = reader.var_u32("debug name")?;
178    let line_info = if reader.u8("line info flag")? != 0 {
179        Some(decode_line_info(reader, code_words)?)
180    } else {
181        None
182    };
183    let debug_info = if reader.u8("debug info flag")? != 0 {
184        Some(decode_debug_info(reader)?)
185    } else {
186        None
187    };
188    let feedback_slots = if version >= 11 {
189        let count = reader.var_u32("feedback slot count")?;
190        let mut slots = Vec::with_capacity(reader.cap(count));
191        for _ in 0..count {
192            let kind = FeedbackType::from_byte(reader.u8("feedback slot type")?)
193                .ok_or_else(|| DecodeError::new("unknown feedback slot type"))?;
194            let pc = reader.var_u32("feedback slot pc")?;
195            slots.push(FeedbackSlot { kind, pc });
196        }
197        slots
198    } else {
199        Vec::new()
200    };
201
202    Ok(Proto {
203        max_stack_size,
204        num_params,
205        num_upvalues,
206        is_vararg,
207        flags,
208        type_info,
209        code,
210        constants,
211        child_protos,
212        line_defined,
213        debug_name,
214        line_info,
215        debug_info,
216        feedback_slots,
217    })
218}
219
220fn decode_type_info(reader: &mut Reader<'_>) -> Result<TypeInfo, DecodeError> {
221    let size = reader.var_u32("type info size")? as usize;
222    let raw = reader.bytes(size, "type info payload")?.to_vec();
223    Ok(TypeInfo { raw })
224}
225
226fn decode_constant(reader: &mut Reader<'_>) -> Result<Constant, DecodeError> {
227    let tag = ConstantTag::from_byte(reader.u8("constant tag")?)
228        .ok_or_else(|| DecodeError::new("unknown constant tag"))?;
229    Ok(match tag {
230        ConstantTag::Nil => Constant::Nil,
231        ConstantTag::Boolean => Constant::Boolean {
232            value: reader.u8("boolean constant")? != 0,
233        },
234        ConstantTag::Number => Constant::Number {
235            bits: reader.u64("number constant")?,
236        },
237        ConstantTag::String => Constant::String {
238            string: reader.var_u32("string constant id")?,
239        },
240        ConstantTag::Import => Constant::Import {
241            import_id: reader.u32("import id")?,
242        },
243        ConstantTag::Table => {
244            let count = reader.var_u32("table key count")?;
245            let mut keys = Vec::with_capacity(reader.cap(count));
246            for _ in 0..count {
247                keys.push(reader.var_u32("table key")?);
248            }
249            Constant::Table { keys }
250        }
251        ConstantTag::Closure => Constant::Closure {
252            proto: reader.var_u32("closure proto id")?,
253        },
254        ConstantTag::Vector => {
255            let mut bits = [0; 4];
256            for bit in &mut bits {
257                *bit = reader.u32("vector component")?;
258            }
259            Constant::Vector { bits }
260        }
261        ConstantTag::TableWithConstants => {
262            let count = reader.var_u32("table entry count")?;
263            let mut entries = Vec::with_capacity(reader.cap(count));
264            for _ in 0..count {
265                entries.push(TableEntry {
266                    key: reader.var_u32("table entry key")?,
267                    value: reader.i32("table entry value")?,
268                });
269            }
270            Constant::TableWithConstants { entries }
271        }
272        ConstantTag::Integer => {
273            let negative = reader.u8("integer sign")? != 0;
274            let magnitude = reader.var_u64("integer magnitude")?;
275            let value = if negative {
276                (!magnitude).wrapping_add(1) as i64
277            } else {
278                magnitude as i64
279            };
280            Constant::Integer { value }
281        }
282        ConstantTag::ClassShape => Constant::ClassShape {
283            shape: decode_class_shape(reader)?,
284        },
285    })
286}
287
288fn decode_class_shape(reader: &mut Reader<'_>) -> Result<ClassShape, DecodeError> {
289    let class_name = reader.var_u32("class name")?;
290    let property_count = reader.var_u32("class property count")?;
291    let method_count = reader.var_u32("class method count")?;
292    let mut property_names = Vec::with_capacity(reader.cap(property_count));
293    for _ in 0..property_count {
294        property_names.push(reader.var_u32("class property name")?);
295    }
296    let mut method_names = Vec::with_capacity(reader.cap(method_count));
297    for _ in 0..method_count {
298        method_names.push(reader.var_u32("class method name")?);
299    }
300    Ok(ClassShape {
301        class_name,
302        property_names,
303        method_names,
304    })
305}
306
307fn decode_line_info(
308    reader: &mut Reader<'_>,
309    instruction_words: u32,
310) -> Result<LineInfo, DecodeError> {
311    let log2_span = reader.u8("line info log span")?;
312    if log2_span >= 32 {
313        return Err(DecodeError::new(format!(
314            "line info log span {log2_span} out of range (must be < 32)"
315        )));
316    }
317    let mut delta_bytes = Vec::with_capacity(reader.cap(instruction_words));
318    for _ in 0..instruction_words {
319        delta_bytes.push(reader.u8("line info delta")?);
320    }
321    let intervals = ((instruction_words.saturating_sub(1)) >> log2_span) + 1;
322    let mut baseline_deltas = Vec::with_capacity(reader.cap(intervals));
323    for _ in 0..intervals {
324        baseline_deltas.push(reader.i32("line info baseline")?);
325    }
326    Ok(LineInfo {
327        log2_span,
328        delta_bytes,
329        baseline_deltas,
330    })
331}
332
333fn decode_debug_info(reader: &mut Reader<'_>) -> Result<DebugInfo, DecodeError> {
334    let local_count = reader.var_u32("debug local count")?;
335    let mut locals = Vec::with_capacity(reader.cap(local_count));
336    for _ in 0..local_count {
337        locals.push(DebugLocal {
338            name: reader.var_u32("debug local name")?,
339            start_pc: reader.var_u32("debug local start pc")?,
340            end_pc: reader.var_u32("debug local end pc")?,
341            register: reader.u8("debug local register")?,
342        });
343    }
344    let upvalue_count = reader.var_u32("debug upvalue count")?;
345    let mut upvalues = Vec::with_capacity(reader.cap(upvalue_count));
346    for _ in 0..upvalue_count {
347        upvalues.push(reader.var_u32("debug upvalue name")?);
348    }
349    Ok(DebugInfo { locals, upvalues })
350}
351
352/// Encodes a chunk back into upstream wire bytes.
353pub fn encode_chunk(chunk: &BytecodeChunk) -> Result<Vec<u8>, EncodeError> {
354    let mut writer = Writer::default();
355    match chunk {
356        BytecodeChunk::Error { message } => {
357            writer.u8(0);
358            writer.bytes(message);
359        }
360        BytecodeChunk::Valid {
361            bytecode_version,
362            type_version,
363            strings,
364            userdata_type_mappings,
365            userdata_mapping_terminator,
366            protos,
367            main_proto,
368        } => {
369            if *userdata_mapping_terminator != 0 {
370                return Err(EncodeError::new("userdata mapping terminator must be zero"));
371            }
372            writer.u8(*bytecode_version);
373            writer.u8(*type_version);
374            writer.var_u64(strings.len() as u64);
375            for string in strings {
376                writer.var_u64(string.len() as u64);
377                writer.bytes(string);
378            }
379            for mapping in userdata_type_mappings {
380                writer.u8(mapping.type_index);
381                writer.var_u64(mapping.name as u64);
382            }
383            writer.u8(0);
384            writer.var_u64(protos.len() as u64);
385            for proto in protos {
386                encode_proto(&mut writer, *bytecode_version, proto);
387            }
388            writer.var_u64(*main_proto as u64);
389        }
390    }
391    Ok(writer.bytes)
392}
393
394fn encode_proto(writer: &mut Writer, version: u8, proto: &Proto) {
395    writer.u8(proto.max_stack_size);
396    writer.u8(proto.num_params);
397    writer.u8(proto.num_upvalues);
398    writer.u8(proto.is_vararg);
399    writer.u8(proto.flags);
400    writer.var_u64(proto.type_info.raw.len() as u64);
401    writer.bytes(&proto.type_info.raw);
402    writer.var_u64(u64::from(code_word_count(&proto.code)));
403    for instruction in &proto.code {
404        writer.u32(instruction.header);
405        if let Some(aux) = instruction.aux {
406            writer.u32(aux);
407        }
408    }
409    writer.var_u64(proto.constants.len() as u64);
410    for constant in &proto.constants {
411        encode_constant(writer, constant);
412    }
413    writer.var_u64(proto.child_protos.len() as u64);
414    for child in &proto.child_protos {
415        writer.var_u64(*child as u64);
416    }
417    writer.var_u64(proto.line_defined as u64);
418    writer.var_u64(proto.debug_name as u64);
419    if let Some(line_info) = &proto.line_info {
420        writer.u8(1);
421        writer.u8(line_info.log2_span);
422        writer.bytes(&line_info.delta_bytes);
423        for baseline in &line_info.baseline_deltas {
424            writer.i32(*baseline);
425        }
426    } else {
427        writer.u8(0);
428    }
429    if let Some(debug_info) = &proto.debug_info {
430        writer.u8(1);
431        writer.var_u64(debug_info.locals.len() as u64);
432        for local in &debug_info.locals {
433            writer.var_u64(local.name as u64);
434            writer.var_u64(local.start_pc as u64);
435            writer.var_u64(local.end_pc as u64);
436            writer.u8(local.register);
437        }
438        writer.var_u64(debug_info.upvalues.len() as u64);
439        for upvalue in &debug_info.upvalues {
440            writer.var_u64(*upvalue as u64);
441        }
442    } else {
443        writer.u8(0);
444    }
445    if version >= 11 {
446        writer.var_u64(proto.feedback_slots.len() as u64);
447        for slot in &proto.feedback_slots {
448            writer.u8(slot.kind as u8);
449            writer.var_u64(slot.pc as u64);
450        }
451    }
452}
453
454fn encode_constant(writer: &mut Writer, constant: &Constant) {
455    match constant {
456        Constant::Nil => writer.u8(ConstantTag::Nil as u8),
457        Constant::Boolean { value } => {
458            writer.u8(ConstantTag::Boolean as u8);
459            writer.u8(u8::from(*value));
460        }
461        Constant::Number { bits } => {
462            writer.u8(ConstantTag::Number as u8);
463            writer.u64(*bits);
464        }
465        Constant::String { string } => {
466            writer.u8(ConstantTag::String as u8);
467            writer.var_u64(*string as u64);
468        }
469        Constant::Import { import_id } => {
470            writer.u8(ConstantTag::Import as u8);
471            writer.u32(*import_id);
472        }
473        Constant::Table { keys } => {
474            writer.u8(ConstantTag::Table as u8);
475            writer.var_u64(keys.len() as u64);
476            for key in keys {
477                writer.var_u64(*key as u64);
478            }
479        }
480        Constant::Closure { proto } => {
481            writer.u8(ConstantTag::Closure as u8);
482            writer.var_u64(*proto as u64);
483        }
484        Constant::Vector { bits } => {
485            writer.u8(ConstantTag::Vector as u8);
486            for bit in bits {
487                writer.u32(*bit);
488            }
489        }
490        Constant::TableWithConstants { entries } => {
491            writer.u8(ConstantTag::TableWithConstants as u8);
492            writer.var_u64(entries.len() as u64);
493            for entry in entries {
494                writer.var_u64(entry.key as u64);
495                writer.i32(entry.value);
496            }
497        }
498        Constant::Integer { value } => {
499            writer.u8(ConstantTag::Integer as u8);
500            if *value < 0 {
501                writer.u8(1);
502                writer.var_u64((!(*value as u64)).wrapping_add(1));
503            } else {
504                writer.u8(0);
505                writer.var_u64(*value as u64);
506            }
507        }
508        Constant::ClassShape { shape } => {
509            writer.u8(ConstantTag::ClassShape as u8);
510            writer.var_u64(shape.class_name as u64);
511            writer.var_u64(shape.property_names.len() as u64);
512            writer.var_u64(shape.method_names.len() as u64);
513            for name in &shape.property_names {
514                writer.var_u64(*name as u64);
515            }
516            for name in &shape.method_names {
517                writer.var_u64(*name as u64);
518            }
519        }
520    }
521}
522
523struct Reader<'a> {
524    bytes: &'a [u8],
525    offset: usize,
526}
527
528impl<'a> Reader<'a> {
529    fn new(bytes: &'a [u8]) -> Self {
530        Self { bytes, offset: 0 }
531    }
532
533    fn is_eof(&self) -> bool {
534        self.offset == self.bytes.len()
535    }
536
537    fn remaining(&self) -> usize {
538        self.bytes.len() - self.offset
539    }
540
541    /// A pre-allocation capacity capped by the bytes still available. A chunk
542    /// cannot hold more length-prefixed elements than it has bytes (each element
543    /// consumes at least one byte), so a hostile count cannot trigger a huge
544    /// speculative allocation; if the declared count really is larger than the
545    /// data, the element loop fails cleanly when the reader runs out of bytes.
546    fn cap(&self, count: u32) -> usize {
547        (count as usize).min(self.remaining())
548    }
549
550    fn bytes(&mut self, len: usize, label: &str) -> Result<&'a [u8], DecodeError> {
551        if self.remaining() < len {
552            return Err(DecodeError::new(format!(
553                "unexpected end while reading {label}: need {len} byte(s), have {}",
554                self.remaining()
555            )));
556        }
557        let start = self.offset;
558        self.offset += len;
559        Ok(&self.bytes[start..self.offset])
560    }
561
562    fn u8(&mut self, label: &str) -> Result<u8, DecodeError> {
563        Ok(self.bytes(1, label)?[0])
564    }
565
566    fn u32(&mut self, label: &str) -> Result<u32, DecodeError> {
567        Ok(u32::from_le_bytes(self.fixed_bytes(label)?))
568    }
569
570    fn i32(&mut self, label: &str) -> Result<i32, DecodeError> {
571        Ok(i32::from_le_bytes(self.fixed_bytes(label)?))
572    }
573
574    fn u64(&mut self, label: &str) -> Result<u64, DecodeError> {
575        Ok(u64::from_le_bytes(self.fixed_bytes(label)?))
576    }
577
578    fn fixed_bytes<const N: usize>(&mut self, label: &str) -> Result<[u8; N], DecodeError> {
579        let mut bytes = [0; N];
580        bytes.copy_from_slice(self.bytes(N, label)?);
581        Ok(bytes)
582    }
583
584    fn var_u32(&mut self, label: &str) -> Result<u32, DecodeError> {
585        let value = self.var_u64(label)?;
586        u32::try_from(value)
587            .map_err(|_| DecodeError::new(format!("{label} varint {value} overflows u32")))
588    }
589
590    fn var_u64(&mut self, label: &str) -> Result<u64, DecodeError> {
591        let mut result = 0u64;
592        let mut shift = 0;
593        loop {
594            if shift >= 64 {
595                return Err(DecodeError::new(format!("{label} varint is too large")));
596            }
597            let byte = self.u8(label)?;
598            result |= u64::from(byte & VARINT_PAYLOAD_MASK) << shift;
599            if byte & VARINT_CONTINUATION_BIT == 0 {
600                return Ok(result);
601            }
602            shift += 7;
603        }
604    }
605}
606
607#[derive(Default)]
608struct Writer {
609    bytes: Vec<u8>,
610}
611
612impl Writer {
613    fn bytes(&mut self, bytes: &[u8]) {
614        self.bytes.extend_from_slice(bytes);
615    }
616
617    fn u8(&mut self, value: u8) {
618        self.bytes.push(value);
619    }
620
621    fn u32(&mut self, value: u32) {
622        self.bytes.extend_from_slice(&value.to_le_bytes());
623    }
624
625    fn i32(&mut self, value: i32) {
626        self.bytes.extend_from_slice(&value.to_le_bytes());
627    }
628
629    fn u64(&mut self, value: u64) {
630        self.bytes.extend_from_slice(&value.to_le_bytes());
631    }
632
633    fn var_u64(&mut self, value: u64) {
634        write_varint(&mut self.bytes, value);
635    }
636}
637
638/// LEB128 varint: low seven bits of each byte carry payload.
639const VARINT_PAYLOAD_MASK: u8 = 0x7f;
640/// LEB128 varint: the high bit marks a continuation byte.
641const VARINT_CONTINUATION_BIT: u8 = 0x80;
642
643/// Appends `value` to `bytes` as an unsigned LEB128 varint.
644pub fn write_varint(bytes: &mut Vec<u8>, mut value: u64) {
645    loop {
646        let byte = (value & u64::from(VARINT_PAYLOAD_MASK)) as u8
647            | (u8::from(value > u64::from(VARINT_PAYLOAD_MASK)) << 7);
648        bytes.push(byte);
649        value >>= 7;
650        if value == 0 {
651            break;
652        }
653    }
654}
655
656#[cfg(test)]
657mod tests {
658    use super::{decode_chunk, encode_chunk};
659    use crate::{
660        BytecodeChunk, ClassShape, Constant, DebugInfo, DebugLocal, FeedbackSlot, Instruction,
661        LineInfo, Proto, TableEntry, TypeInfo, UserdataTypeMapping,
662        opcodes::{FeedbackType, Opcode},
663    };
664
665    #[test]
666    fn error_bytecode_roundtrips() {
667        let bytes = b"\0compile failed";
668        let chunk = decode_chunk(bytes).expect("decode error chunk");
669        assert_eq!(
670            chunk,
671            BytecodeChunk::Error {
672                message: b"compile failed".to_vec()
673            }
674        );
675        assert_eq!(encode_chunk(&chunk).expect("encode"), bytes);
676    }
677
678    #[test]
679    fn rejects_unknown_valid_version() {
680        let err = decode_chunk(&[12, 3]).expect_err("version is unsupported");
681        assert!(err.to_string().contains("unsupported bytecode version 12"));
682    }
683
684    #[test]
685    fn rejects_unsupported_type_encoding_version() {
686        let err = decode_chunk(&[6, 4]).expect_err("type encoding version is unsupported");
687        assert!(
688            err.to_string()
689                .contains("unsupported bytecode type encoding version 4")
690        );
691    }
692
693    #[test]
694    fn rich_wire_shapes_roundtrip() {
695        let chunk = BytecodeChunk::Valid {
696            bytecode_version: 11,
697            type_version: 3,
698            strings: vec![
699                b"main".to_vec(),
700                b"Widget".to_vec(),
701                b"width".to_vec(),
702                b"height".to_vec(),
703                b"resize".to_vec(),
704                b"userdataName".to_vec(),
705                b"upvalueName".to_vec(),
706            ],
707            userdata_type_mappings: vec![UserdataTypeMapping {
708                type_index: 64,
709                name: 6,
710            }],
711            userdata_mapping_terminator: 0,
712            protos: vec![minimal_proto(), rich_proto()],
713            main_proto: 1,
714        };
715
716        let bytes = encode_chunk(&chunk).expect("encode rich chunk");
717        let decoded = decode_chunk(&bytes).expect("decode rich chunk");
718
719        assert_eq!(decoded, chunk);
720        assert_eq!(encode_chunk(&decoded).expect("re-encode rich chunk"), bytes);
721        let BytecodeChunk::Valid {
722            userdata_type_mappings,
723            protos,
724            ..
725        } = decoded
726        else {
727            panic!("expected valid chunk");
728        };
729        assert_eq!(userdata_type_mappings[0].type_index, 64);
730        assert_eq!(protos[1].code[0].opcode, Opcode::Coverage);
731        assert!(matches!(protos[1].constants[7], Constant::Vector { .. }));
732        assert!(matches!(
733            protos[1].constants[9],
734            Constant::Integer { value: -42 }
735        ));
736        assert!(matches!(
737            protos[1].constants[10],
738            Constant::ClassShape { .. }
739        ));
740    }
741
742    fn minimal_proto() -> Proto {
743        Proto {
744            max_stack_size: 1,
745            num_params: 0,
746            num_upvalues: 0,
747            is_vararg: 0,
748            flags: 0,
749            type_info: TypeInfo { raw: Vec::new() },
750            code: vec![Instruction::abc(Opcode::Return, 0, 1, 0)],
751            constants: Vec::new(),
752            child_protos: Vec::new(),
753            line_defined: 0,
754            debug_name: 0,
755            line_info: None,
756            debug_info: None,
757            feedback_slots: Vec::new(),
758        }
759    }
760
761    fn rich_proto() -> Proto {
762        Proto {
763            max_stack_size: 4,
764            num_params: 1,
765            num_upvalues: 1,
766            is_vararg: 1,
767            flags: 0,
768            type_info: TypeInfo {
769                raw: vec![1, 2, 3, 4],
770            },
771            code: vec![
772                Instruction::abc(Opcode::Coverage, 0, 0, 0),
773                Instruction::abc_with_aux(Opcode::CallFb, 0, 1, 2, Some(0xfeed_beef)),
774                Instruction::abc(Opcode::Return, 0, 1, 0),
775            ],
776            constants: vec![
777                Constant::Nil,
778                Constant::Boolean { value: true },
779                Constant::Number {
780                    bits: 1.25_f64.to_bits(),
781                },
782                Constant::String { string: 1 },
783                Constant::Import {
784                    import_id: 0x0102_0304,
785                },
786                Constant::Table { keys: vec![1, 2] },
787                Constant::Closure { proto: 0 },
788                Constant::Vector {
789                    bits: [
790                        1.0_f32.to_bits(),
791                        2.0_f32.to_bits(),
792                        3.0_f32.to_bits(),
793                        4.0_f32.to_bits(),
794                    ],
795                },
796                Constant::TableWithConstants {
797                    entries: vec![
798                        TableEntry { key: 1, value: -1 },
799                        TableEntry { key: 2, value: 6 },
800                    ],
801                },
802                Constant::Integer { value: -42 },
803                Constant::ClassShape {
804                    shape: ClassShape {
805                        class_name: 2,
806                        property_names: vec![3, 4],
807                        method_names: vec![5],
808                    },
809                },
810            ],
811            child_protos: vec![0],
812            line_defined: 10,
813            debug_name: 1,
814            line_info: Some(LineInfo {
815                log2_span: 1,
816                delta_bytes: vec![0, 0, 1, 1],
817                baseline_deltas: vec![10, 2],
818            }),
819            debug_info: Some(DebugInfo {
820                locals: vec![DebugLocal {
821                    name: 1,
822                    start_pc: 0,
823                    end_pc: 3,
824                    register: 0,
825                }],
826                upvalues: vec![7],
827            }),
828            feedback_slots: vec![FeedbackSlot {
829                kind: FeedbackType::CallTarget,
830                pc: 1,
831            }],
832        }
833    }
834
835    /// Regression corpus: hostile byte sequences found by the `bytecode_decode`
836    /// and `vm_load` fuzz targets. Each previously triggered a panic or an
837    /// unbounded allocation; the decoder must now return cleanly (`Ok` or `Err`)
838    /// on every one — never panic or OOM. Reproducers are kept inline because the
839    /// fuzz corpus directory is not checked in.
840    #[test]
841    fn decode_survives_hostile_inputs() {
842        // Unbounded length-prefix allocation: a huge declared string count once
843        // drove a multi-gigabyte `Vec::with_capacity`.
844        const UNBOUNDED_ALLOC: &[u8] = &[0x03, 0x03, 0xff, 0xff, 0xff, 0xff, 0x04, 0xa6];
845        // Line-info `log2_span` of 0x25 (>= 32) once overflowed a `u32` shift.
846        const SHIFT_OVERFLOW: &[u8] = &[
847            0x06, 0x03, 0x00, 0x00, 0x25, 0x00, 0x3d, 0x7c, 0x2f, 0x00, 0x00, 0x00, 0x00, 0x00,
848            0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00,
849        ];
850        // A line-delta stream whose running `i32` sum once overflowed.
851        const ADD_OVERFLOW: &[u8] = &[
852            0x03, 0x03, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x28, 0x03,
853            0x5b, 0xfe, 0x00, 0x2d, 0x00, 0xd9, 0x2d, 0x00, 0x00, 0x04, 0x00, 0x00, 0xaf, 0x01,
854            0x00, 0x03, 0x00, 0x00, 0x41, 0x03, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x00, 0x8d,
855            0x80, 0x2b, 0x03, 0x01, 0x00, 0x00,
856        ];
857
858        // The declared string count now hits the remaining-bytes bound before
859        // any allocation, so decoding fails on the truncated string table.
860        assert!(
861            decode_chunk(UNBOUNDED_ALLOC).is_err(),
862            "truncated string table must be rejected"
863        );
864        // The out-of-range span is now rejected up front instead of shifting.
865        assert!(
866            decode_chunk(SHIFT_OVERFLOW).is_err(),
867            "log2_span >= 32 must be rejected"
868        );
869        // The running line-delta sum now wraps instead of overflowing, and the
870        // rest of this chunk is well-formed, so it decodes successfully.
871        assert!(
872            decode_chunk(ADD_OVERFLOW).is_ok(),
873            "wrapped line-delta stream decodes cleanly"
874        );
875    }
876}