Repository: bytecodealliance/wasmtime
Pull request #7350 (2023-10-24 16:48:22)

Expand further minimization section of documentation
This commit fills out the page about producing minimal builds a bit more. The intention here is to provide examples of ideas about how to reduce size further as well as current limitations and how they can be evaluated.

<!--
Please make sure you include the following information:

- If this work has been discussed elsewhere, please include a link to that
  conversation. If it was discussed in an issue, just mention "issue #...".

- Explain why this change is needed. If the details are in an issue already,
  this can be brief.

Our development process is documented in the Wasmtime book:
https://docs.wasmtime.dev/contributing-development-process.html

Please ensure all communication follows the code of conduct:
https://github.com/bytecodealliance/wasmtime/blob/main/CODE_OF_CONDUCT.md
-->



Patch:
diff --git a/RELEASES.md b/RELEASES.md
index 35c8e9c18..6148c7427 100644
--- a/RELEASES.md
+++ b/RELEASES.md
@@ -10,6 +10,19 @@ Unreleased.
 
 --------------------------------------------------------------------------------
 
+## 14.0.1
+
+Released 2023-10-23
+
+### Fixed
+
+* Cranelift: preserve uext and sext flags for parameters on x86\_64 and apple
+  aarch64. Note that this does not affect Wasmtime and is only intended for
+  Cranelift embedders such as `rustc_codegen_cranelift`.
+  [#7333](https://github.com/bytecodealliance/wasmtime/pull/7333)
+
+--------------------------------------------------------------------------------
+
 ## 14.0.0
 
 Released 2023-10-20
diff --git a/cranelift/codegen/src/isa/riscv64/inst/emit.rs b/cranelift/codegen/src/isa/riscv64/inst/emit.rs
index cdc7619f8..936037d77 100644
--- a/cranelift/codegen/src/isa/riscv64/inst/emit.rs
+++ b/cranelift/codegen/src/isa/riscv64/inst/emit.rs
@@ -482,7 +482,7 @@ impl Inst {
                 rd,
                 rs,
                 imm12,
-            } if rd.to_reg() != zero_reg() && rs == zero_reg() && imm12.as_i16() != 0 => {
+            } if rd.to_reg() != zero_reg() && rs == zero_reg() => {
                 let imm6 = Imm6::maybe_from_imm12(imm12)?;
                 sink.put2(encode_ci_type(CiOp::CLi, rd, imm6));
             }
diff --git a/crates/runtime/src/mpk/enabled.rs b/crates/runtime/src/mpk/enabled.rs
index 37456ef13..9c8774233 100644
--- a/crates/runtime/src/mpk/enabled.rs
+++ b/crates/runtime/src/mpk/enabled.rs
@@ -26,11 +26,12 @@ pub fn keys() -> &'static [ProtectionKey] {
         if is_supported() {
             while let Ok(key_id) = sys::pkey_alloc(0, 0) {
                 debug_assert!(key_id < 16);
-                // UNSAFETY: here we unsafely assume that the system-allocated pkey
-                // will exist forever.
-                let pkey = ProtectionKey(key_id);
-                debug_assert_eq!(pkey.as_stripe(), allocated.len());
-                allocated.push(pkey);
+                // UNSAFETY: here we unsafely assume that the system-allocated
+                // pkey will exist forever.
+                allocated.push(ProtectionKey {
+                    id: key_id,
+                    stripe: allocated.len().try_into().unwrap(),
+                });
             }
         }
         allocated
@@ -58,7 +59,10 @@ pub fn allow(mask: ProtectionMask) {
 ///   [`ProtectionMask`]; any accesses to unmarked pages result in a fault
 /// - drop the key
 #[derive(Clone, Copy, Debug)]
-pub struct ProtectionKey(u32);
+pub struct ProtectionKey {
+    id: u32,
+    stripe: u32,
+}
 
 impl ProtectionKey {
     /// Mark a page as protected by this [`ProtectionKey`].
@@ -75,7 +79,7 @@ impl ProtectionKey {
         let addr = region.as_mut_ptr() as usize;
         let len = region.len();
         let prot = sys::PROT_READ | sys::PROT_WRITE;
-        sys::pkey_mprotect(addr, len, prot, self.0).with_context(|| {
+        sys::pkey_mprotect(addr, len, prot, self.id).with_context(|| {
             format!(
                 "failed to mark region with pkey (addr = {addr:#x}, len = {len}, prot = {prot:#b})"
             )
@@ -87,8 +91,7 @@ impl ProtectionKey {
     ///
     /// This function assumes that the kernel has allocated key 0 for itself.
     pub fn as_stripe(&self) -> usize {
-        debug_assert!(self.0 != 0);
-        self.0 as usize - 1
+        self.stripe as usize
     }
 }
 
@@ -117,7 +120,7 @@ impl ProtectionMask {
     /// Include `pkey` as another allowed protection key in the mask.
     #[inline]
     pub fn or(self, pkey: ProtectionKey) -> Self {
-        let mask = pkru::DISABLE_ACCESS ^ 0b11 << (pkey.0 * 2);
+        let mask = pkru::DISABLE_ACCESS ^ 0b11 << (pkey.id * 2);
         Self(self.0 & mask)
     }
 }
@@ -178,13 +181,13 @@ mod tests {
         allow(ProtectionMask::all());
         assert_eq!(0, pkru::read());
 
-        allow(ProtectionMask::all().or(ProtectionKey(5)));
+        allow(ProtectionMask::all().or(ProtectionKey { id: 5, stripe: 0 }));
         assert_eq!(0, pkru::read());
 
         allow(ProtectionMask::zero());
         assert_eq!(0b11111111_11111111_11111111_11111100, pkru::read());
 
-        allow(ProtectionMask::zero().or(ProtectionKey(5)));
+        allow(ProtectionMask::zero().or(ProtectionKey { id: 5, stripe: 0 }));
         assert_eq!(0b11111111_11111111_11110011_11111100, pkru::read());
 
         // Reset the PKRU state to what we originally observed.
diff --git a/crates/wasi-http/wit/deps/sockets/udp-create-socket.wit b/crates/wasi-http/wit/deps/sockets/udp-create-socket.wit
index 4e61d30fa..cc58234d8 100644
--- a/crates/wasi-http/wit/deps/sockets/udp-create-socket.wit
+++ b/crates/wasi-http/wit/deps/sockets/udp-create-socket.wit
@@ -8,7 +8,7 @@ interface udp-create-socket {
     /// Similar to `socket(AF_INET or AF_INET6, SOCK_DGRAM, IPPROTO_UDP)` in POSIX.
     ///
     /// This function does not require a network capability handle. This is considered to be safe because
-    /// at time of creation, the socket is not bound to any `network` yet. Up to the moment `bind`/`connect` is called,
+    /// at time of creation, the socket is not bound to any `network` yet. Up to the moment `bind` is called,
     /// the socket is effectively an in-memory configuration object, unable to communicate with the outside world.
     ///
     /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous operations.
diff --git a/crates/wasi-http/wit/deps/sockets/udp.wit b/crates/wasi-http/wit/deps/sockets/udp.wit
index 8641cc2c5..232c2b41c 100644
--- a/crates/wasi-http/wit/deps/sockets/udp.wit
+++ b/crates/wasi-http/wit/deps/sockets/udp.wit
@@ -3,17 +3,34 @@ interface udp {
     use wasi:io/poll@0.2.0-rc-2023-11-05.{pollable};
     use network.{network, error-code, ip-socket-address, ip-address-family};
 
+    /// A received datagram.
+    record incoming-datagram {
+        /// The payload.
+        /// 
+        /// Theoretical max size: ~64 KiB. In practice, typically less than 1500 bytes.
+        data: list<u8>,
 
-    record datagram {
-        data: list<u8>, // Theoretical max size: ~64 KiB. In practice, typically less than 1500 bytes.
+        /// The source address.
+        ///
+        /// This field is guaranteed to match the remote address the stream was initialized with, if any.
+        ///
+        /// Equivalent to the `src_addr` out parameter of `recvfrom`.
         remote-address: ip-socket-address,
+    }
+
+    /// A datagram to be sent out.
+    record outgoing-datagram {
+        /// The payload.
+        data: list<u8>,
 
-        /// Possible future additions:
-        /// local-address: ip-socket-address, // IP_PKTINFO / IP_RECVDSTADDR / IPV6_PKTINFO
-        /// local-interface: u32, // IP_PKTINFO / IP_RECVIF
-        /// ttl: u8, // IP_RECVTTL
-        /// dscp: u6, // IP_RECVTOS
-        /// ecn: u2, // IP_RECVTOS
+        /// The destination address.
+        ///
+        /// The requirements on this field depend on how the stream was initialized:
+        /// - with a remote address: this field must be None or match the stream's remote address exactly.
+        /// - without a remote address: this field is required.
+        ///
+        /// If this value is None, the send operation is equivalent to `send` in POSIX. Otherwise it is equivalent to `sendto`.
+        remote-address: option<ip-socket-address>,
     }
 
 
@@ -24,9 +41,7 @@ interface udp {
         ///
         /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the implementation to decide which
         /// network interface(s) to bind to.
-        /// If the TCP/UDP port is zero, the socket will be bound to a random free port.
-        ///
-        /// When a socket is not explicitly bound, the first invocation to connect will implicitly bind the socket.
+        /// If the port is zero, the socket will be bound to a random free port.
         ///
         /// Unlike in POSIX, this function is async. This enables interactive WASI hosts to inject permission prompts.
         ///
@@ -49,95 +64,47 @@ interface udp {
         start-bind: func(network: borrow<network>, local-address: ip-socket-address) -> result<_, error-code>;
         finish-bind: func() -> result<_, error-code>;
 
-        /// Set the destination address.
-        ///
-        /// The local-address is updated based on the best network path to `remote-address`.
-        ///
-        /// When a destination address is set:
-        /// - all receive operations will only return datagrams sent from the provided `remote-address`.
-        /// - the `send` function can only be used to send to this destination.
-        ///
-        /// Note that this function does not generate any network traffic and the peer is not aware of this "connection".
-        ///
-        /// Unlike in POSIX, this function is async. This enables interactive WASI hosts to inject permission prompts.
-        ///
-        /// # Typical `start` errors
+        /// Set up inbound & outbound communication channels, optionally to a specific peer.
+        ///
+        /// This function only changes the local socket configuration and does not generate any network traffic.
+        /// On success, the `remote-address` of the socket is updated. The `local-address` may be updated as well,
+        /// based on the best network path to `remote-address`.
+        ///
+        /// When a `remote-address` is provided, the returned streams are limited to communicating with that specific peer:
+        /// - `send` can only be used to send to this destination.
+        /// - `receive` will only return datagrams sent from the provided `remote-address`.
+        ///
+        /// This method may be called multiple times on the same socket to change its association, but
+        /// only the most recently returned pair of streams will be operational. Implementations may trap if
+        /// the streams returned by a previous invocation haven't been dropped yet before calling `stream` again.
+        /// 
+        /// The POSIX equivalent in pseudo-code is:
+        /// ```text
+        /// if (was previously connected) {
+        /// 	connect(s, AF_UNSPEC)
+        /// }
+        /// if (remote_address is Some) {
+        /// 	connect(s, remote_address)
+        /// }
+        /// ```
+        ///
+        /// Unlike in POSIX, the socket must already be explicitly bound.
+        /// 
+        /// # Typical errors
         /// - `invalid-argument`:          The `remote-address` has the wrong address family. (EAFNOSUPPORT)
         /// - `invalid-argument`:          `remote-address` is a non-IPv4-mapped IPv6 address, but the socket was bound to a specific IPv4-mapped IPv6 address. (or vice versa)
         /// - `invalid-argument`:          The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL)
         /// - `invalid-argument`:          The port in `remote-address` is set to 0. (EDESTADDRREQ, EADDRNOTAVAIL)
-        /// - `invalid-argument`:          The socket is already bound to a different network. The `network` passed to `connect` must be identical to the one passed to `bind`.
-        ///
-        /// # Typical `finish` errors
+        /// - `invalid-state`:             The socket is not bound.
         /// - `address-in-use`:            Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD)
-        /// - `not-in-progress`:           A `connect` operation is not in progress.
-        /// - `would-block`:               Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN)
+        /// - `remote-unreachable`:        The remote address is not reachable. (ECONNREFUSED, ECONNRESET, ENETRESET, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN)
         ///
         /// # References
         /// - <https://pubs.opengroup.org/onlinepubs/9699919799/functions/connect.html>
         /// - <https://man7.org/linux/man-pages/man2/connect.2.html>
         /// - <https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-connect>
         /// - <https://man.freebsd.org/cgi/man.cgi?connect>
-        start-connect: func(network: borrow<network>, remote-address: ip-socket-address) -> result<_, error-code>;
-        finish-connect: func() -> result<_, error-code>;
-
-        /// Receive messages on the socket.
-        ///
-        /// This function attempts to receive up to `max-results` datagrams on the socket without blocking.
-        /// The returned list may contain fewer elements than requested, but never more.
-        /// If `max-results` is 0, this function returns successfully with an empty list.
-        ///
-        /// # Typical errors
-        /// - `invalid-state`:      The socket is not bound to any local address. (EINVAL)
-        /// - `remote-unreachable`: The remote address is not reachable. (ECONNREFUSED, ECONNRESET, ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN)
-        /// - `would-block`:        There is no pending data available to be read at the moment. (EWOULDBLOCK, EAGAIN)
-        ///
-        /// # References
-        /// - <https://pubs.opengroup.org/onlinepubs/9699919799/functions/recvfrom.html>
-        /// - <https://pubs.opengroup.org/onlinepubs/9699919799/functions/recvmsg.html>
-        /// - <https://man7.org/linux/man-pages/man2/recv.2.html>
-        /// - <https://man7.org/linux/man-pages/man2/recvmmsg.2.html>
-        /// - <https://learn.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-recv>
-        /// - <https://learn.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-recvfrom>
-        /// - <https://learn.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms741687(v=vs.85)>
-        /// - <https://man.freebsd.org/cgi/man.cgi?query=recv&sektion=2>
-        receive: func(max-results: u64) -> result<list<datagram>, error-code>;
-
-        /// Send messages on the socket.
-        ///
-        /// This function attempts to send all provided `datagrams` on the socket without blocking and
-        /// returns how many messages were actually sent (or queued for sending).
-        ///
-        /// This function semantically behaves the same as iterating the `datagrams` list and sequentially
-        /// sending each individual datagram until either the end of the list has been reached or the first error occurred.
-        /// If at least one datagram has been sent successfully, this function never returns an error.
-        ///
-        /// If the input list is empty, the function returns `ok(0)`.
-        ///
-        /// The remote address option is required. To send a message to the "connected" peer,
-        /// call `remote-address` to get their address.
-        ///
-        /// # Typical errors
-        /// - `invalid-argument`:        The `remote-address` has the wrong address family. (EAFNOSUPPORT)
-        /// - `invalid-argument`:        `remote-address` is a non-IPv4-mapped IPv6 address, but the socket was bound to a specific IPv4-mapped IPv6 address. (or vice versa)
-        /// - `invalid-argument`:        The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL)
-        /// - `invalid-argument`:        The port in `remote-address` is set to 0. (EDESTADDRREQ, EADDRNOTAVAIL)
-        /// - `invalid-argument`:        The socket is in "connected" mode and the `datagram.remote-address` does not match the address passed to `connect`. (EISCONN)
-        /// - `invalid-state`:           The socket is not bound to any local address. Unlike POSIX, this function does not perform an implicit bind.
-        /// - `remote-unreachable`:      The remote address is not reachable. (ECONNREFUSED, ECONNRESET, ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN)
-        /// - `datagram-too-large`:      The datagram is too large. (EMSGSIZE)
-        /// - `would-block`:             The send buffer is currently full. (EWOULDBLOCK, EAGAIN)
-        ///
-        /// # References
-        /// - <https://pubs.opengroup.org/onlinepubs/9699919799/functions/sendto.html>
-        /// - <https://pubs.opengroup.org/onlinepubs/9699919799/functions/sendmsg.html>
-        /// - <https://man7.org/linux/man-pages/man2/send.2.html>
-        /// - <https://man7.org/linux/man-pages/man2/sendmmsg.2.html>
-        /// - <https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-send>
-        /// - <https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-sendto>
-        /// - <https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasendmsg>
-        /// - <https://man.freebsd.org/cgi/man.cgi?query=send&sektion=2>
-        send: func(datagrams: list<datagram>) -> result<u64, error-code>;
+        %stream: func(remote-address: option<ip-socket-address>) -> result<tuple<incoming-datagram-stream, outgoing-datagram-stream>, error-code>;
 
         /// Get the current bound address.
         ///
@@ -146,7 +113,7 @@ interface udp {
         /// > stored in the object pointed to by `address` is unspecified.
         ///
         /// WASI is stricter and requires `local-address` to return `invalid-state` when the socket hasn't been bound yet.
-        ///
+        /// 
         /// # Typical errors
         /// - `invalid-state`: The socket is not bound to any local address.
         ///
@@ -157,10 +124,10 @@ interface udp {
         /// - <https://man.freebsd.org/cgi/man.cgi?getsockname>
         local-address: func() -> result<ip-socket-address, error-code>;
 
-        /// Get the address set with `connect`.
+        /// Get the address the socket is currently streaming to.
         ///
         /// # Typical errors
-        /// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN)
+        /// - `invalid-state`: The socket is not streaming to a specific remote address. (ENOTCONN)
         ///
         /// # References
         /// - <https://pubs.opengroup.org/onlinepubs/9699919799/functions/getpeername.html>
@@ -192,11 +159,11 @@ interface udp {
         /// The kernel buffer space reserved for sends/receives on this socket.
         ///
         /// Note #1: an implementation may choose to cap or round the buffer size when setting the value.
-        ///     In other words, after setting a value, reading the same setting back may return a different value.
+        /// 	In other words, after setting a value, reading the same setting back may return a different value.
         ///
         /// Note #2: there is not necessarily a direct relationship between the kernel buffer size and the bytes of
-        ///     actual data to be sent/received by the application, because the kernel might also use the buffer space
-        ///     for internal metadata structures.
+        /// 	actual data to be sent/received by the application, because the kernel might also use the buffer space
+        /// 	for internal metadata structures.
         ///
         /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options.
         receive-buffer-size: func() -> result<u64, error-code>;
@@ -210,4 +177,93 @@ interface udp {
         /// It's planned to be removed when `future` is natively supported in Preview3.
         subscribe: func() -> pollable;
     }
+
+    resource incoming-datagram-stream {
+        /// Receive messages on the socket.
+        ///
+        /// This function attempts to receive up to `max-results` datagrams on the socket without blocking.
+        /// The returned list may contain fewer elements than requested, but never more.
+        ///
+        /// This function returns successfully with an empty list when either:
+        /// - `max-results` is 0, or:
+        /// - `max-results` is greater than 0, but no results are immediately available.
+        /// This function never returns `error(would-block)`.
+        ///
+        /// # Typical errors
+        /// - `remote-unreachable`: The remote address is not reachable. (ECONNREFUSED, ECONNRESET, ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN)
+        ///
+        /// # References
+        /// - <https://pubs.opengroup.org/onlinepubs/9699919799/functions/recvfrom.html>
+        /// - <https://pubs.opengroup.org/onlinepubs/9699919799/functions/recvmsg.html>
+        /// - <https://man7.org/linux/man-pages/man2/recv.2.html>
+        /// - <https://man7.org/linux/man-pages/man2/recvmmsg.2.html>
+        /// - <https://learn.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-recv>
+        /// - <https://learn.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-recvfrom>
+        /// - <https://learn.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms741687(v=vs.85)>
+        /// - <https://man.freebsd.org/cgi/man.cgi?query=recv&sektion=2>
+        receive: func(max-results: u64) -> result<list<incoming-datagram>, error-code>;
+
+        /// Create a `pollable` which will resolve once the stream is ready to receive again.
+        ///
+        /// Note: this function is here for WASI Preview2 only.
+        /// It's planned to be removed when `future` is natively supported in Preview3.
+        subscribe: func() -> pollable;
+    }
+
+    resource outgoing-datagram-stream {
+        /// Check readiness for sending. This function never blocks.
+        ///
+        /// Returns the number of datagrams permitted for the next call to `send`,
+        /// or an error. Calling `send` with more datagrams than this function has
+        /// permitted will trap.
+        ///
+        /// When this function returns ok(0), the `subscribe` pollable will
+        /// become ready when this function will report at least ok(1), or an
+        /// error.
+        /// 
+        /// Never returns `would-block`.
+        check-send: func() -> result<u64, error-code>;
+
+        /// Send messages on the socket.
+        ///
+        /// This function attempts to send all provided `datagrams` on the socket without blocking and
+        /// returns how many messages were actually sent (or queued for sending). This function never
+        /// returns `error(would-block)`. If none of the datagrams were able to be sent, `ok(0)` is returned.
+        ///
+        /// This function semantically behaves the same as iterating the `datagrams` list and sequentially
+        /// sending each individual datagram until either the end of the list has been reached or the first error occurred.
+        /// If at least one datagram has been sent successfully, this function never returns an error.
+        ///
+        /// If the input list is empty, the function returns `ok(0)`.
+        ///
+        /// Each call to `send` must be permitted by a preceding `check-send`. Implementations must trap if
+        /// either `check-send` was not called or `datagrams` contains more items than `check-send` permitted.
+        ///
+        /// # Typical errors
+        /// - `invalid-argument`:        The `remote-address` has the wrong address family. (EAFNOSUPPORT)
+        /// - `invalid-argument`:        `remote-address` is a non-IPv4-mapped IPv6 address, but the socket was bound to a specific IPv4-mapped IPv6 address. (or vice versa)
+        /// - `invalid-argument`:        The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL)
+        /// - `invalid-argument`:        The port in `remote-address` is set to 0. (EDESTADDRREQ, EADDRNOTAVAIL)
+        /// - `invalid-argument`:        The socket is in "connected" mode and `remote-address` is `some` value that does not match the address passed to `stream`. (EISCONN)
+        /// - `invalid-argument`:        The socket is not "connected" and no value for `remote-address` was provided. (EDESTADDRREQ)
+        /// - `remote-unreachable`:      The remote address is not reachable. (ECONNREFUSED, ECONNRESET, ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN)
+        /// - `datagram-too-large`:      The datagram is too large. (EMSGSIZE)
+        ///
+        /// # References
+        /// - <https://pubs.opengroup.org/onlinepubs/9699919799/functions/sendto.html>
+        /// - <https://pubs.opengroup.org/onlinepubs/9699919799/functions/sendmsg.html>
+        /// - <https://man7.org/linux/man-pages/man2/send.2.html>
+        /// - <https://man7.org/linux/man-pages/man2/sendmmsg.2.html>
+        /// - <https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-send>
+        /// - <https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-sendto>
+        /// - <https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasendmsg>
+        /// - <https://man.freebsd.org/cgi/man.cgi?query=send&sektion=2>
+        send: func(datagrams: list<outgoing-datagram>) -> result<u64, error-code>;
+        
+        /// Create a `pollable` which will resolve once the stream is ready to send again.
+        ///
+        /// Note: this function is here for WASI Preview2 only.
+        /// It's planned to be removed when `future` is natively supported in Preview3.
+        subscribe: func() -> pollable;
+    }
 }
diff --git a/crates/wasi/src/preview2/error.rs b/crates/wasi/src/preview2/error.rs
index ccae912d4..f92317c1f 100644
--- a/crates/wasi/src/preview2/error.rs
+++ b/crates/wasi/src/preview2/error.rs
@@ -61,6 +61,13 @@ impl<T> TrappableError<T> {
     {
         self.err.downcast()
     }
+
+    pub fn downcast_ref(&self) -> Option<&T>
+    where
+        T: Error + Send + Sync + 'static,
+    {
+        self.err.downcast_ref()
+    }
 }
 
 impl<T> From<T> for TrappableError<T>
diff --git a/crates/wasi/src/preview2/host/udp.rs b/crates/wasi/src/preview2/host/udp.rs
index 857925eb6..a97bd1bcd 100644
--- a/crates/wasi/src/preview2/host/udp.rs
+++ b/crates/wasi/src/preview2/host/udp.rs
@@ -5,23 +5,27 @@ use crate::preview2::{
         sockets::network::{ErrorCode, IpAddressFamily, IpSocketAddress, Network},
         sockets::udp,
     },
-    udp::UdpState,
+    udp::{IncomingDatagramStream, OutgoingDatagramStream, SendState, UdpState},
+    Subscribe,
 };
-use crate::preview2::{Pollable, SocketResult, WasiView};
+use crate::preview2::{Pollable, SocketError, SocketResult, WasiView};
+use anyhow::anyhow;
+use async_trait::async_trait;
 use cap_net_ext::{AddressFamily, PoolExt};
 use io_lifetimes::AsSocketlike;
 use rustix::io::Errno;
 use rustix::net::sockopt;
+use tokio::io::Interest;
 use wasmtime::component::Resource;
 
 /// Theoretical maximum byte size of a UDP datagram, the real limit is lower,
 /// but we do not account for e.g. the transport layer here for simplicity.
 /// In practice, datagrams are typically less than 1500 bytes.
-const MAX_UDP_DATAGRAM_SIZE: usize = 65535;
+const MAX_UDP_DATAGRAM_SIZE: usize = u16::MAX as usize;
 
 impl<T: WasiView> udp::Host for T {}
 
-impl<T: WasiView> crate::preview2::host::udp::udp::HostUdpSocket for T {
+impl<T: WasiView> udp::HostUdpSocket for T {
     fn start_bind(
         &mut self,
         this: Resource<udp::UdpSocket>,
@@ -30,16 +34,15 @@ impl<T: WasiView> crate::preview2::host::udp::udp::HostUdpSocket for T {
     ) -> SocketResult<()> {
         let table = self.table_mut();
         let socket = table.get(&this)?;
+        let network = table.get(&network)?;
+        let local_address: SocketAddr = local_address.into();
 
         match socket.udp_state {
             UdpState::Default => {}
-            UdpState::BindStarted | UdpState::Connecting(..) => {
-                return Err(ErrorCode::ConcurrencyConflict.into())
-            }
-            UdpState::Bound | UdpState::Connected(..) => return Err(ErrorCode::InvalidState.into()),
+            UdpState::BindStarted => return Err(ErrorCode::ConcurrencyConflict.into()),
+            UdpState::Bound | UdpState::Connected => return Err(ErrorCode::InvalidState.into()),
         }
 
-        let network = table.get(&network)?;
         let binder = network.pool.udp_binder(local_address)?;
 
         // Perform the OS bind call.
@@ -68,157 +71,58 @@ impl<T: WasiView> crate::preview2::host::udp::udp::HostUdpSocket for T {
         }
     }
 
-    fn start_connect(
+    fn stream(
         &mut self,
         this: Resource<udp::UdpSocket>,
-        network: Resource<Network>,
-        remote_address: IpSocketAddress,
-    ) -> SocketResult<()> {
+        remote_address: Option<IpSocketAddress>,
+    ) -> SocketResult<(
+        Resource<udp::IncomingDatagramStream>,
+        Resource<udp::OutgoingDatagramStream>,
+    )> {
         let table = self.table_mut();
-        let socket = table.get(&this)?;
-        let network = table.get(&network)?;
-
-        match socket.udp_state {
-            UdpState::Default | UdpState::Bound => {}
-            UdpState::BindStarted | UdpState::Connecting(..) => {
-                return Err(ErrorCode::ConcurrencyConflict.into())
-            }
-            UdpState::Connected(..) => return Err(ErrorCode::InvalidState.into()),
-        }
 
-        let connecter = network.pool.udp_connecter(remote_address)?;
+        let has_active_streams = table
+            .iter_children(&this)?
+            .any(|c| c.is::<IncomingDatagramStream>() || c.is::<OutgoingDatagramStream>());
 
-        // Do an OS `connect`.
-        connecter.connect_existing_udp_socket(
-            &*socket
-                .udp_socket()
-                .as_socketlike_view::<cap_std::net::UdpSocket>(),
-        )?;
-
-        let socket = table.get_mut(&this)?;
-        socket.udp_state = UdpState::Connecting(remote_address);
-        Ok(())
-    }
+        if has_active_streams {
+            return Err(SocketError::trap(anyhow!("UDP streams not dropped yet")));
+        }
 
-    fn finish_connect(&mut self, this: Resource<udp::UdpSocket>) -> SocketResult<()> {
-        let table = self.table_mut();
         let socket = table.get_mut(&this)?;
+        let remote_address = remote_address.map(SocketAddr::from);
 
         match socket.udp_state {
-            UdpState::Connecting(addr) => {
-                socket.udp_state = UdpState::Connected(addr);
-                Ok(())
-            }
-            _ => Err(ErrorCode::NotInProgress.into()),
+            UdpState::Bound | UdpState::Connected => {}
+            _ => return Err(ErrorCode::InvalidState.into()),
         }
-    }
 
-    fn receive(
-        &mut self,
-        this: Resource<udp::UdpSocket>,
-        max_results: u64,
-    ) -> SocketResult<Vec<udp::Datagram>> {
-        if max_results == 0 {
-            return Ok(vec![]);
+        if let UdpState::Connected = socket.udp_state {
+            // FIXME: Allow multiple (dis)connects. This needs to be supported by rustix first.
+            // rustix::net::disconnect(socket.udp_socket())?;
+            // socket.udp_state = UdpState::Bound;
+            return Err(ErrorCode::NotSupported.into());
         }
 
-        let table = self.table();
-        let socket = table.get(&this)?;
-
-        let udp_socket = socket.udp_socket();
-        let mut datagrams = vec![];
-        let mut buf = [0; MAX_UDP_DATAGRAM_SIZE];
-        match socket.udp_state {
-            UdpState::Default | UdpState::BindStarted => return Err(ErrorCode::InvalidState.into()),
-            UdpState::Bound | UdpState::Connecting(..) => {
-                for i in 0..max_results {
-                    match udp_socket.try_recv_from(&mut buf) {
-                        Ok((size, remote_address)) => datagrams.push(udp::Datagram {
-                            data: buf[..size].into(),
-                            remote_address: remote_address.into(),
-                        }),
-                        Err(_e) if i > 0 => {
-                            return Ok(datagrams);
-                        }
-                        Err(e) => return Err(e.into()),
-                    }
-                }
-            }
-            UdpState::Connected(remote_address) => {
-                for i in 0..max_results {
-                    match udp_socket.try_recv(&mut buf) {
-                        Ok(size) => datagrams.push(udp::Datagram {
-                            data: buf[..size].into(),
-                            remote_address,
-                        }),
-                        Err(_e) if i > 0 => {
-                            return Ok(datagrams);
-                        }
-                        Err(e) => return Err(e.into()),
-                    }
-                }
-            }
+        if let Some(connect_addr) = remote_address {
+            rustix::net::connect(socket.udp_socket(), &connect_addr)?;
+            socket.udp_state = UdpState::Connected;
         }
-        Ok(datagrams)
-    }
 
-    fn send(
-        &mut self,
-        this: Resource<udp::UdpSocket>,
-        datagrams: Vec<udp::Datagram>,
-    ) -> SocketResult<u64> {
-        if datagrams.is_empty() {
-            return Ok(0);
+        let incoming_stream = IncomingDatagramStream {
+            inner: socket.inner.clone(),
+            remote_address,
+        };
+        let outgoing_stream = OutgoingDatagramStream {
+            inner: socket.inner.clone(),
+            remote_address,
+            send_state: SendState::Idle,
         };
-        let table = self.table();
-        let socket = table.get(&this)?;
 
-        let udp_socket = socket.udp_socket();
-        let mut count = 0;
-        match socket.udp_state {
-            UdpState::Default | UdpState::BindStarted => return Err(ErrorCode::InvalidState.into()),
-            UdpState::Bound | UdpState::Connecting(..) => {
-                for udp::Datagram {
-                    data,
-                    remote_address,
-                } in datagrams
-                {
-                    match udp_socket.try_send_to(&data, remote_address.into()) {
-                        Ok(_size) => count += 1,
-                        Err(_e) if count > 0 => {
-                            return Ok(count);
-                        }
-                        Err(e) => return Err(e.into()),
-                    }
-                }
-            }
-            UdpState::Connected(addr) => {
-                let addr = SocketAddr::from(addr);
-                for udp::Datagram {
-                    data,
-                    remote_address,
-                } in datagrams
-                {
-                    if SocketAddr::from(remote_address) != addr {
-                        // From WIT documentation:
-                        // If at least one datagram has been sent successfully, this function never returns an error.
-                        if count == 0 {
-                            return Err(ErrorCode::InvalidArgument.into());
-                        } else {
-                            return Ok(count);
-                        }
-                    }
-                    match udp_socket.try_send(&data) {
-                        Ok(_size) => count += 1,
-                        Err(_e) if count > 0 => {
-                            return Ok(count);
-                        }
-                        Err(e) => return Err(e.into()),
-                    }
-                }
-            }
-        }
-        Ok(count)
+        Ok((
+            self.table_mut().push_child(incoming_stream, &this)?,
+            self.table_mut().push_child(outgoing_stream, &this)?,
+        ))
     }
 
     fn local_address(&mut self, this: Resource<udp::UdpSocket>) -> SocketResult<IpSocketAddress> {
@@ -354,3 +258,226 @@ impl<T: WasiView> crate::preview2::host::udp::udp::HostUdpSocket for T {
         Ok(())
     }
 }
+
+impl<T: WasiView> udp::HostIncomingDatagramStream for T {
+    fn receive(
+        &mut self,
+        this: Resource<udp::IncomingDatagramStream>,
+        max_results: u64,
+    ) -> SocketResult<Vec<udp::IncomingDatagram>> {
+        // Returns Ok(None) when the message was dropped.
+        fn recv_one(
+            stream: &IncomingDatagramStream,
+        ) -> SocketResult<Option<udp::IncomingDatagram>> {
+            let mut buf = [0; MAX_UDP_DATAGRAM_SIZE];
+            let (size, received_addr) = stream.inner.try_recv_from(&mut buf)?;
+
+            match stream.remote_address {
+                Some(connected_addr) if connected_addr != received_addr => {
+                    // Normally, this should have already been checked for us by the OS.
+                    return Ok(None);
+                }
+                _ => {}
+            }
+
+            // FIXME: check permission to receive from `received_addr`.
+            Ok(Some(udp::IncomingDatagram {
+                data: buf[..size].into(),
+                remote_address: received_addr.into(),
+            }))
+        }
+
+        let table = self.table();
+        let stream = table.get(&this)?;
+        let max_results: usize = max_results.try_into().unwrap_or(usize::MAX);
+
+        if max_results == 0 {
+            return Ok(vec![]);
+        }
+
+        let mut datagrams = vec![];
+
+        while datagrams.len() < max_results {
+            match recv_one(stream) {
+                Ok(Some(datagram)) => {
+                    datagrams.push(datagram);
+                }
+                Ok(None) => {
+                    // Message was dropped
+                }
+                Err(_) if datagrams.len() > 0 => {
+                    return Ok(datagrams);
+                }
+                Err(e) if matches!(e.downcast_ref(), Some(ErrorCode::WouldBlock)) => {
+                    return Ok(datagrams);
+                }
+                Err(e) => {
+                    return Err(e);
+                }
+            }
+        }
+
+        Ok(datagrams)
+    }
+
+    fn subscribe(
+        &mut self,
+        this: Resource<udp::IncomingDatagramStream>,
+    ) -> anyhow::Result<Resource<Pollable>> {
+        crate::preview2::poll::subscribe(self.table_mut(), this)
+    }
+
+    fn drop(&mut self, this: Resource<udp::IncomingDatagramStream>) -> Result<(), anyhow::Error> {
+        let table = self.table_mut();
+
+        // As in the filesystem implementation, we assume closing a socket
+        // doesn't block.
+        let dropped = table.delete(this)?;
+        drop(dropped);
+
+        Ok(())
+    }
+}
+
+#[async_trait]
+impl Subscribe for IncomingDatagramStream {
+    async fn ready(&mut self) {
+        // FIXME: Add `Interest::ERROR` when we update to tokio 1.32.
+        self.inner
+            .ready(Interest::READABLE)
+            .await
+            .expect("failed to await UDP socket readiness");
+    }
+}
+
+impl<T: WasiView> udp::HostOutgoingDatagramStream for T {
+    fn check_send(&mut self, this: Resource<udp::OutgoingDatagramStream>) -> SocketResult<u64> {
+        let table = self.table_mut();
+        let stream = table.get_mut(&this)?;
+
+        let permit = match stream.send_state {
+            SendState::Idle => {
+                const PERMIT: usize = 16;
+                stream.send_state = SendState::Permitted(PERMIT);
+                PERMIT
+            }
+            SendState::Permitted(n) => n,
+            SendState::Waiting => 0,
+        };
+
+        Ok(permit.try_into().unwrap())
+    }
+
+    fn send(
+        &mut self,
+        this: Resource<udp::OutgoingDatagramStream>,
+        datagrams: Vec<udp::OutgoingDatagram>,
+    ) -> SocketResult<u64> {
+        fn send_one(
+            stream: &OutgoingDatagramStream,
+            datagram: &udp::OutgoingDatagram,
+        ) -> SocketResult<()> {
+            if datagram.data.len() > MAX_UDP_DATAGRAM_SIZE {
+                return Err(ErrorCode::DatagramTooLarge.into());
+            }
+
+            let provided_addr = datagram.remote_address.map(SocketAddr::from);
+            let addr = match (stream.remote_address, provided_addr) {
+                (None, Some(addr)) => addr,
+                (Some(addr), None) => addr,
+                (Some(connected_addr), Some(provided_addr)) if connected_addr == provided_addr => {
+                    connected_addr
+                }
+                _ => return Err(ErrorCode::InvalidArgument.into()),
+            };
+
+            // FIXME: check permission to send to `addr`.
+            if stream.remote_address == Some(addr) {
+                stream.inner.try_send(&datagram.data)?;
+            } else {
+                stream.inner.try_send_to(&datagram.data, addr)?;
+            }
+
+            Ok(())
+        }
+
+        let table = self.table_mut();
+        let stream = table.get_mut(&this)?;
+
+        match stream.send_state {
+            SendState::Permitted(n) if n >= datagrams.len() => {
+                stream.send_state = SendState::Idle;
+            }
+            SendState::Permitted(_) => {
+                return Err(SocketError::trap(anyhow::anyhow!(
+                    "unpermitted: argument exceeds permitted size"
+                )))
+            }
+            SendState::Idle | SendState::Waiting => {
+                return Err(SocketError::trap(anyhow::anyhow!(
+                    "unpermitted: must call check-send first"
+                )))
+            }
+        }
+
+        if datagrams.is_empty() {
+            return Ok(0);
+        }
+
+        let mut count = 0;
+
+        for datagram in datagrams {
+            match send_one(stream, &datagram) {
+                Ok(_) => count += 1,
+                Err(_) if count > 0 => {
+                    // WIT: "If at least one datagram has been sent successfully, this function never returns an error."
+                    return Ok(count);
+                }
+                Err(e) if matches!(e.downcast_ref(), Some(ErrorCode::WouldBlock)) => {
+                    stream.send_state = SendState::Waiting;
+                    return Ok(count);
+                }
+                Err(e) => {
+                    return Err(e);
+                }
+            }
+        }
+
+        Ok(count)
+    }
+
+    fn subscribe(
+        &mut self,
+        this: Resource<udp::OutgoingDatagramStream>,
+    ) -> anyhow::Result<Resource<Pollable>> {
+        crate::preview2::poll::subscribe(self.table_mut(), this)
+    }
+
+    fn drop(&mut self, this: Resource<udp::OutgoingDatagramStream>) -> Result<(), anyhow::Error> {
+        let table = self.table_mut();
+
+        // As in the filesystem implementation, we assume closing a socket
+        // doesn't block.
+        let dropped = table.delete(this)?;
+        drop(dropped);
+
+        Ok(())
+    }
+}
+
+#[async_trait]
+impl Subscribe for OutgoingDatagramStream {
+    async fn ready(&mut self) {
+        match self.send_state {
+            SendState::Idle | SendState::Permitted(_) => {}
+            SendState::Waiting => {
+                // FIXME: Add `Interest::ERROR` when we update to tokio 1.32.
+                self.inner
+                    .ready(Interest::WRITABLE)
+                    .await
+                    .expect("failed to await UDP socket readiness");
+                self.send_state = SendState::Idle;
+            }
+        }
+    }
+}
diff --git a/crates/wasi/src/preview2/mod.rs b/crates/wasi/src/preview2/mod.rs
index abdfe4df5..f9d097745 100644
--- a/crates/wasi/src/preview2/mod.rs
+++ b/crates/wasi/src/preview2/mod.rs
@@ -161,6 +161,8 @@ pub mod bindings {
             "wasi:sockets/network/network": super::network::Network,
             "wasi:sockets/tcp/tcp-socket": super::tcp::TcpSocket,
             "wasi:sockets/udp/udp-socket": super::udp::UdpSocket,
+            "wasi:sockets/udp/incoming-datagram-stream": super::udp::IncomingDatagramStream,
+            "wasi:sockets/udp/outgoing-datagram-stream": super::udp::OutgoingDatagramStream,
             "wasi:sockets/ip-name-lookup/resolve-address-stream": super::ip_name_lookup::ResolveAddressStream,
             "wasi:filesystem/types/directory-entry-stream": super::filesystem::ReaddirIterator,
             "wasi:filesystem/types/descriptor": super::filesystem::Descriptor,
diff --git a/crates/wasi/src/preview2/table.rs b/crates/wasi/src/preview2/table.rs
index 2454fce03..444e7b25f 100644
--- a/crates/wasi/src/preview2/table.rs
+++ b/crates/wasi/src/preview2/table.rs
@@ -234,6 +234,21 @@ impl Table {
             (item, v)
         })
     }
+
+    /// Iterate over all children belonging to the provided parent
+    pub fn iter_children<T>(
+        &self,
+        parent: &Resource<T>,
+    ) -> Result<impl Iterator<Item = &(dyn Any + Send + Sync)>, TableError>
+    where
+        T: 'static,
+    {
+        let parent_entry = self.map.get(&parent.rep()).ok_or(TableError::NotPresent)?;
+        Ok(parent_entry.children.iter().map(|child_index| {
+            let child = self.map.get(child_index).expect("missing child");
+            child.entry.as_ref()
+        }))
+    }
 }
 
 impl Default for Table {
diff --git a/crates/wasi/src/preview2/udp.rs b/crates/wasi/src/preview2/udp.rs
index 2c879f99a..504dba0b1 100644
--- a/crates/wasi/src/preview2/udp.rs
+++ b/crates/wasi/src/preview2/udp.rs
@@ -1,12 +1,11 @@
-use crate::preview2::bindings::sockets::network::IpSocketAddress;
 use crate::preview2::poll::Subscribe;
 use crate::preview2::with_ambient_tokio_runtime;
 use async_trait::async_trait;
 use cap_net_ext::{AddressFamily, Blocking, UdpSocketExt};
 use io_lifetimes::raw::{FromRawSocketlike, IntoRawSocketlike};
 use std::io;
+use std::net::SocketAddr;
 use std::sync::Arc;
-use tokio::io::Interest;
 
 /// The state of a UDP socket.
 ///
@@ -23,11 +22,8 @@ pub(crate) enum UdpState {
     /// is not yet listening for connections.
     Bound,
 
-    /// A connect call is in progress.
-    Connecting(IpSocketAddress),
-
     /// The socket is "connected" to a peer address.
-    Connected(IpSocketAddress),
+    Connected,
 }
 
 /// A host UDP socket, plus associated bookkeeping.
@@ -49,44 +45,60 @@ pub struct UdpSocket {
 #[async_trait]
 impl Subscribe for UdpSocket {
     async fn ready(&mut self) {
-        // Some states are ready immediately.
-        match self.udp_state {
-            UdpState::BindStarted => return,
-            _ => {}
-        }
-
-        // FIXME: Add `Interest::ERROR` when we update to tokio 1.32.
-        self.inner
-            .ready(Interest::READABLE | Interest::WRITABLE)
-            .await
-            .expect("failed to await UDP socket readiness");
+        // None of the socket-level operations block natively
     }
 }
 
 impl UdpSocket {
     /// Create a new socket in the given family.
     pub fn new(family: AddressFamily) -> io::Result<Self> {
-        // Create a new host socket and set it to non-blocking, which is needed
-        // by our async implementation.
-        let udp_socket = cap_std::net::UdpSocket::new(family, Blocking::No)?;
-        Self::from_udp_socket(udp_socket, family)
-    }
-
-    pub fn from_udp_socket(
-        udp_socket: cap_std::net::UdpSocket,
-        family: AddressFamily,
-    ) -> io::Result<Self> {
-        let fd = udp_socket.into_raw_socketlike();
-        let std_socket = unsafe { std::net::UdpSocket::from_raw_socketlike(fd) };
-        let socket = with_ambient_tokio_runtime(|| tokio::net::UdpSocket::try_from(std_socket))?;
-        Ok(Self {
-            inner: Arc::new(socket),
+        Ok(UdpSocket {
+            inner: Arc::new(Self::new_tokio_socket(family)?),
             udp_state: UdpState::Default,
             family,
         })
     }
 
+    fn new_tokio_socket(family: AddressFamily) -> io::Result<tokio::net::UdpSocket> {
+        // Create a new host socket and set it to non-blocking, which is needed
+        // by our async implementation.
+        let cap_std_socket = cap_std::net::UdpSocket::new(family, Blocking::No)?;
+        let fd = cap_std_socket.into_raw_socketlike();
+        let std_socket = unsafe { std::net::UdpSocket::from_raw_socketlike(fd) };
+        let tokio_socket =
+            with_ambient_tokio_runtime(|| tokio::net::UdpSocket::try_from(std_socket))?;
+
+        Ok(tokio_socket)
+    }
+
     pub fn udp_socket(&self) -> &tokio::net::UdpSocket {
         &self.inner
     }
 }
+
+pub struct IncomingDatagramStream {
+    pub(crate) inner: Arc<tokio::net::UdpSocket>,
+
+    /// If this has a value, the stream is "connected".
+    pub(crate) remote_address: Option<SocketAddr>,
+}
+
+pub struct OutgoingDatagramStream {
+    pub(crate) inner: Arc<tokio::net::UdpSocket>,
+
+    /// If this has a value, the stream is "connected".
+    pub(crate) remote_address: Option<SocketAddr>,
+
+    pub(crate) send_state: SendState,
+}
+
+pub(crate) enum SendState {
+    /// Waiting for the API consumer to call `check-send`.
+    Idle,
+
+    /// Ready to send up to x datagrams.
+    Permitted(usize),
+
+    /// Waiting for the OS.
+    Waiting,
+}
diff --git a/crates/wasi/wit/deps/sockets/udp-create-socket.wit b/crates/wasi/wit/deps/sockets/udp-create-socket.wit
index 4e61d30fa..cc58234d8 100644
--- a/crates/wasi/wit/deps/sockets/udp-create-socket.wit
+++ b/crates/wasi/wit/deps/sockets/udp-create-socket.wit
@@ -8,7 +8,7 @@ interface udp-create-socket {
     /// Similar to `socket(AF_INET or AF_INET6, SOCK_DGRAM, IPPROTO_UDP)` in POSIX.
     ///
     /// This function does not require a network capability handle. This is considered to be safe because
-    /// at time of creation, the socket is not bound to any `network` yet. Up to the moment `bind`/`connect` is called,
+    /// at time of creation, the socket is not bound to any `network` yet. Up to the moment `bind` is called,
     /// the socket is effectively an in-memory configuration object, unable to communicate with the outside world.
     ///
     /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous operations.
diff --git a/crates/wasi/wit/deps/sockets/udp.wit b/crates/wasi/wit/deps/sockets/udp.wit
index 8641cc2c5..232c2b41c 100644
--- a/crates/wasi/wit/deps/sockets/udp.wit
+++ b/crates/wasi/wit/deps/sockets/udp.wit
@@ -3,17 +3,34 @@ interface udp {
     use wasi:io/poll@0.2.0-rc-2023-11-05.{pollable};
     use network.{network, error-code, ip-socket-address, ip-address-family};
 
+    /// A received datagram.
+    record incoming-datagram {
+        /// The payload.
+        /// 
+        /// Theoretical max size: ~64 KiB. In practice, typically less than 1500 bytes.
+        data: list<u8>,
 
-    record datagram {
-        data: list<u8>, // Theoretical max size: ~64 KiB. In practice, typically less than 1500 bytes.
+        /// The source address.
+        ///
+        /// This field is guaranteed to match the remote address the stream was initialized with, if any.
+        ///
+        /// Equivalent to the `src_addr` out parameter of `recvfrom`.
         remote-address: ip-socket-address,
+    }
+
+    /// A datagram to be sent out.
+    record outgoing-datagram {
+        /// The payload.
+        data: list<u8>,
 
-        /// Possible future additions:
-        /// local-address: ip-socket-address, // IP_PKTINFO / IP_RECVDSTADDR / IPV6_PKTINFO
-        /// local-interface: u32, // IP_PKTINFO / IP_RECVIF
-        /// ttl: u8, // IP_RECVTTL
-        /// dscp: u6, // IP_RECVTOS
-        /// ecn: u2, // IP_RECVTOS
+        /// The destination address.
+        ///
+        /// The requirements on this field depend on how the stream was initialized:
+        /// - with a remote address: this field must be None or match the stream's remote address exactly.
+        /// - without a remote address: this field is required.
+        ///
+        /// If this value is None, the send operation is equivalent to `send` in POSIX. Otherwise it is equivalent to `sendto`.
+        remote-address: option<ip-socket-address>,
     }
 
 
@@ -24,9 +41,7 @@ interface udp {
         ///
         /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the implementation to decide which
         /// network interface(s) to bind to.
-        /// If the TCP/UDP port is zero, the socket will be bound to a random free port.
-        ///
-        /// When a socket is not explicitly bound, the first invocation to connect will implicitly bind the socket.
+        /// If the port is zero, the socket will be bound to a random free port.
         ///
         /// Unlike in POSIX, this function is async. This enables interactive WASI hosts to inject permission prompts.
         ///
@@ -49,95 +64,47 @@ interface udp {
         start-bind: func(network: borrow<network>, local-address: ip-socket-address) -> result<_, error-code>;
         finish-bind: func() -> result<_, error-code>;
 
-        /// Set the destination address.
-        ///
-        /// The local-address is updated based on the best network path to `remote-address`.
-        ///
-        /// When a destination address is set:
-        /// - all receive operations will only return datagrams sent from the provided `remote-address`.
-        /// - the `send` function can only be used to send to this destination.
-        ///
-        /// Note that this function does not generate any network traffic and the peer is not aware of this "connection".
-        ///
-        /// Unlike in POSIX, this function is async. This enables interactive WASI hosts to inject permission prompts.
-        ///
-        /// # Typical `start` errors
+        /// Set up inbound & outbound communication channels, optionally to a specific peer.
+        ///
+        /// This function only changes the local socket configuration and does not generate any network traffic.
+        /// On success, the `remote-address` of the socket is updated. The `local-address` may be updated as well,
+        /// based on the best network path to `remote-address`.
+        ///
+        /// When a `remote-address` is provided, the returned streams are limited to communicating with that specific peer:
+        /// - `send` can only be used to send to this destination.
+        /// - `receive` will only return datagrams sent from the provided `remote-address`.
+        ///
+        /// This method may be called multiple times on the same socket to change its association, but
+        /// only the most recently returned pair of streams will be operational. Implementations may trap if
+        /// the streams returned by a previous invocation haven't been dropped yet before calling `stream` again.
+        /// 
+        /// The POSIX equivalent in pseudo-code is:
+        /// ```text
+        /// if (was previously connected) {
+        /// 	connect(s, AF_UNSPEC)
+        /// }
+        /// if (remote_address is Some) {
+        /// 	connect(s, remote_address)
+        /// }
+        /// ```
+        ///
+        /// Unlike in POSIX, the socket must already be explicitly bound.
+        /// 
+        /// # Typical errors
         /// - `invalid-argument`:          The `remote-address` has the wrong address family. (EAFNOSUPPORT)
         /// - `invalid-argument`:          `remote-address` is a non-IPv4-mapped IPv6 address, but the socket was bound to a specific IPv4-mapped IPv6 address. (or vice versa)
         /// - `invalid-argument`:          The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL)
         /// - `invalid-argument`:          The port in `remote-address` is set to 0. (EDESTADDRREQ, EADDRNOTAVAIL)
-        /// - `invalid-argument`:          The socket is already bound to a different network. The `network` passed to `connect` must be identical to the one passed to `bind`.
-        ///
-        /// # Typical `finish` errors
+        /// - `invalid-state`:             The socket is not bound.
         /// - `address-in-use`:            Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD)
-        /// - `not-in-progress`:           A `connect` operation is not in progress.
-        /// - `would-block`:               Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN)
+        /// - `remote-unreachable`:        The remote address is not reachable. (ECONNREFUSED, ECONNRESET, ENETRESET, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN)
         ///
         /// # References
         /// - <https://pubs.opengroup.org/onlinepubs/9699919799/functions/connect.html>
         /// - <https://man7.org/linux/man-pages/man2/connect.2.html>
         /// - <https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-connect>
         /// - <https://man.freebsd.org/cgi/man.cgi?connect>
-        start-connect: func(network: borrow<network>, remote-address: ip-socket-address) -> result<_, error-code>;
-        finish-connect: func() -> result<_, error-code>;
-
-        /// Receive messages on the socket.
-        ///
-        /// This function attempts to receive up to `max-results` datagrams on the socket without blocking.
-        /// The returned list may contain fewer elements than requested, but never more.
-        /// If `max-results` is 0, this function returns successfully with an empty list.
-        ///
-        /// # Typical errors
-        /// - `invalid-state`:      The socket is not bound to any local address. (EINVAL)
-        /// - `remote-unreachable`: The remote address is not reachable. (ECONNREFUSED, ECONNRESET, ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN)
-        /// - `would-block`:        There is no pending data available to be read at the moment. (EWOULDBLOCK, EAGAIN)
-        ///
-        /// # References
-        /// - <https://pubs.opengroup.org/onlinepubs/9699919799/functions/recvfrom.html>
-        /// - <https://pubs.opengroup.org/onlinepubs/9699919799/functions/recvmsg.html>
-        /// - <https://man7.org/linux/man-pages/man2/recv.2.html>
-        /// - <https://man7.org/linux/man-pages/man2/recvmmsg.2.html>
-        /// - <https://learn.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-recv>
-        /// - <https://learn.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-recvfrom>
-        /// - <https://learn.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms741687(v=vs.85)>
-        /// - <https://man.freebsd.org/cgi/man.cgi?query=recv&sektion=2>
-        receive: func(max-results: u64) -> result<list<datagram>, error-code>;
-
-        /// Send messages on the socket.
-        ///
-        /// This function attempts to send all provided `datagrams` on the socket without blocking and
-        /// returns how many messages were actually sent (or queued for sending).
-        ///
-        /// This function semantically behaves the same as iterating the `datagrams` list and sequentially
-        /// sending each individual datagram until either the end of the list has been reached or the first error occurred.
-        /// If at least one datagram has been sent successfully, this function never returns an error.
-        ///
-        /// If the input list is empty, the function returns `ok(0)`.
-        ///
-        /// The remote address option is required. To send a message to the "connected" peer,
-        /// call `remote-address` to get their address.
-        ///
-        /// # Typical errors
-        /// - `invalid-argument`:        The `remote-address` has the wrong address family. (EAFNOSUPPORT)
-        /// - `invalid-argument`:        `remote-address` is a non-IPv4-mapped IPv6 address, but the socket was bound to a specific IPv4-mapped IPv6 address. (or vice versa)
-        /// - `invalid-argument`:        The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL)
-        /// - `invalid-argument`:        The port in `remote-address` is set to 0. (EDESTADDRREQ, EADDRNOTAVAIL)
-        /// - `invalid-argument`:        The socket is in "connected" mode and the `datagram.remote-address` does not match the address passed to `connect`. (EISCONN)
-        /// - `invalid-state`:           The socket is not bound to any local address. Unlike POSIX, this function does not perform an implicit bind.
-        /// - `remote-unreachable`:      The remote address is not reachable. (ECONNREFUSED, ECONNRESET, ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN)
-        /// - `datagram-too-large`:      The datagram is too large. (EMSGSIZE)
-        /// - `would-block`:             The send buffer is currently full. (EWOULDBLOCK, EAGAIN)
-        ///
-        /// # References
-        /// - <https://pubs.opengroup.org/onlinepubs/9699919799/functions/sendto.html>
-        /// - <https://pubs.opengroup.org/onlinepubs/9699919799/functions/sendmsg.html>
-        /// - <https://man7.org/linux/man-pages/man2/send.2.html>
-        /// - <https://man7.org/linux/man-pages/man2/sendmmsg.2.html>
-        /// - <https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-send>
-        /// - <https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-sendto>
-        /// - <https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasendmsg>
-        /// - <https://man.freebsd.org/cgi/man.cgi?query=send&sektion=2>
-        send: func(datagrams: list<datagram>) -> result<u64, error-code>;
+        %stream: func(remote-address: option<ip-socket-address>) -> result<tuple<incoming-datagram-stream, outgoing-datagram-stream>, error-code>;
 
         /// Get the current bound address.
         ///
@@ -146,7 +113,7 @@ interface udp {
         /// > stored in the object pointed to by `address` is unspecified.
         ///
         /// WASI is stricter and requires `local-address` to return `invalid-state` when the socket hasn't been bound yet.
-        ///
+        /// 
         /// # Typical errors
         /// - `invalid-state`: The socket is not bound to any local address.
         ///
@@ -157,10 +124,10 @@ interface udp {
         /// - <https://man.freebsd.org/cgi/man.cgi?getsockname>
         local-address: func() -> result<ip-socket-address, error-code>;
 
-        /// Get the address set with `connect`.
+        /// Get the address the socket is currently streaming to.
         ///
         /// # Typical errors
-        /// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN)
+        /// - `invalid-state`: The socket is not streaming to a specific remote address. (ENOTCONN)
         ///
         /// # References
         /// - <https://pubs.opengroup.org/onlinepubs/9699919799/functions/getpeername.html>
@@ -192,11 +159,11 @@ interface udp {
         /// The kernel buffer space reserved for sends/receives on this socket.
         ///
         /// Note #1: an implementation may choose to cap or round the buffer size when setting the value.
-        ///     In other words, after setting a value, reading the same setting back may return a different value.
+        /// 	In other words, after setting a value, reading the same setting back may return a different value.
         ///
         /// Note #2: there is not necessarily a direct relationship between the kernel buffer size and the bytes of
-        ///     actual data to be sent/received by the application, because the kernel might also use the buffer space
-        ///     for internal metadata structures.
+        /// 	actual data to be sent/received by the application, because the kernel might also use the buffer space
+        /// 	for internal metadata structures.
         ///
         /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options.
         receive-buffer-size: func() -> result<u64, error-code>;
@@ -210,4 +177,93 @@ interface udp {
         /// It's planned to be removed when `future` is natively supported in Preview3.
         subscribe: func() -> pollable;
     }
+
+    resource incoming-datagram-stream {
+        /// Receive messages on the socket.
+        ///
+        /// This function attempts to receive up to `max-results` datagrams on the socket without blocking.
+        /// The returned list may contain fewer elements than requested, but never more.
+        ///
+        /// This function returns successfully with an empty list when either:
+        /// - `max-results` is 0, or:
+        /// - `max-results` is greater than 0, but no results are immediately available.
+        /// This function never returns `error(would-block)`.
+        ///
+        /// # Typical errors
+        /// - `remote-unreachable`: The remote address is not reachable. (ECONNREFUSED, ECONNRESET, ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN)
+        ///
+        /// # References
+        /// - <https://pubs.opengroup.org/onlinepubs/9699919799/functions/recvfrom.html>
+        /// - <https://pubs.opengroup.org/onlinepubs/9699919799/functions/recvmsg.html>
+        /// - <https://man7.org/linux/man-pages/man2/recv.2.html>
+        /// - <https://man7.org/linux/man-pages/man2/recvmmsg.2.html>
+        /// - <https://learn.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-recv>
+        /// - <https://learn.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-recvfrom>
+        /// - <https://learn.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms741687(v=vs.85)>
+        /// - <https://man.freebsd.org/cgi/man.cgi?query=recv&sektion=2>
+        receive: func(max-results: u64) -> result<list<incoming-datagram>, error-code>;
+
+        /// Create a `pollable` which will resolve once the stream is ready to receive again.
+        ///
+        /// Note: this function is here for WASI Preview2 only.
+        /// It's planned to be removed when `future` is natively supported in Preview3.
+        subscribe: func() -> pollable;
+    }
+
+    resource outgoing-datagram-stream {
+        /// Check readiness for sending. This function never blocks.
+        ///
+        /// Returns the number of datagrams permitted for the next call to `send`,
+        /// or an error. Calling `send` with more datagrams than this function has
+        /// permitted will trap.
+        ///
+        /// When this function returns ok(0), the `subscribe` pollable will
+        /// become ready when this function will report at least ok(1), or an
+        /// error.
+        /// 
+        /// Never returns `would-block`.
+        check-send: func() -> result<u64, error-code>;
+
+        /// Send messages on the socket.
+        ///
+        /// This function attempts to send all provided `datagrams` on the socket without blocking and
+        /// returns how many messages were actually sent (or queued for sending). This function never
+        /// returns `error(would-block)`. If none of the datagrams were able to be sent, `ok(0)` is returned.
+        ///
+        /// This function semantically behaves the same as iterating the `datagrams` list and sequentially
+        /// sending each individual datagram until either the end of the list has been reached or the first error occurred.
+        /// If at least one datagram has been sent successfully, this function never returns an error.
+        ///
+        /// If the input list is empty, the function returns `ok(0)`.
+        ///
+        /// Each call to `send` must be permitted by a preceding `check-send`. Implementations must trap if
+        /// either `check-send` was not called or `datagrams` contains more items than `check-send` permitted.
+        ///
+        /// # Typical errors
+        /// - `invalid-argument`:        The `remote-address` has the wrong address family. (EAFNOSUPPORT)
+        /// - `invalid-argument`:        `remote-address` is a non-IPv4-mapped IPv6 address, but the socket was bound to a specific IPv4-mapped IPv6 address. (or vice versa)
+        /// - `invalid-argument`:        The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL)
+        /// - `invalid-argument`:        The port in `remote-address` is set to 0. (EDESTADDRREQ, EADDRNOTAVAIL)
+        /// - `invalid-argument`:        The socket is in "connected" mode and `remote-address` is `some` value that does not match the address passed to `stream`. (EISCONN)
+        /// - `invalid-argument`:        The socket is not "connected" and no value for `remote-address` was provided. (EDESTADDRREQ)
+        /// - `remote-unreachable`:      The remote address is not reachable. (ECONNREFUSED, ECONNRESET, ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN)
+        /// - `datagram-too-large`:      The datagram is too large. (EMSGSIZE)
+        ///
+        /// # References
+        /// - <https://pubs.opengroup.org/onlinepubs/9699919799/functions/sendto.html>
+        /// - <https://pubs.opengroup.org/onlinepubs/9699919799/functions/sendmsg.html>
+        /// - <https://man7.org/linux/man-pages/man2/send.2.html>
+        /// - <https://man7.org/linux/man-pages/man2/sendmmsg.2.html>
+        /// - <https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-send>
+        /// - <https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-sendto>
+        /// - <https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasendmsg>
+        /// - <https://man.freebsd.org/cgi/man.cgi?query=send&sektion=2>
+        send: func(datagrams: list<outgoing-datagram>) -> result<u64, error-code>;
+        
+        /// Create a `pollable` which will resolve once the stream is ready to send again.
+        ///
+        /// Note: this function is here for WASI Preview2 only.
+        /// It's planned to be removed when `future` is natively supported in Preview3.
+        subscribe: func() -> pollable;
+    }
 }
diff --git a/crates/wasmtime/src/config.rs b/crates/wasmtime/src/config.rs
index 1e26adb2c..3f5cb799b 100644
--- a/crates/wasmtime/src/config.rs
+++ b/crates/wasmtime/src/config.rs
@@ -2374,7 +2374,8 @@ impl PoolingAllocationConfig {
     ///   supported
     /// - `disable`: never use MPK
     ///
-    /// By default this value is `disabled`, but may become `auto` in future releases.
+    /// By default this value is `disabled`, but may become `auto` in future
+    /// releases.
     ///
     /// __WARNING__: this configuration options is still experimental--use at
     /// your own risk! MPK uses kernel and CPU features to protect memory
diff --git a/docs/examples-minimal.md b/docs/examples-minimal.md
index 6c0d11cd9..e007e701c 100644
--- a/docs/examples-minimal.md
+++ b/docs/examples-minimal.md
@@ -219,25 +219,63 @@ $ ls -l ./target/aarch64-apple-darwin/release/wasmtime
 ## Minimizing further
 
 Above shows an example of taking the default `cargo build` result of 130M down
-to a 2.1M binary for the `wasmtime` executable. The remaining space in this
-binary is occupied by features which often aren't needed in all embeddings, for
-example:
-
-* Command-line argument parsing via the `clap` crate. Custom embeddings likely
-  won't use this at all and/or will have their own command line parsing
-  elsewhere. In the above 2.1M number this is about ~200k.
-
-* WASI implementations may not all be needed or may be slimmed down. For example
-  the above binary contains two implementations of `wasi_snapshot_preview1` at
-  this time and removing one of them shaves off around 300k.
-
-Most Wasmtime embeddings are unlikely to be the `wasmtime` CLI itself meaning
-that the above sources of size will be eliminated as well in a custom embedding
-of the `wasmtime` crate.
-
-If, however, after applying the above optimizations, flags, etc, results in a
-binary too large for your use case we'd be quite interested to hear about it!
-Please feel free to [open an
-issue](https://github.com/bytecodealliance/wasmtime/issues/new) and let us know.
-There's still remaining fruit to be picked to minimize Wasmtime's footprint
-further and user feedback is helpful to prioritize this work.
+to a 2.1M binary for the `wasmtime` executable. Similar steps can be done to
+reduce the size of the C API binary artifact as well which currently produces a
+~2.8M dynamic library. This is currently the smallest size with the source code
+as-is, but there are more size reductions which haven't been implemented yet.
+
+This is a listing of some example sources of binary size. Some sources of binary
+size may not apply to custom embeddings since, for example, your custom
+embedding might already not use WASI and might already not be included.
+
+* WASI in the Wasmtime CLI - currently the CLI includes all of WASI. This
+  includes two separate implementations of WASI - one for preview2 and one for
+  preview1. This accounts for 1M+ of space which is a significant chunk of the
+  remaining 2.1M.  While removing just preview2 or preview1 would be easy enough
+  with a Cargo feature, the resulting executable wouldn't be able to do
+  anything. Something like a [plugin feature for the
+  CLI](https://github.com/bytecodealliance/wasmtime/issues/7348), however, would
+  enable removing WASI while still being a usable executable.
+
+* Argument parsing in the Wasmtime CLI - as a command line executable `wasmtime`
+  contains parsing of command line arguments which currently uses the `clap`
+  crate. This contributes ~200k of binary size to the final executable which
+  would likely not be present in a custom embedding of Wasmtime. While this
+  can't be removed from Wasmtime it's something to consider when evaluating the
+  size of CI artifacts.
+
+* Cranelift in the C API - one of the features of Wasmtime is the ability to
+  have a runtime without Cranelift that only supports precompiled (AOT) wasm
+  modules. It's [not possible to build the C API without
+  Cranelift](https://github.com/bytecodealliance/wasmtime/issues/7349) though
+  because defining host functions requires Cranelift at this time to emit some
+  stubs.  This means that the C API is significantly larger than a custom Rust
+  embedding which doesn't suffer from the same restriction. This means that
+  while it's still possible to build an embedding of Wasmtime which doesn't have
+  Cranelift it's not easy to see what it might look like size-wise from
+  looking at the C API artifacts.
+
+* Formatting strings in Wasmtime - Wasmtime makes extensive use of formatting
+  strings for error messages and other purposes throughout the implementation.
+  Most of this is intended for debugging and understanding more when something
+  goes wrong, but much of this is not necessary for a truly minimal embedding.
+  In theory much of this could be conditionally compiled out of the Wasmtime
+  project to produce a smaller executable. Just how much of the final binary
+  size is accounted for by formatting string is unknown, but it's well known in
+  Rust that `std::fmt` is not the slimmest of modules.
+
+* Cranelift vs Winch - the "min" builds on CI try to exclude Cranelift from
+  their binary footprint (e.g. the CLI excludes it) but this comes at a cost of
+  the final executable not supporting compilation of wasm modules. If this is
+  required then no effort has yet been put into minimizing the code size of
+  Cranelift itself. One possible tradeoff that can be made though is to choose
+  between the Winch baseline compiler vs Cranelift. Winch should be much smaller
+  from a compiled footprint point of view while not sacrificing everything in
+  terms of performance. Note though that Winch is still under development.
+
+Above are some future avenues to take in terms of reducing the binary size of
+Wasmtime and various tradeoffs that can be made. The Wasmtime project is eager
+to hear embedder use cases/profiles if Wasmtime is not suitable for binary size
+reasons today. Please feel free to [open an
+issue](https://github.com/bytecodealliance/wasmtime/issues/new) and let us know
+and we'd be happy to discuss more how best to handle a particular use case.


Test patch:
diff --git a/cranelift/filetests/filetests/isa/riscv64/zca.clif b/cranelift/filetests/filetests/isa/riscv64/zca.clif
index 5453d4910..6d6620d52 100644
--- a/cranelift/filetests/filetests/isa/riscv64/zca.clif
+++ b/cranelift/filetests/filetests/isa/riscv64/zca.clif
@@ -576,23 +576,44 @@ block0:
 ;   c.addi16sp sp, 0x10
 ;   c.jr ra
 
-function %c_li() -> i64 {
+function %c_li() -> i64, i64, i64, i64, i64 {
 block0:
-  v0 = iconst.i64 1
-  return v0
+  v0 = iconst.i64 0
+  v1 = iconst.i64 1
+  v2 = iconst.i64 -1
+  v3 = iconst.i64 -32
+  v4 = iconst.i64 31
+  return v0, v1, v2, v3, v4
 }
 
 ; VCode:
 ; block0:
-;   li a0,1
+;   li a1,0
+;   mv a5,a1
+;   li a1,1
+;   li a2,-1
+;   li a3,-32
+;   li a4,31
+;   sd a2,0(a0)
+;   sd a3,8(a0)
+;   sd a4,16(a0)
+;   mv a0,a5
 ;   ret
 ;
 ; Disassembled:
 ; block0: ; offset 0x0
-;   c.li a0, 1
+;   c.li a1, 0
+;   c.mv a5, a1
+;   c.li a1, 1
+;   c.li a2, -1
+;   c.li a3, -0x20
+;   c.li a4, 0x1f
+;   c.sd a2, 0(a0)
+;   c.sd a3, 8(a0)
+;   c.sd a4, 0x10(a0)
+;   c.mv a0, a5
 ;   c.jr ra
 
-
 function %c_lui() -> i64, i64, i64 {
 block0:
   v0 = iconst.i64 0x4000
diff --git a/crates/test-programs/src/bin/preview2_udp_sample_application.rs b/crates/test-programs/src/bin/preview2_udp_sample_application.rs
index de8a0a27c..41da701e6 100644
--- a/crates/test-programs/src/bin/preview2_udp_sample_application.rs
+++ b/crates/test-programs/src/bin/preview2_udp_sample_application.rs
@@ -1,9 +1,11 @@
 use test_programs::wasi::sockets::network::{
-    IpAddressFamily, IpSocketAddress, Ipv4SocketAddress, Ipv6SocketAddress, Network,
+    IpAddress, IpAddressFamily, IpSocketAddress, Ipv4SocketAddress, Ipv6SocketAddress, Network,
 };
-use test_programs::wasi::sockets::udp::{Datagram, UdpSocket};
+use test_programs::wasi::sockets::udp::{OutgoingDatagram, UdpSocket};
 
 fn test_sample_application(family: IpAddressFamily, bind_address: IpSocketAddress) {
+    let unspecified_addr = IpSocketAddress::new(IpAddress::new_unspecified(family), 0);
+
     let first_message = &[];
     let second_message = b"Hello, world!";
     let third_message = b"Greetings, planet!";
@@ -13,31 +15,32 @@ fn test_sample_application(family: IpAddressFamily, bind_address: IpSocketAddres
     let server = UdpSocket::new(family).unwrap();
 
     server.blocking_bind(&net, bind_address).unwrap();
+    let (server_incoming, _) = server.stream(None).unwrap();
     let addr = server.local_address().unwrap();
 
     let client_addr = {
         let client = UdpSocket::new(family).unwrap();
-        client.blocking_connect(&net, addr).unwrap();
+        client.blocking_bind(&net, unspecified_addr).unwrap();
+        let (_, client_outgoing) = client.stream(Some(addr)).unwrap();
 
         let datagrams = [
-            Datagram {
+            OutgoingDatagram {
                 data: first_message.to_vec(),
-                remote_address: addr,
+                remote_address: None,
             },
-            Datagram {
+            OutgoingDatagram {
                 data: second_message.to_vec(),
-                remote_address: addr,
+                remote_address: Some(addr),
             },
         ];
-        client.blocking_send(&datagrams).unwrap();
+        client_outgoing.blocking_send(&datagrams).unwrap();
 
         client.local_address().unwrap()
     };
 
     {
         // Check that we've received our sent messages.
-        // Not guaranteed to work but should work in practice.
-        let datagrams = server.blocking_receive(2..100).unwrap();
+        let datagrams = server_incoming.blocking_receive(2..100).unwrap();
         assert_eq!(datagrams.len(), 2);
 
         assert_eq!(datagrams[0].data, first_message);
@@ -50,21 +53,22 @@ fn test_sample_application(family: IpAddressFamily, bind_address: IpSocketAddres
     // Another client
     {
         let client = UdpSocket::new(family).unwrap();
-        client.blocking_connect(&net, addr).unwrap();
+        client.blocking_bind(&net, unspecified_addr).unwrap();
+        let (_, client_outgoing) = client.stream(None).unwrap();
 
-        let datagrams = [Datagram {
+        let datagrams = [OutgoingDatagram {
             data: third_message.to_vec(),
-            remote_address: addr,
+            remote_address: Some(addr),
         }];
-        client.blocking_send(&datagrams).unwrap();
+        client_outgoing.blocking_send(&datagrams).unwrap();
     }
 
     {
         // Check that we sent and received our message!
-        let datagrams = server.blocking_receive(1..100).unwrap();
+        let datagrams = server_incoming.blocking_receive(1..100).unwrap();
         assert_eq!(datagrams.len(), 1);
 
-        assert_eq!(datagrams[0].data, third_message); // Not guaranteed to work but should work in practice.
+        assert_eq!(datagrams[0].data, third_message);
     }
 }
 
diff --git a/crates/test-programs/src/sockets.rs b/crates/test-programs/src/sockets.rs
index 994e0e55e..3033582b6 100644
--- a/crates/test-programs/src/sockets.rs
+++ b/crates/test-programs/src/sockets.rs
@@ -7,7 +7,9 @@ use crate::wasi::sockets::network::{
     Network,
 };
 use crate::wasi::sockets::tcp::TcpSocket;
-use crate::wasi::sockets::udp::{Datagram, UdpSocket};
+use crate::wasi::sockets::udp::{
+    IncomingDatagram, IncomingDatagramStream, OutgoingDatagram, OutgoingDatagramStream, UdpSocket,
+};
 use crate::wasi::sockets::{tcp_create_socket, udp_create_socket};
 use std::ops::Range;
 
@@ -142,42 +144,42 @@ impl UdpSocket {
             }
         }
     }
+}
 
-    pub fn blocking_connect(
-        &self,
-        network: &Network,
-        remote_address: IpSocketAddress,
-    ) -> Result<(), ErrorCode> {
+impl OutgoingDatagramStream {
+    fn blocking_check_send(&self, timeout: &Pollable) -> Result<u64, ErrorCode> {
         let sub = self.subscribe();
 
-        self.start_connect(&network, remote_address)?;
-
         loop {
-            match self.finish_connect() {
-                Err(ErrorCode::WouldBlock) => sub.wait(),
+            match self.check_send() {
+                Ok(0) => sub.wait_until(timeout)?,
                 result => return result,
             }
         }
     }
 
-    pub fn blocking_send(&self, mut datagrams: &[Datagram]) -> Result<(), ErrorCode> {
+    pub fn blocking_send(&self, mut datagrams: &[OutgoingDatagram]) -> Result<(), ErrorCode> {
         let timeout = monotonic_clock::subscribe(TIMEOUT_NS, false);
-        let pollable = self.subscribe();
 
         while !datagrams.is_empty() {
-            match self.send(datagrams) {
+            let permit = self.blocking_check_send(&timeout)?;
+            let chunk_len = datagrams.len().min(permit as usize);
+            match self.send(&datagrams[..chunk_len]) {
+                Ok(0) => {}
                 Ok(packets_sent) => {
-                    datagrams = &datagrams[(packets_sent as usize)..];
+                    let packets_sent = packets_sent as usize;
+                    datagrams = &datagrams[packets_sent..];
                 }
-                Err(ErrorCode::WouldBlock) => pollable.wait_until(&timeout)?,
                 Err(err) => return Err(err),
             }
         }
 
         Ok(())
     }
+}
 
-    pub fn blocking_receive(&self, count: Range<u64>) -> Result<Vec<Datagram>, ErrorCode> {
+impl IncomingDatagramStream {
+    pub fn blocking_receive(&self, count: Range<u64>) -> Result<Vec<IncomingDatagram>, ErrorCode> {
         let timeout = monotonic_clock::subscribe(TIMEOUT_NS, false);
         let pollable = self.subscribe();
         let mut datagrams = vec![];
@@ -187,11 +189,6 @@ impl UdpSocket {
                 Ok(mut chunk) => {
                     datagrams.append(&mut chunk);
 
-                    if datagrams.len() >= count.start as usize {
-                        return Ok(datagrams);
-                    }
-                }
-                Err(ErrorCode::WouldBlock) => {
                     if datagrams.len() >= count.start as usize {
                         return Ok(datagrams);
                     } else {