Skip to main content

runec/clientscript/
decode.rs

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