Given the initialized snapshot, rewrite the Wasm so that it is already initialized.
(
&self,
module: &mut ModuleContext<'_>,
snapshot: &Snapshot,
renames: &FuncRenames,
remove_wasi_initialize: bool,
)
| 11 | /// initialized. |
| 12 | /// |
| 13 | pub(crate) fn rewrite( |
| 14 | &self, |
| 15 | module: &mut ModuleContext<'_>, |
| 16 | snapshot: &Snapshot, |
| 17 | renames: &FuncRenames, |
| 18 | remove_wasi_initialize: bool, |
| 19 | ) -> Vec<u8> { |
| 20 | log::debug!("Rewriting input Wasm to pre-initialized state"); |
| 21 | |
| 22 | let mut encoder = wasm_encoder::Module::new(); |
| 23 | let has_wasi_initialize = module.has_wasi_initialize(); |
| 24 | |
| 25 | // Encode the initialized data segments from the snapshot rather |
| 26 | // than the original, uninitialized data segments. |
| 27 | let add_data_segments = |data_section: &mut wasm_encoder::DataSection| { |
| 28 | for seg in &snapshot.data_segments { |
| 29 | let offset = if seg.is64 { |
| 30 | ConstExpr::i64_const(seg.offset.cast_signed()) |
| 31 | } else { |
| 32 | ConstExpr::i32_const(u32::try_from(seg.offset).unwrap().cast_signed()) |
| 33 | }; |
| 34 | data_section.active(seg.memory_index, &offset, seg.data.iter().copied()); |
| 35 | } |
| 36 | }; |
| 37 | |
| 38 | // There are multiple places were we potentially need to check whether |
| 39 | // we've added the data section already and if we haven't yet, then do |
| 40 | // so. For example, the original Wasm might not have a data section at |
| 41 | // all, and so we have to potentially add it at the end of iterating |
| 42 | // over the original sections. This closure encapsulates all that |
| 43 | // add-it-if-we-haven't-already logic in one place. |
| 44 | let added_data_section = Cell::new(false); |
| 45 | |
| 46 | let add_data_section = |encoder: &mut wasm_encoder::Module| { |
| 47 | if added_data_section.get() { |
| 48 | return; |
| 49 | } |
| 50 | added_data_section.set(true); |
| 51 | let mut data_section = wasm_encoder::DataSection::new(); |
| 52 | add_data_segments(&mut data_section); |
| 53 | encoder.section(&data_section); |
| 54 | }; |
| 55 | |
| 56 | for section in module.raw_sections() { |
| 57 | match section { |
| 58 | // Some tools expect the name custom section to come last, even |
| 59 | // though custom sections are allowed in any order. Therefore, |
| 60 | // make sure we've added our data section by now. |
| 61 | s if is_name_section(s) => { |
| 62 | add_data_section(&mut encoder); |
| 63 | encoder.section(s); |
| 64 | } |
| 65 | |
| 66 | // For the memory section, we update the minimum size of each |
| 67 | // defined memory to the snapshot's initialized size for that |
| 68 | // memory. |
| 69 | s if s.id == u8::from(SectionId::Memory) => { |
| 70 | let mut memories = wasm_encoder::MemorySection::new(); |
no test coverage detected