1use super::{
3 format::{Format, Width},
4 invalid,
5};
6use crate::bytecode::Opcode;
7use crate::types::BaseVarType;
8use std::io::Result;
9
10#[derive(Clone, Debug)]
11pub struct Script {
12 pub name: String,
13 pub local_int_count: u16,
14 pub local_string_count: u16,
15 pub local_long_count: u16,
16 pub int_param_count: u16,
17 pub string_param_count: u16,
18 pub long_param_count: u16,
19 pub opcodes: Vec<u16>,
21 pub operations: Vec<Opcode>,
22 pub int_operands: Vec<i32>,
23 pub string_operands: Vec<Option<String>>,
24 pub long_operands: Vec<Option<i64>>,
25 pub switches: Vec<Vec<(i32, i32)>>,
26}
27
28pub fn is_branch(op: Opcode) -> bool {
29 matches!(
30 op,
31 Opcode::Branch
32 | Opcode::BranchNot
33 | Opcode::BranchEquals
34 | Opcode::BranchLessThan
35 | Opcode::BranchGreaterThan
36 | Opcode::BranchLessThanOrEquals
37 | Opcode::BranchGreaterThanOrEquals
38 | Opcode::LongBranchNot
39 | Opcode::LongBranchEquals
40 | Opcode::LongBranchLessThan
41 | Opcode::LongBranchGreaterThan
42 | Opcode::LongBranchLessThanOrEquals
43 | Opcode::LongBranchGreaterThanOrEquals
44 | Opcode::BranchIfTrue
45 | Opcode::BranchIfFalse
46 | Opcode::ObjBranchEquals
47 | Opcode::ObjBranchNot
48 )
49}
50
51struct Reader<'a> {
52 bytes: &'a [u8],
53 offset: usize,
54}
55impl<'a> Reader<'a> {
56 fn new(bytes: &'a [u8]) -> Self {
57 Self { bytes, offset: 0 }
58 }
59 fn take(&mut self, count: usize) -> Result<&'a [u8]> {
60 let end = self
61 .offset
62 .checked_add(count)
63 .ok_or_else(|| invalid("Byte offset overflow"))?;
64 let bytes = self.bytes.get(self.offset..end).ok_or_else(|| {
65 invalid(format!(
66 "Truncated bytecode at byte {}: expected {count} bytes",
67 self.offset
68 ))
69 })?;
70 self.offset = end;
71 Ok(bytes)
72 }
73 fn u8(&mut self) -> Result<u8> {
74 Ok(self.take(1)?[0])
75 }
76 fn u16(&mut self) -> Result<u16> {
77 Ok(u16::from_be_bytes(self.take(2)?.try_into().unwrap()))
78 }
79 fn i32(&mut self) -> Result<i32> {
80 Ok(i32::from_be_bytes(self.take(4)?.try_into().unwrap()))
81 }
82 fn i64(&mut self) -> Result<i64> {
83 Ok(i64::from_be_bytes(self.take(8)?.try_into().unwrap()))
84 }
85 fn string(&mut self) -> Result<String> {
86 let len = self.bytes[self.offset..]
87 .iter()
88 .position(|&byte| byte == 0)
89 .ok_or_else(|| invalid("Unterminated bytecode string"))?;
90 let bytes = self.take(len + 1)?;
91 const EXTENDED: [char; 32] = [
92 '€', '\u{81}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{8d}', 'Ž',
93 '\u{8f}', '\u{90}', '‘', '’', '“', '”', '•', '–', '—', '˜', '™', 'š', '›', 'œ',
94 '\u{9d}', 'ž', 'Ÿ',
95 ];
96 Ok(bytes[..len]
97 .iter()
98 .map(|&byte| {
99 if (128..160).contains(&byte) {
100 EXTENDED[(byte - 128) as usize]
101 } else {
102 byte as char
103 }
104 })
105 .collect())
106 }
107 fn finished(&self) -> Result<()> {
108 if self.offset == self.bytes.len() {
109 Ok(())
110 } else {
111 Err(invalid(format!(
112 "{} trailing bytecode bytes",
113 self.bytes.len() - self.offset
114 )))
115 }
116 }
117}
118
119impl Script {
120 pub fn decode(data: &[u8], format: &Format) -> Result<Self> {
121 let fixed = 4 + 4 * format.local_types.len();
122 let (metadata_end, switch_size) = if format.switches {
123 let tail = data
124 .get(data.len().saturating_sub(2)..)
125 .filter(|tail| tail.len() == 2)
126 .ok_or_else(|| invalid("Missing switch footer length"))?;
127 let size = u16::from_be_bytes(tail.try_into().unwrap()) as usize;
128 if size == 0 {
129 return Err(invalid("Missing switch count"));
130 }
131 (data.len() - 2, size)
132 } else {
133 (data.len(), 0)
134 };
135 let start = metadata_end
136 .checked_sub(fixed + switch_size)
137 .ok_or_else(|| invalid("Truncated bytecode footer"))?;
138 let mut metadata = Reader::new(&data[start..metadata_end]);
139 let count = metadata.i32()?;
140 if count < 0 || count as usize > start / 3 {
141 return Err(invalid(format!("Invalid instruction count {count}")));
142 }
143 let mut counts = [[0; 3]; 2];
144 for counts in &mut counts {
145 let mut seen = [false; 3];
146 for kind in &format.local_types {
147 let index = match kind {
148 BaseVarType::Integer => 0,
149 BaseVarType::String => 1,
150 BaseVarType::Long => 2,
151 };
152 if seen[index] {
153 return Err(invalid("Repeated local stack in format"));
154 }
155 seen[index] = true;
156 counts[index] = metadata.u16()?;
157 }
158 }
159 if (0..3).any(|i| counts[1][i] > counts[0][i]) {
160 return Err(invalid("Parameters exceed local counts"));
161 }
162 let mut switches = Vec::new();
163 if format.switches {
164 let tables = metadata.u8()?;
165 for _ in 0..tables {
166 let entries = metadata.u16()? as usize;
167 let mut table = Reader::new(metadata.take(entries * 8)?);
168 let mut cases = Vec::with_capacity(entries);
169 for _ in 0..entries {
170 cases.push((table.i32()?, table.i32()?));
171 }
172 switches.push(cases);
173 }
174 }
175 metadata.finished()?;
176 let mut code = Reader::new(&data[..start]);
177 let mut script = Self {
178 name: code.string()?,
179 local_int_count: counts[0][0],
180 local_string_count: counts[0][1],
181 local_long_count: counts[0][2],
182 int_param_count: counts[1][0],
183 string_param_count: counts[1][1],
184 long_param_count: counts[1][2],
185 opcodes: Vec::with_capacity(count as usize),
186 operations: Vec::with_capacity(count as usize),
187 int_operands: Vec::with_capacity(count as usize),
188 string_operands: Vec::with_capacity(count as usize),
189 long_operands: Vec::with_capacity(count as usize),
190 switches,
191 };
192 for pc in 0..count as usize {
193 let opcode = code.u16()?;
194 let (operation, width) = format
195 .decode(opcode)
196 .map_err(|error| invalid(format!("Instruction {pc}: {error}")))?;
197 let mut integer = 0;
198 let mut string = None;
199 let mut long = None;
200 match width {
201 Width::Byte => integer = code.u8()? as i32,
202 Width::Int => integer = code.i32()?,
203 Width::Long => long = Some(code.i64()?),
204 Width::String => string = Some(code.string()?),
205 }
206 script.opcodes.push(opcode);
207 script.operations.push(operation);
208 script.int_operands.push(integer);
209 script.string_operands.push(string);
210 script.long_operands.push(long);
211 }
212 code.finished()?;
213 for (pc, &operation) in script.operations.iter().enumerate() {
214 let operand = script.int_operands[pc];
215 let check_target = |offset: i32| -> Result<()> {
216 let target = pc as i64 + 1 + offset as i64;
217 if !(0..=count as i64).contains(&target) {
218 return Err(invalid(format!(
219 "Instruction {pc}: branch target {target} outside script"
220 )));
221 }
222 Ok(())
223 };
224 if is_branch(operation) {
225 check_target(operand)?;
226 }
227 if operation == Opcode::Switch {
228 let table = script.switches.get(operand as usize).ok_or_else(|| {
229 invalid(format!("Instruction {pc}: invalid switch table {operand}"))
230 })?;
231 for &(_, offset) in table {
232 check_target(offset)?;
233 }
234 }
235 let local = match operation {
236 Opcode::PushIntLocal | Opcode::PopIntLocal => Some(script.local_int_count),
237 Opcode::PushStringLocal | Opcode::PopStringLocal => Some(script.local_string_count),
238 Opcode::PushLongLocal | Opcode::PopLongLocal => Some(script.local_long_count),
239 _ => None,
240 };
241 if local.is_some_and(|count| operand < 0 || operand >= count as i32) {
242 return Err(invalid(format!(
243 "Instruction {pc}: local slot {operand} outside declared locals"
244 )));
245 }
246 }
247 Ok(script)
248 }
249}