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

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

/// Enum on which ModuleTranslator is implemented.
pub enum DropSection {
    NamesSection,
    /// Name of the custom section.
    CustomSectionByName(String),
    /// Index of the custom section.
    CustomSectionByIndex(usize),
    /// Index of the unknown section.
    UnknownSectionByIndex(usize),
}

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

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

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

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

// TODO: consider upstreaming this
fn custom_section_index_for(module: &Module, name: &str) -> Option<usize> {
    module.sections().iter().position(|e| match e {
        Section::Custom(_section) => _section.name() == name,
        Section::Name(_) => name == "name", // If the names section was parsed by parity-wasm, it is distinct from a custom section.
        _ => false,
    })
}

impl DropSection {
    fn find_index(&self, module: &Module) -> Option<usize> {
        match &self {
            DropSection::NamesSection => custom_section_index_for(module, "name"),
            DropSection::CustomSectionByName(name) => custom_section_index_for(module, &name),
            DropSection::CustomSectionByIndex(index) => Some(*index),
            DropSection::UnknownSectionByIndex(index) => Some(*index),
        }
    }

    fn drop_section(&self, module: &mut Module) -> Result<bool, ModuleError> {
        if let Some(index) = self.find_index(&module) {
            let sections = module.sections_mut();
            if index < sections.len() {
                sections.remove(index);
                return Ok(true);
            }
        }

        Ok(false)
    }
}

impl<'a> ModuleTranslator for DropSection {
    fn translate_inplace(&self, module: &mut Module) -> Result<bool, ModuleError> {
        Ok(self.drop_section(module)?)
    }

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

#[cfg(test)]
mod tests {
    use parity_wasm::builder;
    use parity_wasm::elements::CustomSection;
    use rustc_hex::FromHex;

    use super::*;

    #[test]
    fn keep_intact() {
        let mut module = builder::module().build();
        let name = "empty".to_string();
        let dropper = DropSection::CustomSectionByName(name);
        let did_change = dropper.translate_inplace(&mut module).unwrap();
        assert_eq!(did_change, false);
    }

    #[test]
    fn keep_intact_custom_section() {
        let mut module = builder::module()
            .with_section(Section::Custom(CustomSection::new(
                "test".to_string(),
                vec![],
            )))
            .build();
        let name = "empty".to_string();
        let dropper = DropSection::CustomSectionByName(name);
        let did_change = dropper.translate_inplace(&mut module).unwrap();
        assert_eq!(did_change, false);
    }

    #[test]
    fn remove_custom_section() {
        let mut module = builder::module()
            .with_section(Section::Custom(CustomSection::new(
                "test".to_string(),
                vec![],
            )))
            .build();
        let name = "test".to_string();
        let dropper = DropSection::CustomSectionByName(name);
        let did_change = dropper.translate_inplace(&mut module).unwrap();
        assert_eq!(did_change, true);
    }

    #[test]
    fn remove_custom_section_by_index() {
        let mut module = builder::module()
            .with_section(Section::Custom(CustomSection::new(
                "test".to_string(),
                vec![],
            )))
            .build();
        let dropper = DropSection::CustomSectionByIndex(0);
        let did_change = dropper.translate_inplace(&mut module).unwrap();
        assert_eq!(did_change, true);
    }

    #[test]
    fn remove_oob_custom_section_by_index() {
        let mut module = builder::module()
            .with_section(Section::Custom(CustomSection::new(
                "test".to_string(),
                vec![],
            )))
            .build();
        let dropper = DropSection::CustomSectionByIndex(1);
        let did_change = dropper.translate_inplace(&mut module).unwrap();
        assert_eq!(did_change, false);
    }

    #[test]
    fn remove_custom_unknown_by_index() {
        let mut module = builder::module()
            .with_section(Section::Custom(CustomSection::new(
                "test".to_string(),
                vec![],
            )))
            .build();
        let dropper = DropSection::UnknownSectionByIndex(0);
        let did_change = dropper.translate_inplace(&mut module).unwrap();
        assert_eq!(did_change, true);
    }

    #[test]
    fn remove_oob_unknown_section_by_index() {
        let mut module = builder::module()
            .with_section(Section::Custom(CustomSection::new(
                "test".to_string(),
                vec![],
            )))
            .build();
        let dropper = DropSection::UnknownSectionByIndex(1);
        let did_change = dropper.translate_inplace(&mut module).unwrap();
        assert_eq!(did_change, false);
    }

    #[test]
    fn names_section_index() {
        let input = FromHex::from_hex(
            "0061736d010000000104016000000303020000070801046d61696e00010a
            0a020300010b040010000b0014046e616d65010d0200047465737401046d
            61696e",
        )
        .unwrap();

        let mut module = Module::from_bytes(&input).unwrap();
        assert!(custom_section_index_for(&module, "name").is_some());
        module = module.parse_names().expect("Should not fail");
        assert!(custom_section_index_for(&module, "name").is_some());
    }

    #[test]
    fn missing_name_section_index() {
        let input = FromHex::from_hex(
            "0061736d010000000104016000000303020000070801046d61696e00010a
            0a020300010b040010000b",
        )
        .unwrap();

        let module = Module::from_bytes(&input).unwrap();
        assert!(custom_section_index_for(&module, "name").is_none());
    }

    #[test]
    fn dropped_name_section_parsed() {
        let input = FromHex::from_hex(
            "0061736d010000000104016000000303020000070801046d61696e00010a
            0a020300010b040010000b0014046e616d65010d0200047465737401046d
            61696e",
        )
        .unwrap();

        let mut module = Module::from_bytes(&input)
            .unwrap()
            .parse_names()
            .expect("Should not fail");
        let mut module1 = module.clone();

        assert!(custom_section_index_for(&module, "name").is_some());

        let dropper = DropSection::CustomSectionByName("name".to_string());
        let dropper1 = DropSection::NamesSection;

        assert!(dropper
            .translate_inplace(&mut module)
            .expect("Should not fail"));
        assert!(dropper1
            .translate_inplace(&mut module1)
            .expect("Should not fail"));

        assert!(custom_section_index_for(&module, "name").is_none());
        assert!(custom_section_index_for(&module1, "name").is_none());
    }

    #[test]
    fn dropped_name_section_index_unparsed() {
        let input = FromHex::from_hex(
            "0061736d010000000104016000000303020000070801046d61696e00010a
            0a020300010b040010000b0014046e616d65010d0200047465737401046d
            61696e",
        )
        .unwrap();

        let mut module = Module::from_bytes(&input).unwrap();
        let mut module1 = module.clone();

        assert!(custom_section_index_for(&module, "name").is_some());

        let dropper = DropSection::CustomSectionByName("name".to_string());
        let dropper1 = DropSection::NamesSection;

        assert!(dropper
            .translate_inplace(&mut module)
            .expect("Should not fail"));
        assert!(dropper1
            .translate_inplace(&mut module1)
            .expect("Should not fail"));

        assert!(custom_section_index_for(&module, "name").is_none());
        assert!(custom_section_index_for(&module1, "name").is_none());
    }
}