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
use parity_wasm::elements::{ImportEntry, ImportSection, Module};

use super::{
    imports::ImportList, ChiselModule, ModuleError, ModuleKind, ModulePreset, ModuleTranslator,
};

pub struct RemapImports<'a> {
    /// A list of import sets to remap.
    interfaces: Vec<ImportInterface<'a>>,
}

/// A pair containing a list of imports for RemapImports to remap against, and an optional string with which all
/// imports are expected to be prefixed.
pub struct ImportInterface<'a>(ImportList<'a>, Option<&'a str>);

impl<'a> ChiselModule<'a> for RemapImports<'a> {
    type ObjectReference = &'a dyn ModuleTranslator;

    fn id(&'a self) -> String {
        "remapimports".to_string()
    }

    fn kind(&'a self) -> ModuleKind {
        ModuleKind::Translator
    }

    fn as_abstract(&'a self) -> Self::ObjectReference {
        self as Self::ObjectReference
    }
}

impl<'a> ModulePreset for RemapImports<'a> {
    fn with_preset(preset: &str) -> Result<Self, ModuleError> {
        let mut interface_set: Vec<ImportInterface> = Vec::new();

        // Accept a comma-separated list of presets.
        let presets: String = preset
            .chars()
            .filter(|c| *c != '_' && *c != ' ' && *c != '\n' && *c != '\t')
            .collect();
        for preset_individual in presets.split(',') {
            match preset_individual {
                "ewasm" => interface_set.push(ImportInterface::new(
                    ImportList::with_preset("ewasm")?,
                    Some("ethereum_"),
                )),
                "eth2" => interface_set.push(ImportInterface::new(
                    ImportList::with_preset("eth2")?,
                    Some("eth2_"),
                )),
                "debug" => interface_set.push(ImportInterface::new(
                    ImportList::with_preset("debug")?,
                    Some("debug_"),
                )),
                "bignum" => interface_set.push(ImportInterface::new(
                    ImportList::with_preset("bignum")?,
                    Some("bignum_"),
                )),
                _ => return Err(ModuleError::NotSupported),
            }
        }

        Ok(RemapImports {
            interfaces: interface_set,
        })
    }
}

impl<'a> ModuleTranslator for RemapImports<'a> {
    fn translate_inplace(&self, module: &mut Module) -> Result<bool, ModuleError> {
        let mut was_mutated = false;

        if let Some(section) = module.import_section_mut() {
            for interface in self.interfaces.iter() {
                *section = ImportSection::with_entries(
                    section
                        .entries()
                        .iter()
                        .map(|e| self.remap_from_list(e, &mut was_mutated, interface))
                        .collect(),
                );
            }
        }

        Ok(was_mutated)
    }

    fn translate(&self, module: &Module) -> Result<Option<Module>, ModuleError> {
        let mut new_module = module.clone();
        let mut was_mutated = false;

        if let Some(section) = new_module.import_section_mut() {
            // Iterate over entries and remap if needed.
            for interface in self.interfaces.iter() {
                *section = ImportSection::with_entries(
                    section
                        .entries()
                        .iter()
                        .map(|e| self.remap_from_list(e, &mut was_mutated, interface))
                        .collect(),
                );
            }
        }

        if was_mutated {
            Ok(Some(new_module))
        } else {
            Ok(None)
        }
    }
}

impl<'a> ImportInterface<'a> {
    pub fn new(imports: ImportList<'a>, prefix: Option<&'a str>) -> Self {
        ImportInterface(imports, prefix)
    }

    pub fn prefix(&self) -> Option<&str> {
        self.1
    }

    pub fn imports(&self) -> &ImportList<'a> {
        &self.0
    }
}

impl<'a> RemapImports<'a> {
    // NOTE: 'new()' is currently unused in the library but useful in the future.
    #[allow(dead_code)]
    fn new(interfaces: Vec<ImportInterface<'a>>) -> Self {
        RemapImports {
            interfaces: interfaces,
        }
    }

