wirm 4.0.0-rc2

A lightweight WebAssembly Transformation Library for the Component Model
Documentation
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
//! Iterator to traverse a Module

use crate::ir::id::{FunctionID, GlobalID, LocalID};
use crate::ir::module::module_functions::FuncKind;
use crate::ir::module::module_globals::Global;
use crate::ir::module::Module;
use crate::ir::types::{DataType, FuncInstrMode, InjectedInstrs, InstrumentationMode, Location};
use crate::iterator::iterator_trait::{IteratingInstrumenter, Iterator};
use crate::module_builder::AddLocal;
use crate::opcode::{Inject, InjectAt, Instrumenter, MacroOpcode, Opcode};
use crate::subiterator::module_subiterator::ModuleSubIterator;
use wasmparser::Operator;

/// Iterator for a Module.
// 'b should outlive 'a
pub struct ModuleIterator<'a, 'b> {
    /// The Module to Iterate
    pub module: &'a mut Module<'b>,
    /// The SubIterator for this Module
    mod_iterator: ModuleSubIterator,
}

#[allow(dead_code)]
impl<'a, 'b> ModuleIterator<'a, 'b> {
    /// Creates a new ModuleIterator
    pub fn new(module: &'a mut Module<'b>, skip_funcs: &Vec<FunctionID>) -> Self {
        let metadata = module.get_func_metadata();
        ModuleIterator {
            module,
            mod_iterator: ModuleSubIterator::new(metadata, skip_funcs.to_owned()),
        }
    }

    pub fn curr_op_owned(&self) -> Option<Operator<'b>> {
        if let (
            Location::Module {
                func_idx,
                instr_idx,
                ..
            },
            ..,
        ) = self.mod_iterator.curr_loc()
        {
            match &self.module.functions.get(func_idx).kind {
                FuncKind::Import(_) => panic!(
                    "Internal error: Shouldn't have gotten the location of an imported function!"
                ),
                FuncKind::Local(l) => Some(l.body.instructions.get_ops()[instr_idx].clone()),
            }
        } else {
            panic!("Internal error: Should have gotten Module Location!")
        }
    }
}

impl<'b> Inject<'b> for ModuleIterator<'_, 'b> {
    /// Injects an Operator at the current location
    ///
    /// # Example
    /// ```no_run
    /// use wirm::ir::module::Module;
    /// use wirm::iterator::module_iterator::ModuleIterator;
    /// use wasmparser::Operator;
    /// use wirm::ir::types::{Location};
    /// use wirm::iterator::iterator_trait::{IteratingInstrumenter, Iterator};
    /// use wirm::opcode::{Instrumenter, Opcode};
    ///
    /// let file = "path_to_file";
    /// let buff = wat::parse_file(file).expect("couldn't convert the input wat to Wasm");
    /// // Must use `parse_only_module` here as we are only concerned about a Module and not a module that is inside a Component
    /// let mut module = Module::parse(&buff, false, false).expect("Unable to parse");
    /// let mut module_it = ModuleIterator::new(&mut module, &vec![]);
    ///
    /// // Everytime there is a `call 1` instruction we want to inject an `i32.const 0`
    /// let interested = Operator::Call { function_index: 1 };
    ///
    /// loop {
    ///     let op = module_it.curr_op();
    ///     let instr_mode = module_it.curr_instrument_mode();
    ///
    ///     if let Location::Module {
    ///         func_idx,
    ///         instr_idx,
    ///     } = module_it.curr_loc().0
    ///     {
    ///         if *module_it.curr_op().unwrap() == interested {
    ///             module_it.before().i32_const(1);
    ///         }
    ///         if module_it.next().is_none() {
    ///             break;
    ///         };
    ///     } else {
    ///         // Ensures we only get the location of a module while parsing a component
    ///         panic!("Should've gotten Module Location!");
    ///     }
    /// }
    /// ```
    fn inject(&mut self, instr: Operator<'b>) {
        if let (
            Location::Module {
                func_idx,
                instr_idx,
                ..
            },
            ..,
        ) = self.curr_loc()
        {
            match self.module.functions.get_mut(func_idx).kind {
                FuncKind::Import(_) => panic!(
                    "Internal error: Shouldn't have gotten the location of an imported function!"
                ),
                FuncKind::Local(ref mut l) => l.add_instr(instr, instr_idx),
            }
        } else {
            panic!("Internal error: Should have gotten Module Location!")
        }
    }
}
impl<'a> InjectAt<'a> for ModuleIterator<'_, 'a> {
    fn inject_at(&mut self, idx: usize, mode: InstrumentationMode, instr: Operator<'a>) {
        if let (Location::Module { func_idx, .. }, ..) = self.curr_loc() {
            let loc = Location::Module {
                func_idx,
                instr_idx: idx,
            };
            self.set_instrument_mode_at(mode, loc);
            self.add_instr_at(loc, instr);
        } else {
            panic!("Internal error: Should have gotten Module Location!")
        }
    }
}
impl<'a> Opcode<'a> for ModuleIterator<'_, 'a> {}
impl<'a> MacroOpcode<'a> for ModuleIterator<'_, 'a> {}
impl<'a> Instrumenter<'a> for ModuleIterator<'_, 'a> {
    ///Can be called after finishing some instrumentation to reset the mode.
    fn finish_instr(&mut self) {
        if let (
            Location::Module {
                func_idx,
                instr_idx,
                ..
            },
            ..,
        ) = self.mod_iterator.curr_loc()
        {
            match &mut self.module.functions.get_mut(func_idx).kind {
                FuncKind::Import(_) => panic!(
                    "Internal error: Shouldn't have gotten the location of an imported function!"
                ),
                FuncKind::Local(l) => {
                    l.instr_flag.finish_instr();
                    l.body.instructions.finish_instr(instr_idx);
                }
            }
        } else {
            panic!("Internal error: Should have gotten Module Location!")
        }
    }
    /// Returns the Instrumentation at the current Location
    fn curr_instrument_mode(&self) -> Option<InstrumentationMode> {
        if let (
            Location::Module {
                func_idx,
                instr_idx,
                ..
            },
            ..,
        ) = self.mod_iterator.curr_loc()
        {
            match &self.module.functions.get(func_idx).kind {
                FuncKind::Import(_) => panic!(
                    "Internal error: Shouldn't have gotten the location of an imported function!"
                ),
                FuncKind::Local(l) => l.body.instructions.current_mode(instr_idx),
            }
        } else {
            panic!("Internal error: Should have gotten Module Location!")
        }
    }

