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