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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
//! Gas metering instrumentation.
use std::collections::BTreeMap;

use walrus::{ir::*, FunctionBuilder, GlobalId, LocalFunction, Module};

use crate::Error;

/// Name of the exported global that holds the gas limit.
pub const EXPORT_GAS_LIMIT: &str = "gas_limit";
/// Name of the exported global that holds the gas limit exhausted flag.
pub const EXPORT_GAS_LIMIT_EXHAUSTED: &str = "gas_limit_exhausted";

/// Configures the gas limit on the given instance.
pub fn set_gas_limit<C>(
    instance: &wasm3::Instance<'_, '_, C>,
    gas_limit: u64,
) -> Result<(), Error> {
    instance
        .set_global(EXPORT_GAS_LIMIT, gas_limit)
        .map_err(|err| Error::ExecutionFailed(err.into()))
}

/// Returns the remaining gas.
pub fn get_remaining_gas<C>(instance: &wasm3::Instance<'_, '_, C>) -> u64 {
    instance.get_global(EXPORT_GAS_LIMIT).unwrap_or_default()
}

/// Returns the amount of gas requested that was over the limit.
pub fn get_exhausted_amount<C>(instance: &wasm3::Instance<'_, '_, C>) -> u64 {
    instance
        .get_global(EXPORT_GAS_LIMIT_EXHAUSTED)
        .unwrap_or_default()
}

/// Attempts to use the given amount of gas.
pub fn use_gas<C>(instance: &wasm3::Instance<'_, '_, C>, amount: u64) -> Result<(), wasm3::Trap> {
    let gas_limit: u64 = instance
        .get_global(EXPORT_GAS_LIMIT)
        .map_err(|_| wasm3::Trap::Abort)?;
    if gas_limit < amount {
        let _ = instance.set_global(EXPORT_GAS_LIMIT_EXHAUSTED, amount);
        return Err(wasm3::Trap::Abort);
    }
    instance
        .set_global(EXPORT_GAS_LIMIT, gas_limit - amount)
        .map_err(|_| wasm3::Trap::Abort)?;
    Ok(())
}

/// Inject gas metering instrumentation into the module.
pub fn transform(module: &mut Module) {
    let gas_limit_global = module.globals.add_local(
        walrus::ValType::I64,
        true,
        walrus::InitExpr::Value(Value::I64(0)),
    );
    let gas_limit_exhausted_global = module.globals.add_local(
        walrus::ValType::I64,
        true,
        walrus::InitExpr::Value(Value::I64(0)),
    );
    module.exports.add(EXPORT_GAS_LIMIT, gas_limit_global);
    module
        .exports
        .add(EXPORT_GAS_LIMIT_EXHAUSTED, gas_limit_exhausted_global);

    for (_, func) in module.funcs.iter_local_mut() {
        transform_function(func, gas_limit_global, gas_limit_exhausted_global);
    }
}