    fn set_instrument_mode_at(&mut self, mode: InstrumentationMode, loc: Location) {
        if let Location::Module {
            func_idx,
            instr_idx,
            ..
        } = loc
        {
            match self.module.functions.get_mut(func_idx).kind {
                FuncKind::Import(_) => panic!(
                    "Internal error: Shouldn't have gotten the location of an imported function!"
                ),
                FuncKind::Local(ref mut l) => {
                    l.body.instructions.set_current_mode(instr_idx, mode);
                }
            }
        } else {
            panic!("Internal error: Should have gotten Module Location!")
        }
    }

    fn curr_func_instrument_mode(&self) -> &Option<FuncInstrMode> {
        if let (Location::Module { func_idx, .. }, ..) = self.mod_iterator.curr_loc() {
            match &self.module.functions.get(func_idx).kind {
                FuncKind::Import(_) => panic!(
                    "Internal error: Shouldn't have gotten the location of an imported function!"
                ),
                FuncKind::Local(l) => &l.instr_flag.current_mode,
            }
        } else {
            panic!("Internal error: Should have gotten Module Location!")
        }
    }

    fn set_func_instrument_mode(&mut self, mode: FuncInstrMode) {
        if let (Location::Module { func_idx, .. }, ..) = self.mod_iterator.curr_loc() {
            match self.module.functions.get_mut(func_idx).kind {
                FuncKind::Import(_) => panic!(
                    "Internal error: Shouldn't have gotten the location of an imported function!"
                ),
                FuncKind::Local(ref mut l) => l.instr_flag.current_mode = Some(mode),
            }
        } else {
            panic!("Internal error: Should have gotten Module Location!")
        }
    }

    fn curr_instr_len(&self) -> usize {
        if let (
            Location::Module {
                func_idx,
                instr_idx,
                ..
            },
            ..,
        ) = self.mod_iterator.curr_loc()
        {
            match &self.module.functions.get(func_idx).kind {
                FuncKind::Import(_) => panic!(
                    "Internal error: Shouldn't have gotten the location of an imported function!"
                ),
                FuncKind::Local(l) => l.instr_len_at(instr_idx),
            }
        } else {
            panic!("Internal error: Should have gotten Module Location!")
        }
    }

    fn clear_instr_at(&mut self, loc: Location, mode: InstrumentationMode) {
        if let Location::Module {
            func_idx,
            instr_idx,
            ..
        } = loc
        {
            match self.module.functions.get_mut(func_idx).kind {
                FuncKind::Import(_) => panic!(
                    "Internal error: Shouldn't have gotten the location of an imported function!"
                ),
                FuncKind::Local(ref mut l) => {
                    l.clear_instr_at(instr_idx, mode);
                }
            }
        } else {
            panic!("Internal error: Should have gotten Module Location!")
        }
    }

