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
//! Iterator to traverse a Module

use crate::ir::id::{FunctionID, GlobalID, LocalID};
use crate::ir::module::module_functions::{FuncKind, LocalFunction};
use crate::ir::module::module_globals::Global;
use crate::ir::module::{Iter, Module};
use crate::ir::types::{DataType, FuncInstrMode, 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 std::collections::HashMap;
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 {
        // Creates Function -> Number of Instructions
        let mut metadata = HashMap::new();
        for func in module.functions.iter() {
            match &func.kind {
                FuncKind::Import(_) => {}
                FuncKind::Local(LocalFunction { func_id, body, .. }) => {
                    metadata.insert(*func_id, body.num_instructions);
                }
            }
        }
        let num_funcs = module.num_local_functions;
        ModuleIterator {
            module,
            mod_iterator: ModuleSubIterator::new(num_funcs, metadata, skip_funcs.to_owned()),
        }
    }

    pub fn curr_op_owned(&self) -> Option<Operator<'b>> {
        if self.mod_iterator.end() {
            None
        } else if let (
            Location::Module {
                func_idx,
                instr_idx,
                ..
            },
            ..,
        ) = self.mod_iterator.curr_loc()
        {
            match &self.module.functions.get(func_idx as FunctionID).kind {
                FuncKind::Import(_) => panic!("Cannot get an instruction to an imported function"),
                FuncKind::Local(l) => Some(l.body.instructions[instr_idx].op.clone()),
            }
        } else {
            panic!("Should have gotten Module Location!")
        }
    }
}

impl<'a, 'b> Inject<'b> for ModuleIterator<'a, 'b> {
    /// Injects an Operator at the current location
    ///
    /// # Example
    /// ```no_run
    /// use orca_wasm::ir::module::Module;
    /// use orca_wasm::iterator::module_iterator::ModuleIterator;
    /// use wasmparser::Operator;
    /// use orca_wasm::ir::types::{Location};
    /// use orca_wasm::iterator::iterator_trait::{IteratingInstrumenter, Iterator};
    /// use orca_wasm::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).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 as FunctionID).kind {
                FuncKind::Import(_) => panic!("Cannot get an instruction to an imported function"),
                FuncKind::Local(ref mut l) => l.add_instr(instr, instr_idx),
            }
        } else {
            panic!("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!("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> {
    /// 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 as FunctionID).kind {
                FuncKind::Import(_) => panic!("Cannot get an instruction to an imported function"),
                FuncKind::Local(l) => &l.body.instructions[instr_idx].instr_flag.current_mode,
            }
        } else {
            panic!("Should have gotten Module Location and not 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 as FunctionID).kind {
                FuncKind::Import(_) => panic!("Cannot add an instruction to an imported function"),
                FuncKind::Local(ref mut l) => {
                    l.body.instructions[instr_idx].instr_flag.current_mode = Some(mode)
                }
            }
        } else {
            panic!("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 as FunctionID).kind {
                FuncKind::Import(_) => panic!("Cannot get an instruction to an imported function"),
                FuncKind::Local(l) => &l.instr_flag.current_mode,
            }
        } else {
            panic!("Should have gotten Module Location and not 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 as FunctionID).kind {
                FuncKind::Import(_) => panic!("Cannot get an instruction to an imported function"),
                FuncKind::Local(ref mut l) => l.instr_flag.current_mode = Some(mode),
            }
        } else {
            panic!("Should have gotten Module Location and not 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 as FunctionID).kind {
                FuncKind::Import(_) => panic!("Cannot add an instruction to an imported function"),
                FuncKind::Local(ref mut l) => {
                    l.clear_instr_at(instr_idx, mode);
                }
            }
            // Only injects if it is an instrumented location
        } else {
            panic!("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 as FunctionID).kind {
                FuncKind::Import(_) => panic!("Cannot add an instruction to an imported function"),
                FuncKind::Local(ref mut l) => {
                    l.add_instr(instr, instr_idx);
                }
            }
            // Only injects if it is an instrumented location
        } else {
            panic!("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 as FunctionID).kind {
                FuncKind::Import(_) => panic!("Cannot instrument an imported function"),
                FuncKind::Local(ref mut l) => {
                    l.body.instructions[instr_idx].instr_flag.alternate = Some(vec![])
                }
            }
        } else {
            panic!("Should have gotten Module Location and not 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 as FunctionID).kind {
                FuncKind::Import(_) => panic!("Cannot instrument an imported function"),
                FuncKind::Local(ref mut l) => {
                    l.body.instructions[instr_idx].instr_flag.block_alt = Some(vec![]);
                    l.instr_flag.has_special_instr |= true;
                }
            }
        } else {
            panic!("Should have gotten Module Location and not Module Location!")
        }
        self
    }

    /// Gets the injected instruction at the current location by index
    fn get_injected_val(&self, idx: usize) -> &Operator {
        if let (
            Location::Module {
                func_idx,
                instr_idx,
                ..
            },
            ..,
        ) = self.mod_iterator.curr_loc()
        {
            match &self.module.functions.get(func_idx as FunctionID).kind {
                FuncKind::Import(_) => panic!("Cannot get an instruction to an imported function"),
                FuncKind::Local(l) => l.body.instructions[instr_idx].instr_flag.get_instr(idx),
            }
        } else {
            panic!("Should have gotten Component Location and not Module Location!")
        }
    }
}
impl<'a> IteratingInstrumenter<'a> for ModuleIterator<'_, 'a> {
    fn set_instrument_mode(&mut self, mode: InstrumentationMode) {
        self.set_instrument_mode_at(mode, self.curr_loc().0);
    }

    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)
        } else {
            panic!("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<'a>> {
        if self.mod_iterator.end() {
            None
        } else if let (
            Location::Module {
                func_idx,
                instr_idx,
                ..
            },
            ..,
        ) = self.mod_iterator.curr_loc()
        {
            match &self.module.functions.get(func_idx as FunctionID).kind {
                FuncKind::Import(_) => panic!("Cannot get an instruction to an imported function"),
                FuncKind::Local(l) => Some(&l.body.instructions[instr_idx].op),
            }
        } else {
            panic!("Should have gotten Module Location!")
        }
    }
}