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
30const 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 let (instrumented_component, instrumentation) = instrument(component_stage1)?;
75
76 Validator::new_with_features(WasmFeatures::all()).validate_all(&instrumented_component)?;
77
78 let mut invoker = initialize(instrumented_component).await?;
80
81 let measurement = instrumentation.measure(&mut invoker).await?;
84
85 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 matches!(payload, Payload::End(_))
343 || matches!(my_range, Some(my_range) if 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 let is_end = matches!(payload, Payload::End(_))
363 || matches!(my_range, Some(my_range) if my_range.end >= unchecked_range.end);
364 match payload {
365 Payload::ImportSection(reader) => {
366 for import in reader {
367 match import? {
368 Imports::Single(_, import) => {
369 if let TypeRef::Global(_) = import.ty {
370 global_count += 1;
371 }
372 }
373 Imports::Compact1 { .. } | Imports::Compact2 { .. } => todo!(),
374 }
375 }
376 copy_module_section(
377 section,
378 component_stage1,
379 &mut instrumented_module,
380 );
381 }
382
383 Payload::MemorySection(reader) => {
384 for memory in reader {
385 instrumentation.register_memory(module_index, "memory", memory?)?;
386 }
387 copy_module_section(
388 section,
389 component_stage1,
390 &mut instrumented_module,
391 );
392 }
393
394 Payload::GlobalSection(reader) => {
395 for global in reader {
396 let global = global?;
397 let ty = global.ty;
398 global_types.push(ty);
399 let global_index = get_and_increment(&mut global_count);
400 if global.ty.mutable {
401 instrumentation.register_global(
402 module_index,
403 global_index,
404 ty.content_type,
405 )
406 }
407 }
408 copy_module_section(
409 section,
410 component_stage1,
411 &mut instrumented_module,
412 );
413 }
414
415 Payload::ExportSection(reader) => {
416 let mut exports = ExportSection::new();
417 for export in reader {
418 let export = export?;
419 if let ExternalKind::Global = export.kind {
420 instrumentation.register_global_export(
421 module_index,
422 export.index,
423 export.name,
424 )
425 }
426 exports.export(
427 export.name,
428 Encode.export_kind(export.kind)?,
429 export.index,
430 );
431 }
432
433 instrumentation.amend_module_exports(module_index, &mut exports);
434
435 instrumented_module.section(&exports);
436 }
437
438 Payload::CodeSectionEntry(body) => {
439 for operator in body.get_operators_reader()? {
440 match operator? {
441 Operator::TableCopy { .. }
442 | Operator::TableFill { .. }
443 | Operator::TableGrow { .. }
444 | Operator::TableInit { .. }
445 | Operator::TableSet { .. } => {
446 bail!("table operations not allowed");
447 }
448
449 _ => (),
450 }
451 }
452 copy_module_section(
453 section,
454 component_stage1,
455 &mut instrumented_module,
456 );
457 }
458
459 Payload::DataSection(reader) => {
460 if reader.clone().into_iter().any(|data| {
461 matches!(
462 data,
463 Ok(Data {
464 kind: DataKind::Passive,
465 ..
466 })
467 )
468 }) {
469 instrumentation
470 .modules_with_passive_data_segments
471 .insert(module_index);
472 }
473 copy_module_section(section, component_stage1, &mut instrumented_module)
474 }
475
476 _ => {
477 copy_module_section(section, component_stage1, &mut instrumented_module)
478 }
479 }
480
481 if is_end {
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 function.instruction(&Ins::I32Const(PAGE_SIZE_BYTES));
707 function.instruction(&Ins::I32Mul);
708 function.instruction(&Ins::LocalTee(0));
709 function.instruction(&Ins::I32Const(1));
712 function.instruction(&Ins::MemoryGrow(0));
713 function.instruction(&Ins::I32Const(0));
716 function.instruction(&Ins::I32LtS);
717 function.instruction(&Ins::If(wasm_encoder::BlockType::Empty));
718 function.instruction(&Ins::Unreachable);
720 function.instruction(&Ins::Else);
721 function.instruction(&Ins::End);
722
723 function.instruction(&Ins::I32Const(0));
725 function.instruction(&Ins::I32Store(mem_arg(0, 1)));
728 function.instruction(&Ins::LocalGet(0));
730 function.instruction(&Ins::LocalGet(0));
731 function.instruction(&Ins::I32Store(mem_arg(4, 1)));
734 function.instruction(&Ins::LocalGet(0));
737 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 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 matches!(payload, Payload::End(_))
827 || matches!(my_range, Some(my_range) if 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 let is_end = matches!(payload, Payload::End(_))
847 || matches!(my_range, Some(my_range) if my_range.end >= unchecked_range.end);
848 match payload {
849 Payload::MemorySection(reader) => {
850 let mut memories = MemorySection::new();
851 for memory in reader {
852 let mut memory = memory?;
853
854 memory.initial = measurement
855 .memory_initial(module_index)
856 .expect("measurement for module's memory");
857
858 memories.memory(Encode.memory_type(memory)?);
859 }
860 initialized_module.section(&memories);
861 }
862
863 Payload::ImportSection(reader) => {
864 for import in reader {
865 match import? {
866 Imports::Single(_, import) => {
867 if let TypeRef::Global(_) = import.ty {
868 global_count += 1;
869 }
870 }
871 Imports::Compact1 { .. } | Imports::Compact2 { .. } => {
872 todo!()
873 }
874 }
875 }
876 copy_module_section(section, component_stage2, &mut initialized_module);
877 }
878
879 Payload::GlobalSection(reader) => {
880 let mut globals = GlobalSection::new();
881 for global in reader {
882 let global = global?;
883 let global_index = get_and_increment(&mut global_count);
884 globals.global(
885 Encode.global_type(global.ty)?,
886 &if global.ty.mutable {
887 measurement
888 .global_init(module_index, global_index)
889 .expect("measurement for global")
890 } else {
891 Encode.const_expr(global.init_expr)?
892 },
893 );
894 }
895 initialized_module.section(&globals);
896 }
897
898 Payload::DataSection(reader) => {
899 if measurement
900 .modules_with_passive_data_segments
901 .contains(&module_index)
902 {
903 assert!(data_section.is_none());
904 let mut segments = DataSection::new();
905 for data in reader {
906 let data = data?;
907 match &data.kind {
908 DataKind::Passive => {
909 segments.passive(data.data.iter().copied());
910 }
911 DataKind::Active { .. } => {
912 segments.active(0, &ConstExpr::i32_const(0), []);
914 }
915 }
916 }
917 initialized_module.section(&segments);
918 }
919 }
920
921 Payload::StartSection { .. } => (),
922
923 Payload::DataCountSection { count, .. } => {
924 let count = if measurement
925 .modules_with_passive_data_segments
926 .contains(&module_index)
927 {
928 if data_section.is_some() {
929 bail!(
930 "not yet supported: modules with passive data segments _and_ snapshot segments"
931 );
932 }
933 count
934 } else {
935 data_segment_count
936 };
937
938 initialized_module.section(&DataCountSection { count });
939 }
940
941 _ => {
942 copy_module_section(section, component_stage2, &mut initialized_module)
943 }
944 }
945
946 if is_end {
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}