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