1 | use crate::encoding::{Instance, Item, LibraryInfo, MainOrAdapter}; |
2 | use crate::{ComponentEncoder, StringEncoding}; |
3 | use anyhow::{bail, Context, Result}; |
4 | use indexmap::{map::Entry, IndexMap, IndexSet}; |
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 | types::TypesRef, Encoding, ExternalKind, FuncType, Parser, Payload, TypeRef, ValType, |
11 | ValidPayload, Validator, |
12 | }; |
13 | use wit_parser::{ |
14 | abi::{AbiVariant, WasmSignature, WasmType}, |
15 | Function, InterfaceId, PackageName, Resolve, TypeDefKind, TypeId, World, WorldId, WorldItem, |
16 | WorldKey, |
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 | params:signature.params.iter().map(from_wasm_type), |
34 | results: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 | info: Option<&LibraryInfo>, |
60 | ) -> Result<ValidatedModule> { |
61 | let mut validator = Validator::new(); |
62 | let mut ret = ValidatedModule::default(); |
63 | |
64 | for payload in Parser::new(0).parse_all(bytes) { |
65 | let payload = payload?; |
66 | if let ValidPayload::End(_) = validator.payload(&payload)? { |
67 | break; |
68 | } |
69 | |
70 | let types = validator.types(0).unwrap(); |
71 | |
72 | match payload { |
73 | Payload::Version { encoding, .. } if encoding != Encoding::Module => { |
74 | bail!("data is not a WebAssembly module" ); |
75 | } |
76 | Payload::ImportSection(s) => { |
77 | for import in s { |
78 | let import = import?; |
79 | ret.imports.add(import, encoder, info, types)?; |
80 | } |
81 | } |
82 | Payload::ExportSection(s) => { |
83 | for export in s { |
84 | let export = export?; |
85 | ret.exports.add(export, encoder, &exports, types)?; |
86 | } |
87 | } |
88 | _ => continue, |
89 | } |
90 | } |
91 | |
92 | ret.exports.validate(encoder, exports)?; |
93 | |
94 | Ok(ret) |
95 | } |
96 | } |
97 | |
98 | /// Metadata information about a module's imports. |
99 | /// |
100 | /// This structure maintains the connection between component model "things" and |
101 | /// core wasm "things" by ensuring that all imports to the core wasm module are |
102 | /// classified by the `Import` enumeration. |
103 | #[derive (Default)] |
104 | pub struct ImportMap { |
105 | /// The first level of the map here is the module namespace of the import |
106 | /// and the second level of the map is the field namespace. The item is then |
107 | /// how the import is satisfied. |
108 | names: IndexMap<String, ImportInstance>, |
109 | } |
110 | |
111 | pub enum ImportInstance { |
112 | /// This import is satisfied by an entire instance of another |
113 | /// adapter/module. |
114 | Whole(MainOrAdapter), |
115 | |
116 | /// This import is satisfied by filling out each name possibly differently. |
117 | Names(IndexMap<String, Import>), |
118 | } |
119 | |
120 | /// Represents metadata about a `stream<T>` or `future<T>` type for a specific |
121 | /// payload type `T`. |
122 | /// |
123 | /// Currently, the name mangling scheme we use to represent `stream` and |
124 | /// `future` intrinsics as core module function imports refers to a specific |
125 | /// `stream` or `future` type by naming an imported or exported component |
126 | /// function which has that type as a parameter or return type (where the |
127 | /// specific type is refered to using an ordinal numbering scheme). Not only |
128 | /// does this approach unambiguously indicate the type of interest, but it |
129 | /// allows us to reuse the `realloc`, string encoding, memory, etc. used by that |
130 | /// function when emitting intrinsic declarations. |
131 | /// |
132 | /// TODO: Rather than reusing the same canon opts as the function in which the |
133 | /// type appears, consider encoding them in the name mangling stream on an |
134 | /// individual basis, similar to how we encode `error-context.*` built-in |
135 | /// imports. |
136 | #[derive (Debug, Eq, PartialEq, Clone)] |
137 | pub struct PayloadInfo { |
138 | /// The original, mangled import name used to import this built-in |
139 | /// (currently used only for hashing and debugging). |
140 | pub name: String, |
141 | /// The resolved type id for the `stream` or `future` type of interest. |
142 | pub ty: TypeId, |
143 | /// The component-level function import or export where the type appeared as |
144 | /// a parameter or result type. |
145 | pub function: Function, |
146 | /// The world key representing the import or export context of `function`. |
147 | pub key: WorldKey, |
148 | /// The interface that `function` was imported from or exported in, if any. |
149 | pub interface: Option<InterfaceId>, |
150 | /// Whether `function` is being imported or exported. |
151 | /// |
152 | /// This may affect how we emit the declaration of the built-in, e.g. if the |
153 | /// payload type is an exported resource. |
154 | pub imported: bool, |
155 | } |
156 | |
157 | impl Hash for PayloadInfo { |
158 | /// We derive `Hash` for this type by hand and exclude the `function` field |
159 | /// because (A) `Function` doesn't implement `Hash` and (B) the other fields |
160 | /// are sufficient to uniquely identify the type of interest, which function |
161 | /// it appeared in, and which parameter or return type we found it in. |
162 | fn hash<H: Hasher>(&self, state: &mut H) { |
163 | self.name.hash(state); |
164 | self.ty.hash(state); |
165 | self.key.hash(state); |
166 | self.interface.hash(state); |
167 | self.imported.hash(state); |
168 | } |
169 | } |
170 | |
171 | /// The different kinds of items that a module or an adapter can import. |
172 | /// |
173 | /// This is intended to be an exhaustive definition of what can be imported into |
174 | /// core modules within a component that wit-component supports. |
175 | #[derive (Debug, Clone)] |
176 | pub enum Import { |
177 | /// A top-level world function, with the name provided here, is imported |
178 | /// into the module. |
179 | WorldFunc(WorldKey, String, AbiVariant), |
180 | |
181 | /// An interface's function is imported into the module. |
182 | /// |
183 | /// The `WorldKey` here is the name of the interface in the world in |
184 | /// question. The `InterfaceId` is the interface that was imported from and |
185 | /// `String` is the WIT name of the function. |
186 | InterfaceFunc(WorldKey, InterfaceId, String, AbiVariant), |
187 | |
188 | /// An imported resource's destructor is imported. |
189 | /// |
190 | /// The key provided indicates whether it's for the top-level types of the |
191 | /// world (`None`) or an interface (`Some` with the name of the interface). |
192 | /// The `TypeId` is what resource is being dropped. |
193 | ImportedResourceDrop(WorldKey, Option<InterfaceId>, TypeId), |
194 | |
195 | /// A `canon resource.drop` intrinsic for an exported item is being |
196 | /// imported. |
197 | /// |
198 | /// This lists the key of the interface that's exporting the resource plus |
199 | /// the id within that interface. |
200 | ExportedResourceDrop(WorldKey, TypeId), |
201 | |
202 | /// A `canon resource.new` intrinsic for an exported item is being |
203 | /// imported. |
204 | /// |
205 | /// This lists the key of the interface that's exporting the resource plus |
206 | /// the id within that interface. |
207 | ExportedResourceNew(WorldKey, TypeId), |
208 | |
209 | /// A `canon resource.rep` intrinsic for an exported item is being |
210 | /// imported. |
211 | /// |
212 | /// This lists the key of the interface that's exporting the resource plus |
213 | /// the id within that interface. |
214 | ExportedResourceRep(WorldKey, TypeId), |
215 | |
216 | /// An export of an adapter is being imported with the specified type. |
217 | /// |
218 | /// This is used for when the main module imports an adapter function. The |
219 | /// adapter name and function name match the module's own import, and the |
220 | /// type must match that listed here. |
221 | AdapterExport(FuncType), |
222 | |
223 | /// An adapter is importing the memory of the main module. |
224 | /// |
225 | /// (should be combined with `MainModuleExport` below one day) |
226 | MainModuleMemory, |
227 | |
228 | /// An adapter is importing an arbitrary item from the main module. |
229 | MainModuleExport { name: String, kind: ExportKind }, |
230 | |
231 | /// An arbitrary item from either the main module or an adapter is being |
232 | /// imported. |
233 | /// |
234 | /// (should probably subsume `MainModule*` and maybe `AdapterExport` above |
235 | /// one day. |
236 | Item(Item), |
237 | |
238 | /// A `canon task.return` intrinsic for an exported function. |
239 | /// |
240 | /// This allows an exported function to return a value and then continue |
241 | /// running. |
242 | /// |
243 | /// As of this writing, only async-lifted exports use `task.return`, but the |
244 | /// plan is to also support it for sync-lifted exports in the future as |
245 | /// well. |
246 | ExportedTaskReturn(Function), |
247 | |
248 | /// A `canon task.backpressure` intrinsic. |
249 | /// |
250 | /// This allows the guest to dynamically indicate whether it's ready for |
251 | /// additional concurrent calls. |
252 | TaskBackpressure, |
253 | |
254 | /// A `canon task.wait` intrinsic. |
255 | /// |
256 | /// This allows the guest to wait for any pending calls to async-lowered |
257 | /// imports and/or `stream` and `future` operations to complete without |
258 | /// unwinding the current Wasm stack. |
259 | TaskWait { async_: bool }, |
260 | |
261 | /// A `canon task.poll` intrinsic. |
262 | /// |
263 | /// This allows the guest to check whether any pending calls to |
264 | /// async-lowered imports and/or `stream` and `future` operations have |
265 | /// completed without unwinding the current Wasm stack and without blocking. |
266 | TaskPoll { async_: bool }, |
267 | |
268 | /// A `canon task.wait` intrinsic. |
269 | /// |
270 | /// This allows the guest to yield (e.g. during an computationally-intensive |
271 | /// operation) and allow other subtasks to make progress. |
272 | TaskYield { async_: bool }, |
273 | |
274 | /// A `canon subtask.drop` intrinsic. |
275 | /// |
276 | /// This allows the guest to release its handle to an completed subtask. |
277 | SubtaskDrop, |
278 | |
279 | /// A `canon stream.new` intrinsic. |
280 | /// |
281 | /// This allows the guest to create a new `stream` of the specified type. |
282 | StreamNew(PayloadInfo), |
283 | |
284 | /// A `canon stream.read` intrinsic. |
285 | /// |
286 | /// This allows the guest to read the next values (if any) from the specifed |
287 | /// stream. |
288 | StreamRead { async_: bool, info: PayloadInfo }, |
289 | |
290 | /// A `canon stream.write` intrinsic. |
291 | /// |
292 | /// This allows the guest to write one or more values to the specifed |
293 | /// stream. |
294 | StreamWrite { async_: bool, info: PayloadInfo }, |
295 | |
296 | /// A `canon stream.cancel-read` intrinsic. |
297 | /// |
298 | /// This allows the guest to cancel a pending read it initiated earlier (but |
299 | /// which may have already partially or entirely completed). |
300 | StreamCancelRead { |
301 | ty: TypeId, |
302 | imported: bool, |
303 | async_: bool, |
304 | }, |
305 | |
306 | /// A `canon stream.cancel-write` intrinsic. |
307 | /// |
308 | /// This allows the guest to cancel a pending write it initiated earlier |
309 | /// (but which may have already partially or entirely completed). |
310 | StreamCancelWrite { |
311 | ty: TypeId, |
312 | imported: bool, |
313 | async_: bool, |
314 | }, |
315 | |
316 | /// A `canon stream.close-readable` intrinsic. |
317 | /// |
318 | /// This allows the guest to close the readable end of a `stream`. |
319 | StreamCloseReadable { ty: TypeId, imported: bool }, |
320 | |
321 | /// A `canon stream.close-writable` intrinsic. |
322 | /// |
323 | /// This allows the guest to close the writable end of a `stream`. |
324 | StreamCloseWritable { ty: TypeId, imported: bool }, |
325 | |
326 | /// A `canon future.new` intrinsic. |
327 | /// |
328 | /// This allows the guest to create a new `future` of the specified type. |
329 | FutureNew(PayloadInfo), |
330 | |
331 | /// A `canon future.read` intrinsic. |
332 | /// |
333 | /// This allows the guest to read the value (if any) from the specifed |
334 | /// future. |
335 | FutureRead { async_: bool, info: PayloadInfo }, |
336 | |
337 | /// A `canon future.write` intrinsic. |
338 | /// |
339 | /// This allows the guest to write a value to the specifed future. |
340 | FutureWrite { async_: bool, info: PayloadInfo }, |
341 | |
342 | /// A `canon future.cancel-read` intrinsic. |
343 | /// |
344 | /// This allows the guest to cancel a pending read it initiated earlier (but |
345 | /// which may have already completed). |
346 | FutureCancelRead { |
347 | ty: TypeId, |
348 | imported: bool, |
349 | async_: bool, |
350 | }, |
351 | |
352 | /// A `canon future.cancel-write` intrinsic. |
353 | /// |
354 | /// This allows the guest to cancel a pending write it initiated earlier |
355 | /// (but which may have already completed). |
356 | FutureCancelWrite { |
357 | ty: TypeId, |
358 | imported: bool, |
359 | async_: bool, |
360 | }, |
361 | |
362 | /// A `canon future.close-readable` intrinsic. |
363 | /// |
364 | /// This allows the guest to close the readable end of a `future`. |
365 | FutureCloseReadable { ty: TypeId, imported: bool }, |
366 | |
367 | /// A `canon future.close-writable` intrinsic. |
368 | /// |
369 | /// This allows the guest to close the writable end of a `future`. |
370 | FutureCloseWritable { ty: TypeId, imported: bool }, |
371 | |
372 | /// A `canon error-context.new` intrinsic. |
373 | /// |
374 | /// This allows the guest to create a new `error-context` instance with a |
375 | /// specified debug message. |
376 | ErrorContextNew { encoding: StringEncoding }, |
377 | |
378 | /// A `canon error-context.debug-message` intrinsic. |
379 | /// |
380 | /// This allows the guest to retrieve the debug message from a |
381 | /// `error-context` instance. Note that the content of this message might |
382 | /// not be identical to what was passed in to `error-context.new`. |
383 | ErrorContextDebugMessage { |
384 | encoding: StringEncoding, |
385 | realloc: String, |
386 | }, |
387 | |
388 | /// A `canon error-context.drop` intrinsic. |
389 | /// |
390 | /// This allows the guest to release its handle to the specified |
391 | /// `error-context` instance. |
392 | ErrorContextDrop, |
393 | } |
394 | |
395 | impl ImportMap { |
396 | /// Returns whether the top-level world function `func` is imported. |
397 | pub fn uses_toplevel_func(&self, func: &str) -> bool { |
398 | self.imports().any(|(_, _, item)| match item { |
399 | Import::WorldFunc(_, name, _) => func == name, |
400 | _ => false, |
401 | }) |
402 | } |
403 | |
404 | /// Returns whether the interface function specified is imported. |
405 | pub fn uses_interface_func(&self, interface: InterfaceId, func: &str) -> bool { |
406 | self.imports().any(|(_, _, import)| match import { |
407 | Import::InterfaceFunc(_, id, name, _) => *id == interface && name == func, |
408 | _ => false, |
409 | }) |
410 | } |
411 | |
412 | /// Returns whether the specified resource's drop method is needed to import. |
413 | pub fn uses_imported_resource_drop(&self, resource: TypeId) -> bool { |
414 | self.imports().any(|(_, _, import)| match import { |
415 | Import::ImportedResourceDrop(_, _, id) => resource == *id, |
416 | _ => false, |
417 | }) |
418 | } |
419 | |
420 | /// Returns the list of items that the adapter named `name` must export. |
421 | pub fn required_from_adapter(&self, name: &str) -> IndexMap<String, FuncType> { |
422 | let names = match self.names.get(name) { |
423 | Some(ImportInstance::Names(names)) => names, |
424 | _ => return IndexMap::new(), |
425 | }; |
426 | names |
427 | .iter() |
428 | .map(|(name, import)| { |
429 | ( |
430 | name.clone(), |
431 | match import { |
432 | Import::AdapterExport(ty) => ty.clone(), |
433 | _ => unreachable!(), |
434 | }, |
435 | ) |
436 | }) |
437 | .collect() |
438 | } |
439 | |
440 | /// Returns an iterator over all individual imports registered in this map. |
441 | /// |
442 | /// Note that this doesn't iterate over the "whole instance" imports. |
443 | pub fn imports(&self) -> impl Iterator<Item = (&str, &str, &Import)> + '_ { |
444 | self.names |
445 | .iter() |
446 | .filter_map(|(module, m)| match m { |
447 | ImportInstance::Names(names) => Some((module, names)), |
448 | ImportInstance::Whole(_) => None, |
449 | }) |
450 | .flat_map(|(module, m)| { |
451 | m.iter() |
452 | .map(move |(field, import)| (module.as_str(), field.as_str(), import)) |
453 | }) |
454 | } |
455 | |
456 | /// Returns the map for how all imports must be satisfied. |
457 | pub fn modules(&self) -> &IndexMap<String, ImportInstance> { |
458 | &self.names |
459 | } |
460 | |
461 | /// Helper function used during validation to build up this `ImportMap`. |
462 | fn add( |
463 | &mut self, |
464 | import: wasmparser::Import<'_>, |
465 | encoder: &ComponentEncoder, |
466 | library_info: Option<&LibraryInfo>, |
467 | types: TypesRef<'_>, |
468 | ) -> Result<()> { |
469 | if self.classify_import_with_library(import, library_info)? { |
470 | return Ok(()); |
471 | } |
472 | let item = self.classify(import, encoder, types).with_context(|| { |
473 | format!( |
474 | "failed to resolve import ` {}:: {}`" , |
475 | import.module, import.name, |
476 | ) |
477 | })?; |
478 | self.insert_import(import, item) |
479 | } |
480 | |
481 | fn classify( |
482 | &self, |
483 | import: wasmparser::Import<'_>, |
484 | encoder: &ComponentEncoder, |
485 | types: TypesRef<'_>, |
486 | ) -> Result<Import> { |
487 | // Special-case the main module's memory imported into adapters which |
488 | // currently with `wasm-ld` is not easily configurable. |
489 | if import.module == "env" && import.name == "memory" { |
490 | return Ok(Import::MainModuleMemory); |
491 | } |
492 | |
493 | // Special-case imports from the main module into adapters. |
494 | if import.module == "__main_module__" { |
495 | return Ok(Import::MainModuleExport { |
496 | name: import.name.to_string(), |
497 | kind: match import.ty { |
498 | TypeRef::Func(_) => ExportKind::Func, |
499 | TypeRef::Table(_) => ExportKind::Table, |
500 | TypeRef::Memory(_) => ExportKind::Memory, |
501 | TypeRef::Global(_) => ExportKind::Global, |
502 | TypeRef::Tag(_) => ExportKind::Tag, |
503 | }, |
504 | }); |
505 | } |
506 | |
507 | let ty_index = match import.ty { |
508 | TypeRef::Func(ty) => ty, |
509 | _ => bail!("module is only allowed to import functions" ), |
510 | }; |
511 | let ty = types[types.core_type_at_in_module(ty_index)].unwrap_func(); |
512 | |
513 | // Handle main module imports that match known adapters and set it up as |
514 | // an import of an adapter export. |
515 | if encoder.adapters.contains_key(import.module) { |
516 | return Ok(Import::AdapterExport(ty.clone())); |
517 | } |
518 | |
519 | let (module, names) = match import.module.strip_prefix("cm32p2" ) { |
520 | Some(suffix) => (suffix, STANDARD), |
521 | None if encoder.reject_legacy_names => (import.module, STANDARD), |
522 | None => (import.module, LEGACY), |
523 | }; |
524 | self.classify_component_model_import(module, import.name, encoder, ty, names) |
525 | } |
526 | |
527 | /// Attempts to classify the import `{module}::{name}` with the rules |
528 | /// specified in WebAssembly/component-model#378 |
529 | fn classify_component_model_import( |
530 | &self, |
531 | module: &str, |
532 | name: &str, |
533 | encoder: &ComponentEncoder, |
534 | ty: &FuncType, |
535 | names: &dyn NameMangling, |
536 | ) -> Result<Import> { |
537 | let resolve = &encoder.metadata.resolve; |
538 | let world_id = encoder.metadata.world; |
539 | let world = &resolve.worlds[world_id]; |
540 | |
541 | if let Some(import) = names.payload_import(module, name, resolve, world, ty)? { |
542 | return Ok(import); |
543 | } |
544 | |
545 | let async_import_for_export = |interface: Option<(WorldKey, InterfaceId)>| { |
546 | Ok::<_, anyhow::Error>(if let Some(function_name) = names.task_return_name(name) { |
547 | let interface_id = interface.as_ref().map(|(_, id)| *id); |
548 | let func = get_function(resolve, world, function_name, interface_id, false)?; |
549 | // Note that we can't statically validate the type signature of |
550 | // a `task.return` built-in since we can't know which export |
551 | // it's associated with in general. Instead, the host will |
552 | // compare it with the expected type at runtime and trap if |
553 | // necessary. |
554 | Some(Import::ExportedTaskReturn(func)) |
555 | } else { |
556 | None |
557 | }) |
558 | }; |
559 | |
560 | let (abi, name) = if let Some(name) = names.async_name(name) { |
561 | (AbiVariant::GuestImportAsync, name) |
562 | } else { |
563 | (AbiVariant::GuestImport, name) |
564 | }; |
565 | |
566 | if module == names.import_root() { |
567 | if Some(name) == names.error_context_drop() { |
568 | let expected = FuncType::new([ValType::I32], []); |
569 | validate_func_sig(name, &expected, ty)?; |
570 | return Ok(Import::ErrorContextDrop); |
571 | } |
572 | |
573 | if Some(name) == names.task_backpressure() { |
574 | let expected = FuncType::new([ValType::I32], []); |
575 | validate_func_sig(name, &expected, ty)?; |
576 | return Ok(Import::TaskBackpressure); |
577 | } |
578 | |
579 | if Some(name) == names.task_wait() { |
580 | let expected = FuncType::new([ValType::I32], [ValType::I32]); |
581 | validate_func_sig(name, &expected, ty)?; |
582 | return Ok(Import::TaskWait { |
583 | async_: abi == AbiVariant::GuestImportAsync, |
584 | }); |
585 | } |
586 | |
587 | if Some(name) == names.task_poll() { |
588 | let expected = FuncType::new([ValType::I32], [ValType::I32]); |
589 | validate_func_sig(name, &expected, ty)?; |
590 | return Ok(Import::TaskPoll { |
591 | async_: abi == AbiVariant::GuestImportAsync, |
592 | }); |
593 | } |
594 | |
595 | if Some(name) == names.task_yield() { |
596 | let expected = FuncType::new([], []); |
597 | validate_func_sig(name, &expected, ty)?; |
598 | return Ok(Import::TaskYield { |
599 | async_: abi == AbiVariant::GuestImportAsync, |
600 | }); |
601 | } |
602 | |
603 | if Some(name) == names.subtask_drop() { |
604 | let expected = FuncType::new([ValType::I32], []); |
605 | validate_func_sig(name, &expected, ty)?; |
606 | return Ok(Import::SubtaskDrop); |
607 | } |
608 | |
609 | if let Some(encoding) = names.error_context_new(name) { |
610 | let expected = FuncType::new([ValType::I32; 2], [ValType::I32]); |
611 | validate_func_sig(name, &expected, ty)?; |
612 | return Ok(Import::ErrorContextNew { encoding }); |
613 | } |
614 | |
615 | if let Some((encoding, realloc)) = names.error_context_debug_message(name) { |
616 | let expected = FuncType::new([ValType::I32; 2], []); |
617 | validate_func_sig(name, &expected, ty)?; |
618 | return Ok(Import::ErrorContextDebugMessage { |
619 | encoding, |
620 | realloc: realloc.to_owned(), |
621 | }); |
622 | } |
623 | |
624 | if let Some(import) = async_import_for_export(None)? { |
625 | return Ok(import); |
626 | } |
627 | |
628 | let key = WorldKey::Name(name.to_string()); |
629 | if let Some(WorldItem::Function(func)) = world.imports.get(&key) { |
630 | validate_func(resolve, ty, func, abi)?; |
631 | return Ok(Import::WorldFunc(key, func.name.clone(), abi)); |
632 | } |
633 | |
634 | let get_resource = resource_test_for_world(resolve, world_id); |
635 | if let Some(resource) = names.resource_drop_name(name) { |
636 | if let Some(id) = get_resource(resource) { |
637 | let expected = FuncType::new([ValType::I32], []); |
638 | validate_func_sig(name, &expected, ty)?; |
639 | return Ok(Import::ImportedResourceDrop(key, None, id)); |
640 | } |
641 | } |
642 | |
643 | match world.imports.get(&key) { |
644 | Some(_) => bail!("expected world top-level import ` {name}` to be a function" ), |
645 | None => bail!("no top-level imported function ` {name}` specified" ), |
646 | } |
647 | } |
648 | |
649 | let interface = match module.strip_prefix(names.import_non_root_prefix()) { |
650 | Some(name) => name, |
651 | None => bail!("unknown or invalid component model import syntax" ), |
652 | }; |
653 | |
654 | if let Some(interface) = interface.strip_prefix(names.import_exported_intrinsic_prefix()) { |
655 | if let Some(import) = async_import_for_export(Some(names.module_to_interface( |
656 | interface, |
657 | resolve, |
658 | &world.exports, |
659 | )?))? { |
660 | return Ok(import); |
661 | } |
662 | |
663 | let (key, id) = names.module_to_interface(interface, resolve, &world.exports)?; |
664 | |
665 | let get_resource = resource_test_for_interface(resolve, id); |
666 | if let Some(name) = names.resource_drop_name(name) { |
667 | if let Some(id) = get_resource(name) { |
668 | let expected = FuncType::new([ValType::I32], []); |
669 | validate_func_sig(name, &expected, ty)?; |
670 | return Ok(Import::ExportedResourceDrop(key, id)); |
671 | } |
672 | } |
673 | if let Some(name) = names.resource_new_name(name) { |
674 | if let Some(id) = get_resource(name) { |
675 | let expected = FuncType::new([ValType::I32], [ValType::I32]); |
676 | validate_func_sig(name, &expected, ty)?; |
677 | return Ok(Import::ExportedResourceNew(key, id)); |
678 | } |
679 | } |
680 | if let Some(name) = names.resource_rep_name(name) { |
681 | if let Some(id) = get_resource(name) { |
682 | let expected = FuncType::new([ValType::I32], [ValType::I32]); |
683 | validate_func_sig(name, &expected, ty)?; |
684 | return Ok(Import::ExportedResourceRep(key, id)); |
685 | } |
686 | } |
687 | bail!("unknown function ` {name}`" ) |
688 | } |
689 | |
690 | let (key, id) = names.module_to_interface(interface, resolve, &world.imports)?; |
691 | let interface = &resolve.interfaces[id]; |
692 | let get_resource = resource_test_for_interface(resolve, id); |
693 | if let Some(f) = interface.functions.get(name) { |
694 | validate_func(resolve, ty, f, abi).with_context(|| { |
695 | let name = resolve.name_world_key(&key); |
696 | format!("failed to validate import interface ` {name}`" ) |
697 | })?; |
698 | return Ok(Import::InterfaceFunc(key, id, f.name.clone(), abi)); |
699 | } else if let Some(resource) = names.resource_drop_name(name) { |
700 | if let Some(resource) = get_resource(resource) { |
701 | let expected = FuncType::new([ValType::I32], []); |
702 | validate_func_sig(name, &expected, ty)?; |
703 | return Ok(Import::ImportedResourceDrop(key, Some(id), resource)); |
704 | } |
705 | } |
706 | bail!( |
707 | "import interface ` {module}` is missing function \ |
708 | ` {name}` that is required by the module" , |
709 | ) |
710 | } |
711 | |
712 | fn classify_import_with_library( |
713 | &mut self, |
714 | import: wasmparser::Import<'_>, |
715 | library_info: Option<&LibraryInfo>, |
716 | ) -> Result<bool> { |
717 | let info = match library_info { |
718 | Some(info) => info, |
719 | None => return Ok(false), |
720 | }; |
721 | let Some((_, instance)) = info |
722 | .arguments |
723 | .iter() |
724 | .find(|(name, _items)| *name == import.module) |
725 | else { |
726 | return Ok(false); |
727 | }; |
728 | match instance { |
729 | Instance::MainOrAdapter(module) => match self.names.get(import.module) { |
730 | Some(ImportInstance::Whole(which)) => { |
731 | if which != module { |
732 | bail!("different whole modules imported under the same name" ); |
733 | } |
734 | } |
735 | Some(ImportInstance::Names(_)) => { |
736 | bail!("cannot mix individual imports and whole module imports" ) |
737 | } |
738 | None => { |
739 | let instance = ImportInstance::Whole(module.clone()); |
740 | self.names.insert(import.module.to_string(), instance); |
741 | } |
742 | }, |
743 | Instance::Items(items) => { |
744 | let Some(item) = items.iter().find(|i| i.alias == import.name) else { |
745 | return Ok(false); |
746 | }; |
747 | self.insert_import(import, Import::Item(item.clone()))?; |
748 | } |
749 | } |
750 | Ok(true) |
751 | } |
752 | |
753 | fn insert_import(&mut self, import: wasmparser::Import<'_>, item: Import) -> Result<()> { |
754 | let entry = self |
755 | .names |
756 | .entry(import.module.to_string()) |
757 | .or_insert(ImportInstance::Names(IndexMap::default())); |
758 | let names = match entry { |
759 | ImportInstance::Names(names) => names, |
760 | _ => bail!("cannot mix individual imports with module imports" ), |
761 | }; |
762 | let entry = match names.entry(import.name.to_string()) { |
763 | Entry::Occupied(_) => { |
764 | bail!( |
765 | "module has duplicate import for ` {}:: {}`" , |
766 | import.module, |
767 | import.name |
768 | ); |
769 | } |
770 | Entry::Vacant(v) => v, |
771 | }; |
772 | log::trace!( |
773 | "classifying import ` {}:: {} as {item:?}" , |
774 | import.module, |
775 | import.name |
776 | ); |
777 | entry.insert(item); |
778 | Ok(()) |
779 | } |
780 | } |
781 | |
782 | /// Dual of `ImportMap` except describes the exports of a module instead of the |
783 | /// imports. |
784 | #[derive (Default)] |
785 | pub struct ExportMap { |
786 | names: IndexMap<String, Export>, |
787 | raw_exports: IndexMap<String, FuncType>, |
788 | } |
789 | |
790 | /// All possible (known) exports from a core wasm module that are recognized and |
791 | /// handled during the componentization process. |
792 | #[derive (Debug)] |
793 | pub enum Export { |
794 | /// An export of a top-level function of a world, where the world function |
795 | /// is named here. |
796 | WorldFunc(WorldKey, String, AbiVariant), |
797 | |
798 | /// A post-return for a top-level function of a world. |
799 | WorldFuncPostReturn(WorldKey), |
800 | |
801 | /// An export of a function in an interface. |
802 | InterfaceFunc(WorldKey, InterfaceId, String, AbiVariant), |
803 | |
804 | /// A post-return for the above function. |
805 | InterfaceFuncPostReturn(WorldKey, String), |
806 | |
807 | /// A destructor for an exported resource. |
808 | ResourceDtor(TypeId), |
809 | |
810 | /// Memory, typically for an adapter. |
811 | Memory, |
812 | |
813 | /// `cabi_realloc` |
814 | GeneralPurposeRealloc, |
815 | |
816 | /// `cabi_export_realloc` |
817 | GeneralPurposeExportRealloc, |
818 | |
819 | /// `cabi_import_realloc` |
820 | GeneralPurposeImportRealloc, |
821 | |
822 | /// `_initialize` |
823 | Initialize, |
824 | |
825 | /// `cabi_realloc_adapter` |
826 | ReallocForAdapter, |
827 | |
828 | WorldFuncCallback(WorldKey), |
829 | |
830 | InterfaceFuncCallback(WorldKey, String), |
831 | } |
832 | |
833 | impl ExportMap { |
834 | fn add( |
835 | &mut self, |
836 | export: wasmparser::Export<'_>, |
837 | encoder: &ComponentEncoder, |
838 | exports: &IndexSet<WorldKey>, |
839 | types: TypesRef<'_>, |
840 | ) -> Result<()> { |
841 | if let Some(item) = self.classify(export, encoder, exports, types)? { |
842 | log::debug!("classifying export ` {}` as {item:?}" , export.name); |
843 | let prev = self.names.insert(export.name.to_string(), item); |
844 | assert!(prev.is_none()); |
845 | } |
846 | Ok(()) |
847 | } |
848 | |
849 | fn classify( |
850 | &mut self, |
851 | export: wasmparser::Export<'_>, |
852 | encoder: &ComponentEncoder, |
853 | exports: &IndexSet<WorldKey>, |
854 | types: TypesRef<'_>, |
855 | ) -> Result<Option<Export>> { |
856 | match export.kind { |
857 | ExternalKind::Func => { |
858 | let ty = types[types.core_function_at(export.index)].unwrap_func(); |
859 | self.raw_exports.insert(export.name.to_string(), ty.clone()); |
860 | } |
861 | _ => {} |
862 | } |
863 | |
864 | // Handle a few special-cased names first. |
865 | if export.name == "canonical_abi_realloc" { |
866 | return Ok(Some(Export::GeneralPurposeRealloc)); |
867 | } else if export.name == "cabi_import_realloc" { |
868 | return Ok(Some(Export::GeneralPurposeImportRealloc)); |
869 | } else if export.name == "cabi_export_realloc" { |
870 | return Ok(Some(Export::GeneralPurposeExportRealloc)); |
871 | } else if export.name == "cabi_realloc_adapter" { |
872 | return Ok(Some(Export::ReallocForAdapter)); |
873 | } |
874 | |
875 | let (name, names) = match export.name.strip_prefix("cm32p2" ) { |
876 | Some(name) => (name, STANDARD), |
877 | None if encoder.reject_legacy_names => return Ok(None), |
878 | None => (export.name, LEGACY), |
879 | }; |
880 | |
881 | if let Some(export) = self |
882 | .classify_component_export(names, name, &export, encoder, exports, types) |
883 | .with_context(|| format!("failed to classify export ` {}`" , export.name))? |
884 | { |
885 | return Ok(Some(export)); |
886 | } |
887 | log::debug!("unknown export ` {}`" , export.name); |
888 | Ok(None) |
889 | } |
890 | |
891 | fn classify_component_export( |
892 | &mut self, |
893 | names: &dyn NameMangling, |
894 | name: &str, |
895 | export: &wasmparser::Export<'_>, |
896 | encoder: &ComponentEncoder, |
897 | exports: &IndexSet<WorldKey>, |
898 | types: TypesRef<'_>, |
899 | ) -> Result<Option<Export>> { |
900 | let resolve = &encoder.metadata.resolve; |
901 | let world = encoder.metadata.world; |
902 | match export.kind { |
903 | ExternalKind::Func => {} |
904 | ExternalKind::Memory => { |
905 | if name == names.export_memory() { |
906 | return Ok(Some(Export::Memory)); |
907 | } |
908 | return Ok(None); |
909 | } |
910 | _ => return Ok(None), |
911 | } |
912 | let ty = types[types.core_function_at(export.index)].unwrap_func(); |
913 | |
914 | // Handle a few special-cased names first. |
915 | if name == names.export_realloc() { |
916 | let expected = FuncType::new([ValType::I32; 4], [ValType::I32]); |
917 | validate_func_sig(name, &expected, ty)?; |
918 | return Ok(Some(Export::GeneralPurposeRealloc)); |
919 | } else if name == names.export_initialize() { |
920 | let expected = FuncType::new([], []); |
921 | validate_func_sig(name, &expected, ty)?; |
922 | return Ok(Some(Export::Initialize)); |
923 | } |
924 | |
925 | let full_name = name; |
926 | let (abi, name) = if let Some(name) = names.async_name(name) { |
927 | (AbiVariant::GuestExportAsync, name) |
928 | } else if let Some(name) = names.async_stackful_name(name) { |
929 | (AbiVariant::GuestExportAsyncStackful, name) |
930 | } else { |
931 | (AbiVariant::GuestExport, name) |
932 | }; |
933 | |
934 | // Try to match this to a known WIT export that `exports` allows. |
935 | if let Some((key, id, f)) = names.match_wit_export(name, resolve, world, exports) { |
936 | validate_func(resolve, ty, f, abi).with_context(|| { |
937 | let key = resolve.name_world_key(key); |
938 | format!("failed to validate export for ` {key}`" ) |
939 | })?; |
940 | match id { |
941 | Some(id) => { |
942 | return Ok(Some(Export::InterfaceFunc( |
943 | key.clone(), |
944 | id, |
945 | f.name.clone(), |
946 | abi, |
947 | ))); |
948 | } |
949 | None => { |
950 | return Ok(Some(Export::WorldFunc(key.clone(), f.name.clone(), abi))); |
951 | } |
952 | } |
953 | } |
954 | |
955 | // See if this is a post-return for any known WIT export. |
956 | if let Some(remaining) = names.strip_post_return(name) { |
957 | if let Some((key, id, f)) = names.match_wit_export(remaining, resolve, world, exports) { |
958 | validate_post_return(resolve, ty, f).with_context(|| { |
959 | let key = resolve.name_world_key(key); |
960 | format!("failed to validate export for ` {key}`" ) |
961 | })?; |
962 | match id { |
963 | Some(_id) => { |
964 | return Ok(Some(Export::InterfaceFuncPostReturn( |
965 | key.clone(), |
966 | f.name.clone(), |
967 | ))); |
968 | } |
969 | None => { |
970 | return Ok(Some(Export::WorldFuncPostReturn(key.clone()))); |
971 | } |
972 | } |
973 | } |
974 | } |
975 | |
976 | if let Some(suffix) = names.callback_name(full_name) { |
977 | if let Some((key, id, f)) = names.match_wit_export(suffix, resolve, world, exports) { |
978 | validate_func_sig( |
979 | full_name, |
980 | &FuncType::new([ValType::I32; 4], [ValType::I32]), |
981 | ty, |
982 | )?; |
983 | return Ok(Some(if id.is_some() { |
984 | Export::InterfaceFuncCallback(key.clone(), f.name.clone()) |
985 | } else { |
986 | Export::WorldFuncCallback(key.clone()) |
987 | })); |
988 | } |
989 | } |
990 | |
991 | // And, finally, see if it matches a known destructor. |
992 | if let Some(dtor) = names.match_wit_resource_dtor(name, resolve, world, exports) { |
993 | let expected = FuncType::new([ValType::I32], []); |
994 | validate_func_sig(full_name, &expected, ty)?; |
995 | return Ok(Some(Export::ResourceDtor(dtor))); |
996 | } |
997 | |
998 | Ok(None) |
999 | } |
1000 | |
1001 | /// Returns the name of the post-return export, if any, for the `key` and |
1002 | /// `func` combo. |
1003 | pub fn post_return(&self, key: &WorldKey, func: &Function) -> Option<&str> { |
1004 | self.find(|m| match m { |
1005 | Export::WorldFuncPostReturn(k) => k == key, |
1006 | Export::InterfaceFuncPostReturn(k, f) => k == key && func.name == *f, |
1007 | _ => false, |
1008 | }) |
1009 | } |
1010 | |
1011 | /// Returns the name of the async callback export, if any, for the `key` and |
1012 | /// `func` combo. |
1013 | pub fn callback(&self, key: &WorldKey, func: &Function) -> Option<&str> { |
1014 | self.find(|m| match m { |
1015 | Export::WorldFuncCallback(k) => k == key, |
1016 | Export::InterfaceFuncCallback(k, f) => k == key && func.name == *f, |
1017 | _ => false, |
1018 | }) |
1019 | } |
1020 | |
1021 | pub fn abi(&self, key: &WorldKey, func: &Function) -> Option<AbiVariant> { |
1022 | self.names.values().find_map(|m| match m { |
1023 | Export::WorldFunc(k, f, abi) if k == key && func.name == *f => Some(*abi), |
1024 | Export::InterfaceFunc(k, _, f, abi) if k == key && func.name == *f => Some(*abi), |
1025 | _ => None, |
1026 | }) |
1027 | } |
1028 | |
1029 | /// Returns the realloc that the exported function `interface` and `func` |
1030 | /// are using. |
1031 | pub fn export_realloc_for(&self, key: &WorldKey, func: &Function) -> Option<&str> { |
1032 | // TODO: This realloc detection should probably be improved with |
1033 | // some sort of scheme to have per-function reallocs like |
1034 | // `cabi_realloc_{name}` or something like that. |
1035 | let _ = (key, func); |
1036 | |
1037 | if let Some(name) = self.find(|m| matches!(m, Export::GeneralPurposeExportRealloc)) { |
1038 | return Some(name); |
1039 | } |
1040 | self.general_purpose_realloc() |
1041 | } |
1042 | |
1043 | /// Returns the realloc that the imported function `interface` and `func` |
1044 | /// are using. |
1045 | pub fn import_realloc_for(&self, interface: Option<InterfaceId>, func: &str) -> Option<&str> { |
1046 | // TODO: This realloc detection should probably be improved with |
1047 | // some sort of scheme to have per-function reallocs like |
1048 | // `cabi_realloc_{name}` or something like that. |
1049 | let _ = (interface, func); |
1050 | |
1051 | if let Some(name) = self.find(|m| matches!(m, Export::GeneralPurposeImportRealloc)) { |
1052 | return Some(name); |
1053 | } |
1054 | self.general_purpose_realloc() |
1055 | } |
1056 | |
1057 | /// Returns the realloc that the main module is exporting into the adapter. |
1058 | pub fn realloc_to_import_into_adapter(&self) -> Option<&str> { |
1059 | if let Some(name) = self.find(|m| matches!(m, Export::ReallocForAdapter)) { |
1060 | return Some(name); |
1061 | } |
1062 | self.general_purpose_realloc() |
1063 | } |
1064 | |
1065 | fn general_purpose_realloc(&self) -> Option<&str> { |
1066 | self.find(|m| matches!(m, Export::GeneralPurposeRealloc)) |
1067 | } |
1068 | |
1069 | /// Returns the memory, if exported, for this module. |
1070 | pub fn memory(&self) -> Option<&str> { |
1071 | self.find(|m| matches!(m, Export::Memory)) |
1072 | } |
1073 | |
1074 | /// Returns the `_initialize` intrinsic, if exported, for this module. |
1075 | pub fn initialize(&self) -> Option<&str> { |
1076 | self.find(|m| matches!(m, Export::Initialize)) |
1077 | } |
1078 | |
1079 | /// Returns destructor for the exported resource `ty`, if it was listed. |
1080 | pub fn resource_dtor(&self, ty: TypeId) -> Option<&str> { |
1081 | self.find(|m| match m { |
1082 | Export::ResourceDtor(t) => *t == ty, |
1083 | _ => false, |
1084 | }) |
1085 | } |
1086 | |
1087 | /// NB: this is a linear search and if that's ever a problem this should |
1088 | /// build up an inverse map during construction to accelerate it. |
1089 | fn find(&self, f: impl Fn(&Export) -> bool) -> Option<&str> { |
1090 | let (name, _) = self.names.iter().filter(|(_, m)| f(m)).next()?; |
1091 | Some(name) |
1092 | } |
1093 | |
1094 | /// Iterates over all exports of this module. |
1095 | pub fn iter(&self) -> impl Iterator<Item = (&str, &Export)> + '_ { |
1096 | self.names.iter().map(|(n, e)| (n.as_str(), e)) |
1097 | } |
1098 | |
1099 | fn validate(&self, encoder: &ComponentEncoder, exports: &IndexSet<WorldKey>) -> Result<()> { |
1100 | let resolve = &encoder.metadata.resolve; |
1101 | let world = encoder.metadata.world; |
1102 | // Multi-memory isn't supported because otherwise we don't know what |
1103 | // memory to put things in. |
1104 | if self |
1105 | .names |
1106 | .values() |
1107 | .filter(|m| matches!(m, Export::Memory)) |
1108 | .count() |
1109 | > 1 |
1110 | { |
1111 | bail!("cannot componentize module that exports multiple memories" ) |
1112 | } |
1113 | |
1114 | // All of `exports` must be exported and found within this module. |
1115 | for export in exports { |
1116 | let require_interface_func = |interface: InterfaceId, name: &str| -> Result<()> { |
1117 | let result = self.find(|e| match e { |
1118 | Export::InterfaceFunc(_, id, s, _) => interface == *id && name == s, |
1119 | _ => false, |
1120 | }); |
1121 | if result.is_some() { |
1122 | Ok(()) |
1123 | } else { |
1124 | let export = resolve.name_world_key(export); |
1125 | bail!("failed to find export of interface ` {export}` function ` {name}`" ) |
1126 | } |
1127 | }; |
1128 | let require_world_func = |name: &str| -> Result<()> { |
1129 | let result = self.find(|e| match e { |
1130 | Export::WorldFunc(_, s, _) => name == s, |
1131 | _ => false, |
1132 | }); |
1133 | if result.is_some() { |
1134 | Ok(()) |
1135 | } else { |
1136 | bail!("failed to find export of function ` {name}`" ) |
1137 | } |
1138 | }; |
1139 | match &resolve.worlds[world].exports[export] { |
1140 | WorldItem::Interface { id, .. } => { |
1141 | for (name, _) in resolve.interfaces[*id].functions.iter() { |
1142 | require_interface_func(*id, name)?; |
1143 | } |
1144 | } |
1145 | WorldItem::Function(f) => { |
1146 | require_world_func(&f.name)?; |
1147 | } |
1148 | WorldItem::Type(_) => unreachable!(), |
1149 | } |
1150 | } |
1151 | |
1152 | Ok(()) |
1153 | } |
1154 | } |
1155 | |
1156 | /// Trait dispatch and definition for parsing and interpreting "mangled names" |
1157 | /// which show up in imports and exports of the component model. |
1158 | /// |
1159 | /// This trait is used to implement classification of imports and exports in the |
1160 | /// component model. The methods on `ImportMap` and `ExportMap` will use this to |
1161 | /// determine what an import is and how it's lifted/lowered in the world being |
1162 | /// bound. |
1163 | /// |
1164 | /// This trait has a bit of history behind it as well. Before |
1165 | /// WebAssembly/component-model#378 there was no standard naming scheme for core |
1166 | /// wasm imports or exports when componenitizing. This meant that |
1167 | /// `wit-component` implemented a particular scheme which mostly worked but was |
1168 | /// mostly along the lines of "this at least works" rather than "someone sat |
1169 | /// down and designed this". Since then, however, an standard naming scheme has |
1170 | /// now been specified which was indeed designed. |
1171 | /// |
1172 | /// This trait serves as the bridge between these two. The historical naming |
1173 | /// scheme is still supported for now through the `Legacy` implementation below |
1174 | /// and will be for some time. The transition plan at this time is to support |
1175 | /// the new scheme, eventually get it supported in bindings generators, and once |
1176 | /// that's all propagated remove support for the legacy scheme. |
1177 | trait NameMangling { |
1178 | fn import_root(&self) -> &str; |
1179 | fn import_non_root_prefix(&self) -> &str; |
1180 | fn import_exported_intrinsic_prefix(&self) -> &str; |
1181 | fn export_memory(&self) -> &str; |
1182 | fn export_initialize(&self) -> &str; |
1183 | fn export_realloc(&self) -> &str; |
1184 | fn resource_drop_name<'a>(&self, s: &'a str) -> Option<&'a str>; |
1185 | fn resource_new_name<'a>(&self, s: &'a str) -> Option<&'a str>; |
1186 | fn resource_rep_name<'a>(&self, s: &'a str) -> Option<&'a str>; |
1187 | fn task_return_name<'a>(&self, s: &'a str) -> Option<&'a str>; |
1188 | fn task_backpressure(&self) -> Option<&str>; |
1189 | fn task_wait(&self) -> Option<&str>; |
1190 | fn task_poll(&self) -> Option<&str>; |
1191 | fn task_yield(&self) -> Option<&str>; |
1192 | fn subtask_drop(&self) -> Option<&str>; |
1193 | fn callback_name<'a>(&self, s: &'a str) -> Option<&'a str>; |
1194 | fn async_name<'a>(&self, s: &'a str) -> Option<&'a str>; |
1195 | fn async_stackful_name<'a>(&self, s: &'a str) -> Option<&'a str>; |
1196 | fn error_context_new(&self, s: &str) -> Option<StringEncoding>; |
1197 | fn error_context_debug_message<'a>(&self, s: &'a str) -> Option<(StringEncoding, &'a str)>; |
1198 | fn error_context_drop(&self) -> Option<&str>; |
1199 | fn payload_import( |
1200 | &self, |
1201 | module: &str, |
1202 | name: &str, |
1203 | resolve: &Resolve, |
1204 | world: &World, |
1205 | ty: &FuncType, |
1206 | ) -> Result<Option<Import>>; |
1207 | fn module_to_interface( |
1208 | &self, |
1209 | module: &str, |
1210 | resolve: &Resolve, |
1211 | items: &IndexMap<WorldKey, WorldItem>, |
1212 | ) -> Result<(WorldKey, InterfaceId)>; |
1213 | fn strip_post_return<'a>(&self, s: &'a str) -> Option<&'a str>; |
1214 | fn match_wit_export<'a>( |
1215 | &self, |
1216 | export_name: &str, |
1217 | resolve: &'a Resolve, |
1218 | world: WorldId, |
1219 | exports: &'a IndexSet<WorldKey>, |
1220 | ) -> Option<(&'a WorldKey, Option<InterfaceId>, &'a Function)>; |
1221 | fn match_wit_resource_dtor<'a>( |
1222 | &self, |
1223 | export_name: &str, |
1224 | resolve: &'a Resolve, |
1225 | world: WorldId, |
1226 | exports: &'a IndexSet<WorldKey>, |
1227 | ) -> Option<TypeId>; |
1228 | } |
1229 | |
1230 | /// Definition of the "standard" naming scheme which currently starts with |
1231 | /// "cm32p2". Note that wasm64 is not supported at this time. |
1232 | struct Standard; |
1233 | |
1234 | const STANDARD: &'static dyn NameMangling = &Standard; |
1235 | |
1236 | impl NameMangling for Standard { |
1237 | fn import_root(&self) -> &str { |
1238 | "" |
1239 | } |
1240 | fn import_non_root_prefix(&self) -> &str { |
1241 | "|" |
1242 | } |
1243 | fn import_exported_intrinsic_prefix(&self) -> &str { |
1244 | "_ex_" |
1245 | } |
1246 | fn export_memory(&self) -> &str { |
1247 | "_memory" |
1248 | } |
1249 | fn export_initialize(&self) -> &str { |
1250 | "_initialize" |
1251 | } |
1252 | fn export_realloc(&self) -> &str { |
1253 | "_realloc" |
1254 | } |
1255 | fn resource_drop_name<'a>(&self, s: &'a str) -> Option<&'a str> { |
1256 | s.strip_suffix("_drop" ) |
1257 | } |
1258 | fn resource_new_name<'a>(&self, s: &'a str) -> Option<&'a str> { |
1259 | s.strip_suffix("_new" ) |
1260 | } |
1261 | fn resource_rep_name<'a>(&self, s: &'a str) -> Option<&'a str> { |
1262 | s.strip_suffix("_rep" ) |
1263 | } |
1264 | fn task_return_name<'a>(&self, s: &'a str) -> Option<&'a str> { |
1265 | _ = s; |
1266 | None |
1267 | } |
1268 | fn task_backpressure(&self) -> Option<&str> { |
1269 | None |
1270 | } |
1271 | fn task_wait(&self) -> Option<&str> { |
1272 | None |
1273 | } |
1274 | fn task_poll(&self) -> Option<&str> { |
1275 | None |
1276 | } |
1277 | fn task_yield(&self) -> Option<&str> { |
1278 | None |
1279 | } |
1280 | fn subtask_drop(&self) -> Option<&str> { |
1281 | None |
1282 | } |
1283 | fn callback_name<'a>(&self, s: &'a str) -> Option<&'a str> { |
1284 | _ = s; |
1285 | None |
1286 | } |
1287 | fn async_name<'a>(&self, s: &'a str) -> Option<&'a str> { |
1288 | _ = s; |
1289 | None |
1290 | } |
1291 | fn async_stackful_name<'a>(&self, s: &'a str) -> Option<&'a str> { |
1292 | _ = s; |
1293 | None |
1294 | } |
1295 | fn error_context_new(&self, s: &str) -> Option<StringEncoding> { |
1296 | _ = s; |
1297 | None |
1298 | } |
1299 | fn error_context_debug_message<'a>(&self, s: &'a str) -> Option<(StringEncoding, &'a str)> { |
1300 | _ = s; |
1301 | None |
1302 | } |
1303 | fn error_context_drop(&self) -> Option<&str> { |
1304 | None |
1305 | } |
1306 | fn payload_import( |
1307 | &self, |
1308 | module: &str, |
1309 | name: &str, |
1310 | resolve: &Resolve, |
1311 | world: &World, |
1312 | ty: &FuncType, |
1313 | ) -> Result<Option<Import>> { |
1314 | _ = (module, name, resolve, world, ty); |
1315 | Ok(None) |
1316 | } |
1317 | fn module_to_interface( |
1318 | &self, |
1319 | interface: &str, |
1320 | resolve: &Resolve, |
1321 | items: &IndexMap<WorldKey, WorldItem>, |
1322 | ) -> Result<(WorldKey, InterfaceId)> { |
1323 | for (key, item) in items.iter() { |
1324 | let id = match key { |
1325 | // Bare keys are matched exactly against `interface` |
1326 | WorldKey::Name(name) => match item { |
1327 | WorldItem::Interface { id, .. } if name == interface => *id, |
1328 | _ => continue, |
1329 | }, |
1330 | // ID-identified keys are matched with their "canonical name" |
1331 | WorldKey::Interface(id) => { |
1332 | if resolve.canonicalized_id_of(*id).as_deref() != Some(interface) { |
1333 | continue; |
1334 | } |
1335 | *id |
1336 | } |
1337 | }; |
1338 | return Ok((key.clone(), id)); |
1339 | } |
1340 | bail!("failed to find world item corresponding to interface ` {interface}`" ) |
1341 | } |
1342 | fn strip_post_return<'a>(&self, s: &'a str) -> Option<&'a str> { |
1343 | s.strip_suffix("_post" ) |
1344 | } |
1345 | fn match_wit_export<'a>( |
1346 | &self, |
1347 | export_name: &str, |
1348 | resolve: &'a Resolve, |
1349 | world: WorldId, |
1350 | exports: &'a IndexSet<WorldKey>, |
1351 | ) -> Option<(&'a WorldKey, Option<InterfaceId>, &'a Function)> { |
1352 | if let Some(world_export_name) = export_name.strip_prefix("||" ) { |
1353 | let key = exports.get(&WorldKey::Name(world_export_name.to_string()))?; |
1354 | match &resolve.worlds[world].exports[key] { |
1355 | WorldItem::Function(f) => return Some((key, None, f)), |
1356 | _ => return None, |
1357 | } |
1358 | } |
1359 | |
1360 | let (key, id, func_name) = |
1361 | self.match_wit_interface(export_name, resolve, world, exports)?; |
1362 | let func = resolve.interfaces[id].functions.get(func_name)?; |
1363 | Some((key, Some(id), func)) |
1364 | } |
1365 | |
1366 | fn match_wit_resource_dtor<'a>( |
1367 | &self, |
1368 | export_name: &str, |
1369 | resolve: &'a Resolve, |
1370 | world: WorldId, |
1371 | exports: &'a IndexSet<WorldKey>, |
1372 | ) -> Option<TypeId> { |
1373 | let (_key, id, name) = |
1374 | self.match_wit_interface(export_name.strip_suffix("_dtor" )?, resolve, world, exports)?; |
1375 | let ty = *resolve.interfaces[id].types.get(name)?; |
1376 | match resolve.types[ty].kind { |
1377 | TypeDefKind::Resource => Some(ty), |
1378 | _ => None, |
1379 | } |
1380 | } |
1381 | } |
1382 | |
1383 | impl Standard { |
1384 | fn match_wit_interface<'a, 'b>( |
1385 | &self, |
1386 | export_name: &'b str, |
1387 | resolve: &'a Resolve, |
1388 | world: WorldId, |
1389 | exports: &'a IndexSet<WorldKey>, |
1390 | ) -> Option<(&'a WorldKey, InterfaceId, &'b str)> { |
1391 | let world = &resolve.worlds[world]; |
1392 | let export_name = export_name.strip_prefix("|" )?; |
1393 | |
1394 | for export in exports { |
1395 | let id = match &world.exports[export] { |
1396 | WorldItem::Interface { id, .. } => *id, |
1397 | WorldItem::Function(_) => continue, |
1398 | WorldItem::Type(_) => unreachable!(), |
1399 | }; |
1400 | let remaining = match export { |
1401 | WorldKey::Name(name) => export_name.strip_prefix(name), |
1402 | WorldKey::Interface(_) => { |
1403 | let prefix = resolve.canonicalized_id_of(id).unwrap(); |
1404 | export_name.strip_prefix(&prefix) |
1405 | } |
1406 | }; |
1407 | let item_name = match remaining.and_then(|s| s.strip_prefix("|" )) { |
1408 | Some(name) => name, |
1409 | None => continue, |
1410 | }; |
1411 | return Some((export, id, item_name)); |
1412 | } |
1413 | |
1414 | None |
1415 | } |
1416 | } |
1417 | |
1418 | /// Definition of wit-component's "legacy" naming scheme which predates |
1419 | /// WebAssembly/component-model#378. |
1420 | struct Legacy; |
1421 | |
1422 | const LEGACY: &'static dyn NameMangling = &Legacy; |
1423 | |
1424 | impl NameMangling for Legacy { |
1425 | fn import_root(&self) -> &str { |
1426 | "$root" |
1427 | } |
1428 | fn import_non_root_prefix(&self) -> &str { |
1429 | "" |
1430 | } |
1431 | fn import_exported_intrinsic_prefix(&self) -> &str { |
1432 | "[export]" |
1433 | } |
1434 | fn export_memory(&self) -> &str { |
1435 | "memory" |
1436 | } |
1437 | fn export_initialize(&self) -> &str { |
1438 | "_initialize" |
1439 | } |
1440 | fn export_realloc(&self) -> &str { |
1441 | "cabi_realloc" |
1442 | } |
1443 | fn resource_drop_name<'a>(&self, s: &'a str) -> Option<&'a str> { |
1444 | s.strip_prefix("[resource-drop]" ) |
1445 | } |
1446 | fn resource_new_name<'a>(&self, s: &'a str) -> Option<&'a str> { |
1447 | s.strip_prefix("[resource-new]" ) |
1448 | } |
1449 | fn resource_rep_name<'a>(&self, s: &'a str) -> Option<&'a str> { |
1450 | s.strip_prefix("[resource-rep]" ) |
1451 | } |
1452 | fn task_return_name<'a>(&self, s: &'a str) -> Option<&'a str> { |
1453 | s.strip_prefix("[task-return]" ) |
1454 | } |
1455 | fn task_backpressure(&self) -> Option<&str> { |
1456 | Some("[task-backpressure]" ) |
1457 | } |
1458 | fn task_wait(&self) -> Option<&str> { |
1459 | Some("[task-wait]" ) |
1460 | } |
1461 | fn task_poll(&self) -> Option<&str> { |
1462 | Some("[task-poll]" ) |
1463 | } |
1464 | fn task_yield(&self) -> Option<&str> { |
1465 | Some("[task-yield]" ) |
1466 | } |
1467 | fn subtask_drop(&self) -> Option<&str> { |
1468 | Some("[subtask-drop]" ) |
1469 | } |
1470 | fn callback_name<'a>(&self, s: &'a str) -> Option<&'a str> { |
1471 | s.strip_prefix("[callback][async]" ) |
1472 | } |
1473 | fn async_name<'a>(&self, s: &'a str) -> Option<&'a str> { |
1474 | s.strip_prefix("[async]" ) |
1475 | } |
1476 | fn async_stackful_name<'a>(&self, s: &'a str) -> Option<&'a str> { |
1477 | s.strip_prefix("[async-stackful]" ) |
1478 | } |
1479 | fn error_context_new(&self, s: &str) -> Option<StringEncoding> { |
1480 | parse_encoding( |
1481 | s.strip_prefix("[error-context-new;encoding=" )? |
1482 | .strip_suffix("]" )?, |
1483 | ) |
1484 | } |
1485 | fn error_context_debug_message<'a>(&self, s: &'a str) -> Option<(StringEncoding, &'a str)> { |
1486 | let mut suffix = s.strip_prefix("[error-context-debug-message;" )?; |
1487 | let mut encoding = None; |
1488 | let mut realloc = None; |
1489 | loop { |
1490 | if let Some(index) = suffix.find(';' ).or_else(|| suffix.find(']' )) { |
1491 | if let Some(suffix) = suffix[..index].strip_prefix("encoding=" ) { |
1492 | if encoding.is_some() { |
1493 | return None; |
1494 | } |
1495 | encoding = parse_encoding(suffix) |
1496 | } else if let Some(suffix) = suffix[..index].strip_prefix("realloc=" ) { |
1497 | if realloc.is_some() { |
1498 | return None; |
1499 | } |
1500 | realloc = Some(suffix); |
1501 | } else { |
1502 | return None; |
1503 | } |
1504 | suffix = &suffix[index + 1..]; |
1505 | } else { |
1506 | break; |
1507 | } |
1508 | } |
1509 | Some((encoding?, realloc?)) |
1510 | } |
1511 | fn error_context_drop(&self) -> Option<&str> { |
1512 | Some("[error-context-drop]" ) |
1513 | } |
1514 | fn payload_import( |
1515 | &self, |
1516 | module: &str, |
1517 | name: &str, |
1518 | resolve: &Resolve, |
1519 | world: &World, |
1520 | ty: &FuncType, |
1521 | ) -> Result<Option<Import>> { |
1522 | Ok( |
1523 | if let Some((suffix, imported)) = module |
1524 | .strip_prefix("[import-payload]" ) |
1525 | .map(|v| (v, true)) |
1526 | .or_else(|| module.strip_prefix("[export-payload]" ).map(|v| (v, false))) |
1527 | { |
1528 | let (key, interface) = if suffix == self.import_root() { |
1529 | (WorldKey::Name(name.to_string()), None) |
1530 | } else { |
1531 | let (key, id) = self.module_to_interface( |
1532 | suffix, |
1533 | resolve, |
1534 | if imported { |
1535 | &world.imports |
1536 | } else { |
1537 | &world.exports |
1538 | }, |
1539 | )?; |
1540 | (key, Some(id)) |
1541 | }; |
1542 | |
1543 | let orig_name = name; |
1544 | |
1545 | let (name, async_) = if let Some(name) = self.async_name(name) { |
1546 | (name, true) |
1547 | } else { |
1548 | (name, false) |
1549 | }; |
1550 | |
1551 | let info = |payload_key| { |
1552 | let (function, ty) = get_future_or_stream_type( |
1553 | resolve, |
1554 | world, |
1555 | &payload_key, |
1556 | interface, |
1557 | imported, |
1558 | )?; |
1559 | Ok::<_, anyhow::Error>(PayloadInfo { |
1560 | name: orig_name.to_string(), |
1561 | ty, |
1562 | function, |
1563 | key: key.clone(), |
1564 | interface, |
1565 | imported, |
1566 | }) |
1567 | }; |
1568 | |
1569 | Some( |
1570 | if let Some(key) = match_payload_prefix(name, "[future-new-" ) { |
1571 | if async_ { |
1572 | bail!("async `future.new` calls not supported" ); |
1573 | } |
1574 | validate_func_sig(name, &FuncType::new([], [ValType::I32]), ty)?; |
1575 | Import::FutureNew(info(key)?) |
1576 | } else if let Some(key) = match_payload_prefix(name, "[future-write-" ) { |
1577 | validate_func_sig( |
1578 | name, |
1579 | &FuncType::new([ValType::I32; 2], [ValType::I32]), |
1580 | ty, |
1581 | )?; |
1582 | Import::FutureWrite { |
1583 | async_, |
1584 | info: info(key)?, |
1585 | } |
1586 | } else if let Some(key) = match_payload_prefix(name, "[future-read-" ) { |
1587 | validate_func_sig( |
1588 | name, |
1589 | &FuncType::new([ValType::I32; 2], [ValType::I32]), |
1590 | ty, |
1591 | )?; |
1592 | Import::FutureRead { |
1593 | async_, |
1594 | info: info(key)?, |
1595 | } |
1596 | } else if let Some(key) = match_payload_prefix(name, "[future-cancel-write-" ) { |
1597 | validate_func_sig( |
1598 | name, |
1599 | &FuncType::new([ValType::I32], [ValType::I32]), |
1600 | ty, |
1601 | )?; |
1602 | let info = info(key)?; |
1603 | Import::FutureCancelWrite { |
1604 | async_, |
1605 | ty: info.ty, |
1606 | imported: info.imported, |
1607 | } |
1608 | } else if let Some(key) = match_payload_prefix(name, "[future-cancel-read-" ) { |
1609 | validate_func_sig( |
1610 | name, |
1611 | &FuncType::new([ValType::I32], [ValType::I32]), |
1612 | ty, |
1613 | )?; |
1614 | let info = info(key)?; |
1615 | Import::FutureCancelRead { |
1616 | async_, |
1617 | ty: info.ty, |
1618 | imported: info.imported, |
1619 | } |
1620 | } else if let Some(key) = match_payload_prefix(name, "[future-close-writable-" ) |
1621 | { |
1622 | if async_ { |
1623 | bail!("async `future.close-writable` calls not supported" ); |
1624 | } |
1625 | validate_func_sig(name, &FuncType::new([ValType::I32; 2], []), ty)?; |
1626 | let info = info(key)?; |
1627 | Import::FutureCloseWritable { |
1628 | ty: info.ty, |
1629 | imported: info.imported, |
1630 | } |
1631 | } else if let Some(key) = match_payload_prefix(name, "[future-close-readable-" ) |
1632 | { |
1633 | if async_ { |
1634 | bail!("async `future.close-readable` calls not supported" ); |
1635 | } |
1636 | validate_func_sig(name, &FuncType::new([ValType::I32], []), ty)?; |
1637 | let info = info(key)?; |
1638 | Import::FutureCloseReadable { |
1639 | ty: info.ty, |
1640 | imported: info.imported, |
1641 | } |
1642 | } else if let Some(key) = match_payload_prefix(name, "[stream-new-" ) { |
1643 | if async_ { |
1644 | bail!("async `stream.new` calls not supported" ); |
1645 | } |
1646 | validate_func_sig(name, &FuncType::new([], [ValType::I32]), ty)?; |
1647 | Import::StreamNew(info(key)?) |
1648 | } else if let Some(key) = match_payload_prefix(name, "[stream-write-" ) { |
1649 | validate_func_sig( |
1650 | name, |
1651 | &FuncType::new([ValType::I32; 3], [ValType::I32]), |
1652 | ty, |
1653 | )?; |
1654 | Import::StreamWrite { |
1655 | async_, |
1656 | info: info(key)?, |
1657 | } |
1658 | } else if let Some(key) = match_payload_prefix(name, "[stream-read-" ) { |
1659 | validate_func_sig( |
1660 | name, |
1661 | &FuncType::new([ValType::I32; 3], [ValType::I32]), |
1662 | ty, |
1663 | )?; |
1664 | Import::StreamRead { |
1665 | async_, |
1666 | info: info(key)?, |
1667 | } |
1668 | } else if let Some(key) = match_payload_prefix(name, "[stream-cancel-write-" ) { |
1669 | validate_func_sig( |
1670 | name, |
1671 | &FuncType::new([ValType::I32], [ValType::I32]), |
1672 | ty, |
1673 | )?; |
1674 | let info = info(key)?; |
1675 | Import::StreamCancelWrite { |
1676 | async_, |
1677 | ty: info.ty, |
1678 | imported: info.imported, |
1679 | } |
1680 | } else if let Some(key) = match_payload_prefix(name, "[stream-cancel-read-" ) { |
1681 | validate_func_sig( |
1682 | name, |
1683 | &FuncType::new([ValType::I32], [ValType::I32]), |
1684 | ty, |
1685 | )?; |
1686 | let info = info(key)?; |
1687 | Import::StreamCancelRead { |
1688 | async_, |
1689 | ty: info.ty, |
1690 | imported: info.imported, |
1691 | } |
1692 | } else if let Some(key) = match_payload_prefix(name, "[stream-close-writable-" ) |
1693 | { |
1694 | if async_ { |
1695 | bail!("async `stream.close-writable` calls not supported" ); |
1696 | } |
1697 | validate_func_sig(name, &FuncType::new([ValType::I32; 2], []), ty)?; |
1698 | let info = info(key)?; |
1699 | Import::StreamCloseWritable { |
1700 | ty: info.ty, |
1701 | imported: info.imported, |
1702 | } |
1703 | } else if let Some(key) = match_payload_prefix(name, "[stream-close-readable-" ) |
1704 | { |
1705 | if async_ { |
1706 | bail!("async `stream.close-readable` calls not supported" ); |
1707 | } |
1708 | validate_func_sig(name, &FuncType::new([ValType::I32], []), ty)?; |
1709 | let info = info(key)?; |
1710 | Import::StreamCloseReadable { |
1711 | ty: info.ty, |
1712 | imported: info.imported, |
1713 | } |
1714 | } else { |
1715 | bail!("unrecognized payload import: {name}" ); |
1716 | }, |
1717 | ) |
1718 | } else { |
1719 | None |
1720 | }, |
1721 | ) |
1722 | } |
1723 | fn module_to_interface( |
1724 | &self, |
1725 | module: &str, |
1726 | resolve: &Resolve, |
1727 | items: &IndexMap<WorldKey, WorldItem>, |
1728 | ) -> Result<(WorldKey, InterfaceId)> { |
1729 | // First see if this is a bare name |
1730 | let bare_name = WorldKey::Name(module.to_string()); |
1731 | if let Some(WorldItem::Interface { id, .. }) = items.get(&bare_name) { |
1732 | return Ok((bare_name, *id)); |
1733 | } |
1734 | |
1735 | // ... and if this isn't a bare name then it's time to do some parsing |
1736 | // related to interfaces, versions, and such. First up the `module` name |
1737 | // is parsed as a normal component name from `wasmparser` to see if it's |
1738 | // of the "interface kind". If it's not then that means the above match |
1739 | // should have been a hit but it wasn't, so an error is returned. |
1740 | let kebab_name = ComponentName::new(module, 0); |
1741 | let name = match kebab_name.as_ref().map(|k| k.kind()) { |
1742 | Ok(ComponentNameKind::Interface(name)) => name, |
1743 | _ => bail!("module requires an import interface named ` {module}`" ), |
1744 | }; |
1745 | |
1746 | // Prioritize an exact match based on versions, so try that first. |
1747 | let pkgname = PackageName { |
1748 | namespace: name.namespace().to_string(), |
1749 | name: name.package().to_string(), |
1750 | version: name.version(), |
1751 | }; |
1752 | if let Some(pkg) = resolve.package_names.get(&pkgname) { |
1753 | if let Some(id) = resolve.packages[*pkg] |
1754 | .interfaces |
1755 | .get(name.interface().as_str()) |
1756 | { |
1757 | let key = WorldKey::Interface(*id); |
1758 | if items.contains_key(&key) { |
1759 | return Ok((key, *id)); |
1760 | } |
1761 | } |
1762 | } |
1763 | |
1764 | // If an exact match wasn't found then instead search for the first |
1765 | // match based on versions. This means that a core wasm import for |
1766 | // "1.2.3" might end up matching an interface at "1.2.4", for example. |
1767 | // (or "1.2.2", depending on what's available). |
1768 | for (key, _) in items { |
1769 | let id = match key { |
1770 | WorldKey::Interface(id) => *id, |
1771 | WorldKey::Name(_) => continue, |
1772 | }; |
1773 | // Make sure the interface names match |
1774 | let interface = &resolve.interfaces[id]; |
1775 | if interface.name.as_ref().unwrap() != name.interface().as_str() { |
1776 | continue; |
1777 | } |
1778 | |
1779 | // Make sure the package name (without version) matches |
1780 | let pkg = &resolve.packages[interface.package.unwrap()]; |
1781 | if pkg.name.namespace != pkgname.namespace || pkg.name.name != pkgname.name { |
1782 | continue; |
1783 | } |
1784 | |
1785 | let module_version = match name.version() { |
1786 | Some(version) => version, |
1787 | None => continue, |
1788 | }; |
1789 | let pkg_version = match &pkg.name.version { |
1790 | Some(version) => version, |
1791 | None => continue, |
1792 | }; |
1793 | |
1794 | // Test if the two semver versions are compatible |
1795 | let module_compat = PackageName::version_compat_track(&module_version); |
1796 | let pkg_compat = PackageName::version_compat_track(pkg_version); |
1797 | if module_compat == pkg_compat { |
1798 | return Ok((key.clone(), id)); |
1799 | } |
1800 | } |
1801 | |
1802 | bail!("module requires an import interface named ` {module}`" ) |
1803 | } |
1804 | fn strip_post_return<'a>(&self, s: &'a str) -> Option<&'a str> { |
1805 | s.strip_prefix("cabi_post_" ) |
1806 | } |
1807 | fn match_wit_export<'a>( |
1808 | &self, |
1809 | export_name: &str, |
1810 | resolve: &'a Resolve, |
1811 | world: WorldId, |
1812 | exports: &'a IndexSet<WorldKey>, |
1813 | ) -> Option<(&'a WorldKey, Option<InterfaceId>, &'a Function)> { |
1814 | let world = &resolve.worlds[world]; |
1815 | for name in exports { |
1816 | match &world.exports[name] { |
1817 | WorldItem::Function(f) => { |
1818 | if f.legacy_core_export_name(None) == export_name { |
1819 | return Some((name, None, f)); |
1820 | } |
1821 | } |
1822 | WorldItem::Interface { id, .. } => { |
1823 | let string = resolve.name_world_key(name); |
1824 | for (_, func) in resolve.interfaces[*id].functions.iter() { |
1825 | if func.legacy_core_export_name(Some(&string)) == export_name { |
1826 | return Some((name, Some(*id), func)); |
1827 | } |
1828 | } |
1829 | } |
1830 | |
1831 | WorldItem::Type(_) => unreachable!(), |
1832 | } |
1833 | } |
1834 | |
1835 | None |
1836 | } |
1837 | |
1838 | fn match_wit_resource_dtor<'a>( |
1839 | &self, |
1840 | export_name: &str, |
1841 | resolve: &'a Resolve, |
1842 | world: WorldId, |
1843 | exports: &'a IndexSet<WorldKey>, |
1844 | ) -> Option<TypeId> { |
1845 | let world = &resolve.worlds[world]; |
1846 | for name in exports { |
1847 | let id = match &world.exports[name] { |
1848 | WorldItem::Interface { id, .. } => *id, |
1849 | WorldItem::Function(_) => continue, |
1850 | WorldItem::Type(_) => unreachable!(), |
1851 | }; |
1852 | let name = resolve.name_world_key(name); |
1853 | let resource = match export_name |
1854 | .strip_prefix(&name) |
1855 | .and_then(|s| s.strip_prefix("#[dtor]" )) |
1856 | .and_then(|r| resolve.interfaces[id].types.get(r)) |
1857 | { |
1858 | Some(id) => *id, |
1859 | None => continue, |
1860 | }; |
1861 | |
1862 | match resolve.types[resource].kind { |
1863 | TypeDefKind::Resource => {} |
1864 | _ => continue, |
1865 | } |
1866 | |
1867 | return Some(resource); |
1868 | } |
1869 | |
1870 | None |
1871 | } |
1872 | } |
1873 | |
1874 | /// This function validates the following: |
1875 | /// |
1876 | /// * The `bytes` represent a valid core WebAssembly module. |
1877 | /// * The module's imports are all satisfied by the given `imports` interfaces |
1878 | /// or the `adapters` set. |
1879 | /// * The given default and exported interfaces are satisfied by the module's |
1880 | /// exports. |
1881 | /// |
1882 | /// The `ValidatedModule` return value contains the metadata which describes the |
1883 | /// input module on success. This is then further used to generate a component |
1884 | /// for this module. |
1885 | pub fn validate_module(encoder: &ComponentEncoder, bytes: &[u8]) -> Result<ValidatedModule> { |
1886 | ValidatedModule::new(encoder, bytes, &encoder.main_module_exports, info:None) |
1887 | } |
1888 | |
1889 | /// This function will validate the `bytes` provided as a wasm adapter module. |
1890 | /// Notably this will validate the wasm module itself in addition to ensuring |
1891 | /// that it has the "shape" of an adapter module. Current constraints are: |
1892 | /// |
1893 | /// * The adapter module can import only one memory |
1894 | /// * The adapter module can only import from the name of `interface` specified, |
1895 | /// and all function imports must match the `required` types which correspond |
1896 | /// to the lowered types of the functions in `interface`. |
1897 | /// |
1898 | /// The wasm module passed into this function is the output of the GC pass of an |
1899 | /// adapter module's original source. This means that the adapter module is |
1900 | /// already minimized and this is a double-check that the minimization pass |
1901 | /// didn't accidentally break the wasm module. |
1902 | /// |
1903 | /// If `is_library` is true, we waive some of the constraints described above, |
1904 | /// allowing the module to import tables and globals, as well as import |
1905 | /// functions at the world level, not just at the interface level. |
1906 | pub fn validate_adapter_module( |
1907 | encoder: &ComponentEncoder, |
1908 | bytes: &[u8], |
1909 | required_by_import: &IndexMap<String, FuncType>, |
1910 | exports: &IndexSet<WorldKey>, |
1911 | library_info: Option<&LibraryInfo>, |
1912 | ) -> Result<ValidatedModule> { |
1913 | let ret: ValidatedModule = ValidatedModule::new(encoder, bytes, exports, library_info)?; |
1914 | |
1915 | for (name: &String, required_ty: &FuncType) in required_by_import { |
1916 | let actual: &FuncType = match ret.exports.raw_exports.get(key:name) { |
1917 | Some(ty: &FuncType) => ty, |
1918 | None => bail!("adapter module did not export ` {name}`" ), |
1919 | }; |
1920 | validate_func_sig(name, expected:required_ty, &actual)?; |
1921 | } |
1922 | |
1923 | Ok(ret) |
1924 | } |
1925 | |
1926 | fn resource_test_for_interface<'a>( |
1927 | resolve: &'a Resolve, |
1928 | id: InterfaceId, |
1929 | ) -> impl Fn(&str) -> Option<TypeId> + 'a { |
1930 | let interface: &Interface = &resolve.interfaces[id]; |
1931 | move |name: &str| { |
1932 | let ty: Id = match interface.types.get(key:name) { |
1933 | Some(ty: &Id) => *ty, |
1934 | None => return None, |
1935 | }; |
1936 | if matches!(resolve.types[ty].kind, TypeDefKind::Resource) { |
1937 | Some(ty) |
1938 | } else { |
1939 | None |
1940 | } |
1941 | } |
1942 | } |
1943 | |
1944 | fn resource_test_for_world<'a>( |
1945 | resolve: &'a Resolve, |
1946 | id: WorldId, |
1947 | ) -> impl Fn(&str) -> Option<TypeId> + 'a { |
1948 | let world: &World = &resolve.worlds[id]; |
1949 | move |name: &str| match world.imports.get(&WorldKey::Name(name.to_string()))? { |
1950 | WorldItem::Type(r: &Id) => { |
1951 | if matches!(resolve.types[*r].kind, TypeDefKind::Resource) { |
1952 | Some(*r) |
1953 | } else { |
1954 | None |
1955 | } |
1956 | } |
1957 | _ => None, |
1958 | } |
1959 | } |
1960 | |
1961 | fn validate_func( |
1962 | resolve: &Resolve, |
1963 | ty: &wasmparser::FuncType, |
1964 | func: &Function, |
1965 | abi: AbiVariant, |
1966 | ) -> Result<()> { |
1967 | validate_func_sig( |
1968 | &func.name, |
1969 | &wasm_sig_to_func_type(resolve.wasm_signature(variant:abi, func)), |
1970 | ty, |
1971 | ) |
1972 | } |
1973 | |
1974 | fn validate_post_return( |
1975 | resolve: &Resolve, |
1976 | ty: &wasmparser::FuncType, |
1977 | func: &Function, |
1978 | ) -> Result<()> { |
1979 | // The expected signature of a post-return function is to take all the |
1980 | // parameters that are returned by the guest function and then return no |
1981 | // results. Model this by calculating the signature of `func` and then |
1982 | // moving its results into the parameters list while emptying out the |
1983 | // results. |
1984 | let mut sig: WasmSignature = resolve.wasm_signature(variant:AbiVariant::GuestExport, func); |
1985 | sig.params = mem::take(&mut sig.results); |
1986 | validate_func_sig( |
1987 | &format!(" {} post-return" , func.name), |
1988 | &wasm_sig_to_func_type(signature:sig), |
1989 | ty, |
1990 | ) |
1991 | } |
1992 | |
1993 | fn validate_func_sig(name: &str, expected: &FuncType, ty: &wasmparser::FuncType) -> Result<()> { |
1994 | if ty != expected { |
1995 | bail!( |
1996 | "type mismatch for function ` {}`: expected ` {:?} -> {:?}` but found ` {:?} -> {:?}`" , |
1997 | name, |
1998 | expected.params(), |
1999 | expected.results(), |
2000 | ty.params(), |
2001 | ty.results() |
2002 | ); |
2003 | } |
2004 | |
2005 | Ok(()) |
2006 | } |
2007 | |
2008 | fn match_payload_prefix(name: &str, prefix: &str) -> Option<(String, usize)> { |
2009 | let suffix: &str = name.strip_prefix(prefix)?; |
2010 | let index: usize = suffix.find(']' )?; |
2011 | Some(( |
2012 | suffix[index + 1..].to_owned(), |
2013 | suffix[..index].parse().ok()?, |
2014 | )) |
2015 | } |
2016 | |
2017 | /// Retrieve the specified function from the specified world or interface, along |
2018 | /// with the future or stream type at the specified index. |
2019 | /// |
2020 | /// The index refers to the entry in the list returned by |
2021 | /// `Function::find_futures_and_streams`. |
2022 | fn get_future_or_stream_type( |
2023 | resolve: &Resolve, |
2024 | world: &World, |
2025 | (name: &String, index: &usize): &(String, usize), |
2026 | interface: Option<InterfaceId>, |
2027 | imported: bool, |
2028 | ) -> Result<(Function, TypeId)> { |
2029 | let function: Function = get_function(resolve, world, name, interface, imported)?; |
2030 | let ty: Id = function.find_futures_and_streams(resolve)[*index]; |
2031 | Ok((function, ty)) |
2032 | } |
2033 | |
2034 | fn get_function( |
2035 | resolve: &Resolve, |
2036 | world: &World, |
2037 | name: &str, |
2038 | interface: Option<InterfaceId>, |
2039 | imported: bool, |
2040 | ) -> Result<Function> { |
2041 | let function: Option = if let Some(id: Id) = interface { |
2042 | resolveOption.interfaces[id] |
2043 | .functions |
2044 | .get(key:name) |
2045 | .cloned() |
2046 | .map(WorldItem::Function) |
2047 | } else if imported { |
2048 | worldOption<&WorldItem> |
2049 | .imports |
2050 | .get(&WorldKey::Name(name.to_string())) |
2051 | .cloned() |
2052 | } else { |
2053 | worldOption<&WorldItem> |
2054 | .exports |
2055 | .get(&WorldKey::Name(name.to_string())) |
2056 | .cloned() |
2057 | }; |
2058 | let Some(WorldItem::Function(function: Function)) = function else { |
2059 | bail!("no export ` {name}` found" ); |
2060 | }; |
2061 | Ok(function) |
2062 | } |
2063 | |
2064 | fn parse_encoding(s: &str) -> Option<StringEncoding> { |
2065 | match s { |
2066 | "utf8" => Some(StringEncoding::UTF8), |
2067 | "utf16" => Some(StringEncoding::UTF16), |
2068 | "compact-utf16" => Some(StringEncoding::CompactUTF16), |
2069 | _ => None, |
2070 | } |
2071 | } |
2072 | |