    /// Takes an import entry and returns either the same entry or a remapped version if it exists.
    /// Sets the mutation flag if was remapped.
    fn remap_from_list(
        &self,
        entry: &ImportEntry,
        mutflag: &mut bool,
        interface: &ImportInterface,
    ) -> ImportEntry {
        match interface.prefix() {
            Some(prefix) => {
                let prefix_len = prefix.len();
                if entry.field().len() > prefix_len && prefix == &entry.field()[..prefix_len] {
                    // Look for a matching remappable import and mutate if found.
                    if let Some(import) = interface
                        .imports()
                        .lookup_by_field(&entry.field()[prefix_len..])
                    {
                        *mutflag = true;
                        return ImportEntry::new(
                            import.module().into(),
                            import.field().into(),
                            entry.external().clone(),
                        );
                    }
                }
                entry.clone()
            }
            None => {
                if let Some(import) = interface.imports().lookup_by_field(&entry.field()) {
                    *mutflag = true;
                    ImportEntry::new(
                        import.module().into(),
                        import.field().into(),
                        entry.external().clone(),
                    )
                } else {
                    entry.clone()
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use rustc_hex::FromHex;

    use super::*;
    use crate::verifyimports::*;
    use crate::{ModulePreset, ModuleTranslator, ModuleValidator};

    #[test]
    fn smoke_test() {
        let input = FromHex::from_hex(
            "
            0061736d0100000001050160017e0002170103656e760f65746865726575
            6d5f7573654761730000
        ",
        )
        .unwrap();
        let mut module = Module::from_bytes(&input).unwrap();
        let did_change = RemapImports::with_preset("ewasm")
            .unwrap()
            .translate_inplace(&mut module)
            .unwrap();
        let output = module.to_bytes().unwrap();
        let expected = FromHex::from_hex(
            "
            0061736d0100000001050160017e0002130108657468657265756d067573
            654761730000
        ",
        )
        .unwrap();
        assert_eq!(output, expected);
        assert!(did_change);
    }

    #[test]
    fn remap_did_mutate() {
        // wast:
        // (module
        //   (import "env" "ethereum_useGas" (func (param i64)))
        //   (memory 1)
        //   (export "main" (func $main))
        //   (export "memory" (memory 0))
        //
        //   (func $main)
        // )
        let wasm: Vec<u8> = vec![
            0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x60, 0x01, 0x7e,
            0x00, 0x60, 0x00, 0x00, 0x02, 0x17, 0x01, 0x03, 0x65, 0x6e, 0x76, 0x0f, 0x65, 0x74,
            0x68, 0x65, 0x72, 0x65, 0x75, 0x6d, 0x5f, 0x75, 0x73, 0x65, 0x47, 0x61, 0x73, 0x00,
            0x00, 0x03, 0x02, 0x01, 0x01, 0x05, 0x03, 0x01, 0x00, 0x01, 0x07, 0x11, 0x02, 0x04,
            0x6d, 0x61, 0x69, 0x6e, 0x00, 0x01, 0x06, 0x6d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x02,
            0x00, 0x0a, 0x04, 0x01, 0x02, 0x00, 0x0b,
        ];

        let module = Module::from_bytes(&wasm).unwrap();

        let new = RemapImports::with_preset("ewasm")
            .unwrap()
            .translate(&module)
            .expect("Module internal error");

        assert!(new.is_some());
    }

    #[test]
    fn remap_did_mutate_verify() {
        // wast:
        // (module
        //   (import "env" "ethereum_useGas" (func (param i64)))
        //   (memory 1)
        //   (export "main" (func $main))
        //   (export "memory" (memory 0))
        //
        //   (func $main)
        // )
        let wasm: Vec<u8> = vec![
            0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x60, 0x01, 0x7e,
            0x00, 0x60, 0x00, 0x00, 0x02, 0x17, 0x01, 0x03, 0x65, 0x6e, 0x76, 0x0f, 0x65, 0x74,
            0x68, 0x65, 0x72, 0x65, 0x75, 0x6d, 0x5f, 0x75, 0x73, 0x65, 0x47, 0x61, 0x73, 0x00,
            0x00, 0x03, 0x02, 0x01, 0x01, 0x05, 0x03, 0x01, 0x00, 0x01, 0x07, 0x11, 0x02, 0x04,
            0x6d, 0x61, 0x69, 0x6e, 0x00, 0x01, 0x06, 0x6d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x02,
            0x00, 0x0a, 0x04, 0x01, 0x02, 0x00, 0x0b,
        ];

        let module = Module::from_bytes(&wasm).unwrap();

        let new = RemapImports::with_preset("ewasm")
            .unwrap()
            .translate(&module)
            .expect("Module internal error");

        assert!(new.is_some());

        let verified = VerifyImports::with_preset("ewasm")
            .unwrap()
            .validate(&new.unwrap())
            .unwrap();

        assert_eq!(verified, true);
    }

    #[test]
    fn remap_did_mutate_verify_explicit_type_section() {
        // wast:
        // (module
        //   (type (;0;) (func (result i64)))
        //   (import "env" "ethereum_getGasLeft" (func (;0;) (type 0)))
        //   (memory 1)
        //   (func $main)
        //   (export "main" (func $main))
        //   (export "memory" (memory 0))
        // )

        let wasm: Vec<u8> = vec![
            0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x60, 0x00, 0x01,
            0x7e, 0x60, 0x00, 0x00, 0x02, 0x1b, 0x01, 0x03, 0x65, 0x6e, 0x76, 0x13, 0x65, 0x74,
            0x68, 0x65, 0x72, 0x65, 0x75, 0x6d, 0x5f, 0x67, 0x65, 0x74, 0x47, 0x61, 0x73, 0x4c,
            0x65, 0x66, 0x74, 0x00, 0x00, 0x03, 0x02, 0x01, 0x01, 0x05, 0x03, 0x01, 0x00, 0x01,
            0x07, 0x11, 0x02, 0x04, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x01, 0x06, 0x6d, 0x65, 0x6d,
            0x6f, 0x72, 0x79, 0x02, 0x00, 0x0a, 0x04, 0x01, 0x02, 0x00, 0x0b,
        ];

        let module = Module::from_bytes(&wasm).unwrap();

        let new = RemapImports::with_preset("ewasm")
            .unwrap()
            .translate(&module)
            .expect("Module internal error");

        assert!(new.is_some());

        let verified = VerifyImports::with_preset("ewasm")
            .unwrap()
            .validate(&new.unwrap())
            .unwrap();

        assert_eq!(verified, true);
    }

    #[test]
    fn remap_mutated_multiple_interfaces() {
        // wast:
        // (module
        //   (type (;0;) (func (result i64)))
        //   (type (;1;) (func (param i32 i32 i32)))
        //   (type (;2;) (func (param i32)))
        //   (import "env" "ethereum_getGasLeft" (func (;0;) (type 0)))
        //   (import "env" "bignum_mul256" (func (;1;) (type 1)))
        //   (import "env" "debug_printStorage" (func (;2;) (type 2)))
        //   (memory 1)
        //   (func $main)
        //   (export "main" (func $main))
        //   (export "memory" (memory 0))
        // )

        let wasm: Vec<u8> = vec![
            0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x12, 0x04, 0x60, 0x00, 0x01,
            0x7e, 0x60, 0x03, 0x7f, 0x7f, 0x7f, 0x00, 0x60, 0x01, 0x7f, 0x00, 0x60, 0x00, 0x00,
            0x02, 0x48, 0x03, 0x03, 0x65, 0x6e, 0x76, 0x13, 0x65, 0x74, 0x68, 0x65, 0x72, 0x65,
            0x75, 0x6d, 0x5f, 0x67, 0x65, 0x74, 0x47, 0x61, 0x73, 0x4c, 0x65, 0x66, 0x74, 0x00,
            0x00, 0x03, 0x65, 0x6e, 0x76, 0x0d, 0x62, 0x69, 0x67, 0x6e, 0x75, 0x6d, 0x5f, 0x6d,
            0x75, 0x6c, 0x32, 0x35, 0x36, 0x00, 0x01, 0x03, 0x65, 0x6e, 0x76, 0x12, 0x64, 0x65,
            0x62, 0x75, 0x67, 0x5f, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x53, 0x74, 0x6f, 0x72, 0x61,
            0x67, 0x65, 0x00, 0x02, 0x03, 0x02, 0x01, 0x03, 0x05, 0x03, 0x01, 0x00, 0x01, 0x07,
            0x11, 0x02, 0x04, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x03, 0x06, 0x6d, 0x65, 0x6d, 0x6f,
            0x72, 0x79, 0x02, 0x00, 0x0a, 0x04, 0x01, 0x02, 0x00, 0x0b,
        ];

        let module = Module::from_bytes(&wasm).unwrap();

        let new = RemapImports::with_preset("ewasm, bignum, debug")
            .unwrap()
            .translate(&module)
            .expect("Module internal error")
            .expect("Module was not mutated");

        let verifier = VerifyImports::with_preset("ewasm, bignum, debug").unwrap();

        assert_eq!(verifier.validate(&new), Ok(true));
    }

    #[test]
    fn no_prefix() {
        // wast:
        // (module
        //   (type (;0;) (func (result i64)))
        //   (type (;1;) (func (param i32 i32 i32)))
        //   (type (;2;) (func (param i32)))
        //   (import "env" "getGasLeft" (func (;0;) (type 0)))
        //   (import "env" "mul256" (func (;1;) (type 1)))
        //   (import "env" "printStorage" (func (;2;) (type 2)))
        //   (memory 1)
        //   (func $main)
        //   (export "main" (func $main))
        //   (export "memory" (memory 0))
        // )

        let wasm: Vec<u8> = vec![
            0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x12, 0x04, 0x60, 0x00, 0x01,
            0x7e, 0x60, 0x03, 0x7f, 0x7f, 0x7f, 0x00, 0x60, 0x01, 0x7f, 0x00, 0x60, 0x00, 0x00,
            0x02, 0x32, 0x03, 0x03, 0x65, 0x6e, 0x76, 0x0a, 0x67, 0x65, 0x74, 0x47, 0x61, 0x73,
            0x4c, 0x65, 0x66, 0x74, 0x00, 0x00, 0x03, 0x65, 0x6e, 0x76, 0x06, 0x6d, 0x75, 0x6c,
            0x32, 0x35, 0x36, 0x00, 0x01, 0x03, 0x65, 0x6e, 0x76, 0x0c, 0x70, 0x72, 0x69, 0x6e,
            0x74, 0x53, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65, 0x00, 0x02, 0x03, 0x02, 0x01, 0x03,
            0x05, 0x03, 0x01, 0x00, 0x01, 0x07, 0x11, 0x02, 0x04, 0x6d, 0x61, 0x69, 0x6e, 0x00,
            0x03, 0x06, 0x6d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x02, 0x00, 0x0a, 0x04, 0x01, 0x02,
            0x00, 0x0b,
        ];

        let module = Module::from_bytes(&wasm).unwrap();

        let interfaces_noprefix = vec![
            ImportInterface::new(ImportList::with_preset("ewasm").unwrap(), None),
            ImportInterface::new(ImportList::with_preset("bignum").unwrap(), None),
            ImportInterface::new(ImportList::with_preset("debug").unwrap(), None),
        ];

        let new = RemapImports::new(interfaces_noprefix)
            .translate(&module)
            .expect("Module internal error")
            .expect("Module was not mutated");

        let verifier = VerifyImports::with_preset("ewasm, bignum, debug").unwrap();

        assert_eq!(verifier.validate(&new), Ok(true));
    }
}