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
//! Exported items in a wasm module.

use crate::emit::{Emit, EmitContext, Section};
use crate::parse::IndicesToIds;
use crate::tombstone_arena::{Id, Tombstone, TombstoneArena};
use crate::{FunctionId, GlobalId, MemoryId, Module, Result, TableId};

/// The id of an export.
pub type ExportId = Id<Export>;

/// A named item exported from the wasm.
#[derive(Clone, Debug)]
pub struct Export {
    id: ExportId,
    /// The name of this export.
    pub name: String,
    /// The item being exported.
    pub item: ExportItem,
}

impl Tombstone for Export {
    fn on_delete(&mut self) {
        self.name = String::new();
    }
}

impl Export {
    /// Returns the id of this export
    pub fn id(&self) -> ExportId {
        self.id
    }
}

/// An exported item.
#[derive(Copy, Clone, Debug)]
pub enum ExportItem {
    /// An exported function.
    Function(FunctionId),
    /// An exported table.
    Table(TableId),
    /// An exported memory.
    Memory(MemoryId),
    /// An exported global.
    Global(GlobalId),
}

/// The set of exports in a module.
#[derive(Debug, Default)]
pub struct ModuleExports {
    /// The arena containing this module's exports.
    arena: TombstoneArena<Export>,
}

impl ModuleExports {
    /// Gets a reference to an export given its id
    pub fn get(&self, id: ExportId) -> &Export {
        &self.arena[id]
    }

    /// Gets a reference to an export given its id
    pub fn get_mut(&mut self, id: ExportId) -> &mut Export {
        &mut self.arena[id]
    }

    /// Delete an export entry from this module.
    pub fn delete(&mut self, id: ExportId) {
        self.arena.delete(id);
    }

    /// Get a shared reference to this module's exports.
    pub fn iter(&self) -> impl Iterator<Item = &Export> {
        self.arena.iter().map(|(_, f)| f)
    }

    /// Get a mutable reference to this module's exports.
    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut Export> {
        self.arena.iter_mut().map(|(_, f)| f)
    }

    /// Add a new export to this module
    pub fn add(&mut self, name: &str, item: impl Into<ExportItem>) -> ExportId {
        self.arena.alloc_with_id(|id| Export {
            id,
            name: name.to_string(),
            item: item.into(),
        })
    }

    #[doc(hidden)]
    #[deprecated(note = "Use `ModuleExports::delete` instead")]
    pub fn remove_root(&mut self, id: ExportId) {
        self.delete(id);
    }

    /// Get a reference to a function export given its function id.
    pub fn get_exported_func(&self, f: FunctionId) -> Option<&Export> {
        self.iter().find(|e| match e.item {
            ExportItem::Function(f0) => f0 == f,
            _ => false,
        })
    }

    /// Get a reference to a table export given its table id.
    pub fn get_exported_table(&self, t: TableId) -> Option<&Export> {
        self.iter().find(|e| match e.item {
            ExportItem::Table(t0) => t0 == t,
            _ => false,
        })
    }

    /// Get a reference to a memory export given its export id.
    pub fn get_exported_memory(&self, m: MemoryId) -> Option<&Export> {
        self.iter().find(|e| match e.item {
            ExportItem::Memory(m0) => m0 == m,
            _ => false,
        })
    }

    /// Get a reference to a global export given its global id.
    pub fn get_exported_global(&self, g: GlobalId) -> Option<&Export> {
        self.iter().find(|e| match e.item {
            ExportItem::Global(g0) => g0 == g,
            _ => false,
        })
    }
}

impl Module {
    /// Construct the export set for a wasm module.
    pub(crate) fn parse_exports(
        &mut self,
        section: wasmparser::ExportSectionReader,
        ids: &IndicesToIds,
    ) -> Result<()> {
        log::debug!("parse export section");
        use wasmparser::ExternalKind::*;

        for entry in section {
            let entry = entry?;
            let item = match entry.kind {
                Function => ExportItem::Function(ids.get_func(entry.index)?),
                Table => ExportItem::Table(ids.get_table(entry.index)?),
                Memory => ExportItem::Memory(ids.get_memory(entry.index)?),
                Global => ExportItem::Global(ids.get_global(entry.index)?),
            };
            self.exports.arena.alloc_with_id(|id| Export {
                id,
                name: entry.field.to_string(),
                item,
            });
        }
        Ok(())
    }
}

impl Emit for ModuleExports {
    fn emit(&self, cx: &mut EmitContext) {
        log::debug!("emit export section");
        // NB: exports are always considered used. They are the roots that the
        // used analysis searches out from.

        let count = self.iter().count();
        if count == 0 {
            return;
        }

        let mut cx = cx.start_section(Section::Export);
        cx.encoder.usize(count);

        for export in self.iter() {
            cx.encoder.str(&export.name);
            match export.item {
                ExportItem::Function(id) => {
                    let index = cx.indices.get_func_index(id);
                    cx.encoder.byte(0x00);
                    cx.encoder.u32(index);
                }
                ExportItem::Table(id) => {
                    let index = cx.indices.get_table_index(id);
                    cx.encoder.byte(0x01);
                    cx.encoder.u32(index);
                }
                ExportItem::Memory(id) => {
                    let index = cx.indices.get_memory_index(id);
                    cx.encoder.byte(0x02);
                    cx.encoder.u32(index);
                }
                ExportItem::Global(id) => {
                    let index = cx.indices.get_global_index(id);
                    cx.encoder.byte(0x03);
                    cx.encoder.u32(index);
                }
            }
        }
    }
}

