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