1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
// SPDX-License-Identifier: GPL-3.0-only
//! Everything related to GML (GameMaker language) bytecode.
//!
//! DOCME: explain more.
pub mod analysis;
pub mod assembly;
pub mod instruction;
mod name_validation;
pub mod opcodes;
use std::ops::Range;
pub use crate::gml::instruction::Instruction;
use crate::prelude::*;
use crate::wad::elem::function::CodeLocal;
/// A code entry in a GameMaker data file.
#[derive(Debug, Clone, PartialEq)]
pub struct Code {
/// A mangled name for this code entry.
///
/// This will be something like `gml_Script_my_script123` or `gml_Object_my_object456_Step_0`.
/// The runner uses this name for stack traces in error messages.
/// Changing this name will not change the script name, event type or similar.
/// This name exists purely for debugging purposes.
/// It is not an asset name like sprites or objects have one.
/// In some cases, it can even be ambiguous (Collision events)!
/// A demangler is coming soon(TM).
pub name: GMRef<String>,
/// A list of VM instructions this code entry has.
///
/// This will be empty for child code entries.
/// The actual instructions will be stored in the referenced parent code.
pub instructions: Vec<Instruction>,
/// Extra data for WAD 15+.
pub modern_data: Option<ModernData>,
}
impl Code {
/// Find child code entries of this code entry.
///
/// This is always `false` before WAD 15, since child/parent code entries
/// did not exist then.
///
/// This function has to compare the names of code entries and is also
/// failable. If you have access to a [`GMRef`] to this code entry
/// instead, consider using [`Self::find_children`] instead.
///
/// This has to iterate over all code entries in the data file,
/// so it's a good idea to cache this if possible.
pub fn find_children_by_name(&self, data: &GMData) -> Result<Vec<GMRef<Self>>> {
if data.general_info.wad_version < 15 {
return Ok(Vec::new());
}
let mut children: Vec<GMRef<Self>> = Vec::new();
for (gmref, code_entry) in data.codes.element_refs() {
if !code_entry.is_root() {
continue;
}
let parent = data.codes.by_ref(code_entry.parent())?;
if self.name == parent.name {
children.push(gmref);
}
}
Ok(children)
}
/// Find child code entries of this code entry.
///
/// This is always `false` before WAD 15, since child/parent code entries
/// did not exist then.
///
/// This function takes a `GMRef<Code>` instead of `&Code`.
/// If you only have a [`Code`] available, you'll have to
/// use [`Self::find_children_by_name`] instead.
///
/// This has to iterate over all code entries in the data file,
/// so it's a good idea to cache this if possible.
#[must_use]
pub fn find_children(code_ref: GMRef<Self>, data: &GMData) -> Vec<GMRef<Self>> {
if data.general_info.wad_version < 15 || code_ref.is_none() {
return Vec::new();
}
let mut children: Vec<GMRef<Self>> = Vec::new();
for (gmref, code_entry) in data.codes.element_refs() {
if code_entry.parent() == code_ref {
children.push(gmref);
}
}
children
}
/// Gets the total (cumulative) size of all instructions, in bytes.
///
/// This function simply calls [`Instruction::size`] on each instruction and
/// sums up the sizes.
#[must_use]
pub fn length(&self) -> u32 {
instructions_size(&self.instructions)
}
/// The parent code entry of this code entry, if it has one.
///
/// This will always be [`GMRef::none`] for WAD < 15.
#[must_use]
pub const fn parent(&self) -> GMRef<Self> {
match &self.modern_data {
Some(data) => data.parent,
None => GMRef::none(),
}
}
/// Whether this code entry is a root entry, meaning it has no parent code
/// entries.
///
/// This will always be `true` for WAD < 15.
#[must_use]
pub const fn is_root(&self) -> bool {
self.parent().is_none()
}
/// The offset, **in bytes**, where code should begin
/// executing from within the bytecode of this code entry.
///
/// This will always be zero for root code entries and before WAD 15.
#[must_use]
pub const fn execution_offset(&self) -> u32 {
match &self.modern_data {
Some(data) => data.execution_offset,
None => 0,
}
}
}
impl GMData {
pub fn make_code(&mut self, name: &str, instructions: Vec<Instruction>) -> GMRef<Code> {
if let Ok(code) = self.codes.ref_by_name(name, &self.strings) {
return code;
}
let name = self.strings.make(name);
let modern_data = if self.general_info.wad_version >= 15 {
Some(ModernData::default())
} else {
None
};
let code = Code { name, instructions, modern_data };
let code_ref = self.codes.push(code);
self.functions
.code_locals
.push(CodeLocal { name, variables: Vec::new() });
code_ref
}
}
/// Extra data for code entries in WAD Version 15 and higher.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ModernData {
/// The amount of local variables this code entry has.
pub local_count: u16,
/// The amount of arguments this code entry accepts.
pub argument_count: u16,
/// A flag set on certain code entries, which usually don't have locals attached to them.
///
/// DOCME: more info pls
pub weird_local_flag: bool,
/// Offset, **in bytes**, where code should begin executing from within the
/// bytecode of this code entry. Should be 0 for root-level (parent)
/// code entries, and nonzero for child code entries.
pub execution_offset: u32,
/// Parent entry of this code entry, if this is a child entry,
pub parent: GMRef<Code>,
}
/// Gets the total (cumulative) size of all instructions, in bytes.
///
/// This function simply calls [`Instruction::size`] on each instruction and
/// sums up the sizes.
#[must_use]
pub fn instructions_size(instructions: &[Instruction]) -> u32 {
let mut size: u32 = 0;
for instruction in instructions {
size += instruction.size();
}
size
}
fn splice_instructions(
haystack: &mut Vec<Instruction>,
range: Range<u32>,
replace_with: &[Instruction],
needs_result: bool,
) -> Result<Option<Vec<Instruction>>> {
let start = range.start as usize;
let end = range.end as usize;
let len = haystack.len();
if start >= len {
bail!("Start index {start} out of bounds for vector with instruction count {len}");
}
if start > end {
bail!("Start index {start} is greater than the end index {end}");
}
let insertion_size = instructions_size(replace_with);
let removal_size = instructions_size(&haystack[start..end]);
let fixed_offset = (insertion_size - removal_size) as i32 / 4;
let first_half_size = instructions_size(&haystack[..start]) as i32 / 4;
let mut cur_pos: u32 = 0;
for (i, instr) in haystack.iter_mut().enumerate() {
// (this technically ignores stuff that is neither half 1 nor 2 if range is
// nonzero but it shouldnt make a different i think)
cur_pos += instr.size4();
let Some(offset) = instr.jump_offset_mut() else {
continue;
};
let branch_target_pos = cur_pos as i32 + *offset;
let origin_is_first_half = i < start;
let target_is_first_half = branch_target_pos < first_half_size;
// if branching withing their half, everything is fine.
if origin_is_first_half == target_is_first_half {
continue;
}
// branch crosses boundary; fix the jump offsets.
if origin_is_first_half {
*offset += fixed_offset;
} else {
*offset -= fixed_offset;
}
}
// now perform the actual splice
let iter = haystack.splice(start..end, replace_with.iter().cloned());
if needs_result {
Ok(Some(iter.collect()))
} else {
Ok(None)
}
}
pub fn insert_instructions(
haystack: &mut Vec<Instruction>,
index: u32,
insertion: &[Instruction],
) -> Result<()> {
splice_instructions(haystack, index..index, insertion, false).ctx(|| {
format!(
"inserting {} instructions at index {} into vector with {} instructions",
insertion.len(),
index,
haystack.len(),
)
})?;
Ok(())
}
pub fn insert_instruction(
haystack: &mut Vec<Instruction>,
index: u32,
insertion: &Instruction,
) -> Result<()> {
insert_instructions(haystack, index, std::slice::from_ref(insertion))
.ctx(|| format!("inserting single instruction {insertion:?}"))
}
#[allow(clippy::missing_panics_doc)]
pub fn remove_instructions(
haystack: &mut Vec<Instruction>,
range: Range<u32>,
) -> Result<Vec<Instruction>> {
let removal_len = range.len();
let index = range.start;
let old_instrs = splice_instructions(haystack, range, &[], true).ctx(|| {
format!(
"removing {} instructions at index {} of vector with {} instructions",
removal_len,
index,
haystack.len(),
)
})?;
Ok(old_instrs.unwrap())
}
pub fn remove_instruction(haystack: &mut Vec<Instruction>, index: u32) -> Result<Vec<Instruction>> {
remove_instructions(haystack, index..index + 1)
}