    fn add_instr_at(&mut self, loc: Location, instr: Operator<'a>) {
        if let Location::Module {
            func_idx,
            instr_idx,
            ..
        } = loc
        {
            match self.module.functions.get_mut(func_idx).kind {
                FuncKind::Import(_) => panic!(
                    "Internal error: Shouldn't have gotten the location of an imported function!"
                ),
                FuncKind::Local(ref mut l) => {
                    l.add_instr(instr, instr_idx);
                }
            }
        } else {
            panic!("Internal error: Should have gotten Module Location!")
        }
    }

    fn empty_alternate_at(&mut self, loc: Location) -> &mut Self {
        if let Location::Module {
            func_idx,
            instr_idx,
            ..
        } = loc
        {
            match self.module.functions.get_mut(func_idx).kind {
                FuncKind::Import(_) => panic!(
                    "Internal error: Shouldn't have gotten the location of an imported function!"
                ),
                FuncKind::Local(ref mut l) => {
                    l.body
                        .instructions
                        .set_alternate(instr_idx, InjectedInstrs::default());
                }
            }
        } else {
            panic!("Internal error: Should have gotten Module Location!")
        }
        self
    }

    fn empty_block_alt_at(&mut self, loc: Location) -> &mut Self {
        if let Location::Module {
            func_idx,
            instr_idx,
            ..
        } = loc
        {
            match self.module.functions.get_mut(func_idx).kind {
                FuncKind::Import(_) => panic!(
                    "Internal error: Shouldn't have gotten the location of an imported function!"
                ),
                FuncKind::Local(ref mut l) => {
                    l.body
                        .instructions
                        .set_block_alt(instr_idx, InjectedInstrs::default());
                    l.instr_flag.has_special_instr |= true;
                }
            }
        } else {
            panic!("Internal error: Should have gotten Module Location!")
        }
        self
    }

    fn append_tag_at(&mut self, data: Vec<u8>, loc: Location) -> &mut Self {
        if let Location::Module {
            func_idx,
            instr_idx,
            ..
        } = loc
        {
            match self.module.functions.get_mut(func_idx).kind {
                FuncKind::Import(_) => panic!(
                    "Internal error: Shouldn't have gotten the location of an imported function!"
                ),
                FuncKind::Local(ref mut l) => {
                    l.append_instr_tag_at(data, instr_idx);
                }
            }
        } else {
            panic!("Internal error: Should have gotten Module Location!")
        }
        self
    }
}

impl<'a> IteratingInstrumenter<'a> for ModuleIterator<'_, 'a> {
    fn add_global(&mut self, global: Global) -> GlobalID {
        self.module.globals.add(global)
    }
}

impl AddLocal for ModuleIterator<'_, '_> {
    fn add_local(&mut self, val_type: DataType) -> LocalID {
        let curr_loc = self.curr_loc();
        if let (Location::Module { func_idx, .. }, ..) = curr_loc {
            self.module
                .functions
                .add_local(func_idx, val_type)
                .expect("Internal error: Should have found the local function successfully!")
        } else {
            panic!("Internal error: Should have gotten Module Location!")
        }
    }
}

// Note: Marked Trait as the same lifetime as component
impl<'a> Iterator for ModuleIterator<'_, 'a> {
    /// Resets the Module Iterator
    fn reset(&mut self) {
        self.mod_iterator.reset();
    }

    /// Goes to the next instruction and returns the instruction
    fn next(&mut self) -> Option<&Operator<'_>> {
        match self.mod_iterator.next() {
            false => None,
            true => self.curr_op(),
        }
    }

    /// Returns the Current Location as a Location and a bool value that
    /// says whether the location is at the end of the function.
    fn curr_loc(&self) -> (Location, bool) {
        self.mod_iterator.curr_loc()
    }

    /// Returns the current instruction
    fn curr_op(&self) -> Option<&Operator<'_>> {
        if let (
            Location::Module {
                func_idx,
                instr_idx,
                ..
            },
            ..,
        ) = self.mod_iterator.curr_loc()
        {
            match &self.module.functions.get(func_idx).kind {
                FuncKind::Import(_) => panic!(
                    "Internal error: Shouldn't have gotten the location of an imported function!"
                ),
                FuncKind::Local(l) => Some(&l.body.instructions.get_ops()[instr_idx]),
            }
        } else {
            panic!("Internal error: Should have gotten Module Location!")
        }
    }
}