A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Track lends of borrows in the face of async (#14580)
Alex Crichton4d953159b9e2
diff --git a/crates/wasmtime/src/runtime/component/resources/any.rs b/crates/wasmtime/src/runtime/component/resources/any.rsindex 18b265cb44..225825051f 100644--- a/crates/wasmtime/src/runtime/component/resources/any.rs+++ b/crates/wasmtime/src/runtime/component/resources/any.rs@@ -130,6 +130,9 @@ impl ResourceAny {////// # Errors///+ /// See [`Resource::try_from_resource_any`] for the conditions under which+ /// this conversion fails.+ ////// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when/// memory allocation fails. See the `OutOfMemory` type's documentation for/// details on Wasmtime's out-of-memory handling.@@ -143,6 +146,11 @@ impl ResourceAny {/// This conversion accepts only host-defined resources. Guest-defined/// resources must remain [`ResourceAny`] values and be used through their/// generated functions and resource projection.+ ///+ /// # Errors+ ///+ /// See [`Resource::try_from_resource_any`] for the conditions under which+ /// this conversion fails.pub fn try_into_resource_dynamic(self, store: impl AsContextMut) -> Result<ResourceDynamic> {ResourceDynamic::try_from_resource_any(self, store)}@@ -171,8 +179,8 @@ impl ResourceAny {Ok(HostResource::new_own(rep, ty))} else {// Typed borrows have no dynamic state. Remove the table- // entry after lifting its representation.- let rep = tables.host_resource_lift_borrow(idx)?;+ // entry after reading its representation.+ let rep = tables.host_resource_rep(idx)?;let res = tables.host_resource_drop(idx)?;assert!(res.is_none());Ok(HostResource::new_borrow(rep, ty))diff --git a/crates/wasmtime/src/runtime/component/resources/host_static.rs b/crates/wasmtime/src/runtime/component/resources/host_static.rsindex a85cfefa0f..b9f997f42d 100644--- a/crates/wasmtime/src/runtime/component/resources/host_static.rs+++ b/crates/wasmtime/src/runtime/component/resources/host_static.rs@@ -199,7 +199,9 @@ where////// This function will return an error if `resource` does not have type/// `ResourceType::host::<T>()`. This function may also return an error if- /// `resource` is no longer valid, for example it was previously converted.+ /// `resource` is no longer valid, for example it was previously converted,+ /// or if `resource` is a borrow which is currently lent out to an+ /// in-progress call.////// # Panics///diff --git a/crates/wasmtime/src/runtime/component/resources/host_tables.rs b/crates/wasmtime/src/runtime/component/resources/host_tables.rsindex 7c315ba4da..74ca89871f 100644--- a/crates/wasmtime/src/runtime/component/resources/host_tables.rs+++ b/crates/wasmtime/src/runtime/component/resources/host_tables.rs@@ -125,7 +125,6 @@ impl<'a> HostResourceTables<'a> {/// Validates that `idx` still refers to a live host-owned resource and/// returns its `rep`, without consuming it or lending it out.- #[cfg(feature = "component-model-async")]pub fn host_resource_rep(&mut self, idx: HostResourceIndex) -> Result<u32> {let (idx, _) = self.validate_host_index(idx, false)?;self.tables.resource_rep(TypedResourceIndex::Host(idx))diff --git a/crates/wasmtime/src/runtime/vm/component/handle_table.rs b/crates/wasmtime/src/runtime/vm/component/handle_table.rsindex 4f48010acd..978500ad44 100644--- a/crates/wasmtime/src/runtime/vm/component/handle_table.rs+++ b/crates/wasmtime/src/runtime/vm/component/handle_table.rs@@ -66,9 +66,13 @@ enum Slot {////// The `rep` is listed and dropping this borrow will decrement the borrow/// count of the `scope`.+ ///+ /// Like `ResourceOwn` the `lend_count` tracks how many times this borrow+ /// has been lent out to other calls, and if nonzero this can't be removed.ResourceBorrow {resource: TypedResource,scope: Scope,+ lend_count: u32,},/// Represents a host task handle.@@ -199,7 +203,11 @@ impl HandleTable {/// specified by `resource`. The `scope` specified is used by/// `CallContexts` to manage lending information.pub fn resource_borrow_insert(&mut self, resource: TypedResource, scope: Scope) -> Result<u32> {- self.insert(Slot::ResourceBorrow { resource, scope })+ self.insert(Slot::ResourceBorrow {+ resource,+ scope,+ lend_count: 0,+ })}/// Returns the internal "rep" of the resource specified by `idx`.@@ -218,42 +226,46 @@ impl HandleTable {/// Accesses the "rep" of the resource pointed to by `idx` as part of a/// lending operation.///- /// This will increase `lend_count` for owned resources and must be paired- /// with a `resource_undo_lend` below later on (managed by `CallContexts`).+ /// This will increase `lend_count` for both `own` and `borrow` handles and+ /// must be paired with a `resource_undo_lend` below later on (managed by+ /// `CallContexts`).///- /// Upon success returns the "rep" plus whether the borrow came from an- /// `own` handle.- pub fn resource_lend(&mut self, idx: TypedResourceIndex) -> Result<(u32, bool)> {+ /// Upon success returns the "rep" of the resource.+ pub fn resource_lend(&mut self, idx: TypedResourceIndex) -> Result<u32> {match self.get_mut(idx.raw_index())? {Slot::ResourceOwn {resource,lend_count,+ }+ | Slot::ResourceBorrow {+ resource,+ lend_count,+ ..} => {let rep = resource.rep(&idx)?;*lend_count = lend_count.checked_add(1).unwrap();- Ok((rep, true))+ Ok(rep)}- Slot::ResourceBorrow { resource, .. } => Ok((resource.rep(&idx)?, false)),_ => bail!("index {} is not a resource", idx.raw_index()),}}- /// For `own` resources that were borrowed in `resource_lend`, undoes the- /// lending operation.+ /// Undoes a lending operation previously performed by `resource_lend`.pub fn resource_undo_lend(&mut self, idx: TypedResourceIndex) -> Result<()> {match self.get_mut(idx.raw_index())? {- Slot::ResourceOwn { lend_count, .. } => {+ Slot::ResourceOwn { lend_count, .. } | Slot::ResourceBorrow { lend_count, .. } => {*lend_count -= 1;Ok(())}- _ => bail!("index {} is not an own resource", idx.raw_index()),+ _ => bail!("index {} is not a resource", idx.raw_index()),}}/// Removes the resource specified by `idx` from the table.////// This can fail if `idx` doesn't point to a resource, points to a- /// borrowed resource, or points to a resource of the wrong type.+ /// resource (own or borrow) which is currently lent out, or points to a+ /// resource of the wrong type.pub fn remove_resource(&mut self, idx: TypedResourceIndex) -> Result<RemovedResource> {let ret = match self.get_mut(idx.raw_index())? {Slot::ResourceOwn {@@ -267,9 +279,16 @@ impl HandleTable {rep: resource.rep(&idx)?,}}- Slot::ResourceBorrow { resource, scope } => {+ Slot::ResourceBorrow {+ resource,+ scope,+ lend_count,+ } => {// Ensure the drop is done with the right typeresource.rep(&idx)?;+ if *lend_count != 0 {+ bail!("cannot remove borrowed resource while it is lent out")+ }RemovedResource::Borrow { scope: *scope }}_ => bail!("index {} is not a resource", idx.raw_index()),diff --git a/crates/wasmtime/src/runtime/vm/component/resources.rs b/crates/wasmtime/src/runtime/vm/component/resources.rsindex 8f0895bfee..a8039af1a0 100644--- a/crates/wasmtime/src/runtime/vm/component/resources.rs+++ b/crates/wasmtime/src/runtime/vm/component/resources.rs@@ -246,7 +246,7 @@ impl ResourceTables<'_> {/// the specified table. This operation can fail if:////// * The index is invalid.- /// * The index points to an `own` resource which has active borrows.+ /// * The index points to a resource which has been lent out./// * The index's type is mismatched with the entry in the table's type.////// Otherwise this will return `Some(rep)` if the destructor for `rep` needs@@ -335,17 +335,20 @@ impl ResourceTables<'_> {/// Extracts the underlying resource representation by lifting a "borrow"/// from the tables.///- /// This primarily employs dynamic tracking when a borrow is created from an- /// "own" handle to ensure that the "own" handle isn't dropped while the- /// borrow is active and additionally that when the current call scope- /// returns the lend operation is undone.+ /// This primarily employs dynamic tracking when a borrow is created from+ /// either an "own" or a "borrow" handle to ensure that the lending handle+ /// isn't dropped while the borrow is active and additionally that when the+ /// current call scope returns the lend operation is undone.////// This is an implementation of the canonical ABI `lift_borrow` function.pub fn resource_lift_borrow(&mut self, index: TypedResourceIndex) -> Result<u32> {- let (rep, is_own) = self.table_for_index(&index).resource_lend(index)?;- if is_own {- self.current_scope()?.lenders.push(index);- }+ // FIXME: the logic here applies to all resources, both own and borrow,+ // although tracking `borrow` here isn't always necessary for sync+ // tasks. Ideally the `lenders.push` would be skipped for sync tasks but+ // that requires a bit more plumbing and also appropriately tracking the+ // `lend_count` and such. For now this treats own/borrow the same way.+ let rep = self.table_for_index(&index).resource_lend(index)?;+ self.current_scope()?.lenders.push(index);Ok(rep)}diff --git a/tests/misc_testsuite/component-model/async/borrow-lend-async.wast b/tests/misc_testsuite/component-model/async/borrow-lend-async.wastnew file mode 100644index 0000000000..f5a10d50af--- /dev/null+++ b/tests/misc_testsuite/component-model/async/borrow-lend-async.wast@@ -0,0 +1,176 @@+;;! component_model_async = true++;; A lends an own handle to an async callee B which holds the borrow across+;; yields, waits, and cancellation.+;;+;; mode 0: B drops the borrow and returns immediately+;; mode 1: B returns without dropping the borrow (traps)+;; mode 2: B yields, then drops the borrow and returns+;; mode 3: B yields, and A drops the own handle while it's lent (traps)+;; mode 4: B waits, is cancelled, and cancels without dropping the borrow+;; (traps)+;; mode 5: B waits, is cancelled, and drops the borrow before cancelling++(component definition $C+ (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 $B+ (import "r" (type $r (sub resource)))+ (core func $resource.drop (canon resource.drop $r))+ (core func $task.return (canon task.return))+ (core func $task.cancel (canon task.cancel))+ (core func $waitable-set.new (canon waitable-set.new))+ (core module $m+ (import "" "resource.drop" (func $resource.drop (param i32)))+ (import "" "task.return" (func $task.return))+ (import "" "task.cancel" (func $task.cancel))+ (import "" "waitable-set.new" (func $waitable-set.new (result i32)))+ (global $b (mut i32) (i32.const 0))+ (global $mode (mut i32) (i32.const 0))+ (func (export "f") (param $x i32) (param $mode i32) (result i32)+ (global.set $b (local.get $x))+ ;; mode 0: drop + return+ (if (i32.eq (local.get $mode) (i32.const 0)) (then+ (call $resource.drop (local.get $x))+ (call $task.return)+ (return (i32.const 0 (; EXIT ;)))))+ ;; mode 1: return without dropping borrow -> must trap+ (if (i32.eq (local.get $mode) (i32.const 1)) (then+ (call $task.return)+ (return (i32.const 0 (; EXIT ;)))))+ (global.set $mode (local.get $mode))+ ;; mode 4/5: wait forever (until cancelled) holding borrow+ (if (i32.ge_u (local.get $mode) (i32.const 4)) (then+ (return+ (i32.or+ (i32.const 2 (; WAIT ;))+ (i32.shl (call $waitable-set.new) (i32.const 4))))))+ ;; mode 2/3: yield while holding borrow+ (i32.const 1 (; YIELD ;)))+ (func (export "cb") (param $ev i32) (param i32 i32) (result i32)+ (if (i32.ge_u (global.get $mode) (i32.const 4)) (then+ (if (i32.ne (local.get $ev) (i32.const 6 (; TASK_CANCELLED ;)))+ (then unreachable))+ (if (i32.eq (global.get $mode) (i32.const 5)) (then+ (call $resource.drop (global.get $b))))+ (call $task.cancel)+ (return (i32.const 0 (; EXIT ;)))))+ (call $resource.drop (global.get $b))+ (call $task.return)+ (i32.const 0 (; EXIT ;)))+ )+ (core instance $i (instantiate $m (with "" (instance+ (export "resource.drop" (func $resource.drop))+ (export "task.return" (func $task.return))+ (export "task.cancel" (func $task.cancel))+ (export "waitable-set.new" (func $waitable-set.new))+ ))))+ (func (export "f") async (param "x" (borrow $r)) (param "mode" u32)+ (canon lift (core func $i "f") async (callback (core func $i "cb"))))+ )+ (instance $b (instantiate $B (with "r" (type $r))))++ (component $A+ (import "r" (type $r (sub resource)))+ (import "ctor" (func $ctor (param "r" u32) (result (own $r))))+ (import "f" (func $f async (param "x" (borrow $r)) (param "mode" u32)))+ (core func $ctor (canon lower (func $ctor)))+ (core func $f (canon lower (func $f) async))+ (core func $resource.drop (canon resource.drop $r))+ (core func $waitable-set.new (canon waitable-set.new))+ (core func $waitable.join (canon waitable.join))+ (core func $subtask.drop (canon subtask.drop))+ (core func $task.return (canon task.return))+ (core func $subtask.cancel (canon subtask.cancel))+ (core module $m+ (import "" "ctor" (func $ctor (param i32) (result i32)))+ (import "" "f" (func $f (param i32 i32) (result i32)))+ (import "" "resource.drop" (func $resource.drop (param i32)))+ (import "" "waitable-set.new" (func $waitable-set.new (result i32)))+ (import "" "waitable.join" (func $waitable.join (param i32 i32)))+ (import "" "subtask.drop" (func $subtask.drop (param i32)))+ (import "" "task.return" (func $task.return))+ (import "" "subtask.cancel"+ (func $subtask.cancel (param i32) (result i32)))+ (global $h (mut i32) (i32.const 0))+ (global $s (mut i32) (i32.const 0))+ (func (export "run") (param $mode i32) (result i32)+ (local $h i32) (local $s i32) (local $ws i32)+ (local.set $h (call $ctor (i32.const 7)))+ (local.set $s (call $f (local.get $h) (local.get $mode)))+ (if (i32.eq (i32.and (local.get $s) (i32.const 0xf))+ (i32.const 1 (; STARTED ;))) (then+ (local.set $s (i32.shr_u (local.get $s) (i32.const 4)))+ ;; mode 3: drop the own while it's lent -> must trap+ (if (i32.eq (local.get $mode) (i32.const 3)) (then+ (call $resource.drop (local.get $h))))+ (if (i32.ge_u (local.get $mode) (i32.const 4)) (then+ (if (i32.ne (call $subtask.cancel (local.get $s))+ (i32.const 4 (; RETURN_CANCELLED ;)))+ (then unreachable))+ (call $subtask.drop (local.get $s))+ (call $resource.drop (local.get $h))+ (call $task.return)+ (return (i32.const 0 (; EXIT ;)))))+ ;; mode 2: wait for the subtask to return, finishing in `cb`+ (global.set $h (local.get $h))+ (global.set $s (local.get $s))+ (local.set $ws (call $waitable-set.new))+ (call $waitable.join (local.get $s) (local.get $ws))+ (return+ (i32.or+ (i32.const 2 (; WAIT ;))+ (i32.shl (local.get $ws) (i32.const 4))))))+ (call $resource.drop (local.get $h))+ (call $task.return)+ (i32.const 0 (; EXIT ;)))+ (func (export "cb")+ (param $ev i32) (param $idx i32) (param $code i32) (result i32)+ (if (i32.ne (local.get $ev) (i32.const 1 (; SUBTASK ;)))+ (then unreachable))+ (if (i32.ne (local.get $idx) (global.get $s)) (then unreachable))+ (if (i32.ne (local.get $code) (i32.const 2 (; RETURNED ;)))+ (then unreachable))+ (call $subtask.drop (global.get $s))+ (call $resource.drop (global.get $h))+ (call $task.return)+ (i32.const 0 (; EXIT ;)))+ )+ (core instance $i (instantiate $m (with "" (instance+ (export "ctor" (func $ctor))+ (export "f" (func $f))+ (export "resource.drop" (func $resource.drop))+ (export "waitable-set.new" (func $waitable-set.new))+ (export "waitable.join" (func $waitable.join))+ (export "subtask.drop" (func $subtask.drop))+ (export "task.return" (func $task.return))+ (export "subtask.cancel" (func $subtask.cancel))+ ))))+ (func (export "run") async (param "mode" u32)+ (canon lift (core func $i "run") async (callback (core func $i "cb"))))+ )+ (instance $a (instantiate $A+ (with "r" (type $r))+ (with "ctor" (func $ctor))+ (with "f" (func $b "f"))))+ (func (export "run") (alias export $a "run"))+)++(component instance $c0 $C)+(assert_return (invoke "run" (u32.const 0)))+(component instance $c1 $C)+(assert_trap (invoke "run" (u32.const 1)) "borrow handles still remain")+(component instance $c2 $C)+(assert_return (invoke "run" (u32.const 2)))+(component instance $c3 $C)+(assert_trap (invoke "run" (u32.const 3))+ "cannot remove owned resource while borrowed")+(component instance $c4 $C)+(assert_trap (invoke "run" (u32.const 4)) "borrow handles still remain")+(component instance $c5 $C)+(assert_return (invoke "run" (u32.const 5)))diff --git a/tests/misc_testsuite/component-model/async/borrow-relend.wast b/tests/misc_testsuite/component-model/async/borrow-relend.wastnew file mode 100644index 0000000000..9ab08f0178--- /dev/null+++ b/tests/misc_testsuite/component-model/async/borrow-relend.wast@@ -0,0 +1,389 @@+;;! component_model_async = true++;; A lends own<r> `h` to B (async). B re-lends its borrow `b` to C (async),+;; then drops `b` while C's subtask is still unresolved and still holds a+;; borrow derived from it. Per the canonical ABI `lift_borrow` adds a lender+;; for *any* handle, and `resource.drop` traps if the handle has any+;; outstanding lends, so B's `resource.drop` must trap. If it didn't then B+;; could return, A would destroy the resource, and C would still be able to use+;; its borrow of a destroyed resource.+(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))++ ;; C: holds a borrow across a yield.+ (component $C+ (import "r" (type $r (sub resource)))+ (core module $m+ (func (export "g") (param i32) (result i32)+ (i32.const 1 (; YIELD ;)))+ (func (export "cb") (param i32 i32 i32) (result i32) unreachable))+ (core instance $i (instantiate $m))+ (func (export "g") async (param "x" (borrow $r))+ (canon lift (core func $i "g") async (callback (core func $i "cb"))))+ )+ (instance $c (instantiate $C (with "r" (type $r))))++ ;; B: re-lends its borrow to C, then drops it, which traps.+ (component $B+ (import "r" (type $r (sub resource)))+ (import "g" (func $g async (param "x" (borrow $r))))+ (core func $g (canon lower (func $g) async))+ (core func $resource.drop (canon resource.drop $r))+ (core module $m+ (import "" "g" (func $g (param i32) (result i32)))+ (import "" "resource.drop" (func $resource.drop (param i32)))+ (func (export "f") (param $x i32) (result i32)+ ;; C starts and yields, so this must be STARTED+ (if (i32.ne (i32.and (call $g (local.get $x)) (i32.const 0xf))+ (i32.const 1 (; STARTED ;)))+ (then unreachable))+ ;; `x` is lent to C's unresolved subtask, so this traps+ (call $resource.drop (local.get $x))+ unreachable)+ (func (export "cb") (param i32 i32 i32) (result i32) unreachable))+ (core instance $i (instantiate $m (with "" (instance+ (export "g" (func $g))+ (export "resource.drop" (func $resource.drop))))))+ (func (export "f") async (param "x" (borrow $r))+ (canon lift (core func $i "f") async (callback (core func $i "cb"))))+ )+ (instance $b (instantiate $B (with "r" (type $r)) (with "g" (func $c "g"))))++ ;; A: lends an own handle to B.+ (component $A+ (import "r" (type $r (sub resource)))+ (import "ctor" (func $ctor (param "r" u32) (result (own $r))))+ (import "f" (func $f async (param "x" (borrow $r))))+ (core func $ctor (canon lower (func $ctor)))+ (core func $f (canon lower (func $f) async))+ (core module $m+ (import "" "ctor" (func $ctor (param i32) (result i32)))+ (import "" "f" (func $f (param i32) (result i32)))+ (func (export "run") (result i32)+ (drop (call $f (call $ctor (i32.const 42))))+ unreachable)+ (func (export "cb") (param i32 i32 i32) (result i32) unreachable))+ (core instance $i (instantiate $m (with "" (instance+ (export "ctor" (func $ctor))+ (export "f" (func $f))))))+ (func (export "run") async+ (canon lift (core func $i "run") async (callback (core func $i "cb"))))+ )+ (instance $a (instantiate $A+ (with "r" (type $r))+ (with "ctor" (func $ctor))+ (with "f" (func $b "f"))))+ (func (export "run") (alias export $a "run"))+)++(assert_trap (invoke "run")+ "cannot remove borrowed resource while it is lent out")++;; Variations on the above where B re-lends its borrow to C and then drops its+;; borrow only once C's lend has been released, which is all valid.+(component definition $C+ (import "host" (instance $host+ (export "resource1" (type $r (sub resource)))+ (export "[constructor]resource1" (func (param "r" u32) (result (own $r))))+ (export "[static]resource1.drops" (func (result u32)))+ ))+ (alias export $host "resource1" (type $r))+ (alias export $host "[constructor]resource1" (func $ctor))+ (alias export $host "[static]resource1.drops" (func $drops))++ ;; C: takes a borrow and holds it until it's resumed or cancelled.+ ;;+ ;; mode 0: YIELD, then drop the borrow and return+ ;; mode 1: WAIT forever, and when cancelled drop the borrow and cancel+ ;; mode 2: WAIT forever, and when cancelled cancel without dropping the+ ;; borrow (traps)+ (component $C+ (import "r" (type $r (sub resource)))+ (core func $resource.drop (canon resource.drop $r))+ (core func $task.return (canon task.return))+ (core func $task.cancel (canon task.cancel))+ (core func $waitable-set.new (canon waitable-set.new))+ (core module $m+ (import "" "resource.drop" (func $resource.drop (param i32)))+ (import "" "task.return" (func $task.return))+ (import "" "task.cancel" (func $task.cancel))+ (import "" "waitable-set.new" (func $waitable-set.new (result i32)))+ (global $b (mut i32) (i32.const 0))+ (global $mode (mut i32) (i32.const 0))+ (func (export "g") (param $x i32) (param $mode i32) (result i32)+ (global.set $b (local.get $x))+ (global.set $mode (local.get $mode))+ (if (i32.eqz (local.get $mode)) (then (return (i32.const 1)))) ;; YIELD+ ;; WAIT on an empty waitable set+ (i32.or (i32.const 2) (i32.shl (call $waitable-set.new) (i32.const 4))))+ (func (export "cb") (param $ev i32) (param i32 i32) (result i32)+ (if (i32.eqz (global.get $mode)) (then+ (call $resource.drop (global.get $b))+ (call $task.return)+ (return (i32.const 0))))+ ;; EVENT_TASK_CANCELLED+ (if (i32.ne (local.get $ev) (i32.const 6)) (then unreachable))+ (if (i32.eq (global.get $mode) (i32.const 1)) (then+ (call $resource.drop (global.get $b))))+ (call $task.cancel)+ (i32.const 0))+ )+ (core instance $i (instantiate $m (with "" (instance+ (export "resource.drop" (func $resource.drop))+ (export "task.return" (func $task.return))+ (export "task.cancel" (func $task.cancel))+ (export "waitable-set.new" (func $waitable-set.new))+ ))))+ (func (export "g") async (param "x" (borrow $r)) (param "mode" u32)+ (canon lift (core func $i "g") async (callback (core func $i "cb"))))+ )+ (instance $c (instantiate $C (with "r" (type $r))))++ ;; B: re-lends its borrow to C and drops it after C has resolved.+ ;;+ ;; mode 0: async call to C which yields, wait for it to return+ ;; mode 1: async call to C, cancel it, and C drops its borrow+ ;; mode 2: async call to C, cancel it, and C keeps its borrow (traps)+ ;; mode 3: sync call to C+ (component $B+ (import "r" (type $r (sub resource)))+ (import "g" (func $g async (param "x" (borrow $r)) (param "mode" u32)))+ (core func $g.async (canon lower (func $g) async))+ (core func $g.sync (canon lower (func $g)))+ (core func $resource.drop (canon resource.drop $r))+ (core func $task.return (canon task.return))+ (core func $waitable-set.new (canon waitable-set.new))+ (core func $waitable.join (canon waitable.join))+ (core func $subtask.drop (canon subtask.drop))+ (core func $subtask.cancel (canon subtask.cancel))+ (core module $m+ (import "" "g.async" (func $g.async (param i32 i32) (result i32)))+ (import "" "g.sync" (func $g.sync (param i32 i32)))+ (import "" "resource.drop" (func $resource.drop (param i32)))+ (import "" "task.return" (func $task.return))+ (import "" "waitable-set.new" (func $waitable-set.new (result i32)))+ (import "" "waitable.join" (func $waitable.join (param i32 i32)))+ (import "" "subtask.drop" (func $subtask.drop (param i32)))+ (import "" "subtask.cancel"+ (func $subtask.cancel (param i32) (result i32)))+ (global $x (mut i32) (i32.const 0))+ (global $s (mut i32) (i32.const 0))+ (func (export "f") (param $x i32) (param $mode i32) (result i32)+ (local $s i32) (local $ws i32)+ (global.set $x (local.get $x))++ (if (i32.eq (local.get $mode) (i32.const 3)) (then+ (call $g.sync (local.get $x) (i32.const 0))+ (call $resource.drop (local.get $x))+ (call $task.return)+ (return (i32.const 0))))++ (local.set $s (call $g.async (local.get $x) (local.get $mode)))+ ;; STARTED+ (if (i32.ne (i32.and (local.get $s) (i32.const 0xf)) (i32.const 1))+ (then unreachable))+ (local.set $s (i32.shr_u (local.get $s) (i32.const 4)))+ (global.set $s (local.get $s))++ (if (i32.eqz (local.get $mode)) (then+ (local.set $ws (call $waitable-set.new))+ (call $waitable.join (local.get $s) (local.get $ws))+ ;; WAIT for C to return+ (return ;; WAIT+ (i32.or (i32.const 2) (i32.shl (local.get $ws) (i32.const 4))))))++ ;; RETURN_CANCELLED+ (if (i32.ne (call $subtask.cancel (local.get $s)) (i32.const 4))+ (then unreachable))+ (call $subtask.drop (local.get $s))+ (call $resource.drop (local.get $x))+ (call $task.return)+ (i32.const 0))+ (func (export "cb")+ (param $ev i32) (param $s i32) (param $status i32) (result i32)+ ;; EVENT_SUBTASK for C with RETURNED+ (if (i32.ne (local.get $ev) (i32.const 1)) (then unreachable))+ (if (i32.ne (local.get $s) (global.get $s)) (then unreachable))+ (if (i32.ne (local.get $status) (i32.const 2)) (then unreachable))+ (call $subtask.drop (global.get $s))+ (call $resource.drop (global.get $x))+ (call $task.return)+ (i32.const 0))+ )+ (core instance $i (instantiate $m (with "" (instance+ (export "g.async" (func $g.async))+ (export "g.sync" (func $g.sync))+ (export "resource.drop" (func $resource.drop))+ (export "task.return" (func $task.return))+ (export "waitable-set.new" (func $waitable-set.new))+ (export "waitable.join" (func $waitable.join))+ (export "subtask.drop" (func $subtask.drop))+ (export "subtask.cancel" (func $subtask.cancel))+ ))))+ (func (export "f") async (param "x" (borrow $r)) (param "mode" u32)+ (canon lift (core func $i "f") async (callback (core func $i "cb"))))+ )+ (instance $b (instantiate $B (with "r" (type $r)) (with "g" (func $c "g"))))++ ;; A: lends an own handle to B, then destroys it and returns how many+ ;; resources were destroyed during the call.+ (component $A+ (import "r" (type $r (sub resource)))+ (import "ctor" (func $ctor (param "r" u32) (result (own $r))))+ (import "drops" (func $drops (result u32)))+ (import "f" (func $f async (param "x" (borrow $r)) (param "mode" u32)))+ (core func $ctor (canon lower (func $ctor)))+ (core func $drops (canon lower (func $drops)))+ (core func $f (canon lower (func $f)))+ (core func $resource.drop (canon resource.drop $r))+ (core func $task.return (canon task.return (result u32)))+ (core module $m+ (import "" "ctor" (func $ctor (param i32) (result i32)))+ (import "" "drops" (func $drops (result i32)))+ (import "" "f" (func $f (param i32 i32)))+ (import "" "resource.drop" (func $resource.drop (param i32)))+ (import "" "task.return" (func $task.return (param i32)))+ (func (export "run") (param $mode i32) (result i32)+ (local $h i32) (local $before i32)+ (local.set $before (call $drops))+ (local.set $h (call $ctor (i32.const 42)))+ (call $f (local.get $h) (local.get $mode))+ (call $resource.drop (local.get $h))+ (call $task.return (i32.sub (call $drops) (local.get $before)))+ (i32.const 0))+ (func (export "cb") (param i32 i32 i32) (result i32) unreachable)+ )+ (core instance $i (instantiate $m (with "" (instance+ (export "ctor" (func $ctor))+ (export "drops" (func $drops))+ (export "f" (func $f))+ (export "resource.drop" (func $resource.drop))+ (export "task.return" (func $task.return))+ ))))+ (func (export "run") async (param "mode" u32) (result u32)+ (canon lift (core func $i "run") async (callback (core func $i "cb"))))+ )+ (instance $a (instantiate $A (with "r" (type $r)) (with "ctor" (func $ctor))+ (with "drops" (func $drops)) (with "f" (func $b "f"))))+ (func (export "run") (alias export $a "run"))+)++(component instance $c0 $C)+(assert_return (invoke "run" (u32.const 0)) (u32.const 1))+(component instance $c1 $C)+(assert_return (invoke "run" (u32.const 1)) (u32.const 1))+(component instance $c2 $C)+(assert_trap (invoke "run" (u32.const 2)) "borrow handles still remain")+(component instance $c3 $C)+(assert_return (invoke "run" (u32.const 3)) (u32.const 1))++;; Same as the first test above, but B re-lends its borrow to a host subtask+;; instead of a guest subtask.+(component definition $C+ (import "host" (instance $host+ (export "resource1" (type $r (sub resource)))+ (export "[constructor]resource1" (func (param "r" u32) (result (own $r))))+ (export "[method]resource1.never-return"+ (func async (param "self" (borrow $r))))+ ))+ (alias export $host "resource1" (type $r))+ (alias export $host "[constructor]resource1" (func $ctor))+ (alias export $host "[method]resource1.never-return" (func $never-return))++ ;; B: re-lends its borrow to the host.+ ;;+ ;; mode 0: drop the borrow while the host subtask is still running (traps)+ ;; mode 1: cancel the host subtask and then drop the borrow+ (component $B+ (import "r" (type $r (sub resource)))+ (import "never-return"+ (func $never-return async (param "self" (borrow $r))))+ (core func $never-return (canon lower (func $never-return) async))+ (core func $resource.drop (canon resource.drop $r))+ (core func $task.return (canon task.return))+ (core func $subtask.drop (canon subtask.drop))+ (core func $subtask.cancel (canon subtask.cancel))+ (core module $m+ (import "" "never-return" (func $never-return (param i32) (result i32)))+ (import "" "resource.drop" (func $resource.drop (param i32)))+ (import "" "task.return" (func $task.return))+ (import "" "subtask.drop" (func $subtask.drop (param i32)))+ (import "" "subtask.cancel"+ (func $subtask.cancel (param i32) (result i32)))+ (func (export "f") (param $x i32) (param $mode i32) (result i32)+ (local $s i32)+ (local.set $s (call $never-return (local.get $x)))+ ;; STARTED+ (if (i32.ne (i32.and (local.get $s) (i32.const 0xf)) (i32.const 1))+ (then unreachable))+ (local.set $s (i32.shr_u (local.get $s) (i32.const 4)))+ (if (local.get $mode) (then+ ;; RETURN_CANCELLED+ (if (i32.ne (call $subtask.cancel (local.get $s)) (i32.const 4))+ (then unreachable))+ (call $subtask.drop (local.get $s))))+ (call $resource.drop (local.get $x))+ (call $task.return)+ (i32.const 0))+ (func (export "cb") (param i32 i32 i32) (result i32) unreachable)+ )+ (core instance $i (instantiate $m (with "" (instance+ (export "never-return" (func $never-return))+ (export "resource.drop" (func $resource.drop))+ (export "task.return" (func $task.return))+ (export "subtask.drop" (func $subtask.drop))+ (export "subtask.cancel" (func $subtask.cancel))+ ))))+ (func (export "f") async (param "x" (borrow $r)) (param "mode" u32)+ (canon lift (core func $i "f") async (callback (core func $i "cb"))))+ )+ (instance $b (instantiate $B (with "r" (type $r))+ (with "never-return" (func $never-return))))++ ;; A: lends an own handle to B and then destroys it.+ (component $A+ (import "r" (type $r (sub resource)))+ (import "ctor" (func $ctor (param "r" u32) (result (own $r))))+ (import "f" (func $f async (param "x" (borrow $r)) (param "mode" u32)))+ (core func $ctor (canon lower (func $ctor)))+ (core func $f (canon lower (func $f)))+ (core func $resource.drop (canon resource.drop $r))+ (core func $task.return (canon task.return))+ (core module $m+ (import "" "ctor" (func $ctor (param i32) (result i32)))+ (import "" "f" (func $f (param i32 i32)))+ (import "" "resource.drop" (func $resource.drop (param i32)))+ (import "" "task.return" (func $task.return))+ (func (export "run") (param $mode i32) (result i32)+ (local $h i32)+ (local.set $h (call $ctor (i32.const 42)))+ (call $f (local.get $h) (local.get $mode))+ (call $resource.drop (local.get $h))+ (call $task.return)+ (i32.const 0))+ (func (export "cb") (param i32 i32 i32) (result i32) unreachable)+ )+ (core instance $i (instantiate $m (with "" (instance+ (export "ctor" (func $ctor))+ (export "f" (func $f))+ (export "resource.drop" (func $resource.drop))+ (export "task.return" (func $task.return))+ ))))+ (func (export "run") async (param "mode" u32)+ (canon lift (core func $i "run") async (callback (core func $i "cb"))))+ )+ (instance $a (instantiate $A (with "r" (type $r)) (with "ctor" (func $ctor))+ (with "f" (func $b "f"))))+ (func (export "run") (alias export $a "run"))+)++(component instance $c0 $C)+(assert_trap (invoke "run" (u32.const 0))+ "cannot remove borrowed resource while it is lent out")+(component instance $c1 $C)+(assert_return (invoke "run" (u32.const 1)))