A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Add a dedicated libcall for passing resource borrows to their owners (#14962)
Nick Fitzgerald883c5e85db8f
diff --git a/crates/cranelift/src/compiler/component.rs b/crates/cranelift/src/compiler/component.rsindex f36c5e2c3a..7a40c012a0 100644--- a/crates/cranelift/src/compiler/component.rs+++ b/crates/cranelift/src/compiler/component.rs@@ -613,6 +613,14 @@ impl<'a> TrampolineCompiler<'a> {|_, _| {},);}+ Trampoline::ResourceTransferBorrowToOwner => {+ self.translate_libcall(+ host::resource_transfer_borrow_to_owner,+ TrapSentinel::NegativeOne,+ WasmArgs::InRegisters,+ |_, _| {},+ );+ }Trampoline::PrepareCall { memory } => {self.translate_libcall(host::prepare_call,@@ -1411,6 +1419,7 @@ impl<'a> TrampolineCompiler<'a> {// directly from guest wasm, so no check is needed.Trampoline::ResourceTransferOwn| Trampoline::ResourceTransferBorrow+ | Trampoline::ResourceTransferBorrowToOwner| Trampoline::PrepareCall { .. }| Trampoline::StartCall { .. }| Trampoline::FutureTransferdiff --git a/crates/environ/src/component.rs b/crates/environ/src/component.rsindex c762630aca..6744977589 100644--- a/crates/environ/src/component.rs+++ b/crates/environ/src/component.rs@@ -110,6 +110,10 @@ macro_rules! foreach_builtin_component_function {resource_transfer_own(vmctx: vmctx, src_idx: u32, src_table: u32, dst_table: u32) -> u64;resource_transfer_borrow(vmctx: vmctx, src_idx: u32, src_table: u32, dst_table: u32) -> u64;+ // Same as `resource_transfer_borrow` but for when the destination+ // instance owns the resource, in which case it receives the+ // representation directly and no destination table is involved.+ resource_transfer_borrow_to_owner(vmctx: vmctx, src_idx: u32, src_table: u32) -> u64;enter_sync_call(vmctx: vmctx, callee_async: u32, callee_instance: u32) -> bool;exit_sync_call(vmctx: vmctx) -> bool;diff --git a/crates/environ/src/component/dfg.rs b/crates/environ/src/component/dfg.rsindex 60ece44cc3..e35aa98806 100644--- a/crates/environ/src/component/dfg.rs+++ b/crates/environ/src/component/dfg.rs@@ -470,6 +470,7 @@ pub enum Trampoline {},ResourceTransferOwn,ResourceTransferBorrow,+ ResourceTransferBorrowToOwner,PrepareCall {memory: Option<MemoryId>,},@@ -714,6 +715,24 @@ impl ComponentDfg {pub fn resource_index(&self, defined: DefinedResourceIndex) -> ResourceIndex {ResourceIndex::from_u32(defined.as_u32() + (self.imported_resources.len() as u32))}++ /// Convert a resource index into a defined index, or `None` if `idx` is for+ /// an imported resource.+ pub fn defined_resource_index(&self, idx: ResourceIndex) -> Option<DefinedResourceIndex> {+ let idx = idx+ .as_u32()+ .checked_sub(u32::try_from(self.imported_resources.len()).unwrap())?;+ Some(DefinedResourceIndex::from_u32(idx))+ }++ /// Returns the component instance which defines `idx`, or `None` if `idx`+ /// is for an imported resource.+ pub fn defined_resource_instance(+ &self,+ idx: ResourceIndex,+ ) -> Option<RuntimeComponentInstanceIndex> {+ Some(self.resources[self.defined_resource_index(idx)?].instance)+ }}struct LinearizeDfg<'a> {@@ -1168,6 +1187,9 @@ impl LinearizeDfg<'_> {},Trampoline::ResourceTransferOwn => info::Trampoline::ResourceTransferOwn,Trampoline::ResourceTransferBorrow => info::Trampoline::ResourceTransferBorrow,+ Trampoline::ResourceTransferBorrowToOwner => {+ info::Trampoline::ResourceTransferBorrowToOwner+ }Trampoline::PrepareCall { memory } => info::Trampoline::PrepareCall {memory: memory.map(|v| self.runtime_memory(v)),},diff --git a/crates/environ/src/component/info.rs b/crates/environ/src/component/info.rsindex 1a602e4f17..7b6df1da7a 100644--- a/crates/environ/src/component/info.rs+++ b/crates/environ/src/component/info.rs@@ -223,6 +223,15 @@ impl Component {pub fn resource_index(&self, idx: DefinedResourceIndex) -> ResourceIndex {ResourceIndex::from_u32(self.imported_resources.len() as u32 + idx.as_u32())}++ /// Returns the component instance which defines `idx`, or `None` if `idx`+ /// is imported rather than defined within this component.+ pub fn defined_resource_instance(+ &self,+ idx: ResourceIndex,+ ) -> Option<RuntimeComponentInstanceIndex> {+ Some(self.defined_resource_instances[self.defined_resource_index(idx)?])+ }}/// GlobalInitializer instructions to get processed when instantiating a@@ -1065,6 +1074,11 @@ pub enum Trampoline {/// Same as `ResourceTransferOwn` but for borrows.ResourceTransferBorrow,+ /// Same as `ResourceTransferBorrow` but for a destination instance which+ /// owns the resource and so receives its representation directly, meaning+ /// no destination table is consulted.+ ResourceTransferBorrowToOwner,+/// An intrinsic used by FACT-generated modules to prepare a call involving/// an async-lowered import and/or an async-lifted export.PrepareCall {@@ -1242,6 +1256,9 @@ impl Trampoline {ErrorContextDrop { .. } => format!("error-context-drop"),ResourceTransferOwn => format!("component-resource-transfer-own"),ResourceTransferBorrow => format!("component-resource-transfer-borrow"),+ ResourceTransferBorrowToOwner => {+ format!("component-resource-transfer-borrow-to-owner")+ }PrepareCall { .. } => format!("component-prepare-call"),StartCall { .. } => format!("component-start-call"),FutureTransfer => format!("future-transfer"),diff --git a/crates/environ/src/component/thread_transparency.rs b/crates/environ/src/component/thread_transparency.rsindex eeeba31322..bcb31a460d 100644--- a/crates/environ/src/component/thread_transparency.rs+++ b/crates/environ/src/component/thread_transparency.rs@@ -304,6 +304,7 @@ fn trampoline_callable(Transcoder { .. }| ResourceTransferOwn| ResourceTransferBorrow+ | ResourceTransferBorrowToOwner| PrepareCall { .. }| StartCall { .. }| FutureTransferdiff --git a/crates/environ/src/component/translate/adapt.rs b/crates/environ/src/component/translate/adapt.rsindex 1f14152e40..b2a0cfbfcb 100644--- a/crates/environ/src/component/translate/adapt.rs+++ b/crates/environ/src/component/translate/adapt.rs@@ -205,13 +205,14 @@ impl<'data> Translator<'_, 'data> {for (module_id, adapter_module) in state.adapter_modules.iter() {let mut module = fact::Module::new(self.types.types(),+ component,self.tunables,*self.validator.features(),);let mut names = Vec::with_capacity(adapter_module.adapters.len());for adapter in adapter_module.adapters.iter() {let name = format!("adapter{}", adapter.as_u32());- module.adapt(&name, component, *adapter);+ module.adapt(&name, *adapter);names.push(name);}let wasm = module.encode();@@ -324,6 +325,9 @@ fn fact_import_to_core_def(fact::Import::ResourceTransferBorrow => {simple_intrinsic(dfg::Trampoline::ResourceTransferBorrow)}+ fact::Import::ResourceTransferBorrowToOwner => {+ simple_intrinsic(dfg::Trampoline::ResourceTransferBorrowToOwner)+ }fact::Import::PrepareCall { memory } => simple_intrinsic(dfg::Trampoline::PrepareCall {memory: memory.as_ref().map(|v| dfg.memories.push(unwrap_memory(v))),}),diff --git a/crates/environ/src/component/types.rs b/crates/environ/src/component/types.rsindex 6c8eefe054..4e3b87c6b9 100644--- a/crates/environ/src/component/types.rs+++ b/crates/environ/src/component/types.rs@@ -340,6 +340,24 @@ impl TypeTrace for ComponentTypes {}impl ComponentTypes {+ /// Returns whether the resource that `ty` points to is owned by the very+ /// instance that `ty` itself belongs to.+ pub fn resource_owned_by_own_instance(+ &self,+ ty: TypeResourceTableIndex,+ defined_resource_instance: impl FnOnce(ResourceIndex) -> Option<RuntimeComponentInstanceIndex>,+ ) -> bool {+ let (resource_ty, resource_instance) = match self[ty] {+ TypeResourceTable::Concrete { ty, instance } => (ty, instance),+ // Abstract tables don't exist at runtime, so there's nothing to+ // own them.+ TypeResourceTable::Abstract(_) => return false,+ };+ // An imported resource is never defined by, and so never owned by, an+ // instance within this component.+ defined_resource_instance(resource_ty) == Some(resource_instance)+ }+/// Returns the core wasm module types known within this component.pub fn module_types(&self) -> &ModuleTypes {self.module_types.as_ref().unwrap()diff --git a/crates/environ/src/component/types_builder.rs b/crates/environ/src/component/types_builder.rsindex 9e453f9ac2..edd64cef9b 100644--- a/crates/environ/src/component/types_builder.rs+++ b/crates/environ/src/component/types_builder.rs@@ -193,6 +193,16 @@ impl ComponentTypesBuilder {self.component_types.resource_tables.len()}+ /// Forwards to `ComponentTypes::resource_owned_by_own_instance`.+ pub fn resource_owned_by_own_instance(+ &self,+ ty: TypeResourceTableIndex,+ defined_resource_instance: impl FnOnce(ResourceIndex) -> Option<RuntimeComponentInstanceIndex>,+ ) -> bool {+ self.component_types+ .resource_owned_by_own_instance(ty, defined_resource_instance)+ }+/// Returns the number of future tables allocated so far, or the maximum/// `TypeFutureTableIndex`.pub fn num_future_tables(&self) -> usize {diff --git a/crates/environ/src/fact.rs b/crates/environ/src/fact.rsindex d20674c81c..0878fa428b 100644--- a/crates/environ/src/fact.rs+++ b/crates/environ/src/fact.rs@@ -22,7 +22,7 @@ use crate::component::dfg::{AdapterId, ComponentDfg, CoreDef};use crate::component::{AdapterOptions as AdapterOptionsDfg, CanonicalAbiInfo, ComponentTypesBuilder, FlatType,InterfaceType, RuntimeComponentInstanceIndex, StringEncoding, Transcode, TypeFuncIndex,- UnsafeIntrinsic,+ TypeResourceTableIndex, UnsafeIntrinsic,};use crate::fact::transcode::Transcoder;use crate::prelude::*;@@ -62,6 +62,9 @@ pub struct Module<'a> {/// Type information from the creator of this `Module`types: &'a ComponentTypesBuilder,+ /// The component being adapted.+ component: &'a ComponentDfg,+/// The Wasm features enabled for validation of this module.features: WasmFeatures,@@ -84,6 +87,7 @@ pub struct Module<'a> {/// Cached versions of imported trampolines for working with resources.imported_resource_transfer_own: Option<FuncIndex>,imported_resource_transfer_borrow: Option<FuncIndex>,+ imported_resource_transfer_borrow_to_owner: Option<FuncIndex>,// Cached versions of imported trampolines for working with the async ABI.imported_start_calls: HashMap<(Option<FuncIndex>, Option<FuncIndex>, Vec<ValType>), FuncIndex>,@@ -270,12 +274,14 @@ impl<'a> Module<'a> {/// Creates an empty module.pub fn new(types: &'a ComponentTypesBuilder,+ component: &'a ComponentDfg,tunables: &'a Tunables,features: WasmFeatures,) -> Module<'a> {Module {tunables,types,+ component,features,core_types: Default::default(),core_imports: Default::default(),@@ -290,6 +296,7 @@ impl<'a> Module<'a> {helper_worklist: Vec::new(),imported_resource_transfer_own: None,imported_resource_transfer_borrow: None,+ imported_resource_transfer_borrow_to_owner: None,imported_start_calls: HashMap::new(),imported_future_transfer: None,imported_stream_transfer: None,@@ -305,11 +312,11 @@ impl<'a> Module<'a> {/// Registers a new adapter within this adapter module.////// The `name` provided is the export name of the adapter from the final- /// module, and `adapter` indexes into `component` for all the metadata- /// necessary for compilation.- pub fn adapt(&mut self, name: &str, component: &ComponentDfg, adapter: AdapterId) {- let thread_transparent = component.transparent_adapters.contains(adapter);- let adapter = &component.adapters[adapter];+ /// module, and `adapter` indexes into this module's component for all the+ /// metadata necessary for compilation.+ pub fn adapt(&mut self, name: &str, adapter: AdapterId) {+ let thread_transparent = self.component.transparent_adapters.contains(adapter);+ let adapter = &self.component.adapters[adapter];// Import any items required by the various canonical options// (memories, reallocs, etc)@@ -689,6 +696,24 @@ impl<'a> Module<'a> {)}+ /// Returns whether a borrow lowered into the resource table `ty` has its+ /// resource owned by `ty`'s own instance.+ fn resource_owned_by_own_instance(&self, ty: TypeResourceTableIndex) -> bool {+ self.types+ .resource_owned_by_own_instance(ty, |idx| self.component.defined_resource_instance(idx))+ }++ fn import_resource_transfer_borrow_to_owner(&mut self) -> FuncIndex {+ self.import_simple(+ "resource",+ "transfer-borrow-to-owner",+ &[ValType::I32, ValType::I32],+ &[ValType::I32],+ Import::ResourceTransferBorrowToOwner,+ |me| &mut me.imported_resource_transfer_borrow_to_owner,+ )+ }+fn import_enter_sync_call(&mut self) -> FuncIndex {self.import_simple("async",@@ -877,6 +902,9 @@ pub enum Import {ResourceTransferOwn,/// Transfers a borrowed resource from one table to another.ResourceTransferBorrow,+ /// Lifts a borrowed resource for a destination which owns the resource and+ /// therefore receives its representation rather than a handle.+ ResourceTransferBorrowToOwner,/// An intrinsic used by FACT-generated modules to begin a call involving/// an async-lowered import and/or an async-lifted export.PrepareCall {diff --git a/crates/environ/src/fact/trampoline.rs b/crates/environ/src/fact/trampoline.rsindex 625dab433b..06e39b78ba 100644--- a/crates/environ/src/fact/trampoline.rs+++ b/crates/environ/src/fact/trampoline.rs@@ -3388,7 +3388,7 @@ impl<'a, 'b> Compiler<'a, 'b> {_ => panic!("expected a `Future`"),};let transfer = self.module.import_future_transfer();- self.translate_handle(src_ty.as_u32(), src, dst_ty.as_u32(), dst, transfer);+ self.translate_handle(src_ty.as_u32(), src, Some(dst_ty.as_u32()), dst, transfer);}fn translate_stream(@@ -3403,7 +3403,7 @@ impl<'a, 'b> Compiler<'a, 'b> {_ => panic!("expected a `Stream`"),};let transfer = self.module.import_stream_transfer();- self.translate_handle(src_ty.as_u32(), src, dst_ty.as_u32(), dst, transfer);+ self.translate_handle(src_ty.as_u32(), src, Some(dst_ty.as_u32()), dst, transfer);}fn translate_error_context(@@ -3418,7 +3418,7 @@ impl<'a, 'b> Compiler<'a, 'b> {_ => panic!("expected an `ErrorContext`"),};let transfer = self.module.import_error_context_transfer();- self.translate_handle(src_ty.as_u32(), src, dst_ty.as_u32(), dst, transfer);+ self.translate_handle(src_ty.as_u32(), src, Some(dst_ty.as_u32()), dst, transfer);}fn translate_own(@@ -3433,7 +3433,7 @@ impl<'a, 'b> Compiler<'a, 'b> {_ => panic!("expected an `Own`"),};let transfer = self.module.import_resource_transfer_own();- self.translate_handle(src_ty.as_u32(), src, dst_ty.as_u32(), dst, transfer);+ self.translate_handle(src_ty.as_u32(), src, Some(dst_ty.as_u32()), dst, transfer);}fn translate_borrow(@@ -3448,8 +3448,15 @@ impl<'a, 'b> Compiler<'a, 'b> {_ => panic!("expected an `Borrow`"),};- let transfer = self.module.import_resource_transfer_borrow();- self.translate_handle(src_ty.as_u32(), src, dst_ty.as_u32(), dst, transfer);+ let (transfer, dst_ty) = if self.module.resource_owned_by_own_instance(dst_ty) {+ (self.module.import_resource_transfer_borrow_to_owner(), None)+ } else {+ (+ self.module.import_resource_transfer_borrow(),+ Some(dst_ty.as_u32()),+ )+ };+ self.translate_handle(src_ty.as_u32(), src, dst_ty, dst, transfer);}/// Translates the index `src`, which resides in the table `src_ty`, into@@ -3463,7 +3470,7 @@ impl<'a, 'b> Compiler<'a, 'b> {&mut self,src_ty: u32,src: &Source<'_>,- dst_ty: u32,+ dst_ty: Option<u32>,dst: &Destination,transfer: FuncIndex,) {@@ -3474,7 +3481,9 @@ impl<'a, 'b> Compiler<'a, 'b> {Source::Struct(_) | Source::Array(_) => todo!("CM+GC"),}self.instruction(I32Const(src_ty as i32));- self.instruction(I32Const(dst_ty as i32));+ if let Some(dst_ty) = dst_ty {+ self.instruction(I32Const(dst_ty as i32));+ }self.instruction(Call(transfer.as_u32()));match dst {Destination::Memory(mem) => self.i32_store(mem),diff --git a/crates/wasmtime/src/runtime/component/instance.rs b/crates/wasmtime/src/runtime/component/instance.rsindex 3cef979cf1..439583f0ea 100644--- a/crates/wasmtime/src/runtime/component/instance.rs+++ b/crates/wasmtime/src/runtime/component/instance.rs@@ -429,23 +429,27 @@ impl Instance {src: TypeResourceTableIndex,dst: TypeResourceTableIndex,) -> Result<u32> {- let dst_owns_resource = self.id().get(store).resource_owned_by_own_instance(dst);+ debug_assert!(+ !self.id().get(store).resource_owned_by_own_instance(dst),+ "should have used `resource.transfer-borrow-to-owner` instead",+ );let mut tables = store.component_resource_tables(Some(self))?;let rep = tables.resource_lift_borrow(TypedResourceIndex::Component { ty: src, index })?;- // Implement `lower_borrow`'s special case here where if a borrow's- // resource type is owned by `dst` then the destination receives the- // representation directly rather than a handle to the representation.- //- // This can perhaps become a different libcall in the future to avoid- // this check at runtime since we know at compile time whether the- // destination type owns the resource, but that's left as a future- // refactoring if truly necessary.- if dst_owns_resource {- return Ok(rep);- }tables.resource_lower_borrow(TypedResource::Component { ty: dst, rep })}+ /// Variant of `resource_transfer_borrow` for when the destination instance+ /// owns the resource, and so receives the representation directly.+ pub(crate) fn resource_transfer_borrow_to_owner(+ self,+ store: &mut StoreOpaque,+ index: u32,+ src: TypeResourceTableIndex,+ ) -> Result<u32> {+ let mut tables = store.component_resource_tables(Some(self))?;+ tables.resource_lift_borrow(TypedResourceIndex::Component { ty: src, index })+ }+pub(crate) fn lookup_vmdef(&self, store: &mut StoreOpaque, def: &CoreDef) -> vm::Export {lookup_vmdef(store, self.id.instance(), def)}diff --git a/crates/wasmtime/src/runtime/vm/component.rs b/crates/wasmtime/src/runtime/vm/component.rsindex e8a276411a..57629a19fa 100644--- a/crates/wasmtime/src/runtime/vm/component.rs+++ b/crates/wasmtime/src/runtime/vm/component.rs@@ -848,16 +848,10 @@ impl ComponentInstance {/// This is used when lowering borrows to skip table management and instead/// thread through the underlying representation directly.pub fn resource_owned_by_own_instance(&self, ty: TypeResourceTableIndex) -> bool {- let (resource_ty, resource_instance) = match self.component.types()[ty] {- TypeResourceTable::Concrete { ty, instance } => (ty, instance),- TypeResourceTable::Abstract(_) => return false,- };let component = self.component.env_component();- let idx = match component.defined_resource_index(resource_ty) {- Some(idx) => idx,- None => return false,- };- resource_instance == component.defined_resource_instances[idx]+ self.component+ .types()+ .resource_owned_by_own_instance(ty, |idx| component.defined_resource_instance(idx))}/// Returns the runtime state of resources and concurrency associated with@@ -897,10 +891,10 @@ impl ComponentInstance {let dtor = self.resource_destructor(resource);let component = self.component.env_component();let instance = component- .defined_resource_index(resource)- .map(|i| RuntimeInstance {+ .defined_resource_instance(resource)+ .map(|index| RuntimeInstance {instance: self.id(),- index: component.defined_resource_instances[i],+ index,});(dtor, instance)}diff --git a/crates/wasmtime/src/runtime/vm/component/libcalls.rs b/crates/wasmtime/src/runtime/vm/component/libcalls.rsindex 83f8e53405..3319476598 100644--- a/crates/wasmtime/src/runtime/vm/component/libcalls.rs+++ b/crates/wasmtime/src/runtime/vm/component/libcalls.rs@@ -668,6 +668,16 @@ fn resource_transfer_borrow(instance.resource_transfer_borrow(store, src_idx, src_table, dst_table)}+fn resource_transfer_borrow_to_owner(+ store: &mut dyn VMStore,+ instance: Instance,+ src_idx: u32,+ src_table: u32,+) -> Result<u32> {+ let src_table = TypeResourceTableIndex::from_u32(src_table);+ instance.resource_transfer_borrow_to_owner(store, src_idx, src_table)+}+fn enter_sync_call(store: &mut dyn VMStore,instance: Instance,diff --git a/tests/misc_testsuite/component-model/borrow-transfer-to-owner.wast b/tests/misc_testsuite/component-model/borrow-transfer-to-owner.wastnew file mode 100644index 0000000000..de4b0809ef--- /dev/null+++ b/tests/misc_testsuite/component-model/borrow-transfer-to-owner.wast@@ -0,0 +1,167 @@+;; Guest-to-guest `borrow` transfers on both sides of FACT's choice between+;; `resource.transfer-borrow-to-owner` and `resource.transfer-borrow`.++;; The callee defines the resource, so `borrow` params arrive as reps.+(component+ (component $A+ (type $t' (resource (rep i32)))+ (export $t "t" (type $t'))++ (core func $ctor (canon resource.new $t))++ (core module $m+ ;; The offset tells a rep apart from a handle index.+ (func (export "[method]t.get") (param i32) (result i32)+ (i32.add (local.get 0) (i32.const 100)))++ ;; Never reached: lifting `b` traps, `self` already lent the handle out.+ (func (export "[method]t.take-own") (param i32) (param i32)+ (unreachable))+ )+ (core instance $i (instantiate $m))++ (func (export "[constructor]t") (param "x" u32) (result (own $t))+ (canon lift (core func $ctor)))+ (func (export "[method]t.get") (param "self" (borrow $t)) (result u32)+ (canon lift (core func $i "[method]t.get")))+ (func (export "[method]t.take-own") (param "self" (borrow $t)) (param "b" (own $t))+ (canon lift (core func $i "[method]t.take-own")))+ )+ (instance $a (instantiate $A))++ (component $B+ (import "a" (instance $i+ (export "t" (type $t (sub resource)))+ (export "[constructor]t" (func (param "x" u32) (result (own $t))))+ (export "[method]t.get" (func (param "self" (borrow $t)) (result u32)))+ (export "[method]t.take-own" (func (param "self" (borrow $t)) (param "b" (own $t))))+ ))++ (alias export $i "t" (type $t))+ (alias export $i "[constructor]t" (func $ctor))+ (alias export $i "[method]t.get" (func $get))+ (alias export $i "[method]t.take-own" (func $take-own))++ (core func $ctor' (canon lower (func $ctor)))+ (core func $get' (canon lower (func $get)))+ (core func $take-own' (canon lower (func $take-own)))+ (core func $drop (canon resource.drop $t))++ (core module $m+ (import "" "ctor" (func $ctor (param i32) (result i32)))+ (import "" "get" (func $get (param i32) (result i32)))+ (import "" "take-own" (func $take-own (param i32 i32)))+ (import "" "drop" (func $drop (param i32)))++ (func (export "get") (param i32) (result i32)+ (local $h i32) (local $v i32)+ (local.set $h (call $ctor (local.get 0)))+ (local.set $v (call $get (local.get $h)))+ (call $drop (local.get $h))+ (local.get $v))++ (func (export "lend-then-give-away")+ (local $h i32)+ (local.set $h (call $ctor (i32.const 100)))+ (call $take-own (local.get $h) (local.get $h)))+ )+ (core instance $i2 (instantiate $m (with "" (instance+ (export "ctor" (func $ctor'))+ (export "get" (func $get'))+ (export "take-own" (func $take-own'))+ (export "drop" (func $drop))))))++ (func (export "get") (param "x" u32) (result u32)+ (canon lift (core func $i2 "get")))+ (func (export "lend-then-give-away")+ (canon lift (core func $i2 "lend-then-give-away")))+ )+ (instance $b (instantiate $B (with "a" (instance $a))))+ (export "get" (func $b "get"))+ (export "lend-then-give-away" (func $b "lend-then-give-away"))+)++(assert_return (invoke "get" (u32.const 42)) (u32.const 142))+(assert_trap (invoke "lend-then-give-away") "cannot remove owned resource while borrowed")++;; Neither guest defines the host's resource, so `borrow` params arrive as+;; handles, which the callee must drop.+(component+ (import "host" (instance $host+ (export "resource1" (type $r (sub resource)))+ (export "[constructor]resource1" (func (param "r" u32) (result (own $r))))+ ))+ (alias export $host "resource1" (type $r))+ (alias export $host "[constructor]resource1" (func $ctor))++ (component $A+ (import "t" (type $t (sub resource)))+ (core func $drop (canon resource.drop $t))+ (core module $m+ (import "" "drop" (func $drop (param i32)))+ (func (export "get") (param i32) (result i32)+ (call $drop (local.get 0))+ (i32.add (local.get 0) (i32.const 1000)))+ )+ (core instance $i (instantiate $m+ (with "" (instance (export "drop" (func $drop))))))+ (func (export "get") (param "self" (borrow $t)) (result u32)+ (canon lift (core func $i "get")))+ )+ (instance $a (instantiate $A (with "t" (type $r))))++ (component $B+ (import "t" (type $t (sub resource)))+ (import "a" (instance $i+ (export "get" (func (param "self" (borrow $t)) (result u32)))+ ))+ (alias export $i "get" (func $get))++ (core func $get' (canon lower (func $get)))+ (core func $drop (canon resource.drop $t))+ (core module $m+ (import "" "get" (func $get (param i32) (result i32)))+ (import "" "drop" (func $drop (param i32)))+ (func (export "get") (param i32) (result i32)+ (local $v i32)+ (local.set $v (call $get (local.get 0)))+ (call $drop (local.get 0))+ (local.get $v))+ )+ (core instance $i2 (instantiate $m (with "" (instance+ (export "get" (func $get'))+ (export "drop" (func $drop))))))+ (func (export "get") (param "self" (borrow $t)) (result u32)+ (canon lift (core func $i2 "get")))+ )+ (instance $b (instantiate $B+ (with "t" (type $r))+ (with "a" (instance $a))))+ (alias export $b "get" (func $b-get))++ ;; The host owns the resource, so this outermost component is not the owner+ ;; either: it creates an `own` handle via the host constructor and lends it+ ;; down the chain, which is what gets `A` and `B` actually executed.+ (core func $ctor' (canon lower (func $ctor)))+ (core func $b-get' (canon lower (func $b-get)))+ (core func $drop (canon resource.drop $r))+ (core module $m+ (import "" "ctor" (func $ctor (param i32) (result i32)))+ (import "" "get" (func $get (param i32) (result i32)))+ (import "" "drop" (func $drop (param i32)))+ (func (export "run") (param i32) (result i32)+ (local $h i32) (local $v i32)+ (local.set $h (call $ctor (local.get 0)))+ (local.set $v (call $get (local.get $h)))+ (call $drop (local.get $h))+ (local.get $v))+ )+ (core instance $i (instantiate $m (with "" (instance+ (export "ctor" (func $ctor'))+ (export "get" (func $b-get'))+ (export "drop" (func $drop))))))+ (func (export "run") (param "x" u32) (result u32)+ (canon lift (core func $i "run")))+)++(assert_return (invoke "run" (u32.const 42)) (u32.const 1001))