/// Instruction cost function.
fn instruction_cost(instr: &Instr) -> u64 {
    match instr {
        Instr::Loop(_) | Instr::Block(_) => 2,

        Instr::LocalGet(_)
        | Instr::LocalSet(_)
        | Instr::LocalTee(_)
        | Instr::GlobalGet(_)
        | Instr::GlobalSet(_)
        | Instr::Const(_) => 1,

        Instr::Call(_) => 15,

        Instr::CallIndirect(_) => 20,

        Instr::Br(_) | Instr::BrIf(_) => 3,
        Instr::BrTable(_) => 4,

        Instr::Binop(op) => match op.op {
            BinaryOp::I32Eq
            | BinaryOp::I32Ne
            | BinaryOp::I32LtS
            | BinaryOp::I32LtU
            | BinaryOp::I32GtS
            | BinaryOp::I32GtU
            | BinaryOp::I32LeS
            | BinaryOp::I32LeU
            | BinaryOp::I32GeS
            | BinaryOp::I32GeU
            | BinaryOp::I64Eq
            | BinaryOp::I64Ne
            | BinaryOp::I64LtS
            | BinaryOp::I64LtU
            | BinaryOp::I64GtS
            | BinaryOp::I64GtU
            | BinaryOp::I64LeS
            | BinaryOp::I64LeU
            | BinaryOp::I64GeS
            | BinaryOp::I64GeU
            | BinaryOp::I32Add
            | BinaryOp::I32Sub
            | BinaryOp::I32Mul
            | BinaryOp::I32And
            | BinaryOp::I32Or
            | BinaryOp::I32Xor
            | BinaryOp::I32Shl
            | BinaryOp::I32ShrS
            | BinaryOp::I32ShrU
            | BinaryOp::I32Rotl
            | BinaryOp::I32Rotr
            | BinaryOp::I64Add
            | BinaryOp::I64Sub
            | BinaryOp::I64Mul
            | BinaryOp::I64And
            | BinaryOp::I64Or
            | BinaryOp::I64Xor
            | BinaryOp::I64Shl
            | BinaryOp::I64ShrS
            | BinaryOp::I64ShrU
            | BinaryOp::I64Rotl
            | BinaryOp::I64Rotr => 1,
            BinaryOp::I32DivS
            | BinaryOp::I32DivU
            | BinaryOp::I32RemS
            | BinaryOp::I32RemU
            | BinaryOp::I64DivS
            | BinaryOp::I64DivU
            | BinaryOp::I64RemS
            | BinaryOp::I64RemU => 4,
            _ => 3,
        },

        Instr::Unop(op) => match op.op {
            UnaryOp::I32Eqz
            | UnaryOp::I32Clz
            | UnaryOp::I32Ctz
            | UnaryOp::I32Popcnt
            | UnaryOp::I64Eqz
            | UnaryOp::I64Clz
            | UnaryOp::I64Ctz
            | UnaryOp::I64Popcnt => 1,

            _ => 3,
        },

        _ => 10,
    }
}

/// A block of instructions which is metered.
#[derive(Debug)]
struct MeteredBlock {
    /// Instruction sequence where metering code should be injected.
    seq_id: InstrSeqId,
    /// Start index of instruction within the instruction sequence before which the metering code
    /// should be injected.
    start_index: usize,
    /// Instruction cost.
    cost: u64,
    /// Indication of whether the metered block can be merged in case instruction sequence and start
    /// index match. In case the block cannot be merged this contains the index
    merge_index: Option<usize>,
}

impl MeteredBlock {
    fn new(seq_id: InstrSeqId, start_index: usize) -> Self {
        Self {
            seq_id,
            start_index,
            cost: 0,
            merge_index: None,
        }
    }

    /// Create a mergable version of this metered block with the given start index.
    fn mergable(&self, start_index: usize) -> Self {
        Self {
            seq_id: self.seq_id,
            start_index,
            cost: 0,
            merge_index: Some(self.start_index),
        }
    }
}

/// A map of finalized metered blocks.
#[derive(Default)]
struct MeteredBlocks {
    blocks: BTreeMap<InstrSeqId, Vec<MeteredBlock>>,
}

impl MeteredBlocks {
    /// Finalize the given metered block. This means that the cost associated with the block cannot
    /// change anymore.
    fn finalize(&mut self, block: MeteredBlock) {
        if block.cost > 0 {
            self.blocks.entry(block.seq_id).or_default().push(block);
        }
    }
}

