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
use parity_wasm::elements::{ExportEntry, ExportSection, Internal, Module};

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

/// Struct containing a list of valid exports.
struct ExportWhitelist {
    pub entries: Vec<ExportEntry>,
}

/// Wrapper struct implementing ModuleTranslator.
/// Removes any exports that are noncompliant with a specified interface.
pub struct TrimExports {
    whitelist: ExportWhitelist,
}

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

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

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

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

/// Helper that compares the enum variant of two WebAssembly exports.
fn cmp_internal_variant(a: &Internal, b: &Internal) -> bool {
    std::mem::discriminant(a) == std::mem::discriminant(b)
}

impl ModulePreset for ExportWhitelist {
    fn with_preset(preset: &str) -> Result<Self, ModuleError> {
        match preset {
            "ewasm" => Ok(ExportWhitelist {
                entries: vec![
                    //NOTE: function signatures are not checked yet
                    ExportEntry::new("main".to_string(), Internal::Function(0)),
                    ExportEntry::new("memory".to_string(), Internal::Memory(0)),
                ],
            }),
            "pwasm" => Ok(ExportWhitelist {
                entries: vec![ExportEntry::new("_call".to_string(), Internal::Function(0))],
            }),
            _ => Err(ModuleError::NotSupported),
        }
    }
}

impl ExportWhitelist {
    /// Constructs an empty whitelist. Mostly useless.
    fn new() -> Self {
        ExportWhitelist {
            entries: Vec::new(),
        }
    }

    /// Looks up a given export entry in the whitelist and returns true if it is valid.
    fn lookup(&self, export: &ExportEntry) -> bool {
        self.entries
            .iter()
            .find(|matched_export| {
                export.field() == matched_export.field()
                    && cmp_internal_variant(export.internal(), matched_export.internal())
            })
            .is_some()
    }
}

impl TrimExports {
    /// Constructs an empty `trimexports` context.
    pub fn new() -> Self {
        TrimExports {
            whitelist: ExportWhitelist::new(),
        }
    }

    /// Iterates over the export section, if there is one, and removes
    /// unnecessary entries.
    fn trim_exports(&self, module: &mut Module) -> bool {
        if let Some(section) = module.export_section_mut() {
            let new_section = ExportSection::with_entries(
                section
                    .entries()
                    .iter()
                    .cloned()
                    .filter(|entry| self.whitelist.lookup(entry))
                    .collect(),
            );

            if new_section.entries().len() < section.entries().len() {
                *section = new_section;
                return true;
            }

            false
        } else {
            false
        }
    }
}

impl ModulePreset for TrimExports {
    /// Takes a given preset string and constructs a context with the
    /// corresponding whitelist.
    fn with_preset(preset: &str) -> Result<Self, ModuleError> {
        match preset {
            "ewasm" => Ok(TrimExports {
                whitelist: ExportWhitelist::with_preset("ewasm")?,
            }),
            "pwasm" => Ok(TrimExports {
                whitelist: ExportWhitelist::with_preset("pwasm")?,
            }),
            _ => Err(ModuleError::NotSupported),
        }
    }
}

impl ModuleTranslator for TrimExports {
    fn translate_inplace(&self, module: &mut Module) -> Result<bool, ModuleError> {
        Ok(self.trim_exports(module))
    }

    fn translate(&self, module: &Module) -> Result<Option<Module>, ModuleError> {
        let mut ret = module.clone();
        let modified = self.trim_exports(&mut ret);
        if modified {
            return Ok(Some(ret));
        }
        Ok(None)
    }
}

#[cfg(test)]
mod tests {
    use parity_wasm::builder;

    use super::*;

    // Smoke tests
    #[test]
    fn builder_all_exports_good_ewasm() {
        let mut module = builder::module()
            .function()
            .signature()
            .build()
            .body()
            .build()
            .build()
            .export()
            .field("main")
            .internal()
            .func(0)
            .build()
            .export()
            .field("memory")
            .internal()
            .memory(0)
            .build()
            .build();

        let trimmer = TrimExports::with_preset("ewasm").unwrap();
        let did_change = trimmer.translate_inplace(&mut module).unwrap();
        assert_eq!(false, did_change);
    }

    #[test]
    fn builder_one_wrong_mem_export_ewasm() {
        let mut module = builder::module()
            .function()
            .signature()
            .build()
            .body()
            .build()
            .build()
            .export()
            .field("main")
            .internal()
            .func(0)
            .build()
            .export()
            .field("memory")
            .internal()
            .memory(0)
            .build()
            .export()
            .field("foo")
            .internal()
            .memory(0)
            .build()
            .build();

        let trimmer = TrimExports::with_preset("ewasm").unwrap();
        let did_change = trimmer.translate_inplace(&mut module).unwrap();
        assert_eq!(true, did_change);
    }

    #[test]
    fn builder_no_export_ewasm() {
        let mut module = builder::module()
            .function()
            .signature()
            .build()
            .body()
            .build()
            .build()
            .build();

        let trimmer = TrimExports::with_preset("ewasm").unwrap();
        let did_change = trimmer.translate_inplace(&mut module).unwrap();
        assert_eq!(false, did_change);
    }

    #[test]
    fn builder_all_exports_good_pwasm() {
        let mut module = builder::module()
            .function()
            .signature()
            .build()
            .body()
            .build()
            .build()
            .export()
            .field("_call")
            .internal()
            .func(0)
            .build()
            .build();

        let trimmer = TrimExports::with_preset("pwasm").unwrap();
        let did_change = trimmer.translate_inplace(&mut module).unwrap();
        assert_eq!(false, did_change);
    }
}