Skip to main content

ruau_bytecode/
types.rs

1//! Structured representation of one serialized Luau bytecode chunk.
2
3use serde::{Deserialize, Serialize};
4
5use crate::opcodes::{CaptureType, FeedbackType, Opcode};
6
7/// One decoded bytecode blob.
8#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
9#[serde(tag = "kind", rename_all = "camelCase")]
10pub enum BytecodeChunk {
11    /// Valid bytecode chunk.
12    Valid {
13        /// Serialized bytecode version.
14        bytecode_version: u8,
15        /// Serialized type-encoding version.
16        type_version: u8,
17        /// String table in wire order. Entry ids are one-based; id zero is empty.
18        strings: Vec<Vec<u8>>,
19        /// Userdata type-name mappings in wire order.
20        userdata_type_mappings: Vec<UserdataTypeMapping>,
21        /// Explicit terminating byte read after userdata mappings.
22        userdata_mapping_terminator: u8,
23        /// Protos in wire order.
24        protos: Vec<Proto>,
25        /// Main proto id.
26        main_proto: u32,
27    },
28    /// Non-throwing upstream compile error bytecode.
29    Error {
30        /// Raw error message bytes after the leading zero marker.
31        message: Vec<u8>,
32    },
33}
34
35/// Userdata type-name remapping entry.
36#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
37#[serde(rename_all = "camelCase")]
38pub struct UserdataTypeMapping {
39    /// Type tag index.
40    pub type_index: u8,
41    /// One-based string-table id.
42    pub name: u32,
43}
44
45/// One decoded proto.
46#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
47#[serde(rename_all = "camelCase")]
48pub struct Proto {
49    /// Maximum stack size.
50    pub max_stack_size: u8,
51    /// Fixed parameter count.
52    pub num_params: u8,
53    /// Upvalue count.
54    pub num_upvalues: u8,
55    /// Vararg flag.
56    pub is_vararg: u8,
57    /// Proto flags.
58    pub flags: u8,
59    /// Type-info section.
60    pub type_info: TypeInfo,
61    /// Decoded instructions in word order.
62    pub code: Vec<Instruction>,
63    /// Constant table.
64    pub constants: Vec<Constant>,
65    /// Child proto ids.
66    pub child_protos: Vec<u32>,
67    /// Source line where this proto is defined.
68    pub line_defined: u32,
69    /// One-based string-table id of debug name, or zero.
70    pub debug_name: u32,
71    /// Encoded line-info block.
72    pub line_info: Option<LineInfo>,
73    /// Local and upvalue debug info.
74    pub debug_info: Option<DebugInfo>,
75    /// Feedback slots, present in version 11 chunks.
76    #[serde(default, skip_serializing_if = "Vec::is_empty")]
77    pub feedback_slots: Vec<FeedbackSlot>,
78}
79
80/// Raw type-info payload with decoded counts.
81#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
82#[serde(rename_all = "camelCase")]
83pub struct TypeInfo {
84    /// Encoded type-info payload bytes.
85    pub raw: Vec<u8>,
86}
87
88/// One instruction header and its optional static AUX word.
89///
90/// Plain-old-data on purpose: the dispatch loop fetches instructions by copy,
91/// so the type must never grow a heap allocation. Every aux-bearing Luau
92/// opcode carries exactly one AUX word (`Opcode::instruction_len`).
93#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
94#[serde(rename_all = "camelCase")]
95pub struct Instruction {
96    /// Header word.
97    pub header: u32,
98    /// Decoded opcode.
99    pub opcode: Opcode,
100    /// ABC A operand.
101    pub a: u8,
102    /// ABC B operand.
103    pub b: u8,
104    /// ABC C operand.
105    pub c: u8,
106    /// AD D operand.
107    pub d: i16,
108    /// E operand.
109    pub e: i32,
110    /// The static AUX word following the header, when the opcode has one.
111    /// Serialized as a 0/1-element array to keep the committed fixture shape.
112    #[serde(with = "aux_serde")]
113    pub aux: Option<u32>,
114}
115
116/// Serializes the optional AUX word as the 0/1-element array the committed
117/// fixture corpus already uses.
118mod aux_serde {
119    use serde::{Deserialize, Deserializer, Serialize, Serializer};
120
121    pub fn serialize<S: Serializer>(aux: &Option<u32>, serializer: S) -> Result<S::Ok, S::Error> {
122        let words: &[u32] = match aux {
123            Some(word) => std::slice::from_ref(word),
124            None => &[],
125        };
126        words.serialize(serializer)
127    }
128
129    pub fn deserialize<'de, D: Deserializer<'de>>(
130        deserializer: D,
131    ) -> Result<Option<u32>, D::Error> {
132        let words = Vec::<u32>::deserialize(deserializer)?;
133        match words.as_slice() {
134            [] => Ok(None),
135            [word] => Ok(Some(*word)),
136            _ => Err(serde::de::Error::custom(
137                "an instruction has at most one AUX word",
138            )),
139        }
140    }
141}
142
143impl Instruction {
144    /// Creates an instruction from its raw words.
145    #[must_use]
146    pub fn from_words(header: u32, aux: Option<u32>) -> Option<Self> {
147        let opcode = Opcode::from_byte((header & 0xff) as u8)?;
148        Some(Self {
149            header,
150            opcode,
151            a: ((header >> 8) & 0xff) as u8,
152            b: ((header >> 16) & 0xff) as u8,
153            c: ((header >> 24) & 0xff) as u8,
154            d: (header >> 16) as u16 as i16,
155            e: (header as i32) >> 8,
156            aux,
157        })
158    }
159
160    /// Encodes ABC instruction fields.
161    #[must_use]
162    pub fn abc(opcode: Opcode, a: u8, b: u8, c: u8) -> Self {
163        let header =
164            opcode.byte() as u32 | ((a as u32) << 8) | ((b as u32) << 16) | ((c as u32) << 24);
165        Self::from_words(header, None).expect("opcode bytes from the Opcode enum always decode")
166    }
167
168    /// Encodes ABC instruction fields followed by an optional static AUX word.
169    #[must_use]
170    pub fn abc_with_aux(opcode: Opcode, a: u8, b: u8, c: u8, aux: Option<u32>) -> Self {
171        let header =
172            opcode.byte() as u32 | ((a as u32) << 8) | ((b as u32) << 16) | ((c as u32) << 24);
173        Self::from_words(header, aux).expect("opcode bytes from the Opcode enum always decode")
174    }
175
176    /// Encodes AD instruction fields.
177    #[must_use]
178    pub fn ad(opcode: Opcode, a: u8, d: i16) -> Self {
179        let header = opcode.byte() as u32 | ((a as u32) << 8) | ((d as u16 as u32) << 16);
180        Self::from_words(header, None).expect("opcode bytes from the Opcode enum always decode")
181    }
182
183    /// Returns the encoded jump offset in instruction words, if this opcode jumps.
184    ///
185    /// Luau jump offsets are relative to the word after the instruction header.
186    /// For instructions with AUX words, the AUX words are part of the encoded
187    /// offset span; for example, comparison jumps use `D = 1` for the next
188    /// decoded instruction because their AUX word occupies the intervening word.
189    #[must_use]
190    pub fn jump_offset_words(&self) -> Option<i32> {
191        match self.opcode {
192            Opcode::Jump
193            | Opcode::JumpBack
194            | Opcode::JumpIf
195            | Opcode::JumpIfNot
196            | Opcode::JumpIfEq
197            | Opcode::JumpIfLe
198            | Opcode::JumpIfLt
199            | Opcode::JumpIfNotEq
200            | Opcode::JumpIfNotLe
201            | Opcode::JumpIfNotLt
202            | Opcode::ForNPrep
203            | Opcode::ForNLoop
204            | Opcode::ForGLoop
205            | Opcode::ForGPrepInext
206            | Opcode::ForGPrepNext
207            | Opcode::ForGPrep
208            | Opcode::JumpXEqKNil
209            | Opcode::JumpXEqKB
210            | Opcode::JumpXEqKN
211            | Opcode::JumpXEqKS
212            | Opcode::CmpProto => Some(i32::from(self.d)),
213            Opcode::JumpX => Some(self.e),
214            Opcode::LoadB
215            | Opcode::FastCall
216            | Opcode::FastCall1
217            | Opcode::FastCall2
218            | Opcode::FastCall2K
219            | Opcode::FastCall3 => Some(i32::from(self.c)),
220            _ => None,
221        }
222    }
223
224    /// Resolves this instruction's jump target as an absolute instruction-word offset.
225    #[must_use]
226    pub fn jump_target_word(&self, instruction_word: u32) -> Option<i32> {
227        Some(instruction_word as i32 + 1 + self.jump_offset_words()?)
228    }
229
230    /// Returns the `CAPTURE` operand kind, if this is a valid capture instruction.
231    #[must_use]
232    pub fn capture_type(&self) -> Option<CaptureType> {
233        if self.opcode == Opcode::Capture {
234            CaptureType::from_byte(self.a)
235        } else {
236            None
237        }
238    }
239
240    /// Returns the `CAPTURE` source register or upvalue index.
241    #[must_use]
242    pub fn capture_source(&self) -> Option<u8> {
243        self.capture_type().map(|_| self.b)
244    }
245
246    /// Returns the number of instruction words this instruction occupies,
247    /// counting its header word plus any AUX words.
248    #[must_use]
249    pub fn word_len(&self) -> u32 {
250        1 + u32::from(self.aux.is_some())
251    }
252}
253
254/// Returns the total number of instruction words spanned by `code`.
255#[must_use]
256pub fn code_word_count(code: &[Instruction]) -> u32 {
257    code.iter().map(Instruction::word_len).sum()
258}
259
260/// Returns the absolute instruction-word offset for each decoded instruction.
261#[must_use]
262pub fn instruction_word_offsets(code: &[Instruction]) -> Vec<u32> {
263    let mut next = 0u32;
264    code.iter()
265        .map(|instruction| {
266            let current = next;
267            next += instruction.word_len();
268            current
269        })
270        .collect()
271}
272
273/// Resolves one decoded instruction's jump target to another decoded instruction index.
274#[must_use]
275pub fn jump_target_instruction_index(
276    code: &[Instruction],
277    instruction_index: usize,
278) -> Option<usize> {
279    let offsets = instruction_word_offsets(code);
280    let instruction = code.get(instruction_index)?;
281    let source_word = *offsets.get(instruction_index)?;
282    let target = instruction.jump_target_word(source_word)?;
283    offsets.iter().position(|word| *word as i32 == target)
284}
285
286/// Constant table entry.
287#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
288#[serde(tag = "kind", rename_all = "camelCase")]
289pub enum Constant {
290    /// Nil.
291    Nil,
292    /// Boolean.
293    Boolean {
294        /// Boolean value.
295        value: bool,
296    },
297    /// Floating-point number, stored by exact bits.
298    Number {
299        /// Little-endian f64 bit pattern interpreted numerically by upstream.
300        bits: u64,
301    },
302    /// One-based string-table id.
303    String {
304        /// String table id.
305        string: u32,
306    },
307    /// Packed import id.
308    Import {
309        /// Import id.
310        import_id: u32,
311    },
312    /// Table shape.
313    Table {
314        /// Constant ids used as keys.
315        keys: Vec<u32>,
316    },
317    /// Closure proto reference.
318    Closure {
319        /// Proto id.
320        proto: u32,
321    },
322    /// Vector, stored by exact f32 bits.
323    Vector {
324        /// Four f32 bit patterns.
325        bits: [u32; 4],
326    },
327    /// Table shape with constant payloads.
328    TableWithConstants {
329        /// Key/value entries.
330        entries: Vec<TableEntry>,
331    },
332    /// 64-bit integer.
333    Integer {
334        /// Integer value.
335        value: i64,
336    },
337    /// Class shape.
338    ClassShape {
339        /// Shape payload.
340        shape: ClassShape,
341    },
342}
343
344/// One table shape entry with a pre-filled constant.
345#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
346#[serde(rename_all = "camelCase")]
347pub struct TableEntry {
348    /// Key constant id.
349    pub key: u32,
350    /// Value constant id, or -1 sentinel.
351    pub value: i32,
352}
353
354/// Class-shape constant payload.
355#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
356#[serde(rename_all = "camelCase")]
357pub struct ClassShape {
358    /// Class-name string id.
359    pub class_name: u32,
360    /// Property-name string ids.
361    pub property_names: Vec<u32>,
362    /// Method-name string ids.
363    pub method_names: Vec<u32>,
364}
365
366/// Wire-preserving line info.
367#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
368#[serde(rename_all = "camelCase")]
369pub struct LineInfo {
370    /// Log2 of encoded line span.
371    pub log2_span: u8,
372    /// Per-instruction unsigned delta differences.
373    pub delta_bytes: Vec<u8>,
374    /// Per-span signed baseline differences.
375    pub baseline_deltas: Vec<i32>,
376}
377
378impl LineInfo {
379    /// Encodes absolute source lines using upstream's line-info span packing.
380    #[must_use]
381    pub(crate) fn from_line_numbers(lines: &[i32]) -> Option<Self> {
382        if lines.is_empty() {
383            return None;
384        }
385
386        let mut span = 1usize << 24;
387        let mut offset = 0usize;
388        while offset < lines.len() {
389            let mut next = offset;
390            let mut min = lines[offset];
391            let mut max = lines[offset];
392
393            while next < lines.len() && next < offset + span {
394                min = min.min(lines[next]);
395                max = max.max(lines[next]);
396                if max - min > 255 {
397                    break;
398                }
399                next += 1;
400            }
401
402            if next < lines.len() && next - offset < span {
403                span = 1usize << line_info_log2(next - offset);
404            }
405
406            offset += span;
407        }
408
409        let log2_span = line_info_log2(span) as u8;
410        let baseline_size = (lines.len() - 1) / span + 1;
411        let mut baselines = Vec::with_capacity(baseline_size);
412        for chunk in lines.chunks(span) {
413            baselines.push(*chunk.iter().min().expect("non-empty chunk"));
414        }
415
416        let mut delta_bytes = Vec::with_capacity(lines.len());
417        let mut last_offset = 0u8;
418        for (index, line) in lines.iter().enumerate() {
419            let baseline = baselines[index >> usize::from(log2_span)];
420            let delta = *line - baseline;
421            debug_assert!((0..=255).contains(&delta));
422            let delta = delta as u8;
423            delta_bytes.push(delta.wrapping_sub(last_offset));
424            last_offset = delta;
425        }
426
427        let mut baseline_deltas = Vec::with_capacity(baseline_size);
428        let mut last_line = 0;
429        for baseline in baselines {
430            baseline_deltas.push(baseline - last_line);
431            last_line = baseline;
432        }
433
434        Some(Self {
435            log2_span,
436            delta_bytes,
437            baseline_deltas,
438        })
439    }
440
441    /// Decodes wire line-info payloads into absolute source lines.
442    #[must_use]
443    pub fn to_line_numbers(&self) -> Option<Vec<i32>> {
444        let mut baselines = Vec::with_capacity(self.baseline_deltas.len());
445        let mut baseline = 0i32;
446        for delta in &self.baseline_deltas {
447            // Line numbers wrap rather than panic on a hostile delta stream.
448            baseline = baseline.wrapping_add(*delta);
449            baselines.push(baseline);
450        }
451
452        let mut lines = Vec::with_capacity(self.delta_bytes.len());
453        let mut last_offset = 0u8;
454        for (index, byte) in self.delta_bytes.iter().enumerate() {
455            let baseline = *baselines.get(index >> usize::from(self.log2_span))?;
456            let offset = last_offset.wrapping_add(*byte);
457            lines.push(baseline.wrapping_add(i32::from(offset)));
458            last_offset = offset;
459        }
460
461        Some(lines)
462    }
463}
464
465fn line_info_log2(value: usize) -> usize {
466    debug_assert!(value > 0);
467
468    let mut result = 0;
469    while value >= (2usize << result) {
470        result += 1;
471    }
472    result
473}
474
475/// Debug local and upvalue names.
476#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
477#[serde(rename_all = "camelCase")]
478pub struct DebugInfo {
479    /// Local debug entries.
480    pub locals: Vec<DebugLocal>,
481    /// One-based string-table ids for upvalue names.
482    pub upvalues: Vec<u32>,
483}
484
485/// One local debug-info entry.
486#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
487#[serde(rename_all = "camelCase")]
488pub struct DebugLocal {
489    /// One-based string-table id.
490    pub name: u32,
491    /// Inclusive start pc.
492    pub start_pc: u32,
493    /// Exclusive end pc.
494    pub end_pc: u32,
495    /// Register.
496    pub register: u8,
497}
498
499/// Feedback slot metadata.
500#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
501#[serde(rename_all = "camelCase")]
502pub struct FeedbackSlot {
503    /// Slot type.
504    pub kind: FeedbackType,
505    /// Instruction pc associated with the slot.
506    pub pc: u32,
507}
508
509#[cfg(test)]
510mod tests {
511    use super::{
512        CaptureType, Instruction, LineInfo, Opcode, instruction_word_offsets,
513        jump_target_instruction_index,
514    };
515
516    #[test]
517    fn jump_targets_are_word_relative() {
518        let jump_next = Instruction::ad(Opcode::Jump, 0, 0);
519        assert_eq!(jump_next.jump_offset_words(), Some(0));
520        assert_eq!(jump_next.jump_target_word(10), Some(11));
521
522        let jump_back = Instruction::ad(Opcode::JumpBack, 0, -3);
523        assert_eq!(jump_back.jump_target_word(10), Some(8));
524
525        let jump_x = Instruction::from_words(
526            Opcode::JumpX.byte() as u32 | ((-5_i32 as u32 & 0x00ff_ffff) << 8),
527            None,
528        )
529        .expect("jumpx");
530        assert_eq!(jump_x.jump_offset_words(), Some(-5));
531        assert_eq!(jump_x.jump_target_word(10), Some(6));
532    }
533
534    #[test]
535    fn jump_targets_count_aux_words() {
536        let compare = Instruction::abc_with_aux(Opcode::JumpIfEq, 0, 1, 0, Some(0));
537        assert_eq!(compare.jump_offset_words(), Some(1));
538        assert_eq!(compare.jump_target_word(4), Some(6));
539
540        let code = vec![
541            Instruction::ad(Opcode::LoadN, 0, 1),
542            compare,
543            Instruction::ad(Opcode::LoadN, 1, 2),
544            Instruction::abc(Opcode::Return, 0, 1, 0),
545        ];
546        assert_eq!(instruction_word_offsets(&code), vec![0, 1, 3, 4]);
547        assert_eq!(jump_target_instruction_index(&code, 1), Some(2));
548
549        let compare_to_return = Instruction::abc_with_aux(Opcode::JumpIfEq, 0, 2, 0, Some(0));
550        let code = vec![
551            Instruction::ad(Opcode::LoadN, 0, 1),
552            compare_to_return,
553            Instruction::ad(Opcode::LoadN, 1, 2),
554            Instruction::abc(Opcode::Return, 0, 1, 0),
555        ];
556        assert_eq!(jump_target_instruction_index(&code, 1), Some(3));
557    }
558
559    #[test]
560    fn short_jump_operands_are_exposed() {
561        let loadb = Instruction::abc(Opcode::LoadB, 0, 1, 2);
562        assert_eq!(loadb.jump_offset_words(), Some(2));
563        assert_eq!(loadb.jump_target_word(7), Some(10));
564
565        let fastcall = Instruction::abc(Opcode::FastCall2K, 18, 1, 3);
566        assert_eq!(fastcall.jump_offset_words(), Some(3));
567        assert_eq!(fastcall.jump_target_word(7), Some(11));
568
569        let not_a_jump = Instruction::ad(Opcode::LoadN, 0, 5);
570        assert_eq!(not_a_jump.jump_offset_words(), None);
571        assert_eq!(not_a_jump.jump_target_word(0), None);
572    }
573
574    #[test]
575    fn capture_operands_are_exposed() {
576        let by_value = Instruction::abc(Opcode::Capture, CaptureType::Val as u8, 3, 0);
577        assert_eq!(by_value.capture_type(), Some(CaptureType::Val));
578        assert_eq!(by_value.capture_source(), Some(3));
579
580        let by_reference = Instruction::abc(Opcode::Capture, CaptureType::Ref as u8, 4, 0);
581        assert_eq!(by_reference.capture_type(), Some(CaptureType::Ref));
582        assert_eq!(by_reference.capture_source(), Some(4));
583
584        let upvalue = Instruction::abc(Opcode::Capture, CaptureType::Upval as u8, 1, 0);
585        assert_eq!(upvalue.capture_type(), Some(CaptureType::Upval));
586        assert_eq!(upvalue.capture_source(), Some(1));
587
588        let invalid = Instruction::abc(Opcode::Capture, 99, 1, 0);
589        assert_eq!(invalid.capture_type(), None);
590        assert_eq!(invalid.capture_source(), None);
591
592        let not_capture = Instruction::ad(Opcode::LoadN, 0, 5);
593        assert_eq!(not_capture.capture_type(), None);
594        assert_eq!(not_capture.capture_source(), None);
595    }
596
597    #[test]
598    fn line_info_uses_large_span_when_deltas_fit() {
599        let line_info = LineInfo::from_line_numbers(&[10, 10, 20]).expect("line info");
600        assert_eq!(line_info.log2_span, 24);
601        assert_eq!(line_info.delta_bytes, vec![0, 0, 10]);
602        assert_eq!(line_info.baseline_deltas, vec![10]);
603        assert_eq!(
604            line_info.to_line_numbers().expect("line numbers"),
605            vec![10, 10, 20]
606        );
607    }
608
609    #[test]
610    fn line_info_shrinks_span_before_8_bit_delta_overflows() {
611        let lines = [1, 2, 300, 301, 302];
612        let line_info = LineInfo::from_line_numbers(&lines).expect("line info");
613
614        assert_eq!(line_info.log2_span, 1);
615        assert_eq!(line_info.delta_bytes, vec![0, 1, 255, 1, 255]);
616        assert_eq!(line_info.baseline_deltas, vec![1, 299, 2]);
617        assert_eq!(line_info.to_line_numbers().expect("line numbers"), lines);
618    }
619}