fn determine_metered_blocks(func: &LocalFunction) -> BTreeMap<InstrSeqId, Vec<MeteredBlock>> {
    // NOTE: This is based on walrus::ir::dfs_in_order but we need more information.

    let mut blocks = MeteredBlocks::default();
    let mut stack: Vec<(InstrSeqId, usize, MeteredBlock)> = vec![(
        func.entry_block(),                       // Initial instruction sequence to visit.
        0,                                        // Instruction offset within the sequence.
        MeteredBlock::new(func.entry_block(), 0), // Initial metered block.
    )];

    'traversing_blocks: while let Some((seq_id, index, mut metered_block)) = stack.pop() {
        let seq = func.block(seq_id);

        'traversing_instrs: for (index, (instr, _)) in seq.instrs.iter().enumerate().skip(index) {
            // NOTE: Current instruction is always included in the current metered block.
            metered_block.cost += instruction_cost(instr);

            // Determine whether we need to end/start a metered block.
            match instr {
                Instr::Block(Block { seq }) => {
                    // Do not start a new metered block as blocks are unconditional and metered
                    // blocks can encompass many of them to avoid injecting unnecessary
                    // instructions.
                    stack.push((seq_id, index + 1, metered_block.mergable(index + 1)));
                    stack.push((*seq, 0, metered_block));
                    continue 'traversing_blocks;
                }

                Instr::Loop(Loop { seq }) => {
                    // Finalize current metered block.
                    blocks.finalize(metered_block);
                    // Start a new metered block for remainder of block.
                    stack.push((seq_id, index + 1, MeteredBlock::new(seq_id, index + 1)));
                    // Start a new metered block for loop body.
                    stack.push((*seq, 0, MeteredBlock::new(*seq, 0)));
                    continue 'traversing_blocks;
                }

                Instr::IfElse(IfElse {
                    consequent,
                    alternative,
                }) => {
                    // Finalize current metered block.
                    blocks.finalize(metered_block);

                    // Start a new metered block for remainder of block.
                    stack.push((seq_id, index + 1, MeteredBlock::new(seq_id, index + 1)));
                    // Start new metered blocks for alternative and consequent blocks.
                    stack.push((*alternative, 0, MeteredBlock::new(*alternative, 0)));
                    stack.push((*consequent, 0, MeteredBlock::new(*consequent, 0)));
                    continue 'traversing_blocks;
                }

                Instr::Call(_)
                | Instr::CallIndirect(_)
                | Instr::Br(_)
                | Instr::BrIf(_)
                | Instr::BrTable(_)
                | Instr::Return(_) => {
                    // Finalize current metered block and start a new one for the remainder.
                    blocks.finalize(std::mem::replace(
                        &mut metered_block,
                        MeteredBlock::new(seq_id, index + 1),
                    ));
                    continue 'traversing_instrs;
                }

                _ => continue 'traversing_instrs,
            }
        }

        // Check if we can merge the blocks.
        if let Some((_, _, upper)) = stack.last_mut() {
            match upper.merge_index {
                Some(index)
                    if upper.seq_id == metered_block.seq_id
                        && index == metered_block.start_index =>
                {
                    // Blocks can be merged, so overwrite upper.
                    *upper = metered_block;
                    continue 'traversing_blocks;
                }
                _ => {
                    // Blocks cannot be merged so treat as new block.
                }
            }
        }

        blocks.finalize(metered_block);
    }

    blocks.blocks
}

fn transform_function(
    func: &mut LocalFunction,
    gas_limit_global: GlobalId,
    gas_limit_exhausted_global: GlobalId,
) {
    // First pass: determine where metering instructions should be injected.
    let blocks = determine_metered_blocks(func);

    // Second pass: actually emit metering instructions in correct positions.
    let builder = func.builder_mut();
    for (seq_id, blocks) in blocks {
        let mut seq = builder.instr_seq(seq_id);
        let instrs = seq.instrs_mut();

        let original_instrs = std::mem::take(instrs);
        let new_instrs_len = instrs.len() + METERING_INSTRUCTION_COUNT * blocks.len();
        let mut new_instrs = Vec::with_capacity(new_instrs_len);

        let mut block_iter = blocks.into_iter().peekable();
        for (index, (instr, loc)) in original_instrs.into_iter().enumerate() {
            match block_iter.peek() {
                Some(block) if block.start_index == index => {
                    inject_metering(
                        builder,
                        &mut new_instrs,
                        block_iter.next().unwrap(),
                        gas_limit_global,
                        gas_limit_exhausted_global,
                    );
                }
                _ => {}
            }

            // Push original instruction.
            new_instrs.push((instr, loc));
        }

        let mut seq = builder.instr_seq(seq_id);
        let instrs = seq.instrs_mut();
        *instrs = new_instrs;
    }
}

