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