Skip to main content

component_init_transform/
lib.rs

1#![deny(warnings)]
2
3use {
4    anyhow::{Context, Result, bail},
5    async_trait::async_trait,
6    futures::future::BoxFuture,
7    std::{
8        collections::{HashMap, HashSet, hash_map::Entry},
9        convert, iter,
10        ops::Range,
11    },
12    wasm_encoder::{
13        Alias, CanonicalFunctionSection, CanonicalOption, CodeSection, Component,
14        ComponentAliasSection, ComponentExportKind, ComponentExportSection, ComponentTypeSection,
15        ComponentValType, ConstExpr, DataCountSection, DataSection, ExportKind, ExportSection,
16        Function, FunctionSection, GlobalSection, GlobalType, ImportSection, InstanceSection,
17        Instruction as Ins, MemArg, MemorySection, Module, ModuleArg, ModuleSection,
18        NestedComponentSection, PrimitiveValType, RawSection, TypeSection, ValType,
19        reencode::{Reencode, RoundtripReencoder as Encode},
20    },
21    wasmparser::{
22        CanonicalFunction, ComponentAlias, ComponentExternalKind, ComponentTypeRef, Data, DataKind,
23        ExternalKind, Imports, Instance, Operator, Parser, Payload, TypeRef, Validator,
24        WasmFeatures,
25    },
26};
27
28const PAGE_SIZE_BYTES: i32 = 64 * 1024;
29
30// TODO: this should ideally be 8 in order to minimize binary size, but that can result in larger numbers of data
31// segments than some tools and runtimes will tolerate.  We should probably start at 8 and increase as necessary if
32// the segment count is too high for a given component.
33const MAX_CONSECUTIVE_ZEROS: usize = 64;
34
35#[async_trait]
36pub trait Invoker {
37    async fn call_s32(&mut self, function: &str) -> Result<i32>;
38    async fn call_s64(&mut self, function: &str) -> Result<i64>;
39    async fn call_f32(&mut self, function: &str) -> Result<f32>;
40    async fn call_f64(&mut self, function: &str) -> Result<f64>;
41    async fn call_list_u8(&mut self, function: &str) -> Result<Vec<u8>>;
42}
43
44pub async fn initialize(
45    component: &[u8],
46    initialize: impl FnOnce(Vec<u8>) -> BoxFuture<'static, Result<Box<dyn Invoker>>>,
47) -> Result<Vec<u8>> {
48    initialize_staged(component, None, initialize).await
49}
50
51pub type Stage2Map<'a> = Option<(&'a [u8], &'a dyn Fn(u32) -> u32)>;
52
53#[allow(clippy::type_complexity)]
54pub async fn initialize_staged(
55    component_stage1: &[u8],
56    component_stage2_and_map_module_index: Stage2Map<'_>,
57    initialize: impl FnOnce(Vec<u8>) -> BoxFuture<'static, Result<Box<dyn Invoker>>>,
58) -> Result<Vec<u8>> {
59    // First, instrument the input component, validating that it conforms to certain rules and exposing the memory
60    // and all mutable globals via synthesized function exports.
61    //
62    // Note that we currently only support a certain style of component, but plan to eventually generalize this
63    // tool to support arbitrary component graphs.
64    //
65    // Current rules:
66    // - Flat structure (i.e. no subcomponents)
67    // - Single memory
68    // - No runtime table operations
69    // - No reference type globals
70    // - Each module instantiated at most once
71    //
72    // `instrumentation` keeps track of all of the state which will be gathered from the instrumented
73    // component.
74    let (instrumented_component, instrumentation) = instrument(component_stage1)?;
75
76    Validator::new_with_features(WasmFeatures::all()).validate_all(&instrumented_component)?;
77
78    // A component runtime will instantiate the component and run its component init function.
79    let mut invoker = initialize(instrumented_component).await?;
80
81    // The Invoker interface is used to extract the values instrumentation provided into a
82    // measurement.
83    let measurement = instrumentation.measure(&mut invoker).await?;
84
85    // Finally, create a new component by applying the measurement (contents of all globals and memory) to the component.
86    // The resulting component will identical to the original except with all mutable globals initialized to
87    // the snapshoted values, with all data sections and start functions removed, and with a single active data
88    // section added containing the memory snapshot.
89    apply(
90        measurement,
91        component_stage1,
92        component_stage2_and_map_module_index,
93    )
94}
95
96struct MemoryInfo {
97    module_index: u32,
98    export_name: String,
99    ty: wasmparser::MemoryType,
100}
101type GlobalMap<T> = HashMap<u32, HashMap<u32, T>>;
102#[derive(Debug)]
103enum GlobalExport {
104    Existing {
105        module_index: u32,
106        global_index: u32,
107        export_name: String,
108    },
109    Synthesized {
110        module_index: u32,
111        global_index: u32,
112    },
113}
114impl GlobalExport {
115    fn module_export(&self) -> String {
116        match self {
117            Self::Existing { export_name, .. } => export_name.clone(),
118            Self::Synthesized { global_index, .. } => format!("component-init:{global_index}"),
119        }
120    }
121    fn component_export(&self) -> String {
122        match self {
123            Self::Existing {
124                module_index,
125                global_index,
126                ..
127            } => format!("component-init-get-module{module_index}-global{global_index}"),
128            Self::Synthesized {
129                module_index,
130                global_index,
131            } => format!("component-init-get-module{module_index}-global{global_index}"),
132        }
133    }
134}
135
136#[derive(Default)]
137struct Instrumentation {
138    memory: Option<MemoryInfo>,
139    globals: GlobalMap<(GlobalExport, wasmparser::ValType)>,
140    modules_with_passive_data_segments: HashSet<u32>,
141}
142impl Instrumentation {
143    fn register_memory(
144        &mut self,
145        module_index: u32,
146        name: impl AsRef<str>,
147        ty: wasmparser::MemoryType,
148    ) -> Result<()> {
149        if self.memory.is_some() {
150            bail!("only one memory allowed per component");
151        }
152        self.memory = Some(MemoryInfo {
153            module_index,
154            export_name: name.as_ref().to_string(),
155            ty,
156        });
157        Ok(())
158    }
159    fn register_global(&mut self, module_index: u32, global_index: u32, ty: wasmparser::ValType) {
160        self.globals.entry(module_index).or_default().insert(
161            global_index,
162            (
163                GlobalExport::Synthesized {
164                    module_index,
165                    global_index,
166                },
167                ty,
168            ),
169        );
170    }
171    fn register_global_export(
172        &mut self,
173        module_index: u32,
174        global_index: u32,
175        export_name: impl AsRef<str>,
176    ) {
177        if let Some((name, _)) = self
178            .globals
179            .get_mut(&module_index)
180            .and_then(|map| map.get_mut(&global_index))
181        {
182            let export_name = export_name.as_ref().to_string();
183            *name = GlobalExport::Existing {
184                module_index,
185                global_index,
186                export_name,
187            };
188        }
189    }
190    fn amend_module_exports(&self, module_index: u32, exports: &mut ExportSection) {
191        if let Some(g_map) = self.globals.get(&module_index) {
192            for (export, _ty) in g_map.values() {
193                if let GlobalExport::Synthesized { global_index, .. } = export {
194                    exports.export(&export.module_export(), ExportKind::Global, *global_index);
195                }
196            }
197        }
198    }
199    async fn measure(&self, invoker: &mut Box<dyn Invoker>) -> Result<Measurement> {
200        let mut globals = HashMap::new();
201
202        for (module_index, globals_to_export) in &self.globals {
203            let mut my_global_values = HashMap::new();
204            for (global_index, (global_export, ty)) in globals_to_export {
205                my_global_values.insert(
206                    *global_index,
207                    match ty {
208                        wasmparser::ValType::I32 => ConstExpr::i32_const(
209                            invoker
210                                .call_s32(&global_export.component_export())
211                                .await
212                                .with_context(|| {
213                                    format!("retrieving global value {global_export:?}")
214                                })?,
215                        ),
216                        wasmparser::ValType::I64 => ConstExpr::i64_const(
217                            invoker
218                                .call_s64(&global_export.component_export())
219                                .await
220                                .with_context(|| {
221                                    format!("retrieving global value {global_export:?}")
222                                })?,
223                        ),
224                        wasmparser::ValType::F32 => ConstExpr::f32_const(
225                            invoker
226                                .call_f32(&global_export.component_export())
227                                .await
228                                .with_context(|| {
229                                    format!("retrieving global value {global_export:?}")
230                                })?
231                                .into(),
232                        ),
233                        wasmparser::ValType::F64 => ConstExpr::f64_const(
234                            invoker
235                                .call_f64(&global_export.component_export())
236                                .await
237                                .with_context(|| {
238                                    format!("retrieving global value {global_export:?}")
239                                })?
240                                .into(),
241                        ),
242                        wasmparser::ValType::V128 => bail!("V128 not yet supported"),
243                        wasmparser::ValType::Ref(_) => bail!("reference types not supported"),
244                    },
245                );
246            }
247            globals.insert(*module_index, my_global_values);
248        }
249
250        let memory = if let Some(info) = &self.memory {
251            let name = "component-init-get-memory";
252            Some((
253                info.module_index,
254                invoker
255                    .call_list_u8(name)
256                    .await
257                    .with_context(|| format!("retrieving memory with {name}"))?,
258            ))
259        } else {
260            None
261        };
262        Ok(Measurement {
263            memory,
264            globals,
265            modules_with_passive_data_segments: self.modules_with_passive_data_segments.clone(),
266        })
267    }
268}
269
270struct Measurement {
271    memory: Option<(u32, Vec<u8>)>,
272    globals: GlobalMap<wasm_encoder::ConstExpr>,
273    modules_with_passive_data_segments: HashSet<u32>,
274}
275
276impl Measurement {
277    fn data_section(&self, module_index: u32) -> (Option<DataSection>, u32) {
278        if let Some((m_ix, value)) = &self.memory
279            && *m_ix == module_index
280        {
281            let mut data = DataSection::new();
282            let mut data_segment_count = 0;
283            for (start, len) in Segments::new(value) {
284                data_segment_count += 1;
285                data.active(
286                    0,
287                    &ConstExpr::i32_const(start.try_into().unwrap()),
288                    value[start..][..len].iter().copied(),
289                );
290            }
291            (Some(data), data_segment_count)
292        } else {
293            (None, 0)
294        }
295    }
296
297    fn memory_initial(&self, module_index: u32) -> Option<u64> {
298        if let Some((m_ix, value)) = &self.memory
299            && *m_ix == module_index
300        {
301            Some(
302                u64::try_from((value.len() / usize::try_from(PAGE_SIZE_BYTES).unwrap()) + 1)
303                    .unwrap(),
304            )
305        } else {
306            None
307        }
308    }
309
310    fn global_init(&self, module_index: u32, global_index: u32) -> Option<wasm_encoder::ConstExpr> {
311        self.globals
312            .get(&module_index)
313            .and_then(|m| m.get(&global_index).cloned())
314    }
315}
316
317fn instrument(component_stage1: &[u8]) -> Result<(Vec<u8>, Instrumentation)> {
318    let mut module_count = 0;
319    let mut instance_count = 0;
320    let mut core_function_count = 0;
321    let mut function_count = 0;
322    let mut type_count = 0;
323    let mut instrumentation = Instrumentation::default();
324    let mut instantiations = HashMap::new();
325    let mut instrumented_component = Component::new();
326    let mut parser = Parser::new(0).parse_all(component_stage1);
327    #[allow(clippy::while_let_on_iterator)]
328    while let Some(payload) = parser.next() {
329        let payload = payload?;
330        let section = payload.as_section();
331        match payload {
332            Payload::ComponentSection {
333                unchecked_range, ..
334            } => {
335                let mut subcomponent = Component::new();
336                while let Some(payload) = parser.next() {
337                    let payload = payload?;
338                    let section = payload.as_section();
339                    let my_range = section.as_ref().map(|(_, range)| range.clone());
340                    copy_component_section(section, component_stage1, &mut subcomponent);
341
342                    if let Some(my_range) = my_range
343                        && my_range.end >= unchecked_range.end
344                    {
345                        break;
346                    }
347                }
348                instrumented_component.section(&NestedComponentSection(&subcomponent));
349            }
350
351            Payload::ModuleSection {
352                unchecked_range, ..
353            } => {
354                let module_index = get_and_increment(&mut module_count);
355                let mut global_types = Vec::new();
356                let mut instrumented_module = Module::new();
357                let mut global_count = 0;
358                while let Some(payload) = parser.next() {
359                    let payload = payload?;
360                    let section = payload.as_section();
361                    let my_range = section.as_ref().map(|(_, range)| range.clone());
362                    match payload {
363                        Payload::ImportSection(reader) => {
364                            for import in reader {
365                                match import? {
366                                    Imports::Single(_, import) => {
367                                        if let TypeRef::Global(_) = import.ty {
368                                            global_count += 1;
369                                        }
370                                    }
371                                    Imports::Compact1 { .. } | Imports::Compact2 { .. } => todo!(),
372                                }
373                            }
374                            copy_module_section(
375                                section,
376                                component_stage1,
377                                &mut instrumented_module,
378                            );
379                        }
380
381                        Payload::MemorySection(reader) => {
382                            for memory in reader {
383                                instrumentation.register_memory(module_index, "memory", memory?)?;
384                            }
385                            copy_module_section(
386                                section,
387                                component_stage1,
388                                &mut instrumented_module,
389                            );
390                        }
391
392                        Payload::GlobalSection(reader) => {
393                            for global in reader {
394                                let global = global?;
395                                let ty = global.ty;
396                                global_types.push(ty);
397                                let global_index = get_and_increment(&mut global_count);
398                                if global.ty.mutable {
399                                    instrumentation.register_global(
400                                        module_index,
401                                        global_index,
402                                        ty.content_type,
403                                    )
404                                }
405                            }
406                            copy_module_section(
407                                section,
408                                component_stage1,
409                                &mut instrumented_module,
410                            );
411                        }
412
413                        Payload::ExportSection(reader) => {
414                            let mut exports = ExportSection::new();
415                            for export in reader {
416                                let export = export?;
417                                if let ExternalKind::Global = export.kind {
418                                    instrumentation.register_global_export(
419                                        module_index,
420                                        export.index,
421                                        export.name,
422                                    )
423                                }
424                                exports.export(
425                                    export.name,
426                                    Encode.export_kind(export.kind)?,
427                                    export.index,
428                                );
429                            }
430
431                            instrumentation.amend_module_exports(module_index, &mut exports);
432
433                            instrumented_module.section(&exports);
434                        }
435
436                        Payload::CodeSectionEntry(body) => {
437                            for operator in body.get_operators_reader()? {
438                                match operator? {
439                                    Operator::TableCopy { .. }
440                                    | Operator::TableFill { .. }
441                                    | Operator::TableGrow { .. }
442                                    | Operator::TableInit { .. }
443                                    | Operator::TableSet { .. } => {
444                                        bail!("table operations not allowed");
445                                    }
446
447                                    _ => (),
448                                }
449                            }
450                            copy_module_section(
451                                section,
452                                component_stage1,
453                                &mut instrumented_module,
454                            );
455                        }
456
457                        Payload::DataSection(reader) => {
458                            if reader.clone().into_iter().any(|data| {
459                                matches!(
460                                    data,
461                                    Ok(Data {
462                                        kind: DataKind::Passive,
463                                        ..
464                                    })
465                                )
466                            }) {
467                                instrumentation
468                                    .modules_with_passive_data_segments
469                                    .insert(module_index);
470                            }
471                            copy_module_section(section, component_stage1, &mut instrumented_module)
472                        }
473
474                        _ => {
475                            copy_module_section(section, component_stage1, &mut instrumented_module)
476                        }
477                    }
478
479                    if let Some(my_range) = my_range
480                        && my_range.end >= unchecked_range.end
481                    {
482                        break;
483                    }
484                }
485                instrumented_component.section(&ModuleSection(&instrumented_module));
486            }
487
488            Payload::InstanceSection(reader) => {
489                for instance in reader {
490                    let instance_index = get_and_increment(&mut instance_count);
491
492                    if let Instance::Instantiate { module_index, .. } = instance? {
493                        match instantiations.entry(module_index) {
494                            Entry::Vacant(entry) => {
495                                entry.insert(instance_index);
496                            }
497                            Entry::Occupied(_) => bail!("modules may be instantiated at most once"),
498                        }
499                    }
500                }
501                copy_component_section(section, component_stage1, &mut instrumented_component);
502            }
503
504            Payload::ComponentAliasSection(reader) => {
505                for alias in reader {
506                    match alias? {
507                        ComponentAlias::CoreInstanceExport {
508                            kind: ExternalKind::Func,
509                            ..
510                        } => {
511                            core_function_count += 1;
512                        }
513                        ComponentAlias::InstanceExport {
514                            kind: ComponentExternalKind::Type,
515                            ..
516                        } => {
517                            type_count += 1;
518                        }
519                        ComponentAlias::InstanceExport {
520                            kind: ComponentExternalKind::Func,
521                            ..
522                        } => {
523                            function_count += 1;
524                        }
525                        _ => (),
526                    }
527                }
528                copy_component_section(section, component_stage1, &mut instrumented_component);
529            }
530
531            Payload::ComponentCanonicalSection(reader) => {
532                for function in reader {
533                    match function? {
534                        CanonicalFunction::Lower { .. }
535                        | CanonicalFunction::ThreadSpawnRef { .. }
536                        | CanonicalFunction::ThreadSpawnIndirect { .. }
537                        | CanonicalFunction::ThreadAvailableParallelism { .. }
538                        | CanonicalFunction::SubtaskCancel { .. }
539                        | CanonicalFunction::ThreadIndex
540                        | CanonicalFunction::ThreadNewIndirect { .. }
541                        | CanonicalFunction::ThreadResumeLater
542                        | CanonicalFunction::ThreadSuspend { .. }
543                        | CanonicalFunction::ThreadSuspendThenResume { .. }
544                        | CanonicalFunction::ThreadSuspendThenPromote { .. }
545                        | CanonicalFunction::ThreadYield { .. }
546                        | CanonicalFunction::ThreadYieldThenResume { .. }
547                        | CanonicalFunction::ThreadYieldThenPromote { .. }
548                        | CanonicalFunction::ResourceNew { .. }
549                        | CanonicalFunction::ResourceDrop { .. }
550                        | CanonicalFunction::ResourceRep { .. }
551                        | CanonicalFunction::BackpressureInc
552                        | CanonicalFunction::BackpressureDec
553                        | CanonicalFunction::TaskCancel
554                        | CanonicalFunction::TaskReturn { .. }
555                        | CanonicalFunction::ContextGet { .. }
556                        | CanonicalFunction::ContextSet { .. }
557                        | CanonicalFunction::SubtaskDrop
558                        | CanonicalFunction::WaitableSetNew
559                        | CanonicalFunction::WaitableSetWait { .. }
560                        | CanonicalFunction::WaitableSetPoll { .. }
561                        | CanonicalFunction::WaitableSetDrop
562                        | CanonicalFunction::WaitableJoin
563                        | CanonicalFunction::StreamNew { .. }
564                        | CanonicalFunction::StreamRead { .. }
565                        | CanonicalFunction::StreamWrite { .. }
566                        | CanonicalFunction::StreamCancelRead { .. }
567                        | CanonicalFunction::StreamCancelWrite { .. }
568                        | CanonicalFunction::StreamDropReadable { .. }
569                        | CanonicalFunction::StreamDropWritable { .. }
570                        | CanonicalFunction::FutureNew { .. }
571                        | CanonicalFunction::FutureRead { .. }
572                        | CanonicalFunction::FutureWrite { .. }
573                        | CanonicalFunction::FutureCancelRead { .. }
574                        | CanonicalFunction::FutureCancelWrite { .. }
575                        | CanonicalFunction::FutureDropReadable { .. }
576                        | CanonicalFunction::FutureDropWritable { .. }
577                        | CanonicalFunction::ErrorContextNew { .. }
578                        | CanonicalFunction::ErrorContextDebugMessage { .. }
579                        | CanonicalFunction::ErrorContextDrop => {
580                            core_function_count += 1;
581                        }
582                        CanonicalFunction::Lift { .. } => {
583                            function_count += 1;
584                        }
585                    }
586                }
587                copy_component_section(section, component_stage1, &mut instrumented_component);
588            }
589
590            Payload::ComponentImportSection(reader) => {
591                for import in reader {
592                    match import?.ty {
593                        ComponentTypeRef::Func(_) => {
594                            function_count += 1;
595                        }
596                        ComponentTypeRef::Type(_) => {
597                            type_count += 1;
598                        }
599                        _ => (),
600                    }
601                }
602                copy_component_section(section, component_stage1, &mut instrumented_component);
603            }
604
605            Payload::ComponentExportSection(reader) => {
606                for export in reader {
607                    match export?.kind {
608                        ComponentExternalKind::Func => {
609                            function_count += 1;
610                        }
611                        ComponentExternalKind::Type => {
612                            type_count += 1;
613                        }
614                        _ => (),
615                    }
616                }
617                copy_component_section(section, component_stage1, &mut instrumented_component);
618            }
619
620            Payload::ComponentTypeSection(reader) => {
621                for _ in reader {
622                    type_count += 1;
623                }
624                copy_component_section(section, component_stage1, &mut instrumented_component);
625            }
626
627            _ => copy_component_section(section, component_stage1, &mut instrumented_component),
628        }
629    }
630
631    let mut types = TypeSection::new();
632    let mut imports = ImportSection::new();
633    let mut functions = FunctionSection::new();
634    let mut exports = ExportSection::new();
635    let mut code = CodeSection::new();
636    let mut aliases = ComponentAliasSection::new();
637    let mut lifts = CanonicalFunctionSection::new();
638    let mut component_types = ComponentTypeSection::new();
639    let mut component_exports = ComponentExportSection::new();
640
641    for (module_index, module_globals) in &instrumentation.globals {
642        for (global_export, ty) in module_globals.values() {
643            let ty = Encode.val_type(*ty)?;
644            let offset = types.len();
645            types.ty().function([], [ty]);
646            imports.import(
647                &module_index.to_string(),
648                &global_export.module_export(),
649                GlobalType {
650                    val_type: ty,
651                    mutable: true,
652                    shared: false,
653                },
654            );
655            functions.function(offset);
656            let mut function = Function::new([]);
657            function.instruction(&Ins::GlobalGet(offset));
658            function.instruction(&Ins::End);
659            code.function(&function);
660            let export_name = global_export.component_export();
661            exports.export(&export_name, ExportKind::Func, offset);
662            aliases.alias(Alias::CoreInstanceExport {
663                instance: instance_count,
664                kind: ExportKind::Func,
665                name: &export_name,
666            });
667            component_types
668                .function()
669                .params(iter::empty::<(_, ComponentValType)>())
670                .result(Some(ComponentValType::Primitive(match ty {
671                    ValType::I32 => PrimitiveValType::S32,
672                    ValType::I64 => PrimitiveValType::S64,
673                    ValType::F32 => PrimitiveValType::F32,
674                    ValType::F64 => PrimitiveValType::F64,
675                    ValType::V128 => bail!("V128 not yet supported"),
676                    ValType::Ref(_) => bail!("reference types not supported"),
677                })));
678            lifts.lift(
679                core_function_count + offset,
680                type_count + component_types.len() - 1,
681                [CanonicalOption::UTF8],
682            );
683            component_exports.export(
684                &export_name,
685                ComponentExportKind::Func,
686                function_count + offset,
687                None,
688            );
689        }
690    }
691
692    if let Some(memory_info) = &instrumentation.memory {
693        let offset = types.len();
694        types.ty().function([], [wasm_encoder::ValType::I32]);
695        imports.import(
696            &memory_info.module_index.to_string(),
697            &memory_info.export_name,
698            Encode.entity_type(TypeRef::Memory(memory_info.ty))?,
699        );
700        functions.function(offset);
701
702        let mut function = Function::new([(1, wasm_encoder::ValType::I32)]);
703        function.instruction(&Ins::MemorySize(0));
704        // stack[0] = current memory, in pages
705
706        function.instruction(&Ins::I32Const(PAGE_SIZE_BYTES));
707        function.instruction(&Ins::I32Mul);
708        function.instruction(&Ins::LocalTee(0));
709        // stack[0] = local[0] = current memory, in bytes
710
711        function.instruction(&Ins::I32Const(1));
712        function.instruction(&Ins::MemoryGrow(0));
713        // stack[1] = old memory, in bytes
714        // stack[0] = grown memory, in pages, or -1 if failed
715        function.instruction(&Ins::I32Const(0));
716        function.instruction(&Ins::I32LtS);
717        function.instruction(&Ins::If(wasm_encoder::BlockType::Empty));
718        // Trap if memory grow failed
719        function.instruction(&Ins::Unreachable);
720        function.instruction(&Ins::Else);
721        function.instruction(&Ins::End);
722
723        // stack[0] = old memory, in bytes
724        function.instruction(&Ins::I32Const(0));
725        // stack[1] = old memory in bytes
726        // stack[0] = 0 (start of memory)
727        function.instruction(&Ins::I32Store(mem_arg(0, 1)));
728        // 0 stored at end of old memory
729        function.instruction(&Ins::LocalGet(0));
730        function.instruction(&Ins::LocalGet(0));
731        // stack[1] = old memory in bytes
732        // stack[0] = old memory in bytes
733        function.instruction(&Ins::I32Store(mem_arg(4, 1)));
734        // old memory size, stored at old memory + 4
735
736        function.instruction(&Ins::LocalGet(0));
737        // stack[0] = old memory in bytes
738        function.instruction(&Ins::End);
739        code.function(&function);
740
741        let export_name = "component-init-get-memory".to_owned();
742        exports.export(&export_name, ExportKind::Func, offset);
743        aliases.alias(Alias::CoreInstanceExport {
744            instance: instance_count,
745            kind: ExportKind::Func,
746            name: &export_name,
747        });
748        let list_type = type_count + component_types.len();
749        component_types.defined_type().list(PrimitiveValType::U8);
750        component_types
751            .function()
752            .params(iter::empty::<(_, ComponentValType)>())
753            .result(Some(ComponentValType::Type(list_type)));
754        lifts.lift(
755            core_function_count + offset,
756            type_count + component_types.len() - 1,
757            [CanonicalOption::UTF8, CanonicalOption::Memory(0)],
758        );
759        component_exports.export(
760            &export_name,
761            ComponentExportKind::Func,
762            function_count + offset,
763            None,
764        );
765    }
766
767    let mut instances = InstanceSection::new();
768    instances.instantiate(
769        module_count,
770        instantiations
771            .into_iter()
772            .map(|(module_index, instance_index)| {
773                (
774                    module_index.to_string(),
775                    ModuleArg::Instance(instance_index),
776                )
777            }),
778    );
779
780    let mut module = Module::new();
781    module.section(&types);
782    module.section(&imports);
783    module.section(&functions);
784    module.section(&exports);
785    module.section(&code);
786
787    instrumented_component.section(&ModuleSection(&module));
788    instrumented_component.section(&instances);
789    instrumented_component.section(&component_types);
790    instrumented_component.section(&aliases);
791    instrumented_component.section(&lifts);
792    instrumented_component.section(&component_exports);
793
794    // Next, invoke the provided `initialize` function, which will return a trait object through which we can
795    // invoke the functions we added above to capture the state of the initialized instance.
796
797    let instrumented_component = instrumented_component.finish();
798    Ok((instrumented_component, instrumentation))
799}
800
801fn apply(
802    measurement: Measurement,
803    component_stage1: &[u8],
804    component_stage2_and_map_module_index: Stage2Map<'_>,
805) -> Result<Vec<u8>> {
806    let (component_stage2, map_module_index) =
807        component_stage2_and_map_module_index.unwrap_or((component_stage1, &convert::identity));
808    let mut initialized_component = Component::new();
809    let mut parser = Parser::new(0).parse_all(component_stage2);
810    let mut module_count = 0;
811    #[allow(clippy::while_let_on_iterator)]
812    while let Some(payload) = parser.next() {
813        let payload = payload?;
814        let section = payload.as_section();
815        match payload {
816            Payload::ComponentSection {
817                unchecked_range, ..
818            } => {
819                let mut subcomponent = Component::new();
820                while let Some(payload) = parser.next() {
821                    let payload = payload?;
822                    let section = payload.as_section();
823                    let my_range = section.as_ref().map(|(_, range)| range.clone());
824                    copy_component_section(section, component_stage2, &mut subcomponent);
825
826                    if let Some(my_range) = my_range
827                        && my_range.end >= unchecked_range.end
828                    {
829                        break;
830                    }
831                }
832                initialized_component.section(&NestedComponentSection(&subcomponent));
833            }
834
835            Payload::ModuleSection {
836                unchecked_range, ..
837            } => {
838                let module_index = map_module_index(get_and_increment(&mut module_count));
839                let mut initialized_module = Module::new();
840                let mut global_count = 0;
841                let (data_section, data_segment_count) = measurement.data_section(module_index);
842                while let Some(payload) = parser.next() {
843                    let payload = payload?;
844                    let section = payload.as_section();
845                    let my_range = section.as_ref().map(|(_, range)| range.clone());
846                    match payload {
847                        Payload::MemorySection(reader) => {
848                            let mut memories = MemorySection::new();
849                            for memory in reader {
850                                let mut memory = memory?;
851
852                                memory.initial = measurement
853                                    .memory_initial(module_index)
854                                    .expect("measurement for module's memory");
855
856                                memories.memory(Encode.memory_type(memory)?);
857                            }
858                            initialized_module.section(&memories);
859                        }
860
861                        Payload::ImportSection(reader) => {
862                            for import in reader {
863                                match import? {
864                                    Imports::Single(_, import) => {
865                                        if let TypeRef::Global(_) = import.ty {
866                                            global_count += 1;
867                                        }
868                                    }
869                                    Imports::Compact1 { .. } | Imports::Compact2 { .. } => {
870                                        todo!()
871                                    }
872                                }
873                            }
874                            copy_module_section(section, component_stage2, &mut initialized_module);
875                        }
876
877                        Payload::GlobalSection(reader) => {
878                            let mut globals = GlobalSection::new();
879                            for global in reader {
880                                let global = global?;
881                                let global_index = get_and_increment(&mut global_count);
882                                globals.global(
883                                    Encode.global_type(global.ty)?,
884                                    &if global.ty.mutable {
885                                        measurement
886                                            .global_init(module_index, global_index)
887                                            .expect("measurement for global")
888                                    } else {
889                                        Encode.const_expr(global.init_expr)?
890                                    },
891                                );
892                            }
893                            initialized_module.section(&globals);
894                        }
895
896                        Payload::DataSection(reader) => {
897                            if measurement
898                                .modules_with_passive_data_segments
899                                .contains(&module_index)
900                            {
901                                assert!(data_section.is_none());
902                                let mut segments = DataSection::new();
903                                for data in reader {
904                                    let data = data?;
905                                    match &data.kind {
906                                        DataKind::Passive => {
907                                            segments.passive(data.data.iter().copied());
908                                        }
909                                        DataKind::Active { .. } => {
910                                            // dummy segment just to keep the indexes unchanged:
911                                            segments.active(0, &ConstExpr::i32_const(0), []);
912                                        }
913                                    }
914                                }
915                                initialized_module.section(&segments);
916                            }
917                        }
918
919                        Payload::StartSection { .. } => (),
920
921                        Payload::DataCountSection { count, .. } => {
922                            let count = if measurement
923                                .modules_with_passive_data_segments
924                                .contains(&module_index)
925                            {
926                                if data_section.is_some() {
927                                    bail!(
928                                        "not yet supported: modules with passive data segments _and_ snapshot segments"
929                                    );
930                                }
931                                count
932                            } else {
933                                data_segment_count
934                            };
935
936                            initialized_module.section(&DataCountSection { count });
937                        }
938
939                        _ => {
940                            copy_module_section(section, component_stage2, &mut initialized_module)
941                        }
942                    }
943
944                    if let Some(my_range) = my_range
945                        && my_range.end >= unchecked_range.end
946                    {
947                        break;
948                    }
949                }
950                if let Some(data_section) = data_section {
951                    initialized_module.section(&data_section);
952                }
953
954                initialized_component.section(&ModuleSection(&initialized_module));
955            }
956
957            _ => copy_component_section(section, component_stage2, &mut initialized_component),
958        }
959    }
960
961    let initialized_component = initialized_component.finish();
962
963    let mut add = wasm_metadata::AddMetadata::default();
964    add.processed_by = vec![(
965        "component-init-transform".to_owned(),
966        env!("CARGO_PKG_VERSION").to_owned(),
967    )];
968
969    let initialized_component = add.to_wasm(&initialized_component)?;
970
971    Validator::new_with_features(WasmFeatures::all()).validate_all(&initialized_component)?;
972
973    Ok(initialized_component)
974}
975
976struct Segments<'a> {
977    bytes: &'a [u8],
978    offset: usize,
979}
980
981impl<'a> Segments<'a> {
982    fn new(bytes: &'a [u8]) -> Self {
983        Self { bytes, offset: 0 }
984    }
985}
986
987impl<'a> Iterator for Segments<'a> {
988    type Item = (usize, usize);
989
990    fn next(&mut self) -> Option<Self::Item> {
991        let mut zero_count = 0;
992        let mut start = 0;
993        let mut length = 0;
994        for (index, value) in self.bytes[self.offset..].iter().enumerate() {
995            if *value == 0 {
996                zero_count += 1;
997            } else {
998                if zero_count > MAX_CONSECUTIVE_ZEROS {
999                    if length > 0 {
1000                        start += self.offset;
1001                        self.offset += index;
1002                        return Some((start, length));
1003                    } else {
1004                        start = index;
1005                        length = 1;
1006                    }
1007                } else {
1008                    length += zero_count + 1;
1009                }
1010                zero_count = 0;
1011            }
1012        }
1013        if length > 0 {
1014            start += self.offset;
1015            self.offset = self.bytes.len();
1016            Some((start, length))
1017        } else {
1018            self.offset = self.bytes.len();
1019            None
1020        }
1021    }
1022}
1023
1024fn get_and_increment(n: &mut u32) -> u32 {
1025    let v = *n;
1026    *n += 1;
1027    v
1028}
1029
1030fn mem_arg(offset: u64, align: u32) -> MemArg {
1031    MemArg {
1032        offset,
1033        align,
1034        memory_index: 0,
1035    }
1036}
1037
1038fn copy_component_section(
1039    section: Option<(u8, Range<u64>)>,
1040    component: &[u8],
1041    result: &mut Component,
1042) {
1043    if let Some((id, range)) = section {
1044        result.section(&RawSection {
1045            id,
1046            data: &component
1047                [usize::try_from(range.start).unwrap()..usize::try_from(range.end).unwrap()],
1048        });
1049    }
1050}
1051
1052fn copy_module_section(section: Option<(u8, Range<u64>)>, module: &[u8], result: &mut Module) {
1053    if let Some((id, range)) = section {
1054        result.section(&RawSection {
1055            id,
1056            data: &module
1057                [usize::try_from(range.start).unwrap()..usize::try_from(range.end).unwrap()],
1058        });
1059    }
1060}