/// Number of injected metering instructions (needed to calculate final instruction size).
const METERING_INSTRUCTION_COUNT: usize = 8;

fn inject_metering(
    builder: &mut FunctionBuilder,
    instrs: &mut Vec<(Instr, InstrLocId)>,
    block: MeteredBlock,
    gas_limit_global: GlobalId,
    gas_limit_exhausted_global: GlobalId,
) {
    let mut builder = builder.dangling_instr_seq(None);
    let seq = builder
        // if unsigned(globals[gas_limit]) < unsigned(block.cost) { throw(); }
        .global_get(gas_limit_global)
        .i64_const(block.cost as i64)
        .binop(BinaryOp::I64LtU)
        .if_else(
            None,
            |then| {
                then.i64_const(block.cost as i64)
                    .global_set(gas_limit_exhausted_global)
                    .unreachable();
            },
            |_else| {},
        )
        // globals[gas_limit] -= block.cost;
        .global_get(gas_limit_global)
        .i64_const(block.cost as i64)
        .binop(BinaryOp::I64Sub)
        .global_set(gas_limit_global);

    instrs.append(seq.instrs_mut());
}

#[cfg(test)]
mod test {
    use pretty_assertions::assert_eq;

    macro_rules! test_transform {
        (name = $name:ident, source = $src:expr, expected = $expected:expr) => {
            #[test]
            fn $name() {
                let src = wat::parse_str($src).unwrap();
                let expected = wat::parse_str($expected).unwrap();

                let mut result_module = walrus::ModuleConfig::new()
                    .generate_producers_section(false)
                    .parse(&src)
                    .unwrap();

                super::transform(&mut result_module);

                let mut expected_module = walrus::ModuleConfig::new()
                    .generate_producers_section(false)
                    .parse(&expected)
                    .unwrap();

                let result_wasm = result_module.emit_wasm();
                let expected_wasm = expected_module.emit_wasm();
                let result = wasmprinter::print_bytes(&result_wasm).unwrap();
                let expected = wasmprinter::print_bytes(&expected_wasm).unwrap();

                assert_eq!(result, expected);
            }
        };
    }

    test_transform! {
        name = simple,
        source = r#"
        (module
            (func (result i32)
                (i32.const 1)))
        "#,
        expected = r#"
        (module
            (func (result i32)
                (if
                    (i64.lt_u
                        (global.get 0)
                        (i64.const 1))
                    (then
                        (global.set 1
                            (i64.const 1))
                        (unreachable)))
                (global.set 0
                    (i64.sub
                        (global.get 0)
                        (i64.const 1)))
                (i32.const 1))
            (global (;0;) (mut i64) (i64.const 0))
            (global (;1;) (mut i64) (i64.const 0))
            (export "gas_limit" (global 0))
            (export "gas_limit_exhausted" (global 1)))
        "#
    }

    test_transform! {
        name = nested_blocks,
        source = r#"
        (module
            (func (result i32)
                (block
                    (block
                        (block
                            (i32.const 1)
                            (drop))))
                (i32.const 1)))
        "#,
        expected = r#"
        (module
            (func (result i32)
                (if
                    (i64.lt_u
                        (global.get 0)
                        (i64.const 18))
                    (then
                        (global.set 1
                            (i64.const 18))
                        (unreachable)))
                (global.set 0
                    (i64.sub
                        (global.get 0)
                        (i64.const 18)))
                (block
                    (block
                        (block
                            (i32.const 1)
                            (drop))))
                (i32.const 1))
            (global (;0;) (mut i64) (i64.const 0))
            (global (;1;) (mut i64) (i64.const 0))
            (export "gas_limit" (global 0))
            (export "gas_limit_exhausted" (global 1)))
        "#
    }