impl From<MemoryId> for ExportItem {
    fn from(id: MemoryId) -> ExportItem {
        ExportItem::Memory(id)
    }
}

impl From<FunctionId> for ExportItem {
    fn from(id: FunctionId) -> ExportItem {
        ExportItem::Function(id)
    }
}

impl From<GlobalId> for ExportItem {
    fn from(id: GlobalId) -> ExportItem {
        ExportItem::Global(id)
    }
}

impl From<TableId> for ExportItem {
    fn from(id: TableId) -> ExportItem {
        ExportItem::Table(id)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{FunctionBuilder, Module};
    use id_arena::Arena;

    /// this function always returns the same ID
    fn always_the_same_id<T>() -> Id<T> {
        let arena: Arena<T> = Arena::new();
        arena.next_id()
    }

    #[test]
    fn get_exported_func() {
        let mut module = Module::default();
        let mut builder = FunctionBuilder::new(&mut module.types, &[], &[]);
        builder.func_body().i32_const(1234).drop();
        let id: FunctionId = builder.finish(vec![], &mut module.funcs);
        module.exports.add("dummy", id);

        let actual: Option<&Export> = module.exports.get_exported_func(id);

        let export: &Export = actual.expect("Expected Some(Export) got None");
        assert_eq!(export.name, "dummy");
        match export.item {
            ExportItem::Function(f) => assert_eq!(f, id),
            _ => panic!("Expected a Function variant"),
        }
    }

    #[test]
    fn get_exported_func_should_return_none_for_unknown_function_id() {
        let module = Module::default();
        let id: FunctionId = always_the_same_id();
        let actual: Option<&Export> = module.exports.get_exported_func(id);
        assert!(actual.is_none());
    }

    #[test]
    fn get_exported_table() {
        let mut module = Module::default();
        let id: TableId = always_the_same_id();
        module.exports.add("dummy", id);

        let actual: Option<&Export> = module.exports.get_exported_table(id);

        let export: &Export = actual.expect("Expected Some(Export) got None");
        assert_eq!(export.name, "dummy");
        match export.item {
            ExportItem::Table(f) => assert_eq!(f, id),
            _ => panic!("Expected a Table variant"),
        }
    }

    #[test]
    fn get_exported_table_should_return_none_for_unknown_table_id() {
        let module = Module::default();
        let id: TableId = always_the_same_id();
        let actual: Option<&Export> = module.exports.get_exported_table(id);
        assert!(actual.is_none());
    }

    #[test]
    fn get_exported_memory() {
        let mut module = Module::default();
        let id: MemoryId = always_the_same_id();
        module.exports.add("dummy", id);

        let actual: Option<&Export> = module.exports.get_exported_memory(id);

        let export: &Export = actual.expect("Expected Some(Export) got None");
        assert_eq!(export.name, "dummy");
        match export.item {
            ExportItem::Memory(f) => assert_eq!(f, id),
            _ => panic!("Expected a Memory variant"),
        }
    }

    #[test]
    fn get_exported_memory_should_return_none_for_unknown_memory_id() {
        let module = Module::default();
        let id: MemoryId = always_the_same_id();
        let actual: Option<&Export> = module.exports.get_exported_memory(id);
        assert!(actual.is_none());
    }

    #[test]
    fn get_exported_global() {
        let mut module = Module::default();
        let id: GlobalId = always_the_same_id();
        module.exports.add("dummy", id);

        let actual: Option<&Export> = module.exports.get_exported_global(id);

        let export: &Export = actual.expect("Expected Some(Export) got None");
        assert_eq!(export.name, "dummy");
        match export.item {
            ExportItem::Global(f) => assert_eq!(f, id),
            _ => panic!("Expected a Global variant"),
        }
    }

    #[test]
    fn get_exported_global_should_return_none_for_unknown_global_id() {
        let module = Module::default();
        let id: GlobalId = always_the_same_id();
        let actual: Option<&Export> = module.exports.get_exported_global(id);
        assert!(actual.is_none());
    }

    #[test]
    fn delete() {
        let mut module = Module::default();
        let fn_id: FunctionId = always_the_same_id();
        let export_id: ExportId = module.exports.add("dummy", fn_id);
        assert!(module.exports.get_exported_func(fn_id).is_some());
        module.exports.delete(export_id);

        assert!(module.exports.get_exported_func(fn_id).is_none());
    }

    #[test]
    fn iter_mut_can_update_export_item() {
        let mut module = Module::default();

        let mut builder = FunctionBuilder::new(&mut module.types, &[], &[]);
        builder.func_body().i32_const(1234).drop();
        let fn_id0: FunctionId = builder.finish(vec![], &mut module.funcs);

        let mut builder = FunctionBuilder::new(&mut module.types, &[], &[]);
        builder.func_body().i32_const(1234).drop();
        let fn_id1: FunctionId = builder.finish(vec![], &mut module.funcs);

        assert_ne!(fn_id0, fn_id1);

        let export_id: ExportId = module.exports.add("dummy", fn_id0);
        assert!(module.exports.get_exported_func(fn_id0).is_some());

        module
            .exports
            .iter_mut()
            .for_each(|x: &mut Export| x.item = ExportItem::Function(fn_id1));

        assert!(module.exports.get_exported_func(fn_id0).is_none());
        let actual: &Export = module
            .exports
            .get_exported_func(fn_id1)
            .expect("Expected Some(Export) got None");
        assert_eq!(actual.id, export_id);
        assert_eq!(actual.name, "dummy");
        match actual.item {
            ExportItem::Function(f) => assert_eq!(f, fn_id1),
            _ => panic!("Expected a Function variant"),
        }
    }
}