Skip to main content

ruau_bytecode/
validate.rs

1//! Conservative semantic validation for decoded bytecode chunks.
2
3#[cfg(test)]
4use std::cell::Cell;
5
6use serde::{Deserialize, Serialize};
7
8use crate::{
9    BytecodeChunk, Constant, Instruction, Proto,
10    opcodes::{
11        BuiltinFunction, CaptureType, FORGLOOP_INEXT_BIT, IMPORT_PATH_COMPONENT_MASK,
12        IMPORT_PATH_COUNT_SHIFT, JUMPX_K_INDEX_MASK, Opcode, import_component_shift,
13    },
14};
15
16/// One structural bytecode validation failure.
17#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
18#[serde(rename_all = "camelCase")]
19pub struct ValidationError {
20    /// Proto index containing the failure, if proto-local.
21    pub proto_index: Option<usize>,
22    /// Instruction index containing the failure, if instruction-local.
23    pub instruction_index: Option<usize>,
24    /// Error category.
25    pub kind: ValidationErrorKind,
26    /// Human-readable diagnostic.
27    pub message: String,
28}
29
30/// Structural bytecode validation error categories.
31#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
32#[serde(rename_all = "kebab-case")]
33pub enum ValidationErrorKind {
34    /// A proto id does not refer to an existing proto.
35    InvalidProtoReference,
36    /// A string id does not refer to the string table or the empty string.
37    InvalidStringReference,
38    /// A constant id does not refer to the proto constant table.
39    InvalidConstantReference,
40    /// An instruction has the wrong static AUX arity for its opcode.
41    InvalidAuxArity,
42    /// An AUX payload references impossible data.
43    InvalidAuxPayload,
44    /// A jump target is outside the proto or lands inside an AUX word.
45    InvalidJumpTarget,
46    /// A register operand exceeds the proto stack size.
47    InvalidRegister,
48    /// Line info is malformed for the proto instruction words.
49    InvalidLineInfo,
50    /// Debug info is malformed for the proto.
51    InvalidDebugInfo,
52    /// Feedback metadata is malformed for the proto.
53    InvalidFeedbackSlot,
54    /// Closure capture instructions do not match the referenced child proto.
55    InvalidClosureCapture,
56    /// Proto metadata is malformed.
57    InvalidProtoMetadata,
58}
59
60/// Returns all structural validation errors in `chunk`.
61#[must_use]
62pub fn validate_chunk(chunk: &BytecodeChunk) -> Vec<ValidationError> {
63    validate_chunk_inner(chunk).errors
64}
65
66#[cfg(test)]
67fn validate_chunk_with_boundary_probe_count(
68    chunk: &BytecodeChunk,
69) -> (Vec<ValidationError>, usize) {
70    let result = validate_chunk_inner(chunk);
71    (result.errors, result.boundary_probes)
72}
73
74fn validate_chunk_inner(chunk: &BytecodeChunk) -> ValidationResult {
75    let BytecodeChunk::Valid {
76        strings,
77        userdata_type_mappings,
78        protos,
79        main_proto,
80        ..
81    } = chunk
82    else {
83        return ValidationResult {
84            errors: Vec::new(),
85            #[cfg(test)]
86            boundary_probes: 0,
87        };
88    };
89
90    let mut validator = Validator {
91        strings,
92        protos,
93        errors: Vec::new(),
94        #[cfg(test)]
95        boundary_probes: 0,
96    };
97
98    if !proto_id_is_valid(*main_proto, protos) {
99        validator.push_chunk(
100            ValidationErrorKind::InvalidProtoReference,
101            format!(
102                "main proto id {main_proto} is outside {} protos",
103                protos.len()
104            ),
105        );
106    }
107
108    for mapping in userdata_type_mappings {
109        validator.check_string_id(None, None, mapping.name, "userdata type mapping name");
110    }
111
112    for (proto_index, proto) in protos.iter().enumerate() {
113        validator.validate_proto(proto_index, proto);
114    }
115
116    ValidationResult {
117        errors: validator.errors,
118        #[cfg(test)]
119        boundary_probes: validator.boundary_probes,
120    }
121}
122
123struct ValidationResult {
124    errors: Vec<ValidationError>,
125    #[cfg(test)]
126    boundary_probes: usize,
127}
128
129struct Validator<'a> {
130    strings: &'a [Vec<u8>],
131    protos: &'a [Proto],
132    errors: Vec<ValidationError>,
133    #[cfg(test)]
134    boundary_probes: usize,
135}
136
137struct InstructionBoundaryIndex {
138    word_offsets: Vec<u32>,
139    instruction_words: Vec<bool>,
140    code_words: u32,
141    #[cfg(test)]
142    probes: Cell<usize>,
143}
144
145impl InstructionBoundaryIndex {
146    fn new(code: &[Instruction]) -> Result<Self, &'static str> {
147        let mut word_offsets = Vec::with_capacity(code.len());
148        let mut next_word = 0u32;
149        for instruction in code {
150            word_offsets.push(next_word);
151            next_word = next_word
152                .checked_add(instruction.word_len())
153                .ok_or("proto code is too large")?;
154        }
155
156        let word_count = usize::try_from(next_word).map_err(|_| "proto code is too large")?;
157        let mut instruction_words = vec![false; word_count];
158        for &word in &word_offsets {
159            let word = usize::try_from(word).map_err(|_| "proto code is too large")?;
160            instruction_words[word] = true;
161        }
162
163        Ok(Self {
164            word_offsets,
165            instruction_words,
166            code_words: next_word,
167            #[cfg(test)]
168            probes: Cell::new(0),
169        })
170    }
171
172    fn code_words(&self) -> u32 {
173        self.code_words
174    }
175
176    fn word_offset(&self, instruction_index: usize) -> Option<u32> {
177        self.word_offsets.get(instruction_index).copied()
178    }
179
180    fn is_instruction_word(&self, word: u32) -> bool {
181        #[cfg(test)]
182        self.record_probe();
183
184        self.contains_instruction_word(word)
185    }
186
187    fn is_instruction_word_i32(&self, word: i32) -> bool {
188        #[cfg(test)]
189        self.record_probe();
190
191        let Ok(word) = u32::try_from(word) else {
192            return false;
193        };
194        self.contains_instruction_word(word)
195    }
196
197    fn contains_instruction_word(&self, word: u32) -> bool {
198        let Ok(word) = usize::try_from(word) else {
199            return false;
200        };
201        self.instruction_words.get(word).copied().unwrap_or(false)
202    }
203
204    #[cfg(test)]
205    fn record_probe(&self) {
206        self.probes.set(self.probes.get() + 1);
207    }
208
209    #[cfg(test)]
210    fn probe_count(&self) -> usize {
211        self.probes.get()
212    }
213}
214
215#[derive(Clone, Copy, Debug, Eq, PartialEq)]
216enum RegisterPolicy {
217    None,
218    FastCall0,
219    FastCall1,
220    FastCall2,
221    FastCall3,
222    Capture,
223    Call,
224    Return,
225    NameCall,
226    NumericFor,
227    GenericForLoop,
228    LoadNil,
229    SetList,
230    CompareJump,
231    A,
232    AB,
233    #[allow(clippy::upper_case_acronyms)]
234    ABC,
235    AC,
236}
237
238#[derive(Clone, Copy, Debug, Eq, PartialEq)]
239enum ReferencePolicy {
240    None,
241    DConstant,
242    LoadKx,
243    AuxStringConstant,
244    NewClosureChild,
245    DupClosureConstant,
246    CConstant,
247    BConstant,
248    FastCall2K,
249    JumpXEqKConstant,
250    CallFb,
251    BUpvalue,
252}
253
254fn register_policy(opcode: Opcode) -> RegisterPolicy {
255    match opcode {
256        Opcode::Nop
257        | Opcode::Break
258        | Opcode::Jump
259        | Opcode::JumpBack
260        | Opcode::Coverage
261        | Opcode::NativeCall
262        | Opcode::ForGPrepInext
263        | Opcode::ForGPrepNext
264        | Opcode::ForGPrep
265        | Opcode::PrepVarargs
266        | Opcode::JumpX => RegisterPolicy::None,
267        Opcode::FastCall => RegisterPolicy::FastCall0,
268        Opcode::FastCall1 => RegisterPolicy::FastCall1,
269        Opcode::FastCall2 | Opcode::FastCall2K => RegisterPolicy::FastCall2,
270        Opcode::FastCall3 => RegisterPolicy::FastCall3,
271        Opcode::Capture => RegisterPolicy::Capture,
272        Opcode::Call | Opcode::CallFb => RegisterPolicy::Call,
273        Opcode::Return => RegisterPolicy::Return,
274        Opcode::NameCall | Opcode::NameCallUdata => RegisterPolicy::NameCall,
275        Opcode::ForNPrep | Opcode::ForNLoop => RegisterPolicy::NumericFor,
276        Opcode::ForGLoop => RegisterPolicy::GenericForLoop,
277        Opcode::LoadNil => RegisterPolicy::LoadNil,
278        Opcode::SetList => RegisterPolicy::SetList,
279        Opcode::LoadB
280        | Opcode::LoadN
281        | Opcode::LoadK
282        | Opcode::GetGlobal
283        | Opcode::SetGlobal
284        | Opcode::GetUpval
285        | Opcode::SetUpval
286        | Opcode::CloseUpvals
287        | Opcode::GetImport
288        | Opcode::GetVarargs
289        | Opcode::NewClosure
290        | Opcode::DupClosure
291        | Opcode::LoadKx
292        | Opcode::NewTable
293        | Opcode::DupTable
294        | Opcode::JumpIf
295        | Opcode::JumpIfNot
296        | Opcode::JumpXEqKNil
297        | Opcode::JumpXEqKB
298        | Opcode::JumpXEqKN
299        | Opcode::JumpXEqKS
300        | Opcode::CmpProto
301        | Opcode::NewClassMember
302        | Opcode::GetUdataKs
303        | Opcode::SetUdataKs => RegisterPolicy::A,
304        Opcode::Move
305        | Opcode::GetTableKs
306        | Opcode::SetTableKs
307        | Opcode::GetTableN
308        | Opcode::SetTableN
309        | Opcode::Not
310        | Opcode::Minus
311        | Opcode::Length
312        | Opcode::And
313        | Opcode::Or
314        | Opcode::AndK
315        | Opcode::OrK
316        | Opcode::AddK
317        | Opcode::SubK
318        | Opcode::MulK
319        | Opcode::DivK
320        | Opcode::ModK
321        | Opcode::PowK
322        | Opcode::IDivK => RegisterPolicy::AB,
323        Opcode::GetTable
324        | Opcode::SetTable
325        | Opcode::Add
326        | Opcode::Sub
327        | Opcode::Mul
328        | Opcode::Div
329        | Opcode::Mod
330        | Opcode::Pow
331        | Opcode::IDiv
332        | Opcode::Concat => RegisterPolicy::ABC,
333        Opcode::JumpIfEq
334        | Opcode::JumpIfLe
335        | Opcode::JumpIfLt
336        | Opcode::JumpIfNotEq
337        | Opcode::JumpIfNotLe
338        | Opcode::JumpIfNotLt => RegisterPolicy::CompareJump,
339        Opcode::SubRk | Opcode::DivRk => RegisterPolicy::AC,
340    }
341}
342
343fn reference_policy(opcode: Opcode) -> ReferencePolicy {
344    match opcode {
345        Opcode::Nop
346        | Opcode::Break
347        | Opcode::LoadNil
348        | Opcode::LoadB
349        | Opcode::LoadN
350        | Opcode::Move
351        | Opcode::CloseUpvals
352        | Opcode::GetImport
353        | Opcode::GetTable
354        | Opcode::SetTable
355        | Opcode::GetTableN
356        | Opcode::SetTableN
357        | Opcode::Call
358        | Opcode::Return
359        | Opcode::Jump
360        | Opcode::JumpBack
361        | Opcode::JumpIf
362        | Opcode::JumpIfNot
363        | Opcode::JumpIfEq
364        | Opcode::JumpIfLe
365        | Opcode::JumpIfLt
366        | Opcode::JumpIfNotEq
367        | Opcode::JumpIfNotLe
368        | Opcode::JumpIfNotLt
369        | Opcode::Add
370        | Opcode::Sub
371        | Opcode::Mul
372        | Opcode::Div
373        | Opcode::Mod
374        | Opcode::Pow
375        | Opcode::And
376        | Opcode::Or
377        | Opcode::Concat
378        | Opcode::Not
379        | Opcode::Minus
380        | Opcode::Length
381        | Opcode::NewTable
382        | Opcode::DupTable
383        | Opcode::SetList
384        | Opcode::ForNPrep
385        | Opcode::ForNLoop
386        | Opcode::ForGLoop
387        | Opcode::ForGPrepInext
388        | Opcode::FastCall3
389        | Opcode::ForGPrepNext
390        | Opcode::NativeCall
391        | Opcode::GetVarargs
392        | Opcode::PrepVarargs
393        | Opcode::JumpX
394        | Opcode::FastCall
395        | Opcode::FastCall1
396        | Opcode::FastCall2
397        | Opcode::Coverage
398        | Opcode::Capture
399        | Opcode::ForGPrep
400        | Opcode::JumpXEqKNil
401        | Opcode::JumpXEqKB
402        | Opcode::IDiv
403        | Opcode::CmpProto => ReferencePolicy::None,
404        Opcode::LoadK => ReferencePolicy::DConstant,
405        Opcode::DupClosure => ReferencePolicy::DupClosureConstant,
406        Opcode::LoadKx => ReferencePolicy::LoadKx,
407        Opcode::GetGlobal
408        | Opcode::SetGlobal
409        | Opcode::GetTableKs
410        | Opcode::SetTableKs
411        | Opcode::NameCall
412        | Opcode::GetUdataKs
413        | Opcode::SetUdataKs
414        | Opcode::NameCallUdata
415        | Opcode::NewClassMember => ReferencePolicy::AuxStringConstant,
416        Opcode::NewClosure => ReferencePolicy::NewClosureChild,
417        Opcode::AddK
418        | Opcode::SubK
419        | Opcode::MulK
420        | Opcode::DivK
421        | Opcode::ModK
422        | Opcode::PowK
423        | Opcode::AndK
424        | Opcode::OrK
425        | Opcode::IDivK => ReferencePolicy::CConstant,
426        Opcode::FastCall2K => ReferencePolicy::FastCall2K,
427        Opcode::JumpXEqKN | Opcode::JumpXEqKS => ReferencePolicy::JumpXEqKConstant,
428        Opcode::SubRk | Opcode::DivRk => ReferencePolicy::BConstant,
429        Opcode::CallFb => ReferencePolicy::CallFb,
430        Opcode::GetUpval | Opcode::SetUpval => ReferencePolicy::BUpvalue,
431    }
432}
433
434impl Validator<'_> {
435    fn validate_proto(&mut self, proto_index: usize, proto: &Proto) {
436        if proto.num_params > proto.max_stack_size {
437            self.push_proto(
438                proto_index,
439                ValidationErrorKind::InvalidProtoMetadata,
440                format!(
441                    "num_params {} exceeds max_stack_size {}",
442                    proto.num_params, proto.max_stack_size
443                ),
444            );
445        }
446
447        self.check_string_id(Some(proto_index), None, proto.debug_name, "debug name");
448        for child in &proto.child_protos {
449            if !proto_id_is_valid(*child, self.protos) {
450                self.push_proto(
451                    proto_index,
452                    ValidationErrorKind::InvalidProtoReference,
453                    format!(
454                        "child proto id {child} is outside {} protos",
455                        self.protos.len()
456                    ),
457                );
458            }
459        }
460
461        for (constant_index, constant) in proto.constants.iter().enumerate() {
462            self.validate_constant(proto_index, proto, constant_index, constant);
463        }
464
465        let boundaries = match InstructionBoundaryIndex::new(&proto.code) {
466            Ok(boundaries) => boundaries,
467            Err(message) => {
468                self.push_proto(
469                    proto_index,
470                    ValidationErrorKind::InvalidProtoMetadata,
471                    message.to_owned(),
472                );
473                return;
474            }
475        };
476        let code_words = boundaries.code_words();
477        for (instruction_index, instruction) in proto.code.iter().enumerate() {
478            self.validate_instruction(
479                proto_index,
480                proto,
481                &boundaries,
482                instruction_index,
483                instruction,
484            );
485        }
486
487        if let Some(line_info) = &proto.line_info {
488            if line_info.delta_bytes.len() as u32 != code_words {
489                self.push_proto(
490                    proto_index,
491                    ValidationErrorKind::InvalidLineInfo,
492                    format!(
493                        "line info has {} deltas for {code_words} instruction words",
494                        line_info.delta_bytes.len()
495                    ),
496                );
497            }
498            match line_info.to_line_numbers() {
499                Some(lines) if lines.len() as u32 == code_words => {}
500                Some(lines) => self.push_proto(
501                    proto_index,
502                    ValidationErrorKind::InvalidLineInfo,
503                    format!(
504                        "line info decodes to {} lines for {code_words} instruction words",
505                        lines.len()
506                    ),
507                ),
508                None => self.push_proto(
509                    proto_index,
510                    ValidationErrorKind::InvalidLineInfo,
511                    "line info does not decode".to_owned(),
512                ),
513            }
514        }
515
516        if let Some(debug_info) = &proto.debug_info {
517            if debug_info.upvalues.len() != usize::from(proto.num_upvalues) {
518                self.push_proto(
519                    proto_index,
520                    ValidationErrorKind::InvalidDebugInfo,
521                    format!(
522                        "debug info has {} upvalues for proto num_upvalues {}",
523                        debug_info.upvalues.len(),
524                        proto.num_upvalues
525                    ),
526                );
527            }
528            for name in &debug_info.upvalues {
529                self.check_string_id(Some(proto_index), None, *name, "debug upvalue name");
530            }
531            for local in &debug_info.locals {
532                self.check_string_id(Some(proto_index), None, local.name, "debug local name");
533                self.check_register(
534                    Some(proto_index),
535                    None,
536                    proto,
537                    local.register,
538                    "debug local",
539                );
540                if local.start_pc > local.end_pc || local.end_pc > code_words {
541                    self.push_proto(
542                        proto_index,
543                        ValidationErrorKind::InvalidDebugInfo,
544                        format!(
545                            "debug local pc range {}..{} is outside 0..{code_words}",
546                            local.start_pc, local.end_pc
547                        ),
548                    );
549                }
550            }
551        }
552
553        for (slot_index, slot) in proto.feedback_slots.iter().enumerate() {
554            if !boundaries.is_instruction_word(slot.pc) {
555                self.push_proto(
556                    proto_index,
557                    ValidationErrorKind::InvalidFeedbackSlot,
558                    format!(
559                        "feedback slot {slot_index} pc {} is not an instruction",
560                        slot.pc
561                    ),
562                );
563            }
564        }
565
566        self.validate_closure_captures(proto_index, proto);
567
568        #[cfg(test)]
569        {
570            self.boundary_probes += boundaries.probe_count();
571        }
572    }
573
574    fn validate_constant(
575        &mut self,
576        proto_index: usize,
577        proto: &Proto,
578        constant_index: usize,
579        constant: &Constant,
580    ) {
581        match constant {
582            Constant::Nil
583            | Constant::Boolean { .. }
584            | Constant::Number { .. }
585            | Constant::Vector { .. }
586            | Constant::Integer { .. } => {}
587            Constant::String { string } => {
588                self.check_string_id(Some(proto_index), None, *string, "string constant");
589            }
590            Constant::Import { import_id } => {
591                let count = import_id >> IMPORT_PATH_COUNT_SHIFT;
592                if !(1..=3).contains(&count) {
593                    self.push_proto(
594                        proto_index,
595                        ValidationErrorKind::InvalidConstantReference,
596                        format!("import constant {constant_index} has path count {count}"),
597                    );
598                    return;
599                }
600                for index in 0..count {
601                    let constant_id =
602                        (import_id >> import_component_shift(index)) & IMPORT_PATH_COMPONENT_MASK;
603                    self.check_string_constant_id(
604                        proto_index,
605                        proto,
606                        constant_id,
607                        "import path component",
608                    );
609                }
610            }
611            Constant::Table { keys } => {
612                for key in keys {
613                    self.check_constant_id(proto_index, proto, *key, "table key");
614                }
615            }
616            Constant::Closure { proto } => {
617                if !proto_id_is_valid(*proto, self.protos) {
618                    self.push_proto(
619                        proto_index,
620                        ValidationErrorKind::InvalidProtoReference,
621                        format!(
622                            "closure constant {constant_index} proto id {proto} is outside {} protos",
623                            self.protos.len()
624                        ),
625                    );
626                }
627            }
628            Constant::TableWithConstants { entries } => {
629                for entry in entries {
630                    self.check_constant_id(
631                        proto_index,
632                        proto,
633                        entry.key,
634                        "table-with-constants key",
635                    );
636                    if entry.value >= 0 {
637                        self.check_constant_id(
638                            proto_index,
639                            proto,
640                            entry.value as u32,
641                            "table-with-constants value",
642                        );
643                    }
644                }
645            }
646            Constant::ClassShape { shape } => {
647                self.check_string_constant_id(
648                    proto_index,
649                    proto,
650                    shape.class_name,
651                    "class shape name",
652                );
653                for name in &shape.property_names {
654                    self.check_string_constant_id(
655                        proto_index,
656                        proto,
657                        *name,
658                        "class shape property",
659                    );
660                }
661                for name in &shape.method_names {
662                    self.check_string_constant_id(proto_index, proto, *name, "class shape method");
663                }
664            }
665        }
666    }
667
668    fn validate_instruction(
669        &mut self,
670        proto_index: usize,
671        proto: &Proto,
672        boundaries: &InstructionBoundaryIndex,
673        instruction_index: usize,
674        instruction: &Instruction,
675    ) {
676        let expected_aux = instruction.opcode.instruction_len() - 1;
677        if usize::from(instruction.aux.is_some()) != expected_aux {
678            self.push_instruction(
679                proto_index,
680                instruction_index,
681                ValidationErrorKind::InvalidAuxArity,
682                format!(
683                    "{:?} has {} AUX words, expected {expected_aux}",
684                    instruction.opcode,
685                    usize::from(instruction.aux.is_some())
686                ),
687            );
688            return;
689        }
690
691        let code_words = boundaries.code_words();
692        if let Some(target) = invalid_jump_target(&proto.code, boundaries, instruction_index) {
693            self.push_instruction(
694                proto_index,
695                instruction_index,
696                ValidationErrorKind::InvalidJumpTarget,
697                format!(
698                    "{:?} jumps to word {target}, outside instruction boundaries 0..{code_words}",
699                    instruction.opcode
700                ),
701            );
702        }
703
704        self.validate_register_operands(proto_index, proto, instruction_index, instruction);
705        self.validate_instruction_references(proto_index, proto, instruction_index, instruction);
706    }
707
708    fn validate_register_operands(
709        &mut self,
710        proto_index: usize,
711        proto: &Proto,
712        instruction_index: usize,
713        instruction: &Instruction,
714    ) {
715        let policy = register_policy(instruction.opcode);
716        match policy {
717            RegisterPolicy::None | RegisterPolicy::FastCall0 | RegisterPolicy::Capture => {}
718            RegisterPolicy::FastCall1 => {
719                self.check_register(
720                    Some(proto_index),
721                    Some(instruction_index),
722                    proto,
723                    instruction.b,
724                    "fastcall argument",
725                );
726            }
727            RegisterPolicy::FastCall2 => {
728                self.check_register(
729                    Some(proto_index),
730                    Some(instruction_index),
731                    proto,
732                    instruction.b,
733                    "fastcall first argument",
734                );
735            }
736            RegisterPolicy::FastCall3 => {
737                self.check_register(
738                    Some(proto_index),
739                    Some(instruction_index),
740                    proto,
741                    instruction.b,
742                    "fastcall first argument",
743                );
744                if let Some(aux) = instruction.aux {
745                    self.check_register(
746                        Some(proto_index),
747                        Some(instruction_index),
748                        proto,
749                        (aux & 0xff) as u8,
750                        "fastcall second argument",
751                    );
752                    self.check_register(
753                        Some(proto_index),
754                        Some(instruction_index),
755                        proto,
756                        ((aux >> 8) & 0xff) as u8,
757                        "fastcall third argument",
758                    );
759                }
760            }
761            RegisterPolicy::Call => {
762                self.check_register(
763                    Some(proto_index),
764                    Some(instruction_index),
765                    proto,
766                    instruction.a,
767                    "call function",
768                );
769                self.check_register_range(
770                    Some(proto_index),
771                    Some(instruction_index),
772                    proto,
773                    instruction.a,
774                    instruction.b.saturating_sub(1),
775                    "call arguments",
776                );
777                if instruction.c > 0 {
778                    self.check_register_range(
779                        Some(proto_index),
780                        Some(instruction_index),
781                        proto,
782                        instruction.a,
783                        instruction.c.saturating_sub(1),
784                        "call results",
785                    );
786                }
787            }
788            RegisterPolicy::Return => {
789                self.check_register_range(
790                    Some(proto_index),
791                    Some(instruction_index),
792                    proto,
793                    instruction.a,
794                    instruction.b.saturating_sub(1),
795                    "return values",
796                );
797            }
798            RegisterPolicy::NameCall => {
799                self.check_register_range(
800                    Some(proto_index),
801                    Some(instruction_index),
802                    proto,
803                    instruction.a,
804                    2,
805                    "namecall output",
806                );
807                self.check_register(
808                    Some(proto_index),
809                    Some(instruction_index),
810                    proto,
811                    instruction.b,
812                    "namecall receiver",
813                );
814            }
815            RegisterPolicy::NumericFor => {
816                self.check_register_range(
817                    Some(proto_index),
818                    Some(instruction_index),
819                    proto,
820                    instruction.a,
821                    3,
822                    "numeric for registers",
823                );
824            }
825            RegisterPolicy::GenericForLoop => {
826                let variable_count = instruction.aux.map_or(0, generic_for_loop_variable_count);
827                self.check_register_range(
828                    Some(proto_index),
829                    Some(instruction_index),
830                    proto,
831                    instruction.a,
832                    variable_count.saturating_add(3),
833                    "generic for registers",
834                );
835            }
836            RegisterPolicy::LoadNil => {
837                self.check_register_range(
838                    Some(proto_index),
839                    Some(instruction_index),
840                    proto,
841                    instruction.a,
842                    instruction.b.saturating_add(1),
843                    "loadnil range",
844                );
845            }
846            RegisterPolicy::SetList => {
847                self.check_register(
848                    Some(proto_index),
849                    Some(instruction_index),
850                    proto,
851                    instruction.a,
852                    "setlist table",
853                );
854                if instruction.c > 0 {
855                    self.check_register_range(
856                        Some(proto_index),
857                        Some(instruction_index),
858                        proto,
859                        instruction.b,
860                        instruction.c.saturating_sub(1),
861                        "setlist values",
862                    );
863                } else {
864                    self.check_register(
865                        Some(proto_index),
866                        Some(instruction_index),
867                        proto,
868                        instruction.b,
869                        "setlist first value",
870                    );
871                }
872            }
873            RegisterPolicy::CompareJump => {
874                self.check_register(
875                    Some(proto_index),
876                    Some(instruction_index),
877                    proto,
878                    instruction.a,
879                    "compare jump left operand",
880                );
881                if let Some(aux) = instruction.aux {
882                    self.check_register_u32(
883                        Some(proto_index),
884                        Some(instruction_index),
885                        proto,
886                        aux,
887                        "compare jump right operand",
888                    );
889                }
890            }
891            RegisterPolicy::A | RegisterPolicy::AB | RegisterPolicy::ABC | RegisterPolicy::AC => {
892                let operands: &[(u8, &str)] = match policy {
893                    RegisterPolicy::A => &[(instruction.a, "A operand")],
894                    RegisterPolicy::AB => {
895                        &[(instruction.a, "A operand"), (instruction.b, "B operand")]
896                    }
897                    RegisterPolicy::ABC => &[
898                        (instruction.a, "A operand"),
899                        (instruction.b, "B operand"),
900                        (instruction.c, "C operand"),
901                    ],
902                    RegisterPolicy::AC => {
903                        &[(instruction.a, "A operand"), (instruction.c, "C operand")]
904                    }
905                    _ => unreachable!("outer arm covers only the register-operand policies"),
906                };
907                for (register, label) in operands {
908                    self.check_register(
909                        Some(proto_index),
910                        Some(instruction_index),
911                        proto,
912                        *register,
913                        label,
914                    );
915                }
916            }
917        }
918    }
919
920    fn validate_instruction_references(
921        &mut self,
922        proto_index: usize,
923        proto: &Proto,
924        instruction_index: usize,
925        instruction: &Instruction,
926    ) {
927        match reference_policy(instruction.opcode) {
928            ReferencePolicy::None => {}
929            ReferencePolicy::DConstant => {
930                self.check_constant_id(
931                    proto_index,
932                    proto,
933                    instruction.d as u16 as u32,
934                    "D constant operand",
935                );
936            }
937            ReferencePolicy::LoadKx => {
938                if let Some(constant) = instruction.aux {
939                    self.check_constant_id(proto_index, proto, constant, "LOADKX constant");
940                }
941            }
942            ReferencePolicy::AuxStringConstant => {
943                if let Some(string) = instruction.aux {
944                    self.check_string_constant_id(proto_index, proto, string, "string AUX");
945                }
946            }
947            ReferencePolicy::NewClosureChild => {
948                let child_index = instruction.d as u16 as usize;
949                if child_index >= proto.child_protos.len() {
950                    self.push_instruction(
951                        proto_index,
952                        instruction_index,
953                        ValidationErrorKind::InvalidProtoReference,
954                        format!(
955                            "NEWCLOSURE child index {child_index} outside {} child protos",
956                            proto.child_protos.len()
957                        ),
958                    );
959                }
960            }
961            ReferencePolicy::DupClosureConstant => {
962                let constant_id = instruction.d as u16 as u32;
963                self.check_constant_id(proto_index, proto, constant_id, "D closure constant");
964                if !matches!(
965                    proto.constants.get(constant_id as usize),
966                    Some(Constant::Closure { .. })
967                ) {
968                    self.push_instruction(
969                        proto_index,
970                        instruction_index,
971                        ValidationErrorKind::InvalidConstantReference,
972                        format!("D closure constant id {constant_id} is not a closure constant"),
973                    );
974                }
975            }
976            ReferencePolicy::CConstant => {
977                self.check_constant_id(
978                    proto_index,
979                    proto,
980                    instruction.c as u32,
981                    "C constant operand",
982                );
983            }
984            ReferencePolicy::FastCall2K => {
985                if let Some(constant) = instruction.aux {
986                    self.check_constant_id(proto_index, proto, constant, "fastcall constant AUX");
987                }
988            }
989            ReferencePolicy::JumpXEqKConstant => {
990                if let Some(constant) = instruction.aux {
991                    self.check_constant_id(
992                        proto_index,
993                        proto,
994                        constant & JUMPX_K_INDEX_MASK,
995                        "jump constant AUX",
996                    );
997                }
998            }
999            ReferencePolicy::BConstant => {
1000                self.check_constant_id(
1001                    proto_index,
1002                    proto,
1003                    instruction.b as u32,
1004                    "B constant operand",
1005                );
1006            }
1007            ReferencePolicy::CallFb => {
1008                if let Some(slot) = instruction.aux
1009                    && slot as usize >= proto.feedback_slots.len()
1010                {
1011                    self.push_instruction(
1012                        proto_index,
1013                        instruction_index,
1014                        ValidationErrorKind::InvalidFeedbackSlot,
1015                        format!(
1016                            "CALLFB slot {slot} outside {} feedback slots",
1017                            proto.feedback_slots.len()
1018                        ),
1019                    );
1020                }
1021            }
1022            ReferencePolicy::BUpvalue => {
1023                self.check_upvalue(
1024                    proto_index,
1025                    instruction_index,
1026                    proto,
1027                    instruction.b,
1028                    "B upvalue operand",
1029                );
1030            }
1031        }
1032
1033        self.validate_opcode_specific_payload(proto_index, proto, instruction_index, instruction);
1034    }
1035
1036    fn validate_opcode_specific_payload(
1037        &mut self,
1038        proto_index: usize,
1039        proto: &Proto,
1040        instruction_index: usize,
1041        instruction: &Instruction,
1042    ) {
1043        if matches!(
1044            instruction.opcode,
1045            Opcode::FastCall
1046                | Opcode::FastCall1
1047                | Opcode::FastCall2
1048                | Opcode::FastCall2K
1049                | Opcode::FastCall3
1050        ) {
1051            if instruction.a == BuiltinFunction::NONE
1052                || instruction.a > BuiltinFunction::BUFFER_WRITEINTEGER
1053            {
1054                self.push_instruction(
1055                    proto_index,
1056                    instruction_index,
1057                    ValidationErrorKind::InvalidAuxPayload,
1058                    format!("fastcall builtin id {} is invalid", instruction.a),
1059                );
1060            }
1061            if instruction.c == 0 {
1062                self.push_instruction(
1063                    proto_index,
1064                    instruction_index,
1065                    ValidationErrorKind::InvalidJumpTarget,
1066                    "fastcall skip offset is zero".to_owned(),
1067                );
1068            }
1069        }
1070
1071        if instruction.opcode == Opcode::Capture {
1072            let Some(capture_type) = CaptureType::from_byte(instruction.a) else {
1073                self.push_instruction(
1074                    proto_index,
1075                    instruction_index,
1076                    ValidationErrorKind::InvalidAuxPayload,
1077                    format!("capture kind {} is invalid", instruction.a),
1078                );
1079                return;
1080            };
1081            match capture_type {
1082                CaptureType::Val | CaptureType::Ref => self.check_register(
1083                    Some(proto_index),
1084                    Some(instruction_index),
1085                    proto,
1086                    instruction.b,
1087                    "capture source",
1088                ),
1089                CaptureType::Upval => self.check_upvalue(
1090                    proto_index,
1091                    instruction_index,
1092                    proto,
1093                    instruction.b,
1094                    "capture source upvalue",
1095                ),
1096            }
1097        }
1098    }
1099
1100    fn validate_closure_captures(&mut self, proto_index: usize, proto: &Proto) {
1101        let mut expected_capture = vec![false; proto.code.len()];
1102        for (instruction_index, instruction) in proto.code.iter().enumerate() {
1103            let Some(child_proto_id) = self.closure_child_proto_id(proto_index, proto, instruction)
1104            else {
1105                continue;
1106            };
1107            let Some(child_proto) = self.protos.get(child_proto_id as usize) else {
1108                continue;
1109            };
1110            let expected = usize::from(child_proto.num_upvalues);
1111            for capture_offset in 0..expected {
1112                let capture_index = instruction_index + 1 + capture_offset;
1113                let Some(capture) = proto.code.get(capture_index) else {
1114                    self.push_instruction(
1115                        proto_index,
1116                        instruction_index,
1117                        ValidationErrorKind::InvalidClosureCapture,
1118                        format!(
1119                            "{:?} for child proto {child_proto_id} expects {expected} capture instruction(s), but code ended after {capture_offset}",
1120                            instruction.opcode
1121                        ),
1122                    );
1123                    break;
1124                };
1125                if capture.opcode != Opcode::Capture {
1126                    self.push_instruction(
1127                        proto_index,
1128                        capture_index,
1129                        ValidationErrorKind::InvalidClosureCapture,
1130                        format!(
1131                            "{:?} for child proto {child_proto_id} expects CAPTURE at instruction {capture_index}, found {:?}",
1132                            instruction.opcode, capture.opcode
1133                        ),
1134                    );
1135                    break;
1136                }
1137                expected_capture[capture_index] = true;
1138            }
1139        }
1140
1141        for (instruction_index, instruction) in proto.code.iter().enumerate() {
1142            if instruction.opcode == Opcode::Capture && !expected_capture[instruction_index] {
1143                self.push_instruction(
1144                    proto_index,
1145                    instruction_index,
1146                    ValidationErrorKind::InvalidClosureCapture,
1147                    "CAPTURE instruction is not attached to a closure instruction".to_owned(),
1148                );
1149            }
1150        }
1151    }
1152
1153    fn closure_child_proto_id(
1154        &self,
1155        _proto_index: usize,
1156        proto: &Proto,
1157        instruction: &Instruction,
1158    ) -> Option<u32> {
1159        match instruction.opcode {
1160            Opcode::NewClosure => proto
1161                .child_protos
1162                .get(instruction.d as u16 as usize)
1163                .copied(),
1164            Opcode::DupClosure => {
1165                let constant_id = instruction.d as u16 as usize;
1166                match proto.constants.get(constant_id) {
1167                    Some(Constant::Closure { proto }) => Some(*proto),
1168                    _ => None,
1169                }
1170            }
1171            _ => None,
1172        }
1173    }
1174
1175    fn check_constant_id(&mut self, proto_index: usize, proto: &Proto, id: u32, context: &str) {
1176        if id as usize >= proto.constants.len() {
1177            self.push_proto(
1178                proto_index,
1179                ValidationErrorKind::InvalidConstantReference,
1180                format!(
1181                    "{context} constant id {id} is outside {} constants",
1182                    proto.constants.len()
1183                ),
1184            );
1185        }
1186    }
1187
1188    fn check_string_constant_id(
1189        &mut self,
1190        proto_index: usize,
1191        proto: &Proto,
1192        id: u32,
1193        context: &str,
1194    ) {
1195        let Some(constant) = proto.constants.get(id as usize) else {
1196            self.push_proto(
1197                proto_index,
1198                ValidationErrorKind::InvalidConstantReference,
1199                format!(
1200                    "{context} string constant id {id} is outside {} constants",
1201                    proto.constants.len()
1202                ),
1203            );
1204            return;
1205        };
1206        if !matches!(constant, Constant::String { .. }) {
1207            self.push_proto(
1208                proto_index,
1209                ValidationErrorKind::InvalidConstantReference,
1210                format!("{context} constant id {id} is not a string constant"),
1211            );
1212        }
1213    }
1214
1215    fn check_string_id(
1216        &mut self,
1217        proto_index: Option<usize>,
1218        instruction_index: Option<usize>,
1219        id: u32,
1220        context: &str,
1221    ) {
1222        if id as usize > self.strings.len() {
1223            self.push(
1224                proto_index,
1225                instruction_index,
1226                ValidationErrorKind::InvalidStringReference,
1227                format!(
1228                    "{context} string id {id} is outside {} strings",
1229                    self.strings.len()
1230                ),
1231            );
1232        }
1233    }
1234
1235    fn check_register(
1236        &mut self,
1237        proto_index: Option<usize>,
1238        instruction_index: Option<usize>,
1239        proto: &Proto,
1240        register: u8,
1241        context: &str,
1242    ) {
1243        if register >= proto.max_stack_size {
1244            self.push(
1245                proto_index,
1246                instruction_index,
1247                ValidationErrorKind::InvalidRegister,
1248                format!(
1249                    "{context} register {register} exceeds max_stack_size {}",
1250                    proto.max_stack_size
1251                ),
1252            );
1253        }
1254    }
1255
1256    fn check_register_range(
1257        &mut self,
1258        proto_index: Option<usize>,
1259        instruction_index: Option<usize>,
1260        proto: &Proto,
1261        start: u8,
1262        count: u8,
1263        context: &str,
1264    ) {
1265        if count == 0 {
1266            return;
1267        }
1268        let end = u16::from(start) + u16::from(count) - 1;
1269        if end >= u16::from(proto.max_stack_size) {
1270            self.push(
1271                proto_index,
1272                instruction_index,
1273                ValidationErrorKind::InvalidRegister,
1274                format!(
1275                    "{context} register range {start}..={end} exceeds max_stack_size {}",
1276                    proto.max_stack_size
1277                ),
1278            );
1279        }
1280    }
1281
1282    fn check_register_u32(
1283        &mut self,
1284        proto_index: Option<usize>,
1285        instruction_index: Option<usize>,
1286        proto: &Proto,
1287        register: u32,
1288        context: &str,
1289    ) {
1290        if register >= u32::from(proto.max_stack_size) {
1291            self.push(
1292                proto_index,
1293                instruction_index,
1294                ValidationErrorKind::InvalidRegister,
1295                format!(
1296                    "{context} register {register} exceeds max_stack_size {}",
1297                    proto.max_stack_size
1298                ),
1299            );
1300        }
1301    }
1302
1303    fn check_upvalue(
1304        &mut self,
1305        proto_index: usize,
1306        instruction_index: usize,
1307        proto: &Proto,
1308        upvalue: u8,
1309        context: &str,
1310    ) {
1311        if upvalue >= proto.num_upvalues {
1312            self.push_instruction(
1313                proto_index,
1314                instruction_index,
1315                ValidationErrorKind::InvalidProtoMetadata,
1316                format!(
1317                    "{context} {upvalue} exceeds proto num_upvalues {}",
1318                    proto.num_upvalues
1319                ),
1320            );
1321        }
1322    }
1323
1324    fn push_chunk(&mut self, kind: ValidationErrorKind, message: String) {
1325        self.push(None, None, kind, message);
1326    }
1327
1328    fn push_proto(&mut self, proto_index: usize, kind: ValidationErrorKind, message: String) {
1329        self.push(Some(proto_index), None, kind, message);
1330    }
1331
1332    fn push_instruction(
1333        &mut self,
1334        proto_index: usize,
1335        instruction_index: usize,
1336        kind: ValidationErrorKind,
1337        message: String,
1338    ) {
1339        self.push(Some(proto_index), Some(instruction_index), kind, message);
1340    }
1341
1342    fn push(
1343        &mut self,
1344        proto_index: Option<usize>,
1345        instruction_index: Option<usize>,
1346        kind: ValidationErrorKind,
1347        message: String,
1348    ) {
1349        self.errors.push(ValidationError {
1350            proto_index,
1351            instruction_index,
1352            kind,
1353            message,
1354        });
1355    }
1356}
1357
1358fn invalid_jump_target(
1359    code: &[Instruction],
1360    boundaries: &InstructionBoundaryIndex,
1361    instruction_index: usize,
1362) -> Option<i32> {
1363    let instruction = code.get(instruction_index)?;
1364    instruction.jump_offset_words()?;
1365    let source_word = boundaries.word_offset(instruction_index)?;
1366    let target = instruction.jump_target_word(source_word)?;
1367    let code_words = boundaries.code_words();
1368    if u32::try_from(target).ok() == Some(code_words) {
1369        return None;
1370    }
1371    (!boundaries.is_instruction_word_i32(target)).then_some(target)
1372}
1373
1374fn proto_id_is_valid(proto: u32, protos: &[Proto]) -> bool {
1375    (proto as usize) < protos.len()
1376}
1377
1378fn generic_for_loop_variable_count(aux: u32) -> u8 {
1379    (aux & !FORGLOOP_INEXT_BIT).min(u32::from(u8::MAX)) as u8
1380}
1381
1382#[cfg(test)]
1383mod tests {
1384    use crate::{
1385        BytecodeChunk, CompileOptions, Constant, FeedbackSlot, Instruction, LineInfo, Proto,
1386        TypeInfo, compile_source,
1387        opcodes::{BuiltinFunction, CaptureType, FeedbackType, Opcode},
1388        validate::ValidationErrorKind,
1389        validate_chunk,
1390    };
1391
1392    #[test]
1393    fn accepts_minimal_valid_chunk() {
1394        let chunk = BytecodeChunk::Valid {
1395            bytecode_version: 6,
1396            type_version: 3,
1397            strings: Vec::new(),
1398            userdata_type_mappings: Vec::new(),
1399            userdata_mapping_terminator: 0,
1400            protos: vec![minimal_proto()],
1401            main_proto: 0,
1402        };
1403
1404        assert_eq!(validate_chunk(&chunk), Vec::new());
1405    }
1406
1407    #[test]
1408    fn accepts_empty_source_zero_stack_proto() {
1409        let chunk = compile_source("", &CompileOptions::default()).expect("compile empty source");
1410
1411        assert_eq!(validate_chunk(&chunk), Vec::new());
1412    }
1413
1414    #[test]
1415    fn accepts_numeric_for_three_register_window() {
1416        let chunk = compile_source("for i=2,1 do\nend", &CompileOptions::default())
1417            .expect("compile numeric for");
1418
1419        assert_eq!(validate_chunk(&chunk), Vec::new());
1420    }
1421
1422    #[test]
1423    fn accepts_generic_for_aux_variable_count() {
1424        let chunk = compile_source("for key in pairs(x) do end", &CompileOptions::default())
1425            .expect("compile generic for");
1426
1427        assert_eq!(validate_chunk(&chunk), Vec::new());
1428    }
1429
1430    #[test]
1431    fn rejects_invalid_main_proto_reference() {
1432        let chunk = BytecodeChunk::Valid {
1433            bytecode_version: 6,
1434            type_version: 3,
1435            strings: Vec::new(),
1436            userdata_type_mappings: Vec::new(),
1437            userdata_mapping_terminator: 0,
1438            protos: vec![minimal_proto()],
1439            main_proto: 7,
1440        };
1441
1442        let errors = validate_chunk(&chunk);
1443        assert!(
1444            errors
1445                .iter()
1446                .any(|error| error.kind == ValidationErrorKind::InvalidProtoReference)
1447        );
1448    }
1449
1450    #[test]
1451    fn accepts_unreachable_but_valid_protos() {
1452        let chunk = BytecodeChunk::Valid {
1453            bytecode_version: 6,
1454            type_version: 3,
1455            strings: Vec::new(),
1456            userdata_type_mappings: Vec::new(),
1457            userdata_mapping_terminator: 0,
1458            protos: vec![minimal_proto(), minimal_proto()],
1459            main_proto: 1,
1460        };
1461
1462        assert_eq!(validate_chunk(&chunk), Vec::new());
1463    }
1464
1465    #[test]
1466    fn rejects_jump_into_nowhere() {
1467        let mut proto = minimal_proto();
1468        proto.code = vec![Instruction::ad(Opcode::Jump, 0, 99)];
1469        let chunk = BytecodeChunk::Valid {
1470            bytecode_version: 6,
1471            type_version: 3,
1472            strings: Vec::new(),
1473            userdata_type_mappings: Vec::new(),
1474            userdata_mapping_terminator: 0,
1475            protos: vec![proto],
1476            main_proto: 0,
1477        };
1478
1479        let errors = validate_chunk(&chunk);
1480        assert!(
1481            errors
1482                .iter()
1483                .any(|error| error.kind == ValidationErrorKind::InvalidJumpTarget)
1484        );
1485    }
1486
1487    #[test]
1488    fn accepts_jump_to_end_boundary() {
1489        let mut proto = minimal_proto();
1490        proto.code = vec![
1491            Instruction::ad(Opcode::Jump, 0, 1),
1492            Instruction::abc(Opcode::Return, 0, 1, 0),
1493        ];
1494        let chunk = BytecodeChunk::Valid {
1495            bytecode_version: 6,
1496            type_version: 3,
1497            strings: Vec::new(),
1498            userdata_type_mappings: Vec::new(),
1499            userdata_mapping_terminator: 0,
1500            protos: vec![proto],
1501            main_proto: 0,
1502        };
1503
1504        assert_eq!(validate_chunk(&chunk), Vec::new());
1505    }
1506
1507    #[test]
1508    fn rejects_jump_into_aux_word() {
1509        let mut proto = minimal_proto();
1510        proto.constants = vec![Constant::Nil];
1511        proto.code = vec![
1512            Instruction::ad(Opcode::Jump, 0, 1),
1513            Instruction::abc_with_aux(Opcode::LoadKx, 0, 0, 0, Some(0)),
1514            Instruction::abc(Opcode::Return, 0, 1, 0),
1515        ];
1516
1517        let errors = validate_chunk(&chunk_with_proto(proto));
1518        assert!(
1519            errors
1520                .iter()
1521                .any(|error| error.kind == ValidationErrorKind::InvalidJumpTarget)
1522        );
1523    }
1524
1525    #[test]
1526    fn jump_target_boundary_checks_are_linear() {
1527        const JUMP_COUNT: usize = 4096;
1528
1529        let mut proto = minimal_proto();
1530        proto.code = (0..JUMP_COUNT)
1531            .map(|_| Instruction::ad(Opcode::Jump, 0, i16::MAX))
1532            .collect();
1533
1534        let (errors, probes) =
1535            super::validate_chunk_with_boundary_probe_count(&chunk_with_proto(proto));
1536        assert_eq!(
1537            errors
1538                .iter()
1539                .filter(|error| error.kind == ValidationErrorKind::InvalidJumpTarget)
1540                .count(),
1541            JUMP_COUNT
1542        );
1543        assert!(
1544            probes <= JUMP_COUNT,
1545            "jump target validation used {probes} boundary probes for {JUMP_COUNT} jumps"
1546        );
1547    }
1548
1549    #[test]
1550    fn feedback_slot_boundary_checks_are_linear() {
1551        const SLOT_COUNT: usize = 4096;
1552
1553        let mut proto = minimal_proto();
1554        proto.feedback_slots = (0..SLOT_COUNT)
1555            .map(|pc| FeedbackSlot {
1556                kind: FeedbackType::CallTarget,
1557                pc: pc as u32 + 1,
1558            })
1559            .collect();
1560
1561        let (errors, probes) =
1562            super::validate_chunk_with_boundary_probe_count(&chunk_with_proto(proto));
1563        assert_eq!(
1564            errors
1565                .iter()
1566                .filter(|error| error.kind == ValidationErrorKind::InvalidFeedbackSlot)
1567                .count(),
1568            SLOT_COUNT
1569        );
1570        assert!(
1571            probes <= SLOT_COUNT,
1572            "feedback validation used {probes} boundary probes for {SLOT_COUNT} slots"
1573        );
1574    }
1575
1576    #[test]
1577    fn rejects_invalid_constant_reference() {
1578        let mut proto = minimal_proto();
1579        proto.constants = vec![Constant::Table { keys: vec![7] }];
1580        let chunk = BytecodeChunk::Valid {
1581            bytecode_version: 6,
1582            type_version: 3,
1583            strings: Vec::new(),
1584            userdata_type_mappings: Vec::new(),
1585            userdata_mapping_terminator: 0,
1586            protos: vec![proto],
1587            main_proto: 0,
1588        };
1589
1590        let errors = validate_chunk(&chunk);
1591        assert!(
1592            errors
1593                .iter()
1594                .any(|error| error.kind == ValidationErrorKind::InvalidConstantReference)
1595        );
1596    }
1597
1598    #[test]
1599    fn rejects_line_info_length_mismatch() {
1600        let mut proto = minimal_proto();
1601        proto.line_info = Some(LineInfo {
1602            log2_span: 0,
1603            delta_bytes: Vec::new(),
1604            baseline_deltas: Vec::new(),
1605        });
1606        let chunk = BytecodeChunk::Valid {
1607            bytecode_version: 6,
1608            type_version: 3,
1609            strings: Vec::new(),
1610            userdata_type_mappings: Vec::new(),
1611            userdata_mapping_terminator: 0,
1612            protos: vec![proto],
1613            main_proto: 0,
1614        };
1615
1616        let errors = validate_chunk(&chunk);
1617        assert!(
1618            errors
1619                .iter()
1620                .any(|error| error.kind == ValidationErrorKind::InvalidLineInfo)
1621        );
1622    }
1623
1624    #[test]
1625    fn setlist_values_start_at_b_register() {
1626        let mut proto = minimal_proto();
1627        proto.max_stack_size = 21;
1628        proto.code = vec![
1629            Instruction::abc_with_aux(Opcode::SetList, 7, 12, 4, Some(1)),
1630            Instruction::abc(Opcode::Return, 0, 1, 0),
1631        ];
1632        let chunk = BytecodeChunk::Valid {
1633            bytecode_version: 6,
1634            type_version: 3,
1635            strings: Vec::new(),
1636            userdata_type_mappings: Vec::new(),
1637            userdata_mapping_terminator: 0,
1638            protos: vec![proto],
1639            main_proto: 0,
1640        };
1641
1642        assert_eq!(validate_chunk(&chunk), Vec::new());
1643    }
1644
1645    #[test]
1646    fn rk_arithmetic_uses_b_as_constant_and_c_as_register() {
1647        let mut proto = minimal_proto();
1648        proto.max_stack_size = 11;
1649        proto.constants = vec![Constant::Nil, Constant::Nil, Constant::Nil, Constant::Nil];
1650        proto.code = vec![
1651            Instruction::abc(Opcode::SubRk, 10, 3, 9),
1652            Instruction::abc(Opcode::Return, 0, 1, 0),
1653        ];
1654        let chunk = BytecodeChunk::Valid {
1655            bytecode_version: 6,
1656            type_version: 3,
1657            strings: Vec::new(),
1658            userdata_type_mappings: Vec::new(),
1659            userdata_mapping_terminator: 0,
1660            protos: vec![proto],
1661            main_proto: 0,
1662        };
1663
1664        assert_eq!(validate_chunk(&chunk), Vec::new());
1665
1666        let BytecodeChunk::Valid { protos, .. } = &chunk else {
1667            unreachable!("test chunk is valid")
1668        };
1669        let mut div_proto = protos[0].clone();
1670        div_proto.code[0] = Instruction::abc(Opcode::DivRk, 10, 3, 9);
1671        let chunk = BytecodeChunk::Valid {
1672            bytecode_version: 6,
1673            type_version: 3,
1674            strings: Vec::new(),
1675            userdata_type_mappings: Vec::new(),
1676            userdata_mapping_terminator: 0,
1677            protos: vec![div_proto],
1678            main_proto: 0,
1679        };
1680        assert_eq!(validate_chunk(&chunk), Vec::new());
1681    }
1682
1683    #[test]
1684    fn compare_jumps_use_d_offset_and_aux_register() {
1685        let mut proto = minimal_proto();
1686        proto.max_stack_size = 2;
1687        proto.code = vec![
1688            Instruction::abc_with_aux(Opcode::JumpIfNotLt, 0, 3, 0, Some(1)),
1689            Instruction::ad(Opcode::LoadN, 0, 0),
1690            Instruction::ad(Opcode::LoadN, 0, 0),
1691            Instruction::abc(Opcode::Return, 0, 1, 0),
1692        ];
1693        let chunk = BytecodeChunk::Valid {
1694            bytecode_version: 6,
1695            type_version: 3,
1696            strings: Vec::new(),
1697            userdata_type_mappings: Vec::new(),
1698            userdata_mapping_terminator: 0,
1699            protos: vec![proto],
1700            main_proto: 0,
1701        };
1702
1703        assert_eq!(validate_chunk(&chunk), Vec::new());
1704
1705        let BytecodeChunk::Valid { protos, .. } = &chunk else {
1706            unreachable!("test chunk is valid")
1707        };
1708        let mut invalid_proto = protos[0].clone();
1709        invalid_proto.code[0] = Instruction::abc_with_aux(Opcode::JumpIfNotLt, 0, 3, 0, Some(2));
1710        let invalid = BytecodeChunk::Valid {
1711            bytecode_version: 6,
1712            type_version: 3,
1713            strings: Vec::new(),
1714            userdata_type_mappings: Vec::new(),
1715            userdata_mapping_terminator: 0,
1716            protos: vec![invalid_proto],
1717            main_proto: 0,
1718        };
1719
1720        let errors = validate_chunk(&invalid);
1721        assert!(
1722            errors
1723                .iter()
1724                .any(|error| error.kind == ValidationErrorKind::InvalidRegister)
1725        );
1726    }
1727
1728    #[test]
1729    fn jumpx_eqk_aux_masks_not_flag_from_constant_id() {
1730        let mut proto = minimal_proto();
1731        proto.max_stack_size = 1;
1732        proto.constants = vec![Constant::Number {
1733            bits: 1.0f64.to_bits(),
1734        }];
1735        proto.code = vec![
1736            Instruction::abc_with_aux(Opcode::JumpXEqKN, 0, 1, 0, Some(0x8000_0000)),
1737            Instruction::abc(Opcode::Return, 0, 1, 0),
1738        ];
1739        let chunk = BytecodeChunk::Valid {
1740            bytecode_version: 6,
1741            type_version: 3,
1742            strings: Vec::new(),
1743            userdata_type_mappings: Vec::new(),
1744            userdata_mapping_terminator: 0,
1745            protos: vec![proto],
1746            main_proto: 0,
1747        };
1748
1749        assert_eq!(validate_chunk(&chunk), Vec::new());
1750
1751        let BytecodeChunk::Valid { protos, .. } = &chunk else {
1752            unreachable!("test chunk is valid")
1753        };
1754        let mut invalid_proto = protos[0].clone();
1755        invalid_proto.code[0] =
1756            Instruction::abc_with_aux(Opcode::JumpXEqKN, 0, 1, 0, Some(0x0100_0001));
1757        let invalid = BytecodeChunk::Valid {
1758            bytecode_version: 6,
1759            type_version: 3,
1760            strings: Vec::new(),
1761            userdata_type_mappings: Vec::new(),
1762            userdata_mapping_terminator: 0,
1763            protos: vec![invalid_proto],
1764            main_proto: 0,
1765        };
1766
1767        let errors = validate_chunk(&invalid);
1768        assert!(
1769            errors
1770                .iter()
1771                .any(|error| error.kind == ValidationErrorKind::InvalidConstantReference)
1772        );
1773    }
1774
1775    #[test]
1776    fn opcode_policy_covers_every_opcode() {
1777        for byte in 0..Opcode::COUNT {
1778            let opcode = Opcode::from_byte(byte).expect("opcode below COUNT");
1779            let _ = super::register_policy(opcode);
1780            let _ = super::reference_policy(opcode);
1781        }
1782        assert!(Opcode::from_byte(Opcode::COUNT).is_none());
1783    }
1784
1785    #[test]
1786    fn rejects_upvalue_operands_outside_proto_upvalue_count() {
1787        let mut proto = minimal_proto();
1788        proto.max_stack_size = 2;
1789        proto.num_upvalues = 1;
1790        proto.code = vec![
1791            Instruction::abc(Opcode::GetUpval, 0, 1, 0),
1792            Instruction::abc(Opcode::Return, 0, 1, 0),
1793        ];
1794        let chunk = BytecodeChunk::Valid {
1795            bytecode_version: 6,
1796            type_version: 3,
1797            strings: Vec::new(),
1798            userdata_type_mappings: Vec::new(),
1799            userdata_mapping_terminator: 0,
1800            protos: vec![proto],
1801            main_proto: 0,
1802        };
1803
1804        let errors = validate_chunk(&chunk);
1805        assert!(
1806            errors
1807                .iter()
1808                .any(|error| error.kind == ValidationErrorKind::InvalidProtoMetadata)
1809        );
1810    }
1811
1812    #[test]
1813    fn closure_instruction_requires_child_capture_count() {
1814        let mut root = minimal_proto();
1815        root.max_stack_size = 2;
1816        root.child_protos = vec![1];
1817        root.code = vec![
1818            Instruction::ad(Opcode::NewClosure, 0, 0),
1819            Instruction::abc(Opcode::Return, 0, 1, 0),
1820        ];
1821        let mut child = minimal_proto();
1822        child.num_upvalues = 1;
1823        let chunk = BytecodeChunk::Valid {
1824            bytecode_version: 6,
1825            type_version: 3,
1826            strings: Vec::new(),
1827            userdata_type_mappings: Vec::new(),
1828            userdata_mapping_terminator: 0,
1829            protos: vec![root, child],
1830            main_proto: 0,
1831        };
1832
1833        let errors = validate_chunk(&chunk);
1834        assert!(
1835            errors
1836                .iter()
1837                .any(|error| error.kind == ValidationErrorKind::InvalidClosureCapture)
1838        );
1839    }
1840
1841    #[test]
1842    fn closure_capture_sources_are_checked() {
1843        let mut root = minimal_proto();
1844        root.max_stack_size = 2;
1845        root.child_protos = vec![1];
1846        root.code = vec![
1847            Instruction::ad(Opcode::NewClosure, 0, 0),
1848            Instruction::abc(Opcode::Capture, CaptureType::Val as u8, 2, 0),
1849            Instruction::abc(Opcode::Return, 0, 1, 0),
1850        ];
1851        let mut child = minimal_proto();
1852        child.num_upvalues = 1;
1853        let chunk = BytecodeChunk::Valid {
1854            bytecode_version: 6,
1855            type_version: 3,
1856            strings: Vec::new(),
1857            userdata_type_mappings: Vec::new(),
1858            userdata_mapping_terminator: 0,
1859            protos: vec![root, child],
1860            main_proto: 0,
1861        };
1862
1863        let errors = validate_chunk(&chunk);
1864        assert!(
1865            errors
1866                .iter()
1867                .any(|error| error.kind == ValidationErrorKind::InvalidRegister)
1868        );
1869    }
1870
1871    #[test]
1872    fn rejects_invalid_fastcall_builtin_ids() {
1873        let mut proto = minimal_proto();
1874        proto.max_stack_size = 2;
1875        proto.code = vec![
1876            Instruction::abc(Opcode::FastCall1, 0, 0, 1),
1877            Instruction::abc(Opcode::Return, 0, 1, 0),
1878        ];
1879        let chunk = BytecodeChunk::Valid {
1880            bytecode_version: 6,
1881            type_version: 3,
1882            strings: Vec::new(),
1883            userdata_type_mappings: Vec::new(),
1884            userdata_mapping_terminator: 0,
1885            protos: vec![proto],
1886            main_proto: 0,
1887        };
1888
1889        let errors = validate_chunk(&chunk);
1890        assert!(
1891            errors
1892                .iter()
1893                .any(|error| error.kind == ValidationErrorKind::InvalidAuxPayload)
1894        );
1895    }
1896
1897    #[test]
1898    fn fastcall_aux_registers_are_checked() {
1899        let mut proto = minimal_proto();
1900        proto.max_stack_size = 2;
1901        proto.code = vec![
1902            Instruction::abc_with_aux(
1903                Opcode::FastCall3,
1904                BuiltinFunction::MATH_MAX,
1905                0,
1906                1,
1907                Some(1 | (2 << 8)),
1908            ),
1909            Instruction::abc(Opcode::Return, 0, 1, 0),
1910        ];
1911        let chunk = BytecodeChunk::Valid {
1912            bytecode_version: 6,
1913            type_version: 3,
1914            strings: Vec::new(),
1915            userdata_type_mappings: Vec::new(),
1916            userdata_mapping_terminator: 0,
1917            protos: vec![proto],
1918            main_proto: 0,
1919        };
1920
1921        let errors = validate_chunk(&chunk);
1922        assert!(
1923            errors
1924                .iter()
1925                .any(|error| error.kind == ValidationErrorKind::InvalidRegister)
1926        );
1927    }
1928
1929    #[test]
1930    fn loadkx_aux_constant_is_checked() {
1931        let mut proto = minimal_proto();
1932        proto.max_stack_size = 2;
1933        proto.code = vec![
1934            Instruction::abc_with_aux(Opcode::LoadKx, 0, 0, 0, Some(7)),
1935            Instruction::abc(Opcode::Return, 0, 1, 0),
1936        ];
1937        let chunk = BytecodeChunk::Valid {
1938            bytecode_version: 6,
1939            type_version: 3,
1940            strings: Vec::new(),
1941            userdata_type_mappings: Vec::new(),
1942            userdata_mapping_terminator: 0,
1943            protos: vec![proto],
1944            main_proto: 0,
1945        };
1946
1947        let errors = validate_chunk(&chunk);
1948        assert!(
1949            errors
1950                .iter()
1951                .any(|error| error.kind == ValidationErrorKind::InvalidConstantReference)
1952        );
1953    }
1954
1955    #[test]
1956    fn callfb_aux_feedback_slot_is_checked() {
1957        let mut proto = minimal_proto();
1958        proto.max_stack_size = 2;
1959        proto.feedback_slots = vec![FeedbackSlot {
1960            kind: FeedbackType::CallTarget,
1961            pc: 0,
1962        }];
1963        proto.code = vec![
1964            Instruction::abc_with_aux(Opcode::CallFb, 0, 1, 1, Some(1)),
1965            Instruction::abc(Opcode::Return, 0, 1, 0),
1966        ];
1967        let chunk = BytecodeChunk::Valid {
1968            bytecode_version: 11,
1969            type_version: 3,
1970            strings: Vec::new(),
1971            userdata_type_mappings: Vec::new(),
1972            userdata_mapping_terminator: 0,
1973            protos: vec![proto],
1974            main_proto: 0,
1975        };
1976
1977        let errors = validate_chunk(&chunk);
1978        assert!(
1979            errors
1980                .iter()
1981                .any(|error| error.kind == ValidationErrorKind::InvalidFeedbackSlot)
1982        );
1983    }
1984
1985    #[test]
1986    fn class_and_userdata_string_aux_references_are_checked() {
1987        let mut proto = minimal_proto();
1988        proto.max_stack_size = 2;
1989        proto.constants = vec![Constant::Nil];
1990        proto.code = vec![
1991            Instruction::abc_with_aux(Opcode::NameCallUdata, 0, 1, 0, Some(0)),
1992            Instruction::abc_with_aux(Opcode::NewClassMember, 0, 0, 0, Some(0)),
1993            Instruction::abc(Opcode::Return, 0, 1, 0),
1994        ];
1995        let chunk = BytecodeChunk::Valid {
1996            bytecode_version: 6,
1997            type_version: 3,
1998            strings: Vec::new(),
1999            userdata_type_mappings: Vec::new(),
2000            userdata_mapping_terminator: 0,
2001            protos: vec![proto],
2002            main_proto: 0,
2003        };
2004
2005        let errors = validate_chunk(&chunk);
2006        assert!(
2007            errors
2008                .iter()
2009                .filter(|error| error.kind == ValidationErrorKind::InvalidConstantReference)
2010                .count()
2011                >= 2
2012        );
2013    }
2014
2015    fn chunk_with_proto(proto: Proto) -> BytecodeChunk {
2016        BytecodeChunk::Valid {
2017            bytecode_version: 11,
2018            type_version: 3,
2019            strings: Vec::new(),
2020            userdata_type_mappings: Vec::new(),
2021            userdata_mapping_terminator: 0,
2022            protos: vec![proto],
2023            main_proto: 0,
2024        }
2025    }
2026
2027    fn minimal_proto() -> Proto {
2028        Proto {
2029            max_stack_size: 1,
2030            num_params: 0,
2031            num_upvalues: 0,
2032            is_vararg: 0,
2033            flags: 0,
2034            type_info: TypeInfo { raw: Vec::new() },
2035            code: vec![Instruction::abc(Opcode::Return, 0, 1, 0)],
2036            constants: Vec::new(),
2037            child_protos: Vec::new(),
2038            line_defined: 0,
2039            debug_name: 0,
2040            line_info: None,
2041            debug_info: None,
2042            feedback_slots: Vec::new(),
2043        }
2044    }
2045}