    test_transform! {
        name = nested_blocks_with_loop,
        source = r#"
        (module
            (func (result i32)
                (block
                    (block
                        (block
                            (i32.const 1)
                            (drop))
                        (loop
                            (i32.const 1)
                            (drop)
                            (i32.const 1)
                            (drop)
                            (br 0))))
                (i32.const 1)))
        "#,
        expected = r#"
        (module
            (func (result i32)
                (if
                    (i64.lt_u
                        (global.get 0)
                        (i64.const 19))
                    (then
                        (global.set 1
                            (i64.const 19))
                        (unreachable)))
                (global.set 0
                    (i64.sub
                        (global.get 0)
                        (i64.const 19)))
                (block
                    (block
                        (block
                            (i32.const 1)
                            (drop))
                        (loop
                            (if
                                (i64.lt_u
                                    (global.get 0)
                                    (i64.const 25))
                                (then
                                    (global.set 1
                                        (i64.const 25))
                                    (unreachable)))
                            (global.set 0
                                (i64.sub
                                    (global.get 0)
                                    (i64.const 25)))
                            (i32.const 1)
                            (drop)
                            (i32.const 1)
                            (drop)
                            (br 0))))
                (if
                    (i64.lt_u
                        (global.get 0)
                        (i64.const 1))
                    (then
                        (global.set 1
                            (i64.const 1))
                        (unreachable)))
                (global.set 0
                    (i64.sub
                        (global.get 0)
                        (i64.const 1)))
                (i32.const 1))
            (global (;0;) (mut i64) (i64.const 0))
            (global (;1;) (mut i64) (i64.const 0))
            (export "gas_limit" (global 0))
            (export "gas_limit_exhausted" (global 1)))
        "#
    }

    test_transform! {
        name = if_else,
        source = r#"
        (module
            (func (result i32)
                (i32.const 1)
                (if
                    (then
                        (i32.const 1)
                        (drop)
                        (i32.const 1)
                        (drop))
                    (else
                        (i32.const 1)
                        (drop)))
                (i32.const 1)))
        "#,
        expected = r#"
        (module
            (func (result i32)
                (if
                    (i64.lt_u
                        (global.get 0)
                        (i64.const 11))
                    (then
                        (global.set 1
                            (i64.const 11))
                        (unreachable)))
                (global.set 0
                    (i64.sub
                        (global.get 0)
                        (i64.const 11)))
                (i32.const 1)
                (if
                    (then
                        (if
                            (i64.lt_u
                                (global.get 0)
                                (i64.const 22))
                            (then
                                (global.set 1
                                    (i64.const 22))
                                (unreachable)))
                        (global.set 0
                            (i64.sub
                                (global.get 0)
                                (i64.const 22)))
                        (i32.const 1)
                        (drop)
                        (i32.const 1)
                        (drop)
                    )
                    (else
                        (if
                            (i64.lt_u
                                (global.get 0)
                                (i64.const 11))
                            (then
                                (global.set 1
                                    (i64.const 11))
                                (unreachable)))
                        (global.set 0
                            (i64.sub
                                (global.get 0)
                                (i64.const 11)))
                        (i32.const 1)
                        (drop)
                    )
                )
                (if
                    (i64.lt_u
                        (global.get 0)
                        (i64.const 1))
                    (then
                        (global.set 1
                            (i64.const 1))
                        (unreachable)))
                (global.set 0
                    (i64.sub
                        (global.get 0)
                        (i64.const 1)))
                (i32.const 1))
            (global (;0;) (mut i64) (i64.const 0))
            (global (;1;) (mut i64) (i64.const 0))
            (export "gas_limit" (global 0))
            (export "gas_limit_exhausted" (global 1)))
        "#
    }
}