Debian Codegraph @

crates/wit-component/src/validation.rs

raw
1 use crate::encoding::{Instance, Item, LibraryInfo, MainOrAdapter, ModuleImportMap};
2 use crate::{ComponentEncoder, StringEncoding};
3 use anyhow::{Context, Result, anyhow, bail};
4 use indexmap::{IndexMap, IndexSet, map::Entry};
5 use std::hash::{Hash, Hasher};
6 use std::mem;
7 use wasm_encoder::ExportKind;
8 use wasmparser::names::{ComponentName, ComponentNameKind};
9 use wasmparser::{
10 Encoding, ExternalKind, FuncType, Parser, Payload, TypeRef, ValType, ValidPayload, Validator,
11 types::TypesRef,
12 };
13 use wit_parser::{
14 Function, InterfaceId, PackageName, Resolve, Type, TypeDefKind, TypeId, World, WorldId,
15 WorldItem, WorldKey,
16 abi::{AbiVariant, WasmSignature, WasmType},
17 };
18
19 fn wasm_sig_to_func_type(signature: WasmSignature) -> FuncType {
20 fn from_wasm_type(ty: &WasmType) -> ValType {
21 match ty {
22 WasmType::I32 => ValType::I32,
23 WasmType::I64 => ValType::I64,
24 WasmType::F32 => ValType::F32,
25 WasmType::F64 => ValType::F64,
26 WasmType::Pointer => ValType::I32,
27 WasmType::PointerOrI64 => ValType::I64,
28 WasmType::Length => ValType::I32,
29 }
30 }
31
32 FuncType::new(
33 signature.params.iter().map(from_wasm_type),
34 signature.results.iter().map(from_wasm_type),
35 )
36 }
37
38 /// Metadata about a validated module and what was found internally.
39 ///
40 /// This structure houses information about `imports` and `exports` to the
41 /// module. Each of these specialized types contains "connection" information
42 /// between a module's imports/exports and the WIT or component-level constructs
43 /// they correspond to.
44
45 #[derive(Default)]
46 pub struct ValidatedModule {
47 /// Information about a module's imports.
48 pub imports: ImportMap,
49
50 /// Information about a module's exports.
51 pub exports: ExportMap,
52 }
53
54 impl ValidatedModule {
55 fn new(
56 encoder: &ComponentEncoder,
57 bytes: &[u8],
58 exports: &IndexSet<WorldKey>,
59 import_map: Option<&ModuleImportMap>,
60 info: Option<&LibraryInfo>,
61 ) -> Result<ValidatedModule> {
62 let mut validator = Validator::new();
63 let mut ret = ValidatedModule::default();
64
65 for payload in Parser::new(0).parse_all(bytes) {
66 let payload = payload?;
67 if let ValidPayload::End(_) = validator.payload(&payload)? {
68 break;
69 }
70
71 let types = validator.types(0).unwrap();
72
73 match payload {
74 Payload::Version { encoding, .. } if encoding != Encoding::Module => {
75 bail!("data is not a WebAssembly module");
76 }
77 Payload::ImportSection(s) => {
78 for import in s {
79 let import = import?;
80 ret.imports.add(import, encoder, import_map, info, types)?;
81 }
82 }
83 Payload::ExportSection(s) => {
84 for export in s {
85 let export = export?;
86 ret.exports.add(export, encoder, &exports, types)?;
87 }
88 }
89 _ => continue,
90 }
91 }
92
93 ret.exports.validate(encoder, exports)?;
94
95 Ok(ret)
96 }
97 }
98
99 /// Metadata information about a module's imports.
100 ///
101 /// This structure maintains the connection between component model "things" and
102 /// core wasm "things" by ensuring that all imports to the core wasm module are
103 /// classified by the `Import` enumeration.
104 #[derive(Default)]
105 pub struct ImportMap {
106 /// The first level of the map here is the module namespace of the import
107 /// and the second level of the map is the field namespace. The item is then
108 /// how the import is satisfied.
109 names: IndexMap<String, ImportInstance>,
110 }
111
112 pub enum ImportInstance {
113 /// This import is satisfied by an entire instance of another
114 /// adapter/module.
115 Whole(MainOrAdapter),
116
117 /// This import is satisfied by filling out each name possibly differently.
118 Names(IndexMap<String, Import>),
119 }
120
121 /// Represents metadata about a `stream<T>` or `future<T>` type for a specific
122 /// payload type `T`.
123 ///
124 /// Currently, the name mangling scheme we use to represent `stream` and
125 /// `future` intrinsics as core module function imports refers to a specific
126 /// `stream` or `future` type by naming an imported or exported component
127 /// function which has that type as a parameter or return type (where the
128 /// specific type is referred to using an ordinal numbering scheme). Not only
129 /// does this approach unambiguously indicate the type of interest, but it
130 /// allows us to reuse the `realloc`, string encoding, memory, etc. used by that
131 /// function when emitting intrinsic declarations.
132 ///
133 /// TODO: Rather than reusing the same canon opts as the function in which the
134 /// type appears, consider encoding them in the name mangling stream on an
135 /// individual basis, similar to how we encode `error-context.*` built-in
136 /// imports.
137 #[derive(Debug, Eq, PartialEq, Clone)]
138 pub struct PayloadInfo {
139 /// The original, mangled import name used to import this built-in
140 /// (currently used only for hashing and debugging).
141 pub name: String,
142 /// The resolved type id for the `stream` or `future` type of interest.
143 pub ty: TypeId,
144 /// The component-level function import or export where the type appeared as
145 /// a parameter or result type.
146 pub function: String,
147 /// The world key representing the import or export context of `function`.
148 pub key: WorldKey,
149 /// The interface that `function` was imported from or exported in, if any.
150 pub interface: Option<InterfaceId>,
151 /// Whether `function` is being imported or exported.
152 ///
153 /// This may affect how we emit the declaration of the built-in, e.g. if the
154 /// payload type is an exported resource.
155 pub imported: bool,
156 }
157
158 impl PayloadInfo {
159 /// Returns the payload type that this future/stream type is using.
160 pub fn payload(&self, resolve: &Resolve) -> Option<Type> {
161 match resolve.types[self.ty].kind {
162 TypeDefKind::Future(payload) | TypeDefKind::Stream(payload) => payload,
163 _ => unreachable!(),
164 }
165 }
166 }
167
168 impl Hash for PayloadInfo {
169 /// We derive `Hash` for this type by hand and exclude the `function` field
170 /// because (A) `Function` doesn't implement `Hash` and (B) the other fields
171 /// are sufficient to uniquely identify the type of interest, which function
172 /// it appeared in, and which parameter or return type we found it in.
173 fn hash<H: Hasher>(&self, state: &mut H) {
174 self.name.hash(state);
175 self.ty.hash(state);
176 self.key.hash(state);
177 self.interface.hash(state);
178 self.imported.hash(state);
179 }
180 }
181
182 /// The different kinds of items that a module or an adapter can import.
183 ///
184 /// This is intended to be an exhaustive definition of what can be imported into
185 /// core modules within a component that wit-component supports. This doesn't
186 /// get down to the level of storing any idx numbers; at its most specific, it
187 /// gives a name.
188 #[derive(Debug, Clone)]
189 pub enum Import {
190 /// A top-level world function, with the name provided here, is imported
191 /// into the module.
192 WorldFunc(WorldKey, String, AbiVariant),
193
194 /// An interface's function is imported into the module.
195 ///
196 /// The `WorldKey` here is the name of the interface in the world in
197 /// question. The `InterfaceId` is the interface that was imported from and
198 /// `String` is the WIT name of the function.
199 InterfaceFunc(WorldKey, InterfaceId, String, AbiVariant),
200
201 /// An imported resource's destructor is imported.
202 ///
203 /// The key provided indicates whether it's for the top-level types of the
204 /// world (`None`) or an interface (`Some` with the name of the interface).
205 /// The `TypeId` is what resource is being dropped.
206 ImportedResourceDrop(WorldKey, Option<InterfaceId>, TypeId),
207
208 /// A `canon resource.drop` intrinsic for an exported item is being
209 /// imported.
210 ///
211 /// This lists the key of the interface that's exporting the resource plus
212 /// the id within that interface.
213 ExportedResourceDrop(WorldKey, TypeId),
214
215 /// A `canon resource.new` intrinsic for an exported item is being
216 /// imported.
217 ///
218 /// This lists the key of the interface that's exporting the resource plus
219 /// the id within that interface.
220 ExportedResourceNew(WorldKey, TypeId),
221
222 /// A `canon resource.rep` intrinsic for an exported item is being
223 /// imported.
224 ///
225 /// This lists the key of the interface that's exporting the resource plus
226 /// the id within that interface.
227 ExportedResourceRep(WorldKey, TypeId),
228
229 /// An export of an adapter is being imported with the specified type.
230 ///
231 /// This is used for when the main module imports an adapter function. The
232 /// adapter name and function name match the module's own import, and the
233 /// type must match that listed here.
234 AdapterExport {
235 adapter: String,
236 func: String,
237 ty: FuncType,
238 },
239
240 /// An adapter is importing the memory of the main module.
241 ///
242 /// (should be combined with `MainModuleExport` below one day)
243 MainModuleMemory,
244
245 /// An adapter is importing an arbitrary item from the main module.
246 MainModuleExport { name: String, kind: ExportKind },
247
248 /// An arbitrary item from either the main module or an adapter is being
249 /// imported.
250 ///
251 /// (should probably subsume `MainModule*` and maybe `AdapterExport` above
252 /// one day.
253 Item(Item),
254
255 /// A `canon task.return` intrinsic for an exported function.
256 ///
257 /// This allows an exported function to return a value and then continue
258 /// running.
259 ///
260 /// As of this writing, only async-lifted exports use `task.return`, but the
261 /// plan is to also support it for sync-lifted exports in the future as
262 /// well.
263 ExportedTaskReturn(WorldKey, Option<InterfaceId>, String, Option<Type>),
264
265 /// A `canon task.cancel` intrinsic for an exported function.
266 ///
267 /// This allows an exported function to acknowledge a `CANCELLED` event.
268 ExportedTaskCancel,
269
270 /// The `context.get` intrinsic for the nth slot of storage.
271 ContextGet(u32),
272 /// The `context.set` intrinsic for the nth slot of storage.
273 ContextSet(u32),
274
275 /// A `canon backpressure.set` intrinsic.
276 ///
277 /// This allows the guest to dynamically indicate whether it's ready for
278 /// additional concurrent calls.
279 BackpressureSet,
280
281 /// A `canon backpressure.inc` intrinsic.
282 BackpressureInc,
283
284 /// A `canon backpressure.dec` intrinsic.
285 BackpressureDec,
286
287 /// A `waitable-set.new` intrinsic.
288 WaitableSetNew,
289
290 /// A `canon waitable-set.wait` intrinsic.
291 ///
292 /// This allows the guest to wait for any pending calls to async-lowered
293 /// imports and/or `stream` and `future` operations to complete without
294 /// unwinding the current Wasm stack.
295 WaitableSetWait { cancellable: bool },
296
297 /// A `canon waitable.poll` intrinsic.
298 ///
299 /// This allows the guest to check whether any pending calls to
300 /// async-lowered imports and/or `stream` and `future` operations have
301 /// completed without unwinding the current Wasm stack and without blocking.
302 WaitableSetPoll { cancellable: bool },
303
304 /// A `waitable-set.drop` intrinsic.
305 WaitableSetDrop,
306
307 /// A `waitable.join` intrinsic.
308 WaitableJoin,
309
310 /// A `canon thread.yield` intrinsic.
311 ///
312 /// This allows the guest to yield (e.g. during an computationally-intensive
313 /// operation) and allow other subtasks to make progress.
314 ThreadYield { cancellable: bool },
315
316 /// A `canon subtask.drop` intrinsic.
317 ///
318 /// This allows the guest to release its handle to a completed subtask.
319 SubtaskDrop,
320
321 /// A `canon subtask.cancel` intrinsic.
322 ///
323 /// This allows the guest to cancel an in-progress subtask.
324 SubtaskCancel { async_: bool },
325
326 /// A `canon stream.new` intrinsic.
327 ///
328 /// This allows the guest to create a new `stream` of the specified type.
329 StreamNew(PayloadInfo),
330
331 /// A `canon stream.read` intrinsic.
332 ///
333 /// This allows the guest to read the next values (if any) from the specified
334 /// stream.
335 StreamRead { async_: bool, info: PayloadInfo },
336
337 /// A `canon stream.write` intrinsic.
338 ///
339 /// This allows the guest to write one or more values to the specified
340 /// stream.
341 StreamWrite { async_: bool, info: PayloadInfo },
342
343 /// A `canon stream.cancel-read` intrinsic.
344 ///
345 /// This allows the guest to cancel a pending read it initiated earlier (but
346 /// which may have already partially or entirely completed).
347 StreamCancelRead { info: PayloadInfo, async_: bool },
348
349 /// A `canon stream.cancel-write` intrinsic.
350 ///
351 /// This allows the guest to cancel a pending write it initiated earlier
352 /// (but which may have already partially or entirely completed).
353 StreamCancelWrite { info: PayloadInfo, async_: bool },
354
355 /// A `canon stream.drop-readable` intrinsic.
356 ///
357 /// This allows the guest to drop the readable end of a `stream`.
358 StreamDropReadable(PayloadInfo),
359
360 /// A `canon stream.drop-writable` intrinsic.
361 ///
362 /// This allows the guest to drop the writable end of a `stream`.
363 StreamDropWritable(PayloadInfo),
364
365 /// A `canon future.new` intrinsic.
366 ///
367 /// This allows the guest to create a new `future` of the specified type.
368 FutureNew(PayloadInfo),
369
370 /// A `canon future.read` intrinsic.
371 ///
372 /// This allows the guest to read the value (if any) from the specified
373 /// future.
374 FutureRead { async_: bool, info: PayloadInfo },
375
376 /// A `canon future.write` intrinsic.
377 ///
378 /// This allows the guest to write a value to the specified future.
379 FutureWrite { async_: bool, info: PayloadInfo },
380
381 /// A `canon future.cancel-read` intrinsic.
382 ///
383 /// This allows the guest to cancel a pending read it initiated earlier (but
384 /// which may have already completed).
385 FutureCancelRead { info: PayloadInfo, async_: bool },
386
387 /// A `canon future.cancel-write` intrinsic.
388 ///
389 /// This allows the guest to cancel a pending write it initiated earlier
390 /// (but which may have already completed).
391 FutureCancelWrite { info: PayloadInfo, async_: bool },
392
393 /// A `canon future.drop-readable` intrinsic.
394 ///
395 /// This allows the guest to drop the readable end of a `future`.
396 FutureDropReadable(PayloadInfo),
397
398 /// A `canon future.drop-writable` intrinsic.
399 ///
400 /// This allows the guest to drop the writable end of a `future`.
401 FutureDropWritable(PayloadInfo),
402
403 /// A `canon error-context.new` intrinsic.
404 ///
405 /// This allows the guest to create a new `error-context` instance with a
406 /// specified debug message.
407 ErrorContextNew { encoding: StringEncoding },
408
409 /// A `canon error-context.debug-message` intrinsic.
410 ///
411 /// This allows the guest to retrieve the debug message from a
412 /// `error-context` instance. Note that the content of this message might
413 /// not be identical to what was passed in to `error-context.new`.
414 ErrorContextDebugMessage { encoding: StringEncoding },
415
416 /// A `canon error-context.drop` intrinsic.
417 ///
418 /// This allows the guest to release its handle to the specified
419 /// `error-context` instance.
420 ErrorContextDrop,
421
422 /// A `canon thread.index` intrinsic.
423 ///
424 /// This allows the guest to get the index of the current thread.
425 ThreadIndex,
426
427 /// A `canon thread.new_indirect` intrinsic.
428 ///
429 /// This allows the guest to create a new thread running a specified function.
430 ThreadNewIndirect,
431
432 /// A `canon thread.switch-to` intrinsic.
433 ///
434 /// This allows the guest to switch execution to another thread.
435 ThreadSwitchTo { cancellable: bool },
436
437 /// A `canon thread.suspend` intrinsic.
438 ///
439 /// This allows the guest to suspend the current thread, switching execution to
440 /// an unspecified thread.
441 ThreadSuspend { cancellable: bool },
442
443 /// A `canon thread.resume-later` intrinsic.
444 ///
445 /// This allows the guest to mark a suspended thread for later resumption.
446 ThreadResumeLater,
447
448 /// A `canon thread.yield-to` intrinsic.
449 ///
450 /// This allows the guest to suspend, yielding execution to a specified thread.
451 ThreadYieldTo { cancellable: bool },
452 }
453
454 impl ImportMap {
455 /// Returns the list of items that the adapter named `name` must export.
456 pub fn required_from_adapter(&self, name: &str) -> IndexMap<String, FuncType> {
457 let names = match self.names.get(name) {
458 Some(ImportInstance::Names(names)) => names,
459 _ => return IndexMap::new(),
460 };
461 names
462 .iter()
463 .map(|(_, import)| match import {
464 Import::AdapterExport { ty, func, adapter } => {
465 assert_eq!(adapter, name);
466 (func.clone(), ty.clone())
467 }
468 _ => unreachable!(),
469 })
470 .collect()
471 }
472
473 /// Returns an iterator over all individual imports registered in this map.
474 ///
475 /// Note that this doesn't iterate over the "whole instance" imports.
476 pub fn imports(&self) -> impl Iterator<Item = (&str, &str, &Import)> + '_ {
477 self.names
478 .iter()
479 .filter_map(|(module, m)| match m {
480 ImportInstance::Names(names) => Some((module, names)),
481 ImportInstance::Whole(_) => None,
482 })
483 .flat_map(|(module, m)| {
484 m.iter()
485 .map(move |(field, import)| (module.as_str(), field.as_str(), import))
486 })
487 }
488
489 /// Returns the map for how all imports must be satisfied.
490 pub fn modules(&self) -> &IndexMap<String, ImportInstance> {
491 &self.names
492 }
493
494 /// Classify an import and call `insert_import()` on it. Used during
495 /// validation to build up this `ImportMap`.
496 fn add(
497 &mut self,
498 import: wasmparser::Import<'_>,
499 encoder: &ComponentEncoder,
500 import_map: Option<&ModuleImportMap>,
501 library_info: Option<&LibraryInfo>,
502 types: TypesRef<'_>,
503 ) -> Result<()> {
504 if self.classify_import_with_library(import, library_info)? {
505 return Ok(());
506 }
507 let mut import_to_classify = import;
508 if let Some(map) = import_map {
509 if let Some(original_name) = map.original_name(&import) {
510 import_to_classify.name = original_name;
511 }
512 }
513 let item = self
514 .classify(import_to_classify, encoder, types)
515 .with_context(|| {
516 format!(
517 "failed to resolve import `{}::{}`",
518 import.module, import.name,
519 )
520 })?;
521 self.insert_import(import, item)
522 }
523
524 /// Determines what kind of thing is being imported: maps it from the
525 /// module/name/type triple in the raw wasm module to an enum.
526 ///
527 /// Handles a few special cases, then delegates to
528 /// `classify_component_model_import()`.
529 fn classify(
530 &self,
531 import: wasmparser::Import<'_>,
532 encoder: &ComponentEncoder,
533 types: TypesRef<'_>,
534 ) -> Result<Import> {
535 // Special-case the main module's memory imported into adapters which
536 // currently with `wasm-ld` is not easily configurable.
537 if import.module == "env" && import.name == "memory" {
538 return Ok(Import::MainModuleMemory);
539 }
540
541 // Special-case imports from the main module into adapters.
542 if import.module == "__main_module__" {
543 return Ok(Import::MainModuleExport {
544 name: import.name.to_string(),
545 kind: match import.ty {
546 TypeRef::Func(_) => ExportKind::Func,
547 TypeRef::Table(_) => ExportKind::Table,
548 TypeRef::Memory(_) => ExportKind::Memory,
549 TypeRef::Global(_) => ExportKind::Global,
550 TypeRef::Tag(_) => ExportKind::Tag,
551 },
552 });
553 }
554
555 let ty_index = match import.ty {
556 TypeRef::Func(ty) => ty,
557 _ => bail!("module is only allowed to import functions"),
558 };
559 let ty = types[types.core_type_at_in_module(ty_index)].unwrap_func();
560
561 // Handle main module imports that match known adapters and set it up as
562 // an import of an adapter export.
563 if encoder.adapters.contains_key(import.module) {
564 return Ok(Import::AdapterExport {
565 adapter: import.module.to_string(),
566 func: import.name.to_string(),
567 ty: ty.clone(),
568 });
569 }
570
571 let (module, names) = match import.module.strip_prefix("cm32p2") {
572 Some(suffix) => (suffix, STANDARD),
573 None if encoder.reject_legacy_names => (import.module, STANDARD),
574 None => (import.module, LEGACY),
575 };
576 self.classify_component_model_import(module, import.name, encoder, ty, names)
577 }
578
579 /// Attempts to classify the import `{module}::{name}` with the rules
580 /// specified in WebAssembly/component-model#378
581 fn classify_component_model_import(
582 &self,
583 module: &str,
584 name: &str,
585 encoder: &ComponentEncoder,
586 ty: &FuncType,
587 names: &dyn NameMangling,
588 ) -> Result<Import> {
589 let resolve = &encoder.metadata.resolve;
590 let world_id = encoder.metadata.world;
591 let world = &resolve.worlds[world_id];
592
593 if module == names.import_root() {
594 if names.error_context_drop(name) {
595 let expected = FuncType::new([ValType::I32], []);
596 validate_func_sig(name, &expected, ty)?;
597 return Ok(Import::ErrorContextDrop);
598 }
599
600 if names.backpressure_set(name) {
601 let expected = FuncType::new([ValType::I32], []);
602 validate_func_sig(name, &expected, ty)?;
603 return Ok(Import::BackpressureSet);
604 }
605
606 if names.backpressure_inc(name) {
607 let expected = FuncType::new([], []);
608 validate_func_sig(name, &expected, ty)?;
609 return Ok(Import::BackpressureInc);
610 }
611
612 if names.backpressure_dec(name) {
613 let expected = FuncType::new([], []);
614 validate_func_sig(name, &expected, ty)?;
615 return Ok(Import::BackpressureDec);
616 }
617
618 if names.waitable_set_new(name) {
619 let expected = FuncType::new([], [ValType::I32]);
620 validate_func_sig(name, &expected, ty)?;
621 return Ok(Import::WaitableSetNew);
622 }
623
624 if let Some(info) = names.waitable_set_wait(name) {
625 let expected = FuncType::new([ValType::I32; 2], [ValType::I32]);
626 validate_func_sig(name, &expected, ty)?;
627 return Ok(Import::WaitableSetWait {
628 cancellable: info.cancellable,
629 });
630 }
631
632 if let Some(info) = names.waitable_set_poll(name) {
633 let expected = FuncType::new([ValType::I32; 2], [ValType::I32]);
634 validate_func_sig(name, &expected, ty)?;
635 return Ok(Import::WaitableSetPoll {
636 cancellable: info.cancellable,
637 });
638 }
639
640 if names.waitable_set_drop(name) {
641 let expected = FuncType::new([ValType::I32], []);
642 validate_func_sig(name, &expected, ty)?;
643 return Ok(Import::WaitableSetDrop);
644 }
645
646 if names.waitable_join(name) {
647 let expected = FuncType::new([ValType::I32; 2], []);
648 validate_func_sig(name, &expected, ty)?;
649 return Ok(Import::WaitableJoin);
650 }
651
652 if let Some(info) = names.thread_yield(name) {
653 let expected = FuncType::new([], [ValType::I32]);
654 validate_func_sig(name, &expected, ty)?;
655 return Ok(Import::ThreadYield {
656 cancellable: info.cancellable,
657 });
658 }
659
660 if names.subtask_drop(name) {
661 let expected = FuncType::new([ValType::I32], []);
662 validate_func_sig(name, &expected, ty)?;
663 return Ok(Import::SubtaskDrop);
664 }
665
666 if let Some(info) = names.subtask_cancel(name) {
667 let expected = FuncType::new([ValType::I32], [ValType::I32]);
668 validate_func_sig(name, &expected, ty)?;
669 return Ok(Import::SubtaskCancel {
670 async_: info.async_lowered,
671 });
672 }
673
674 if let Some(encoding) = names.error_context_new(name) {
675 let expected = FuncType::new([ValType::I32; 2], [ValType::I32]);
676 validate_func_sig(name, &expected, ty)?;
677 return Ok(Import::ErrorContextNew { encoding });
678 }
679
680 if let Some(encoding) = names.error_context_debug_message(name) {
681 let expected = FuncType::new([ValType::I32; 2], []);
682 validate_func_sig(name, &expected, ty)?;
683 return Ok(Import::ErrorContextDebugMessage { encoding });
684 }
685
686 if let Some(i) = names.context_get(name) {
687 let expected = FuncType::new([], [ValType::I32]);
688 validate_func_sig(name, &expected, ty)?;
689 return Ok(Import::ContextGet(i));
690 }
691 if let Some(i) = names.context_set(name) {
692 let expected = FuncType::new([ValType::I32], []);
693 validate_func_sig(name, &expected, ty)?;
694 return Ok(Import::ContextSet(i));
695 }
696 if names.thread_index(name) {
697 let expected = FuncType::new([], [ValType::I32]);
698 validate_func_sig(name, &expected, ty)?;
699 return Ok(Import::ThreadIndex);
700 }
701 if names.thread_new_indirect(name) {
702 let expected = FuncType::new([ValType::I32; 2], [ValType::I32]);
703 validate_func_sig(name, &expected, ty)?;
704 return Ok(Import::ThreadNewIndirect);
705 }
706 if let Some(info) = names.thread_switch_to(name) {
707 let expected = FuncType::new([ValType::I32], [ValType::I32]);
708 validate_func_sig(name, &expected, ty)?;
709 return Ok(Import::ThreadSwitchTo {
710 cancellable: info.cancellable,
711 });
712 }
713 if let Some(info) = names.thread_suspend(name) {
714 let expected = FuncType::new([], [ValType::I32]);
715 validate_func_sig(name, &expected, ty)?;
716 return Ok(Import::ThreadSuspend {
717 cancellable: info.cancellable,
718 });
719 }
720 if names.thread_resume_later(name) {
721 let expected = FuncType::new([ValType::I32], []);
722 validate_func_sig(name, &expected, ty)?;
723 return Ok(Import::ThreadResumeLater);
724 }
725 if let Some(info) = names.thread_yield_to(name) {
726 let expected = FuncType::new([ValType::I32], [ValType::I32]);
727 validate_func_sig(name, &expected, ty)?;
728 return Ok(Import::ThreadYieldTo {
729 cancellable: info.cancellable,
730 });
731 }
732
733 let (key_name, abi) = names.world_key_name_and_abi(name);
734 let key = WorldKey::Name(key_name.to_string());
735 if let Some(WorldItem::Function(func)) = world.imports.get(&key) {
736 validate_func(resolve, ty, func, abi)?;
737 return Ok(Import::WorldFunc(key, func.name.clone(), abi));
738 }
739
740 if let Some(import) =
741 self.maybe_classify_wit_intrinsic(name, None, encoder, ty, true, names)?
742 {
743 return Ok(import);
744 }
745
746 match world.imports.get(&key) {
747 Some(_) => bail!("expected world top-level import `{name}` to be a function"),
748 None => bail!("no top-level imported function `{name}` specified"),
749 }
750 }
751
752 // Check for `[export]$root::[task-return]foo` or similar
753 if matches!(
754 module.strip_prefix(names.import_exported_intrinsic_prefix()),
755 Some(module) if module == names.import_root()
756 ) {
757 if let Some(import) =
758 self.maybe_classify_wit_intrinsic(name, None, encoder, ty, false, names)?
759 {
760 return Ok(import);
761 }
762 }
763
764 let interface = match module.strip_prefix(names.import_non_root_prefix()) {
765 Some(name) => name,
766 None => bail!("unknown or invalid component model import syntax"),
767 };
768
769 if let Some(interface) = interface.strip_prefix(names.import_exported_intrinsic_prefix()) {
770 let (key, id) = names.module_to_interface(interface, resolve, &world.exports)?;
771
772 if let Some(import) =
773 self.maybe_classify_wit_intrinsic(name, Some((key, id)), encoder, ty, false, names)?
774 {
775 return Ok(import);
776 }
777 bail!("unknown function `{name}`")
778 }
779
780 let (key, id) = names.module_to_interface(interface, resolve, &world.imports)?;
781 let interface = &resolve.interfaces[id];
782 let (function_name, abi) = names.interface_function_name_and_abi(name);
783 if let Some(f) = interface.functions.get(function_name) {
784 validate_func(resolve, ty, f, abi).with_context(|| {
785 let name = resolve.name_world_key(&key);
786 format!("failed to validate import interface `{name}`")
787 })?;
788 return Ok(Import::InterfaceFunc(key, id, f.name.clone(), abi));
789 }
790
791 if let Some(import) =
792 self.maybe_classify_wit_intrinsic(name, Some((key, id)), encoder, ty, true, names)?
793 {
794 return Ok(import);
795 }
796 bail!(
797 "import interface `{module}` is missing function \
798 `{name}` that is required by the module",
799 )
800 }
801
802 /// Attempts to detect and classify `name` as a WIT intrinsic.
803 ///
804 /// This function is a bit of a sprawling sequence of matches used to
805 /// detect whether `name` corresponds to a WIT intrinsic, so specifically
806 /// not a WIT function itself. This is only used for functions imported
807 /// into a module but the import could be for an imported item in a world
808 /// or an exported item.
809 ///
810 /// ## Parameters
811 ///
812 /// * `name` - the core module name which is being pattern-matched. This
813 /// should be the "field" of the import. This may include the "[async-lower]"
814 /// or "[cancellable]" prefixes.
815 /// * `key_and_id` - this is the inferred "container" for the function
816 /// being described which is inferred from the module portion of the core
817 /// wasm import field. This is `None` for root-level function/type
818 /// imports, such as when referring to `import x: func();`. This is `Some`
819 /// when an interface is used (either `import x: interface { .. }` or a
820 /// standalone `interface`) where the world key is specified for the
821 /// interface in addition to the interface that was identified.
822 /// * `encoder` - this is the encoder state that contains
823 /// `Resolve`/metadata information.
824 /// * `ty` - the core wasm type of this import.
825 /// * `import` - whether or not this core wasm import is operating on a WIT
826 /// level import or export. An example of this being an export is when a
827 /// core module imports a destructor for an exported resource.
828 /// * `names` - the name mangling scheme that's configured to be used.
829 fn maybe_classify_wit_intrinsic(
830 &self,
831 name: &str,
832 key_and_id: Option<(WorldKey, InterfaceId)>,
833 encoder: &ComponentEncoder,
834 ty: &FuncType,
835 import: bool,
836 names: &dyn NameMangling,
837 ) -> Result<Option<Import>> {
838 let resolve = &encoder.metadata.resolve;
839 let world_id = encoder.metadata.world;
840 let world = &resolve.worlds[world_id];
841
842 // Separate out `Option<WorldKey>` and `Option<InterfaceId>`. If an
843 // interface is NOT specified then the `WorldKey` which is attached to
844 // imports is going to be calculated based on the name of the item
845 // extracted, such as the resource or function referenced.
846 let (key, id) = match key_and_id {
847 Some((key, id)) => (Some(key), Some(id)),
848 None => (None, None),
849 };
850
851 // Tests whether `name` is a resource within `id` (or `world_id`).
852 let resource_test = |name: &str| match id {
853 Some(id) => resource_test_for_interface(resolve, id)(name),
854 None => resource_test_for_world(resolve, world_id)(name),
855 };
856
857 // Test whether this is a `resource.drop` intrinsic.
858 if let Some(resource) = names.resource_drop_name(name) {
859 if let Some(resource_id) = resource_test(resource) {
860 let key = key.unwrap_or_else(|| WorldKey::Name(resource.to_string()));
861 let expected = FuncType::new([ValType::I32], []);
862 validate_func_sig(name, &expected, ty)?;
863 return Ok(Some(if import {
864 Import::ImportedResourceDrop(key, id, resource_id)
865 } else {
866 Import::ExportedResourceDrop(key, resource_id)
867 }));
868 }
869 }
870
871 // There are some intrinsics which are only applicable to exported
872 // functions/resources, so check those use cases here.
873 if !import {
874 if let Some(name) = names.resource_new_name(name) {
875 if let Some(id) = resource_test(name) {
876 let key = key.unwrap_or_else(|| WorldKey::Name(name.to_string()));
877 let expected = FuncType::new([ValType::I32], [ValType::I32]);
878 validate_func_sig(name, &expected, ty)?;
879 return Ok(Some(Import::ExportedResourceNew(key, id)));
880 }
881 }
882 if let Some(name) = names.resource_rep_name(name) {
883 if let Some(id) = resource_test(name) {
884 let key = key.unwrap_or_else(|| WorldKey::Name(name.to_string()));
885 let expected = FuncType::new([ValType::I32], [ValType::I32]);
886 validate_func_sig(name, &expected, ty)?;
887 return Ok(Some(Import::ExportedResourceRep(key, id)));
888 }
889 }
890 if let Some(name) = names.task_return_name(name) {
891 let func = get_function(resolve, world, name, id, import)?;
892 let key = key.unwrap_or_else(|| WorldKey::Name(name.to_string()));
893 // TODO: should call `validate_func_sig` but would require
894 // calculating the expected signature based of `func.result`.
895 return Ok(Some(Import::ExportedTaskReturn(
896 key,
897 id,
898 func.name.clone(),
899 func.result,
900 )));
901 }
902 if names.task_cancel(name) {
903 let expected = FuncType::new([], []);
904 validate_func_sig(name, &expected, ty)?;
905 return Ok(Some(Import::ExportedTaskCancel));
906 }
907 }
908
909 let lookup_context = PayloadLookupContext {
910 resolve,
911 world,
912 key,
913 id,
914 import,
915 };
916
917 // Test for a number of async-related intrinsics. All intrinsics are
918 // prefixed with `[...-N]` where `...` is the name of the intrinsic and
919 // the `N` is the indexed future/stream that is being referred to.
920 let import = if let Some(info) = names.future_new(&lookup_context, name) {
921 validate_func_sig(name, &FuncType::new([], [ValType::I64]), ty)?;
922 Import::FutureNew(info)
923 } else if let Some(info) = names.future_write(&lookup_context, name) {
924 validate_func_sig(name, &FuncType::new([ValType::I32; 2], [ValType::I32]), ty)?;
925 Import::FutureWrite {
926 async_: info.async_lowered,
927 info: info.inner,
928 }
929 } else if let Some(info) = names.future_read(&lookup_context, name) {
930 validate_func_sig(name, &FuncType::new([ValType::I32; 2], [ValType::I32]), ty)?;
931 Import::FutureRead {
932 async_: info.async_lowered,
933 info: info.inner,
934 }
935 } else if let Some(info) = names.future_cancel_write(&lookup_context, name) {
936 validate_func_sig(name, &FuncType::new([ValType::I32], [ValType::I32]), ty)?;
937 Import::FutureCancelWrite {
938 async_: info.async_lowered,
939 info: info.inner,
940 }
941 } else if let Some(info) = names.future_cancel_read(&lookup_context, name) {
942 validate_func_sig(name, &FuncType::new([ValType::I32], [ValType::I32]), ty)?;
943 Import::FutureCancelRead {
944 async_: info.async_lowered,
945 info: info.inner,
946 }
947 } else if let Some(info) = names.future_drop_writable(&lookup_context, name) {
948 validate_func_sig(name, &FuncType::new([ValType::I32], []), ty)?;
949 Import::FutureDropWritable(info)
950 } else if let Some(info) = names.future_drop_readable(&lookup_context, name) {
951 validate_func_sig(name, &FuncType::new([ValType::I32], []), ty)?;
952 Import::FutureDropReadable(info)
953 } else if let Some(info) = names.stream_new(&lookup_context, name) {
954 validate_func_sig(name, &FuncType::new([], [ValType::I64]), ty)?;
955 Import::StreamNew(info)
956 } else if let Some(info) = names.stream_write(&lookup_context, name) {
957 validate_func_sig(name, &FuncType::new([ValType::I32; 3], [ValType::I32]), ty)?;
958 Import::StreamWrite {
959 async_: info.async_lowered,
960 info: info.inner,
961 }
962 } else if let Some(info) = names.stream_read(&lookup_context, name) {
963 validate_func_sig(name, &FuncType::new([ValType::I32; 3], [ValType::I32]), ty)?;
964 Import::StreamRead {
965 async_: info.async_lowered,
966 info: info.inner,
967 }
968 } else if let Some(info) = names.stream_cancel_write(&lookup_context, name) {
969 validate_func_sig(name, &FuncType::new([ValType::I32], [ValType::I32]), ty)?;
970 Import::StreamCancelWrite {
971 async_: info.async_lowered,
972 info: info.inner,
973 }
974 } else if let Some(info) = names.stream_cancel_read(&lookup_context, name) {
975 validate_func_sig(name, &FuncType::new([ValType::I32], [ValType::I32]), ty)?;
976 Import::StreamCancelRead {
977 async_: info.async_lowered,
978 info: info.inner,
979 }
980 } else if let Some(info) = names.stream_drop_writable(&lookup_context, name) {
981 validate_func_sig(name, &FuncType::new([ValType::I32], []), ty)?;
982 Import::StreamDropWritable(info)
983 } else if let Some(info) = names.stream_drop_readable(&lookup_context, name) {
984 validate_func_sig(name, &FuncType::new([ValType::I32], []), ty)?;
985 Import::StreamDropReadable(info)
986 } else {
987 return Ok(None);
988 };
989 Ok(Some(import))
990 }
991
992 fn classify_import_with_library(
993 &mut self,
994 import: wasmparser::Import<'_>,
995 library_info: Option<&LibraryInfo>,
996 ) -> Result<bool> {
997 let info = match library_info {
998 Some(info) => info,
999 None => return Ok(false),
1000 };
1001 let Some((_, instance)) = info
1002 .arguments
1003 .iter()
1004 .find(|(name, _items)| *name == import.module)
1005 else {
1006 return Ok(false);
1007 };
1008 match instance {
1009 Instance::MainOrAdapter(module) => match self.names.get(import.module) {
1010 Some(ImportInstance::Whole(which)) => {
1011 if which != module {
1012 bail!("different whole modules imported under the same name");
1013 }
1014 }
1015 Some(ImportInstance::Names(_)) => {
1016 bail!("cannot mix individual imports and whole module imports")
1017 }
1018 None => {
1019 let instance = ImportInstance::Whole(module.clone());
1020 self.names.insert(import.module.to_string(), instance);
1021 }
1022 },
1023 Instance::Items(items) => {
1024 let Some(item) = items.iter().find(|i| i.alias == import.name) else {
1025 return Ok(false);
1026 };
1027 self.insert_import(import, Import::Item(item.clone()))?;
1028 }
1029 }
1030 Ok(true)
1031 }
1032
1033 /// Map an imported item, by module and field name in `self.names`, to the
1034 /// kind of `Import` it is: for example, a certain-typed function from an
1035 /// adapter.
1036 fn insert_import(&mut self, import: wasmparser::Import<'_>, item: Import) -> Result<()> {
1037 let entry = self
1038 .names
1039 .entry(import.module.to_string())
1040 .or_insert(ImportInstance::Names(IndexMap::default()));
1041 let names = match entry {
1042 ImportInstance::Names(names) => names,
1043 _ => bail!("cannot mix individual imports with module imports"),
1044 };
1045 let entry = match names.entry(import.name.to_string()) {
1046 Entry::Occupied(_) => {
1047 bail!(
1048 "module has duplicate import for `{}::{}`",
1049 import.module,
1050 import.name
1051 );
1052 }
1053 Entry::Vacant(v) => v,
1054 };
1055 log::trace!(
1056 "classifying import `{}::{} as {item:?}",
1057 import.module,
1058 import.name
1059 );
1060 entry.insert(item);
1061 Ok(())
1062 }
1063 }
1064
1065 /// Dual of `ImportMap` except describes the exports of a module instead of the
1066 /// imports.
1067 #[derive(Default)]
1068 pub struct ExportMap {
1069 names: IndexMap<String, Export>,
1070 raw_exports: IndexMap<String, FuncType>,
1071 }
1072
1073 /// All possible (known) exports from a core wasm module that are recognized and
1074 /// handled during the componentization process.
1075 #[derive(Debug)]
1076 pub enum Export {
1077 /// An export of a top-level function of a world, where the world function
1078 /// is named here.
1079 WorldFunc(WorldKey, String, AbiVariant),
1080
1081 /// A post-return for a top-level function of a world.
1082 WorldFuncPostReturn(WorldKey),
1083
1084 /// An export of a function in an interface.
1085 InterfaceFunc(WorldKey, InterfaceId, String, AbiVariant),
1086
1087 /// A post-return for the above function.
1088 InterfaceFuncPostReturn(WorldKey, String),
1089
1090 /// A destructor for an exported resource.
1091 ResourceDtor(TypeId),
1092
1093 /// Memory, typically for an adapter.
1094 Memory,
1095
1096 /// `cabi_realloc`
1097 GeneralPurposeRealloc,
1098
1099 /// `cabi_export_realloc`
1100 GeneralPurposeExportRealloc,
1101
1102 /// `cabi_import_realloc`
1103 GeneralPurposeImportRealloc,
1104
1105 /// `_initialize`
1106 Initialize,
1107
1108 /// `cabi_realloc_adapter`
1109 ReallocForAdapter,
1110
1111 WorldFuncCallback(WorldKey),
1112
1113 InterfaceFuncCallback(WorldKey, String),
1114
1115 /// __indirect_function_table, used for `thread.new_indirect`
1116 IndirectFunctionTable,
1117 }
1118
1119 impl ExportMap {
1120 fn add(
1121 &mut self,
1122 export: wasmparser::Export<'_>,
1123 encoder: &ComponentEncoder,
1124 exports: &IndexSet<WorldKey>,
1125 types: TypesRef<'_>,
1126 ) -> Result<()> {
1127 if let Some(item) = self.classify(export, encoder, exports, types)? {
1128 log::debug!("classifying export `{}` as {item:?}", export.name);
1129 let prev = self.names.insert(export.name.to_string(), item);
1130 assert!(prev.is_none());
1131 }
1132 Ok(())
1133 }
1134
1135 fn classify(
1136 &mut self,
1137 export: wasmparser::Export<'_>,
1138 encoder: &ComponentEncoder,
1139 exports: &IndexSet<WorldKey>,
1140 types: TypesRef<'_>,
1141 ) -> Result<Option<Export>> {
1142 match export.kind {
1143 ExternalKind::Func => {
1144 let ty = types[types.core_function_at(export.index)].unwrap_func();
1145 self.raw_exports.insert(export.name.to_string(), ty.clone());
1146 }
1147 _ => {}
1148 }
1149
1150 // Handle a few special-cased names first.
1151 if export.name == "canonical_abi_realloc" {
1152 return Ok(Some(Export::GeneralPurposeRealloc));
1153 } else if export.name == "cabi_import_realloc" {
1154 return Ok(Some(Export::GeneralPurposeImportRealloc));
1155 } else if export.name == "cabi_export_realloc" {
1156 return Ok(Some(Export::GeneralPurposeExportRealloc));
1157 } else if export.name == "cabi_realloc_adapter" {
1158 return Ok(Some(Export::ReallocForAdapter));
1159 }
1160
1161 let (name, names) = match export.name.strip_prefix("cm32p2") {
1162 Some(name) => (name, STANDARD),
1163 None if encoder.reject_legacy_names => return Ok(None),
1164 None => (export.name, LEGACY),
1165 };
1166
1167 if let Some(export) = self
1168 .classify_component_export(names, name, &export, encoder, exports, types)
1169 .with_context(|| format!("failed to classify export `{}`", export.name))?
1170 {
1171 return Ok(Some(export));
1172 }
1173 log::debug!("unknown export `{}`", export.name);
1174 Ok(None)
1175 }
1176
1177 fn classify_component_export(
1178 &mut self,
1179 names: &dyn NameMangling,
1180 name: &str,
1181 export: &wasmparser::Export<'_>,
1182 encoder: &ComponentEncoder,
1183 exports: &IndexSet<WorldKey>,
1184 types: TypesRef<'_>,
1185 ) -> Result<Option<Export>> {
1186 let resolve = &encoder.metadata.resolve;
1187 let world = encoder.metadata.world;
1188 match export.kind {
1189 ExternalKind::Func => {}
1190 ExternalKind::Memory => {
1191 if name == names.export_memory() {
1192 return Ok(Some(Export::Memory));
1193 }
1194 return Ok(None);
1195 }
1196 ExternalKind::Table => {
1197 if Some(name) == names.export_indirect_function_table() {
1198 return Ok(Some(Export::IndirectFunctionTable));
1199 }
1200 return Ok(None);
1201 }
1202 _ => return Ok(None),
1203 }
1204 let ty = types[types.core_function_at(export.index)].unwrap_func();
1205
1206 // Handle a few special-cased names first.
1207 if name == names.export_realloc() {
1208 let expected = FuncType::new([ValType::I32; 4], [ValType::I32]);
1209 validate_func_sig(name, &expected, ty)?;
1210 return Ok(Some(Export::GeneralPurposeRealloc));
1211 } else if name == names.export_initialize() {
1212 let expected = FuncType::new([], []);
1213 validate_func_sig(name, &expected, ty)?;
1214 return Ok(Some(Export::Initialize));
1215 }
1216
1217 let full_name = name;
1218 let (abi, name) = if let Some(name) = names.async_lift_name(name) {
1219 (AbiVariant::GuestExportAsync, name)
1220 } else if let Some(name) = names.async_lift_stackful_name(name) {
1221 (AbiVariant::GuestExportAsyncStackful, name)
1222 } else {
1223 (AbiVariant::GuestExport, name)
1224 };
1225
1226 // Try to match this to a known WIT export that `exports` allows.
1227 if let Some((key, id, f)) = names.match_wit_export(name, resolve, world, exports) {
1228 validate_func(resolve, ty, f, abi).with_context(|| {
1229 let key = resolve.name_world_key(key);
1230 format!("failed to validate export for `{key}`")
1231 })?;
1232 match id {
1233 Some(id) => {
1234 return Ok(Some(Export::InterfaceFunc(
1235 key.clone(),
1236 id,
1237 f.name.clone(),
1238 abi,
1239 )));
1240 }
1241 None => {
1242 return Ok(Some(Export::WorldFunc(key.clone(), f.name.clone(), abi)));
1243 }
1244 }
1245 }
1246
1247 // See if this is a post-return for any known WIT export.
1248 if let Some(remaining) = names.strip_post_return(name) {
1249 if let Some((key, id, f)) = names.match_wit_export(remaining, resolve, world, exports) {
1250 validate_post_return(resolve, ty, f).with_context(|| {
1251 let key = resolve.name_world_key(key);
1252 format!("failed to validate export for `{key}`")
1253 })?;
1254 match id {
1255 Some(_id) => {
1256 return Ok(Some(Export::InterfaceFuncPostReturn(
1257 key.clone(),
1258 f.name.clone(),
1259 )));
1260 }
1261 None => {
1262 return Ok(Some(Export::WorldFuncPostReturn(key.clone())));
1263 }
1264 }
1265 }
1266 }
1267
1268 if let Some(suffix) = names.async_lift_callback_name(full_name) {
1269 if let Some((key, id, f)) = names.match_wit_export(suffix, resolve, world, exports) {
1270 validate_func_sig(
1271 full_name,
1272 &FuncType::new([ValType::I32; 3], [ValType::I32]),
1273 ty,
1274 )?;
1275 return Ok(Some(if id.is_some() {
1276 Export::InterfaceFuncCallback(key.clone(), f.name.clone())
1277 } else {
1278 Export::WorldFuncCallback(key.clone())
1279 }));
1280 }
1281 }
1282
1283 // And, finally, see if it matches a known destructor.
1284 if let Some(dtor) = names.match_wit_resource_dtor(name, resolve, world, exports) {
1285 let expected = FuncType::new([ValType::I32], []);
1286 validate_func_sig(full_name, &expected, ty)?;
1287 return Ok(Some(Export::ResourceDtor(dtor)));
1288 }
1289
1290 Ok(None)
1291 }
1292
1293 /// Returns the name of the post-return export, if any, for the `key` and
1294 /// `func` combo.
1295 pub fn post_return(&self, key: &WorldKey, func: &Function) -> Option<&str> {
1296 self.find(|m| match m {
1297 Export::WorldFuncPostReturn(k) => k == key,
1298 Export::InterfaceFuncPostReturn(k, f) => k == key && func.name == *f,
1299 _ => false,
1300 })
1301 }
1302
1303 /// Returns the name of the async callback export, if any, for the `key` and
1304 /// `func` combo.
1305 pub fn callback(&self, key: &WorldKey, func: &Function) -> Option<&str> {
1306 self.find(|m| match m {
1307 Export::WorldFuncCallback(k) => k == key,
1308 Export::InterfaceFuncCallback(k, f) => k == key && func.name == *f,
1309 _ => false,
1310 })
1311 }
1312
1313 pub fn abi(&self, key: &WorldKey, func: &Function) -> Option<AbiVariant> {
1314 self.names.values().find_map(|m| match m {
1315 Export::WorldFunc(k, f, abi) if k == key && func.name == *f => Some(*abi),
1316 Export::InterfaceFunc(k, _, f, abi) if k == key && func.name == *f => Some(*abi),
1317 _ => None,
1318 })
1319 }
1320
1321 /// Returns the realloc that the exported function `interface` and `func`
1322 /// are using.
1323 pub fn export_realloc_for(&self, key: &WorldKey, func: &str) -> Option<&str> {
1324 // TODO: This realloc detection should probably be improved with
1325 // some sort of scheme to have per-function reallocs like
1326 // `cabi_realloc_{name}` or something like that.
1327 let _ = (key, func);
1328
1329 if let Some(name) = self.find(|m| matches!(m, Export::GeneralPurposeExportRealloc)) {
1330 return Some(name);
1331 }
1332 self.general_purpose_realloc()
1333 }
1334
1335 /// Returns the realloc that the imported function `interface` and `func`
1336 /// are using.
1337 pub fn import_realloc_for(&self, interface: Option<InterfaceId>, func: &str) -> Option<&str> {
1338 // TODO: This realloc detection should probably be improved with
1339 // some sort of scheme to have per-function reallocs like
1340 // `cabi_realloc_{name}` or something like that.
1341 let _ = (interface, func);
1342
1343 self.import_realloc_fallback()
1344 }
1345
1346 /// Returns the general-purpose realloc function to use for imports.
1347 ///
1348 /// Note that `import_realloc_for` should be used instead where possible.
1349 pub fn import_realloc_fallback(&self) -> Option<&str> {
1350 if let Some(name) = self.find(|m| matches!(m, Export::GeneralPurposeImportRealloc)) {
1351 return Some(name);
1352 }
1353 self.general_purpose_realloc()
1354 }
1355
1356 /// Returns the realloc that the main module is exporting into the adapter.
1357 pub fn realloc_to_import_into_adapter(&self) -> Option<&str> {
1358 if let Some(name) = self.find(|m| matches!(m, Export::ReallocForAdapter)) {
1359 return Some(name);
1360 }
1361 self.general_purpose_realloc()
1362 }
1363
1364 fn general_purpose_realloc(&self) -> Option<&str> {
1365 self.find(|m| matches!(m, Export::GeneralPurposeRealloc))
1366 }
1367
1368 /// Returns the memory, if exported, for this module.
1369 pub fn memory(&self) -> Option<&str> {
1370 self.find(|m| matches!(m, Export::Memory))
1371 }
1372
1373 /// Returns the indirect function table, if exported, for this module.
1374 pub fn indirect_function_table(&self) -> Option<&str> {
1375 self.find(|t| matches!(t, Export::IndirectFunctionTable))
1376 }
1377
1378 /// Returns the `_initialize` intrinsic, if exported, for this module.
1379 pub fn initialize(&self) -> Option<&str> {
1380 self.find(|m| matches!(m, Export::Initialize))
1381 }
1382
1383 /// Returns destructor for the exported resource `ty`, if it was listed.
1384 pub fn resource_dtor(&self, ty: TypeId) -> Option<&str> {
1385 self.find(|m| match m {
1386 Export::ResourceDtor(t) => *t == ty,
1387 _ => false,
1388 })
1389 }
1390
1391 /// NB: this is a linear search and if that's ever a problem this should
1392 /// build up an inverse map during construction to accelerate it.
1393 fn find(&self, f: impl Fn(&Export) -> bool) -> Option<&str> {
1394 let (name, _) = self.names.iter().filter(|(_, m)| f(m)).next()?;
1395 Some(name)
1396 }
1397
1398 /// Iterates over all exports of this module.
1399 pub fn iter(&self) -> impl Iterator<Item = (&str, &Export)> + '_ {
1400 self.names.iter().map(|(n, e)| (n.as_str(), e))
1401 }
1402
1403 fn validate(&self, encoder: &ComponentEncoder, exports: &IndexSet<WorldKey>) -> Result<()> {
1404 let resolve = &encoder.metadata.resolve;
1405 let world = encoder.metadata.world;
1406 // Multi-memory isn't supported because otherwise we don't know what
1407 // memory to put things in.
1408 if self
1409 .names
1410 .values()
1411 .filter(|m| matches!(m, Export::Memory))
1412 .count()
1413 > 1
1414 {
1415 bail!("cannot componentize module that exports multiple memories")
1416 }
1417
1418 // Every async-with-callback-lifted export must have a callback.
1419 for (name, export) in &self.names {
1420 match export {
1421 Export::WorldFunc(_, _, AbiVariant::GuestExportAsync) => {
1422 if !matches!(
1423 self.names.get(&format!("[callback]{name}")),
1424 Some(Export::WorldFuncCallback(_))
1425 ) {
1426 bail!("missing callback for `{name}`");
1427 }
1428 }
1429 Export::InterfaceFunc(_, _, _, AbiVariant::GuestExportAsync) => {
1430 if !matches!(
1431 self.names.get(&format!("[callback]{name}")),
1432 Some(Export::InterfaceFuncCallback(_, _))
1433 ) {
1434 bail!("missing callback for `{name}`");
1435 }
1436 }
1437 _ => {}
1438 }
1439 }
1440
1441 // All of `exports` must be exported and found within this module.
1442 for export in exports {
1443 let require_interface_func = |interface: InterfaceId, name: &str| -> Result<()> {
1444 let result = self.find(|e| match e {
1445 Export::InterfaceFunc(_, id, s, _) => interface == *id && name == s,
1446 _ => false,
1447 });
1448 if result.is_some() {
1449 Ok(())
1450 } else {
1451 let export = resolve.name_world_key(export);
1452 bail!("failed to find export of interface `{export}` function `{name}`")
1453 }
1454 };
1455 let require_world_func = |name: &str| -> Result<()> {
1456 let result = self.find(|e| match e {
1457 Export::WorldFunc(_, s, _) => name == s,
1458 _ => false,
1459 });
1460 if result.is_some() {
1461 Ok(())
1462 } else {
1463 bail!("failed to find export of function `{name}`")
1464 }
1465 };
1466 match &resolve.worlds[world].exports[export] {
1467 WorldItem::Interface { id, .. } => {
1468 for (name, _) in resolve.interfaces[*id].functions.iter() {
1469 require_interface_func(*id, name)?;
1470 }
1471 }
1472 WorldItem::Function(f) => {
1473 require_world_func(&f.name)?;
1474 }
1475 WorldItem::Type(_) => unreachable!(),
1476 }
1477 }
1478
1479 Ok(())
1480 }
1481 }
1482
1483 /// A builtin that may be declared as cancellable.
1484 struct MaybeCancellable<T> {
1485 #[allow(unused)]
1486 inner: T,
1487 cancellable: bool,
1488 }
1489
1490 /// A builtin that may be declared as async-lowered.
1491 struct MaybeAsyncLowered<T> {
1492 inner: T,
1493 async_lowered: bool,
1494 }
1495
1496 /// Context passed to `NameMangling` implementations of stream and future functions
1497 /// to help with looking up payload information.
1498 struct PayloadLookupContext<'a> {
1499 resolve: &'a Resolve,
1500 world: &'a World,
1501 id: Option<InterfaceId>,
1502 import: bool,
1503 key: Option<WorldKey>,
1504 }
1505
1506 /// Trait dispatch and definition for parsing and interpreting "mangled names"
1507 /// which show up in imports and exports of the component model.
1508 ///
1509 /// This trait is used to implement classification of imports and exports in the
1510 /// component model. The methods on `ImportMap` and `ExportMap` will use this to
1511 /// determine what an import is and how it's lifted/lowered in the world being
1512 /// bound.
1513 ///
1514 /// This trait has a bit of history behind it as well. Before
1515 /// WebAssembly/component-model#378 there was no standard naming scheme for core
1516 /// wasm imports or exports when componenitizing. This meant that
1517 /// `wit-component` implemented a particular scheme which mostly worked but was
1518 /// mostly along the lines of "this at least works" rather than "someone sat
1519 /// down and designed this". Since then, however, an standard naming scheme has
1520 /// now been specified which was indeed designed.
1521 ///
1522 /// This trait serves as the bridge between these two. The historical naming
1523 /// scheme is still supported for now through the `Legacy` implementation below
1524 /// and will be for some time. The transition plan at this time is to support
1525 /// the new scheme, eventually get it supported in bindings generators, and once
1526 /// that's all propagated remove support for the legacy scheme.
1527 trait NameMangling {
1528 fn import_root(&self) -> &str;
1529 fn import_non_root_prefix(&self) -> &str;
1530 fn import_exported_intrinsic_prefix(&self) -> &str;
1531 fn export_memory(&self) -> &str;
1532 fn export_initialize(&self) -> &str;
1533 fn export_realloc(&self) -> &str;
1534 fn export_indirect_function_table(&self) -> Option<&str>;
1535 fn resource_drop_name<'a>(&self, name: &'a str) -> Option<&'a str>;
1536 fn resource_new_name<'a>(&self, name: &'a str) -> Option<&'a str>;
1537 fn resource_rep_name<'a>(&self, name: &'a str) -> Option<&'a str>;
1538 fn task_return_name<'a>(&self, name: &'a str) -> Option<&'a str>;
1539 fn task_cancel(&self, name: &str) -> bool;
1540 fn backpressure_set(&self, name: &str) -> bool;
1541 fn backpressure_inc(&self, name: &str) -> bool;
1542 fn backpressure_dec(&self, name: &str) -> bool;
1543 fn waitable_set_new(&self, name: &str) -> bool;
1544 fn waitable_set_wait(&self, name: &str) -> Option<MaybeCancellable<()>>;
1545 fn waitable_set_poll(&self, name: &str) -> Option<MaybeCancellable<()>>;
1546 fn waitable_set_drop(&self, name: &str) -> bool;
1547 fn waitable_join(&self, name: &str) -> bool;
1548 fn thread_yield(&self, name: &str) -> Option<MaybeCancellable<()>>;
1549 fn subtask_drop(&self, name: &str) -> bool;
1550 fn subtask_cancel(&self, name: &str) -> Option<MaybeAsyncLowered<()>>;
1551 fn async_lift_callback_name<'a>(&self, name: &'a str) -> Option<&'a str>;
1552 fn async_lift_name<'a>(&self, name: &'a str) -> Option<&'a str>;
1553 fn async_lift_stackful_name<'a>(&self, name: &'a str) -> Option<&'a str>;
1554 fn error_context_new(&self, name: &str) -> Option<StringEncoding>;
1555 fn error_context_debug_message(&self, name: &str) -> Option<StringEncoding>;
1556 fn error_context_drop(&self, name: &str) -> bool;
1557 fn context_get(&self, name: &str) -> Option<u32>;
1558 fn context_set(&self, name: &str) -> Option<u32>;
1559 fn future_new(&self, lookup_context: &PayloadLookupContext, name: &str) -> Option<PayloadInfo>;
1560 fn future_write(
1561 &self,
1562 lookup_context: &PayloadLookupContext,
1563 name: &str,
1564 ) -> Option<MaybeAsyncLowered<PayloadInfo>>;
1565 fn future_read(
1566 &self,
1567 lookup_context: &PayloadLookupContext,
1568 name: &str,
1569 ) -> Option<MaybeAsyncLowered<PayloadInfo>>;
1570 fn future_cancel_write(
1571 &self,
1572 lookup_context: &PayloadLookupContext,
1573 name: &str,
1574 ) -> Option<MaybeAsyncLowered<PayloadInfo>>;
1575 fn future_cancel_read(
1576 &self,
1577 lookup_context: &PayloadLookupContext,
1578 name: &str,
1579 ) -> Option<MaybeAsyncLowered<PayloadInfo>>;
1580 fn future_drop_writable(
1581 &self,
1582 lookup_context: &PayloadLookupContext,
1583 name: &str,
1584 ) -> Option<PayloadInfo>;
1585 fn future_drop_readable(
1586 &self,
1587 lookup_context: &PayloadLookupContext,
1588 name: &str,
1589 ) -> Option<PayloadInfo>;
1590 fn stream_new(&self, lookup_context: &PayloadLookupContext, name: &str) -> Option<PayloadInfo>;
1591 fn stream_write(
1592 &self,
1593 lookup_context: &PayloadLookupContext,
1594 name: &str,
1595 ) -> Option<MaybeAsyncLowered<PayloadInfo>>;
1596 fn stream_read(
1597 &self,
1598 lookup_context: &PayloadLookupContext,
1599 name: &str,
1600 ) -> Option<MaybeAsyncLowered<PayloadInfo>>;
1601 fn stream_cancel_write(
1602 &self,
1603 lookup_context: &PayloadLookupContext,
1604 name: &str,
1605 ) -> Option<MaybeAsyncLowered<PayloadInfo>>;
1606 fn stream_cancel_read(
1607 &self,
1608 lookup_context: &PayloadLookupContext,
1609 name: &str,
1610 ) -> Option<MaybeAsyncLowered<PayloadInfo>>;
1611 fn stream_drop_writable(
1612 &self,
1613 lookup_context: &PayloadLookupContext,
1614 name: &str,
1615 ) -> Option<PayloadInfo>;
1616 fn stream_drop_readable(
1617 &self,
1618 lookup_context: &PayloadLookupContext,
1619 name: &str,
1620 ) -> Option<PayloadInfo>;
1621 fn thread_index(&self, name: &str) -> bool;
1622 fn thread_new_indirect(&self, name: &str) -> bool;
1623 fn thread_switch_to(&self, name: &str) -> Option<MaybeCancellable<()>>;
1624 fn thread_suspend(&self, name: &str) -> Option<MaybeCancellable<()>>;
1625 fn thread_resume_later(&self, name: &str) -> bool;
1626 fn thread_yield_to(&self, name: &str) -> Option<MaybeCancellable<()>>;
1627 fn module_to_interface(
1628 &self,
1629 module: &str,
1630 resolve: &Resolve,
1631 items: &IndexMap<WorldKey, WorldItem>,
1632 ) -> Result<(WorldKey, InterfaceId)>;
1633 fn strip_post_return<'a>(&self, name: &'a str) -> Option<&'a str>;
1634 fn match_wit_export<'a>(
1635 &self,
1636 export_name: &str,
1637 resolve: &'a Resolve,
1638 world: WorldId,
1639 exports: &'a IndexSet<WorldKey>,
1640 ) -> Option<(&'a WorldKey, Option<InterfaceId>, &'a Function)>;
1641 fn match_wit_resource_dtor<'a>(
1642 &self,
1643 export_name: &str,
1644 resolve: &'a Resolve,
1645 world: WorldId,
1646 exports: &'a IndexSet<WorldKey>,
1647 ) -> Option<TypeId>;
1648 fn world_key_name_and_abi<'a>(&self, name: &'a str) -> (&'a str, AbiVariant);
1649 fn interface_function_name_and_abi<'a>(&self, name: &'a str) -> (&'a str, AbiVariant);
1650 }
1651
1652 /// Definition of the "standard" naming scheme which currently starts with
1653 /// "cm32p2". Note that wasm64 is not supported at this time.
1654 struct Standard;
1655
1656 const STANDARD: &'static dyn NameMangling = &Standard;
1657
1658 impl NameMangling for Standard {
1659 fn import_root(&self) -> &str {
1660 ""
1661 }
1662 fn import_non_root_prefix(&self) -> &str {
1663 "|"
1664 }
1665 fn import_exported_intrinsic_prefix(&self) -> &str {
1666 "_ex_"
1667 }
1668 fn export_memory(&self) -> &str {
1669 "_memory"
1670 }
1671 fn export_initialize(&self) -> &str {
1672 "_initialize"
1673 }
1674 fn export_realloc(&self) -> &str {
1675 "_realloc"
1676 }
1677 fn export_indirect_function_table(&self) -> Option<&str> {
1678 None
1679 }
1680 fn resource_drop_name<'a>(&self, name: &'a str) -> Option<&'a str> {
1681 name.strip_suffix("_drop")
1682 }
1683 fn resource_new_name<'a>(&self, name: &'a str) -> Option<&'a str> {
1684 name.strip_suffix("_new")
1685 }
1686 fn resource_rep_name<'a>(&self, name: &'a str) -> Option<&'a str> {
1687 name.strip_suffix("_rep")
1688 }
1689 fn task_return_name<'a>(&self, _name: &'a str) -> Option<&'a str> {
1690 None
1691 }
1692 fn task_cancel(&self, _name: &str) -> bool {
1693 false
1694 }
1695 fn backpressure_set(&self, _name: &str) -> bool {
1696 false
1697 }
1698 fn backpressure_inc(&self, _name: &str) -> bool {
1699 false
1700 }
1701 fn backpressure_dec(&self, _name: &str) -> bool {
1702 false
1703 }
1704 fn waitable_set_new(&self, _name: &str) -> bool {
1705 false
1706 }
1707 fn waitable_set_wait(&self, _name: &str) -> Option<MaybeCancellable<()>> {
1708 None
1709 }
1710 fn waitable_set_poll(&self, _name: &str) -> Option<MaybeCancellable<()>> {
1711 None
1712 }
1713 fn waitable_set_drop(&self, _name: &str) -> bool {
1714 false
1715 }
1716 fn waitable_join(&self, _name: &str) -> bool {
1717 false
1718 }
1719 fn thread_yield(&self, _name: &str) -> Option<MaybeCancellable<()>> {
1720 None
1721 }
1722 fn subtask_drop(&self, _name: &str) -> bool {
1723 false
1724 }
1725 fn subtask_cancel(&self, _name: &str) -> Option<MaybeAsyncLowered<()>> {
1726 None
1727 }
1728 fn async_lift_callback_name<'a>(&self, _name: &'a str) -> Option<&'a str> {
1729 None
1730 }
1731 fn async_lift_name<'a>(&self, _name: &'a str) -> Option<&'a str> {
1732 None
1733 }
1734 fn async_lift_stackful_name<'a>(&self, _name: &'a str) -> Option<&'a str> {
1735 None
1736 }
1737 fn error_context_new(&self, _name: &str) -> Option<StringEncoding> {
1738 None
1739 }
1740 fn error_context_debug_message(&self, _name: &str) -> Option<StringEncoding> {
1741 None
1742 }
1743 fn error_context_drop(&self, _name: &str) -> bool {
1744 false
1745 }
1746 fn context_get(&self, _name: &str) -> Option<u32> {
1747 None
1748 }
1749 fn context_set(&self, _name: &str) -> Option<u32> {
1750 None
1751 }
1752 fn thread_index(&self, _name: &str) -> bool {
1753 false
1754 }
1755 fn thread_new_indirect(&self, _name: &str) -> bool {
1756 false
1757 }
1758 fn thread_switch_to(&self, _name: &str) -> Option<MaybeCancellable<()>> {
1759 None
1760 }
1761 fn thread_suspend(&self, _name: &str) -> Option<MaybeCancellable<()>> {
1762 None
1763 }
1764 fn thread_resume_later(&self, _name: &str) -> bool {
1765 false
1766 }
1767 fn thread_yield_to(&self, _name: &str) -> Option<MaybeCancellable<()>> {
1768 None
1769 }
1770 fn future_new(
1771 &self,
1772 _lookup_context: &PayloadLookupContext,
1773 _name: &str,
1774 ) -> Option<PayloadInfo> {
1775 None
1776 }
1777 fn future_write(
1778 &self,
1779 _lookup_context: &PayloadLookupContext,
1780 _name: &str,
1781 ) -> Option<MaybeAsyncLowered<PayloadInfo>> {
1782 None
1783 }
1784 fn future_read(
1785 &self,
1786 _lookup_context: &PayloadLookupContext,
1787 _name: &str,
1788 ) -> Option<MaybeAsyncLowered<PayloadInfo>> {
1789 None
1790 }
1791 fn future_cancel_write(
1792 &self,
1793 _lookup_context: &PayloadLookupContext,
1794 _name: &str,
1795 ) -> Option<MaybeAsyncLowered<PayloadInfo>> {
1796 None
1797 }
1798 fn future_cancel_read(
1799 &self,
1800 _lookup_context: &PayloadLookupContext,
1801 _name: &str,
1802 ) -> Option<MaybeAsyncLowered<PayloadInfo>> {
1803 None
1804 }
1805 fn future_drop_writable(
1806 &self,
1807 _lookup_context: &PayloadLookupContext,
1808 _name: &str,
1809 ) -> Option<PayloadInfo> {
1810 None
1811 }
1812 fn future_drop_readable(
1813 &self,
1814 _lookup_context: &PayloadLookupContext,
1815 _name: &str,
1816 ) -> Option<PayloadInfo> {
1817 None
1818 }
1819 fn stream_new(
1820 &self,
1821 _lookup_context: &PayloadLookupContext,
1822 _name: &str,
1823 ) -> Option<PayloadInfo> {
1824 None
1825 }
1826 fn stream_write(
1827 &self,
1828 _lookup_context: &PayloadLookupContext,
1829 _name: &str,
1830 ) -> Option<MaybeAsyncLowered<PayloadInfo>> {
1831 None
1832 }
1833 fn stream_read(
1834 &self,
1835 _lookup_context: &PayloadLookupContext,
1836 _name: &str,
1837 ) -> Option<MaybeAsyncLowered<PayloadInfo>> {
1838 None
1839 }
1840 fn stream_cancel_write(
1841 &self,
1842 _lookup_context: &PayloadLookupContext,
1843 _name: &str,
1844 ) -> Option<MaybeAsyncLowered<PayloadInfo>> {
1845 None
1846 }
1847 fn stream_cancel_read(
1848 &self,
1849 _lookup_context: &PayloadLookupContext,
1850 _name: &str,
1851 ) -> Option<MaybeAsyncLowered<PayloadInfo>> {
1852 None
1853 }
1854 fn stream_drop_writable(
1855 &self,
1856 _lookup_context: &PayloadLookupContext,
1857 _name: &str,
1858 ) -> Option<PayloadInfo> {
1859 None
1860 }
1861 fn stream_drop_readable(
1862 &self,
1863 _lookup_context: &PayloadLookupContext,
1864 _name: &str,
1865 ) -> Option<PayloadInfo> {
1866 None
1867 }
1868 fn module_to_interface(
1869 &self,
1870 interface: &str,
1871 resolve: &Resolve,
1872 items: &IndexMap<WorldKey, WorldItem>,
1873 ) -> Result<(WorldKey, InterfaceId)> {
1874 for (key, item) in items.iter() {
1875 let id = match key {
1876 // Bare keys are matched exactly against `interface`
1877 WorldKey::Name(name) => match item {
1878 WorldItem::Interface { id, .. } if name == interface => *id,
1879 _ => continue,
1880 },
1881 // ID-identified keys are matched with their "canonical name"
1882 WorldKey::Interface(id) => {
1883 if resolve.canonicalized_id_of(*id).as_deref() != Some(interface) {
1884 continue;
1885 }
1886 *id
1887 }
1888 };
1889 return Ok((key.clone(), id));
1890 }
1891 bail!("failed to find world item corresponding to interface `{interface}`")
1892 }
1893 fn strip_post_return<'a>(&self, name: &'a str) -> Option<&'a str> {
1894 name.strip_suffix("_post")
1895 }
1896 fn match_wit_export<'a>(
1897 &self,
1898 export_name: &str,
1899 resolve: &'a Resolve,
1900 world: WorldId,
1901 exports: &'a IndexSet<WorldKey>,
1902 ) -> Option<(&'a WorldKey, Option<InterfaceId>, &'a Function)> {
1903 if let Some(world_export_name) = export_name.strip_prefix("||") {
1904 let key = exports.get(&WorldKey::Name(world_export_name.to_string()))?;
1905 match &resolve.worlds[world].exports[key] {
1906 WorldItem::Function(f) => return Some((key, None, f)),
1907 _ => return None,
1908 }
1909 }
1910
1911 let (key, id, func_name) =
1912 self.match_wit_interface(export_name, resolve, world, exports)?;
1913 let func = resolve.interfaces[id].functions.get(func_name)?;
1914 Some((key, Some(id), func))
1915 }
1916
1917 fn match_wit_resource_dtor<'a>(
1918 &self,
1919 export_name: &str,
1920 resolve: &'a Resolve,
1921 world: WorldId,
1922 exports: &'a IndexSet<WorldKey>,
1923 ) -> Option<TypeId> {
1924 let (_key, id, name) =
1925 self.match_wit_interface(export_name.strip_suffix("_dtor")?, resolve, world, exports)?;
1926 let ty = *resolve.interfaces[id].types.get(name)?;
1927 match resolve.types[ty].kind {
1928 TypeDefKind::Resource => Some(ty),
1929 _ => None,
1930 }
1931 }
1932
1933 fn world_key_name_and_abi<'a>(&self, name: &'a str) -> (&'a str, AbiVariant) {
1934 (name, AbiVariant::GuestImport)
1935 }
1936 fn interface_function_name_and_abi<'a>(&self, name: &'a str) -> (&'a str, AbiVariant) {
1937 (name, AbiVariant::GuestImport)
1938 }
1939 }
1940
1941 impl Standard {
1942 fn match_wit_interface<'a, 'b>(
1943 &self,
1944 export_name: &'b str,
1945 resolve: &'a Resolve,
1946 world: WorldId,
1947 exports: &'a IndexSet<WorldKey>,
1948 ) -> Option<(&'a WorldKey, InterfaceId, &'b str)> {
1949 let world = &resolve.worlds[world];
1950 let export_name = export_name.strip_prefix("|")?;
1951
1952 for export in exports {
1953 let id = match &world.exports[export] {
1954 WorldItem::Interface { id, .. } => *id,
1955 WorldItem::Function(_) => continue,
1956 WorldItem::Type(_) => unreachable!(),
1957 };
1958 let remaining = match export {
1959 WorldKey::Name(name) => export_name.strip_prefix(name),
1960 WorldKey::Interface(_) => {
1961 let prefix = resolve.canonicalized_id_of(id).unwrap();
1962 export_name.strip_prefix(&prefix)
1963 }
1964 };
1965 let item_name = match remaining.and_then(|s| s.strip_prefix("|")) {
1966 Some(name) => name,
1967 None => continue,
1968 };
1969 return Some((export, id, item_name));
1970 }
1971
1972 None
1973 }
1974 }
1975
1976 /// Definition of wit-component's "legacy" naming scheme which predates
1977 /// WebAssembly/component-model#378.
1978 struct Legacy;
1979
1980 const LEGACY: &'static dyn NameMangling = &Legacy;
1981
1982 impl Legacy {
1983 // Looks for `[$prefix-N]foo` within `name`. If found then `foo` is
1984 // used to find a function within `id` and `world` above. Once found
1985 // then `N` is used to index within that function to extract a
1986 // future/stream type. If that's all found then a `PayloadInfo` is
1987 // returned to get attached to an intrinsic.
1988 fn prefixed_payload(
1989 &self,
1990 lookup_context: &PayloadLookupContext,
1991 name: &str,
1992 prefix: &str,
1993 ) -> Option<PayloadInfo> {
1994 // parse the `prefix` into `func_name` and `type_index`, bailing out
1995 // with `None` if anything doesn't match.
1996 let (type_index, func_name) = prefixed_integer(name, prefix)?;
1997 let type_index = type_index as usize;
1998
1999 // Double-check that `func_name` is indeed a function name within
2000 // this interface/world. Then additionally double-check that
2001 // `type_index` is indeed a valid index for this function's type
2002 // signature.
2003 let function = get_function(
2004 lookup_context.resolve,
2005 lookup_context.world,
2006 func_name,
2007 lookup_context.id,
2008 lookup_context.import,
2009 )
2010 .ok()?;
2011 let ty = *function
2012 .find_futures_and_streams(lookup_context.resolve)
2013 .get(type_index)?;
2014
2015 // And if all that passes wrap up everything in a `PayloadInfo`.
2016 Some(PayloadInfo {
2017 name: name.to_string(),
2018 ty,
2019 function: function.name.clone(),
2020 key: lookup_context
2021 .key
2022 .clone()
2023 .unwrap_or_else(|| WorldKey::Name(name.to_string())),
2024 interface: lookup_context.id,
2025 imported: lookup_context.import,
2026 })
2027 }
2028
2029 fn maybe_async_lowered_payload(
2030 &self,
2031 lookup_context: &PayloadLookupContext,
2032 name: &str,
2033 prefix: &str,
2034 ) -> Option<MaybeAsyncLowered<PayloadInfo>> {
2035 let (async_lowered, clean_name) = self.strip_async_lowered_prefix(name);
2036 let payload = self.prefixed_payload(lookup_context, clean_name, prefix)?;
2037 Some(MaybeAsyncLowered {
2038 inner: payload,
2039 async_lowered,
2040 })
2041 }
2042
2043 fn strip_async_lowered_prefix<'a>(&self, name: &'a str) -> (bool, &'a str) {
2044 name.strip_prefix("[async-lower]")
2045 .map_or((false, name), |s| (true, s))
2046 }
2047 fn match_with_async_lowered_prefix(
2048 &self,
2049 name: &str,
2050 expected: &str,
2051 ) -> Option<MaybeAsyncLowered<()>> {
2052 let (async_lowered, clean_name) = self.strip_async_lowered_prefix(name);
2053 if clean_name == expected {
2054 Some(MaybeAsyncLowered {
2055 inner: (),
2056 async_lowered,
2057 })
2058 } else {
2059 None
2060 }
2061 }
2062 fn strip_cancellable_prefix<'a>(&self, name: &'a str) -> (bool, &'a str) {
2063 name.strip_prefix("[cancellable]")
2064 .map_or((false, name), |s| (true, s))
2065 }
2066 fn match_with_cancellable_prefix(
2067 &self,
2068 name: &str,
2069 expected: &str,
2070 ) -> Option<MaybeCancellable<()>> {
2071 let (cancellable, clean_name) = self.strip_cancellable_prefix(name);
2072 if clean_name == expected {
2073 Some(MaybeCancellable {
2074 inner: (),
2075 cancellable,
2076 })
2077 } else {
2078 None
2079 }
2080 }
2081 }
2082
2083 impl NameMangling for Legacy {
2084 fn import_root(&self) -> &str {
2085 "$root"
2086 }
2087 fn import_non_root_prefix(&self) -> &str {
2088 ""
2089 }
2090 fn import_exported_intrinsic_prefix(&self) -> &str {
2091 "[export]"
2092 }
2093 fn export_memory(&self) -> &str {
2094 "memory"
2095 }
2096 fn export_initialize(&self) -> &str {
2097 "_initialize"
2098 }
2099 fn export_realloc(&self) -> &str {
2100 "cabi_realloc"
2101 }
2102 fn export_indirect_function_table(&self) -> Option<&str> {
2103 Some("__indirect_function_table")
2104 }
2105 fn resource_drop_name<'a>(&self, name: &'a str) -> Option<&'a str> {
2106 name.strip_prefix("[resource-drop]")
2107 }
2108 fn resource_new_name<'a>(&self, name: &'a str) -> Option<&'a str> {
2109 name.strip_prefix("[resource-new]")
2110 }
2111 fn resource_rep_name<'a>(&self, name: &'a str) -> Option<&'a str> {
2112 name.strip_prefix("[resource-rep]")
2113 }
2114 fn task_return_name<'a>(&self, name: &'a str) -> Option<&'a str> {
2115 name.strip_prefix("[task-return]")
2116 }
2117 fn task_cancel(&self, name: &str) -> bool {
2118 name == "[task-cancel]"
2119 }
2120 fn backpressure_set(&self, name: &str) -> bool {
2121 name == "[backpressure-set]"
2122 }
2123 fn backpressure_inc(&self, name: &str) -> bool {
2124 name == "[backpressure-inc]"
2125 }
2126 fn backpressure_dec(&self, name: &str) -> bool {
2127 name == "[backpressure-dec]"
2128 }
2129 fn waitable_set_new(&self, name: &str) -> bool {
2130 name == "[waitable-set-new]"
2131 }
2132 fn waitable_set_wait(&self, name: &str) -> Option<MaybeCancellable<()>> {
2133 self.match_with_cancellable_prefix(name, "[waitable-set-wait]")
2134 }
2135 fn waitable_set_poll(&self, name: &str) -> Option<MaybeCancellable<()>> {
2136 self.match_with_cancellable_prefix(name, "[waitable-set-poll]")
2137 }
2138 fn waitable_set_drop(&self, name: &str) -> bool {
2139 name == "[waitable-set-drop]"
2140 }
2141 fn waitable_join(&self, name: &str) -> bool {
2142 name == "[waitable-join]"
2143 }
2144 fn thread_yield(&self, name: &str) -> Option<MaybeCancellable<()>> {
2145 self.match_with_cancellable_prefix(name, "[thread-yield]")
2146 }
2147 fn subtask_drop(&self, name: &str) -> bool {
2148 name == "[subtask-drop]"
2149 }
2150 fn subtask_cancel(&self, name: &str) -> Option<MaybeAsyncLowered<()>> {
2151 self.match_with_async_lowered_prefix(name, "[subtask-cancel]")
2152 }
2153 fn async_lift_callback_name<'a>(&self, name: &'a str) -> Option<&'a str> {
2154 name.strip_prefix("[callback][async-lift]")
2155 }
2156 fn async_lift_name<'a>(&self, name: &'a str) -> Option<&'a str> {
2157 name.strip_prefix("[async-lift]")
2158 }
2159 fn async_lift_stackful_name<'a>(&self, name: &'a str) -> Option<&'a str> {
2160 name.strip_prefix("[async-lift-stackful]")
2161 }
2162 fn error_context_new(&self, name: &str) -> Option<StringEncoding> {
2163 match name {
2164 "[error-context-new-utf8]" => Some(StringEncoding::UTF8),
2165 "[error-context-new-utf16]" => Some(StringEncoding::UTF16),
2166 "[error-context-new-latin1+utf16]" => Some(StringEncoding::CompactUTF16),
2167 _ => None,
2168 }
2169 }
2170 fn error_context_debug_message(&self, name: &str) -> Option<StringEncoding> {
2171 match name {
2172 "[error-context-debug-message-utf8]" => Some(StringEncoding::UTF8),
2173 "[error-context-debug-message-utf16]" => Some(StringEncoding::UTF16),
2174 "[error-context-debug-message-latin1+utf16]" => Some(StringEncoding::CompactUTF16),
2175 _ => None,
2176 }
2177 }
2178 fn error_context_drop(&self, name: &str) -> bool {
2179 name == "[error-context-drop]"
2180 }
2181 fn context_get(&self, name: &str) -> Option<u32> {
2182 let (n, rest) = prefixed_integer(name, "[context-get-")?;
2183 if rest.is_empty() { Some(n) } else { None }
2184 }
2185 fn context_set(&self, name: &str) -> Option<u32> {
2186 let (n, rest) = prefixed_integer(name, "[context-set-")?;
2187 if rest.is_empty() { Some(n) } else { None }
2188 }
2189 fn thread_index(&self, name: &str) -> bool {
2190 name == "[thread-index]"
2191 }
2192 fn thread_new_indirect(&self, name: &str) -> bool {
2193 // For now, we'll fix the type of the start function and the table to extract it from
2194 name == "[thread-new-indirect-v0]"
2195 }
2196 fn thread_switch_to(&self, name: &str) -> Option<MaybeCancellable<()>> {
2197 self.match_with_cancellable_prefix(name, "[thread-switch-to]")
2198 }
2199 fn thread_suspend(&self, name: &str) -> Option<MaybeCancellable<()>> {
2200 self.match_with_cancellable_prefix(name, "[thread-suspend]")
2201 }
2202 fn thread_resume_later(&self, name: &str) -> bool {
2203 name == "[thread-resume-later]"
2204 }
2205 fn thread_yield_to(&self, name: &str) -> Option<MaybeCancellable<()>> {
2206 self.match_with_cancellable_prefix(name, "[thread-yield-to]")
2207 }
2208 fn future_new(&self, lookup_context: &PayloadLookupContext, name: &str) -> Option<PayloadInfo> {
2209 self.prefixed_payload(lookup_context, name, "[future-new-")
2210 }
2211 fn future_write(
2212 &self,
2213 lookup_context: &PayloadLookupContext,
2214 name: &str,
2215 ) -> Option<MaybeAsyncLowered<PayloadInfo>> {
2216 self.maybe_async_lowered_payload(lookup_context, name, "[future-write-")
2217 }
2218 fn future_read(
2219 &self,
2220 lookup_context: &PayloadLookupContext,
2221 name: &str,
2222 ) -> Option<MaybeAsyncLowered<PayloadInfo>> {
2223 self.maybe_async_lowered_payload(lookup_context, name, "[future-read-")
2224 }
2225 fn future_cancel_write(
2226 &self,
2227 lookup_context: &PayloadLookupContext,
2228 name: &str,
2229 ) -> Option<MaybeAsyncLowered<PayloadInfo>> {
2230 self.maybe_async_lowered_payload(lookup_context, name, "[future-cancel-write-")
2231 }
2232 fn future_cancel_read(
2233 &self,
2234 lookup_context: &PayloadLookupContext,
2235 name: &str,
2236 ) -> Option<MaybeAsyncLowered<PayloadInfo>> {
2237 self.maybe_async_lowered_payload(lookup_context, name, "[future-cancel-read-")
2238 }
2239 fn future_drop_writable(
2240 &self,
2241 lookup_context: &PayloadLookupContext,
2242 name: &str,
2243 ) -> Option<PayloadInfo> {
2244 self.prefixed_payload(lookup_context, name, "[future-drop-writable-")
2245 }
2246 fn future_drop_readable(
2247 &self,
2248 lookup_context: &PayloadLookupContext,
2249 name: &str,
2250 ) -> Option<PayloadInfo> {
2251 self.prefixed_payload(lookup_context, name, "[future-drop-readable-")
2252 }
2253 fn stream_new(&self, lookup_context: &PayloadLookupContext, name: &str) -> Option<PayloadInfo> {
2254 self.prefixed_payload(lookup_context, name, "[stream-new-")
2255 }
2256 fn stream_write(
2257 &self,
2258 lookup_context: &PayloadLookupContext,
2259 name: &str,
2260 ) -> Option<MaybeAsyncLowered<PayloadInfo>> {
2261 self.maybe_async_lowered_payload(lookup_context, name, "[stream-write-")
2262 }
2263 fn stream_read(
2264 &self,
2265 lookup_context: &PayloadLookupContext,
2266 name: &str,
2267 ) -> Option<MaybeAsyncLowered<PayloadInfo>> {
2268 self.maybe_async_lowered_payload(lookup_context, name, "[stream-read-")
2269 }
2270 fn stream_cancel_write(
2271 &self,
2272 lookup_context: &PayloadLookupContext,
2273 name: &str,
2274 ) -> Option<MaybeAsyncLowered<PayloadInfo>> {
2275 self.maybe_async_lowered_payload(lookup_context, name, "[stream-cancel-write-")
2276 }
2277 fn stream_cancel_read(
2278 &self,
2279 lookup_context: &PayloadLookupContext,
2280 name: &str,
2281 ) -> Option<MaybeAsyncLowered<PayloadInfo>> {
2282 self.maybe_async_lowered_payload(lookup_context, name, "[stream-cancel-read-")
2283 }
2284 fn stream_drop_writable(
2285 &self,
2286 lookup_context: &PayloadLookupContext,
2287 name: &str,
2288 ) -> Option<PayloadInfo> {
2289 self.prefixed_payload(lookup_context, name, "[stream-drop-writable-")
2290 }
2291 fn stream_drop_readable(
2292 &self,
2293 lookup_context: &PayloadLookupContext,
2294 name: &str,
2295 ) -> Option<PayloadInfo> {
2296 self.prefixed_payload(lookup_context, name, "[stream-drop-readable-")
2297 }
2298 fn module_to_interface(
2299 &self,
2300 module: &str,
2301 resolve: &Resolve,
2302 items: &IndexMap<WorldKey, WorldItem>,
2303 ) -> Result<(WorldKey, InterfaceId)> {
2304 // First see if this is a bare name
2305 let bare_name = WorldKey::Name(module.to_string());
2306 if let Some(WorldItem::Interface { id, .. }) = items.get(&bare_name) {
2307 return Ok((bare_name, *id));
2308 }
2309
2310 // ... and if this isn't a bare name then it's time to do some parsing
2311 // related to interfaces, versions, and such. First up the `module` name
2312 // is parsed as a normal component name from `wasmparser` to see if it's
2313 // of the "interface kind". If it's not then that means the above match
2314 // should have been a hit but it wasn't, so an error is returned.
2315 let kebab_name = ComponentName::new(module, 0);
2316 let name = match kebab_name.as_ref().map(|k| k.kind()) {
2317 Ok(ComponentNameKind::Interface(name)) => name,
2318 _ => bail!("module requires an import interface named `{module}`"),
2319 };
2320
2321 // Prioritize an exact match based on versions, so try that first.
2322 let pkgname = PackageName {
2323 namespace: name.namespace().to_string(),
2324 name: name.package().to_string(),
2325 version: name.version(),
2326 };
2327 if let Some(pkg) = resolve.package_names.get(&pkgname) {
2328 if let Some(id) = resolve.packages[*pkg]
2329 .interfaces
2330 .get(name.interface().as_str())
2331 {
2332 let key = WorldKey::Interface(*id);
2333 if items.contains_key(&key) {
2334 return Ok((key, *id));
2335 }
2336 }
2337 }
2338
2339 // If an exact match wasn't found then instead search for the first
2340 // match based on versions. This means that a core wasm import for
2341 // "1.2.3" might end up matching an interface at "1.2.4", for example.
2342 // (or "1.2.2", depending on what's available).
2343 for (key, _) in items {
2344 let id = match key {
2345 WorldKey::Interface(id) => *id,
2346 WorldKey::Name(_) => continue,
2347 };
2348 // Make sure the interface names match
2349 let interface = &resolve.interfaces[id];
2350 if interface.name.as_ref().unwrap() != name.interface().as_str() {
2351 continue;
2352 }
2353
2354 // Make sure the package name (without version) matches
2355 let pkg = &resolve.packages[interface.package.unwrap()];
2356 if pkg.name.namespace != pkgname.namespace || pkg.name.name != pkgname.name {
2357 continue;
2358 }
2359
2360 let module_version = match name.version() {
2361 Some(version) => version,
2362 None => continue,
2363 };
2364 let pkg_version = match &pkg.name.version {
2365 Some(version) => version,
2366 None => continue,
2367 };
2368
2369 // Test if the two semver versions are compatible
2370 let module_compat = PackageName::version_compat_track(&module_version);
2371 let pkg_compat = PackageName::version_compat_track(pkg_version);
2372 if module_compat == pkg_compat {
2373 return Ok((key.clone(), id));
2374 }
2375 }
2376
2377 bail!("module requires an import interface named `{module}`")
2378 }
2379 fn strip_post_return<'a>(&self, name: &'a str) -> Option<&'a str> {
2380 name.strip_prefix("cabi_post_")
2381 }
2382 fn match_wit_export<'a>(
2383 &self,
2384 export_name: &str,
2385 resolve: &'a Resolve,
2386 world: WorldId,
2387 exports: &'a IndexSet<WorldKey>,
2388 ) -> Option<(&'a WorldKey, Option<InterfaceId>, &'a Function)> {
2389 let world = &resolve.worlds[world];
2390 for name in exports {
2391 match &world.exports[name] {
2392 WorldItem::Function(f) => {
2393 if f.legacy_core_export_name(None) == export_name {
2394 return Some((name, None, f));
2395 }
2396 }
2397 WorldItem::Interface { id, .. } => {
2398 let string = resolve.name_world_key(name);
2399 for (_, func) in resolve.interfaces[*id].functions.iter() {
2400 if func.legacy_core_export_name(Some(&string)) == export_name {
2401 return Some((name, Some(*id), func));
2402 }
2403 }
2404 }
2405
2406 WorldItem::Type(_) => unreachable!(),
2407 }
2408 }
2409
2410 None
2411 }
2412
2413 fn match_wit_resource_dtor<'a>(
2414 &self,
2415 export_name: &str,
2416 resolve: &'a Resolve,
2417 world: WorldId,
2418 exports: &'a IndexSet<WorldKey>,
2419 ) -> Option<TypeId> {
2420 let world = &resolve.worlds[world];
2421 for name in exports {
2422 let id = match &world.exports[name] {
2423 WorldItem::Interface { id, .. } => *id,
2424 WorldItem::Function(_) => continue,
2425 WorldItem::Type(_) => unreachable!(),
2426 };
2427 let name = resolve.name_world_key(name);
2428 let resource = match export_name
2429 .strip_prefix(&name)
2430 .and_then(|s| s.strip_prefix("#[dtor]"))
2431 .and_then(|r| resolve.interfaces[id].types.get(r))
2432 {
2433 Some(id) => *id,
2434 None => continue,
2435 };
2436
2437 match resolve.types[resource].kind {
2438 TypeDefKind::Resource => {}
2439 _ => continue,
2440 }
2441
2442 return Some(resource);
2443 }
2444
2445 None
2446 }
2447
2448 fn world_key_name_and_abi<'a>(&self, name: &'a str) -> (&'a str, AbiVariant) {
2449 let (async_abi, name) = self.strip_async_lowered_prefix(name);
2450 (
2451 name,
2452 if async_abi {
2453 AbiVariant::GuestImportAsync
2454 } else {
2455 AbiVariant::GuestImport
2456 },
2457 )
2458 }
2459 fn interface_function_name_and_abi<'a>(&self, name: &'a str) -> (&'a str, AbiVariant) {
2460 let (async_abi, name) = self.strip_async_lowered_prefix(name);
2461 (
2462 name,
2463 if async_abi {
2464 AbiVariant::GuestImportAsync
2465 } else {
2466 AbiVariant::GuestImport
2467 },
2468 )
2469 }
2470 }
2471
2472 /// This function validates the following:
2473 ///
2474 /// * The `bytes` represent a valid core WebAssembly module.
2475 /// * The module's imports are all satisfied by the given `imports` interfaces
2476 /// or the `adapters` set.
2477 /// * The given default and exported interfaces are satisfied by the module's
2478 /// exports.
2479 ///
2480 /// The `ValidatedModule` return value contains the metadata which describes the
2481 /// input module on success. This is then further used to generate a component
2482 /// for this module.
2483 pub fn validate_module(
2484 encoder: &ComponentEncoder,
2485 bytes: &[u8],
2486 import_map: Option<&ModuleImportMap>,
2487 ) -> Result<ValidatedModule> {
2488 ValidatedModule::new(
2489 encoder,
2490 bytes,
2491 &encoder.main_module_exports,
2492 import_map,
2493 None,
2494 )
2495 }
2496
2497 /// This function will validate the `bytes` provided as a wasm adapter module.
2498 /// Notably this will validate the wasm module itself in addition to ensuring
2499 /// that it has the "shape" of an adapter module. Current constraints are:
2500 ///
2501 /// * The adapter module can import only one memory
2502 /// * The adapter module can only import from the name of `interface` specified,
2503 /// and all function imports must match the `required` types which correspond
2504 /// to the lowered types of the functions in `interface`.
2505 ///
2506 /// The wasm module passed into this function is the output of the GC pass of an
2507 /// adapter module's original source. This means that the adapter module is
2508 /// already minimized and this is a double-check that the minimization pass
2509 /// didn't accidentally break the wasm module.
2510 ///
2511 /// If `is_library` is true, we waive some of the constraints described above,
2512 /// allowing the module to import tables and globals, as well as import
2513 /// functions at the world level, not just at the interface level.
2514 pub fn validate_adapter_module(
2515 encoder: &ComponentEncoder,
2516 bytes: &[u8],
2517 required_by_import: &IndexMap<String, FuncType>,
2518 exports: &IndexSet<WorldKey>,
2519 library_info: Option<&LibraryInfo>,
2520 ) -> Result<ValidatedModule> {
2521 let ret = ValidatedModule::new(encoder, bytes, exports, None, library_info)?;
2522
2523 for (name, required_ty) in required_by_import {
2524 let actual = match ret.exports.raw_exports.get(name) {
2525 Some(ty) => ty,
2526 None => bail!("adapter module did not export `{name}`"),
2527 };
2528 validate_func_sig(name, required_ty, &actual)?;
2529 }
2530
2531 Ok(ret)
2532 }
2533
2534 fn resource_test_for_interface<'a>(
2535 resolve: &'a Resolve,
2536 id: InterfaceId,
2537 ) -> impl Fn(&str) -> Option<TypeId> + 'a {
2538 let interface = &resolve.interfaces[id];
2539 move |name: &str| {
2540 let ty = match interface.types.get(name) {
2541 Some(ty) => *ty,
2542 None => return None,
2543 };
2544 if matches!(resolve.types[ty].kind, TypeDefKind::Resource) {
2545 Some(ty)
2546 } else {
2547 None
2548 }
2549 }
2550 }
2551
2552 fn resource_test_for_world<'a>(
2553 resolve: &'a Resolve,
2554 id: WorldId,
2555 ) -> impl Fn(&str) -> Option<TypeId> + 'a {
2556 let world = &resolve.worlds[id];
2557 move |name: &str| match world.imports.get(&WorldKey::Name(name.to_string()))? {
2558 WorldItem::Type(r) => {
2559 if matches!(resolve.types[*r].kind, TypeDefKind::Resource) {
2560 Some(*r)
2561 } else {
2562 None
2563 }
2564 }
2565 _ => None,
2566 }
2567 }
2568
2569 fn validate_func(
2570 resolve: &Resolve,
2571 ty: &wasmparser::FuncType,
2572 func: &Function,
2573 abi: AbiVariant,
2574 ) -> Result<()> {
2575 validate_func_sig(
2576 &func.name,
2577 &wasm_sig_to_func_type(resolve.wasm_signature(abi, func)),
2578 ty,
2579 )
2580 }
2581
2582 fn validate_post_return(
2583 resolve: &Resolve,
2584 ty: &wasmparser::FuncType,
2585 func: &Function,
2586 ) -> Result<()> {
2587 // The expected signature of a post-return function is to take all the
2588 // parameters that are returned by the guest function and then return no
2589 // results. Model this by calculating the signature of `func` and then
2590 // moving its results into the parameters list while emptying out the
2591 // results.
2592 let mut sig = resolve.wasm_signature(AbiVariant::GuestExport, func);
2593 sig.params = mem::take(&mut sig.results);
2594 validate_func_sig(
2595 &format!("{} post-return", func.name),
2596 &wasm_sig_to_func_type(sig),
2597 ty,
2598 )
2599 }
2600
2601 fn validate_func_sig(name: &str, expected: &FuncType, ty: &wasmparser::FuncType) -> Result<()> {
2602 if ty != expected {
2603 bail!(
2604 "type mismatch for function `{}`: expected `{:?} -> {:?}` but found `{:?} -> {:?}`",
2605 name,
2606 expected.params(),
2607 expected.results(),
2608 ty.params(),
2609 ty.results()
2610 );
2611 }
2612
2613 Ok(())
2614 }
2615
2616 /// Matches `name` as `[${prefix}N]...`, and if found returns `(N, "...")`
2617 fn prefixed_integer<'a>(name: &'a str, prefix: &str) -> Option<(u32, &'a str)> {
2618 assert!(prefix.starts_with("["));
2619 assert!(prefix.ends_with("-"));
2620 let suffix = name.strip_prefix(prefix)?;
2621 let index = suffix.find(']')?;
2622 let rest = &suffix[index + 1..];
2623 let n = suffix[..index].parse().ok()?;
2624 Some((n, rest))
2625 }
2626
2627 fn get_function<'a>(
2628 resolve: &'a Resolve,
2629 world: &'a World,
2630 name: &str,
2631 interface: Option<InterfaceId>,
2632 imported: bool,
2633 ) -> Result<&'a Function> {
2634 let function = if let Some(id) = interface {
2635 return resolve.interfaces[id]
2636 .functions
2637 .get(name)
2638 .ok_or_else(|| anyhow!("no export `{name}` found"));
2639 } else if imported {
2640 world.imports.get(&WorldKey::Name(name.to_string()))
2641 } else {
2642 world.exports.get(&WorldKey::Name(name.to_string()))
2643 };
2644 let Some(WorldItem::Function(function)) = function else {
2645 bail!("no export `{name}` found");
2646 };
2647 Ok(function)
2648 }