Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

Remove wasi-threads and wasi-common (#13558)

Alex Crichtonb4b23fe58317
diff --git a/.github/labeler.yml b/.github/labeler.yml
index 1055c283f8..c91f1e68ab 100644
--- a/.github/labeler.yml
+++ b/.github/labeler.yml
@@ -61,7 +61,6 @@
"wasi":
- "crates/wasi/**"
- - "crates/wasi-common/**"
- "crates/wiggle/**"
"wasmtime:api":
diff --git a/Cargo.lock b/Cargo.lock
index 67aa5f5a3c..520c507920 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1377,17 +1377,6 @@ version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
-[[package]]
-name = "fd-lock"
-version = "4.0.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0ce92ff622d6dadf7349484f42c93271a0d49b7cc4d466a936405bacbe10aa78"
-dependencies = [
- "cfg-if",
- "rustix 1.1.4",
- "windows-sys 0.52.0",
-]
-
[[package]]
name = "file-per-thread-logger"
version = "0.2.0"
@@ -2336,17 +2325,6 @@ version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
-[[package]]
-name = "listenfd"
-version = "1.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "14e4fcc00ff6731d94b70e16e71f43bda62883461f31230742e3bc6dddf12988"
-dependencies = [
- "libc",
- "uuid",
- "winapi",
-]
-
[[package]]
name = "litemap"
version = "0.7.4"
@@ -3686,22 +3664,6 @@ dependencies = [
"syn 2.0.106",
]
-[[package]]
-name = "system-interface"
-version = "0.27.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cc4592f674ce18521c2a81483873a49596655b179f71c5e05d10c1fe66c78745"
-dependencies = [
- "bitflags 2.11.1",
- "cap-fs-ext",
- "cap-std",
- "fd-lock",
- "io-lifetimes",
- "rustix 0.38.43",
- "windows-sys 0.52.0",
- "winx",
-]
-
[[package]]
name = "tar"
version = "0.4.46"
@@ -4350,37 +4312,6 @@ dependencies = [
"wit-bindgen-rt",
]
-[[package]]
-name = "wasi-common"
-version = "46.0.0"
-dependencies = [
- "async-trait",
- "bitflags 2.11.1",
- "cap-fs-ext",
- "cap-std",
- "cap-time-ext",
- "fs-set-times",
- "io-extras",
- "io-lifetimes",
- "libc",
- "log",
- "rand 0.10.1",
- "rustix 1.1.4",
- "system-interface",
- "tempfile",
- "test-log",
- "test-programs-artifacts",
- "thiserror 2.0.17",
- "tokio",
- "tracing",
- "tracing-subscriber",
- "wasi-common",
- "wasmtime",
- "wasmtime-environ",
- "wiggle",
- "windows-sys 0.61.2",
-]
-
[[package]]
name = "wasi-nn"
version = "0.6.0"
@@ -4842,7 +4773,6 @@ dependencies = [
"hyper",
"libc",
"libtest-mimic",
- "listenfd",
"log",
"memchr",
"num_cpus",
@@ -4865,7 +4795,6 @@ dependencies = [
"toml",
"tracing",
"walkdir",
- "wasi-common",
"wasm-encoder 0.251.0",
"wasmparser 0.251.0",
"wasmprinter",
@@ -4886,7 +4815,6 @@ dependencies = [
"wasmtime-wasi-http",
"wasmtime-wasi-keyvalue",
"wasmtime-wasi-nn",
- "wasmtime-wasi-threads",
"wasmtime-wasi-tls",
"wasmtime-wast",
"wasmtime-wizer",
@@ -5396,17 +5324,6 @@ dependencies = [
"windows",
]
-[[package]]
-name = "wasmtime-wasi-threads"
-version = "46.0.0"
-dependencies = [
- "log",
- "rand 0.10.1",
- "wasi-common",
- "wasmtime",
- "wasmtime-wasi",
-]
-
[[package]]
name = "wasmtime-wasi-tls"
version = "46.0.0"
diff --git a/Cargo.toml b/Cargo.toml
index 50b4f3575a..47e4fdbe26 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -50,13 +50,11 @@ wasmtime-cranelift = { workspace = true, optional = true }
wasmtime-environ = { workspace = true }
wasmtime-explorer = { workspace = true, optional = true }
wasmtime-wast = { workspace = true, optional = true }
-wasi-common = { workspace = true, default-features = true, features = ["exit", "tokio"], optional = true }
wasmtime-wasi = { workspace = true, default-features = true, optional = true }
wasmtime-wasi-nn = { workspace = true, optional = true }
wasmtime-wasi-config = { workspace = true, optional = true }
wasmtime-wasi-tls = { workspace = true, optional = true }
wasmtime-wasi-keyvalue = { workspace = true, optional = true }
-wasmtime-wasi-threads = { workspace = true, optional = true }
wasmtime-wasi-http = { workspace = true, optional = true }
wasmtime-unwinder = { workspace = true }
wasmtime-wizer = { workspace = true, optional = true, features = ['clap', 'wasmtime'] }
@@ -65,7 +63,6 @@ gdbstub-component-artifact = { workspace = true, optional = true }
clap = { workspace = true }
clap_complete = { workspace = true, optional = true }
target-lexicon = { workspace = true }
-listenfd = { version = "1.0.0", optional = true }
wat = { workspace = true, optional = true }
serde = { workspace = true }
serde_derive = { workspace = true }
@@ -274,7 +271,6 @@ wasmtime-wasi-http = { path = "crates/wasi-http", version = "46.0.0", default-fe
wasmtime-wasi-nn = { path = "crates/wasi-nn", version = "46.0.0" }
wasmtime-wasi-config = { path = "crates/wasi-config", version = "46.0.0" }
wasmtime-wasi-keyvalue = { path = "crates/wasi-keyvalue", version = "46.0.0" }
-wasmtime-wasi-threads = { path = "crates/wasi-threads", version = "46.0.0" }
wasmtime-wasi-tls = { path = "crates/wasi-tls", version = "46.0.0" }
wasmtime-wast = { path = "crates/wast", version = "=46.0.0" }
@@ -309,7 +305,6 @@ wasmtime-wizer = { path = "crates/wizer", version = "46.0.0" }
wiggle = { path = "crates/wiggle", version = "=46.0.0", default-features = false }
wiggle-macro = { path = "crates/wiggle/macro", version = "=46.0.0" }
wiggle-generate = { path = "crates/wiggle/generate", version = "=46.0.0" }
-wasi-common = { path = "crates/wasi-common", version = "=46.0.0", default-features = false }
pulley-interpreter = { path = 'pulley', version = "=46.0.0" }
pulley-macros = { path = 'pulley/macros', version = "=46.0.0" }
@@ -498,7 +493,6 @@ default = [
# On-by-default WASI features
"wasi-nn",
- "wasi-threads",
"wasi-http",
"wasi-config",
"wasi-keyvalue",
@@ -572,7 +566,6 @@ disable-logging = ["log/max_level_off", "tracing/max_level_off"]
# the internal mapping for what they enable in Wasmtime itself.
wasi-nn = ["dep:wasmtime-wasi-nn"]
wasi-tls = ["dep:wasmtime-wasi-tls"]
-wasi-threads = ["dep:wasmtime-wasi-threads", "threads"]
wasi-http = ["component-model", "dep:wasmtime-wasi-http", "dep:tokio", "dep:hyper", "wasmtime-wasi-http/default-send-request"]
wasi-config = ["dep:wasmtime-wasi-config"]
wasi-keyvalue = ["dep:wasmtime-wasi-keyvalue"]
@@ -623,8 +616,6 @@ run = [
"dep:wasmtime-wasi",
"wasmtime/runtime",
"wasmtime/wave",
- "dep:listenfd",
- "dep:wasi-common",
"dep:tokio",
"wasmtime-cli-flags/async",
"wasmtime-wasi-http?/p2",
@@ -647,7 +638,6 @@ hot-blocks = [
wizer = [
"wasmtime-wizer",
"dep:wasmtime-wasi",
- "dep:wasi-common",
"dep:tokio",
"wasmtime/wave",
]
@@ -666,7 +656,6 @@ harness = false
[[example]]
name = "tokio"
-required-features = ["wasi-common/tokio"]
[[bench]]
name = "compile"
diff --git a/crates/wasi-common/Cargo.toml b/crates/wasi-common/Cargo.toml
deleted file mode 100644
index 31ffcf05fc..0000000000
--- a/crates/wasi-common/Cargo.toml
+++ /dev/null
@@ -1,101 +0,0 @@
-[package]
-name = "wasi-common"
-version.workspace = true
-authors.workspace = true
-description = "WASI implementation in Rust"
-license = "Apache-2.0 WITH LLVM-exception"
-categories = ["wasm"]
-keywords = ["webassembly", "wasm"]
-repository = "https://github.com/bytecodealliance/wasmtime"
-readme = "README.md"
-edition.workspace = true
-rust-version.workspace = true
-include = ["src/**/*", "tests/**/*", "witx", "README.md", "LICENSE", "build.rs"]
-
-[lints]
-workspace = true
-
-[dependencies]
-thiserror = { workspace = true }
-wiggle = { workspace = true }
-tracing = { workspace = true }
-cap-std = { workspace = true }
-bitflags = { workspace = true }
-log = { workspace = true }
-rand = { workspace = true, features = ['std_rng', 'thread_rng'] }
-async-trait = { workspace = true }
-wasmtime-environ = { workspace = true }
-
-# Optional, enabled by wasmtime feature:
-wasmtime = { workspace = true, optional = true, features = ['runtime', 'component-model'] }
-# Optional, enabled by sync feature:
-cap-fs-ext = { workspace = true, optional = true }
-cap-time-ext = { workspace = true, optional = true }
-fs-set-times = { workspace = true, optional = true }
-system-interface = { workspace = true, features = ["cap_std_impls"], optional = true }
-io-lifetimes = { workspace = true, optional = true }
-# Optional, enabled by tokio feature:
-tokio = { workspace = true, features = [ "rt", "fs", "time", "io-util", "net", "io-std", "rt-multi-thread"], optional = true }
-
-# Optional, enabled by exit feature:
-libc = { workspace = true, optional = true }
-
-[target.'cfg(unix)'.dependencies]
-rustix = { workspace = true, features = ["fs", "event"] }
-
-[target.'cfg(windows)'.dependencies]
-io-extras = { workspace = true }
-rustix = { workspace = true, features = ["net"] }
-
-[target.'cfg(windows)'.dependencies.windows-sys]
-workspace = true
-features = [
- "Win32_Foundation",
- "Win32_Networking_WinSock",
-]
-
-[dev-dependencies]
-wasi-common = { path = '.', features = ['tokio'] }
-tempfile = { workspace = true }
-test-log = { workspace = true }
-tracing-subscriber = { workspace = true }
-wasmtime = { workspace = true, features = ['cranelift', 'async', 'runtime'] }
-test-programs-artifacts = { workspace = true }
-tokio = { workspace = true, features = ['macros', 'rt-multi-thread'] }
-
-[features]
-default = ["trace_log", "wasmtime", "sync"]
-# This feature enables the `tracing` logs in the calls to target the `log`
-# ecosystem of backends (e.g. `env_logger`. Disable this if you want to use
-# `tracing-subscriber`.
-trace_log = [ "wiggle/tracing_log", "tracing/log" ]
-# Need to make the wiggle_metadata feature available to consumers of this
-# crate if they want the snapshots to have metadata available.
-wiggle_metadata = ["wiggle/wiggle_metadata"]
-# This feature enables integration with wasmtime.
-wasmtime = [
- "dep:wasmtime",
- "wiggle/wasmtime",
-]
-# This feature enables an implementation of the Wasi traits for a
-# synchronous wasmtime embedding.
-sync = [
- "dep:cap-fs-ext",
- "dep:cap-time-ext",
- "dep:fs-set-times",
- "dep:system-interface",
- "dep:io-lifetimes",
-]
-tokio = [
- "sync",
- "wasmtime/async",
- "wiggle/wasmtime_async",
- "dep:tokio",
-]
-exit = [ "wasmtime", "dep:libc" ]
-
-[package.metadata.docs.rs]
-all-features = true
-
-[[test]]
-name = "all"
diff --git a/crates/wasi-common/LICENSE b/crates/wasi-common/LICENSE
deleted file mode 100644
index f9d81955f4..0000000000
--- a/crates/wasi-common/LICENSE
+++ /dev/null
@@ -1,220 +0,0 @@
-
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "[]"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-
-
---- LLVM Exceptions to the Apache 2.0 License ----
-
-As an exception, if, as a result of your compiling your source code, portions
-of this Software are embedded into an Object form of such source code, you
-may redistribute such embedded portions in such Object form without complying
-with the conditions of Sections 4(a), 4(b) and 4(d) of the License.
-
-In addition, if you combine or link compiled forms of this Software with
-software that is licensed under the GPLv2 ("Combined Software") and if a
-court of competent jurisdiction determines that the patent provision (Section
-3), the indemnity provision (Section 9) or other Section of the License
-conflicts with the conditions of the GPLv2, you may retroactively and
-prospectively choose to deem waived or otherwise exclude such Section(s) of
-the License, but only in their entirety and only with respect to the Combined
-Software.
-
diff --git a/crates/wasi-common/README.md b/crates/wasi-common/README.md
deleted file mode 100644
index a6770dbb06..0000000000
--- a/crates/wasi-common/README.md
+++ /dev/null
@@ -1,61 +0,0 @@
-<div align="center">
- <h1><code>wasi-common</code></h1>
-
-<strong>A <a href="https://bytecodealliance.org/">Bytecode Alliance</a> project</strong>
-
- <p>
- <strong>A library providing a common implementation of WASI hostcalls for re-use in any WASI-enabled runtime.</strong>
- </p>
-
- <p>
- <a href="https://crates.io/crates/wasi-common"><img src="https://img.shields.io/crates/v/wasi-common.svg?style=flat-square" alt="Crates.io version" /></a>
- <a href="https://crates.io/crates/wasi-common"><img src="https://img.shields.io/crates/d/wasi-common.svg?style=flat-square" alt="Download" /></a>
- <a href="https://docs.rs/wasi-common/"><img src="https://img.shields.io/badge/docs-latest-blue.svg?style=flat-square" alt="docs.rs docs" /></a>
- </p>
-</div>
-
-The `wasi-common` crate will ultimately serve as a library providing a common implementation of
-WASI hostcalls for re-use in any WASI (and potentially non-WASI) runtimes
-such as [Wasmtime] and [Lucet].
-
-The library is an adaption of [lucet-wasi] crate from the [Lucet] project, and it is
-currently based on [40ae1df][lucet-wasi-tracker] git revision.
-
-Please note that the library requires Rust compiler version at least 1.37.0.
-
-[Wasmtime]: https://github.com/bytecodealliance/wasmtime
-[Lucet]: https://github.com/fastly/lucet
-[lucet-wasi]: https://github.com/fastly/lucet/tree/master/lucet-wasi
-[lucet-wasi-tracker]: https://github.com/fastly/lucet/commit/40ae1df64536250a2b6ab67e7f167d22f4aa7f94
-
-## Supported syscalls
-
-### *nix
-In our *nix implementation, we currently support the entire [WASI API]
-with the exception of the `proc_raise` hostcall, as it is expected to
-be dropped entirely from WASI.
-
-[WASI API]: https://github.com/WebAssembly/WASI/blob/main/legacy/preview1/docs.md
-
-### Windows
-In our Windows implementation, we currently support the minimal subset of [WASI API]
-which allows for running the very basic "Hello world!" style WASM apps. More coming shortly,
-so stay tuned!
-
-## Development hints
-When testing the crate, you may want to enable and run full wasm32 integration testsuite. This
-requires `wasm32-wasip1` target installed which can be done as follows using [rustup]
-
-```
-rustup target add wasm32-wasip1
-```
-
-[rustup]: https://rustup.rs
-
-Now, you should be able to run the integration testsuite by running `cargo test` on the
-`test-programs` package with `test-programs/test_programs` feature enabled:
-
-```
-cargo test --features test-programs/test_programs --package test-programs
-```
-
diff --git a/crates/wasi-common/src/clocks.rs b/crates/wasi-common/src/clocks.rs
deleted file mode 100644
index d72f2f0d99..0000000000
--- a/crates/wasi-common/src/clocks.rs
+++ /dev/null
@@ -1,67 +0,0 @@
-use crate::{Error, ErrorExt};
-use cap_std::time::{Duration, Instant, SystemTime};
-
-pub enum SystemTimeSpec {
- SymbolicNow,
- Absolute(SystemTime),
-}
-
-pub trait WasiSystemClock: Send + Sync {
- fn resolution(&self) -> Duration;
- fn now(&self, precision: Duration) -> SystemTime;
-}
-
-pub trait WasiMonotonicClock: Send + Sync {
- fn resolution(&self) -> Duration;
- fn now(&self, precision: Duration) -> Instant;
-}
-
-pub struct WasiMonotonicOffsetClock {
- pub creation_time: cap_std::time::Instant,
- pub abs_clock: Box<dyn WasiMonotonicClock>,
-}
-
-impl WasiMonotonicOffsetClock {
- pub fn new(clock: impl 'static + WasiMonotonicClock) -> Self {
- Self {
- creation_time: clock.now(clock.resolution()),
- abs_clock: Box::new(clock),
- }
- }
-}
-
-pub struct WasiClocks {
- pub system: Option<Box<dyn WasiSystemClock>>,
- pub monotonic: Option<WasiMonotonicOffsetClock>,
-}
-
-impl WasiClocks {
- pub fn new() -> Self {
- Self {
- system: None,
- monotonic: None,
- }
- }
-
- pub fn with_system(mut self, clock: impl 'static + WasiSystemClock) -> Self {
- self.system = Some(Box::new(clock));
- self
- }
-
- pub fn with_monotonic(mut self, clock: impl 'static + WasiMonotonicClock) -> Self {
- self.monotonic = Some(WasiMonotonicOffsetClock::new(clock));
- self
- }
-
- pub fn system(&self) -> Result<&dyn WasiSystemClock, Error> {
- self.system
- .as_deref()
- .ok_or_else(|| Error::badf().context("system clock is not supported"))
- }
-
- pub fn monotonic(&self) -> Result<&WasiMonotonicOffsetClock, Error> {
- self.monotonic
- .as_ref()
- .ok_or_else(|| Error::badf().context("monotonic clock is not supported"))
- }
-}
diff --git a/crates/wasi-common/src/ctx.rs b/crates/wasi-common/src/ctx.rs
deleted file mode 100644
index 3894b2326d..0000000000
--- a/crates/wasi-common/src/ctx.rs
+++ /dev/null
@@ -1,128 +0,0 @@
-use crate::clocks::WasiClocks;
-use crate::dir::{DirEntry, WasiDir};
-use crate::file::{FileAccessMode, FileEntry, WasiFile};
-use crate::sched::WasiSched;
-use crate::string_array::StringArray;
-use crate::table::Table;
-use crate::{Error, StringArrayError};
-use rand::Rng;
-use std::ops::Deref;
-use std::path::{Path, PathBuf};
-use std::sync::{Arc, Mutex};
-
-/// An `Arc`-wrapper around the wasi-common context to allow mutable access to
-/// the file descriptor table. This wrapper is only necessary due to the
-/// signature of `fd_fdstat_set_flags`; if that changes, there are a variety of
-/// improvements that can be made (TODO:
-/// <https://github.com/bytecodealliance/wasmtime/issues/5643)>.
-#[derive(Clone)]
-pub struct WasiCtx(Arc<WasiCtxInner>);
-
-pub struct WasiCtxInner {
- pub args: StringArray,
- pub env: StringArray,
- // TODO: this mutex should not be necessary, it forces threads to serialize
- // their access to randomness unnecessarily
- // (https://github.com/bytecodealliance/wasmtime/issues/5660).
- pub random: Mutex<Box<dyn Rng + Send + Sync>>,
- pub clocks: WasiClocks,
- pub sched: Box<dyn WasiSched>,
- pub table: Table,
-}
-
-impl WasiCtx {
- pub fn new(
- random: Box<dyn Rng + Send + Sync>,
- clocks: WasiClocks,
- sched: Box<dyn WasiSched>,
- table: Table,
- ) -> Self {
- let s = WasiCtx(Arc::new(WasiCtxInner {
- args: StringArray::new(),
- env: StringArray::new(),
- random: Mutex::new(random),
- clocks,
- sched,
- table,
- }));
- s.set_stdin(Box::new(crate::pipe::ReadPipe::new(std::io::empty())));
- s.set_stdout(Box::new(crate::pipe::WritePipe::new(std::io::sink())));
- s.set_stderr(Box::new(crate::pipe::WritePipe::new(std::io::sink())));
- s
- }
-
- pub fn insert_file(&self, fd: u32, file: Box<dyn WasiFile>, access_mode: FileAccessMode) {
- self.table()
- .insert_at(fd, Arc::new(FileEntry::new(file, access_mode)));
- }
-
- pub fn push_file(
- &self,
- file: Box<dyn WasiFile>,
- access_mode: FileAccessMode,
- ) -> Result<u32, Error> {
- self.table()
- .push(Arc::new(FileEntry::new(file, access_mode)))
- }
-
- pub fn insert_dir(&self, fd: u32, dir: Box<dyn WasiDir>, path: PathBuf) {
- self.table()
- .insert_at(fd, Arc::new(DirEntry::new(Some(path), dir)));
- }
-
- pub fn push_dir(&self, dir: Box<dyn WasiDir>, path: PathBuf) -> Result<u32, Error> {
- self.table().push(Arc::new(DirEntry::new(Some(path), dir)))
- }
-
- pub fn table(&self) -> &Table {
- &self.table
- }
-
- pub fn table_mut(&mut self) -> Option<&mut Table> {
- Arc::get_mut(&mut self.0).map(|c| &mut c.table)
- }
-
- pub fn push_arg(&mut self, arg: &str) -> Result<(), StringArrayError> {
- let s = Arc::get_mut(&mut self.0).expect(
- "`push_arg` should only be used during initialization before the context is cloned",
- );
- s.args.push(arg.to_owned())
- }
-
- pub fn push_env(&mut self, var: &str, value: &str) -> Result<(), StringArrayError> {
- let s = Arc::get_mut(&mut self.0).expect(
- "`push_env` should only be used during initialization before the context is cloned",
- );
- s.env.push(format!("{var}={value}"))?;
- Ok(())
- }
-
- pub fn set_stdin(&self, f: Box<dyn WasiFile>) {
- self.insert_file(0, f, FileAccessMode::READ);
- }
-
- pub fn set_stdout(&self, f: Box<dyn WasiFile>) {
- self.insert_file(1, f, FileAccessMode::WRITE);
- }
-
- pub fn set_stderr(&self, f: Box<dyn WasiFile>) {
- self.insert_file(2, f, FileAccessMode::WRITE);
- }
-
- pub fn push_preopened_dir(
- &self,
- dir: Box<dyn WasiDir>,
- path: impl AsRef<Path>,
- ) -> Result<(), Error> {
- self.table()
- .push(Arc::new(DirEntry::new(Some(path.as_ref().to_owned()), dir)))?;
- Ok(())
- }
-}
-
-impl Deref for WasiCtx {
- type Target = WasiCtxInner;
- fn deref(&self) -> &Self::Target {
- &self.0
- }
-}
diff --git a/crates/wasi-common/src/dir.rs b/crates/wasi-common/src/dir.rs
deleted file mode 100644
index 058e0d3de8..0000000000
--- a/crates/wasi-common/src/dir.rs
+++ /dev/null
@@ -1,140 +0,0 @@
-use crate::file::{FdFlags, FileType, Filestat, OFlags, WasiFile};
-use crate::{Error, ErrorExt, SystemTimeSpec};
-use std::any::Any;
-use std::path::PathBuf;
-use std::sync::Arc;
-
-pub enum OpenResult {
- File(Box<dyn WasiFile>),
- Dir(Box<dyn WasiDir>),
-}
-
-#[async_trait::async_trait]
-pub trait WasiDir: Send + Sync {
- fn as_any(&self) -> &dyn Any;
-
- async fn open_file(
- &self,
- _symlink_follow: bool,
- _path: &str,
- _oflags: OFlags,
- _read: bool,
- _write: bool,
- _fdflags: FdFlags,
- ) -> Result<OpenResult, Error> {
- Err(Error::not_supported())
- }
-
- async fn create_dir(&self, _path: &str) -> Result<(), Error> {
- Err(Error::not_supported())
- }
-
- // XXX the iterator here needs to be asyncified as well!
- async fn readdir(
- &self,
- _cursor: ReaddirCursor,
- ) -> Result<Box<dyn Iterator<Item = Result<ReaddirEntity, Error>> + Send>, Error> {
- Err(Error::not_supported())
- }
-
- async fn symlink(&self, _old_path: &str, _new_path: &str) -> Result<(), Error> {
- Err(Error::not_supported())
- }
-
- async fn remove_dir(&self, _path: &str) -> Result<(), Error> {
- Err(Error::not_supported())
- }
-
- async fn unlink_file(&self, _path: &str) -> Result<(), Error> {
- Err(Error::not_supported())
- }
-
- async fn read_link(&self, _path: &str) -> Result<PathBuf, Error> {
- Err(Error::not_supported())
- }
-
- async fn get_filestat(&self) -> Result<Filestat, Error> {
- Err(Error::not_supported())
- }
-
- async fn get_path_filestat(
- &self,
- _path: &str,
- _follow_symlinks: bool,
- ) -> Result<Filestat, Error> {
- Err(Error::not_supported())
- }
-
- async fn rename(
- &self,
- _path: &str,
- _dest_dir: &dyn WasiDir,
- _dest_path: &str,
- ) -> Result<(), Error> {
- Err(Error::not_supported())
- }
-
- async fn hard_link(
- &self,
- _path: &str,
- _target_dir: &dyn WasiDir,
- _target_path: &str,
- ) -> Result<(), Error> {
- Err(Error::not_supported())
- }
-
- async fn set_times(
- &self,
- _path: &str,
- _atime: Option<SystemTimeSpec>,
- _mtime: Option<SystemTimeSpec>,
- _follow_symlinks: bool,
- ) -> Result<(), Error> {
- Err(Error::not_supported())
- }
-}
-
-pub(crate) struct DirEntry {
- preopen_path: Option<PathBuf>, // precondition: PathBuf is valid unicode
- pub dir: Box<dyn WasiDir>,
-}
-
-impl DirEntry {
- pub fn new(preopen_path: Option<PathBuf>, dir: Box<dyn WasiDir>) -> Self {
- DirEntry { preopen_path, dir }
- }
- pub fn preopen_path(&self) -> &Option<PathBuf> {
- &self.preopen_path
- }
-}
-
-pub(crate) trait TableDirExt {
- fn get_dir(&self, fd: u32) -> Result<Arc<DirEntry>, Error>;
-}
-
-impl TableDirExt for crate::table::Table {
- fn get_dir(&self, fd: u32) -> Result<Arc<DirEntry>, Error> {
- self.get(fd)
- }
-}
-
-#[derive(Debug, Clone)]
-pub struct ReaddirEntity {
- pub next: ReaddirCursor,
- pub inode: u64,
- pub name: String,
- pub filetype: FileType,
-}
-
-#[derive(Debug, Copy, Clone)]
-pub struct ReaddirCursor(u64);
-impl From<u64> for ReaddirCursor {
- fn from(c: u64) -> ReaddirCursor {
- ReaddirCursor(c)
- }
-}
-impl From<ReaddirCursor> for u64 {
- fn from(c: ReaddirCursor) -> u64 {
- c.0
- }
-}
diff --git a/crates/wasi-common/src/error.rs b/crates/wasi-common/src/error.rs
deleted file mode 100644
index a4e52a4efa..0000000000
--- a/crates/wasi-common/src/error.rs
+++ /dev/null
@@ -1,26 +0,0 @@
-//! wasi-common uses an [`Error`] type which represents either a preview 1 [`Errno`] enum, on
-//! [`wasmtime_environ::error::Error`] for trapping execution.
-//!
-//! The user can construct an [`Error`] out of an [`Errno`] using the `From`/`Into` traits.
-//! They may also use [`Error::trap`] to construct an error that traps execution. The contents
-//! can be inspected with [`Error::downcast`] and [`Error::downcast_ref`]. Additional context
-//! can be provided with the [`Error::context`] method. This context is only observable with the
-//! `Display` and `Debug` impls of the error.
-
-pub use crate::snapshots::preview_1::error::{Error, ErrorExt};
-use std::fmt;
-
-/// An error returned from the `proc_exit` host syscall.
-///
-/// Embedders can test if an error returned from wasm is this error, in which
-/// case it may signal a non-fatal trap.
-#[derive(Debug)]
-pub struct I32Exit(pub i32);
-
-impl fmt::Display for I32Exit {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- write!(f, "Exited with i32 exit status {}", self.0)
- }
-}
-
-impl std::error::Error for I32Exit {}
diff --git a/crates/wasi-common/src/file.rs b/crates/wasi-common/src/file.rs
deleted file mode 100644
index 514892e591..0000000000
--- a/crates/wasi-common/src/file.rs
+++ /dev/null
@@ -1,269 +0,0 @@
-use crate::{Error, ErrorExt, SystemTimeSpec};
-use bitflags::bitflags;
-use std::any::Any;
-use std::sync::Arc;
-
-#[async_trait::async_trait]
-pub trait WasiFile: Send + Sync {
- fn as_any(&self) -> &dyn Any;
- async fn get_filetype(&self) -> Result<FileType, Error>;
-
- #[cfg(unix)]
- fn pollable(&self) -> Option<rustix::fd::BorrowedFd<'_>> {
- None
- }
-
- #[cfg(windows)]
- fn pollable(&self) -> Option<io_extras::os::windows::RawHandleOrSocket> {
- None
- }
-
- fn isatty(&self) -> bool {
- false
- }
-
- async fn sock_accept(&self, _fdflags: FdFlags) -> Result<Box<dyn WasiFile>, Error> {
- Err(Error::badf())
- }
-
- async fn sock_recv<'a>(
- &self,
- _ri_data: &mut [std::io::IoSliceMut<'a>],
- _ri_flags: RiFlags,
- ) -> Result<(u64, RoFlags), Error> {
- Err(Error::badf())
- }
-
- async fn sock_send<'a>(
- &self,
- _si_data: &[std::io::IoSlice<'a>],
- _si_flags: SiFlags,
- ) -> Result<u64, Error> {
- Err(Error::badf())
- }
-
- async fn sock_shutdown(&self, _how: SdFlags) -> Result<(), Error> {
- Err(Error::badf())
- }
-
- async fn datasync(&self) -> Result<(), Error> {
- Ok(())
- }
-
- async fn sync(&self) -> Result<(), Error> {
- Ok(())
- }
-
- async fn get_fdflags(&self) -> Result<FdFlags, Error> {
- Ok(FdFlags::empty())
- }
-
- async fn set_fdflags(&mut self, _flags: FdFlags) -> Result<(), Error> {
- Err(Error::badf())
- }
-
- async fn get_filestat(&self) -> Result<Filestat, Error> {
- Ok(Filestat {
- device_id: 0,
- inode: 0,
- filetype: self.get_filetype().await?,
- nlink: 0,
- size: 0, // XXX no way to get a size out of a Read :(
- atim: None,
- mtim: None,
- ctim: None,
- })
- }
-
- async fn set_filestat_size(&self, _size: u64) -> Result<(), Error> {
- Err(Error::badf())
- }
-
- async fn advise(&self, _offset: u64, _len: u64, _advice: Advice) -> Result<(), Error> {
- Err(Error::badf())
- }
-
- async fn set_times(
- &self,
- _atime: Option<SystemTimeSpec>,
- _mtime: Option<SystemTimeSpec>,
- ) -> Result<(), Error> {
- Err(Error::badf())
- }
-
- async fn read_vectored<'a>(&self, _bufs: &mut [std::io::IoSliceMut<'a>]) -> Result<u64, Error> {
- Err(Error::badf())
- }
-
- async fn read_vectored_at<'a>(
- &self,
- _bufs: &mut [std::io::IoSliceMut<'a>],
- _offset: u64,
- ) -> Result<u64, Error> {
- Err(Error::badf())
- }
-
- async fn write_vectored<'a>(&self, _bufs: &[std::io::IoSlice<'a>]) -> Result<u64, Error> {
- Err(Error::badf())
- }
-
- async fn write_vectored_at<'a>(
- &self,
- _bufs: &[std::io::IoSlice<'a>],
- _offset: u64,
- ) -> Result<u64, Error> {
- Err(Error::badf())
- }
-
- async fn seek(&self, _pos: std::io::SeekFrom) -> Result<u64, Error> {
- Err(Error::badf())
- }
-
- async fn peek(&self, _buf: &mut [u8]) -> Result<u64, Error> {
- Err(Error::badf())
- }
-
- fn num_ready_bytes(&self) -> Result<u64, Error> {
- Ok(0)
- }
-
- async fn readable(&self) -> Result<(), Error> {
- Err(Error::badf())
- }
-
- async fn writable(&self) -> Result<(), Error> {
- Err(Error::badf())
- }
-}
-
-#[derive(Debug, Copy, Clone, PartialEq, Eq)]
-pub enum FileType {
- Unknown,
- BlockDevice,
- CharacterDevice,
- Directory,
- RegularFile,
- SocketDgram,
- SocketStream,
- SymbolicLink,
- Pipe,
-}
-
-bitflags! {
- #[derive(Copy, Clone, Debug, PartialEq, Eq)]
- pub struct FdFlags: u32 {
- const APPEND = 0b1;
- const DSYNC = 0b10;
- const NONBLOCK = 0b100;
- const RSYNC = 0b1000;
- const SYNC = 0b10000;
- }
-}
-
-bitflags! {
- #[derive(Copy, Clone, Debug, PartialEq, Eq)]
- pub struct SdFlags: u32 {
- const RD = 0b1;
- const WR = 0b10;
- }
-}
-
-bitflags! {
- #[derive(Copy, Clone, Debug, PartialEq, Eq)]
- pub struct SiFlags: u32 {
- }
-}
-
-bitflags! {
- #[derive(Copy, Clone, Debug, PartialEq, Eq)]
- pub struct RiFlags: u32 {
- const RECV_PEEK = 0b1;
- const RECV_WAITALL = 0b10;
- }
-}
-
-bitflags! {
- #[derive(Copy, Clone, Debug, PartialEq, Eq)]
- pub struct RoFlags: u32 {
- const RECV_DATA_TRUNCATED = 0b1;
- }
-}
-
-bitflags! {
- #[derive(Copy, Clone, Debug, PartialEq, Eq)]
- pub struct OFlags: u32 {
- const CREATE = 0b1;
- const DIRECTORY = 0b10;
- const EXCLUSIVE = 0b100;
- const TRUNCATE = 0b1000;
- }
-}
-
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct Filestat {
- pub device_id: u64,
- pub inode: u64,
- pub filetype: FileType,
- pub nlink: u64,
- pub size: u64, // this is a read field, the rest are file fields
- pub atim: Option<std::time::SystemTime>,
- pub mtim: Option<std::time::SystemTime>,
- pub ctim: Option<std::time::SystemTime>,
-}
-
-pub(crate) trait TableFileExt {
- fn get_file(&self, fd: u32) -> Result<Arc<FileEntry>, Error>;
- fn get_file_mut(&mut self, fd: u32) -> Result<&mut FileEntry, Error>;
-}
-impl TableFileExt for crate::table::Table {
- fn get_file(&self, fd: u32) -> Result<Arc<FileEntry>, Error> {
- self.get(fd)
- }
- fn get_file_mut(&mut self, fd: u32) -> Result<&mut FileEntry, Error> {
- self.get_mut(fd)
- }
-}
-
-pub(crate) struct FileEntry {
- pub file: Box<dyn WasiFile>,
- pub access_mode: FileAccessMode,
-}
-
-bitflags! {
- #[derive(Copy, Clone, Debug, PartialEq, Eq)]
- pub struct FileAccessMode : u32 {
- const READ = 0b1;
- const WRITE= 0b10;
- }
-}
-
-impl FileEntry {
- pub fn new(file: Box<dyn WasiFile>, access_mode: FileAccessMode) -> Self {
- FileEntry { file, access_mode }
- }
-
- pub async fn get_fdstat(&self) -> Result<FdStat, Error> {
- Ok(FdStat {
- filetype: self.file.get_filetype().await?,
- flags: self.file.get_fdflags().await?,
- access_mode: self.access_mode,
- })
- }
-}
-
-#[derive(Debug, Clone)]
-pub struct FdStat {
- pub filetype: FileType,
- pub flags: FdFlags,
- pub access_mode: FileAccessMode,
-}
-
-#[derive(Debug, Clone)]
-pub enum Advice {
- Normal,
- Sequential,
- Random,
- WillNeed,
- DontNeed,
- NoReuse,
-}
diff --git a/crates/wasi-common/src/lib.rs b/crates/wasi-common/src/lib.rs
deleted file mode 100644
index 1e7a915ef5..0000000000
--- a/crates/wasi-common/src/lib.rs
+++ /dev/null
@@ -1,190 +0,0 @@
-//! # wasi-common
-//!
-//! This is Wasmtime's legacy implementation of WASI 0.1 (Preview 1). The
-//! Wasmtime maintainers suggest all users upgrade to the implementation
-//! of WASI 0.1 and 0.2 provided by the `wasmtime-wasi` crate. This
-//! implementation remains in the wasmtime tree because it is required to use
-//! the `wasmtime-wasi-threads` crate, an implementation of the `wasi-threads`
-//! proposal which is not compatible with WASI 0.2.
-//!
-//! In addition to integration with Wasmtime, this implementation may be used
-//! by other runtimes by disabling the `wasmtime` feature on this crate.
-//!
-//! ## The `WasiFile` and `WasiDir` traits
-//!
-//! The WASI specification only defines one `handle` type, `fd`, on which all
-//! operations on both files and directories (aka dirfds) are defined. We
-//! believe this is a design mistake, and are architecting wasi-common to make
-//! this straightforward to correct in future snapshots of WASI. Wasi-common
-//! internally treats files and directories as two distinct resource types in
-//! the table - `Box<dyn WasiFile>` and `Box<dyn WasiDir>`. The snapshot 0 and
-//! 1 interfaces via `fd` will attempt to downcast a table element to one or
-//! both of these interfaces depending on what is appropriate - e.g.
-//! `fd_close` operates on both files and directories, `fd_read` only operates
-//! on files, and `fd_readdir` only operates on directories.
-
-//! The `WasiFile` and `WasiDir` traits are defined by `wasi-common` in terms
-//! of types defined directly in the crate's source code (I decided it should
-//! NOT those generated by the `wiggle` proc macros, see snapshot architecture
-//! below), as well as the `cap_std::time` family of types. And, importantly,
-//! `wasi-common` itself provides no implementation of `WasiDir`, and only two
-//! trivial implementations of `WasiFile` on the `crate::pipe::{ReadPipe,
-//! WritePipe}` types, which in turn just delegate to `std::io::{Read,
-//! Write}`. In order for `wasi-common` to access the local filesystem at all,
-//! you need to provide `WasiFile` and `WasiDir` impls through either the new
-//! `wasi-cap-std-sync` crate found at `crates/wasi-common/cap-std-sync` - see
-//! the section on that crate below - or by providing your own implementation
-//! from elsewhere.
-//!
-//! This design makes it possible for `wasi-common` embedders to statically
-//! reason about access to the local filesystem by examining what impls are
-//! linked into an application. We found that this separation of concerns also
-//! makes it pretty enjoyable to write alternative implementations, e.g. a
-//! virtual filesystem.
-//!
-//! Implementations of the `WasiFile` and `WasiDir` traits are provided
-//! for synchronous embeddings in `wasi_common::sync` and for Tokio embeddings
-//! in `wasi_common::tokio`.
-//!
-//! ## Traits for the rest of WASI's features
-//!
-//! Other aspects of a WASI implementation are not yet considered resources
-//! and accessed by `handle`. We plan to correct this design deficiency in
-//! WASI in the future, but for now we have designed the following traits to
-//! provide embedders with the same sort of implementation flexibility they
-//! get with WasiFile/WasiDir:
-//!
-//! * Timekeeping: `WasiSystemClock` and `WasiMonotonicClock` provide the two
-//! interfaces for a clock. `WasiSystemClock` represents time as a
-//! `cap_std::time::SystemTime`, and `WasiMonotonicClock` represents time as
-//! `cap_std::time::Instant`. * Randomness: we re-use the `cap_rand::RngCore`
-//! trait to represent a randomness source. A trivial `Deterministic` impl is
-//! provided. * Scheduling: The `WasiSched` trait abstracts over the
-//! `sched_yield` and `poll_oneoff` functions.
-//!
-//! Users can provide implementations of each of these interfaces to the
-//! `WasiCtx::builder(...)` function. The
-//! `wasi_cap_std_sync::WasiCtxBuilder::new()` function uses this public
-//! interface to plug in its own implementations of each of these resources.
-
-#![warn(clippy::cast_sign_loss)]
-#![cfg_attr(docsrs, feature(doc_cfg))]
-
-pub mod clocks;
-mod ctx;
-pub mod dir;
-mod error;
-pub mod file;
-pub mod pipe;
-pub mod random;
-pub mod sched;
-pub mod snapshots;
-mod string_array;
-#[cfg_attr(docsrs, doc(cfg(feature = "sync")))]
-#[cfg(feature = "sync")]
-pub mod sync;
-pub mod table;
-#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
-#[cfg(feature = "tokio")]
-pub mod tokio;
-
-pub use clocks::{SystemTimeSpec, WasiClocks, WasiMonotonicClock, WasiSystemClock};
-pub use ctx::WasiCtx;
-pub use dir::WasiDir;
-pub use error::{Error, ErrorExt, I32Exit};
-pub use file::WasiFile;
-pub use rand::TryRng;
-pub use sched::{Poll, WasiSched};
-pub use string_array::{StringArray, StringArrayError};
-pub use table::Table;
-
-pub(crate) use wasmtime_environ::error::Error as EnvError;
-
-// The only difference between these definitions for sync vs async is whether
-// the wasmtime::Funcs generated are async (& therefore need an async Store and an executor to run)
-// or whether they have an internal "dummy executor" that expects the implementation of all
-// the async funcs to poll to Ready immediately.
-#[cfg(feature = "wasmtime")]
-#[doc(hidden)]
-#[macro_export]
-macro_rules! define_wasi {
- ($async_mode:tt $($bounds:tt)*) => {
-
- use wasmtime::Linker;
- use wasmtime_environ::error::Result as EnvResult;
-
- pub fn add_to_linker<T, U>(
- linker: &mut Linker<T>,
- get_cx: impl Fn(&mut T) -> &mut U + Send + Sync + Copy + 'static,
- ) -> EnvResult<()>
- where U: Send
- + crate::snapshots::preview_0::wasi_unstable::WasiUnstable
- + crate::snapshots::preview_1::wasi_snapshot_preview1::WasiSnapshotPreview1,
- T: 'static,
- $($bounds)*
- {
- snapshots::preview_1::add_wasi_snapshot_preview1_to_linker(linker, get_cx)?;
- snapshots::preview_0::add_wasi_unstable_to_linker(linker, get_cx)?;
- Ok(())
- }
-
- pub mod snapshots {
- pub mod preview_1 {
- wiggle::wasmtime_integration!({
- // The wiggle code to integrate with lives here:
- target: crate::snapshots::preview_1,
- witx: ["witx/preview1/wasi_snapshot_preview1.witx"],
- errors: { errno => trappable Error },
- $async_mode: *
- });
- }
- pub mod preview_0 {
- wiggle::wasmtime_integration!({
- // The wiggle code to integrate with lives here:
- target: crate::snapshots::preview_0,
- witx: ["witx/preview0/wasi_unstable.witx"],
- errors: { errno => trappable Error },
- $async_mode: *
- });
- }
- }
-}}
-
-/// Exit the process with a conventional OS error code as long as Wasmtime
-/// understands the error. If the error is not an `I32Exit` or `Trap`, return
-/// the error back to the caller for it to decide what to do.
-///
-/// Note: this function is designed for usage where it is acceptable for
-/// Wasmtime failures to terminate the parent process, such as in the Wasmtime
-/// CLI; this would not be suitable for use in multi-tenant embeddings.
-#[cfg_attr(docsrs, doc(cfg(feature = "exit")))]
-#[cfg(feature = "exit")]
-pub fn maybe_exit_on_error(e: EnvError) -> EnvError {
- use std::process;
- use wasmtime::Trap;
-
- // If a specific WASI error code was requested then that's
- // forwarded through to the process here without printing any
- // extra error information.
- if let Some(exit) = e.downcast_ref::<crate::I32Exit>() {
- process::exit(exit.0);
- }
-
- // If the program exited because of a trap, return an error code
- // to the outside environment indicating a more severe problem
- // than a simple failure.
- if e.is::<Trap>() {
- eprintln!("Error: {e:?}");
-
- if cfg!(unix) {
- // On Unix, return the error code of an abort.
- process::exit(128 + libc::SIGABRT);
- } else if cfg!(windows) {
- // On Windows, return 3.
- // https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/abort?view=vs-2019
- process::exit(3);
- }
- }
-
- e
-}
diff --git a/crates/wasi-common/src/pipe.rs b/crates/wasi-common/src/pipe.rs
deleted file mode 100644
index a7e00242f9..0000000000
--- a/crates/wasi-common/src/pipe.rs
+++ /dev/null
@@ -1,201 +0,0 @@
-//! Virtual pipes.
-//!
-//! These types provide easy implementations of `WasiFile` that mimic much of the behavior of Unix
-//! pipes. These are particularly helpful for redirecting WASI stdio handles to destinations other
-//! than OS files.
-//!
-//! Some convenience constructors are included for common backing types like `Vec<u8>` and `String`,
-//! but the virtual pipes can be instantiated with any `Read` or `Write` type.
-//!
-use crate::Error;
-use crate::file::{FdFlags, FileType, WasiFile};
-use std::any::Any;
-use std::io::{self, Read, Write};
-use std::sync::{Arc, RwLock};
-
-/// A virtual pipe read end.
-///
-/// A variety of `From` impls are provided so that common pipe types are easy to create. For example:
-///
-/// ```rust
-/// use wasi_common::{pipe::ReadPipe, WasiCtx, Table};
-/// let stdin = ReadPipe::from("hello from stdin!");
-/// // Bring these instances from elsewhere (e.g. wasi-cap-std-sync or wasi-cap-std-tokio):
-/// use wasi_common::sync::{random_ctx, clocks_ctx, sched_ctx};
-/// let random = random_ctx();
-/// let clocks = clocks_ctx();
-/// let sched = sched_ctx();
-/// let table = Table::new();
-/// let mut ctx = WasiCtx::new(random, clocks, sched, table);
-/// ctx.set_stdin(Box::new(stdin.clone()));
-/// ```
-#[derive(Debug)]
-pub struct ReadPipe<R: Read> {
- reader: Arc<RwLock<R>>,
-}
-
-impl<R: Read> Clone for ReadPipe<R> {
- fn clone(&self) -> Self {
- Self {
- reader: self.reader.clone(),
- }
- }
-}
-
-impl<R: Read> ReadPipe<R> {
- /// Create a new pipe from a `Read` type.
- ///
- /// All `Handle` read operations delegate to reading from this underlying reader.
- pub fn new(r: R) -> Self {
- Self::from_shared(Arc::new(RwLock::new(r)))
- }
-
- /// Create a new pipe from a shareable `Read` type.
- ///
- /// All `Handle` read operations delegate to reading from this underlying reader.
- pub fn from_shared(reader: Arc<RwLock<R>>) -> Self {
- Self { reader }
- }
-
- /// Try to convert this `ReadPipe<R>` back to the underlying `R` type.
- ///
- /// This will fail with `Err(self)` if multiple references to the underlying `R` exist.
- pub fn try_into_inner(mut self) -> Result<R, Self> {
- match Arc::try_unwrap(self.reader) {
- Ok(rc) => Ok(RwLock::into_inner(rc).unwrap()),
- Err(reader) => {
- self.reader = reader;
- Err(self)
- }
- }
- }
- fn borrow(&self) -> std::sync::RwLockWriteGuard<'_, R> {
- RwLock::write(&self.reader).unwrap()
- }
-}
-
-impl From<Vec<u8>> for ReadPipe<io::Cursor<Vec<u8>>> {
- fn from(r: Vec<u8>) -> Self {
- Self::new(io::Cursor::new(r))
- }
-}
-
-impl From<&[u8]> for ReadPipe<io::Cursor<Vec<u8>>> {
- fn from(r: &[u8]) -> Self {
- Self::from(r.to_vec())
- }
-}
-
-impl From<String> for ReadPipe<io::Cursor<String>> {
- fn from(r: String) -> Self {
- Self::new(io::Cursor::new(r))
- }
-}
-
-impl From<&str> for ReadPipe<io::Cursor<String>> {
- fn from(r: &str) -> Self {
- Self::from(r.to_string())
- }
-}
-
-#[async_trait::async_trait]
-impl<R: Read + Any + Send + Sync> WasiFile for ReadPipe<R> {
- fn as_any(&self) -> &dyn Any {
- self
- }
- async fn get_filetype(&self) -> Result<FileType, Error> {
- Ok(FileType::Pipe)
- }
- async fn read_vectored<'a>(&self, bufs: &mut [io::IoSliceMut<'a>]) -> Result<u64, Error> {
- let n = self.borrow().read_vectored(bufs)?;
- Ok(n.try_into()?)
- }
-}
-
-/// A virtual pipe write end.
-///
-/// ```rust
-/// use wasi_common::{pipe::WritePipe, WasiCtx, Table};
-/// let stdout = WritePipe::new_in_memory();
-/// // Bring these instances from elsewhere (e.g. wasi-cap-std-sync or wasi-cap-std-tokio):
-/// use wasi_common::sync::{random_ctx, clocks_ctx, sched_ctx};
-/// let random = random_ctx();
-/// let clocks = clocks_ctx();
-/// let sched = sched_ctx();
-/// let table = Table::new();
-/// let mut ctx = WasiCtx::new(random, clocks, sched, table);
-/// ctx.set_stdout(Box::new(stdout.clone()));
-/// // use ctx in an instance, then make sure it is dropped:
-/// drop(ctx);
-/// let contents: Vec<u8> = stdout.try_into_inner().expect("sole remaining reference to WritePipe").into_inner();
-/// println!("contents of stdout: {:?}", contents);
-/// ```
-#[derive(Debug)]
-pub struct WritePipe<W: Write> {
- writer: Arc<RwLock<W>>,
-}
-
-impl<W: Write> Clone for WritePipe<W> {
- fn clone(&self) -> Self {
- Self {
- writer: self.writer.clone(),
- }
- }
-}
-
-impl<W: Write> WritePipe<W> {
- /// Create a new pipe from a `Write` type.
- ///
- /// All `Handle` write operations delegate to writing to this underlying writer.
- pub fn new(w: W) -> Self {
- Self::from_shared(Arc::new(RwLock::new(w)))
- }
-
- /// Create a new pipe from a shareable `Write` type.
- ///
- /// All `Handle` write operations delegate to writing to this underlying writer.
- pub fn from_shared(writer: Arc<RwLock<W>>) -> Self {
- Self { writer }
- }
-
- /// Try to convert this `WritePipe<W>` back to the underlying `W` type.
- ///
- /// This will fail with `Err(self)` if multiple references to the underlying `W` exist.
- pub fn try_into_inner(mut self) -> Result<W, Self> {
- match Arc::try_unwrap(self.writer) {
- Ok(rc) => Ok(RwLock::into_inner(rc).unwrap()),
- Err(writer) => {
- self.writer = writer;
- Err(self)
- }
- }
- }
-
- fn borrow(&self) -> std::sync::RwLockWriteGuard<'_, W> {
- RwLock::write(&self.writer).unwrap()
- }
-}
-
-impl WritePipe<io::Cursor<Vec<u8>>> {
- /// Create a new writable virtual pipe backed by a `Vec<u8>` buffer.
- pub fn new_in_memory() -> Self {
- Self::new(io::Cursor::new(vec![]))
- }
-}
-
-#[async_trait::async_trait]
-impl<W: Write + Any + Send + Sync> WasiFile for WritePipe<W> {
- fn as_any(&self) -> &dyn Any {
- self
- }
- async fn get_filetype(&self) -> Result<FileType, Error> {
- Ok(FileType::Pipe)
- }
- async fn get_fdflags(&self) -> Result<FdFlags, Error> {
- Ok(FdFlags::APPEND)
- }
- async fn write_vectored<'a>(&self, bufs: &[io::IoSlice<'a>]) -> Result<u64, Error> {
- let n = self.borrow().write_vectored(bufs)?;
- Ok(n.try_into()?)
- }
-}
diff --git a/crates/wasi-common/src/random.rs b/crates/wasi-common/src/random.rs
deleted file mode 100644
index e28d318de6..0000000000
--- a/crates/wasi-common/src/random.rs
+++ /dev/null
@@ -1,51 +0,0 @@
-use core::convert::Infallible;
-use rand::{Rng, TryRng};
-
-/// Implement `WasiRandom` using a deterministic cycle of bytes.
-pub struct Deterministic {
- cycle: std::iter::Cycle<std::vec::IntoIter<u8>>,
-}
-
-impl Deterministic {
- pub fn new(bytes: Vec<u8>) -> Self {
- Deterministic {
- cycle: bytes.into_iter().cycle(),
- }
- }
-}
-
-impl TryRng for Deterministic {
- type Error = Infallible;
- fn try_next_u32(&mut self) -> Result<u32, Infallible> {
- let b0 = self.cycle.next().expect("infinite sequence");
- let b1 = self.cycle.next().expect("infinite sequence");
- let b2 = self.cycle.next().expect("infinite sequence");
- let b3 = self.cycle.next().expect("infinite sequence");
- Ok(((b0 as u32) << 24) + ((b1 as u32) << 16) + ((b2 as u32) << 8) + (b3 as u32))
- }
- fn try_next_u64(&mut self) -> Result<u64, Infallible> {
- let w0 = self.next_u32();
- let w1 = self.next_u32();
- Ok(((w0 as u64) << 32) + (w1 as u64))
- }
- fn try_fill_bytes(&mut self, buf: &mut [u8]) -> Result<(), Infallible> {
- for b in buf.iter_mut() {
- *b = self.cycle.next().expect("infinite sequence");
- }
- Ok(())
- }
-}
-
-#[cfg(test)]
-mod test {
- use super::*;
- #[test]
- fn deterministic() {
- let mut det = Deterministic::new(vec![1, 2, 3, 4]);
- let mut buf = vec![0; 1024];
- det.try_fill_bytes(&mut buf).expect("get randomness");
- for (ix, b) in buf.iter().enumerate() {
- assert_eq!(*b, (ix % 4) as u8 + 1)
- }
- }
-}
diff --git a/crates/wasi-common/src/sched.rs b/crates/wasi-common/src/sched.rs
deleted file mode 100644
index 52a28e8887..0000000000
--- a/crates/wasi-common/src/sched.rs
+++ /dev/null
@@ -1,91 +0,0 @@
-use crate::Error;
-use crate::clocks::WasiMonotonicClock;
-use crate::file::WasiFile;
-use cap_std::time::Instant;
-pub mod subscription;
-pub use cap_std::time::Duration;
-
-pub use subscription::{
- MonotonicClockSubscription, RwEventFlags, RwSubscription, Subscription, SubscriptionResult,
-};
-
-#[async_trait::async_trait]
-pub trait WasiSched: Send + Sync {
- async fn poll_oneoff<'a>(&self, poll: &mut Poll<'a>) -> Result<(), Error>;
- async fn sched_yield(&self) -> Result<(), Error>;
- async fn sleep(&self, duration: Duration) -> Result<(), Error>;
-}
-
-#[derive(Debug, Copy, Clone, PartialEq, Eq)]
-pub struct Userdata(u64);
-impl From<u64> for Userdata {
- fn from(u: u64) -> Userdata {
- Userdata(u)
- }
-}
-
-impl From<Userdata> for u64 {
- fn from(u: Userdata) -> u64 {
- u.0
- }
-}
-
-pub type PollResults = Vec<(SubscriptionResult, Userdata)>;
-
-pub struct Poll<'a> {
- subs: Vec<(Subscription<'a>, Userdata)>,
-}
-
-impl<'a> Poll<'a> {
- pub fn new() -> Self {
- Self { subs: Vec::new() }
- }
- pub fn subscribe_monotonic_clock(
- &mut self,
- clock: &'a dyn WasiMonotonicClock,
- deadline: Instant,
- precision: Duration,
- ud: Userdata,
- ) {
- self.subs.push((
- Subscription::MonotonicClock(MonotonicClockSubscription {
- clock,
- deadline,
- precision,
- }),
- ud,
- ));
- }
- pub fn subscribe_read(&mut self, file: &'a dyn WasiFile, ud: Userdata) {
- self.subs
- .push((Subscription::Read(RwSubscription::new(file)), ud));
- }
- pub fn subscribe_write(&mut self, file: &'a dyn WasiFile, ud: Userdata) {
- self.subs
- .push((Subscription::Write(RwSubscription::new(file)), ud));
- }
- pub fn results(self) -> Vec<(SubscriptionResult, Userdata)> {
- self.subs
- .into_iter()
- .filter_map(|(s, ud)| SubscriptionResult::from_subscription(s).map(|r| (r, ud)))
- .collect()
- }
- pub fn is_empty(&self) -> bool {
- self.subs.is_empty()
- }
- pub fn earliest_clock_deadline(&self) -> Option<&MonotonicClockSubscription<'a>> {
- self.subs
- .iter()
- .filter_map(|(s, _ud)| match s {
- Subscription::MonotonicClock(t) => Some(t),
- _ => None,
- })
- .min_by(|a, b| a.deadline.cmp(&b.deadline))
- }
- pub fn rw_subscriptions<'b>(&'b mut self) -> impl Iterator<Item = &'b mut Subscription<'a>> {
- self.subs.iter_mut().filter_map(|(s, _ud)| match s {
- Subscription::Read { .. } | Subscription::Write { .. } => Some(s),
- _ => None,
- })
- }
-}
diff --git a/crates/wasi-common/src/sched/subscription.rs b/crates/wasi-common/src/sched/subscription.rs
deleted file mode 100644
index bb28f6d5df..0000000000
--- a/crates/wasi-common/src/sched/subscription.rs
+++ /dev/null
@@ -1,77 +0,0 @@
-use crate::Error;
-use crate::clocks::WasiMonotonicClock;
-use crate::file::WasiFile;
-use bitflags::bitflags;
-use cap_std::time::{Duration, Instant};
-
-bitflags! {
- #[derive(Copy, Clone, Debug, PartialEq, Eq)]
- pub struct RwEventFlags: u32 {
- const HANGUP = 0b1;
- }
-}
-
-pub struct RwSubscription<'a> {
- pub file: &'a dyn WasiFile,
- status: Option<Result<(u64, RwEventFlags), Error>>,
-}
-
-impl<'a> RwSubscription<'a> {
- pub fn new(file: &'a dyn WasiFile) -> Self {
- Self { file, status: None }
- }
- pub fn complete(&mut self, size: u64, flags: RwEventFlags) {
- self.status = Some(Ok((size, flags)))
- }
- pub fn error(&mut self, error: Error) {
- self.status = Some(Err(error))
- }
- pub fn result(&mut self) -> Option<Result<(u64, RwEventFlags), Error>> {
- self.status.take()
- }
-}
-
-pub struct MonotonicClockSubscription<'a> {
- pub clock: &'a dyn WasiMonotonicClock,
- pub deadline: Instant,
- pub precision: Duration,
-}
-
-impl<'a> MonotonicClockSubscription<'a> {
- pub fn now(&self) -> Instant {
- self.clock.now(self.precision)
- }
- pub fn duration_until(&self) -> Option<Duration> {
- self.deadline.checked_duration_since(self.now())
- }
- pub fn result(&self) -> Option<Result<(), Error>> {
- if self.now().checked_duration_since(self.deadline).is_some() {
- Some(Ok(()))
- } else {
- None
- }
- }
-}
-
-pub enum Subscription<'a> {
- Read(RwSubscription<'a>),
- Write(RwSubscription<'a>),
- MonotonicClock(MonotonicClockSubscription<'a>),
-}
-
-#[derive(Debug)]
-pub enum SubscriptionResult {
- Read(Result<(u64, RwEventFlags), Error>),
- Write(Result<(u64, RwEventFlags), Error>),
- MonotonicClock(Result<(), Error>),
-}
-
-impl SubscriptionResult {
- pub fn from_subscription(s: Subscription) -> Option<SubscriptionResult> {
- match s {
- Subscription::Read(mut s) => s.result().map(SubscriptionResult::Read),
- Subscription::Write(mut s) => s.result().map(SubscriptionResult::Write),
- Subscription::MonotonicClock(s) => s.result().map(SubscriptionResult::MonotonicClock),
- }
- }
-}
diff --git a/crates/wasi-common/src/snapshots/mod.rs b/crates/wasi-common/src/snapshots/mod.rs
deleted file mode 100644
index a8d50a6119..0000000000
--- a/crates/wasi-common/src/snapshots/mod.rs
+++ /dev/null
@@ -1,24 +0,0 @@
-//! One goal of `wasi-common` is for multiple WASI snapshots to provide an
-//! interface to the same underlying `crate::WasiCtx`. This provides us a path
-//! to evolve WASI by allowing the same WASI Command to import functions from
-//! different snapshots - e.g. the user could use Rust's `std` which imports
-//! snapshot 1, but also depend directly on the `wasi` crate which imports
-//! some future snapshot 2. Right now, this amounts to supporting snapshot 1
-//! and "snapshot 0" aka wasi_unstable at once.
-//!
-//! The architectural rules for snapshots are:
-//!
-//! * Snapshots are arranged into modules under `crate::snapshots::`.
-//! * Each snapshot should invoke `wiggle::from_witx!` with `ctx:
-//! crate::WasiCtx` in its module, and impl all of the required traits.
-//! * Snapshots can be implemented in terms of other snapshots. For example,
-//! snapshot 0 is mostly implemented by calling the snapshot 1 implementation,
-//! and converting its own types back and forth with the snapshot 1 types. In a
-//! few cases, that is not feasible, so snapshot 0 carries its own
-//! implementations in terms of the `WasiFile` and `WasiSched` traits.
-//! * Snapshots can be implemented in terms of the `Wasi*` traits given by
-//! `WasiCtx`. No further downcasting via the `as_any` escape hatch is
-//! permitted.
-
-pub mod preview_0;
-pub mod preview_1;
diff --git a/crates/wasi-common/src/snapshots/preview_0.rs b/crates/wasi-common/src/snapshots/preview_0.rs
deleted file mode 100644
index 5320ddc57d..0000000000
--- a/crates/wasi-common/src/snapshots/preview_0.rs
+++ /dev/null
@@ -1,1079 +0,0 @@
-use crate::file::TableFileExt;
-use crate::sched::{
- Poll, Userdata,
- subscription::{RwEventFlags, SubscriptionResult},
-};
-use crate::snapshots::preview_1::types as snapshot1_types;
-use crate::snapshots::preview_1::wasi_snapshot_preview1::WasiSnapshotPreview1 as Snapshot1;
-use crate::{EnvError, ErrorExt, WasiCtx};
-use cap_std::time::Duration;
-use std::collections::HashSet;
-use wiggle::{GuestMemory, GuestPtr};
-
-wiggle::from_witx!({
- witx: ["witx/preview0/wasi_unstable.witx"],
- errors: { errno => trappable Error },
- async: *,
- wasmtime: false,
-});
-
-use types::Error;
-
-impl ErrorExt for Error {
- fn not_found() -> Self {
- types::Errno::Noent.into()
- }
- fn too_big() -> Self {
- types::Errno::TooBig.into()
- }
- fn badf() -> Self {
- types::Errno::Badf.into()
- }
- fn exist() -> Self {
- types::Errno::Exist.into()
- }
- fn illegal_byte_sequence() -> Self {
- types::Errno::Ilseq.into()
- }
- fn invalid_argument() -> Self {
- types::Errno::Inval.into()
- }
- fn io() -> Self {
- types::Errno::Io.into()
- }
- fn name_too_long() -> Self {
- types::Errno::Nametoolong.into()
- }
- fn not_dir() -> Self {
- types::Errno::Notdir.into()
- }
- fn not_supported() -> Self {
- types::Errno::Notsup.into()
- }
- fn overflow() -> Self {
- types::Errno::Overflow.into()
- }
- fn range() -> Self {
- types::Errno::Range.into()
- }
- fn seek_pipe() -> Self {
- types::Errno::Spipe.into()
- }
- fn perm() -> Self {
- types::Errno::Perm.into()
- }
-}
-
-impl wiggle::GuestErrorType for types::Errno {
- fn success() -> Self {
- Self::Success
- }
-}
-
-impl From<wiggle::GuestError> for Error {
- fn from(err: wiggle::GuestError) -> Error {
- snapshot1_types::Error::from(err).into()
- }
-}
-
-impl From<snapshot1_types::Error> for Error {
- fn from(error: snapshot1_types::Error) -> Error {
- match error.downcast() {
- Ok(errno) => Error::from(types::Errno::from(errno)),
- Err(trap) => Error::trap(trap),
- }
- }
-}
-
-impl From<std::num::TryFromIntError> for Error {
- fn from(_err: std::num::TryFromIntError) -> Error {
- types::Errno::Overflow.into()
- }
-}
-
-// Type conversions
-// The vast majority of the types defined in `types` and `snapshot1_types` are identical. However,
-// since they are defined in separate places for mechanical (wiggle) reasons, we need to manually
-// define conversion functions between them.
-// Below we have defined these functions as they are needed.
-
-/// Fd is a newtype wrapper around u32. Unwrap and wrap it.
-impl From<types::Fd> for snapshot1_types::Fd {
- fn from(fd: types::Fd) -> snapshot1_types::Fd {
- u32::from(fd).into()
- }
-}
-/// Fd is a newtype wrapper around u32. Unwrap and wrap it.
-impl From<snapshot1_types::Fd> for types::Fd {
- fn from(fd: snapshot1_types::Fd) -> types::Fd {
- u32::from(fd).into()
- }
-}
-
-/// Trivial conversion between two c-style enums that have the exact same set of variants.
-/// Could we do something unsafe and not list all these variants out? Probably, but doing
-/// it this way doesn't bother me much. I copy-pasted the list of variants out of the
-/// rendered rustdocs.
-/// LLVM ought to compile these From impls into no-ops, inshallah
-macro_rules! convert_enum {
- ($from:ty, $to:ty, $($var:ident),+) => {
- impl From<$from> for $to {
- fn from(e: $from) -> $to {
- match e {
- $( <$from>::$var => <$to>::$var, )+
- }
- }
- }
- }
-}
-convert_enum!(
- snapshot1_types::Errno,
- types::Errno,
- Success,
- TooBig,
- Acces,
- Addrinuse,
- Addrnotavail,
- Afnosupport,
- Again,
- Already,
- Badf,
- Badmsg,
- Busy,
- Canceled,
- Child,
- Connaborted,
- Connrefused,
- Connreset,
- Deadlk,
- Destaddrreq,
- Dom,
- Dquot,
- Exist,
- Fault,
- Fbig,
- Hostunreach,
- Idrm,
- Ilseq,
- Inprogress,
- Intr,
- Inval,
- Io,
- Isconn,
- Isdir,
- Loop,
- Mfile,
- Mlink,
- Msgsize,
- Multihop,
- Nametoolong,
- Netdown,
- Netreset,
- Netunreach,
- Nfile,
- Nobufs,
- Nodev,
- Noent,
- Noexec,
- Nolck,
- Nolink,
- Nomem,
- Nomsg,
- Noprotoopt,
- Nospc,
- Nosys,
- Notconn,
- Notdir,
- Notempty,
- Notrecoverable,
- Notsock,
- Notsup,
- Notty,
- Nxio,
- Overflow,
- Ownerdead,
- Perm,
- Pipe,
- Proto,
- Protonosupport,
- Prototype,
- Range,
- Rofs,
- Spipe,
- Srch,
- Stale,
- Timedout,
- Txtbsy,
- Xdev,
- Notcapable
-);
-convert_enum!(
- types::Clockid,
- snapshot1_types::Clockid,
- Realtime,
- Monotonic,
- ProcessCputimeId,
- ThreadCputimeId
-);
-
-convert_enum!(
- types::Advice,
- snapshot1_types::Advice,
- Normal,
- Sequential,
- Random,
- Willneed,
- Dontneed,
- Noreuse
-);
-convert_enum!(
- snapshot1_types::Filetype,
- types::Filetype,
- Directory,
- BlockDevice,
- CharacterDevice,
- RegularFile,
- SocketDgram,
- SocketStream,
- SymbolicLink,
- Unknown
-);
-convert_enum!(types::Whence, snapshot1_types::Whence, Cur, End, Set);
-
-/// Prestat isn't a c-style enum, its a union where the variant has a payload. Its the only one of
-/// those we need to convert, so write it by hand.
-impl From<snapshot1_types::Prestat> for types::Prestat {
- fn from(p: snapshot1_types::Prestat) -> types::Prestat {
- match p {
- snapshot1_types::Prestat::Dir(d) => types::Prestat::Dir(d.into()),
- }
- }
-}
-
-/// Trivial conversion between two structs that have the exact same set of fields,
-/// with recursive descent into the field types.
-macro_rules! convert_struct {
- ($from:ty, $to:path, $($field:ident),+) => {
- impl From<$from> for $to {
- fn from(e: $from) -> $to {
- $to {
- $( $field: e.$field.into(), )+
- }
- }
- }
- }
-}
-
-convert_struct!(snapshot1_types::PrestatDir, types::PrestatDir, pr_name_len);
-convert_struct!(
- snapshot1_types::Fdstat,
- types::Fdstat,
- fs_filetype,
- fs_rights_base,
- fs_rights_inheriting,
- fs_flags
-);
-
-/// Snapshot1 Filestat is incompatible with Snapshot0 Filestat - the nlink
-/// field is u32 on this Filestat, and u64 on theirs. If you've got more than
-/// 2^32 links I don't know what to tell you
-impl From<snapshot1_types::Filestat> for types::Filestat {
- fn from(f: snapshot1_types::Filestat) -> types::Filestat {
- types::Filestat {
- dev: f.dev,
- ino: f.ino,
- filetype: f.filetype.into(),
- nlink: f.nlink.try_into().unwrap_or(u32::MAX),
- size: f.size,
- atim: f.atim,
- mtim: f.mtim,
- ctim: f.ctim,
- }
- }
-}
-
-/// Trivial conversion between two bitflags that have the exact same set of flags.
-macro_rules! convert_flags {
- ($from:ty, $to:ty, $($flag:ident),+) => {
- impl From<$from> for $to {
- fn from(f: $from) -> $to {
- let mut out = <$to>::empty();
- $(
- if f.contains(<$from>::$flag) {
- out |= <$to>::$flag;
- }
- )+
- out
- }
- }
- }
-}
-
-/// Need to convert in both directions? This saves listing out the flags twice
-macro_rules! convert_flags_bidirectional {
- ($from:ty, $to:ty, $($flag:tt)*) => {
- convert_flags!($from, $to, $($flag)*);
- convert_flags!($to, $from, $($flag)*);
- }
-}
-
-convert_flags_bidirectional!(
- snapshot1_types::Fdflags,
- types::Fdflags,
- APPEND,
- DSYNC,
- NONBLOCK,
- RSYNC,
- SYNC
-);
-convert_flags!(
- types::Lookupflags,
- snapshot1_types::Lookupflags,
- SYMLINK_FOLLOW
-);
-convert_flags!(
- types::Fstflags,
- snapshot1_types::Fstflags,
- ATIM,
- ATIM_NOW,
- MTIM,
- MTIM_NOW
-);
-convert_flags!(
- types::Oflags,
- snapshot1_types::Oflags,
- CREAT,
- DIRECTORY,
- EXCL,
- TRUNC
-);
-convert_flags_bidirectional!(
- types::Rights,
- snapshot1_types::Rights,
- FD_DATASYNC,
- FD_READ,
- FD_SEEK,
- FD_FDSTAT_SET_FLAGS,
- FD_SYNC,
- FD_TELL,
- FD_WRITE,
- FD_ADVISE,
- FD_ALLOCATE,
- PATH_CREATE_DIRECTORY,
- PATH_CREATE_FILE,
- PATH_LINK_SOURCE,
- PATH_LINK_TARGET,
- PATH_OPEN,
- FD_READDIR,
- PATH_READLINK,
- PATH_RENAME_SOURCE,
- PATH_RENAME_TARGET,
- PATH_FILESTAT_GET,
- PATH_FILESTAT_SET_SIZE,
- PATH_FILESTAT_SET_TIMES,
- FD_FILESTAT_GET,
- FD_FILESTAT_SET_SIZE,
- FD_FILESTAT_SET_TIMES,
- PATH_SYMLINK,
- PATH_REMOVE_DIRECTORY,
- PATH_UNLINK_FILE,
- POLL_FD_READWRITE,
- SOCK_SHUTDOWN
-);
-
-// This implementation, wherever possible, delegates directly to the Snapshot1 implementation,
-// performing the no-op type conversions along the way.
-impl wasi_unstable::WasiUnstable for WasiCtx {
- async fn args_get(
- &mut self,
- memory: &mut GuestMemory<'_>,
- argv: GuestPtr<GuestPtr<u8>>,
- argv_buf: GuestPtr<u8>,
- ) -> Result<(), Error> {
- Snapshot1::args_get(self, memory, argv, argv_buf).await?;
- Ok(())
- }
-
- async fn args_sizes_get(
- &mut self,
- memory: &mut GuestMemory<'_>,
- ) -> Result<(types::Size, types::Size), Error> {
- let s = Snapshot1::args_sizes_get(self, memory).await?;
- Ok(s)
- }
-
- async fn environ_get(
- &mut self,
- memory: &mut GuestMemory<'_>,
- environ: GuestPtr<GuestPtr<u8>>,
- environ_buf: GuestPtr<u8>,
- ) -> Result<(), Error> {
- Snapshot1::environ_get(self, memory, environ, environ_buf).await?;
- Ok(())
- }
-
- async fn environ_sizes_get(
- &mut self,
- memory: &mut GuestMemory<'_>,
- ) -> Result<(types::Size, types::Size), Error> {
- let s = Snapshot1::environ_sizes_get(self, memory).await?;
- Ok(s)
- }
-
- async fn clock_res_get(
- &mut self,
- memory: &mut GuestMemory<'_>,
- id: types::Clockid,
- ) -> Result<types::Timestamp, Error> {
- let t = Snapshot1::clock_res_get(self, memory, id.into()).await?;
- Ok(t)
- }
-
- async fn clock_time_get(
- &mut self,
- memory: &mut GuestMemory<'_>,
- id: types::Clockid,
- precision: types::Timestamp,
- ) -> Result<types::Timestamp, Error> {
- let t = Snapshot1::clock_time_get(self, memory, id.into(), precision).await?;
- Ok(t)
- }
-
- async fn fd_advise(
- &mut self,
- memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- offset: types::Filesize,
- len: types::Filesize,
- advice: types::Advice,
- ) -> Result<(), Error> {
- Snapshot1::fd_advise(self, memory, fd.into(), offset, len, advice.into()).await?;
- Ok(())
- }
-
- async fn fd_allocate(
- &mut self,
- memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- offset: types::Filesize,
- len: types::Filesize,
- ) -> Result<(), Error> {
- Snapshot1::fd_allocate(self, memory, fd.into(), offset, len).await?;
- Ok(())
- }
-
- async fn fd_close(&mut self, memory: &mut GuestMemory<'_>, fd: types::Fd) -> Result<(), Error> {
- Snapshot1::fd_close(self, memory, fd.into()).await?;
- Ok(())
- }
-
- async fn fd_datasync(
- &mut self,
- memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- ) -> Result<(), Error> {
- Snapshot1::fd_datasync(self, memory, fd.into()).await?;
- Ok(())
- }
-
- async fn fd_fdstat_get(
- &mut self,
- memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- ) -> Result<types::Fdstat, Error> {
- Ok(Snapshot1::fd_fdstat_get(self, memory, fd.into())
- .await?
- .into())
- }
-
- async fn fd_fdstat_set_flags(
- &mut self,
- memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- flags: types::Fdflags,
- ) -> Result<(), Error> {
- Snapshot1::fd_fdstat_set_flags(self, memory, fd.into(), flags.into()).await?;
- Ok(())
- }
-
- async fn fd_fdstat_set_rights(
- &mut self,
- memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- fs_rights_base: types::Rights,
- fs_rights_inheriting: types::Rights,
- ) -> Result<(), Error> {
- Snapshot1::fd_fdstat_set_rights(
- self,
- memory,
- fd.into(),
- fs_rights_base.into(),
- fs_rights_inheriting.into(),
- )
- .await?;
- Ok(())
- }
-
- async fn fd_filestat_get(
- &mut self,
- memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- ) -> Result<types::Filestat, Error> {
- Ok(Snapshot1::fd_filestat_get(self, memory, fd.into())
- .await?
- .into())
- }
-
- async fn fd_filestat_set_size(
- &mut self,
- memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- size: types::Filesize,
- ) -> Result<(), Error> {
- Snapshot1::fd_filestat_set_size(self, memory, fd.into(), size).await?;
- Ok(())
- }
-
- async fn fd_filestat_set_times(
- &mut self,
- memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- atim: types::Timestamp,
- mtim: types::Timestamp,
- fst_flags: types::Fstflags,
- ) -> Result<(), Error> {
- Snapshot1::fd_filestat_set_times(self, memory, fd.into(), atim, mtim, fst_flags.into())
- .await?;
- Ok(())
- }
-
- // NOTE on fd_read, fd_pread, fd_write, fd_pwrite implementations:
- // these cast their pointers from preview0 vectors to preview1 vectors and
- // this only works because the representation didn't change between preview0
- // and preview1.
-
- async fn fd_read(
- &mut self,
- memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- iovs: types::IovecArray,
- ) -> Result<types::Size, Error> {
- Ok(Snapshot1::fd_read(self, memory, fd.into(), iovs.cast()).await?)
- }
-
- async fn fd_pread(
- &mut self,
- memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- iovs: types::IovecArray,
- offset: types::Filesize,
- ) -> Result<types::Size, Error> {
- Ok(Snapshot1::fd_pread(self, memory, fd.into(), iovs.cast(), offset).await?)
- }
-
- async fn fd_write(
- &mut self,
- memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- ciovs: types::CiovecArray,
- ) -> Result<types::Size, Error> {
- Ok(Snapshot1::fd_write(self, memory, fd.into(), ciovs.cast()).await?)
- }
-
- async fn fd_pwrite(
- &mut self,
- memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- ciovs: types::CiovecArray,
- offset: types::Filesize,
- ) -> Result<types::Size, Error> {
- Ok(Snapshot1::fd_pwrite(self, memory, fd.into(), ciovs.cast(), offset).await?)
- }
-
- async fn fd_prestat_get(
- &mut self,
- memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- ) -> Result<types::Prestat, Error> {
- Ok(Snapshot1::fd_prestat_get(self, memory, fd.into())
- .await?
- .into())
- }
-
- async fn fd_prestat_dir_name(
- &mut self,
- memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- path: GuestPtr<u8>,
- path_max_len: types::Size,
- ) -> Result<(), Error> {
- Snapshot1::fd_prestat_dir_name(self, memory, fd.into(), path, path_max_len).await?;
- Ok(())
- }
-
- async fn fd_renumber(
- &mut self,
- memory: &mut GuestMemory<'_>,
- from: types::Fd,
- to: types::Fd,
- ) -> Result<(), Error> {
- Snapshot1::fd_renumber(self, memory, from.into(), to.into()).await?;
- Ok(())
- }
-
- async fn fd_seek(
- &mut self,
- memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- offset: types::Filedelta,
- whence: types::Whence,
- ) -> Result<types::Filesize, Error> {
- Ok(Snapshot1::fd_seek(self, memory, fd.into(), offset, whence.into()).await?)
- }
-
- async fn fd_sync(&mut self, memory: &mut GuestMemory<'_>, fd: types::Fd) -> Result<(), Error> {
- Snapshot1::fd_sync(self, memory, fd.into()).await?;
- Ok(())
- }
-
- async fn fd_tell(
- &mut self,
- memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- ) -> Result<types::Filesize, Error> {
- Ok(Snapshot1::fd_tell(self, memory, fd.into()).await?)
- }
-
- async fn fd_readdir(
- &mut self,
- memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- buf: GuestPtr<u8>,
- buf_len: types::Size,
- cookie: types::Dircookie,
- ) -> Result<types::Size, Error> {
- Ok(Snapshot1::fd_readdir(self, memory, fd.into(), buf, buf_len, cookie).await?)
- }
-
- async fn path_create_directory(
- &mut self,
- memory: &mut GuestMemory<'_>,
- dirfd: types::Fd,
- path: GuestPtr<str>,
- ) -> Result<(), Error> {
- Snapshot1::path_create_directory(self, memory, dirfd.into(), path).await?;
- Ok(())
- }
-
- async fn path_filestat_get(
- &mut self,
- memory: &mut GuestMemory<'_>,
- dirfd: types::Fd,
- flags: types::Lookupflags,
- path: GuestPtr<str>,
- ) -> Result<types::Filestat, Error> {
- Ok(
- Snapshot1::path_filestat_get(self, memory, dirfd.into(), flags.into(), path)
- .await?
- .into(),
- )
- }
-
- async fn path_filestat_set_times(
- &mut self,
- memory: &mut GuestMemory<'_>,
- dirfd: types::Fd,
- flags: types::Lookupflags,
- path: GuestPtr<str>,
- atim: types::Timestamp,
- mtim: types::Timestamp,
- fst_flags: types::Fstflags,
- ) -> Result<(), Error> {
- Snapshot1::path_filestat_set_times(
- self,
- memory,
- dirfd.into(),
- flags.into(),
- path,
- atim,
- mtim,
- fst_flags.into(),
- )
- .await?;
- Ok(())
- }
-
- async fn path_link(
- &mut self,
- memory: &mut GuestMemory<'_>,
- src_fd: types::Fd,
- src_flags: types::Lookupflags,
- src_path: GuestPtr<str>,
- target_fd: types::Fd,
- target_path: GuestPtr<str>,
- ) -> Result<(), Error> {
- Snapshot1::path_link(
- self,
- memory,
- src_fd.into(),
- src_flags.into(),
- src_path,
- target_fd.into(),
- target_path,
- )
- .await?;
- Ok(())
- }
-
- async fn path_open(
- &mut self,
- memory: &mut GuestMemory<'_>,
- dirfd: types::Fd,
- dirflags: types::Lookupflags,
- path: GuestPtr<str>,
- oflags: types::Oflags,
- fs_rights_base: types::Rights,
- fs_rights_inheriting: types::Rights,
- fdflags: types::Fdflags,
- ) -> Result<types::Fd, Error> {
- Ok(Snapshot1::path_open(
- self,
- memory,
- dirfd.into(),
- dirflags.into(),
- path,
- oflags.into(),
- fs_rights_base.into(),
- fs_rights_inheriting.into(),
- fdflags.into(),
- )
- .await?
- .into())
- }
-
- async fn path_readlink(
- &mut self,
- memory: &mut GuestMemory<'_>,
- dirfd: types::Fd,
- path: GuestPtr<str>,
- buf: GuestPtr<u8>,
- buf_len: types::Size,
- ) -> Result<types::Size, Error> {
- Ok(Snapshot1::path_readlink(self, memory, dirfd.into(), path, buf, buf_len).await?)
- }
-
- async fn path_remove_directory(
- &mut self,
- memory: &mut GuestMemory<'_>,
- dirfd: types::Fd,
- path: GuestPtr<str>,
- ) -> Result<(), Error> {
- Snapshot1::path_remove_directory(self, memory, dirfd.into(), path).await?;
- Ok(())
- }
-
- async fn path_rename(
- &mut self,
- memory: &mut GuestMemory<'_>,
- src_fd: types::Fd,
- src_path: GuestPtr<str>,
- dest_fd: types::Fd,
- dest_path: GuestPtr<str>,
- ) -> Result<(), Error> {
- Snapshot1::path_rename(
- self,
- memory,
- src_fd.into(),
- src_path,
- dest_fd.into(),
- dest_path,
- )
- .await?;
- Ok(())
- }
-
- async fn path_symlink(
- &mut self,
- memory: &mut GuestMemory<'_>,
- src_path: GuestPtr<str>,
- dirfd: types::Fd,
- dest_path: GuestPtr<str>,
- ) -> Result<(), Error> {
- Snapshot1::path_symlink(self, memory, src_path, dirfd.into(), dest_path).await?;
- Ok(())
- }
-
- async fn path_unlink_file(
- &mut self,
- memory: &mut GuestMemory<'_>,
- dirfd: types::Fd,
- path: GuestPtr<str>,
- ) -> Result<(), Error> {
- Snapshot1::path_unlink_file(self, memory, dirfd.into(), path).await?;
- Ok(())
- }
-
- // NOTE on poll_oneoff implementation:
- // Like fd_write and friends, the arguments and return values are behind GuestPtrs,
- // so they are not values we can convert and pass to the poll_oneoff in Snapshot1.
- // Instead, we have copied the implementation of these functions from the Snapshot1 code.
- // The implementations are identical, but the `types::` in scope locally is different.
- // The bodies of these functions is mostly about converting the GuestPtr and types::-based
- // representation to use the Poll abstraction.
- async fn poll_oneoff(
- &mut self,
- memory: &mut GuestMemory<'_>,
- subs: GuestPtr<types::Subscription>,
- events: GuestPtr<types::Event>,
- nsubscriptions: types::Size,
- ) -> Result<types::Size, Error> {
- if nsubscriptions == 0 {
- return Err(Error::invalid_argument().context("nsubscriptions must be nonzero"));
- }
-
- // Special-case a `poll_oneoff` which is just sleeping on a single
- // relative timer event, such as what WASI libc uses to implement sleep
- // functions. This supports all clock IDs, because POSIX says that
- // `clock_settime` doesn't effect relative sleeps.
- if nsubscriptions == 1 {
- let sub = memory.read(subs)?;
- if let types::SubscriptionU::Clock(clocksub) = sub.u {
- if !clocksub
- .flags
- .contains(types::Subclockflags::SUBSCRIPTION_CLOCK_ABSTIME)
- {
- self.sched
- .sleep(Duration::from_nanos(clocksub.timeout))
- .await?;
- memory.write(
- events,
- types::Event {
- userdata: sub.userdata,
- error: types::Errno::Success,
- type_: types::Eventtype::Clock,
- fd_readwrite: fd_readwrite_empty(),
- },
- )?;
- return Ok(1);
- }
- }
- }
-
- let table = &self.table;
- let mut sub_fds: HashSet<types::Fd> = HashSet::new();
- // We need these refmuts to outlive Poll, which will hold the &mut dyn WasiFile inside
- let mut reads: Vec<(u32, Userdata)> = Vec::new();
- let mut writes: Vec<(u32, Userdata)> = Vec::new();
- let mut poll = Poll::new();
-
- let subs = subs.as_array(nsubscriptions);
- for sub_elem in subs.iter() {
- let sub_ptr = sub_elem?;
- let sub = memory.read(sub_ptr)?;
- match sub.u {
- types::SubscriptionU::Clock(clocksub) => match clocksub.id {
- types::Clockid::Monotonic => {
- let clock = self.clocks.monotonic()?;
- let precision = Duration::from_nanos(clocksub.precision);
- let duration = Duration::from_nanos(clocksub.timeout);
- let start = if clocksub
- .flags
- .contains(types::Subclockflags::SUBSCRIPTION_CLOCK_ABSTIME)
- {
- clock.creation_time
- } else {
- clock.abs_clock.now(precision)
- };
- let deadline = start
- .checked_add(duration)
- .ok_or_else(|| Error::overflow().context("deadline"))?;
- poll.subscribe_monotonic_clock(
- &*clock.abs_clock,
- deadline,
- precision,
- sub.userdata.into(),
- )
- }
- _ => Err(Error::invalid_argument()
- .context("timer subscriptions only support monotonic timer"))?,
- },
- types::SubscriptionU::FdRead(readsub) => {
- let fd = readsub.file_descriptor;
- if sub_fds.contains(&fd) {
- return Err(Error::invalid_argument()
- .context("Fd can be subscribed to at most once per poll"));
- } else {
- sub_fds.insert(fd);
- }
- table.get_file(u32::from(fd))?;
- reads.push((u32::from(fd), sub.userdata.into()));
- }
- types::SubscriptionU::FdWrite(writesub) => {
- let fd = writesub.file_descriptor;
- if sub_fds.contains(&fd) {
- return Err(Error::invalid_argument()
- .context("Fd can be subscribed to at most once per poll"));
- } else {
- sub_fds.insert(fd);
- }
- table.get_file(u32::from(fd))?;
- writes.push((u32::from(fd), sub.userdata.into()));
- }
- }
- }
-
- self.sched.poll_oneoff(&mut poll).await?;
-
- let results = poll.results();
- let num_results = results.len();
- assert!(
- num_results <= nsubscriptions as usize,
- "results exceeds subscriptions"
- );
- let events = events.as_array(
- num_results
- .try_into()
- .expect("not greater than nsubscriptions"),
- );
- for ((result, userdata), event_elem) in results.into_iter().zip(events.iter()) {
- let event_ptr = event_elem?;
- let userdata: types::Userdata = userdata.into();
- memory.write(
- event_ptr,
- match result {
- SubscriptionResult::Read(r) => {
- let type_ = types::Eventtype::FdRead;
- match r {
- Ok((nbytes, flags)) => types::Event {
- userdata,
- error: types::Errno::Success,
- type_,
- fd_readwrite: types::EventFdReadwrite {
- nbytes,
- flags: types::Eventrwflags::from(&flags),
- },
- },
- Err(e) => types::Event {
- userdata,
- error: types::Errno::from(e.downcast().map_err(Error::trap)?),
- type_,
- fd_readwrite: fd_readwrite_empty(),
- },
- }
- }
- SubscriptionResult::Write(r) => {
- let type_ = types::Eventtype::FdWrite;
- match r {
- Ok((nbytes, flags)) => types::Event {
- userdata,
- error: types::Errno::Success,
- type_,
- fd_readwrite: types::EventFdReadwrite {
- nbytes,
- flags: types::Eventrwflags::from(&flags),
- },
- },
- Err(e) => types::Event {
- userdata,
- error: types::Errno::from(e.downcast().map_err(Error::trap)?),
- type_,
- fd_readwrite: fd_readwrite_empty(),
- },
- }
- }
- SubscriptionResult::MonotonicClock(r) => {
- let type_ = types::Eventtype::Clock;
- types::Event {
- userdata,
- error: match r {
- Ok(()) => types::Errno::Success,
- Err(e) => types::Errno::from(e.downcast().map_err(Error::trap)?),
- },
- type_,
- fd_readwrite: fd_readwrite_empty(),
- }
- }
- },
- )?;
- }
-
- Ok(num_results.try_into().expect("results fit into memory"))
- }
-
- async fn proc_exit(
- &mut self,
- memory: &mut GuestMemory<'_>,
- status: types::Exitcode,
- ) -> EnvError {
- Snapshot1::proc_exit(self, memory, status).await
- }
-
- async fn proc_raise(
- &mut self,
- _memory: &mut GuestMemory<'_>,
- _sig: types::Signal,
- ) -> Result<(), Error> {
- Err(Error::trap(EnvError::msg("proc_raise unsupported")))
- }
-
- async fn sched_yield(&mut self, memory: &mut GuestMemory<'_>) -> Result<(), Error> {
- Snapshot1::sched_yield(self, memory).await?;
- Ok(())
- }
-
- async fn random_get(
- &mut self,
- memory: &mut GuestMemory<'_>,
- buf: GuestPtr<u8>,
- buf_len: types::Size,
- ) -> Result<(), Error> {
- Snapshot1::random_get(self, memory, buf, buf_len).await?;
- Ok(())
- }
-
- async fn sock_recv(
- &mut self,
- _memory: &mut GuestMemory<'_>,
- _fd: types::Fd,
- _ri_data: types::IovecArray,
- _ri_flags: types::Riflags,
- ) -> Result<(types::Size, types::Roflags), Error> {
- Err(Error::trap(EnvError::msg("sock_recv unsupported")))
- }
-
- async fn sock_send(
- &mut self,
- _memory: &mut GuestMemory<'_>,
- _fd: types::Fd,
- _si_data: types::CiovecArray,
- _si_flags: types::Siflags,
- ) -> Result<types::Size, Error> {
- Err(Error::trap(EnvError::msg("sock_send unsupported")))
- }
-
- async fn sock_shutdown(
- &mut self,
- _memory: &mut GuestMemory<'_>,
- _fd: types::Fd,
- _how: types::Sdflags,
- ) -> Result<(), Error> {
- Err(Error::trap(EnvError::msg("sock_shutdown unsupported")))
- }
-}
-
-impl From<&RwEventFlags> for types::Eventrwflags {
- fn from(flags: &RwEventFlags) -> types::Eventrwflags {
- let mut out = types::Eventrwflags::empty();
- if flags.contains(RwEventFlags::HANGUP) {
- out = out | types::Eventrwflags::FD_READWRITE_HANGUP;
- }
- out
- }
-}
-
-fn fd_readwrite_empty() -> types::EventFdReadwrite {
- types::EventFdReadwrite {
- nbytes: 0,
- flags: types::Eventrwflags::empty(),
- }
-}
diff --git a/crates/wasi-common/src/snapshots/preview_1.rs b/crates/wasi-common/src/snapshots/preview_1.rs
deleted file mode 100644
index 5e5e256bff..0000000000
--- a/crates/wasi-common/src/snapshots/preview_1.rs
+++ /dev/null
@@ -1,1570 +0,0 @@
-use crate::{
- EnvError, I32Exit, SystemTimeSpec, WasiCtx,
- dir::{DirEntry, OpenResult, ReaddirCursor, ReaddirEntity, TableDirExt},
- file::{
- Advice, FdFlags, FdStat, FileAccessMode, FileEntry, FileType, Filestat, OFlags, RiFlags,
- RoFlags, SdFlags, SiFlags, TableFileExt, WasiFile,
- },
- sched::{
- Poll, Userdata,
- subscription::{RwEventFlags, SubscriptionResult},
- },
-};
-use cap_std::time::{Duration, SystemClock};
-use std::borrow::Cow;
-use std::io::{IoSlice, IoSliceMut};
-use std::ops::Deref;
-use std::sync::Arc;
-use wiggle::GuestMemory;
-use wiggle::GuestPtr;
-
-pub mod error;
-use error::{Error, ErrorExt};
-
-// Limit the size of intermediate buffers when copying to WebAssembly shared
-// memory.
-pub(crate) const MAX_SHARED_BUFFER_SIZE: usize = 1 << 16;
-
-wiggle::from_witx!({
- witx: ["witx/preview1/wasi_snapshot_preview1.witx"],
- errors: { errno => trappable Error },
- // Note: not every function actually needs to be async, however, nearly all of them do, and
- // keeping that set the same in this macro and the wasmtime_wiggle / lucet_wiggle macros is
- // tedious, and there is no cost to having a sync function be async in this case.
- async: *,
- wasmtime: false,
-});
-
-impl wiggle::GuestErrorType for types::Errno {
- fn success() -> Self {
- Self::Success
- }
-}
-
-impl wasi_snapshot_preview1::WasiSnapshotPreview1 for WasiCtx {
- async fn args_get(
- &mut self,
- memory: &mut GuestMemory<'_>,
- argv: GuestPtr<GuestPtr<u8>>,
- argv_buf: GuestPtr<u8>,
- ) -> Result<(), Error> {
- self.args.write_to_guest(memory, argv_buf, argv)
- }
-
- async fn args_sizes_get(
- &mut self,
- _memory: &mut GuestMemory<'_>,
- ) -> Result<(types::Size, types::Size), Error> {
- Ok((self.args.number_elements(), self.args.cumulative_size()))
- }
-
- async fn environ_get(
- &mut self,
- memory: &mut GuestMemory<'_>,
- environ: GuestPtr<GuestPtr<u8>>,
- environ_buf: GuestPtr<u8>,
- ) -> Result<(), Error> {
- self.env.write_to_guest(memory, environ_buf, environ)
- }
-
- async fn environ_sizes_get(
- &mut self,
- _memory: &mut GuestMemory<'_>,
- ) -> Result<(types::Size, types::Size), Error> {
- Ok((self.env.number_elements(), self.env.cumulative_size()))
- }
-
- async fn clock_res_get(
- &mut self,
- _memory: &mut GuestMemory<'_>,
- id: types::Clockid,
- ) -> Result<types::Timestamp, Error> {
- let resolution = match id {
- types::Clockid::Realtime => Ok(self.clocks.system()?.resolution()),
- types::Clockid::Monotonic => Ok(self.clocks.monotonic()?.abs_clock.resolution()),
- types::Clockid::ProcessCputimeId | types::Clockid::ThreadCputimeId => {
- Err(Error::badf().context("process and thread clocks are not supported"))
- }
- }?;
- Ok(resolution.as_nanos().try_into()?)
- }
-
- async fn clock_time_get(
- &mut self,
- _memory: &mut GuestMemory<'_>,
- id: types::Clockid,
- precision: types::Timestamp,
- ) -> Result<types::Timestamp, Error> {
- let precision = Duration::from_nanos(precision);
- match id {
- types::Clockid::Realtime => {
- let now = self.clocks.system()?.now(precision).into_std();
- let d = now
- .duration_since(std::time::SystemTime::UNIX_EPOCH)
- .map_err(|_| Error::trap(EnvError::msg("current time before unix epoch")))?;
- Ok(d.as_nanos().try_into()?)
- }
- types::Clockid::Monotonic => {
- let clock = self.clocks.monotonic()?;
- let now = clock.abs_clock.now(precision);
- let d = now.duration_since(clock.creation_time);
- Ok(d.as_nanos().try_into()?)
- }
- types::Clockid::ProcessCputimeId | types::Clockid::ThreadCputimeId => {
- Err(Error::badf().context("process and thread clocks are not supported"))
- }
- }
- }
-
- async fn fd_advise(
- &mut self,
- _memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- offset: types::Filesize,
- len: types::Filesize,
- advice: types::Advice,
- ) -> Result<(), Error> {
- self.table()
- .get_file(u32::from(fd))?
- .file
- .advise(offset, len, advice.into())
- .await?;
- Ok(())
- }
-
- async fn fd_allocate(
- &mut self,
- _memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- _offset: types::Filesize,
- _len: types::Filesize,
- ) -> Result<(), Error> {
- // Check if fd is a file, and has rights, just to reject those cases
- // with the errors expected:
- let _ = self.table().get_file(u32::from(fd))?;
- // This operation from cloudabi is linux-specific, isn't even
- // supported across all linux filesystems, and has no support on macos
- // or windows. Rather than ship spotty support, it has been removed
- // from preview 2, and we are no longer supporting it in preview 1 as
- // well.
- Err(Error::not_supported())
- }
-
- async fn fd_close(
- &mut self,
- _memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- ) -> Result<(), Error> {
- let table = self.table();
- let fd = u32::from(fd);
-
- // Fail fast: If not present in table, Badf
- if !table.contains_key(fd) {
- return Err(Error::badf().context("key not in table"));
- }
- // fd_close must close either a File or a Dir handle
- if table.is::<FileEntry>(fd) {
- let _ = table.delete::<FileEntry>(fd);
- } else if table.is::<DirEntry>(fd) {
- let _ = table.delete::<DirEntry>(fd);
- } else {
- return Err(Error::badf().context("key does not refer to file or directory"));
- }
-
- Ok(())
- }
-
- async fn fd_datasync(
- &mut self,
- _memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- ) -> Result<(), Error> {
- self.table()
- .get_file(u32::from(fd))?
- .file
- .datasync()
- .await?;
- Ok(())
- }
-
- async fn fd_fdstat_get(
- &mut self,
- _memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- ) -> Result<types::Fdstat, Error> {
- let table = self.table();
- let fd = u32::from(fd);
- if table.is::<FileEntry>(fd) {
- let file_entry: Arc<FileEntry> = table.get(fd)?;
- let fdstat = file_entry.get_fdstat().await?;
- Ok(types::Fdstat::from(&fdstat))
- } else if table.is::<DirEntry>(fd) {
- let _dir_entry: Arc<DirEntry> = table.get(fd)?;
- let dir_fdstat = types::Fdstat {
- fs_filetype: types::Filetype::Directory,
- fs_rights_base: directory_base_rights(),
- fs_rights_inheriting: directory_inheriting_rights(),
- fs_flags: types::Fdflags::empty(),
- };
- Ok(dir_fdstat)
- } else {
- Err(Error::badf())
- }
- }
-
- async fn fd_fdstat_set_flags(
- &mut self,
- _memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- flags: types::Fdflags,
- ) -> Result<(), Error> {
- if let Some(table) = self.table_mut() {
- table
- .get_file_mut(u32::from(fd))?
- .file
- .set_fdflags(FdFlags::from(flags))
- .await
- } else {
- log::warn!(
- "`fd_fdstat_set_flags` does not work with wasi-threads enabled; see https://github.com/bytecodealliance/wasmtime/issues/5643"
- );
- Err(Error::not_supported())
- }
- }
-
- async fn fd_fdstat_set_rights(
- &mut self,
- _memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- _fs_rights_base: types::Rights,
- _fs_rights_inheriting: types::Rights,
- ) -> Result<(), Error> {
- let table = self.table();
- let fd = u32::from(fd);
- if table.is::<FileEntry>(fd) {
- let _file_entry: Arc<FileEntry> = table.get(fd)?;
- Err(Error::not_supported())
- } else if table.is::<DirEntry>(fd) {
- let _dir_entry: Arc<DirEntry> = table.get(fd)?;
- Err(Error::not_supported())
- } else {
- Err(Error::badf())
- }
- }
-
- async fn fd_filestat_get(
- &mut self,
- _memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- ) -> Result<types::Filestat, Error> {
- let table = self.table();
- let fd = u32::from(fd);
- if table.is::<FileEntry>(fd) {
- let filestat = table.get_file(fd)?.file.get_filestat().await?;
- Ok(filestat.into())
- } else if table.is::<DirEntry>(fd) {
- let filestat = table.get_dir(fd)?.dir.get_filestat().await?;
- Ok(filestat.into())
- } else {
- Err(Error::badf())
- }
- }
-
- async fn fd_filestat_set_size(
- &mut self,
- _memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- size: types::Filesize,
- ) -> Result<(), Error> {
- self.table()
- .get_file(u32::from(fd))?
- .file
- .set_filestat_size(size)
- .await?;
- Ok(())
- }
-
- async fn fd_filestat_set_times(
- &mut self,
- _memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- atim: types::Timestamp,
- mtim: types::Timestamp,
- fst_flags: types::Fstflags,
- ) -> Result<(), Error> {
- let fd = u32::from(fd);
- let table = self.table();
- // Validate flags
- let set_atim = fst_flags.contains(types::Fstflags::ATIM);
- let set_atim_now = fst_flags.contains(types::Fstflags::ATIM_NOW);
- let set_mtim = fst_flags.contains(types::Fstflags::MTIM);
- let set_mtim_now = fst_flags.contains(types::Fstflags::MTIM_NOW);
-
- let atim = systimespec(set_atim, atim, set_atim_now).map_err(|e| e.context("atim"))?;
- let mtim = systimespec(set_mtim, mtim, set_mtim_now).map_err(|e| e.context("mtim"))?;
-
- if table.is::<FileEntry>(fd) {
- table
- .get_file(fd)
- .expect("checked that entry is file")
- .file
- .set_times(atim, mtim)
- .await
- } else if table.is::<DirEntry>(fd) {
- table
- .get_dir(fd)
- .expect("checked that entry is dir")
- .dir
- .set_times(".", atim, mtim, false)
- .await
- } else {
- Err(Error::badf())
- }
- }
-
- async fn fd_read(
- &mut self,
- memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- iovs: types::IovecArray,
- ) -> Result<types::Size, Error> {
- let f = self.table().get_file(u32::from(fd))?;
- // Access mode check normalizes error returned (windows would prefer ACCES here)
- if !f.access_mode.contains(FileAccessMode::READ) {
- Err(types::Errno::Badf)?
- }
- let f = &f.file;
-
- let iovs: Vec<wiggle::GuestPtr<[u8]>> = iovs
- .iter()
- .map(|iov_ptr| {
- let iov_ptr = iov_ptr?;
- let iov: types::Iovec = memory.read(iov_ptr)?;
- Ok(iov.buf.as_array(iov.buf_len))
- })
- .collect::<Result<_, Error>>()?;
-
- // If the first iov structure is from shared memory we can safely assume
- // all the rest will be. We then read into memory based on the memory's
- // shared-ness:
- // - if not shared, we copy directly into the Wasm memory
- // - if shared, we use an intermediate buffer; this avoids Rust unsafety
- // due to holding on to a `&mut [u8]` of Wasm memory when we cannot
- // guarantee the `&mut` exclusivity--other threads could be modifying
- // the data as this functions writes to it. Though likely there is no
- // issue with OS writing to io structs in multi-threaded scenarios,
- // since we do not know here if `&dyn WasiFile` does anything else
- // (e.g., read), we cautiously incur some performance overhead by
- // copying twice.
- let is_shared_memory = memory.is_shared_memory();
- let bytes_read: u64 = if is_shared_memory {
- // For shared memory, read into an intermediate buffer. Only the
- // first iov will be filled and even then the read is capped by the
- // `MAX_SHARED_BUFFER_SIZE`, so users are expected to re-call.
- let iov = iovs.into_iter().next();
- if let Some(iov) = iov {
- let mut buffer = vec![0; (iov.len() as usize).min(MAX_SHARED_BUFFER_SIZE)];
- let bytes_read = f.read_vectored(&mut [IoSliceMut::new(&mut buffer)]).await?;
- let iov = iov
- .get_range(0..bytes_read.try_into()?)
- .expect("it should always be possible to slice the iov smaller");
- memory.copy_from_slice(&buffer[0..bytes_read.try_into()?], iov)?;
- bytes_read
- } else {
- return Ok(0);
- }
- } else {
- // Convert the first unsafe guest slice into a safe one--Wiggle
- // can only track mutable borrows for an entire region, and converting
- // all guest pointers to slices would cause a runtime borrow-checking
- // error. As read is allowed to return less than the requested amount,
- // it's valid (though not as efficient) for us to only perform the
- // read of the first buffer.
- let guest_slice: &mut [u8] = match iovs.into_iter().filter(|iov| iov.len() > 0).next() {
- Some(iov) => memory.as_slice_mut(iov)?.unwrap(),
- None => return Ok(0),
- };
-
- // Read directly into the Wasm memory.
- f.read_vectored(&mut [IoSliceMut::new(guest_slice)]).await?
- };
-
- Ok(types::Size::try_from(bytes_read)?)
- }
-
- async fn fd_pread(
- &mut self,
- memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- iovs: types::IovecArray,
- offset: types::Filesize,
- ) -> Result<types::Size, Error> {
- let f = self.table().get_file(u32::from(fd))?;
- // Access mode check normalizes error returned (windows would prefer ACCES here)
- if !f.access_mode.contains(FileAccessMode::READ) {
- Err(types::Errno::Badf)?
- }
- let f = &f.file;
-
- let iovs: Vec<wiggle::GuestPtr<[u8]>> = iovs
- .iter()
- .map(|iov_ptr| {
- let iov_ptr = iov_ptr?;
- let iov: types::Iovec = memory.read(iov_ptr)?;
- Ok(iov.buf.as_array(iov.buf_len))
- })
- .collect::<Result<_, Error>>()?;
-
- // If the first iov structure is from shared memory we can safely assume
- // all the rest will be. We then read into memory based on the memory's
- // shared-ness:
- // - if not shared, we copy directly into the Wasm memory
- // - if shared, we use an intermediate buffer; this avoids Rust unsafety
- // due to holding on to a `&mut [u8]` of Wasm memory when we cannot
- // guarantee the `&mut` exclusivity--other threads could be modifying
- // the data as this functions writes to it. Though likely there is no
- // issue with OS writing to io structs in multi-threaded scenarios,
- // since we do not know here if `&dyn WasiFile` does anything else
- // (e.g., read), we cautiously incur some performance overhead by
- // copying twice.
- let is_shared_memory = memory.is_shared_memory();
- let bytes_read: u64 = if is_shared_memory {
- // For shared memory, read into an intermediate buffer. Only the
- // first iov will be filled and even then the read is capped by the
- // `MAX_SHARED_BUFFER_SIZE`, so users are expected to re-call.
- let iov = iovs.into_iter().next();
- if let Some(iov) = iov {
- let mut buffer = vec![0; (iov.len() as usize).min(MAX_SHARED_BUFFER_SIZE)];
- let bytes_read = f
- .read_vectored_at(&mut [IoSliceMut::new(&mut buffer)], offset)
- .await?;
- let iov = iov
- .get_range(0..bytes_read.try_into()?)
- .expect("it should always be possible to slice the iov smaller");
- memory.copy_from_slice(&buffer[0..bytes_read.try_into()?], iov)?;
- bytes_read
- } else {
- return Ok(0);
- }
- } else {
- // Convert unsafe guest slices to safe ones.
- let guest_slice: &mut [u8] = match iovs.into_iter().filter(|iov| iov.len() > 0).next() {
- Some(iov) => memory.as_slice_mut(iov)?.unwrap(),
- None => return Ok(0),
- };
-
- // Read directly into the Wasm memory.
- f.read_vectored_at(&mut [IoSliceMut::new(guest_slice)], offset)
- .await?
- };
-
- Ok(types::Size::try_from(bytes_read)?)
- }
-
- async fn fd_write(
- &mut self,
- memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- ciovs: types::CiovecArray,
- ) -> Result<types::Size, Error> {
- let f = self.table().get_file(u32::from(fd))?;
- // Access mode check normalizes error returned (windows would prefer ACCES here)
- if !f.access_mode.contains(FileAccessMode::WRITE) {
- Err(types::Errno::Badf)?
- }
- let f = &f.file;
-
- let guest_slices: Vec<Cow<[u8]>> = ciovs
- .iter()
- .map(|iov_ptr| {
- let iov_ptr = iov_ptr?;
- let iov: types::Ciovec = memory.read(iov_ptr)?;
- Ok(memory.as_cow(iov.buf.as_array(iov.buf_len))?)
- })
- .collect::<Result<_, Error>>()?;
-
- let ioslices: Vec<IoSlice> = guest_slices
- .iter()
- .map(|s| IoSlice::new(s.deref()))
- .collect();
- let bytes_written = f.write_vectored(&ioslices).await?;
-
- Ok(types::Size::try_from(bytes_written)?)
- }
-
- async fn fd_pwrite(
- &mut self,
- memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- ciovs: types::CiovecArray,
- offset: types::Filesize,
- ) -> Result<types::Size, Error> {
- let f = self.table().get_file(u32::from(fd))?;
- // Access mode check normalizes error returned (windows would prefer ACCES here)
- if !f.access_mode.contains(FileAccessMode::WRITE) {
- Err(types::Errno::Badf)?
- }
- let f = &f.file;
-
- let guest_slices: Vec<Cow<[u8]>> = ciovs
- .iter()
- .map(|iov_ptr| {
- let iov_ptr = iov_ptr?;
- let iov: types::Ciovec = memory.read(iov_ptr)?;
- Ok(memory.as_cow(iov.buf.as_array(iov.buf_len))?)
- })
- .collect::<Result<_, Error>>()?;
-
- let ioslices: Vec<IoSlice> = guest_slices
- .iter()
- .map(|s| IoSlice::new(s.deref()))
- .collect();
- let bytes_written = f.write_vectored_at(&ioslices, offset).await?;
-
- Ok(types::Size::try_from(bytes_written)?)
- }
-
- async fn fd_prestat_get(
- &mut self,
- _memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- ) -> Result<types::Prestat, Error> {
- let table = self.table();
- let dir_entry: Arc<DirEntry> = table.get(u32::from(fd)).map_err(|_| Error::badf())?;
- if let Some(preopen) = dir_entry.preopen_path() {
- let path_str = preopen.to_str().ok_or_else(|| Error::not_supported())?;
- let pr_name_len = u32::try_from(path_str.as_bytes().len())?;
- Ok(types::Prestat::Dir(types::PrestatDir { pr_name_len }))
- } else {
- Err(Error::not_supported().context("file is not a preopen"))
- }
- }
-
- async fn fd_prestat_dir_name(
- &mut self,
- memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- path: GuestPtr<u8>,
- path_max_len: types::Size,
- ) -> Result<(), Error> {
- let table = self.table();
- let dir_entry: Arc<DirEntry> = table.get(u32::from(fd)).map_err(|_| Error::not_dir())?;
- if let Some(preopen) = dir_entry.preopen_path() {
- let path_bytes = preopen
- .to_str()
- .ok_or_else(|| Error::not_supported())?
- .as_bytes();
- let path_len = path_bytes.len();
- if path_len > path_max_len as usize {
- return Err(Error::name_too_long());
- }
- let path = path.as_array(path_len as u32);
- memory.copy_from_slice(path_bytes, path)?;
- Ok(())
- } else {
- Err(Error::not_supported())
- }
- }
- async fn fd_renumber(
- &mut self,
- _memory: &mut GuestMemory<'_>,
- from: types::Fd,
- to: types::Fd,
- ) -> Result<(), Error> {
- let table = self.table();
- let from = u32::from(from);
- let to = u32::from(to);
- if !table.contains_key(from) {
- return Err(Error::badf());
- }
- if !table.contains_key(to) {
- return Err(Error::badf());
- }
- table.renumber(from, to)
- }
-
- async fn fd_seek(
- &mut self,
- _memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- offset: types::Filedelta,
- whence: types::Whence,
- ) -> Result<types::Filesize, Error> {
- use std::io::SeekFrom;
- let whence = match whence {
- types::Whence::Cur => SeekFrom::Current(offset),
- types::Whence::End => SeekFrom::End(offset),
- types::Whence::Set => {
- SeekFrom::Start(offset.try_into().map_err(|_| Error::invalid_argument())?)
- }
- };
- let newoffset = self
- .table()
- .get_file(u32::from(fd))?
- .file
- .seek(whence)
- .await?;
- Ok(newoffset)
- }
-
- async fn fd_sync(&mut self, _memory: &mut GuestMemory<'_>, fd: types::Fd) -> Result<(), Error> {
- self.table().get_file(u32::from(fd))?.file.sync().await?;
- Ok(())
- }
-
- async fn fd_tell(
- &mut self,
- _memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- ) -> Result<types::Filesize, Error> {
- let offset = self
- .table()
- .get_file(u32::from(fd))?
- .file
- .seek(std::io::SeekFrom::Current(0))
- .await?;
- Ok(offset)
- }
-
- async fn fd_readdir(
- &mut self,
- memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- mut buf: GuestPtr<u8>,
- buf_len: types::Size,
- cookie: types::Dircookie,
- ) -> Result<types::Size, Error> {
- let mut bufused = 0;
- for entity in self
- .table()
- .get_dir(u32::from(fd))?
- .dir
- .readdir(ReaddirCursor::from(cookie))
- .await?
- {
- let entity = entity?;
- let dirent_raw = dirent_bytes(types::Dirent::try_from(&entity)?);
- let dirent_len: types::Size = dirent_raw.len().try_into()?;
- let name_raw = entity.name.as_bytes();
- let name_len: types::Size = name_raw.len().try_into()?;
-
- // Copy as many bytes of the dirent as we can, up to the end of the buffer
- let dirent_copy_len = std::cmp::min(dirent_len, buf_len - bufused);
- let raw = buf.as_array(dirent_copy_len);
- memory.copy_from_slice(&dirent_raw[..dirent_copy_len as usize], raw)?;
-
- // If the dirent struct wasn't compiled entirely, return that we filled the buffer, which
- // tells libc that we're not at EOF.
- if dirent_copy_len < dirent_len {
- return Ok(buf_len);
- }
-
- buf = buf.add(dirent_copy_len)?;
- bufused += dirent_copy_len;
-
- // Copy as many bytes of the name as we can, up to the end of the buffer
- let name_copy_len = std::cmp::min(name_len, buf_len - bufused);
- let raw = buf.as_array(name_copy_len);
- memory.copy_from_slice(&name_raw[..name_copy_len as usize], raw)?;
-
- // If the dirent struct wasn't copied entirely, return that we filled the buffer, which
- // tells libc that we're not at EOF
-
- if name_copy_len < name_len {
- return Ok(buf_len);
- }
-
- buf = buf.add(name_copy_len)?;
- bufused += name_copy_len;
- }
- Ok(bufused)
- }
-
- async fn path_create_directory(
- &mut self,
- memory: &mut GuestMemory<'_>,
- dirfd: types::Fd,
- path: GuestPtr<str>,
- ) -> Result<(), Error> {
- self.table()
- .get_dir(u32::from(dirfd))?
- .dir
- .create_dir(memory.as_cow_str(path)?.deref())
- .await
- }
-
- async fn path_filestat_get(
- &mut self,
- memory: &mut GuestMemory<'_>,
- dirfd: types::Fd,
- flags: types::Lookupflags,
- path: GuestPtr<str>,
- ) -> Result<types::Filestat, Error> {
- let filestat = self
- .table()
- .get_dir(u32::from(dirfd))?
- .dir
- .get_path_filestat(
- memory.as_cow_str(path)?.deref(),
- flags.contains(types::Lookupflags::SYMLINK_FOLLOW),
- )
- .await?;
- Ok(types::Filestat::from(filestat))
- }
-
- async fn path_filestat_set_times(
- &mut self,
- memory: &mut GuestMemory<'_>,
- dirfd: types::Fd,
- flags: types::Lookupflags,
- path: GuestPtr<str>,
- atim: types::Timestamp,
- mtim: types::Timestamp,
- fst_flags: types::Fstflags,
- ) -> Result<(), Error> {
- let set_atim = fst_flags.contains(types::Fstflags::ATIM);
- let set_atim_now = fst_flags.contains(types::Fstflags::ATIM_NOW);
- let set_mtim = fst_flags.contains(types::Fstflags::MTIM);
- let set_mtim_now = fst_flags.contains(types::Fstflags::MTIM_NOW);
-
- let atim = systimespec(set_atim, atim, set_atim_now).map_err(|e| e.context("atim"))?;
- let mtim = systimespec(set_mtim, mtim, set_mtim_now).map_err(|e| e.context("mtim"))?;
- self.table()
- .get_dir(u32::from(dirfd))?
- .dir
- .set_times(
- memory.as_cow_str(path)?.deref(),
- atim,
- mtim,
- flags.contains(types::Lookupflags::SYMLINK_FOLLOW),
- )
- .await
- }
-
- async fn path_link(
- &mut self,
- memory: &mut GuestMemory<'_>,
- src_fd: types::Fd,
- src_flags: types::Lookupflags,
- src_path: GuestPtr<str>,
- target_fd: types::Fd,
- target_path: GuestPtr<str>,
- ) -> Result<(), Error> {
- let table = self.table();
- let src_dir = table.get_dir(u32::from(src_fd))?;
- let target_dir = table.get_dir(u32::from(target_fd))?;
- let symlink_follow = src_flags.contains(types::Lookupflags::SYMLINK_FOLLOW);
- if symlink_follow {
- return Err(Error::invalid_argument()
- .context("symlink following on path_link is not supported"));
- }
-
- src_dir
- .dir
- .hard_link(
- memory.as_cow_str(src_path)?.deref(),
- target_dir.dir.deref(),
- memory.as_cow_str(target_path)?.deref(),
- )
- .await
- }
-
- async fn path_open(
- &mut self,
- memory: &mut GuestMemory<'_>,
- dirfd: types::Fd,
- dirflags: types::Lookupflags,
- path: GuestPtr<str>,
- oflags: types::Oflags,
- fs_rights_base: types::Rights,
- _fs_rights_inheriting: types::Rights,
- fdflags: types::Fdflags,
- ) -> Result<types::Fd, Error> {
- let table = self.table();
- let dirfd = u32::from(dirfd);
- if table.is::<FileEntry>(dirfd) {
- return Err(Error::not_dir());
- }
- let dir_entry = table.get_dir(dirfd)?;
-
- let symlink_follow = dirflags.contains(types::Lookupflags::SYMLINK_FOLLOW);
-
- let oflags = OFlags::from(&oflags);
- let fdflags = FdFlags::from(fdflags);
- let path = memory.as_cow_str(path)?;
-
- let read = fs_rights_base.contains(types::Rights::FD_READ);
- let write = fs_rights_base.contains(types::Rights::FD_WRITE);
- let access_mode = if read {
- FileAccessMode::READ
- } else {
- FileAccessMode::empty()
- } | if write {
- FileAccessMode::WRITE
- } else {
- FileAccessMode::empty()
- };
-
- let file = dir_entry
- .dir
- .open_file(symlink_follow, path.deref(), oflags, read, write, fdflags)
- .await?;
- drop(dir_entry);
-
- let fd = match file {
- // Paper over a divergence between Windows and POSIX, where
- // POSIX returns EISDIR if you open a directory with the
- // WRITE flag: https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html#:~:text=EISDIR
- #[cfg(windows)]
- OpenResult::Dir(_) if write => {
- return Err(types::Errno::Isdir.into());
- }
- OpenResult::File(file) => table.push(Arc::new(FileEntry::new(file, access_mode)))?,
- OpenResult::Dir(child_dir) => table.push(Arc::new(DirEntry::new(None, child_dir)))?,
- };
- Ok(types::Fd::from(fd))
- }
-
- async fn path_readlink(
- &mut self,
- memory: &mut GuestMemory<'_>,
- dirfd: types::Fd,
- path: GuestPtr<str>,
- buf: GuestPtr<u8>,
- buf_len: types::Size,
- ) -> Result<types::Size, Error> {
- let link = self
- .table()
- .get_dir(u32::from(dirfd))?
- .dir
- .read_link(memory.as_cow_str(path)?.deref())
- .await?
- .into_os_string()
- .into_string()
- .map_err(|_| Error::illegal_byte_sequence().context("link contents"))?;
- let link_bytes = link.as_bytes();
- // Like posix readlink(2), silently truncate links when they are larger than the
- // destination buffer:
- let link_len = std::cmp::min(link_bytes.len(), buf_len as usize);
- let buf = buf.as_array(link_len as u32);
- memory.copy_from_slice(&link_bytes[..link_len], buf)?;
- Ok(link_len as types::Size)
- }
-
- async fn path_remove_directory(
- &mut self,
- memory: &mut GuestMemory<'_>,
- dirfd: types::Fd,
- path: GuestPtr<str>,
- ) -> Result<(), Error> {
- self.table()
- .get_dir(u32::from(dirfd))?
- .dir
- .remove_dir(memory.as_cow_str(path)?.deref())
- .await
- }
-
- async fn path_rename(
- &mut self,
- memory: &mut GuestMemory<'_>,
- src_fd: types::Fd,
- src_path: GuestPtr<str>,
- dest_fd: types::Fd,
- dest_path: GuestPtr<str>,
- ) -> Result<(), Error> {
- let table = self.table();
- let src_dir = table.get_dir(u32::from(src_fd))?;
- let dest_dir = table.get_dir(u32::from(dest_fd))?;
- src_dir
- .dir
- .rename(
- memory.as_cow_str(src_path)?.deref(),
- dest_dir.dir.deref(),
- memory.as_cow_str(dest_path)?.deref(),
- )
- .await
- }
-
- async fn path_symlink(
- &mut self,
- memory: &mut GuestMemory<'_>,
- src_path: GuestPtr<str>,
- dirfd: types::Fd,
- dest_path: GuestPtr<str>,
- ) -> Result<(), Error> {
- self.table()
- .get_dir(u32::from(dirfd))?
- .dir
- .symlink(
- memory.as_cow_str(src_path)?.deref(),
- memory.as_cow_str(dest_path)?.deref(),
- )
- .await
- }
-
- async fn path_unlink_file(
- &mut self,
- memory: &mut GuestMemory<'_>,
- dirfd: types::Fd,
- path: GuestPtr<str>,
- ) -> Result<(), Error> {
- self.table()
- .get_dir(u32::from(dirfd))?
- .dir
- .unlink_file(memory.as_cow_str(path)?.deref())
- .await
- }
-
- async fn poll_oneoff(
- &mut self,
- memory: &mut GuestMemory<'_>,
- subs: GuestPtr<types::Subscription>,
- events: GuestPtr<types::Event>,
- nsubscriptions: types::Size,
- ) -> Result<types::Size, Error> {
- if nsubscriptions == 0 {
- return Err(Error::invalid_argument().context("nsubscriptions must be nonzero"));
- }
-
- // Special-case a `poll_oneoff` which is just sleeping on a single
- // relative timer event, such as what WASI libc uses to implement sleep
- // functions. This supports all clock IDs, because POSIX says that
- // `clock_settime` doesn't effect relative sleeps.
- if nsubscriptions == 1 {
- let sub = memory.read(subs)?;
- if let types::SubscriptionU::Clock(clocksub) = sub.u {
- if !clocksub
- .flags
- .contains(types::Subclockflags::SUBSCRIPTION_CLOCK_ABSTIME)
- {
- self.sched
- .sleep(Duration::from_nanos(clocksub.timeout))
- .await?;
- memory.write(
- events,
- types::Event {
- userdata: sub.userdata,
- error: types::Errno::Success,
- type_: types::Eventtype::Clock,
- fd_readwrite: fd_readwrite_empty(),
- },
- )?;
- return Ok(1);
- }
- }
- }
-
- let table = &self.table;
- // We need these refmuts to outlive Poll, which will hold the &mut dyn WasiFile inside
- let mut read_refs: Vec<(Arc<FileEntry>, Option<Userdata>)> = Vec::new();
- let mut write_refs: Vec<(Arc<FileEntry>, Option<Userdata>)> = Vec::new();
-
- let mut poll = Poll::new();
-
- let subs = subs.as_array(nsubscriptions);
- for sub_elem in subs.iter() {
- let sub_ptr = sub_elem?;
- let sub = memory.read(sub_ptr)?;
- match sub.u {
- types::SubscriptionU::Clock(clocksub) => match clocksub.id {
- types::Clockid::Monotonic => {
- let clock = self.clocks.monotonic()?;
- let precision = Duration::from_nanos(clocksub.precision);
- let duration = Duration::from_nanos(clocksub.timeout);
- let start = if clocksub
- .flags
- .contains(types::Subclockflags::SUBSCRIPTION_CLOCK_ABSTIME)
- {
- clock.creation_time
- } else {
- clock.abs_clock.now(precision)
- };
- let deadline = start
- .checked_add(duration)
- .ok_or_else(|| Error::overflow().context("deadline"))?;
- poll.subscribe_monotonic_clock(
- &*clock.abs_clock,
- deadline,
- precision,
- sub.userdata.into(),
- )
- }
- types::Clockid::Realtime => {
- // POSIX specifies that functions like `nanosleep` and others use the
- // `REALTIME` clock. But it also says that `clock_settime` has no effect
- // on threads waiting in these functions. MONOTONIC should always have
- // resolution at least as good as REALTIME, so we can translate a
- // non-absolute `REALTIME` request into a `MONOTONIC` request.
- let clock = self.clocks.monotonic()?;
- let precision = Duration::from_nanos(clocksub.precision);
- let duration = Duration::from_nanos(clocksub.timeout);
- let deadline = if clocksub
- .flags
- .contains(types::Subclockflags::SUBSCRIPTION_CLOCK_ABSTIME)
- {
- return Err(Error::not_supported());
- } else {
- clock
- .abs_clock
- .now(precision)
- .checked_add(duration)
- .ok_or_else(|| Error::overflow().context("deadline"))?
- };
- poll.subscribe_monotonic_clock(
- &*clock.abs_clock,
- deadline,
- precision,
- sub.userdata.into(),
- )
- }
- _ => Err(Error::invalid_argument()
- .context("timer subscriptions only support monotonic timer"))?,
- },
- types::SubscriptionU::FdRead(readsub) => {
- let fd = readsub.file_descriptor;
- let file_ref = table.get_file(u32::from(fd))?;
- read_refs.push((file_ref, Some(sub.userdata.into())));
- }
- types::SubscriptionU::FdWrite(writesub) => {
- let fd = writesub.file_descriptor;
- let file_ref = table.get_file(u32::from(fd))?;
- write_refs.push((file_ref, Some(sub.userdata.into())));
- }
- }
- }
-
- let mut read_mut_refs: Vec<(&dyn WasiFile, Userdata)> = Vec::new();
- for (file_lock, userdata) in read_refs.iter_mut() {
- read_mut_refs.push((file_lock.file.deref(), userdata.take().unwrap()));
- }
-
- for (f, ud) in read_mut_refs.iter_mut() {
- poll.subscribe_read(*f, *ud);
- }
-
- let mut write_mut_refs: Vec<(&dyn WasiFile, Userdata)> = Vec::new();
- for (file_lock, userdata) in write_refs.iter_mut() {
- write_mut_refs.push((file_lock.file.deref(), userdata.take().unwrap()));
- }
-
- for (f, ud) in write_mut_refs.iter_mut() {
- poll.subscribe_write(*f, *ud);
- }
-
- self.sched.poll_oneoff(&mut poll).await?;
-
- let results = poll.results();
- let num_results = results.len();
- assert!(
- num_results <= nsubscriptions as usize,
- "results exceeds subscriptions"
- );
- let events = events.as_array(
- num_results
- .try_into()
- .expect("not greater than nsubscriptions"),
- );
- for ((result, userdata), event_elem) in results.into_iter().zip(events.iter()) {
- let event_ptr = event_elem?;
- let userdata: types::Userdata = userdata.into();
- memory.write(
- event_ptr,
- match result {
- SubscriptionResult::Read(r) => {
- let type_ = types::Eventtype::FdRead;
- match r {
- Ok((nbytes, flags)) => types::Event {
- userdata,
- error: types::Errno::Success,
- type_,
- fd_readwrite: types::EventFdReadwrite {
- nbytes,
- flags: types::Eventrwflags::from(&flags),
- },
- },
- Err(e) => types::Event {
- userdata,
- error: e.downcast().map_err(Error::trap)?,
- type_,
- fd_readwrite: fd_readwrite_empty(),
- },
- }
- }
- SubscriptionResult::Write(r) => {
- let type_ = types::Eventtype::FdWrite;
- match r {
- Ok((nbytes, flags)) => types::Event {
- userdata,
- error: types::Errno::Success,
- type_,
- fd_readwrite: types::EventFdReadwrite {
- nbytes,
- flags: types::Eventrwflags::from(&flags),
- },
- },
- Err(e) => types::Event {
- userdata,
- error: e.downcast().map_err(Error::trap)?,
- type_,
- fd_readwrite: fd_readwrite_empty(),
- },
- }
- }
- SubscriptionResult::MonotonicClock(r) => {
- let type_ = types::Eventtype::Clock;
- types::Event {
- userdata,
- error: match r {
- Ok(()) => types::Errno::Success,
- Err(e) => e.downcast().map_err(Error::trap)?,
- },
- type_,
- fd_readwrite: fd_readwrite_empty(),
- }
- }
- },
- )?;
- }
-
- Ok(num_results.try_into().expect("results fit into memory"))
- }
-
- async fn proc_exit(
- &mut self,
- _memory: &mut GuestMemory<'_>,
- status: types::Exitcode,
- ) -> EnvError {
- // Check that the status is within WASI's range.
- if status < 126 {
- I32Exit(status as i32).into()
- } else {
- EnvError::msg("exit with invalid exit status outside of [0..126)")
- }
- }
-
- async fn proc_raise(
- &mut self,
- _memory: &mut GuestMemory<'_>,
- _sig: types::Signal,
- ) -> Result<(), Error> {
- Err(Error::trap(EnvError::msg("proc_raise unsupported")))
- }
-
- async fn sched_yield(&mut self, _memory: &mut GuestMemory<'_>) -> Result<(), Error> {
- self.sched.sched_yield().await
- }
-
- async fn random_get(
- &mut self,
- memory: &mut GuestMemory<'_>,
- buf: GuestPtr<u8>,
- buf_len: types::Size,
- ) -> Result<(), Error> {
- let buf = buf.as_array(buf_len);
- if memory.is_shared_memory() {
- // If the Wasm memory is shared, copy to an intermediate buffer to
- // avoid Rust unsafety (i.e., the called function could rely on
- // `&mut [u8]`'s exclusive ownership which is not guaranteed due to
- // potential access from other threads).
- let mut copied: u32 = 0;
- while copied < buf.len() {
- let len = (buf.len() - copied).min(MAX_SHARED_BUFFER_SIZE as u32);
- let mut tmp = vec![0; len as usize];
- self.random.lock().unwrap().fill_bytes(&mut tmp);
- let dest = buf.get_range(copied..copied + len).unwrap();
- memory.copy_from_slice(&tmp, dest)?;
- copied += len;
- }
- } else {
- // If the Wasm memory is non-shared, copy directly into the linear
- // memory.
- let mem = &mut memory.as_slice_mut(buf)?.unwrap();
- self.random.lock().unwrap().fill_bytes(mem);
- }
- Ok(())
- }
-
- async fn sock_accept(
- &mut self,
- _memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- flags: types::Fdflags,
- ) -> Result<types::Fd, Error> {
- let table = self.table();
- let f = table.get_file(u32::from(fd))?;
- let file = f.file.sock_accept(FdFlags::from(flags)).await?;
- let fd = table.push(Arc::new(FileEntry::new(file, FileAccessMode::all())))?;
- Ok(types::Fd::from(fd))
- }
-
- async fn sock_recv(
- &mut self,
- memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- ri_data: types::IovecArray,
- ri_flags: types::Riflags,
- ) -> Result<(types::Size, types::Roflags), Error> {
- let f = self.table().get_file(u32::from(fd))?;
-
- let iovs: Vec<wiggle::GuestPtr<[u8]>> = ri_data
- .iter()
- .map(|iov_ptr| {
- let iov_ptr = iov_ptr?;
- let iov: types::Iovec = memory.read(iov_ptr)?;
- Ok(iov.buf.as_array(iov.buf_len))
- })
- .collect::<Result<_, Error>>()?;
-
- // If the first iov structure is from shared memory we can safely assume
- // all the rest will be. We then read into memory based on the memory's
- // shared-ness:
- // - if not shared, we copy directly into the Wasm memory
- // - if shared, we use an intermediate buffer; this avoids Rust unsafety
- // due to holding on to a `&mut [u8]` of Wasm memory when we cannot
- // guarantee the `&mut` exclusivity--other threads could be modifying
- // the data as this functions writes to it. Though likely there is no
- // issue with OS writing to io structs in multi-threaded scenarios,
- // since we do not know here if `&dyn WasiFile` does anything else
- // (e.g., read), we cautiously incur some performance overhead by
- // copying twice.
- let is_shared_memory = memory.is_shared_memory();
- let (bytes_read, ro_flags) = if is_shared_memory {
- // For shared memory, read into an intermediate buffer. Only the
- // first iov will be filled and even then the read is capped by the
- // `MAX_SHARED_BUFFER_SIZE`, so users are expected to re-call.
- let iov = iovs.into_iter().next();
- if let Some(iov) = iov {
- let mut buffer = vec![0; (iov.len() as usize).min(MAX_SHARED_BUFFER_SIZE)];
- let (bytes_read, ro_flags) = f
- .file
- .sock_recv(&mut [IoSliceMut::new(&mut buffer)], RiFlags::from(ri_flags))
- .await?;
- let iov = iov
- .get_range(0..bytes_read.try_into()?)
- .expect("it should always be possible to slice the iov smaller");
- memory.copy_from_slice(&buffer[0..bytes_read.try_into()?], iov)?;
- (bytes_read, ro_flags)
- } else {
- return Ok((0, RoFlags::empty().into()));
- }
- } else {
- // Convert all of the unsafe guest slices to safe ones--this uses
- // Wiggle's internal borrow checker to ensure no overlaps. We assume
- // here that, because the memory is not shared, there are no other
- // threads to access it while it is written to.
- let guest_slice: &mut [u8] = match iovs.into_iter().filter(|iov| iov.len() > 0).next() {
- Some(iov) => memory.as_slice_mut(iov)?.unwrap(),
- None => &mut [],
- };
-
- // Read directly into the Wasm memory.
- f.file
- .sock_recv(&mut [IoSliceMut::new(guest_slice)], RiFlags::from(ri_flags))
- .await?
- };
-
- Ok((types::Size::try_from(bytes_read)?, ro_flags.into()))
- }
-
- async fn sock_send(
- &mut self,
- memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- si_data: types::CiovecArray,
- _si_flags: types::Siflags,
- ) -> Result<types::Size, Error> {
- let f = self.table().get_file(u32::from(fd))?;
-
- let guest_slices: Vec<Cow<[u8]>> = si_data
- .iter()
- .map(|iov_ptr| {
- let iov_ptr = iov_ptr?;
- let iov: types::Ciovec = memory.read(iov_ptr)?;
- Ok(memory.as_cow(iov.buf.as_array(iov.buf_len))?)
- })
- .collect::<Result<_, Error>>()?;
-
- let ioslices: Vec<IoSlice> = guest_slices
- .iter()
- .map(|s| IoSlice::new(s.deref()))
- .collect();
- let bytes_written = f.file.sock_send(&ioslices, SiFlags::empty()).await?;
-
- Ok(types::Size::try_from(bytes_written)?)
- }
-
- async fn sock_shutdown(
- &mut self,
- _memory: &mut GuestMemory<'_>,
- fd: types::Fd,
- how: types::Sdflags,
- ) -> Result<(), Error> {
- let f = self.table().get_file(u32::from(fd))?;
-
- f.file.sock_shutdown(SdFlags::from(how)).await
- }
-}
-
-impl From<types::Advice> for Advice {
- fn from(advice: types::Advice) -> Advice {
- match advice {
- types::Advice::Normal => Advice::Normal,
- types::Advice::Sequential => Advice::Sequential,
- types::Advice::Random => Advice::Random,
- types::Advice::Willneed => Advice::WillNeed,
- types::Advice::Dontneed => Advice::DontNeed,
- types::Advice::Noreuse => Advice::NoReuse,
- }
- }
-}
-
-impl From<&FdStat> for types::Fdstat {
- fn from(fdstat: &FdStat) -> types::Fdstat {
- let mut fs_rights_base = types::Rights::empty();
- if fdstat.access_mode.contains(FileAccessMode::READ) {
- fs_rights_base |= types::Rights::FD_READ;
- }
- if fdstat.access_mode.contains(FileAccessMode::WRITE) {
- fs_rights_base |= types::Rights::FD_WRITE;
- }
- types::Fdstat {
- fs_filetype: types::Filetype::from(&fdstat.filetype),
- fs_rights_base,
- fs_rights_inheriting: types::Rights::empty(),
- fs_flags: types::Fdflags::from(fdstat.flags),
- }
- }
-}
-
-impl From<&FileType> for types::Filetype {
- fn from(ft: &FileType) -> types::Filetype {
- match ft {
- FileType::Directory => types::Filetype::Directory,
- FileType::BlockDevice => types::Filetype::BlockDevice,
- FileType::CharacterDevice => types::Filetype::CharacterDevice,
- FileType::RegularFile => types::Filetype::RegularFile,
- FileType::SocketDgram => types::Filetype::SocketDgram,
- FileType::SocketStream => types::Filetype::SocketStream,
- FileType::SymbolicLink => types::Filetype::SymbolicLink,
- FileType::Unknown => types::Filetype::Unknown,
- FileType::Pipe => types::Filetype::Unknown,
- }
- }
-}
-
-macro_rules! convert_flags {
- ($from:ty, $to:ty, $($flag:ident),+) => {
- impl From<$from> for $to {
- fn from(f: $from) -> $to {
- let mut out = <$to>::empty();
- $(
- if f.contains(<$from>::$flag) {
- out |= <$to>::$flag;
- }
- )+
- out
- }
- }
- }
-}
-
-macro_rules! convert_flags_bidirectional {
- ($from:ty, $to:ty, $($rest:tt)*) => {
- convert_flags!($from, $to, $($rest)*);
- convert_flags!($to, $from, $($rest)*);
- }
-}
-
-convert_flags_bidirectional!(
- FdFlags,
- types::Fdflags,
- APPEND,
- DSYNC,
- NONBLOCK,
- RSYNC,
- SYNC
-);
-
-convert_flags_bidirectional!(RiFlags, types::Riflags, RECV_PEEK, RECV_WAITALL);
-
-convert_flags_bidirectional!(RoFlags, types::Roflags, RECV_DATA_TRUNCATED);
-
-convert_flags_bidirectional!(SdFlags, types::Sdflags, RD, WR);
-
-impl From<&types::Oflags> for OFlags {
- fn from(oflags: &types::Oflags) -> OFlags {
- let mut out = OFlags::empty();
- if oflags.contains(types::Oflags::CREAT) {
- out = out | OFlags::CREATE;
- }
- if oflags.contains(types::Oflags::DIRECTORY) {
- out = out | OFlags::DIRECTORY;
- }
- if oflags.contains(types::Oflags::EXCL) {
- out = out | OFlags::EXCLUSIVE;
- }
- if oflags.contains(types::Oflags::TRUNC) {
- out = out | OFlags::TRUNCATE;
- }
- out
- }
-}
-
-impl From<&OFlags> for types::Oflags {
- fn from(oflags: &OFlags) -> types::Oflags {
- let mut out = types::Oflags::empty();
- if oflags.contains(OFlags::CREATE) {
- out = out | types::Oflags::CREAT;
- }
- if oflags.contains(OFlags::DIRECTORY) {
- out = out | types::Oflags::DIRECTORY;
- }
- if oflags.contains(OFlags::EXCLUSIVE) {
- out = out | types::Oflags::EXCL;
- }
- if oflags.contains(OFlags::TRUNCATE) {
- out = out | types::Oflags::TRUNC;
- }
- out
- }
-}
-impl From<Filestat> for types::Filestat {
- fn from(stat: Filestat) -> types::Filestat {
- types::Filestat {
- dev: stat.device_id,
- ino: stat.inode,
- filetype: types::Filetype::from(&stat.filetype),
- nlink: stat.nlink,
- size: stat.size,
- atim: stat
- .atim
- .map(|t| t.duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos() as u64)
- .unwrap_or(0),
- mtim: stat
- .mtim
- .map(|t| t.duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos() as u64)
- .unwrap_or(0),
- ctim: stat
- .ctim
- .map(|t| t.duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos() as u64)
- .unwrap_or(0),
- }
- }
-}
-
-impl TryFrom<&ReaddirEntity> for types::Dirent {
- type Error = Error;
- fn try_from(e: &ReaddirEntity) -> Result<types::Dirent, Error> {
- Ok(types::Dirent {
- d_ino: e.inode,
- d_namlen: e.name.as_bytes().len().try_into()?,
- d_type: types::Filetype::from(&e.filetype),
- d_next: e.next.into(),
- })
- }
-}
-
-fn dirent_bytes(dirent: types::Dirent) -> Vec<u8> {
- use wiggle::GuestType;
- assert_eq!(
- types::Dirent::guest_size(),
- std::mem::size_of::<types::Dirent>() as u32,
- "Dirent guest repr and host repr should match"
- );
- assert_eq!(
- 1,
- std::mem::size_of_val(&dirent.d_type),
- "Dirent member d_type should be endian-invariant"
- );
- let size = types::Dirent::guest_size()
- .try_into()
- .expect("Dirent is smaller than 2^32");
- let mut bytes = Vec::with_capacity(size);
- bytes.resize(size, 0);
- let ptr = bytes.as_mut_ptr().cast::<types::Dirent>();
- let guest_dirent = types::Dirent {
- d_ino: dirent.d_ino.to_le(),
- d_namlen: dirent.d_namlen.to_le(),
- d_type: dirent.d_type, // endian-invariant
- d_next: dirent.d_next.to_le(),
- };
- unsafe { ptr.write_unaligned(guest_dirent) };
- bytes
-}
-
-impl From<&RwEventFlags> for types::Eventrwflags {
- fn from(flags: &RwEventFlags) -> types::Eventrwflags {
- let mut out = types::Eventrwflags::empty();
- if flags.contains(RwEventFlags::HANGUP) {
- out = out | types::Eventrwflags::FD_READWRITE_HANGUP;
- }
- out
- }
-}
-
-fn fd_readwrite_empty() -> types::EventFdReadwrite {
- types::EventFdReadwrite {
- nbytes: 0,
- flags: types::Eventrwflags::empty(),
- }
-}
-
-fn systimespec(
- set: bool,
- ts: types::Timestamp,
- now: bool,
-) -> Result<Option<SystemTimeSpec>, Error> {
- if set && now {
- Err(Error::invalid_argument())
- } else if set {
- Ok(Some(SystemTimeSpec::Absolute(
- SystemClock::UNIX_EPOCH + Duration::from_nanos(ts),
- )))
- } else if now {
- Ok(Some(SystemTimeSpec::SymbolicNow))
- } else {
- Ok(None)
- }
-}
-
-// This is the default subset of base Rights reported for directories prior to
-// https://github.com/bytecodealliance/wasmtime/pull/6265. Some
-// implementations still expect this set of rights to be reported.
-pub(crate) fn directory_base_rights() -> types::Rights {
- types::Rights::PATH_CREATE_DIRECTORY
- | types::Rights::PATH_CREATE_FILE
- | types::Rights::PATH_LINK_SOURCE
- | types::Rights::PATH_LINK_TARGET
- | types::Rights::PATH_OPEN
- | types::Rights::FD_READDIR
- | types::Rights::PATH_READLINK
- | types::Rights::PATH_RENAME_SOURCE
- | types::Rights::PATH_RENAME_TARGET
- | types::Rights::PATH_SYMLINK
- | types::Rights::PATH_REMOVE_DIRECTORY
- | types::Rights::PATH_UNLINK_FILE
- | types::Rights::PATH_FILESTAT_GET
- | types::Rights::PATH_FILESTAT_SET_TIMES
- | types::Rights::FD_FILESTAT_GET
- | types::Rights::FD_FILESTAT_SET_TIMES
-}
-
-// This is the default subset of inheriting Rights reported for directories
-// prior to https://github.com/bytecodealliance/wasmtime/pull/6265. Some
-// implementations still expect this set of rights to be reported.
-pub(crate) fn directory_inheriting_rights() -> types::Rights {
- types::Rights::FD_DATASYNC
- | types::Rights::FD_READ
- | types::Rights::FD_SEEK
- | types::Rights::FD_FDSTAT_SET_FLAGS
- | types::Rights::FD_SYNC
- | types::Rights::FD_TELL
- | types::Rights::FD_WRITE
- | types::Rights::FD_ADVISE
- | types::Rights::FD_ALLOCATE
- | types::Rights::FD_FILESTAT_GET
- | types::Rights::FD_FILESTAT_SET_SIZE
- | types::Rights::FD_FILESTAT_SET_TIMES
- | types::Rights::POLL_FD_READWRITE
- | directory_base_rights()
-}
diff --git a/crates/wasi-common/src/snapshots/preview_1/error.rs b/crates/wasi-common/src/snapshots/preview_1/error.rs
deleted file mode 100644
index 6352005571..0000000000
--- a/crates/wasi-common/src/snapshots/preview_1/error.rs
+++ /dev/null
@@ -1,259 +0,0 @@
-use wasmtime_environ::error::format_err;
-
-pub use super::types::{Errno, Error};
-
-pub trait ErrorExt {
- fn not_found() -> Self;
- fn too_big() -> Self;
- fn badf() -> Self;
- fn exist() -> Self;
- fn illegal_byte_sequence() -> Self;
- fn invalid_argument() -> Self;
- fn io() -> Self;
- fn name_too_long() -> Self;
- fn not_dir() -> Self;
- fn not_supported() -> Self;
- fn overflow() -> Self;
- fn range() -> Self;
- fn seek_pipe() -> Self;
- fn perm() -> Self;
-}
-
-impl ErrorExt for Error {
- fn not_found() -> Self {
- Errno::Noent.into()
- }
- fn too_big() -> Self {
- Errno::TooBig.into()
- }
- fn badf() -> Self {
- Errno::Badf.into()
- }
- fn exist() -> Self {
- Errno::Exist.into()
- }
- fn illegal_byte_sequence() -> Self {
- Errno::Ilseq.into()
- }
- fn invalid_argument() -> Self {
- Errno::Inval.into()
- }
- fn io() -> Self {
- Errno::Io.into()
- }
- fn name_too_long() -> Self {
- Errno::Nametoolong.into()
- }
- fn not_dir() -> Self {
- Errno::Notdir.into()
- }
- fn not_supported() -> Self {
- Errno::Notsup.into()
- }
- fn overflow() -> Self {
- Errno::Overflow.into()
- }
- fn range() -> Self {
- Errno::Range.into()
- }
- fn seek_pipe() -> Self {
- Errno::Spipe.into()
- }
- fn perm() -> Self {
- Errno::Perm.into()
- }
-}
-
-#[cfg(unix)]
-fn from_raw_os_error(err: Option<i32>) -> Option<Error> {
- use rustix::io::Errno as RustixErrno;
- if err.is_none() {
- return None;
- }
- Some(match RustixErrno::from_raw_os_error(err.unwrap()) {
- RustixErrno::AGAIN => Errno::Again.into(),
- RustixErrno::PIPE => Errno::Pipe.into(),
- RustixErrno::PERM => Errno::Perm.into(),
- RustixErrno::NOENT => Errno::Noent.into(),
- RustixErrno::NOMEM => Errno::Nomem.into(),
- RustixErrno::TOOBIG => Errno::TooBig.into(),
- RustixErrno::IO => Errno::Io.into(),
- RustixErrno::BADF => Errno::Badf.into(),
- RustixErrno::BUSY => Errno::Busy.into(),
- RustixErrno::ACCESS => Errno::Acces.into(),
- RustixErrno::FAULT => Errno::Fault.into(),
- RustixErrno::NOTDIR => Errno::Notdir.into(),
- RustixErrno::ISDIR => Errno::Isdir.into(),
- RustixErrno::INVAL => Errno::Inval.into(),
- RustixErrno::EXIST => Errno::Exist.into(),
- RustixErrno::FBIG => Errno::Fbig.into(),
- RustixErrno::NOSPC => Errno::Nospc.into(),
- RustixErrno::SPIPE => Errno::Spipe.into(),
- RustixErrno::MFILE => Errno::Mfile.into(),
- RustixErrno::MLINK => Errno::Mlink.into(),
- RustixErrno::NAMETOOLONG => Errno::Nametoolong.into(),
- RustixErrno::NFILE => Errno::Nfile.into(),
- RustixErrno::NOTEMPTY => Errno::Notempty.into(),
- RustixErrno::LOOP => Errno::Loop.into(),
- RustixErrno::OVERFLOW => Errno::Overflow.into(),
- RustixErrno::ILSEQ => Errno::Ilseq.into(),
- RustixErrno::NOTSUP => Errno::Notsup.into(),
- RustixErrno::ADDRINUSE => Errno::Addrinuse.into(),
- RustixErrno::CANCELED => Errno::Canceled.into(),
- RustixErrno::ADDRNOTAVAIL => Errno::Addrnotavail.into(),
- RustixErrno::AFNOSUPPORT => Errno::Afnosupport.into(),
- RustixErrno::ALREADY => Errno::Already.into(),
- RustixErrno::CONNABORTED => Errno::Connaborted.into(),
- RustixErrno::CONNREFUSED => Errno::Connrefused.into(),
- RustixErrno::CONNRESET => Errno::Connreset.into(),
- RustixErrno::DESTADDRREQ => Errno::Destaddrreq.into(),
- RustixErrno::DQUOT => Errno::Dquot.into(),
- RustixErrno::HOSTUNREACH => Errno::Hostunreach.into(),
- RustixErrno::INPROGRESS => Errno::Inprogress.into(),
- RustixErrno::INTR => Errno::Intr.into(),
- RustixErrno::ISCONN => Errno::Isconn.into(),
- RustixErrno::MSGSIZE => Errno::Msgsize.into(),
- RustixErrno::NETDOWN => Errno::Netdown.into(),
- RustixErrno::NETRESET => Errno::Netreset.into(),
- RustixErrno::NETUNREACH => Errno::Netunreach.into(),
- RustixErrno::NOBUFS => Errno::Nobufs.into(),
- RustixErrno::NOPROTOOPT => Errno::Noprotoopt.into(),
- RustixErrno::NOTCONN => Errno::Notconn.into(),
- RustixErrno::NOTSOCK => Errno::Notsock.into(),
- RustixErrno::PROTONOSUPPORT => Errno::Protonosupport.into(),
- RustixErrno::PROTOTYPE => Errno::Prototype.into(),
- RustixErrno::STALE => Errno::Stale.into(),
- RustixErrno::TIMEDOUT => Errno::Timedout.into(),
-
- // On some platforms.into(), these have the same value as other errno values.
- #[allow(unreachable_patterns, reason = "see comment")]
- RustixErrno::WOULDBLOCK => Errno::Again.into(),
- #[allow(unreachable_patterns, reason = "see comment")]
- RustixErrno::OPNOTSUPP => Errno::Notsup.into(),
-
- _ => return None,
- })
-}
-#[cfg(windows)]
-fn from_raw_os_error(raw_os_error: Option<i32>) -> Option<Error> {
- use windows_sys::Win32::Foundation;
- use windows_sys::Win32::Networking::WinSock;
-
- match raw_os_error.map(|code| code as u32) {
- Some(Foundation::ERROR_BAD_ENVIRONMENT) => return Some(Errno::TooBig.into()),
- Some(Foundation::ERROR_FILE_NOT_FOUND) => return Some(Errno::Noent.into()),
- Some(Foundation::ERROR_PATH_NOT_FOUND) => return Some(Errno::Noent.into()),
- Some(Foundation::ERROR_TOO_MANY_OPEN_FILES) => return Some(Errno::Nfile.into()),
- Some(Foundation::ERROR_ACCESS_DENIED) => return Some(Errno::Acces.into()),
- Some(Foundation::ERROR_SHARING_VIOLATION) => return Some(Errno::Acces.into()),
- Some(Foundation::ERROR_PRIVILEGE_NOT_HELD) => return Some(Errno::Perm.into()),
- Some(Foundation::ERROR_INVALID_HANDLE) => return Some(Errno::Badf.into()),
- Some(Foundation::ERROR_INVALID_NAME) => return Some(Errno::Noent.into()),
- Some(Foundation::ERROR_NOT_ENOUGH_MEMORY) => return Some(Errno::Nomem.into()),
- Some(Foundation::ERROR_OUTOFMEMORY) => return Some(Errno::Nomem.into()),
- Some(Foundation::ERROR_DIR_NOT_EMPTY) => return Some(Errno::Notempty.into()),
- Some(Foundation::ERROR_NOT_READY) => return Some(Errno::Busy.into()),
- Some(Foundation::ERROR_BUSY) => return Some(Errno::Busy.into()),
- Some(Foundation::ERROR_NOT_SUPPORTED) => return Some(Errno::Notsup.into()),
- Some(Foundation::ERROR_FILE_EXISTS) => return Some(Errno::Exist.into()),
- Some(Foundation::ERROR_BROKEN_PIPE) => return Some(Errno::Pipe.into()),
- Some(Foundation::ERROR_BUFFER_OVERFLOW) => return Some(Errno::Nametoolong.into()),
- Some(Foundation::ERROR_NOT_A_REPARSE_POINT) => return Some(Errno::Inval.into()),
- Some(Foundation::ERROR_NEGATIVE_SEEK) => return Some(Errno::Inval.into()),
- Some(Foundation::ERROR_DIRECTORY) => return Some(Errno::Notdir.into()),
- Some(Foundation::ERROR_ALREADY_EXISTS) => return Some(Errno::Exist.into()),
- Some(Foundation::ERROR_STOPPED_ON_SYMLINK) => return Some(Errno::Loop.into()),
- Some(Foundation::ERROR_DIRECTORY_NOT_SUPPORTED) => return Some(Errno::Isdir.into()),
- _ => {}
- }
-
- match raw_os_error {
- Some(WinSock::WSAEWOULDBLOCK) => Some(Errno::Again.into()),
- Some(WinSock::WSAECANCELLED) => Some(Errno::Canceled.into()),
- Some(WinSock::WSA_E_CANCELLED) => Some(Errno::Canceled.into()),
- Some(WinSock::WSAEBADF) => Some(Errno::Badf.into()),
- Some(WinSock::WSAEFAULT) => Some(Errno::Fault.into()),
- Some(WinSock::WSAEINVAL) => Some(Errno::Inval.into()),
- Some(WinSock::WSAEMFILE) => Some(Errno::Mfile.into()),
- Some(WinSock::WSAENAMETOOLONG) => Some(Errno::Nametoolong.into()),
- Some(WinSock::WSAENOTEMPTY) => Some(Errno::Notempty.into()),
- Some(WinSock::WSAELOOP) => Some(Errno::Loop.into()),
- Some(WinSock::WSAEOPNOTSUPP) => Some(Errno::Notsup.into()),
- Some(WinSock::WSAEADDRINUSE) => Some(Errno::Addrinuse.into()),
- Some(WinSock::WSAEACCES) => Some(Errno::Acces.into()),
- Some(WinSock::WSAEADDRNOTAVAIL) => Some(Errno::Addrnotavail.into()),
- Some(WinSock::WSAEAFNOSUPPORT) => Some(Errno::Afnosupport.into()),
- Some(WinSock::WSAEALREADY) => Some(Errno::Already.into()),
- Some(WinSock::WSAECONNABORTED) => Some(Errno::Connaborted.into()),
- Some(WinSock::WSAECONNREFUSED) => Some(Errno::Connrefused.into()),
- Some(WinSock::WSAECONNRESET) => Some(Errno::Connreset.into()),
- Some(WinSock::WSAEDESTADDRREQ) => Some(Errno::Destaddrreq.into()),
- Some(WinSock::WSAEDQUOT) => Some(Errno::Dquot.into()),
- Some(WinSock::WSAEHOSTUNREACH) => Some(Errno::Hostunreach.into()),
- Some(WinSock::WSAEINPROGRESS) => Some(Errno::Inprogress.into()),
- Some(WinSock::WSAEINTR) => Some(Errno::Intr.into()),
- Some(WinSock::WSAEISCONN) => Some(Errno::Isconn.into()),
- Some(WinSock::WSAEMSGSIZE) => Some(Errno::Msgsize.into()),
- Some(WinSock::WSAENETDOWN) => Some(Errno::Netdown.into()),
- Some(WinSock::WSAENETRESET) => Some(Errno::Netreset.into()),
- Some(WinSock::WSAENETUNREACH) => Some(Errno::Netunreach.into()),
- Some(WinSock::WSAENOBUFS) => Some(Errno::Nobufs.into()),
- Some(WinSock::WSAENOPROTOOPT) => Some(Errno::Noprotoopt.into()),
- Some(WinSock::WSAENOTCONN) => Some(Errno::Notconn.into()),
- Some(WinSock::WSAENOTSOCK) => Some(Errno::Notsock.into()),
- Some(WinSock::WSAEPROTONOSUPPORT) => Some(Errno::Protonosupport.into()),
- Some(WinSock::WSAEPROTOTYPE) => Some(Errno::Prototype.into()),
- Some(WinSock::WSAESTALE) => Some(Errno::Stale.into()),
- Some(WinSock::WSAETIMEDOUT) => Some(Errno::Timedout.into()),
- _ => None,
- }
-}
-
-impl From<std::io::Error> for Error {
- fn from(err: std::io::Error) -> Error {
- match from_raw_os_error(err.raw_os_error()) {
- Some(errno) => errno,
- None => match err.kind() {
- std::io::ErrorKind::NotFound => Errno::Noent.into(),
- std::io::ErrorKind::PermissionDenied => Errno::Perm.into(),
- std::io::ErrorKind::AlreadyExists => Errno::Exist.into(),
- std::io::ErrorKind::InvalidInput => Errno::Inval.into(),
- std::io::ErrorKind::WouldBlock => Errno::Again.into(),
- _ => Error::trap(format_err!(err).context("Unknown OS error")),
- },
- }
- }
-}
-
-impl From<wiggle::GuestError> for Error {
- fn from(err: wiggle::GuestError) -> Error {
- use wiggle::GuestError::*;
- match err {
- InvalidFlagValue { .. } => Errno::Inval.into(),
- InvalidEnumValue { .. } => Errno::Inval.into(),
- // As per
- // https://github.com/WebAssembly/wasi/blob/main/legacy/tools/witx-docs.md#pointers
- //
- // > If a misaligned pointer is passed to a function, the function
- // > shall trap.
- // >
- // > If an out-of-bounds pointer is passed to a function and the
- // > function needs to dereference it, the function shall trap.
- //
- // so this turns OOB and misalignment errors into traps.
- PtrOverflow { .. } | PtrOutOfBounds { .. } | PtrNotAligned { .. } => {
- Error::trap(err.into())
- }
- InvalidUtf8 { .. } => Errno::Ilseq.into(),
- TryFromIntError { .. } => Errno::Overflow.into(),
- SliceLengthsDiffer { .. } => Errno::Fault.into(),
- InFunc { err, .. } => Error::from(*err),
- }
- }
-}
-
-impl From<std::num::TryFromIntError> for Error {
- fn from(_err: std::num::TryFromIntError) -> Error {
- Errno::Overflow.into()
- }
-}
diff --git a/crates/wasi-common/src/string_array.rs b/crates/wasi-common/src/string_array.rs
deleted file mode 100644
index f35efe032c..0000000000
--- a/crates/wasi-common/src/string_array.rs
+++ /dev/null
@@ -1,75 +0,0 @@
-use crate::{Error, ErrorExt};
-use wiggle::{GuestMemory, GuestPtr};
-
-pub struct StringArray {
- elems: Vec<String>,
-}
-
-#[derive(Debug, thiserror::Error)]
-pub enum StringArrayError {
- #[error("Number of elements exceeds 2^32")]
- NumberElements,
- #[error("Element size exceeds 2^32")]
- ElementSize,
- #[error("Cumulative size exceeds 2^32")]
- CumulativeSize,
-}
-
-impl StringArray {
- pub fn new() -> Self {
- StringArray { elems: Vec::new() }
- }
-
- pub fn push(&mut self, elem: String) -> Result<(), StringArrayError> {
- if self.elems.len() + 1 > std::u32::MAX as usize {
- return Err(StringArrayError::NumberElements);
- }
- if elem.as_bytes().len() + 1 > std::u32::MAX as usize {
- return Err(StringArrayError::ElementSize);
- }
- if self.cumulative_size() as usize + elem.as_bytes().len() + 1 > std::u32::MAX as usize {
- return Err(StringArrayError::CumulativeSize);
- }
- self.elems.push(elem);
- Ok(())
- }
-
- pub fn number_elements(&self) -> u32 {
- self.elems.len() as u32
- }
-
- pub fn cumulative_size(&self) -> u32 {
- self.elems
- .iter()
- .map(|e| e.as_bytes().len() + 1)
- .sum::<usize>() as u32
- }
-
- pub fn write_to_guest(
- &self,
- memory: &mut GuestMemory<'_>,
- buffer: GuestPtr<u8>,
- element_heads: GuestPtr<GuestPtr<u8>>,
- ) -> Result<(), Error> {
- let element_heads = element_heads.as_array(self.number_elements());
- let buffer = buffer.as_array(self.cumulative_size());
- let mut cursor = 0;
- for (elem, head) in self.elems.iter().zip(element_heads.iter()) {
- let bytes = elem.as_bytes();
- let len = bytes.len() as u32;
- {
- let elem_buffer = buffer
- .get_range(cursor..(cursor + len))
- .ok_or(Error::invalid_argument())?; // Elements don't fit in buffer provided
- memory.copy_from_slice(bytes, elem_buffer)?;
- }
- memory.write(
- buffer.get(cursor + len).ok_or(Error::invalid_argument())?,
- 0,
- )?; // 0 terminate
- memory.write(head?, buffer.get(cursor).expect("already validated"))?;
- cursor += len + 1;
- }
- Ok(())
- }
-}
diff --git a/crates/wasi-common/src/sync/clocks.rs b/crates/wasi-common/src/sync/clocks.rs
deleted file mode 100644
index bd333e10ae..0000000000
--- a/crates/wasi-common/src/sync/clocks.rs
+++ /dev/null
@@ -1,41 +0,0 @@
-use crate::clocks::{WasiClocks, WasiMonotonicClock, WasiSystemClock};
-use cap_std::time::{Duration, Instant, SystemTime};
-use cap_std::{AmbientAuthority, ambient_authority};
-use cap_time_ext::{MonotonicClockExt, SystemClockExt};
-
-pub struct SystemClock(cap_std::time::SystemClock);
-
-impl SystemClock {
- pub fn new(ambient_authority: AmbientAuthority) -> Self {
- SystemClock(cap_std::time::SystemClock::new(ambient_authority))
- }
-}
-impl WasiSystemClock for SystemClock {
- fn resolution(&self) -> Duration {
- self.0.resolution()
- }
- fn now(&self, precision: Duration) -> SystemTime {
- self.0.now_with(precision)
- }
-}
-
-pub struct MonotonicClock(cap_std::time::MonotonicClock);
-impl MonotonicClock {
- pub fn new(ambient_authority: AmbientAuthority) -> Self {
- MonotonicClock(cap_std::time::MonotonicClock::new(ambient_authority))
- }
-}
-impl WasiMonotonicClock for MonotonicClock {
- fn resolution(&self) -> Duration {
- self.0.resolution()
- }
- fn now(&self, precision: Duration) -> Instant {
- self.0.now_with(precision)
- }
-}
-
-pub fn clocks_ctx() -> WasiClocks {
- WasiClocks::new()
- .with_system(SystemClock::new(ambient_authority()))
- .with_monotonic(MonotonicClock::new(ambient_authority()))
-}
diff --git a/crates/wasi-common/src/sync/dir.rs b/crates/wasi-common/src/sync/dir.rs
deleted file mode 100644
index 5ad37441cb..0000000000
--- a/crates/wasi-common/src/sync/dir.rs
+++ /dev/null
@@ -1,469 +0,0 @@
-use crate::sync::file::{File, filetype_from};
-use crate::{
- Error, ErrorExt,
- dir::{ReaddirCursor, ReaddirEntity, WasiDir},
- file::{FdFlags, FileType, Filestat, OFlags},
-};
-use cap_fs_ext::{DirEntryExt, DirExt, MetadataExt, OpenOptionsMaybeDirExt, SystemTimeSpec};
-use cap_std::fs;
-use std::any::Any;
-use std::path::{Path, PathBuf};
-use system_interface::fs::GetSetFdFlags;
-
-pub struct Dir(fs::Dir);
-
-pub enum OpenResult {
- File(File),
- Dir(Dir),
-}
-
-impl Dir {
- pub fn from_cap_std(dir: fs::Dir) -> Self {
- Dir(dir)
- }
-
- pub fn open_file_(
- &self,
- symlink_follow: bool,
- path: &str,
- oflags: OFlags,
- read: bool,
- write: bool,
- fdflags: FdFlags,
- ) -> Result<OpenResult, Error> {
- use cap_fs_ext::{FollowSymlinks, OpenOptionsFollowExt};
-
- let mut opts = fs::OpenOptions::new();
- opts.maybe_dir(true);
-
- if oflags.contains(OFlags::CREATE | OFlags::EXCLUSIVE) {
- opts.create_new(true);
- opts.write(true);
- } else if oflags.contains(OFlags::CREATE) {
- opts.create(true);
- opts.write(true);
- }
- if oflags.contains(OFlags::TRUNCATE) {
- opts.truncate(true);
- }
- if read {
- opts.read(true);
- }
- if write {
- opts.write(true);
- } else {
- // If not opened write, open read. This way the OS lets us open the file.
- // If FileCaps::READ is not set, read calls will be rejected at the
- // get_cap check.
- opts.read(true);
- }
- if fdflags.contains(FdFlags::APPEND) {
- opts.append(true);
- }
-
- if symlink_follow {
- opts.follow(FollowSymlinks::Yes);
- } else {
- opts.follow(FollowSymlinks::No);
- }
- // the DSYNC, SYNC, and RSYNC flags are ignored! We do not
- // have support for them in cap-std yet.
- // ideally OpenOptions would just support this though:
- // https://github.com/bytecodealliance/cap-std/issues/146
- if fdflags.intersects(
- crate::file::FdFlags::DSYNC | crate::file::FdFlags::SYNC | crate::file::FdFlags::RSYNC,
- ) {
- return Err(Error::not_supported().context("SYNC family of FdFlags"));
- }
-
- if oflags.contains(OFlags::DIRECTORY) {
- if oflags.contains(OFlags::CREATE)
- || oflags.contains(OFlags::EXCLUSIVE)
- || oflags.contains(OFlags::TRUNCATE)
- {
- return Err(Error::invalid_argument().context("directory oflags"));
- }
- }
-
- let mut f = self.0.open_with(Path::new(path), &opts)?;
- if f.metadata()?.is_dir() {
- Ok(OpenResult::Dir(Dir::from_cap_std(fs::Dir::from_std_file(
- f.into_std(),
- ))))
- } else if oflags.contains(OFlags::DIRECTORY) {
- Err(Error::not_dir().context("expected directory but got file"))
- } else {
- // NONBLOCK does not have an OpenOption either, but we can patch that on with set_fd_flags:
- if fdflags.contains(crate::file::FdFlags::NONBLOCK) {
- let set_fd_flags = f.new_set_fd_flags(
- if fdflags.contains(crate::file::FdFlags::APPEND) {
- system_interface::fs::FdFlags::APPEND
- } else {
- system_interface::fs::FdFlags::empty()
- } | system_interface::fs::FdFlags::NONBLOCK,
- )?;
- f.set_fd_flags(set_fd_flags)?;
- }
- Ok(OpenResult::File(File::from_cap_std(f)))
- }
- }
-
- pub fn rename_(&self, src_path: &str, dest_dir: &Self, dest_path: &str) -> Result<(), Error> {
- self.0
- .rename(Path::new(src_path), &dest_dir.0, Path::new(dest_path))?;
- Ok(())
- }
- pub fn hard_link_(
- &self,
- src_path: &str,
- target_dir: &Self,
- target_path: &str,
- ) -> Result<(), Error> {
- let src_path = Path::new(src_path);
- let target_path = Path::new(target_path);
- self.0.hard_link(src_path, &target_dir.0, target_path)?;
- Ok(())
- }
-}
-
-#[async_trait::async_trait]
-impl WasiDir for Dir {
- fn as_any(&self) -> &dyn Any {
- self
- }
- async fn open_file(
- &self,
- symlink_follow: bool,
- path: &str,
- oflags: OFlags,
- read: bool,
- write: bool,
- fdflags: FdFlags,
- ) -> Result<crate::dir::OpenResult, Error> {
- let f = self.open_file_(symlink_follow, path, oflags, read, write, fdflags)?;
- match f {
- OpenResult::File(f) => Ok(crate::dir::OpenResult::File(Box::new(f))),
- OpenResult::Dir(d) => Ok(crate::dir::OpenResult::Dir(Box::new(d))),
- }
- }
-
- async fn create_dir(&self, path: &str) -> Result<(), Error> {
- self.0.create_dir(Path::new(path))?;
- Ok(())
- }
- async fn readdir(
- &self,
- cursor: ReaddirCursor,
- ) -> Result<Box<dyn Iterator<Item = Result<ReaddirEntity, Error>> + Send>, Error> {
- // We need to keep a full-fidelity io Error around to check for a special failure mode
- // on windows, but also this function can fail due to an illegal byte sequence in a
- // filename, which we can't construct an io Error to represent.
- enum ReaddirError {
- Io(std::io::Error),
- IllegalSequence,
- }
- impl From<std::io::Error> for ReaddirError {
- fn from(e: std::io::Error) -> ReaddirError {
- ReaddirError::Io(e)
- }
- }
-
- // cap_std's read_dir does not include . and .., we should prepend these.
- // Why does the Ok contain a tuple? We can't construct a cap_std::fs::DirEntry, and we don't
- // have enough info to make a ReaddirEntity yet.
- let dir_meta = self.0.dir_metadata()?;
- let rd = vec![
- {
- let name = ".".to_owned();
- Ok::<_, ReaddirError>((FileType::Directory, dir_meta.ino(), name))
- },
- {
- let name = "..".to_owned();
- Ok((FileType::Directory, dir_meta.ino(), name))
- },
- ]
- .into_iter()
- .chain({
- // Now process the `DirEntry`s:
- let entries = self.0.entries()?.map(|entry| {
- let entry = entry?;
- let meta = entry.full_metadata()?;
- let inode = meta.ino();
- let filetype = filetype_from(&meta.file_type());
- let name = entry
- .file_name()
- .into_string()
- .map_err(|_| ReaddirError::IllegalSequence)?;
- Ok((filetype, inode, name))
- });
-
- // On Windows, filter out files like `C:\DumpStack.log.tmp` which we
- // can't get a full metadata for.
- #[cfg(windows)]
- let entries = entries.filter(|entry| {
- use windows_sys::Win32::Foundation::{
- ERROR_ACCESS_DENIED, ERROR_SHARING_VIOLATION,
- };
- if let Err(ReaddirError::Io(err)) = entry {
- if err.raw_os_error() == Some(ERROR_SHARING_VIOLATION as i32)
- || err.raw_os_error() == Some(ERROR_ACCESS_DENIED as i32)
- {
- return false;
- }
- }
- true
- });
-
- entries
- })
- // Enumeration of the iterator makes it possible to define the ReaddirCursor
- .enumerate()
- .map(|(ix, r)| match r {
- Ok((filetype, inode, name)) => Ok(ReaddirEntity {
- next: ReaddirCursor::from(ix as u64 + 1),
- filetype,
- inode,
- name,
- }),
- Err(ReaddirError::Io(e)) => Err(e.into()),
- Err(ReaddirError::IllegalSequence) => Err(Error::illegal_byte_sequence()),
- })
- .skip(u64::from(cursor) as usize);
-
- Ok(Box::new(rd))
- }
-
- async fn symlink(&self, src_path: &str, dest_path: &str) -> Result<(), Error> {
- self.0.symlink(src_path, dest_path)?;
- Ok(())
- }
- async fn remove_dir(&self, path: &str) -> Result<(), Error> {
- self.0.remove_dir(Path::new(path))?;
- Ok(())
- }
-
- async fn unlink_file(&self, path: &str) -> Result<(), Error> {
- self.0.remove_file_or_symlink(Path::new(path))?;
- Ok(())
- }
- async fn read_link(&self, path: &str) -> Result<PathBuf, Error> {
- let link = self.0.read_link(Path::new(path))?;
- Ok(link)
- }
- async fn get_filestat(&self) -> Result<Filestat, Error> {
- let meta = self.0.dir_metadata()?;
- Ok(Filestat {
- device_id: meta.dev(),
- inode: meta.ino(),
- filetype: filetype_from(&meta.file_type()),
- nlink: meta.nlink(),
- size: meta.len(),
- atim: meta.accessed().map(|t| Some(t.into_std())).unwrap_or(None),
- mtim: meta.modified().map(|t| Some(t.into_std())).unwrap_or(None),
- ctim: meta.created().map(|t| Some(t.into_std())).unwrap_or(None),
- })
- }
- async fn get_path_filestat(
- &self,
- path: &str,
- follow_symlinks: bool,
- ) -> Result<Filestat, Error> {
- let meta = if follow_symlinks {
- self.0.metadata(Path::new(path))?
- } else {
- self.0.symlink_metadata(Path::new(path))?
- };
- Ok(Filestat {
- device_id: meta.dev(),
- inode: meta.ino(),
- filetype: filetype_from(&meta.file_type()),
- nlink: meta.nlink(),
- size: meta.len(),
- atim: meta.accessed().map(|t| Some(t.into_std())).unwrap_or(None),
- mtim: meta.modified().map(|t| Some(t.into_std())).unwrap_or(None),
- ctim: meta.created().map(|t| Some(t.into_std())).unwrap_or(None),
- })
- }
- async fn rename(
- &self,
- src_path: &str,
- dest_dir: &dyn WasiDir,
- dest_path: &str,
- ) -> Result<(), Error> {
- let dest_dir = dest_dir
- .as_any()
- .downcast_ref::<Self>()
- .ok_or(Error::badf().context("failed downcast to cap-std Dir"))?;
- self.rename_(src_path, dest_dir, dest_path)
- }
- async fn hard_link(
- &self,
- src_path: &str,
- target_dir: &dyn WasiDir,
- target_path: &str,
- ) -> Result<(), Error> {
- let target_dir = target_dir
- .as_any()
- .downcast_ref::<Self>()
- .ok_or(Error::badf().context("failed downcast to cap-std Dir"))?;
- self.hard_link_(src_path, target_dir, target_path)
- }
- async fn set_times(
- &self,
- path: &str,
- atime: Option<crate::SystemTimeSpec>,
- mtime: Option<crate::SystemTimeSpec>,
- follow_symlinks: bool,
- ) -> Result<(), Error> {
- if follow_symlinks {
- self.0.set_times(
- Path::new(path),
- convert_systimespec(atime),
- convert_systimespec(mtime),
- )?;
- } else {
- self.0.set_symlink_times(
- Path::new(path),
- convert_systimespec(atime),
- convert_systimespec(mtime),
- )?;
- }
- Ok(())
- }
-}
-
-fn convert_systimespec(t: Option<crate::SystemTimeSpec>) -> Option<SystemTimeSpec> {
- match t {
- Some(crate::SystemTimeSpec::Absolute(t)) => Some(SystemTimeSpec::Absolute(t)),
- Some(crate::SystemTimeSpec::SymbolicNow) => Some(SystemTimeSpec::SymbolicNow),
- None => None,
- }
-}
-
-#[cfg(test)]
-mod test {
- use super::Dir;
- use crate::file::{FdFlags, OFlags};
- use cap_std::ambient_authority;
- #[test]
- fn scratch_dir() {
- let tempdir = tempfile::Builder::new()
- .prefix("cap-std-sync")
- .tempdir()
- .expect("create temporary dir");
- let preopen_dir = cap_std::fs::Dir::open_ambient_dir(tempdir.path(), ambient_authority())
- .expect("open ambient temporary dir");
- let preopen_dir = Dir::from_cap_std(preopen_dir);
- run(crate::WasiDir::open_file(
- &preopen_dir,
- false,
- ".",
- OFlags::empty(),
- false,
- false,
- FdFlags::empty(),
- ))
- .expect("open the same directory via WasiDir abstraction");
- }
-
- // Readdir does not work on windows, so we won't test it there.
- #[cfg(not(windows))]
- #[test]
- fn readdir() {
- use crate::dir::{ReaddirCursor, ReaddirEntity, WasiDir};
- use crate::file::{FdFlags, FileType, OFlags};
- use std::collections::HashMap;
-
- fn readdir_into_map(dir: &dyn WasiDir) -> HashMap<String, ReaddirEntity> {
- let mut out = HashMap::new();
- for readdir_result in
- run(dir.readdir(ReaddirCursor::from(0))).expect("readdir succeeds")
- {
- let entity = readdir_result.expect("readdir entry is valid");
- out.insert(entity.name.clone(), entity);
- }
- out
- }
-
- let tempdir = tempfile::Builder::new()
- .prefix("cap-std-sync")
- .tempdir()
- .expect("create temporary dir");
- let preopen_dir = cap_std::fs::Dir::open_ambient_dir(tempdir.path(), ambient_authority())
- .expect("open ambient temporary dir");
- let preopen_dir = Dir::from_cap_std(preopen_dir);
-
- let entities = readdir_into_map(&preopen_dir);
- assert_eq!(
- entities.len(),
- 2,
- "should just be . and .. in empty dir: {entities:?}"
- );
- assert!(entities.get(".").is_some());
- assert!(entities.get("..").is_some());
-
- run(preopen_dir.open_file(
- false,
- "file1",
- OFlags::CREATE,
- true,
- false,
- FdFlags::empty(),
- ))
- .expect("create file1");
-
- let entities = readdir_into_map(&preopen_dir);
- assert_eq!(entities.len(), 3, "should be ., .., file1 {entities:?}");
- assert_eq!(
- entities.get(".").expect(". entry").filetype,
- FileType::Directory
- );
- assert_eq!(
- entities.get("..").expect(".. entry").filetype,
- FileType::Directory
- );
- assert_eq!(
- entities.get("file1").expect("file1 entry").filetype,
- FileType::RegularFile
- );
- }
-
- fn run<F: std::future::Future>(future: F) -> F::Output {
- use std::pin::Pin;
- use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
-
- let mut f = Pin::from(Box::new(future));
- let waker = dummy_waker();
- let mut cx = Context::from_waker(&waker);
- match f.as_mut().poll(&mut cx) {
- Poll::Ready(val) => return val,
- Poll::Pending => {
- panic!(
- "Cannot wait on pending future: must enable wiggle \"async\" future and execute on an async Store"
- )
- }
- }
-
- fn dummy_waker() -> Waker {
- return unsafe { Waker::from_raw(clone(5 as *const _)) };
-
- unsafe fn clone(ptr: *const ()) -> RawWaker {
- assert_eq!(ptr as usize, 5);
- const VTABLE: RawWakerVTable = RawWakerVTable::new(clone, wake, wake_by_ref, drop);
- RawWaker::new(ptr, &VTABLE)
- }
-
- unsafe fn wake(ptr: *const ()) {
- assert_eq!(ptr as usize, 5);
- }
-
- unsafe fn wake_by_ref(ptr: *const ()) {
- assert_eq!(ptr as usize, 5);
- }
-
- unsafe fn drop(ptr: *const ()) {
- assert_eq!(ptr as usize, 5);
- }
- }
- }
-}
diff --git a/crates/wasi-common/src/sync/file.rs b/crates/wasi-common/src/sync/file.rs
deleted file mode 100644
index dcb024c601..0000000000
--- a/crates/wasi-common/src/sync/file.rs
+++ /dev/null
@@ -1,250 +0,0 @@
-use crate::{
- Error, ErrorExt,
- file::{Advice, FdFlags, FileType, Filestat, WasiFile},
-};
-use cap_fs_ext::MetadataExt;
-use fs_set_times::{SetTimes, SystemTimeSpec};
-use io_lifetimes::AsFilelike;
-use std::any::Any;
-use std::io::{self, IsTerminal};
-use system_interface::{
- fs::{FileIoExt, GetSetFdFlags},
- io::{IoExt, ReadReady},
-};
-
-pub struct File(cap_std::fs::File);
-
-impl File {
- pub fn from_cap_std(file: cap_std::fs::File) -> Self {
- File(file)
- }
-}
-
-#[async_trait::async_trait]
-impl WasiFile for File {
- fn as_any(&self) -> &dyn Any {
- self
- }
- #[cfg(unix)]
- fn pollable(&self) -> Option<rustix::fd::BorrowedFd<'_>> {
- Some(self.0.as_fd())
- }
- #[cfg(windows)]
- fn pollable(&self) -> Option<io_extras::os::windows::RawHandleOrSocket> {
- Some(self.0.as_raw_handle_or_socket())
- }
- async fn datasync(&self) -> Result<(), Error> {
- self.0.sync_data()?;
- Ok(())
- }
- async fn sync(&self) -> Result<(), Error> {
- self.0.sync_all()?;
- Ok(())
- }
- async fn get_filetype(&self) -> Result<FileType, Error> {
- let meta = self.0.metadata()?;
- Ok(filetype_from(&meta.file_type()))
- }
- async fn get_fdflags(&self) -> Result<FdFlags, Error> {
- let fdflags = get_fd_flags(&self.0)?;
- Ok(fdflags)
- }
- async fn set_fdflags(&mut self, fdflags: FdFlags) -> Result<(), Error> {
- if fdflags.intersects(
- crate::file::FdFlags::DSYNC | crate::file::FdFlags::SYNC | crate::file::FdFlags::RSYNC,
- ) {
- return Err(Error::invalid_argument().context("cannot set DSYNC, SYNC, or RSYNC flag"));
- }
- let set_fd_flags = self.0.new_set_fd_flags(to_sysif_fdflags(fdflags))?;
- self.0.set_fd_flags(set_fd_flags)?;
- Ok(())
- }
- async fn get_filestat(&self) -> Result<Filestat, Error> {
- let meta = self.0.metadata()?;
- Ok(Filestat {
- device_id: meta.dev(),
- inode: meta.ino(),
- filetype: filetype_from(&meta.file_type()),
- nlink: meta.nlink(),
- size: meta.len(),
- atim: meta.accessed().map(|t| Some(t.into_std())).unwrap_or(None),
- mtim: meta.modified().map(|t| Some(t.into_std())).unwrap_or(None),
- ctim: meta.created().map(|t| Some(t.into_std())).unwrap_or(None),
- })
- }
- async fn set_filestat_size(&self, size: u64) -> Result<(), Error> {
- self.0.set_len(size)?;
- Ok(())
- }
- async fn advise(&self, offset: u64, len: u64, advice: Advice) -> Result<(), Error> {
- self.0.advise(offset, len, convert_advice(advice))?;
- Ok(())
- }
- async fn set_times(
- &self,
- atime: Option<crate::SystemTimeSpec>,
- mtime: Option<crate::SystemTimeSpec>,
- ) -> Result<(), Error> {
- self.0
- .set_times(convert_systimespec(atime), convert_systimespec(mtime))?;
- Ok(())
- }
- async fn read_vectored<'a>(&self, bufs: &mut [io::IoSliceMut<'a>]) -> Result<u64, Error> {
- let n = self.0.read_vectored(bufs)?;
- Ok(n.try_into()?)
- }
- async fn read_vectored_at<'a>(
- &self,
- bufs: &mut [io::IoSliceMut<'a>],
- offset: u64,
- ) -> Result<u64, Error> {
- let n = self.0.read_vectored_at(bufs, offset)?;
- Ok(n.try_into()?)
- }
- async fn write_vectored<'a>(&self, bufs: &[io::IoSlice<'a>]) -> Result<u64, Error> {
- let n = self.0.write_vectored(bufs)?;
- Ok(n.try_into()?)
- }
- async fn write_vectored_at<'a>(
- &self,
- bufs: &[io::IoSlice<'a>],
- offset: u64,
- ) -> Result<u64, Error> {
- if bufs.iter().map(|i| i.len()).sum::<usize>() == 0 {
- return Ok(0);
- }
- let n = self.0.write_vectored_at(bufs, offset)?;
- Ok(n.try_into()?)
- }
- async fn seek(&self, pos: std::io::SeekFrom) -> Result<u64, Error> {
- Ok(self.0.seek(pos)?)
- }
- async fn peek(&self, buf: &mut [u8]) -> Result<u64, Error> {
- let n = self.0.peek(buf)?;
- Ok(n.try_into()?)
- }
- fn num_ready_bytes(&self) -> Result<u64, Error> {
- Ok(self.0.num_ready_bytes()?)
- }
- fn isatty(&self) -> bool {
- #[cfg(unix)]
- return self.0.as_fd().is_terminal();
- #[cfg(windows)]
- return self.0.as_handle().is_terminal();
- }
-}
-
-pub fn filetype_from(ft: &cap_std::fs::FileType) -> FileType {
- use cap_fs_ext::FileTypeExt;
- if ft.is_dir() {
- FileType::Directory
- } else if ft.is_symlink() {
- FileType::SymbolicLink
- } else if ft.is_socket() {
- if ft.is_block_device() {
- FileType::SocketDgram
- } else {
- FileType::SocketStream
- }
- } else if ft.is_block_device() {
- FileType::BlockDevice
- } else if ft.is_char_device() {
- FileType::CharacterDevice
- } else if ft.is_file() {
- FileType::RegularFile
- } else {
- FileType::Unknown
- }
-}
-
-#[cfg(windows)]
-use io_lifetimes::{AsHandle, BorrowedHandle};
-#[cfg(windows)]
-impl AsHandle for File {
- fn as_handle(&self) -> BorrowedHandle<'_> {
- self.0.as_handle()
- }
-}
-
-#[cfg(windows)]
-use io_extras::os::windows::{AsRawHandleOrSocket, RawHandleOrSocket};
-#[cfg(windows)]
-impl AsRawHandleOrSocket for File {
- #[inline]
- fn as_raw_handle_or_socket(&self) -> RawHandleOrSocket {
- self.0.as_raw_handle_or_socket()
- }
-}
-
-#[cfg(unix)]
-use io_lifetimes::{AsFd, BorrowedFd};
-
-#[cfg(unix)]
-impl AsFd for File {
- fn as_fd(&self) -> BorrowedFd<'_> {
- self.0.as_fd()
- }
-}
-
-pub(crate) fn convert_systimespec(t: Option<crate::SystemTimeSpec>) -> Option<SystemTimeSpec> {
- match t {
- Some(crate::SystemTimeSpec::Absolute(t)) => Some(SystemTimeSpec::Absolute(t.into_std())),
- Some(crate::SystemTimeSpec::SymbolicNow) => Some(SystemTimeSpec::SymbolicNow),
- None => None,
- }
-}
-
-pub(crate) fn to_sysif_fdflags(f: crate::file::FdFlags) -> system_interface::fs::FdFlags {
- let mut out = system_interface::fs::FdFlags::empty();
- if f.contains(crate::file::FdFlags::APPEND) {
- out |= system_interface::fs::FdFlags::APPEND;
- }
- if f.contains(crate::file::FdFlags::DSYNC) {
- out |= system_interface::fs::FdFlags::DSYNC;
- }
- if f.contains(crate::file::FdFlags::NONBLOCK) {
- out |= system_interface::fs::FdFlags::NONBLOCK;
- }
- if f.contains(crate::file::FdFlags::RSYNC) {
- out |= system_interface::fs::FdFlags::RSYNC;
- }
- if f.contains(crate::file::FdFlags::SYNC) {
- out |= system_interface::fs::FdFlags::SYNC;
- }
- out
-}
-
-/// Return the file-descriptor flags for a given file-like object.
-///
-/// This returns the flags needed to implement [`WasiFile::get_fdflags`].
-pub fn get_fd_flags<Filelike: AsFilelike>(f: Filelike) -> io::Result<crate::file::FdFlags> {
- let f = f.as_filelike().get_fd_flags()?;
- let mut out = crate::file::FdFlags::empty();
- if f.contains(system_interface::fs::FdFlags::APPEND) {
- out |= crate::file::FdFlags::APPEND;
- }
- if f.contains(system_interface::fs::FdFlags::DSYNC) {
- out |= crate::file::FdFlags::DSYNC;
- }
- if f.contains(system_interface::fs::FdFlags::NONBLOCK) {
- out |= crate::file::FdFlags::NONBLOCK;
- }
- if f.contains(system_interface::fs::FdFlags::RSYNC) {
- out |= crate::file::FdFlags::RSYNC;
- }
- if f.contains(system_interface::fs::FdFlags::SYNC) {
- out |= crate::file::FdFlags::SYNC;
- }
- Ok(out)
-}
-
-fn convert_advice(advice: Advice) -> system_interface::fs::Advice {
- match advice {
- Advice::Normal => system_interface::fs::Advice::Normal,
- Advice::Sequential => system_interface::fs::Advice::Sequential,
- Advice::Random => system_interface::fs::Advice::Random,
- Advice::WillNeed => system_interface::fs::Advice::WillNeed,
- Advice::DontNeed => system_interface::fs::Advice::DontNeed,
- Advice::NoReuse => system_interface::fs::Advice::NoReuse,
- }
-}
diff --git a/crates/wasi-common/src/sync/mod.rs b/crates/wasi-common/src/sync/mod.rs
deleted file mode 100644
index 4308cc6052..0000000000
--- a/crates/wasi-common/src/sync/mod.rs
+++ /dev/null
@@ -1,137 +0,0 @@
-//! The `wasi-cap-std-sync` crate provides impl of `WasiFile` and `WasiDir` in
-//! terms of `cap_std::fs::{File, Dir}`. These types provide sandboxed access
-//! to the local filesystem on both Unix and Windows.
-//!
-//! All syscalls are hidden behind the `cap-std` hierarchy, with the lone
-//! exception of the `sched` implementation, which is provided for both unix
-//! and windows in separate modules.
-//!
-//! Any `wasi_common::{WasiCtx, WasiCtxBuilder}` is interoperable with the
-//! implementations provided in `wasi_common::sync`. However, for convenience,
-//! this module provides its own `WasiCtxBuilder` that hooks up to all of the
-//! crate's components, i.e. it fills in all of the arguments to
-//! `WasiCtx::builder(...)`, presents `preopen_dir` in terms of
-//! `cap_std::fs::Dir`, and provides convenience methods for inheriting the
-//! parent process's stdio, args, and env.
-
-pub mod clocks;
-pub mod dir;
-pub mod file;
-pub mod net;
-pub mod sched;
-pub mod stdio;
-
-pub use cap_std::ambient_authority;
-pub use cap_std::fs::Dir;
-pub use cap_std::net::TcpListener;
-pub use clocks::clocks_ctx;
-pub use sched::sched_ctx;
-
-use self::net::Socket;
-use crate::{Error, WasiCtx, WasiFile, file::FileAccessMode, table::Table};
-use rand::{Rng, SeedableRng};
-use std::mem;
-use std::path::Path;
-
-pub struct WasiCtxBuilder {
- ctx: WasiCtx,
- built: bool,
-}
-
-impl WasiCtxBuilder {
- pub fn new() -> Self {
- WasiCtxBuilder {
- ctx: WasiCtx::new(random_ctx(), clocks_ctx(), sched_ctx(), Table::new()),
- built: false,
- }
- }
- pub fn env(&mut self, var: &str, value: &str) -> Result<&mut Self, crate::StringArrayError> {
- self.ctx.push_env(var, value)?;
- Ok(self)
- }
- pub fn envs(&mut self, env: &[(String, String)]) -> Result<&mut Self, crate::StringArrayError> {
- for (k, v) in env {
- self.ctx.push_env(k, v)?;
- }
- Ok(self)
- }
- pub fn inherit_env(&mut self) -> Result<&mut Self, crate::StringArrayError> {
- for (key, value) in std::env::vars() {
- self.ctx.push_env(&key, &value)?;
- }
- Ok(self)
- }
- pub fn arg(&mut self, arg: &str) -> Result<&mut Self, crate::StringArrayError> {
- self.ctx.push_arg(arg)?;
- Ok(self)
- }
- pub fn args(&mut self, arg: &[String]) -> Result<&mut Self, crate::StringArrayError> {
- for a in arg {
- self.ctx.push_arg(&a)?;
- }
- Ok(self)
- }
- pub fn inherit_args(&mut self) -> Result<&mut Self, crate::StringArrayError> {
- for arg in std::env::args() {
- self.ctx.push_arg(&arg)?;
- }
- Ok(self)
- }
- pub fn stdin(&mut self, f: Box<dyn WasiFile>) -> &mut Self {
- self.ctx.set_stdin(f);
- self
- }
- pub fn stdout(&mut self, f: Box<dyn WasiFile>) -> &mut Self {
- self.ctx.set_stdout(f);
- self
- }
- pub fn stderr(&mut self, f: Box<dyn WasiFile>) -> &mut Self {
- self.ctx.set_stderr(f);
- self
- }
- pub fn inherit_stdin(&mut self) -> &mut Self {
- self.stdin(Box::new(crate::sync::stdio::stdin()))
- }
- pub fn inherit_stdout(&mut self) -> &mut Self {
- self.stdout(Box::new(crate::sync::stdio::stdout()))
- }
- pub fn inherit_stderr(&mut self) -> &mut Self {
- self.stderr(Box::new(crate::sync::stdio::stderr()))
- }
- pub fn inherit_stdio(&mut self) -> &mut Self {
- self.inherit_stdin().inherit_stdout().inherit_stderr()
- }
- pub fn preopened_dir(
- &mut self,
- dir: Dir,
- guest_path: impl AsRef<Path>,
- ) -> Result<&mut Self, Error> {
- let dir = Box::new(crate::sync::dir::Dir::from_cap_std(dir));
- self.ctx.push_preopened_dir(dir, guest_path)?;
- Ok(self)
- }
- pub fn preopened_socket(
- &mut self,
- fd: u32,
- socket: impl Into<Socket>,
- ) -> Result<&mut Self, Error> {
- let socket: Socket = socket.into();
- let file: Box<dyn WasiFile> = socket.into();
- self.ctx
- .insert_file(fd, file, FileAccessMode::READ | FileAccessMode::WRITE);
- Ok(self)
- }
- pub fn build(&mut self) -> WasiCtx {
- assert!(!self.built);
- let WasiCtxBuilder { ctx, .. } = mem::replace(self, Self::new());
- self.built = true;
- ctx
- }
-}
-
-pub fn random_ctx() -> Box<dyn Rng + Send + Sync> {
- Box::new(rand::rngs::StdRng::from_seed(rand::random()))
-}
-
-#[cfg(feature = "wasmtime")]
-super::define_wasi!(block_on);
diff --git a/crates/wasi-common/src/sync/net.rs b/crates/wasi-common/src/sync/net.rs
deleted file mode 100644
index 55602f6f76..0000000000
--- a/crates/wasi-common/src/sync/net.rs
+++ /dev/null
@@ -1,393 +0,0 @@
-use crate::{
- Error, ErrorExt,
- file::{FdFlags, FileType, RiFlags, RoFlags, SdFlags, SiFlags, WasiFile},
-};
-#[cfg(windows)]
-use io_extras::os::windows::{AsRawHandleOrSocket, RawHandleOrSocket};
-use io_lifetimes::AsSocketlike;
-#[cfg(unix)]
-use io_lifetimes::{AsFd, BorrowedFd};
-#[cfg(windows)]
-use io_lifetimes::{AsSocket, BorrowedSocket};
-use std::any::Any;
-use std::io;
-#[cfg(unix)]
-use system_interface::fs::GetSetFdFlags;
-use system_interface::io::IoExt;
-use system_interface::io::IsReadWrite;
-use system_interface::io::ReadReady;
-
-pub enum Socket {
- TcpListener(cap_std::net::TcpListener),
- TcpStream(cap_std::net::TcpStream),
- #[cfg(unix)]
- UnixStream(cap_std::os::unix::net::UnixStream),
- #[cfg(unix)]
- UnixListener(cap_std::os::unix::net::UnixListener),
-}
-
-impl From<cap_std::net::TcpListener> for Socket {
- fn from(listener: cap_std::net::TcpListener) -> Self {
- Self::TcpListener(listener)
- }
-}
-
-impl From<cap_std::net::TcpStream> for Socket {
- fn from(stream: cap_std::net::TcpStream) -> Self {
- Self::TcpStream(stream)
- }
-}
-
-#[cfg(unix)]
-impl From<cap_std::os::unix::net::UnixListener> for Socket {
- fn from(listener: cap_std::os::unix::net::UnixListener) -> Self {
- Self::UnixListener(listener)
- }
-}
-
-#[cfg(unix)]
-impl From<cap_std::os::unix::net::UnixStream> for Socket {
- fn from(stream: cap_std::os::unix::net::UnixStream) -> Self {
- Self::UnixStream(stream)
- }
-}
-
-#[cfg(unix)]
-impl From<Socket> for Box<dyn WasiFile> {
- fn from(listener: Socket) -> Self {
- match listener {
- Socket::TcpListener(l) => Box::new(crate::sync::net::TcpListener::from_cap_std(l)),
- Socket::UnixListener(l) => Box::new(crate::sync::net::UnixListener::from_cap_std(l)),
- Socket::TcpStream(l) => Box::new(crate::sync::net::TcpStream::from_cap_std(l)),
- Socket::UnixStream(l) => Box::new(crate::sync::net::UnixStream::from_cap_std(l)),
- }
- }
-}
-
-#[cfg(windows)]
-impl From<Socket> for Box<dyn WasiFile> {
- fn from(listener: Socket) -> Self {
- match listener {
- Socket::TcpListener(l) => Box::new(crate::sync::net::TcpListener::from_cap_std(l)),
- Socket::TcpStream(l) => Box::new(crate::sync::net::TcpStream::from_cap_std(l)),
- }
- }
-}
-
-macro_rules! wasi_listen_write_impl {
- ($ty:ty, $stream:ty) => {
- #[async_trait::async_trait]
- impl WasiFile for $ty {
- fn as_any(&self) -> &dyn Any {
- self
- }
- #[cfg(unix)]
- fn pollable(&self) -> Option<rustix::fd::BorrowedFd<'_>> {
- Some(self.0.as_fd())
- }
- #[cfg(windows)]
- fn pollable(&self) -> Option<io_extras::os::windows::RawHandleOrSocket> {
- Some(self.0.as_raw_handle_or_socket())
- }
- async fn sock_accept(&self, fdflags: FdFlags) -> Result<Box<dyn WasiFile>, Error> {
- let (stream, _) = self.0.accept()?;
- let mut stream = <$stream>::from_cap_std(stream);
- stream.set_fdflags(fdflags).await?;
- Ok(Box::new(stream))
- }
- async fn get_filetype(&self) -> Result<FileType, Error> {
- Ok(FileType::SocketStream)
- }
- #[cfg(unix)]
- async fn get_fdflags(&self) -> Result<FdFlags, Error> {
- let fdflags = get_fd_flags(&self.0)?;
- Ok(fdflags)
- }
- async fn set_fdflags(&mut self, fdflags: FdFlags) -> Result<(), Error> {
- if fdflags == crate::file::FdFlags::NONBLOCK {
- self.0.set_nonblocking(true)?;
- } else if fdflags.is_empty() {
- self.0.set_nonblocking(false)?;
- } else {
- return Err(
- Error::invalid_argument().context("cannot set anything else than NONBLOCK")
- );
- }
- Ok(())
- }
- fn num_ready_bytes(&self) -> Result<u64, Error> {
- Ok(1)
- }
- }
-
- #[cfg(windows)]
- impl AsSocket for $ty {
- #[inline]
- fn as_socket(&self) -> BorrowedSocket<'_> {
- self.0.as_socket()
- }
- }
-
- #[cfg(windows)]
- impl AsRawHandleOrSocket for $ty {
- #[inline]
- fn as_raw_handle_or_socket(&self) -> RawHandleOrSocket {
- self.0.as_raw_handle_or_socket()
- }
- }
-
- #[cfg(unix)]
- impl AsFd for $ty {
- fn as_fd(&self) -> BorrowedFd<'_> {
- self.0.as_fd()
- }
- }
- };
-}
-
-pub struct TcpListener(cap_std::net::TcpListener);
-
-impl TcpListener {
- pub fn from_cap_std(cap_std: cap_std::net::TcpListener) -> Self {
- TcpListener(cap_std)
- }
-}
-wasi_listen_write_impl!(TcpListener, TcpStream);
-
-#[cfg(unix)]
-pub struct UnixListener(cap_std::os::unix::net::UnixListener);
-
-#[cfg(unix)]
-impl UnixListener {
- pub fn from_cap_std(cap_std: cap_std::os::unix::net::UnixListener) -> Self {
- UnixListener(cap_std)
- }
-}
-
-#[cfg(unix)]
-wasi_listen_write_impl!(UnixListener, UnixStream);
-
-macro_rules! wasi_stream_write_impl {
- ($ty:ty, $std_ty:ty) => {
- #[async_trait::async_trait]
- impl WasiFile for $ty {
- fn as_any(&self) -> &dyn Any {
- self
- }
- #[cfg(unix)]
- fn pollable(&self) -> Option<rustix::fd::BorrowedFd<'_>> {
- Some(self.0.as_fd())
- }
- #[cfg(windows)]
- fn pollable(&self) -> Option<io_extras::os::windows::RawHandleOrSocket> {
- Some(self.0.as_raw_handle_or_socket())
- }
- async fn get_filetype(&self) -> Result<FileType, Error> {
- Ok(FileType::SocketStream)
- }
- #[cfg(unix)]
- async fn get_fdflags(&self) -> Result<FdFlags, Error> {
- let fdflags = get_fd_flags(&self.0)?;
- Ok(fdflags)
- }
- async fn set_fdflags(&mut self, fdflags: FdFlags) -> Result<(), Error> {
- if fdflags == crate::file::FdFlags::NONBLOCK {
- self.0.set_nonblocking(true)?;
- } else if fdflags.is_empty() {
- self.0.set_nonblocking(false)?;
- } else {
- return Err(
- Error::invalid_argument().context("cannot set anything else than NONBLOCK")
- );
- }
- Ok(())
- }
- async fn read_vectored<'a>(
- &self,
- bufs: &mut [io::IoSliceMut<'a>],
- ) -> Result<u64, Error> {
- use std::io::Read;
- let n = Read::read_vectored(&mut &*self.as_socketlike_view::<$std_ty>(), bufs)?;
- Ok(n.try_into()?)
- }
- async fn write_vectored<'a>(&self, bufs: &[io::IoSlice<'a>]) -> Result<u64, Error> {
- use std::io::Write;
- let n = Write::write_vectored(&mut &*self.as_socketlike_view::<$std_ty>(), bufs)?;
- Ok(n.try_into()?)
- }
- async fn peek(&self, buf: &mut [u8]) -> Result<u64, Error> {
- let n = self.0.peek(buf)?;
- Ok(n.try_into()?)
- }
- fn num_ready_bytes(&self) -> Result<u64, Error> {
- let val = self.as_socketlike_view::<$std_ty>().num_ready_bytes()?;
- Ok(val)
- }
- async fn readable(&self) -> Result<(), Error> {
- let (readable, _writeable) = is_read_write(&self.0)?;
- if readable { Ok(()) } else { Err(Error::io()) }
- }
- async fn writable(&self) -> Result<(), Error> {
- let (_readable, writeable) = is_read_write(&self.0)?;
- if writeable { Ok(()) } else { Err(Error::io()) }
- }
-
- async fn sock_recv<'a>(
- &self,
- ri_data: &mut [std::io::IoSliceMut<'a>],
- ri_flags: RiFlags,
- ) -> Result<(u64, RoFlags), Error> {
- if (ri_flags & !(RiFlags::RECV_PEEK | RiFlags::RECV_WAITALL)) != RiFlags::empty() {
- return Err(Error::not_supported());
- }
-
- if ri_flags.contains(RiFlags::RECV_PEEK) {
- if let Some(first) = ri_data.iter_mut().next() {
- let n = self.0.peek(first)?;
- return Ok((n as u64, RoFlags::empty()));
- } else {
- return Ok((0, RoFlags::empty()));
- }
- }
-
- if ri_flags.contains(RiFlags::RECV_WAITALL) {
- let n: usize = ri_data.iter().map(|buf| buf.len()).sum();
- self.0.read_exact_vectored(ri_data)?;
- return Ok((n as u64, RoFlags::empty()));
- }
-
- let n = self.0.read_vectored(ri_data)?;
- Ok((n as u64, RoFlags::empty()))
- }
-
- async fn sock_send<'a>(
- &self,
- si_data: &[std::io::IoSlice<'a>],
- si_flags: SiFlags,
- ) -> Result<u64, Error> {
- if si_flags != SiFlags::empty() {
- return Err(Error::not_supported());
- }
-
- let n = self.0.write_vectored(si_data)?;
- Ok(n as u64)
- }
-
- async fn sock_shutdown(&self, how: SdFlags) -> Result<(), Error> {
- let how = if how == SdFlags::RD | SdFlags::WR {
- cap_std::net::Shutdown::Both
- } else if how == SdFlags::RD {
- cap_std::net::Shutdown::Read
- } else if how == SdFlags::WR {
- cap_std::net::Shutdown::Write
- } else {
- return Err(Error::invalid_argument());
- };
- self.0.shutdown(how)?;
- Ok(())
- }
- }
- #[cfg(unix)]
- impl AsFd for $ty {
- fn as_fd(&self) -> BorrowedFd<'_> {
- self.0.as_fd()
- }
- }
-
- #[cfg(windows)]
- impl AsSocket for $ty {
- /// Borrows the socket.
- fn as_socket(&self) -> BorrowedSocket<'_> {
- self.0.as_socket()
- }
- }
-
- #[cfg(windows)]
- impl AsRawHandleOrSocket for TcpStream {
- #[inline]
- fn as_raw_handle_or_socket(&self) -> RawHandleOrSocket {
- self.0.as_raw_handle_or_socket()
- }
- }
- };
-}
-
-pub struct TcpStream(cap_std::net::TcpStream);
-
-impl TcpStream {
- pub fn from_cap_std(socket: cap_std::net::TcpStream) -> Self {
- TcpStream(socket)
- }
-}
-
-wasi_stream_write_impl!(TcpStream, std::net::TcpStream);
-
-#[cfg(unix)]
-pub struct UnixStream(cap_std::os::unix::net::UnixStream);
-
-#[cfg(unix)]
-impl UnixStream {
- pub fn from_cap_std(socket: cap_std::os::unix::net::UnixStream) -> Self {
- UnixStream(socket)
- }
-}
-
-#[cfg(unix)]
-wasi_stream_write_impl!(UnixStream, std::os::unix::net::UnixStream);
-
-pub fn filetype_from(ft: &cap_std::fs::FileType) -> FileType {
- use cap_fs_ext::FileTypeExt;
- if ft.is_block_device() {
- FileType::SocketDgram
- } else {
- FileType::SocketStream
- }
-}
-
-/// Return the file-descriptor flags for a given file-like object.
-///
-/// This returns the flags needed to implement [`WasiFile::get_fdflags`].
-pub fn get_fd_flags<Socketlike: AsSocketlike>(f: Socketlike) -> io::Result<crate::file::FdFlags> {
- // On Unix-family platforms, we can use the same system call that we'd use
- // for files on sockets here.
- #[cfg(not(windows))]
- {
- let mut out = crate::file::FdFlags::empty();
- if f.get_fd_flags()?
- .contains(system_interface::fs::FdFlags::NONBLOCK)
- {
- out |= crate::file::FdFlags::NONBLOCK;
- }
- Ok(out)
- }
-
- // On Windows, sockets are different, and there is no direct way to
- // query for the non-blocking flag. We can get a sufficient approximation
- // by testing whether a zero-length `recv` appears to block.
- #[cfg(windows)]
- let buf: &mut [u8] = &mut [];
- #[cfg(windows)]
- match rustix::net::recv(f, buf, rustix::net::RecvFlags::empty()) {
- Ok(_) => Ok(crate::file::FdFlags::empty()),
- Err(rustix::io::Errno::WOULDBLOCK) => Ok(crate::file::FdFlags::NONBLOCK),
- Err(e) => Err(e.into()),
- }
-}
-
-/// Return the file-descriptor flags for a given file-like object.
-///
-/// This returns the flags needed to implement [`WasiFile::get_fdflags`].
-pub fn is_read_write<Socketlike: AsSocketlike>(f: Socketlike) -> io::Result<(bool, bool)> {
- // On Unix-family platforms, we have an `IsReadWrite` impl.
- #[cfg(not(windows))]
- {
- f.is_read_write()
- }
-
- // On Windows, we only have a `TcpStream` impl, so make a view first.
- #[cfg(windows)]
- {
- f.as_socketlike_view::<std::net::TcpStream>()
- .is_read_write()
- }
-}
diff --git a/crates/wasi-common/src/sync/sched.rs b/crates/wasi-common/src/sync/sched.rs
deleted file mode 100644
index 1b2fa9faa1..0000000000
--- a/crates/wasi-common/src/sync/sched.rs
+++ /dev/null
@@ -1,40 +0,0 @@
-#[cfg(unix)]
-pub mod unix;
-#[cfg(unix)]
-pub use unix::poll_oneoff;
-
-#[cfg(windows)]
-pub mod windows;
-#[cfg(windows)]
-pub use windows::poll_oneoff;
-
-use crate::{
- Error,
- sched::{Poll, WasiSched},
-};
-use std::thread;
-use std::time::Duration;
-
-pub struct SyncSched {}
-impl SyncSched {
- pub fn new() -> Self {
- Self {}
- }
-}
-#[async_trait::async_trait]
-impl WasiSched for SyncSched {
- async fn poll_oneoff<'a>(&self, poll: &mut Poll<'a>) -> Result<(), Error> {
- poll_oneoff(poll).await
- }
- async fn sched_yield(&self) -> Result<(), Error> {
- thread::yield_now();
- Ok(())
- }
- async fn sleep(&self, duration: Duration) -> Result<(), Error> {
- std::thread::sleep(duration);
- Ok(())
- }
-}
-pub fn sched_ctx() -> Box<dyn WasiSched> {
- Box::new(SyncSched::new())
-}
diff --git a/crates/wasi-common/src/sync/sched/unix.rs b/crates/wasi-common/src/sync/sched/unix.rs
deleted file mode 100644
index 548eea5de8..0000000000
--- a/crates/wasi-common/src/sync/sched/unix.rs
+++ /dev/null
@@ -1,83 +0,0 @@
-use crate::sched::subscription::{RwEventFlags, Subscription};
-use crate::{Error, ErrorExt, sched::Poll};
-use cap_std::time::Duration;
-use rustix::event::{PollFd, PollFlags};
-
-pub async fn poll_oneoff<'a>(poll: &mut Poll<'a>) -> Result<(), Error> {
- if poll.is_empty() {
- return Ok(());
- }
- let mut pollfds = Vec::new();
- for s in poll.rw_subscriptions() {
- match s {
- Subscription::Read(f) => {
- let fd = f
- .file
- .pollable()
- .ok_or(Error::invalid_argument().context("file is not pollable"))?;
- pollfds.push(PollFd::from_borrowed_fd(fd, PollFlags::IN));
- }
-
- Subscription::Write(f) => {
- let fd = f
- .file
- .pollable()
- .ok_or(Error::invalid_argument().context("file is not pollable"))?;
- pollfds.push(PollFd::from_borrowed_fd(fd, PollFlags::OUT));
- }
- Subscription::MonotonicClock { .. } => unreachable!(),
- }
- }
-
- let ready = loop {
- let poll_timeout = if let Some(t) = poll.earliest_clock_deadline() {
- let duration = t.duration_until().unwrap_or(Duration::from_secs(0));
- Some(
- duration
- .try_into()
- .map_err(|_| Error::overflow().context("poll timeout"))?,
- )
- } else {
- None
- };
- tracing::debug!(
- poll_timeout = tracing::field::debug(poll_timeout),
- poll_fds = tracing::field::debug(&pollfds),
- "poll"
- );
- match rustix::event::poll(&mut pollfds, poll_timeout.as_ref()) {
- Ok(ready) => break ready,
- Err(rustix::io::Errno::INTR) => continue,
- Err(err) => return Err(std::io::Error::from(err).into()),
- }
- };
- if ready > 0 {
- for (rwsub, pollfd) in poll.rw_subscriptions().zip(pollfds) {
- let revents = pollfd.revents();
- let (nbytes, rwsub) = match rwsub {
- Subscription::Read(sub) => {
- let ready = sub.file.num_ready_bytes()?;
- (std::cmp::max(ready, 1), sub)
- }
- Subscription::Write(sub) => (0, sub),
- _ => unreachable!(),
- };
- if revents.contains(PollFlags::NVAL) {
- rwsub.error(Error::badf());
- } else if revents.contains(PollFlags::ERR) {
- rwsub.error(Error::io());
- } else if revents.contains(PollFlags::HUP) {
- rwsub.complete(nbytes, RwEventFlags::HANGUP);
- } else {
- rwsub.complete(nbytes, RwEventFlags::empty());
- };
- }
- } else {
- poll.earliest_clock_deadline()
- .expect("timed out")
- .result()
- .expect("timer deadline is past")
- .unwrap()
- }
- Ok(())
-}
diff --git a/crates/wasi-common/src/sync/sched/windows.rs b/crates/wasi-common/src/sync/sched/windows.rs
deleted file mode 100644
index a6f4f1fb4f..0000000000
--- a/crates/wasi-common/src/sync/sched/windows.rs
+++ /dev/null
@@ -1,220 +0,0 @@
-// The windows scheduler is unmaintained and due for a rewrite.
-//
-// Rather than use a polling mechanism for file read/write readiness,
-// it checks readiness just once, before sleeping for any timer subscriptions.
-// Checking stdin readiness uses a worker thread which, once started, lives for the
-// lifetime of the process.
-//
-// We suspect there are bugs in this scheduler, however, we have not
-// taken the time to improve it. See bug #2880.
-
-use crate::sched::subscription::{RwEventFlags, Subscription};
-use crate::{EnvError, Error, ErrorExt, file::WasiFile, sched::Poll};
-use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender, TryRecvError};
-use std::sync::{LazyLock, Mutex};
-use std::thread;
-use std::time::Duration;
-
-pub async fn poll_oneoff<'a>(poll: &mut Poll<'a>) -> Result<(), Error> {
- poll_oneoff_(poll, wasi_file_is_stdin).await
-}
-
-pub async fn poll_oneoff_<'a>(
- poll: &mut Poll<'a>,
- file_is_stdin: impl Fn(&dyn WasiFile) -> bool,
-) -> Result<(), Error> {
- if poll.is_empty() {
- return Ok(());
- }
-
- let mut ready = false;
- let waitmode = if let Some(t) = poll.earliest_clock_deadline() {
- if let Some(duration) = t.duration_until() {
- WaitMode::Timeout(duration)
- } else {
- WaitMode::Immediate
- }
- } else {
- if ready {
- WaitMode::Immediate
- } else {
- WaitMode::Infinite
- }
- };
-
- let mut stdin_read_subs = Vec::new();
- let mut immediate_reads = Vec::new();
- let mut immediate_writes = Vec::new();
- for s in poll.rw_subscriptions() {
- match s {
- Subscription::Read(r) => {
- if file_is_stdin(r.file) {
- stdin_read_subs.push(r);
- } else if r.file.pollable().is_some() {
- immediate_reads.push(r);
- } else {
- return Err(Error::invalid_argument().context("file is not pollable"));
- }
- }
- Subscription::Write(w) => {
- if w.file.pollable().is_some() {
- immediate_writes.push(w);
- } else {
- return Err(Error::invalid_argument().context("file is not pollable"));
- }
- }
- Subscription::MonotonicClock { .. } => unreachable!(),
- }
- }
-
- if !stdin_read_subs.is_empty() {
- let state = STDIN_POLL
- .lock()
- .map_err(|_| Error::trap(EnvError::msg("failed to take lock of STDIN_POLL")))?
- .poll(waitmode)?;
- for readsub in stdin_read_subs.into_iter() {
- match state {
- PollState::Ready => {
- readsub.complete(1, RwEventFlags::empty());
- ready = true;
- }
- PollState::NotReady | PollState::TimedOut => {}
- PollState::Error(ref e) => {
- // Unfortunately, we need to deliver the Error to each of the
- // subscriptions, but there is no Clone on std::io::Error. So, we convert it to the
- // kind, and then back to std::io::Error, and finally to EnvError.
- // When its time to turn this into an errno elsewhere, the error kind will
- // be inspected.
- let ekind = e.kind();
- let ioerror = std::io::Error::from(ekind);
- readsub.error(ioerror.into());
- ready = true;
- }
- }
- }
- }
- for r in immediate_reads {
- match r.file.num_ready_bytes() {
- Ok(ready_bytes) => {
- r.complete(ready_bytes, RwEventFlags::empty());
- ready = true;
- }
- Err(e) => {
- r.error(e);
- ready = true;
- }
- }
- }
- for w in immediate_writes {
- // Everything is always ready for writing, apparently?
- w.complete(0, RwEventFlags::empty());
- ready = true;
- }
-
- if !ready {
- if let WaitMode::Timeout(duration) = waitmode {
- thread::sleep(duration);
- }
- }
-
- Ok(())
-}
-
-pub fn wasi_file_is_stdin(f: &dyn WasiFile) -> bool {
- f.as_any().is::<crate::sync::stdio::Stdin>()
-}
-
-enum PollState {
- Ready,
- NotReady, // Not ready, but did not wait
- TimedOut, // Not ready, waited until timeout
- Error(std::io::Error),
-}
-
-#[derive(Copy, Clone)]
-enum WaitMode {
- Timeout(Duration),
- Infinite,
- Immediate,
-}
-
-struct StdinPoll {
- request_tx: Sender<()>,
- notify_rx: Receiver<PollState>,
-}
-
-static STDIN_POLL: LazyLock<Mutex<StdinPoll>> = LazyLock::new(StdinPoll::new);
-
-impl StdinPoll {
- pub fn new() -> Mutex<Self> {
- let (request_tx, request_rx) = mpsc::channel();
- let (notify_tx, notify_rx) = mpsc::channel();
- thread::spawn(move || Self::event_loop(request_rx, notify_tx));
- Mutex::new(StdinPoll {
- request_tx,
- notify_rx,
- })
- }
-
- // This function should not be used directly.
- // Correctness of this function crucially depends on the fact that
- // mpsc::Receiver is !Sync.
- fn poll(&self, wait_mode: WaitMode) -> Result<PollState, Error> {
- match self.notify_rx.try_recv() {
- // Clean up possibly unread result from previous poll.
- Ok(_) | Err(TryRecvError::Empty) => {}
- Err(TryRecvError::Disconnected) => {
- return Err(Error::trap(EnvError::msg(
- "StdinPoll notify_rx channel closed",
- )));
- }
- }
-
- // Notify the worker thread to poll stdin
- self.request_tx
- .send(())
- .map_err(|_| Error::trap(EnvError::msg("request_tx channel closed")))?;
-
- // Wait for the worker thread to send a readiness notification
- match wait_mode {
- WaitMode::Timeout(timeout) => match self.notify_rx.recv_timeout(timeout) {
- Ok(r) => Ok(r),
- Err(RecvTimeoutError::Timeout) => Ok(PollState::TimedOut),
- Err(RecvTimeoutError::Disconnected) => Err(Error::trap(EnvError::msg(
- "StdinPoll notify_rx channel closed",
- ))),
- },
- WaitMode::Infinite => self
- .notify_rx
- .recv()
- .map_err(|_| Error::trap(EnvError::msg("StdinPoll notify_rx channel closed"))),
- WaitMode::Immediate => match self.notify_rx.try_recv() {
- Ok(r) => Ok(r),
- Err(TryRecvError::Empty) => Ok(PollState::NotReady),
- Err(TryRecvError::Disconnected) => Err(Error::trap(EnvError::msg(
- "StdinPoll notify_rx channel closed",
- ))),
- },
- }
- }
-
- fn event_loop(request_rx: Receiver<()>, notify_tx: Sender<PollState>) -> ! {
- use std::io::BufRead;
- loop {
- // Wait on a request:
- request_rx.recv().expect("request_rx channel");
- // Wait for data to appear in stdin. If fill_buf returns any slice, it means
- // that either:
- // (a) there is some data in stdin, if non-empty,
- // (b) EOF was received, if its empty
- // Linux returns `POLLIN` in both cases, so we imitate this behavior.
- let resp = match std::io::stdin().lock().fill_buf() {
- Ok(_) => PollState::Ready,
- Err(e) => PollState::Error(e),
- };
- // Notify about data in stdin. If the read on this channel has timed out, the
- // next poller will have to clean the channel.
- notify_tx.send(resp).expect("notify_tx channel");
- }
- }
-}
diff --git a/crates/wasi-common/src/sync/stdio.rs b/crates/wasi-common/src/sync/stdio.rs
deleted file mode 100644
index 2975a087c9..0000000000
--- a/crates/wasi-common/src/sync/stdio.rs
+++ /dev/null
@@ -1,196 +0,0 @@
-use crate::sync::file::convert_systimespec;
-use fs_set_times::SetTimes;
-use std::any::Any;
-use std::io::{self, IsTerminal, Read, Write};
-use system_interface::io::ReadReady;
-
-use crate::{
- Error, ErrorExt,
- file::{FdFlags, FileType, WasiFile},
-};
-#[cfg(windows)]
-use io_extras::os::windows::{AsRawHandleOrSocket, RawHandleOrSocket};
-#[cfg(unix)]
-use io_lifetimes::{AsFd, BorrowedFd};
-#[cfg(windows)]
-use io_lifetimes::{AsHandle, BorrowedHandle};
-
-pub struct Stdin(std::io::Stdin);
-
-pub fn stdin() -> Stdin {
- Stdin(std::io::stdin())
-}
-
-#[async_trait::async_trait]
-impl WasiFile for Stdin {
- fn as_any(&self) -> &dyn Any {
- self
- }
-
- #[cfg(unix)]
- fn pollable(&self) -> Option<rustix::fd::BorrowedFd<'_>> {
- Some(self.0.as_fd())
- }
-
- #[cfg(windows)]
- fn pollable(&self) -> Option<io_extras::os::windows::RawHandleOrSocket> {
- Some(self.0.as_raw_handle_or_socket())
- }
-
- async fn get_filetype(&self) -> Result<FileType, Error> {
- if self.isatty() {
- Ok(FileType::CharacterDevice)
- } else {
- Ok(FileType::Unknown)
- }
- }
- async fn read_vectored<'a>(&self, bufs: &mut [io::IoSliceMut<'a>]) -> Result<u64, Error> {
- let n = self.0.lock().read_vectored(bufs)?;
- Ok(n.try_into().map_err(|_| Error::range())?)
- }
- async fn read_vectored_at<'a>(
- &self,
- _bufs: &mut [io::IoSliceMut<'a>],
- _offset: u64,
- ) -> Result<u64, Error> {
- Err(Error::seek_pipe())
- }
- async fn seek(&self, _pos: std::io::SeekFrom) -> Result<u64, Error> {
- Err(Error::seek_pipe())
- }
- async fn peek(&self, _buf: &mut [u8]) -> Result<u64, Error> {
- Err(Error::seek_pipe())
- }
- async fn set_times(
- &self,
- atime: Option<crate::SystemTimeSpec>,
- mtime: Option<crate::SystemTimeSpec>,
- ) -> Result<(), Error> {
- self.0
- .set_times(convert_systimespec(atime), convert_systimespec(mtime))?;
- Ok(())
- }
- fn num_ready_bytes(&self) -> Result<u64, Error> {
- Ok(self.0.num_ready_bytes()?)
- }
- fn isatty(&self) -> bool {
- #[cfg(unix)]
- return self.0.as_fd().is_terminal();
- #[cfg(windows)]
- return self.0.as_handle().is_terminal();
- }
-}
-#[cfg(windows)]
-impl AsHandle for Stdin {
- fn as_handle(&self) -> BorrowedHandle<'_> {
- self.0.as_handle()
- }
-}
-#[cfg(windows)]
-impl AsRawHandleOrSocket for Stdin {
- #[inline]
- fn as_raw_handle_or_socket(&self) -> RawHandleOrSocket {
- self.0.as_raw_handle_or_socket()
- }
-}
-#[cfg(unix)]
-impl AsFd for Stdin {
- fn as_fd(&self) -> BorrowedFd<'_> {
- self.0.as_fd()
- }
-}
-
-macro_rules! wasi_file_write_impl {
- ($ty:ty, $ident:ident) => {
- #[async_trait::async_trait]
- impl WasiFile for $ty {
- fn as_any(&self) -> &dyn Any {
- self
- }
- #[cfg(unix)]
- fn pollable(&self) -> Option<rustix::fd::BorrowedFd<'_>> {
- Some(self.0.as_fd())
- }
- #[cfg(windows)]
- fn pollable(&self) -> Option<io_extras::os::windows::RawHandleOrSocket> {
- Some(self.0.as_raw_handle_or_socket())
- }
- async fn get_filetype(&self) -> Result<FileType, Error> {
- if self.isatty() {
- Ok(FileType::CharacterDevice)
- } else {
- Ok(FileType::Unknown)
- }
- }
- async fn get_fdflags(&self) -> Result<FdFlags, Error> {
- Ok(FdFlags::APPEND)
- }
- async fn write_vectored<'a>(&self, bufs: &[io::IoSlice<'a>]) -> Result<u64, Error> {
- let mut io = self.0.lock();
- let n = io.write_vectored(bufs)?;
- // On a successful write additionally flush out the bytes to
- // handle stdio buffering done by libstd since WASI interfaces
- // here aren't buffered.
- io.flush()?;
- Ok(n.try_into().map_err(|_| {
- Error::range().context("converting write_vectored total length")
- })?)
- }
- async fn write_vectored_at<'a>(
- &self,
- _bufs: &[io::IoSlice<'a>],
- _offset: u64,
- ) -> Result<u64, Error> {
- Err(Error::seek_pipe())
- }
- async fn seek(&self, _pos: std::io::SeekFrom) -> Result<u64, Error> {
- Err(Error::seek_pipe())
- }
- async fn set_times(
- &self,
- atime: Option<crate::SystemTimeSpec>,
- mtime: Option<crate::SystemTimeSpec>,
- ) -> Result<(), Error> {
- self.0
- .set_times(convert_systimespec(atime), convert_systimespec(mtime))?;
- Ok(())
- }
- fn isatty(&self) -> bool {
- self.0.is_terminal()
- }
- }
- #[cfg(windows)]
- impl AsHandle for $ty {
- fn as_handle(&self) -> BorrowedHandle<'_> {
- self.0.as_handle()
- }
- }
- #[cfg(unix)]
- impl AsFd for $ty {
- fn as_fd(&self) -> BorrowedFd<'_> {
- self.0.as_fd()
- }
- }
- #[cfg(windows)]
- impl AsRawHandleOrSocket for $ty {
- #[inline]
- fn as_raw_handle_or_socket(&self) -> RawHandleOrSocket {
- self.0.as_raw_handle_or_socket()
- }
- }
- };
-}
-
-pub struct Stdout(std::io::Stdout);
-
-pub fn stdout() -> Stdout {
- Stdout(std::io::stdout())
-}
-wasi_file_write_impl!(Stdout, Stdout);
-
-pub struct Stderr(std::io::Stderr);
-
-pub fn stderr() -> Stderr {
- Stderr(std::io::stderr())
-}
-wasi_file_write_impl!(Stderr, Stderr);
diff --git a/crates/wasi-common/src/table.rs b/crates/wasi-common/src/table.rs
deleted file mode 100644
index cd817d38c3..0000000000
--- a/crates/wasi-common/src/table.rs
+++ /dev/null
@@ -1,114 +0,0 @@
-use crate::{EnvError, Error, ErrorExt};
-use std::any::Any;
-use std::collections::HashMap;
-use std::sync::{Arc, RwLock};
-
-/// The `Table` type is designed to map u32 handles to resources. The table is now part of the
-/// public interface to a `WasiCtx` - it is reference counted so that it can be shared beyond a
-/// `WasiCtx` with other WASI proposals (e.g. `wasi-crypto` and `wasi-nn`) to manage their
-/// resources. Elements in the `Table` are `Any` typed.
-///
-/// The `Table` type is intended to model how the Interface Types concept of Resources is shaping
-/// up. Right now it is just an approximation.
-pub struct Table(RwLock<Inner>);
-
-struct Inner {
- map: HashMap<u32, Arc<dyn Any + Send + Sync>>,
- next_key: u32,
-}
-
-impl Table {
- /// Create an empty table. New insertions will begin at 3, above stdio.
- pub fn new() -> Self {
- Table(RwLock::new(Inner {
- map: HashMap::new(),
- next_key: 3, // 0, 1 and 2 are reserved for stdio
- }))
- }
-
- /// Insert a resource at a certain index.
- pub fn insert_at<T: Any + Send + Sync>(&self, key: u32, a: Arc<T>) {
- self.0.write().unwrap().map.insert(key, a);
- }
-
- /// Insert a resource at the next available index.
- pub fn push<T: Any + Send + Sync>(&self, a: Arc<T>) -> Result<u32, Error> {
- let mut inner = self.0.write().unwrap();
- // NOTE: The performance of this new key calculation could be very bad once keys wrap
- // around.
- if inner.map.len() == u32::MAX as usize {
- return Err(Error::trap(EnvError::msg("table has no free keys")));
- }
- loop {
- let key = inner.next_key;
- inner.next_key += 1;
- if inner.map.contains_key(&key) {
- continue;
- }
- inner.map.insert(key, a);
- return Ok(key);
- }
- }
-
- /// Check if the table has a resource at the given index.
- pub fn contains_key(&self, key: u32) -> bool {
- self.0.read().unwrap().map.contains_key(&key)
- }
-
- /// Check if the resource at a given index can be downcast to a given type.
- /// Note: this will always fail if the resource is already borrowed.
- pub fn is<T: Any + Sized>(&self, key: u32) -> bool {
- if let Some(r) = self.0.read().unwrap().map.get(&key) {
- r.is::<T>()
- } else {
- false
- }
- }
-
- /// Get an Arc reference to a resource of a given type at a given index. Multiple
- /// immutable references can be borrowed at any given time.
- pub fn get<T: Any + Send + Sync + Sized>(&self, key: u32) -> Result<Arc<T>, Error> {
- if let Some(r) = self.0.read().unwrap().map.get(&key).cloned() {
- r.downcast::<T>()
- .map_err(|_| Error::badf().context("element is a different type"))
- } else {
- Err(Error::badf().context("key not in table"))
- }
- }
-
- /// Get a mutable reference to a resource of a given type at a given index.
- /// Only one such reference can be borrowed at any given time.
- pub fn get_mut<T: Any>(&mut self, key: u32) -> Result<&mut T, Error> {
- let entry = match self.0.get_mut().unwrap().map.get_mut(&key) {
- Some(entry) => entry,
- None => return Err(Error::badf().context("key not in table")),
- };
- let entry = match Arc::get_mut(entry) {
- Some(entry) => entry,
- None => return Err(Error::badf().context("cannot mutably borrow shared file")),
- };
- entry
- .downcast_mut::<T>()
- .ok_or_else(|| Error::badf().context("element is a different type"))
- }
-
- /// Remove a resource at a given index from the table. Returns the resource
- /// if it was present.
- pub fn delete<T: Any + Send + Sync>(&self, key: u32) -> Option<Arc<T>> {
- self.0
- .write()
- .unwrap()
- .map
- .remove(&key)
- .map(|r| r.downcast::<T>().unwrap())
- }
-
- /// Remove a resource at a given index from the table. Returns the resource
- /// if it was present.
- pub fn renumber(&self, from: u32, to: u32) -> Result<(), Error> {
- let map = &mut self.0.write().unwrap().map;
- let from_entry = map.remove(&from).ok_or(Error::badf())?;
- map.insert(to, from_entry);
- Ok(())
- }
-}
diff --git a/crates/wasi-common/src/tokio/dir.rs b/crates/wasi-common/src/tokio/dir.rs
deleted file mode 100644
index 74b18e335e..0000000000
--- a/crates/wasi-common/src/tokio/dir.rs
+++ /dev/null
@@ -1,220 +0,0 @@
-use crate::tokio::{block_on_dummy_executor, file::File};
-use crate::{
- Error, ErrorExt,
- dir::{ReaddirCursor, ReaddirEntity, WasiDir},
- file::{FdFlags, Filestat, OFlags},
-};
-use std::any::Any;
-use std::path::PathBuf;
-
-pub struct Dir(crate::sync::dir::Dir);
-
-impl Dir {
- pub fn from_cap_std(dir: cap_std::fs::Dir) -> Self {
- Dir(crate::sync::dir::Dir::from_cap_std(dir))
- }
-}
-
-#[async_trait::async_trait]
-impl WasiDir for Dir {
- fn as_any(&self) -> &dyn Any {
- self
- }
- async fn open_file(
- &self,
- symlink_follow: bool,
- path: &str,
- oflags: OFlags,
- read: bool,
- write: bool,
- fdflags: FdFlags,
- ) -> Result<crate::dir::OpenResult, Error> {
- let f = block_on_dummy_executor(move || async move {
- self.0
- .open_file_(symlink_follow, path, oflags, read, write, fdflags)
- })?;
- match f {
- crate::sync::dir::OpenResult::File(f) => {
- Ok(crate::dir::OpenResult::File(Box::new(File::from_inner(f))))
- }
- crate::sync::dir::OpenResult::Dir(d) => {
- Ok(crate::dir::OpenResult::Dir(Box::new(Dir(d))))
- }
- }
- }
-
- async fn create_dir(&self, path: &str) -> Result<(), Error> {
- block_on_dummy_executor(|| self.0.create_dir(path))
- }
- async fn readdir(
- &self,
- cursor: ReaddirCursor,
- ) -> Result<Box<dyn Iterator<Item = Result<ReaddirEntity, Error>> + Send>, Error> {
- struct I(Box<dyn Iterator<Item = Result<ReaddirEntity, Error>> + Send>);
- impl Iterator for I {
- type Item = Result<ReaddirEntity, Error>;
- fn next(&mut self) -> Option<Self::Item> {
- tokio::task::block_in_place(move || self.0.next())
- }
- }
-
- let inner = block_on_dummy_executor(move || self.0.readdir(cursor))?;
- Ok(Box::new(I(inner)))
- }
-
- async fn symlink(&self, src_path: &str, dest_path: &str) -> Result<(), Error> {
- block_on_dummy_executor(move || self.0.symlink(src_path, dest_path))
- }
- async fn remove_dir(&self, path: &str) -> Result<(), Error> {
- block_on_dummy_executor(move || self.0.remove_dir(path))
- }
-
- async fn unlink_file(&self, path: &str) -> Result<(), Error> {
- block_on_dummy_executor(move || self.0.unlink_file(path))
- }
- async fn read_link(&self, path: &str) -> Result<PathBuf, Error> {
- block_on_dummy_executor(move || self.0.read_link(path))
- }
- async fn get_filestat(&self) -> Result<Filestat, Error> {
- block_on_dummy_executor(|| self.0.get_filestat())
- }
- async fn get_path_filestat(
- &self,
- path: &str,
- follow_symlinks: bool,
- ) -> Result<Filestat, Error> {
- block_on_dummy_executor(move || self.0.get_path_filestat(path, follow_symlinks))
- }
- async fn rename(
- &self,
- src_path: &str,
- dest_dir: &dyn WasiDir,
- dest_path: &str,
- ) -> Result<(), Error> {
- let dest_dir = dest_dir
- .as_any()
- .downcast_ref::<Self>()
- .ok_or(Error::badf().context("failed downcast to tokio Dir"))?;
- block_on_dummy_executor(
- move || async move { self.0.rename_(src_path, &dest_dir.0, dest_path) },
- )
- }
- async fn hard_link(
- &self,
- src_path: &str,
- target_dir: &dyn WasiDir,
- target_path: &str,
- ) -> Result<(), Error> {
- let target_dir = target_dir
- .as_any()
- .downcast_ref::<Self>()
- .ok_or(Error::badf().context("failed downcast to tokio Dir"))?;
- block_on_dummy_executor(move || async move {
- self.0.hard_link_(src_path, &target_dir.0, target_path)
- })
- }
- async fn set_times(
- &self,
- path: &str,
- atime: Option<crate::SystemTimeSpec>,
- mtime: Option<crate::SystemTimeSpec>,
- follow_symlinks: bool,
- ) -> Result<(), Error> {
- block_on_dummy_executor(move || self.0.set_times(path, atime, mtime, follow_symlinks))
- }
-}
-
-#[cfg(test)]
-mod test {
- use super::Dir;
- use crate::file::{FdFlags, OFlags};
- use cap_std::ambient_authority;
-
- #[tokio::test(flavor = "multi_thread")]
- async fn scratch_dir() {
- let tempdir = tempfile::Builder::new()
- .prefix("cap-std-sync")
- .tempdir()
- .expect("create temporary dir");
- let preopen_dir = cap_std::fs::Dir::open_ambient_dir(tempdir.path(), ambient_authority())
- .expect("open ambient temporary dir");
- let preopen_dir = Dir::from_cap_std(preopen_dir);
- crate::WasiDir::open_file(
- &preopen_dir,
- false,
- ".",
- OFlags::empty(),
- false,
- false,
- FdFlags::empty(),
- )
- .await
- .expect("open the same directory via WasiDir abstraction");
- }
-
- // Readdir does not work on windows, so we won't test it there.
- #[cfg(not(windows))]
- #[tokio::test(flavor = "multi_thread")]
- async fn readdir() {
- use crate::dir::{ReaddirCursor, ReaddirEntity, WasiDir};
- use crate::file::{FdFlags, FileType, OFlags};
- use std::collections::HashMap;
-
- async fn readdir_into_map(dir: &dyn WasiDir) -> HashMap<String, ReaddirEntity> {
- let mut out = HashMap::new();
- for readdir_result in dir
- .readdir(ReaddirCursor::from(0))
- .await
- .expect("readdir succeeds")
- {
- let entity = readdir_result.expect("readdir entry is valid");
- out.insert(entity.name.clone(), entity);
- }
- out
- }
-
- let tempdir = tempfile::Builder::new()
- .prefix("cap-std-sync")
- .tempdir()
- .expect("create temporary dir");
- let preopen_dir = cap_std::fs::Dir::open_ambient_dir(tempdir.path(), ambient_authority())
- .expect("open ambient temporary dir");
- let preopen_dir = Dir::from_cap_std(preopen_dir);
-
- let entities = readdir_into_map(&preopen_dir).await;
- assert_eq!(
- entities.len(),
- 2,
- "should just be . and .. in empty dir: {entities:?}"
- );
- assert!(entities.get(".").is_some());
- assert!(entities.get("..").is_some());
-
- preopen_dir
- .open_file(
- false,
- "file1",
- OFlags::CREATE,
- true,
- false,
- FdFlags::empty(),
- )
- .await
- .expect("create file1");
-
- let entities = readdir_into_map(&preopen_dir).await;
- assert_eq!(entities.len(), 3, "should be ., .., file1 {entities:?}");
- assert_eq!(
- entities.get(".").expect(". entry").filetype,
- FileType::Directory
- );
- assert_eq!(
- entities.get("..").expect(".. entry").filetype,
- FileType::Directory
- );
- assert_eq!(
- entities.get("file1").expect("file1 entry").filetype,
- FileType::RegularFile
- );
- }
-}
diff --git a/crates/wasi-common/src/tokio/file.rs b/crates/wasi-common/src/tokio/file.rs
deleted file mode 100644
index fc13ed9b23..0000000000
--- a/crates/wasi-common/src/tokio/file.rs
+++ /dev/null
@@ -1,247 +0,0 @@
-use crate::tokio::block_on_dummy_executor;
-use crate::{
- Error,
- file::{Advice, FdFlags, FileType, Filestat, WasiFile},
-};
-#[cfg(windows)]
-use io_extras::os::windows::{AsRawHandleOrSocket, RawHandleOrSocket};
-#[cfg(not(windows))]
-use io_lifetimes::AsFd;
-use std::any::Any;
-use std::borrow::Borrow;
-use std::io;
-
-pub struct File(crate::sync::file::File);
-
-impl File {
- pub(crate) fn from_inner(file: crate::sync::file::File) -> Self {
- File(file)
- }
- pub fn from_cap_std(file: cap_std::fs::File) -> Self {
- Self::from_inner(crate::sync::file::File::from_cap_std(file))
- }
-}
-
-pub struct TcpListener(crate::sync::net::TcpListener);
-
-impl TcpListener {
- pub(crate) fn from_inner(listener: crate::sync::net::TcpListener) -> Self {
- TcpListener(listener)
- }
- pub fn from_cap_std(listener: cap_std::net::TcpListener) -> Self {
- Self::from_inner(crate::sync::net::TcpListener::from_cap_std(listener))
- }
-}
-
-pub struct TcpStream(crate::sync::net::TcpStream);
-
-impl TcpStream {
- pub(crate) fn from_inner(stream: crate::sync::net::TcpStream) -> Self {
- TcpStream(stream)
- }
- pub fn from_cap_std(stream: cap_std::net::TcpStream) -> Self {
- Self::from_inner(crate::sync::net::TcpStream::from_cap_std(stream))
- }
-}
-
-#[cfg(unix)]
-pub struct UnixListener(crate::sync::net::UnixListener);
-
-#[cfg(unix)]
-impl UnixListener {
- pub(crate) fn from_inner(listener: crate::sync::net::UnixListener) -> Self {
- UnixListener(listener)
- }
- pub fn from_cap_std(listener: cap_std::os::unix::net::UnixListener) -> Self {
- Self::from_inner(crate::sync::net::UnixListener::from_cap_std(listener))
- }
-}
-
-#[cfg(unix)]
-pub struct UnixStream(crate::sync::net::UnixStream);
-
-#[cfg(unix)]
-impl UnixStream {
- fn from_inner(stream: crate::sync::net::UnixStream) -> Self {
- UnixStream(stream)
- }
- pub fn from_cap_std(stream: cap_std::os::unix::net::UnixStream) -> Self {
- Self::from_inner(crate::sync::net::UnixStream::from_cap_std(stream))
- }
-}
-
-pub struct Stdin(crate::sync::stdio::Stdin);
-
-pub fn stdin() -> Stdin {
- Stdin(crate::sync::stdio::stdin())
-}
-
-pub struct Stdout(crate::sync::stdio::Stdout);
-
-pub fn stdout() -> Stdout {
- Stdout(crate::sync::stdio::stdout())
-}
-
-pub struct Stderr(crate::sync::stdio::Stderr);
-
-pub fn stderr() -> Stderr {
- Stderr(crate::sync::stdio::stderr())
-}
-
-macro_rules! wasi_file_impl {
- ($ty:ty) => {
- #[async_trait::async_trait]
- impl WasiFile for $ty {
- fn as_any(&self) -> &dyn Any {
- self
- }
- #[cfg(unix)]
- fn pollable(&self) -> Option<rustix::fd::BorrowedFd<'_>> {
- Some(self.0.as_fd())
- }
- #[cfg(windows)]
- fn pollable(&self) -> Option<io_extras::os::windows::RawHandleOrSocket> {
- Some(self.0.as_raw_handle_or_socket())
- }
- async fn datasync(&self) -> Result<(), Error> {
- block_on_dummy_executor(|| self.0.datasync())
- }
- async fn sync(&self) -> Result<(), Error> {
- block_on_dummy_executor(|| self.0.sync())
- }
- async fn get_filetype(&self) -> Result<FileType, Error> {
- block_on_dummy_executor(|| self.0.get_filetype())
- }
- async fn get_fdflags(&self) -> Result<FdFlags, Error> {
- block_on_dummy_executor(|| self.0.get_fdflags())
- }
- async fn set_fdflags(&mut self, fdflags: FdFlags) -> Result<(), Error> {
- block_on_dummy_executor(|| self.0.set_fdflags(fdflags))
- }
- async fn get_filestat(&self) -> Result<Filestat, Error> {
- block_on_dummy_executor(|| self.0.get_filestat())
- }
- async fn set_filestat_size(&self, size: u64) -> Result<(), Error> {
- block_on_dummy_executor(move || self.0.set_filestat_size(size))
- }
- async fn advise(&self, offset: u64, len: u64, advice: Advice) -> Result<(), Error> {
- block_on_dummy_executor(move || self.0.advise(offset, len, advice))
- }
- async fn read_vectored<'a>(
- &self,
- bufs: &mut [io::IoSliceMut<'a>],
- ) -> Result<u64, Error> {
- block_on_dummy_executor(move || self.0.read_vectored(bufs))
- }
- async fn read_vectored_at<'a>(
- &self,
- bufs: &mut [io::IoSliceMut<'a>],
- offset: u64,
- ) -> Result<u64, Error> {
- block_on_dummy_executor(move || self.0.read_vectored_at(bufs, offset))
- }
- async fn write_vectored<'a>(&self, bufs: &[io::IoSlice<'a>]) -> Result<u64, Error> {
- block_on_dummy_executor(move || self.0.write_vectored(bufs))
- }
- async fn write_vectored_at<'a>(
- &self,
- bufs: &[io::IoSlice<'a>],
- offset: u64,
- ) -> Result<u64, Error> {
- if bufs.iter().map(|i| i.len()).sum::<usize>() == 0 {
- return Ok(0);
- }
- block_on_dummy_executor(move || self.0.write_vectored_at(bufs, offset))
- }
- async fn seek(&self, pos: std::io::SeekFrom) -> Result<u64, Error> {
- block_on_dummy_executor(move || self.0.seek(pos))
- }
- async fn peek(&self, buf: &mut [u8]) -> Result<u64, Error> {
- block_on_dummy_executor(move || self.0.peek(buf))
- }
- async fn set_times(
- &self,
- atime: Option<crate::SystemTimeSpec>,
- mtime: Option<crate::SystemTimeSpec>,
- ) -> Result<(), Error> {
- block_on_dummy_executor(move || self.0.set_times(atime, mtime))
- }
- fn num_ready_bytes(&self) -> Result<u64, Error> {
- self.0.num_ready_bytes()
- }
- fn isatty(&self) -> bool {
- self.0.isatty()
- }
-
- #[cfg(not(windows))]
- async fn readable(&self) -> Result<(), Error> {
- // The Inner impls OwnsRaw, which asserts exclusive use of the handle by the owned object.
- // AsyncFd needs to wrap an owned `impl std::os::unix::io::AsRawFd`. Rather than introduce
- // mutability to let it own the `Inner`, we are depending on the `&mut self` bound on this
- // async method to ensure this is the only Future which can access the RawFd during the
- // lifetime of the AsyncFd.
- use std::os::unix::io::AsRawFd;
- use tokio::io::{Interest, unix::AsyncFd};
- let rawfd = self.0.borrow().as_fd().as_raw_fd();
- match AsyncFd::with_interest(rawfd, Interest::READABLE) {
- Ok(asyncfd) => {
- let _ = asyncfd.readable().await?;
- Ok(())
- }
- Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
- // if e is EPERM, this file isn't supported by epoll because it is immediately
- // available for reading:
- Ok(())
- }
- Err(e) => Err(e.into()),
- }
- }
-
- #[cfg(not(windows))]
- async fn writable(&self) -> Result<(), Error> {
- // The Inner impls OwnsRaw, which asserts exclusive use of the handle by the owned object.
- // AsyncFd needs to wrap an owned `impl std::os::unix::io::AsRawFd`. Rather than introduce
- // mutability to let it own the `Inner`, we are depending on the `&mut self` bound on this
- // async method to ensure this is the only Future which can access the RawFd during the
- // lifetime of the AsyncFd.
- use std::os::unix::io::AsRawFd;
- use tokio::io::{Interest, unix::AsyncFd};
- let rawfd = self.0.borrow().as_fd().as_raw_fd();
- match AsyncFd::with_interest(rawfd, Interest::WRITABLE) {
- Ok(asyncfd) => {
- let _ = asyncfd.writable().await?;
- Ok(())
- }
- Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
- // if e is EPERM, this file isn't supported by epoll because it is immediately
- // available for writing:
- Ok(())
- }
- Err(e) => Err(e.into()),
- }
- }
-
- async fn sock_accept(&self, fdflags: FdFlags) -> Result<Box<dyn WasiFile>, Error> {
- block_on_dummy_executor(|| self.0.sock_accept(fdflags))
- }
- }
- #[cfg(windows)]
- impl AsRawHandleOrSocket for $ty {
- #[inline]
- fn as_raw_handle_or_socket(&self) -> RawHandleOrSocket {
- self.0.borrow().as_raw_handle_or_socket()
- }
- }
- };
-}
-
-wasi_file_impl!(File);
-wasi_file_impl!(TcpListener);
-wasi_file_impl!(TcpStream);
-#[cfg(unix)]
-wasi_file_impl!(UnixListener);
-#[cfg(unix)]
-wasi_file_impl!(UnixStream);
-wasi_file_impl!(Stdin);
-wasi_file_impl!(Stdout);
-wasi_file_impl!(Stderr);
diff --git a/crates/wasi-common/src/tokio/mod.rs b/crates/wasi-common/src/tokio/mod.rs
deleted file mode 100644
index ce786587ce..0000000000
--- a/crates/wasi-common/src/tokio/mod.rs
+++ /dev/null
@@ -1,135 +0,0 @@
-mod dir;
-mod file;
-pub mod net;
-pub mod sched;
-pub mod stdio;
-
-use self::sched::sched_ctx;
-use crate::sync::net::Socket;
-pub use crate::sync::{clocks_ctx, random_ctx};
-use crate::{Error, Table, WasiCtx, WasiFile, file::FileAccessMode};
-pub use dir::Dir;
-pub use file::File;
-pub use net::*;
-use std::future::Future;
-use std::mem;
-use std::path::Path;
-
-pub struct WasiCtxBuilder {
- ctx: WasiCtx,
- built: bool,
-}
-
-impl WasiCtxBuilder {
- pub fn new() -> Self {
- WasiCtxBuilder {
- ctx: WasiCtx::new(random_ctx(), clocks_ctx(), sched_ctx(), Table::new()),
- built: false,
- }
- }
- pub fn env(&mut self, var: &str, value: &str) -> Result<&mut Self, crate::StringArrayError> {
- self.ctx.push_env(var, value)?;
- Ok(self)
- }
- pub fn envs(&mut self, env: &[(String, String)]) -> Result<&mut Self, crate::StringArrayError> {
- for (k, v) in env {
- self.ctx.push_env(k, v)?;
- }
- Ok(self)
- }
- pub fn inherit_env(&mut self) -> Result<&mut Self, crate::StringArrayError> {
- for (key, value) in std::env::vars() {
- self.ctx.push_env(&key, &value)?;
- }
- Ok(self)
- }
- pub fn arg(&mut self, arg: &str) -> Result<&mut Self, crate::StringArrayError> {
- self.ctx.push_arg(arg)?;
- Ok(self)
- }
- pub fn args(&mut self, arg: &[String]) -> Result<&mut Self, crate::StringArrayError> {
- for a in arg {
- self.ctx.push_arg(&a)?;
- }
- Ok(self)
- }
- pub fn inherit_args(&mut self) -> Result<&mut Self, crate::StringArrayError> {
- for arg in std::env::args() {
- self.ctx.push_arg(&arg)?;
- }
- Ok(self)
- }
- pub fn stdin(&mut self, f: Box<dyn WasiFile>) -> &mut Self {
- self.ctx.set_stdin(f);
- self
- }
- pub fn stdout(&mut self, f: Box<dyn WasiFile>) -> &mut Self {
- self.ctx.set_stdout(f);
- self
- }
- pub fn stderr(&mut self, f: Box<dyn WasiFile>) -> &mut Self {
- self.ctx.set_stderr(f);
- self
- }
- pub fn inherit_stdin(&mut self) -> &mut Self {
- self.stdin(Box::new(crate::tokio::stdio::stdin()))
- }
- pub fn inherit_stdout(&mut self) -> &mut Self {
- self.stdout(Box::new(crate::tokio::stdio::stdout()))
- }
- pub fn inherit_stderr(&mut self) -> &mut Self {
- self.stderr(Box::new(crate::tokio::stdio::stderr()))
- }
- pub fn inherit_stdio(&mut self) -> &mut Self {
- self.inherit_stdin().inherit_stdout().inherit_stderr()
- }
- pub fn preopened_dir(
- &mut self,
- dir: cap_std::fs::Dir,
- guest_path: impl AsRef<Path>,
- ) -> Result<&mut Self, Error> {
- let dir = Box::new(crate::tokio::dir::Dir::from_cap_std(dir));
- self.ctx.push_preopened_dir(dir, guest_path)?;
- Ok(self)
- }
- pub fn preopened_socket(
- &mut self,
- fd: u32,
- socket: impl Into<Socket>,
- ) -> Result<&mut Self, Error> {
- let socket: Socket = socket.into();
- let file: Box<dyn WasiFile> = socket.into();
- self.ctx
- .insert_file(fd, file, FileAccessMode::READ | FileAccessMode::WRITE);
- Ok(self)
- }
-
- pub fn build(&mut self) -> WasiCtx {
- assert!(!self.built);
- let WasiCtxBuilder { ctx, .. } = mem::replace(self, Self::new());
- self.built = true;
- ctx
- }
-}
-
-// Much of this mod is implemented in terms of `async` methods from the
-// wasmtime_wasi::p2::sync module. These methods may be async in signature, however,
-// they are synchronous in implementation (always Poll::Ready on first poll)
-// and perform blocking syscalls.
-//
-// This function takes this blocking code and executes it using a dummy executor
-// to assert its immediate readiness. We tell tokio this is a blocking operation
-// with the block_in_place function.
-pub(crate) fn block_on_dummy_executor<'a, F, Fut, T>(f: F) -> Result<T, Error>
-where
- F: FnOnce() -> Fut + Send + 'a,
- Fut: Future<Output = Result<T, Error>>,
- T: Send + 'static,
-{
- tokio::task::block_in_place(move || {
- wiggle::run_in_dummy_executor(f()).expect("wrapped operation should be synchronous")
- })
-}
-
-#[cfg(feature = "wasmtime")]
-super::define_wasi!(async T: Send);
diff --git a/crates/wasi-common/src/tokio/net.rs b/crates/wasi-common/src/tokio/net.rs
deleted file mode 100644
index 93a807ec82..0000000000
--- a/crates/wasi-common/src/tokio/net.rs
+++ /dev/null
@@ -1,6 +0,0 @@
-pub use super::file::TcpListener;
-pub use super::file::TcpStream;
-#[cfg(unix)]
-pub use super::file::UnixListener;
-#[cfg(unix)]
-pub use super::file::UnixStream;
diff --git a/crates/wasi-common/src/tokio/sched.rs b/crates/wasi-common/src/tokio/sched.rs
deleted file mode 100644
index 41a77b4d9e..0000000000
--- a/crates/wasi-common/src/tokio/sched.rs
+++ /dev/null
@@ -1,35 +0,0 @@
-#[cfg(unix)]
-mod unix;
-#[cfg(unix)]
-pub use unix::poll_oneoff;
-
-#[cfg(windows)]
-mod windows;
-#[cfg(windows)]
-pub use windows::poll_oneoff;
-
-use crate::{
- Error,
- sched::{Duration, Poll, WasiSched},
-};
-
-pub fn sched_ctx() -> Box<dyn crate::WasiSched> {
- struct AsyncSched;
-
- #[async_trait::async_trait]
- impl WasiSched for AsyncSched {
- async fn poll_oneoff<'a>(&self, poll: &mut Poll<'a>) -> Result<(), Error> {
- poll_oneoff(poll).await
- }
- async fn sched_yield(&self) -> Result<(), Error> {
- tokio::task::yield_now().await;
- Ok(())
- }
- async fn sleep(&self, duration: Duration) -> Result<(), Error> {
- tokio::time::sleep(duration).await;
- Ok(())
- }
- }
-
- Box::new(AsyncSched)
-}
diff --git a/crates/wasi-common/src/tokio/sched/unix.rs b/crates/wasi-common/src/tokio/sched/unix.rs
deleted file mode 100644
index dc063e4d53..0000000000
--- a/crates/wasi-common/src/tokio/sched/unix.rs
+++ /dev/null
@@ -1,103 +0,0 @@
-use crate::{
- Error,
- sched::{
- Poll,
- subscription::{RwEventFlags, Subscription},
- },
-};
-use std::future::{self, Future};
-use std::pin::{Pin, pin};
-use std::task::{Context, Poll as FPoll};
-
-struct FirstReady<'a, T>(Vec<Pin<Box<dyn Future<Output = T> + Send + 'a>>>);
-
-impl<'a, T> FirstReady<'a, T> {
- fn new() -> Self {
- FirstReady(Vec::new())
- }
- fn push(&mut self, f: impl Future<Output = T> + Send + 'a) {
- self.0.push(Box::pin(f));
- }
-}
-
-impl<'a, T> Future for FirstReady<'a, T> {
- type Output = T;
- fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> FPoll<T> {
- let mut result = FPoll::Pending;
- for f in self.as_mut().0.iter_mut() {
- match f.as_mut().poll(cx) {
- FPoll::Ready(r) => match result {
- // First ready gets to set the result. But, continue the loop so all futures
- // which are ready simultaneously (often on first poll) get to report their
- // readiness.
- FPoll::Pending => {
- result = FPoll::Ready(r);
- }
- _ => {}
- },
- _ => continue,
- }
- }
- return result;
- }
-}
-
-pub async fn poll_oneoff<'a>(poll: &mut Poll<'a>) -> Result<(), Error> {
- if poll.is_empty() {
- return Ok(());
- }
-
- let duration = poll
- .earliest_clock_deadline()
- .map(|sub| sub.duration_until());
-
- let mut futures = FirstReady::new();
- for s in poll.rw_subscriptions() {
- match s {
- Subscription::Read(f) => {
- futures.push(async move {
- f.file
- .readable()
- .await
- .map_err(|e| e.context("readable future"))?;
- f.complete(
- f.file
- .num_ready_bytes()
- .map_err(|e| e.context("read num_ready_bytes"))?,
- RwEventFlags::empty(),
- );
- Ok::<(), Error>(())
- });
- }
-
- Subscription::Write(f) => {
- futures.push(async move {
- f.file
- .writable()
- .await
- .map_err(|e| e.context("writable future"))?;
- f.complete(0, RwEventFlags::empty());
- Ok(())
- });
- }
- Subscription::MonotonicClock { .. } => unreachable!(),
- }
- }
- match duration {
- Some(Some(remaining)) => match tokio::time::timeout(remaining, futures).await {
- Ok(r) => r?,
- Err(_deadline_elapsed) => {}
- },
- Some(None) => {
- let mut futures = pin!(futures);
- future::poll_fn(|cx| match futures.as_mut().poll(cx) {
- FPoll::Ready(e) => FPoll::Ready(e),
- FPoll::Pending => FPoll::Ready(Ok(())),
- })
- .await?
- }
- None => futures.await?,
- }
-
- Ok(())
-}
diff --git a/crates/wasi-common/src/tokio/sched/windows.rs b/crates/wasi-common/src/tokio/sched/windows.rs
deleted file mode 100644
index f0d90fd0da..0000000000
--- a/crates/wasi-common/src/tokio/sched/windows.rs
+++ /dev/null
@@ -1,15 +0,0 @@
-use crate::sync::sched::windows::poll_oneoff_;
-use crate::tokio::block_on_dummy_executor;
-use crate::{Error, file::WasiFile, sched::Poll};
-
-pub async fn poll_oneoff<'a>(poll: &mut Poll<'a>) -> Result<(), Error> {
- // Tokio doesn't provide us the AsyncFd primitive on Windows, so instead
- // we use the blocking poll_oneoff implementation from the wasi_common::sync impl.
- // We provide a function specific to this impl's WasiFile types for downcasting
- // to a RawHandle.
- block_on_dummy_executor(move || poll_oneoff_(poll, wasi_file_is_stdin))
-}
-
-pub fn wasi_file_is_stdin(f: &dyn WasiFile) -> bool {
- f.as_any().is::<crate::tokio::stdio::Stdin>()
-}
diff --git a/crates/wasi-common/src/tokio/stdio.rs b/crates/wasi-common/src/tokio/stdio.rs
deleted file mode 100644
index c796fc7225..0000000000
--- a/crates/wasi-common/src/tokio/stdio.rs
+++ /dev/null
@@ -1 +0,0 @@
-pub use super::file::{Stderr, Stdin, Stdout, stderr, stdin, stdout};
diff --git a/crates/wasi-common/tests/all/async_.rs b/crates/wasi-common/tests/all/async_.rs
deleted file mode 100644
index 10dc1db6b7..0000000000
--- a/crates/wasi-common/tests/all/async_.rs
+++ /dev/null
@@ -1,299 +0,0 @@
-use super::*;
-use test_programs_artifacts::*;
-use wasi_common::WasiCtx;
-use wasi_common::tokio::{WasiCtxBuilder, add_to_linker};
-
-foreach_p1!(assert_test_exists);
-
-pub fn prepare_workspace(exe_name: &str) -> Result<TempDir> {
- let prefix = format!("wasi_tokio_{exe_name}_");
- let tempdir = tempfile::Builder::new().prefix(&prefix).tempdir()?;
- Ok(tempdir)
-}
-
-async fn run(path: &str, inherit_stdio: bool) -> Result<()> {
- let path = Path::new(path);
- let name = path.file_stem().unwrap().to_str().unwrap();
- let workspace = prepare_workspace(name)?;
- let stdout = WritePipe::new_in_memory();
- let stderr = WritePipe::new_in_memory();
- let r = {
- let engine = test_programs_artifacts::engine(|_config| {});
- let mut linker = Linker::<WasiCtx>::new(&engine);
- add_to_linker(&mut linker, |cx| cx)?;
-
- // Create our wasi context.
- // Additionally register any preopened directories if we have them.
- let mut builder = WasiCtxBuilder::new();
-
- if inherit_stdio {
- builder.inherit_stdio();
- } else {
- builder
- .stdout(Box::new(stdout.clone()))
- .stderr(Box::new(stderr.clone()));
- }
- builder.arg(name)?.arg(".")?;
- println!("preopen: {workspace:?}");
- let preopen_dir =
- cap_std::fs::Dir::open_ambient_dir(workspace.path(), cap_std::ambient_authority())?;
- builder.preopened_dir(preopen_dir, ".")?;
- for (var, val) in test_programs_artifacts::wasi_tests_environment() {
- builder.env(var, val)?;
- }
-
- let mut store = Store::new(&engine, builder.build());
- let module = Module::from_file(&engine, path)?;
- let instance = linker.instantiate_async(&mut store, &module).await?;
- let start = instance.get_typed_func::<(), ()>(&mut store, "_start")?;
- start.call_async(&mut store, ()).await?;
- Ok(())
- };
-
- r.map_err(move |trap: EnvError| {
- let stdout = stdout
- .try_into_inner()
- .expect("sole ref to stdout")
- .into_inner();
- if !stdout.is_empty() {
- println!("guest stdout:\n{}\n===", String::from_utf8_lossy(&stdout));
- }
- let stderr = stderr
- .try_into_inner()
- .expect("sole ref to stderr")
- .into_inner();
- if !stderr.is_empty() {
- println!("guest stderr:\n{}\n===", String::from_utf8_lossy(&stderr));
- }
- trap.context(format!(
- "error while testing wasi-tests {name} with cap-std-sync"
- ))
- })?;
- Ok(())
-}
-
-// Below here is mechanical: there should be one test for every binary in
-// wasi-tests.
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_big_random_buf() {
- run(P1_BIG_RANDOM_BUF, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_clock_time_get() {
- run(P1_CLOCK_TIME_GET, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_close_preopen() {
- run(P1_CLOSE_PREOPEN, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_dangling_fd() {
- run(P1_DANGLING_FD, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_dangling_symlink() {
- run(P1_DANGLING_SYMLINK, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_directory_seek() {
- run(P1_DIRECTORY_SEEK, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_dir_fd_op_failures() {
- run(P1_DIR_FD_OP_FAILURES, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_fd_advise() {
- run(P1_FD_ADVISE, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_fd_filestat_get() {
- run(P1_FD_FILESTAT_GET, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_fd_filestat_set() {
- run(P1_FD_FILESTAT_SET, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_fd_flags_set() {
- run(P1_FD_FLAGS_SET, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_fd_readdir() {
- run(P1_FD_READDIR, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_file_allocate() {
- run(P1_FILE_ALLOCATE, true).await.unwrap()
-}
-// see sync.rs for notes about ignores here
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-#[cfg_attr(not(target_os = "linux"), ignore)]
-async fn p1_file_pread_pwrite() {
- run(P1_FILE_PREAD_PWRITE, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_file_read_write() {
- run(P1_FILE_READ_WRITE, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_file_seek_tell() {
- run(P1_FILE_SEEK_TELL, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_file_truncation() {
- run(P1_FILE_TRUNCATION, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_file_unbuffered_write() {
- run(P1_FILE_UNBUFFERED_WRITE, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_interesting_paths() {
- run(P1_INTERESTING_PATHS, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_regular_file_isatty() {
- run(P1_REGULAR_FILE_ISATTY, false).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_nofollow_errors() {
- run(P1_NOFOLLOW_ERRORS, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_overwrite_preopen() {
- run(P1_OVERWRITE_PREOPEN, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_path_exists() {
- run(P1_PATH_EXISTS, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_path_filestat() {
- run(P1_PATH_FILESTAT, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_path_link() {
- run(P1_PATH_LINK, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_path_open_create_existing() {
- run(P1_PATH_OPEN_CREATE_EXISTING, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_path_open_read_write() {
- run(P1_PATH_OPEN_READ_WRITE, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_path_open_dirfd_not_dir() {
- run(P1_PATH_OPEN_DIRFD_NOT_DIR, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_path_open_missing() {
- run(P1_PATH_OPEN_MISSING, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_path_open_nonblock() {
- run(P1_PATH_OPEN_NONBLOCK, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_path_rename_dir_trailing_slashes() {
- run(P1_PATH_RENAME_DIR_TRAILING_SLASHES, true)
- .await
- .unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_path_rename() {
- run(P1_PATH_RENAME, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_path_symlink_trailing_slashes() {
- run(P1_PATH_SYMLINK_TRAILING_SLASHES, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_poll_oneoff_files() {
- run(P1_POLL_ONEOFF_FILES, false).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_poll_oneoff_stdio() {
- run(P1_POLL_ONEOFF_STDIO, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_readlink() {
- run(P1_READLINK, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_remove_directory() {
- run(P1_REMOVE_DIRECTORY, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_remove_nonempty_directory() {
- run(P1_REMOVE_NONEMPTY_DIRECTORY, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_renumber() {
- run(P1_RENUMBER, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_sched_yield() {
- run(P1_SCHED_YIELD, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_stdio() {
- run(P1_STDIO, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_stdio_isatty() {
- // Only a valid test if the host executable's stdio is a terminal:
- if test_programs_artifacts::stdio_is_terminal() {
- // Inherit stdio, test asserts it is a tty:
- run(P1_STDIO_ISATTY, true).await.unwrap()
- }
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_stdio_not_isatty() {
- // Don't inherit stdio, test asserts each is not tty:
- run(P1_STDIO_NOT_ISATTY, false).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_symlink_create() {
- run(P1_SYMLINK_CREATE, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_symlink_filestat() {
- run(P1_SYMLINK_FILESTAT, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_symlink_loop() {
- run(P1_SYMLINK_LOOP, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_unlink_file_trailing_slashes() {
- run(P1_UNLINK_FILE_TRAILING_SLASHES, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_path_open_preopen() {
- run(P1_PATH_OPEN_PREOPEN, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_unicode_output() {
- run(P1_UNICODE_OUTPUT, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_file_write() {
- run(P1_FILE_WRITE, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_path_open_lots() {
- run(P1_PATH_OPEN_LOTS, true).await.unwrap()
-}
-#[test_log::test(tokio::test(flavor = "multi_thread"))]
-async fn p1_sleep_quickly_but_lots() {
- run(P1_SLEEP_QUICKLY_BUT_LOTS, true).await.unwrap()
-}
-#[test]
-fn p1_file_truncation_readonly() {
- println!(
- "blank placeholder test to satisfy assert_test_exists. This test exercises wasmtime-wasi functionality is not relevant to wasi-common"
- );
-}
diff --git a/crates/wasi-common/tests/all/main.rs b/crates/wasi-common/tests/all/main.rs
deleted file mode 100644
index 7b5106855c..0000000000
--- a/crates/wasi-common/tests/all/main.rs
+++ /dev/null
@@ -1,21 +0,0 @@
-use std::path::Path;
-use tempfile::TempDir;
-use wasi_common::pipe::WritePipe;
-use wasmtime::{Linker, Module, Store};
-use wasmtime_environ::error::{Error as EnvError, Result};
-
-pub fn prepare_workspace(exe_name: &str) -> Result<TempDir> {
- let prefix = format!("wasi_common_{exe_name}_");
- let tempdir = tempfile::Builder::new().prefix(&prefix).tempdir()?;
- Ok(tempdir)
-}
-
-macro_rules! assert_test_exists {
- ($name:ident) => {
- #[expect(unused_imports, reason = "just here to ensure a name exists")]
- use self::$name as _;
- };
-}
-
-mod async_;
-mod sync;
diff --git a/crates/wasi-common/tests/all/sync.rs b/crates/wasi-common/tests/all/sync.rs
deleted file mode 100644
index d230daf325..0000000000
--- a/crates/wasi-common/tests/all/sync.rs
+++ /dev/null
@@ -1,293 +0,0 @@
-use super::*;
-use test_programs_artifacts::*;
-use wasi_common::sync::{WasiCtxBuilder, add_to_linker};
-
-foreach_p1!(assert_test_exists);
-
-fn run(path: &str, inherit_stdio: bool) -> Result<()> {
- let path = Path::new(path);
- let name = path.file_stem().unwrap().to_str().unwrap();
- let workspace = prepare_workspace(name)?;
- let stdout = WritePipe::new_in_memory();
- let stderr = WritePipe::new_in_memory();
- let r = {
- let engine = test_programs_artifacts::engine(|_| {});
- let mut linker = Linker::new(&engine);
- add_to_linker(&mut linker, |cx| cx)?;
-
- // Create our wasi context.
- // Additionally register any preopened directories if we have them.
- let mut builder = WasiCtxBuilder::new();
-
- if inherit_stdio {
- builder.inherit_stdio();
- } else {
- builder
- .stdout(Box::new(stdout.clone()))
- .stderr(Box::new(stderr.clone()));
- }
- builder.arg(name)?.arg(".")?;
- println!("preopen: {workspace:?}");
- let preopen_dir =
- cap_std::fs::Dir::open_ambient_dir(workspace.path(), cap_std::ambient_authority())?;
- builder.preopened_dir(preopen_dir, ".")?;
- for (var, val) in test_programs_artifacts::wasi_tests_environment() {
- builder.env(var, val)?;
- }
-
- let mut store = Store::new(&engine, builder.build());
- let module = Module::from_file(&engine, path)?;
- let instance = linker.instantiate(&mut store, &module)?;
- let start = instance.get_typed_func::<(), ()>(&mut store, "_start")?;
- start.call(&mut store, ())?;
- Ok(())
- };
-
- r.map_err(move |trap: EnvError| {
- let stdout = stdout
- .try_into_inner()
- .expect("sole ref to stdout")
- .into_inner();
- if !stdout.is_empty() {
- println!("guest stdout:\n{}\n===", String::from_utf8_lossy(&stdout));
- }
- let stderr = stderr
- .try_into_inner()
- .expect("sole ref to stderr")
- .into_inner();
- if !stderr.is_empty() {
- println!("guest stderr:\n{}\n===", String::from_utf8_lossy(&stderr));
- }
- trap.context(format!(
- "error while testing wasi-tests {name} with cap-std-sync"
- ))
- })?;
- Ok(())
-}
-
-// Below here is mechanical: there should be one test for every binary in
-// wasi-tests.
-#[test_log::test]
-fn p1_big_random_buf() {
- run(P1_BIG_RANDOM_BUF, true).unwrap()
-}
-#[test_log::test]
-fn p1_clock_time_get() {
- run(P1_CLOCK_TIME_GET, true).unwrap()
-}
-#[test_log::test]
-fn p1_close_preopen() {
- run(P1_CLOSE_PREOPEN, true).unwrap()
-}
-#[test_log::test]
-fn p1_dangling_fd() {
- run(P1_DANGLING_FD, true).unwrap()
-}
-#[test_log::test]
-fn p1_dangling_symlink() {
- run(P1_DANGLING_SYMLINK, true).unwrap()
-}
-#[test_log::test]
-fn p1_directory_seek() {
- run(P1_DIRECTORY_SEEK, true).unwrap()
-}
-#[test_log::test]
-fn p1_dir_fd_op_failures() {
- run(P1_DIR_FD_OP_FAILURES, true).unwrap()
-}
-#[test_log::test]
-fn p1_fd_advise() {
- run(P1_FD_ADVISE, true).unwrap()
-}
-#[test_log::test]
-fn p1_fd_filestat_get() {
- run(P1_FD_FILESTAT_GET, true).unwrap()
-}
-#[test_log::test]
-fn p1_fd_filestat_set() {
- run(P1_FD_FILESTAT_SET, true).unwrap()
-}
-#[test_log::test]
-fn p1_fd_flags_set() {
- run(P1_FD_FLAGS_SET, true).unwrap()
-}
-#[test_log::test]
-fn p1_fd_readdir() {
- run(P1_FD_READDIR, true).unwrap()
-}
-#[test_log::test]
-fn p1_file_allocate() {
- run(P1_FILE_ALLOCATE, true).unwrap()
-}
-// This test is outside of linux because the behavior of `pwrite`, which this
-// test bottoms out into, differs across platforms. The wasi-common crate
-// doesn't have the infrastructure in place to manually track the append-mode
-// flag easily, but `wasmtime-wasi` has the "correct" behavior here.
-#[test_log::test]
-#[cfg_attr(not(target_os = "linux"), ignore)]
-fn p1_file_pread_pwrite() {
- run(P1_FILE_PREAD_PWRITE, true).unwrap()
-}
-#[test_log::test]
-fn p1_file_read_write() {
- run(P1_FILE_READ_WRITE, true).unwrap()
-}
-#[test_log::test]
-fn p1_file_seek_tell() {
- run(P1_FILE_SEEK_TELL, true).unwrap()
-}
-#[test_log::test]
-fn p1_file_truncation() {
- run(P1_FILE_TRUNCATION, true).unwrap()
-}
-#[test_log::test]
-fn p1_file_unbuffered_write() {
- run(P1_FILE_UNBUFFERED_WRITE, true).unwrap()
-}
-#[test_log::test]
-fn p1_interesting_paths() {
- run(P1_INTERESTING_PATHS, true).unwrap()
-}
-#[test_log::test]
-fn p1_regular_file_isatty() {
- run(P1_REGULAR_FILE_ISATTY, true).unwrap()
-}
-#[test_log::test]
-fn p1_nofollow_errors() {
- run(P1_NOFOLLOW_ERRORS, true).unwrap()
-}
-#[test_log::test]
-fn p1_overwrite_preopen() {
- run(P1_OVERWRITE_PREOPEN, true).unwrap()
-}
-#[test_log::test]
-fn p1_path_exists() {
- run(P1_PATH_EXISTS, true).unwrap()
-}
-#[test_log::test]
-fn p1_path_filestat() {
- run(P1_PATH_FILESTAT, true).unwrap()
-}
-#[test_log::test]
-fn p1_path_link() {
- run(P1_PATH_LINK, true).unwrap()
-}
-#[test_log::test]
-fn p1_path_open_create_existing() {
- run(P1_PATH_OPEN_CREATE_EXISTING, true).unwrap()
-}
-#[test_log::test]
-fn p1_path_open_read_write() {
- run(P1_PATH_OPEN_READ_WRITE, true).unwrap()
-}
-#[test_log::test]
-fn p1_path_open_dirfd_not_dir() {
- run(P1_PATH_OPEN_DIRFD_NOT_DIR, true).unwrap()
-}
-#[test_log::test]
-fn p1_path_open_missing() {
- run(P1_PATH_OPEN_MISSING, true).unwrap()
-}
-#[test_log::test]
-fn p1_path_open_nonblock() {
- run(P1_PATH_OPEN_NONBLOCK, true).unwrap()
-}
-#[test_log::test]
-fn p1_path_rename_dir_trailing_slashes() {
- run(P1_PATH_RENAME_DIR_TRAILING_SLASHES, true).unwrap()
-}
-#[test_log::test]
-fn p1_path_rename() {
- run(P1_PATH_RENAME, true).unwrap()
-}
-#[test_log::test]
-fn p1_path_symlink_trailing_slashes() {
- run(P1_PATH_SYMLINK_TRAILING_SLASHES, true).unwrap()
-}
-#[test_log::test]
-fn p1_poll_oneoff_files() {
- run(P1_POLL_ONEOFF_FILES, false).unwrap()
-}
-#[test_log::test]
-fn p1_poll_oneoff_stdio() {
- run(P1_POLL_ONEOFF_STDIO, true).unwrap()
-}
-#[test_log::test]
-fn p1_readlink() {
- run(P1_READLINK, true).unwrap()
-}
-#[test_log::test]
-fn p1_remove_directory() {
- run(P1_REMOVE_DIRECTORY, true).unwrap()
-}
-#[test_log::test]
-fn p1_remove_nonempty_directory() {
- run(P1_REMOVE_NONEMPTY_DIRECTORY, true).unwrap()
-}
-#[test_log::test]
-fn p1_renumber() {
- run(P1_RENUMBER, true).unwrap()
-}
-#[test_log::test]
-fn p1_sched_yield() {
- run(P1_SCHED_YIELD, true).unwrap()
-}
-#[test_log::test]
-fn p1_stdio() {
- run(P1_STDIO, true).unwrap()
-}
-#[test_log::test]
-fn p1_stdio_isatty() {
- if test_programs_artifacts::stdio_is_terminal() {
- // Inherit stdio, which is a terminal in the test runner's environment:
- run(P1_STDIO_ISATTY, true).unwrap()
- }
-}
-#[test_log::test]
-fn p1_stdio_not_isatty() {
- // Don't inherit stdio, test asserts each is not tty:
- run(P1_STDIO_NOT_ISATTY, false).unwrap()
-}
-
-#[test_log::test]
-fn p1_symlink_create() {
- run(P1_SYMLINK_CREATE, true).unwrap()
-}
-#[test_log::test]
-fn p1_symlink_filestat() {
- run(P1_SYMLINK_FILESTAT, true).unwrap()
-}
-#[test_log::test]
-fn p1_symlink_loop() {
- run(P1_SYMLINK_LOOP, true).unwrap()
-}
-#[test_log::test]
-fn p1_unlink_file_trailing_slashes() {
- run(P1_UNLINK_FILE_TRAILING_SLASHES, true).unwrap()
-}
-#[test_log::test]
-fn p1_path_open_preopen() {
- run(P1_PATH_OPEN_PREOPEN, true).unwrap()
-}
-#[test_log::test]
-fn p1_unicode_output() {
- run(P1_UNICODE_OUTPUT, true).unwrap()
-}
-#[test_log::test]
-fn p1_file_write() {
- run(P1_FILE_WRITE, true).unwrap()
-}
-#[test_log::test]
-fn p1_path_open_lots() {
- run(P1_PATH_OPEN_LOTS, true).unwrap()
-}
-#[test_log::test]
-fn p1_sleep_quickly_but_lots() {
- run(P1_SLEEP_QUICKLY_BUT_LOTS, true).unwrap()
-}
-#[test]
-fn p1_file_truncation_readonly() {
- println!(
- "blank placeholder test to satisfy assert_test_exists. This test exercises wasmtime-wasi functionality is not relevant to wasi-common"
- );
-}
diff --git a/crates/wasi-common/witx/preview0/typenames.witx b/crates/wasi-common/witx/preview0/typenames.witx
deleted file mode 100644
index c321374332..0000000000
--- a/crates/wasi-common/witx/preview0/typenames.witx
+++ /dev/null
@@ -1,746 +0,0 @@
-;; Type names used by low-level WASI interfaces.
-;;
-;; Some content here is derived from [CloudABI](https://github.com/NuxiNL/cloudabi).
-;;
-;; This is a `witx` file. See [here](https://github.com/WebAssembly/WASI/tree/main/docs/witx.md)
-;; for an explanation of what that means.
-
-(typename $size u32)
-
-;;; Non-negative file size or length of a region within a file.
-(typename $filesize u64)
-
-;;; Timestamp in nanoseconds.
-(typename $timestamp u64)
-
-;;; Identifiers for clocks.
-(typename $clockid
- (enum (@witx tag u32)
- ;;; The clock measuring real time. Time value zero corresponds with
- ;;; 1970-01-01T00:00:00Z.
- $realtime
- ;;; The store-wide monotonic clock, which is defined as a clock measuring
- ;;; real time, whose value cannot be adjusted and which cannot have negative
- ;;; clock jumps. The epoch of this clock is undefined. The absolute time
- ;;; value of this clock therefore has no meaning.
- $monotonic
- ;;; The CPU-time clock associated with the current process.
- $process_cputime_id
- ;;; The CPU-time clock associated with the current thread.
- $thread_cputime_id
- )
-)
-
-;;; Error codes returned by functions.
-;;; Not all of these error codes are returned by the functions provided by this
-;;; API; some are used in higher-level library layers, and others are provided
-;;; merely for alignment with POSIX.
-(typename $errno
- (enum (@witx tag u16)
- ;;; No error occurred. System call completed successfully.
- $success
- ;;; Argument list too long.
- $2big
- ;;; Permission denied.
- $acces
- ;;; Address in use.
- $addrinuse
- ;;; Address not available.
- $addrnotavail
- ;;; Address family not supported.
- $afnosupport
- ;;; Resource unavailable, or operation would block.
- $again
- ;;; Connection already in progress.
- $already
- ;;; Bad file descriptor.
- $badf
- ;;; Bad message.
- $badmsg
- ;;; Device or resource busy.
- $busy
- ;;; Operation canceled.
- $canceled
- ;;; No child processes.
- $child
- ;;; Connection aborted.
- $connaborted
- ;;; Connection refused.
- $connrefused
- ;;; Connection reset.
- $connreset
- ;;; Resource deadlock would occur.
- $deadlk
- ;;; Destination address required.
- $destaddrreq
- ;;; Mathematics argument out of domain of function.
- $dom
- ;;; Reserved.
- $dquot
- ;;; File exists.
- $exist
- ;;; Bad address.
- $fault
- ;;; File too large.
- $fbig
- ;;; Host is unreachable.
- $hostunreach
- ;;; Identifier removed.
- $idrm
- ;;; Illegal byte sequence.
- $ilseq
- ;;; Operation in progress.
- $inprogress
- ;;; Interrupted function.
- $intr
- ;;; Invalid argument.
- $inval
- ;;; I/O error.
- $io
- ;;; Socket is connected.
- $isconn
- ;;; Is a directory.
- $isdir
- ;;; Too many levels of symbolic links.
- $loop
- ;;; File descriptor value too large.
- $mfile
- ;;; Too many links.
- $mlink
- ;;; Message too large.
- $msgsize
- ;;; Reserved.
- $multihop
- ;;; Filename too long.
- $nametoolong
- ;;; Network is down.
- $netdown
- ;;; Connection aborted by network.
- $netreset
- ;;; Network unreachable.
- $netunreach
- ;;; Too many files open in system.
- $nfile
- ;;; No buffer space available.
- $nobufs
- ;;; No such device.
- $nodev
- ;;; No such file or directory.
- $noent
- ;;; Executable file format error.
- $noexec
- ;;; No locks available.
- $nolck
- ;;; Reserved.
- $nolink
- ;;; Not enough space.
- $nomem
- ;;; No message of the desired type.
- $nomsg
- ;;; Protocol not available.
- $noprotoopt
- ;;; No space left on device.
- $nospc
- ;;; Function not supported.
- $nosys
- ;;; The socket is not connected.
- $notconn
- ;;; Not a directory or a symbolic link to a directory.
- $notdir
- ;;; Directory not empty.
- $notempty
- ;;; State not recoverable.
- $notrecoverable
- ;;; Not a socket.
- $notsock
- ;;; Not supported, or operation not supported on socket.
- $notsup
- ;;; Inappropriate I/O control operation.
- $notty
- ;;; No such device or address.
- $nxio
- ;;; Value too large to be stored in data type.
- $overflow
- ;;; Previous owner died.
- $ownerdead
- ;;; Operation not permitted.
- $perm
- ;;; Broken pipe.
- $pipe
- ;;; Protocol error.
- $proto
- ;;; Protocol not supported.
- $protonosupport
- ;;; Protocol wrong type for socket.
- $prototype
- ;;; Result too large.
- $range
- ;;; Read-only file system.
- $rofs
- ;;; Invalid seek.
- $spipe
- ;;; No such process.
- $srch
- ;;; Reserved.
- $stale
- ;;; Connection timed out.
- $timedout
- ;;; Text file busy.
- $txtbsy
- ;;; Cross-device link.
- $xdev
- ;;; Extension: Capabilities insufficient.
- $notcapable
- )
-)
-
-;;; File descriptor rights, determining which actions may be performed.
-(typename $rights
- (flags (@witx repr u64)
- ;;; The right to invoke `fd_datasync`.
- ;;
- ;;; If `rights::path_open` is set, includes the right to invoke
- ;;; `path_open` with `fdflags::dsync`.
- $fd_datasync
- ;;; The right to invoke `fd_read` and `sock_recv`.
- ;;
- ;;; If `rights::fd_seek` is set, includes the right to invoke `fd_pread`.
- $fd_read
- ;;; The right to invoke `fd_seek`. This flag implies `rights::fd_tell`.
- $fd_seek
- ;;; The right to invoke `fd_fdstat_set_flags`.
- $fd_fdstat_set_flags
- ;;; The right to invoke `fd_sync`.
- ;;
- ;;; If `rights::path_open` is set, includes the right to invoke
- ;;; `path_open` with `fdflags::rsync` and `fdflags::dsync`.
- $fd_sync
- ;;; The right to invoke `fd_seek` in such a way that the file offset
- ;;; remains unaltered (i.e., `whence::cur` with offset zero), or to
- ;;; invoke `fd_tell`.
- $fd_tell
- ;;; The right to invoke `fd_write` and `sock_send`.
- ;;; If `rights::fd_seek` is set, includes the right to invoke `fd_pwrite`.
- $fd_write
- ;;; The right to invoke `fd_advise`.
- $fd_advise
- ;;; The right to invoke `fd_allocate`.
- $fd_allocate
- ;;; The right to invoke `path_create_directory`.
- $path_create_directory
- ;;; If `rights::path_open` is set, the right to invoke `path_open` with `oflags::creat`.
- $path_create_file
- ;;; The right to invoke `path_link` with the file descriptor as the
- ;;; source directory.
- $path_link_source
- ;;; The right to invoke `path_link` with the file descriptor as the
- ;;; target directory.
- $path_link_target
- ;;; The right to invoke `path_open`.
- $path_open
- ;;; The right to invoke `fd_readdir`.
- $fd_readdir
- ;;; The right to invoke `path_readlink`.
- $path_readlink
- ;;; The right to invoke `path_rename` with the file descriptor as the source directory.
- $path_rename_source
- ;;; The right to invoke `path_rename` with the file descriptor as the target directory.
- $path_rename_target
- ;;; The right to invoke `path_filestat_get`.
- $path_filestat_get
- ;;; The right to change a file's size (there is no `path_filestat_set_size`).
- ;;; If `rights::path_open` is set, includes the right to invoke `path_open` with `oflags::trunc`.
- $path_filestat_set_size
- ;;; The right to invoke `path_filestat_set_times`.
- $path_filestat_set_times
- ;;; The right to invoke `fd_filestat_get`.
- $fd_filestat_get
- ;;; The right to invoke `fd_filestat_set_size`.
- $fd_filestat_set_size
- ;;; The right to invoke `fd_filestat_set_times`.
- $fd_filestat_set_times
- ;;; The right to invoke `path_symlink`.
- $path_symlink
- ;;; The right to invoke `path_remove_directory`.
- $path_remove_directory
- ;;; The right to invoke `path_unlink_file`.
- $path_unlink_file
- ;;; If `rights::fd_read` is set, includes the right to invoke `poll_oneoff` to subscribe to `eventtype::fd_read`.
- ;;; If `rights::fd_write` is set, includes the right to invoke `poll_oneoff` to subscribe to `eventtype::fd_write`.
- $poll_fd_readwrite
- ;;; The right to invoke `sock_shutdown`.
- $sock_shutdown
- )
-)
-
-;;; A file descriptor handle.
-(typename $fd (handle))
-
-;;; A region of memory for scatter/gather reads.
-(typename $iovec
- (record
- ;;; The address of the buffer to be filled.
- (field $buf (@witx pointer u8))
- ;;; The length of the buffer to be filled.
- (field $buf_len $size)
- )
-)
-
-;;; A region of memory for scatter/gather writes.
-(typename $ciovec
- (record
- ;;; The address of the buffer to be written.
- (field $buf (@witx const_pointer u8))
- ;;; The length of the buffer to be written.
- (field $buf_len $size)
- )
-)
-
-(typename $iovec_array (list $iovec))
-(typename $ciovec_array (list $ciovec))
-
-;;; Relative offset within a file.
-(typename $filedelta s64)
-
-;;; The position relative to which to set the offset of the file descriptor.
-(typename $whence
- (enum (@witx tag u8)
- ;;; Seek relative to current position.
- $cur
- ;;; Seek relative to end-of-file.
- $end
- ;;; Seek relative to start-of-file.
- $set
- )
-)
-
-;;; A reference to the offset of a directory entry.
-(typename $dircookie u64)
-
-;;; The type for the `dirent::d_namlen` field of `dirent` struct.
-(typename $dirnamlen u32)
-
-;;; File serial number that is unique within its file system.
-(typename $inode u64)
-
-;;; The type of a file descriptor or file.
-(typename $filetype
- (enum (@witx tag u8)
- ;;; The type of the file descriptor or file is unknown or is different from any of the other types specified.
- $unknown
- ;;; The file descriptor or file refers to a block device inode.
- $block_device
- ;;; The file descriptor or file refers to a character device inode.
- $character_device
- ;;; The file descriptor or file refers to a directory inode.
- $directory
- ;;; The file descriptor or file refers to a regular file inode.
- $regular_file
- ;;; The file descriptor or file refers to a datagram socket.
- $socket_dgram
- ;;; The file descriptor or file refers to a byte-stream socket.
- $socket_stream
- ;;; The file refers to a symbolic link inode.
- $symbolic_link
- )
-)
-
-;;; A directory entry.
-(typename $dirent
- (record
- ;;; The offset of the next directory entry stored in this directory.
- (field $d_next $dircookie)
- ;;; The serial number of the file referred to by this directory entry.
- (field $d_ino $inode)
- ;;; The length of the name of the directory entry.
- (field $d_namlen $dirnamlen)
- ;;; The type of the file referred to by this directory entry.
- (field $d_type $filetype)
- )
-)
-
-;;; File or memory access pattern advisory information.
-(typename $advice
- (enum (@witx tag u8)
- ;;; The application has no advice to give on its behavior with respect to the specified data.
- $normal
- ;;; The application expects to access the specified data sequentially from lower offsets to higher offsets.
- $sequential
- ;;; The application expects to access the specified data in a random order.
- $random
- ;;; The application expects to access the specified data in the near future.
- $willneed
- ;;; The application expects that it will not access the specified data in the near future.
- $dontneed
- ;;; The application expects to access the specified data once and then not reuse it thereafter.
- $noreuse
- )
-)
-
-;;; File descriptor flags.
-(typename $fdflags
- (flags (@witx repr u16)
- ;;; Append mode: Data written to the file is always appended to the file's end.
- $append
- ;;; Write according to synchronized I/O data integrity completion. Only the data stored in the file is synchronized.
- $dsync
- ;;; Non-blocking mode.
- $nonblock
- ;;; Synchronized read I/O operations.
- $rsync
- ;;; Write according to synchronized I/O file integrity completion. In
- ;;; addition to synchronizing the data stored in the file, the implementation
- ;;; may also synchronously update the file's metadata.
- $sync
- )
-)
-
-;;; File descriptor attributes.
-(typename $fdstat
- (record
- ;;; File type.
- (field $fs_filetype $filetype)
- ;;; File descriptor flags.
- (field $fs_flags $fdflags)
- ;;; Rights that apply to this file descriptor.
- (field $fs_rights_base $rights)
- ;;; Maximum set of rights that may be installed on new file descriptors that
- ;;; are created through this file descriptor, e.g., through `path_open`.
- (field $fs_rights_inheriting $rights)
- )
-)
-
-;;; Identifier for a device containing a file system. Can be used in combination
-;;; with `inode` to uniquely identify a file or directory in the filesystem.
-(typename $device u64)
-
-;;; Which file time attributes to adjust.
-(typename $fstflags
- (flags (@witx repr u16)
- ;;; Adjust the last data access timestamp to the value stored in `filestat::atim`.
- $atim
- ;;; Adjust the last data access timestamp to the time of clock `clockid::realtime`.
- $atim_now
- ;;; Adjust the last data modification timestamp to the value stored in `filestat::mtim`.
- $mtim
- ;;; Adjust the last data modification timestamp to the time of clock `clockid::realtime`.
- $mtim_now
- )
-)
-
-;;; Flags determining the method of how paths are resolved.
-(typename $lookupflags
- (flags (@witx repr u32)
- ;;; As long as the resolved path corresponds to a symbolic link, it is expanded.
- $symlink_follow
- )
-)
-
-;;; Open flags used by `path_open`.
-(typename $oflags
- (flags (@witx repr u16)
- ;;; Create file if it does not exist.
- $creat
- ;;; Fail if not a directory.
- $directory
- ;;; Fail if file already exists.
- $excl
- ;;; Truncate file to size 0.
- $trunc
- )
-)
-
-;;; Number of hard links to an inode.
-(typename $linkcount u32)
-
-;;; File attributes.
-(typename $filestat
- (record
- ;;; Device ID of device containing the file.
- (field $dev $device)
- ;;; File serial number.
- (field $ino $inode)
- ;;; File type.
- (field $filetype $filetype)
- ;;; Number of hard links to the file.
- (field $nlink $linkcount)
- ;;; For regular files, the file size in bytes. For symbolic links, the length in bytes of the pathname contained in the symbolic link.
- (field $size $filesize)
- ;;; Last data access timestamp.
- (field $atim $timestamp)
- ;;; Last data modification timestamp.
- (field $mtim $timestamp)
- ;;; Last file status change timestamp.
- (field $ctim $timestamp)
- )
-)
-
-;;; User-provided value that may be attached to objects that is retained when
-;;; extracted from the implementation.
-(typename $userdata u64)
-
-;;; Type of a subscription to an event or its occurrence.
-(typename $eventtype
- (enum (@witx tag u8)
- ;;; The time value of clock `subscription_clock::id` has
- ;;; reached timestamp `subscription_clock::timeout`.
- $clock
- ;;; File descriptor `subscription_fd_readwrite::file_descriptor` has data
- ;;; available for reading. This event always triggers for regular files.
- $fd_read
- ;;; File descriptor `subscription_fd_readwrite::file_descriptor` has capacity
- ;;; available for writing. This event always triggers for regular files.
- $fd_write
- )
-)
-
-;;; The state of the file descriptor subscribed to with
-;;; `eventtype::fd_read` or `eventtype::fd_write`.
-(typename $eventrwflags
- (flags (@witx repr u16)
- ;;; The peer of this socket has closed or disconnected.
- $fd_readwrite_hangup
- )
-)
-
-;;; The contents of an `event` for the `eventtype::fd_read` and
-;;; `eventtype::fd_write` variants
-(typename $event_fd_readwrite
- (record
- ;;; The number of bytes available for reading or writing.
- (field $nbytes $filesize)
- ;;; The state of the file descriptor.
- (field $flags $eventrwflags)
- )
-)
-
-;;; An event that occurred.
-(typename $event
- (record
- ;;; User-provided value that got attached to `subscription::userdata`.
- (field $userdata $userdata)
- ;;; If non-zero, an error that occurred while processing the subscription request.
- (field $error $errno)
- ;;; The type of event that occurred
- (field $type $eventtype)
- ;;; The contents of the event, if it is an `eventtype::fd_read` or
- ;;; `eventtype::fd_write`. `eventtype::clock` events ignore this field.
- (field $fd_readwrite $event_fd_readwrite)
- )
-)
-
-;;; Flags determining how to interpret the timestamp provided in
-;;; `subscription_clock::timeout`.
-(typename $subclockflags
- (flags (@witx repr u16)
- ;;; If set, treat the timestamp provided in
- ;;; `subscription_clock::timeout` as an absolute timestamp of clock
- ;;; `subscription_clock::id`. If clear, treat the timestamp
- ;;; provided in `subscription_clock::timeout` relative to the
- ;;; current time value of clock `subscription_clock::id`.
- $subscription_clock_abstime
- )
-)
-
-;;; The contents of a `subscription` when type is `eventtype::clock`.
-(typename $subscription_clock
- (record
- ;;; The user-defined unique identifier of the clock.
- (field $identifier $userdata)
- ;;; The clock against which to compare the timestamp.
- (field $id $clockid)
- ;;; The absolute or relative timestamp.
- (field $timeout $timestamp)
- ;;; The amount of time that the implementation may wait additionally
- ;;; to coalesce with other events.
- (field $precision $timestamp)
- ;;; Flags specifying whether the timeout is absolute or relative
- (field $flags $subclockflags)
- )
-)
-
-;;; The contents of a `subscription` when the variant is
-;;; `eventtype::fd_read` or `eventtype::fd_write`.
-(typename $subscription_fd_readwrite
- (record
- ;;; The file descriptor on which to wait for it to become ready for reading or writing.
- (field $file_descriptor $fd)
- )
-)
-
-;;; The contents of a `subscription`.
-(typename $subscription_u
- (union (@witx tag $eventtype)
- $subscription_clock
- $subscription_fd_readwrite
- $subscription_fd_readwrite
- )
-)
-
-;;; Subscription to an event.
-(typename $subscription
- (record
- ;;; User-provided value that is attached to the subscription in the
- ;;; implementation and returned through `event::userdata`.
- (field $userdata $userdata)
- ;;; The type of the event to which to subscribe.
- (field $u $subscription_u)
- )
-)
-
-;;; Exit code generated by a process when exiting.
-(typename $exitcode u32)
-
-;;; Signal condition.
-(typename $signal
- (enum (@witx tag u8)
- ;;; No signal. Note that POSIX has special semantics for `kill(pid, 0)`,
- ;;; so this value is reserved.
- $none
- ;;; Hangup.
- ;;; Action: Terminates the process.
- $hup
- ;;; Terminate interrupt signal.
- ;;; Action: Terminates the process.
- $int
- ;;; Terminal quit signal.
- ;;; Action: Terminates the process.
- $quit
- ;;; Illegal instruction.
- ;;; Action: Terminates the process.
- $ill
- ;;; Trace/breakpoint trap.
- ;;; Action: Terminates the process.
- $trap
- ;;; Process abort signal.
- ;;; Action: Terminates the process.
- $abrt
- ;;; Access to an undefined portion of a memory object.
- ;;; Action: Terminates the process.
- $bus
- ;;; Erroneous arithmetic operation.
- ;;; Action: Terminates the process.
- $fpe
- ;;; Kill.
- ;;; Action: Terminates the process.
- $kill
- ;;; User-defined signal 1.
- ;;; Action: Terminates the process.
- $usr1
- ;;; Invalid memory reference.
- ;;; Action: Terminates the process.
- $segv
- ;;; User-defined signal 2.
- ;;; Action: Terminates the process.
- $usr2
- ;;; Write on a pipe with no one to read it.
- ;;; Action: Ignored.
- $pipe
- ;;; Alarm clock.
- ;;; Action: Terminates the process.
- $alrm
- ;;; Termination signal.
- ;;; Action: Terminates the process.
- $term
- ;;; Child process terminated, stopped, or continued.
- ;;; Action: Ignored.
- $chld
- ;;; Continue executing, if stopped.
- ;;; Action: Continues executing, if stopped.
- $cont
- ;;; Stop executing.
- ;;; Action: Stops executing.
- $stop
- ;;; Terminal stop signal.
- ;;; Action: Stops executing.
- $tstp
- ;;; Background process attempting read.
- ;;; Action: Stops executing.
- $ttin
- ;;; Background process attempting write.
- ;;; Action: Stops executing.
- $ttou
- ;;; High bandwidth data is available at a socket.
- ;;; Action: Ignored.
- $urg
- ;;; CPU time limit exceeded.
- ;;; Action: Terminates the process.
- $xcpu
- ;;; File size limit exceeded.
- ;;; Action: Terminates the process.
- $xfsz
- ;;; Virtual timer expired.
- ;;; Action: Terminates the process.
- $vtalrm
- ;;; Profiling timer expired.
- ;;; Action: Terminates the process.
- $prof
- ;;; Window changed.
- ;;; Action: Ignored.
- $winch
- ;;; I/O possible.
- ;;; Action: Terminates the process.
- $poll
- ;;; Power failure.
- ;;; Action: Terminates the process.
- $pwr
- ;;; Bad system call.
- ;;; Action: Terminates the process.
- $sys
- )
-)
-
-;;; Flags provided to `sock_recv`.
-(typename $riflags
- (flags (@witx repr u16)
- ;;; Returns the message without removing it from the socket's receive queue.
- $recv_peek
- ;;; On byte-stream sockets, block until the full amount of data can be returned.
- $recv_waitall
- )
-)
-
-;;; Flags returned by `sock_recv`.
-(typename $roflags
- (flags (@witx repr u16)
- ;;; Returned by `sock_recv`: Message data has been truncated.
- $recv_data_truncated
- )
-)
-
-;;; Flags provided to `sock_send`. As there are currently no flags
-;;; defined, it must be set to zero.
-(typename $siflags u16)
-
-;;; Which channels on a socket to shut down.
-(typename $sdflags
- (flags (@witx repr u8)
- ;;; Disables further receive operations.
- $rd
- ;;; Disables further send operations.
- $wr
- )
-)
-
-;;; Identifiers for preopened capabilities.
-(typename $preopentype
- (enum (@witx tag u8)
- ;;; A pre-opened directory.
- $dir
- )
-)
-
-;;; The contents of a $prestat when type is `preopentype::dir`.
-(typename $prestat_dir
- (record
- ;;; The length of the directory name for use with `fd_prestat_dir_name`.
- (field $pr_name_len $size)
- )
-)
-
-;;; Information about a pre-opened capability.
-(typename $prestat
- (union (@witx tag $preopentype)
- $prestat_dir
- )
-)
diff --git a/crates/wasi-common/witx/preview0/wasi_unstable.witx b/crates/wasi-common/witx/preview0/wasi_unstable.witx
deleted file mode 100644
index ee01abcfed..0000000000
--- a/crates/wasi-common/witx/preview0/wasi_unstable.witx
+++ /dev/null
@@ -1,513 +0,0 @@
-;; WASI Preview. This is an evolution of the API that WASI initially
-;; launched with.
-;;
-;; Some content here is derived from [CloudABI](https://github.com/NuxiNL/cloudabi).
-;;
-;; This is a `witx` file. See [here](https://github.com/WebAssembly/WASI/blob/main/legacy/tools/witx-docs.md)
-;; for an explanation of what that means.
-
-(use "typenames.witx")
-
-;;; This API predated the convention of naming modules with a `wasi_unstable_`
-;;; prefix and a version number. It is preserved here for compatibility, but
-;;; we shouldn't follow this pattern in new APIs.
-(module $wasi_unstable
- ;;; Linear memory to be accessed by WASI functions that need it.
- (import "memory" (memory))
-
- ;;; Read command-line argument data.
- ;;; The size of the array should match that returned by `args_sizes_get`.
- ;;; Each argument is expected to be `\0` terminated.
- (@interface func (export "args_get")
- (param $argv (@witx pointer (@witx pointer u8)))
- (param $argv_buf (@witx pointer u8))
- (result $error (expected (error $errno)))
- )
- ;;; Return command-line argument data sizes.
- (@interface func (export "args_sizes_get")
- ;;; Returns the number of arguments and the size of the argument string
- ;;; data, or an error.
- (result $error (expected (tuple $size $size) (error $errno)))
- )
-
- ;;; Read environment variable data.
- ;;; The sizes of the buffers should match that returned by `environ_sizes_get`.
- ;;; Key/value pairs are expected to be joined with `=`s, and terminated with `\0`s.
- (@interface func (export "environ_get")
- (param $environ (@witx pointer (@witx pointer u8)))
- (param $environ_buf (@witx pointer u8))
- (result $error (expected (error $errno)))
- )
- ;;; Return environment variable data sizes.
- (@interface func (export "environ_sizes_get")
- ;;; Returns the number of environment variable arguments and the size of the
- ;;; environment variable data.
- (result $error (expected (tuple $size $size) (error $errno)))
- )
-
- ;;; Return the resolution of a clock.
- ;;; Implementations are required to provide a non-zero value for supported clocks. For unsupported clocks, return
- ;;; `errno::inval`.
- ;;; Note: This is similar to `clock_getres` in POSIX.
- (@interface func (export "clock_res_get")
- ;;; The clock for which to return the resolution.
- (param $id $clockid)
- ;;; The resolution of the clock, or an error if one happened.
- (result $error (expected $timestamp (error $errno)))
- )
- ;;; Return the time value of a clock.
- ;;; Note: This is similar to `clock_gettime` in POSIX.
- (@interface func (export "clock_time_get")
- ;;; The clock for which to return the time.
- (param $id $clockid)
- ;;; The maximum lag (exclusive) that the returned time value may have, compared to its actual value.
- (param $precision $timestamp)
- ;;; The time value of the clock.
- (result $error (expected $timestamp (error $errno)))
- )
-
- ;;; Provide file advisory information on a file descriptor.
- ;;; Note: This is similar to `posix_fadvise` in POSIX.
- (@interface func (export "fd_advise")
- (param $fd $fd)
- ;;; The offset within the file to which the advisory applies.
- (param $offset $filesize)
- ;;; The length of the region to which the advisory applies.
- (param $len $filesize)
- ;;; The advice.
- (param $advice $advice)
- (result $error (expected (error $errno)))
- )
-
- ;;; Force the allocation of space in a file.
- ;;; Note: This is similar to `posix_fallocate` in POSIX.
- (@interface func (export "fd_allocate")
- (param $fd $fd)
- ;;; The offset at which to start the allocation.
- (param $offset $filesize)
- ;;; The length of the area that is allocated.
- (param $len $filesize)
- (result $error (expected (error $errno)))
- )
-
- ;;; Close a file descriptor.
- ;;; Note: This is similar to `close` in POSIX.
- (@interface func (export "fd_close")
- (param $fd $fd)
- (result $error (expected (error $errno)))
- )
-
- ;;; Synchronize the data of a file to disk.
- ;;; Note: This is similar to `fdatasync` in POSIX.
- (@interface func (export "fd_datasync")
- (param $fd $fd)
- (result $error (expected (error $errno)))
- )
-
- ;;; Get the attributes of a file descriptor.
- ;;; Note: This returns similar flags to `fsync(fd, F_GETFL)` in POSIX, as well as additional fields.
- (@interface func (export "fd_fdstat_get")
- (param $fd $fd)
- ;;; The buffer where the file descriptor's attributes are stored.
- (result $error (expected $fdstat (error $errno)))
- )
-
- ;;; Adjust the flags associated with a file descriptor.
- ;;; Note: This is similar to `fcntl(fd, F_SETFL, flags)` in POSIX.
- (@interface func (export "fd_fdstat_set_flags")
- (param $fd $fd)
- ;;; The desired values of the file descriptor flags.
- (param $flags $fdflags)
- (result $error (expected (error $errno)))
- )
-
- ;;; Adjust the rights associated with a file descriptor.
- ;;; This can only be used to remove rights, and returns `errno::notcapable` if called in a way that would attempt to add rights
- (@interface func (export "fd_fdstat_set_rights")
- (param $fd $fd)
- ;;; The desired rights of the file descriptor.
- (param $fs_rights_base $rights)
- (param $fs_rights_inheriting $rights)
- (result $error (expected (error $errno)))
- )
-
- ;;; Return the attributes of an open file.
- (@interface func (export "fd_filestat_get")
- (param $fd $fd)
- ;;; The buffer where the file's attributes are stored.
- (result $error (expected $filestat (error $errno)))
- )
-
- ;;; Adjust the size of an open file. If this increases the file's size, the extra bytes are filled with zeros.
- ;;; Note: This is similar to `ftruncate` in POSIX.
- (@interface func (export "fd_filestat_set_size")
- (param $fd $fd)
- ;;; The desired file size.
- (param $size $filesize)
- (result $error (expected (error $errno)))
- )
-
- ;;; Adjust the timestamps of an open file or directory.
- ;;; Note: This is similar to `futimens` in POSIX.
- (@interface func (export "fd_filestat_set_times")
- (param $fd $fd)
- ;;; The desired values of the data access timestamp.
- (param $atim $timestamp)
- ;;; The desired values of the data modification timestamp.
- (param $mtim $timestamp)
- ;;; A bitmask indicating which timestamps to adjust.
- (param $fst_flags $fstflags)
- (result $error (expected (error $errno)))
- )
-
- ;;; Read from a file descriptor, without using and updating the file descriptor's offset.
- ;;; Note: This is similar to `preadv` in POSIX.
- (@interface func (export "fd_pread")
- (param $fd $fd)
- ;;; List of scatter/gather vectors in which to store data.
- (param $iovs $iovec_array)
- ;;; The offset within the file at which to read.
- (param $offset $filesize)
- ;;; The number of bytes read.
- (result $error (expected $size (error $errno)))
- )
-
- ;;; Return a description of the given preopened file descriptor.
- (@interface func (export "fd_prestat_get")
- (param $fd $fd)
- ;;; The buffer where the description is stored.
- (result $error (expected $prestat (error $errno)))
- )
-
- ;;; Return a description of the given preopened file descriptor.
- (@interface func (export "fd_prestat_dir_name")
- (param $fd $fd)
- ;;; A buffer into which to write the preopened directory name.
- (param $path (@witx pointer u8))
- (param $path_len $size)
- (result $error (expected (error $errno)))
- )
-
- ;;; Write to a file descriptor, without using and updating the file descriptor's offset.
- ;;; Note: This is similar to `pwritev` in POSIX.
- (@interface func (export "fd_pwrite")
- (param $fd $fd)
- ;;; List of scatter/gather vectors from which to retrieve data.
- (param $iovs $ciovec_array)
- ;;; The offset within the file at which to write.
- (param $offset $filesize)
- ;;; The number of bytes written.
- (result $error (expected $size (error $errno)))
- )
-
- ;;; Read from a file descriptor.
- ;;; Note: This is similar to `readv` in POSIX.
- (@interface func (export "fd_read")
- (param $fd $fd)
- ;;; List of scatter/gather vectors to which to store data.
- (param $iovs $iovec_array)
- ;;; The number of bytes read.
- (result $error (expected $size (error $errno)))
- )
-
- ;;; Read directory entries from a directory.
- ;;; When successful, the contents of the output buffer consist of a sequence of
- ;;; directory entries. Each directory entry consists of a `dirent` object,
- ;;; followed by `dirent::d_namlen` bytes holding the name of the directory
- ;;; entry.
- ;;
- ;;; This function fills the output buffer as much as possible, potentially
- ;;; truncating the last directory entry. This allows the caller to grow its
- ;;; read buffer size in case it's too small to fit a single large directory
- ;;; entry, or skip the oversized directory entry.
- (@interface func (export "fd_readdir")
- (param $fd $fd)
- ;;; The buffer where directory entries are stored
- (param $buf (@witx pointer u8))
- (param $buf_len $size)
- ;;; The location within the directory to start reading
- (param $cookie $dircookie)
- ;;; The number of bytes stored in the read buffer. If less than the size of the read buffer, the end of the directory has been reached.
- (result $error (expected $size (error $errno)))
- )
-
- ;;; Atomically replace a file descriptor by renumbering another file descriptor.
- ;;
- ;;; Due to the strong focus on thread safety, this environment does not provide
- ;;; a mechanism to duplicate or renumber a file descriptor to an arbitrary
- ;;; number, like `dup2()`. This would be prone to race conditions, as an actual
- ;;; file descriptor with the same number could be allocated by a different
- ;;; thread at the same time.
- ;;
- ;;; This function provides a way to atomically renumber file descriptors, which
- ;;; would disappear if `dup2()` were to be removed entirely.
- (@interface func (export "fd_renumber")
- (param $fd $fd)
- ;;; The file descriptor to overwrite.
- (param $to $fd)
- (result $error (expected (error $errno)))
- )
-
- ;;; Move the offset of a file descriptor.
- ;;; Note: This is similar to `lseek` in POSIX.
- (@interface func (export "fd_seek")
- (param $fd $fd)
- ;;; The number of bytes to move.
- (param $offset $filedelta)
- ;;; The base from which the offset is relative.
- (param $whence $whence)
- ;;; The new offset of the file descriptor, relative to the start of the file.
- (result $error (expected $filesize (error $errno)))
- )
-
- ;;; Synchronize the data and metadata of a file to disk.
- ;;; Note: This is similar to `fsync` in POSIX.
- (@interface func (export "fd_sync")
- (param $fd $fd)
- (result $error (expected (error $errno)))
- )
-
- ;;; Return the current offset of a file descriptor.
- ;;; Note: This is similar to `lseek(fd, 0, SEEK_CUR)` in POSIX.
- (@interface func (export "fd_tell")
- (param $fd $fd)
- ;;; The current offset of the file descriptor, relative to the start of the file.
- (result $error (expected $filesize (error $errno)))
- )
-
- ;;; Write to a file descriptor.
- ;;; Note: This is similar to `writev` in POSIX.
- (@interface func (export "fd_write")
- (param $fd $fd)
- ;;; List of scatter/gather vectors from which to retrieve data.
- (param $iovs $ciovec_array)
- (result $error (expected $size (error $errno)))
- )
-
- ;;; Create a directory.
- ;;; Note: This is similar to `mkdirat` in POSIX.
- (@interface func (export "path_create_directory")
- (param $fd $fd)
- ;;; The path at which to create the directory.
- (param $path string)
- (result $error (expected (error $errno)))
- )
-
- ;;; Return the attributes of a file or directory.
- ;;; Note: This is similar to `stat` in POSIX.
- (@interface func (export "path_filestat_get")
- (param $fd $fd)
- ;;; Flags determining the method of how the path is resolved.
- (param $flags $lookupflags)
- ;;; The path of the file or directory to inspect.
- (param $path string)
- ;;; The buffer where the file's attributes are stored.
- (result $error (expected $filestat (error $errno)))
- )
-
- ;;; Adjust the timestamps of a file or directory.
- ;;; Note: This is similar to `utimensat` in POSIX.
- (@interface func (export "path_filestat_set_times")
- (param $fd $fd)
- ;;; Flags determining the method of how the path is resolved.
- (param $flags $lookupflags)
- ;;; The path of the file or directory to operate on.
- (param $path string)
- ;;; The desired values of the data access timestamp.
- (param $atim $timestamp)
- ;;; The desired values of the data modification timestamp.
- (param $mtim $timestamp)
- ;;; A bitmask indicating which timestamps to adjust.
- (param $fst_flags $fstflags)
- (result $error (expected (error $errno)))
- )
-
- ;;; Create a hard link.
- ;;; Note: This is similar to `linkat` in POSIX.
- (@interface func (export "path_link")
- (param $old_fd $fd)
- ;;; Flags determining the method of how the path is resolved.
- (param $old_flags $lookupflags)
- ;;; The source path from which to link.
- (param $old_path string)
- ;;; The working directory at which the resolution of the new path starts.
- (param $new_fd $fd)
- ;;; The destination path at which to create the hard link.
- (param $new_path string)
- (result $error (expected (error $errno)))
- )
-
- ;;; Open a file or directory.
- ;;
- ;;; The returned file descriptor is not guaranteed to be the lowest-numbered
- ;;; file descriptor not currently open; it is randomized to prevent
- ;;; applications from depending on making assumptions about indexes, since this
- ;;; is error-prone in multi-threaded contexts. The returned file descriptor is
- ;;; guaranteed to be less than 2**31.
- ;;
- ;;; Note: This is similar to `openat` in POSIX.
- (@interface func (export "path_open")
- (param $fd $fd)
- ;;; Flags determining the method of how the path is resolved.
- (param $dirflags $lookupflags)
- ;;; The relative path of the file or directory to open, relative to the
- ;;; `path_open::fd` directory.
- (param $path string)
- ;;; The method by which to open the file.
- (param $oflags $oflags)
- ;;; The initial rights of the newly created file descriptor. The
- ;;; implementation is allowed to return a file descriptor with fewer rights
- ;;; than specified, if and only if those rights do not apply to the type of
- ;;; file being opened.
- ;;
- ;;; The *base* rights are rights that will apply to operations using the file
- ;;; descriptor itself, while the *inheriting* rights are rights that apply to
- ;;; file descriptors derived from it.
- (param $fs_rights_base $rights)
- (param $fs_rights_inheriting $rights)
- (param $fdflags $fdflags)
- ;;; The file descriptor of the file that has been opened.
- (result $error (expected $fd (error $errno)))
- )
-
- ;;; Read the contents of a symbolic link.
- ;;; Note: This is similar to `readlinkat` in POSIX.
- (@interface func (export "path_readlink")
- (param $fd $fd)
- ;;; The path of the symbolic link from which to read.
- (param $path string)
- ;;; The buffer to which to write the contents of the symbolic link.
- (param $buf (@witx pointer u8))
- (param $buf_len $size)
- ;;; The number of bytes placed in the buffer.
- (result $error (expected $size (error $errno)))
- )
-
- ;;; Remove a directory.
- ;;; Return `errno::notempty` if the directory is not empty.
- ;;; Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX.
- (@interface func (export "path_remove_directory")
- (param $fd $fd)
- ;;; The path to a directory to remove.
- (param $path string)
- (result $error (expected (error $errno)))
- )
-
- ;;; Rename a file or directory.
- ;;; Note: This is similar to `renameat` in POSIX.
- (@interface func (export "path_rename")
- (param $fd $fd)
- ;;; The source path of the file or directory to rename.
- (param $old_path string)
- ;;; The working directory at which the resolution of the new path starts.
- (param $new_fd $fd)
- ;;; The destination path to which to rename the file or directory.
- (param $new_path string)
- (result $error (expected (error $errno)))
- )
-
- ;;; Create a symbolic link.
- ;;; Note: This is similar to `symlinkat` in POSIX.
- (@interface func (export "path_symlink")
- ;;; The contents of the symbolic link.
- (param $old_path string)
- (param $fd $fd)
- ;;; The destination path at which to create the symbolic link.
- (param $new_path string)
- (result $error (expected (error $errno)))
- )
-
-
- ;;; Unlink a file.
- ;;; Return `errno::isdir` if the path refers to a directory.
- ;;; Note: This is similar to `unlinkat(fd, path, 0)` in POSIX.
- (@interface func (export "path_unlink_file")
- (param $fd $fd)
- ;;; The path to a file to unlink.
- (param $path string)
- (result $error (expected (error $errno)))
- )
-
- ;;; Concurrently poll for the occurrence of a set of events.
- (@interface func (export "poll_oneoff")
- ;;; The events to which to subscribe.
- (param $in (@witx const_pointer $subscription))
- ;;; The events that have occurred.
- (param $out (@witx pointer $event))
- ;;; Both the number of subscriptions and events.
- (param $nsubscriptions $size)
- ;;; The number of events stored.
- (result $error (expected $size (error $errno)))
- )
-
- ;;; Terminate the process normally. An exit code of 0 indicates successful
- ;;; termination of the program. The meanings of other values is dependent on
- ;;; the environment.
- (@interface func (export "proc_exit")
- ;;; The exit code returned by the process.
- (param $rval $exitcode)
- (@witx noreturn)
- )
-
- ;;; Send a signal to the process of the calling thread.
- ;;; Note: This is similar to `raise` in POSIX.
- (@interface func (export "proc_raise")
- ;;; The signal condition to trigger.
- (param $sig $signal)
- (result $error (expected (error $errno)))
- )
-
- ;;; Temporarily yield execution of the calling thread.
- ;;; Note: This is similar to `sched_yield` in POSIX.
- (@interface func (export "sched_yield")
- (result $error (expected (error $errno)))
- )
-
- ;;; Write high-quality random data into a buffer.
- ;;; This function blocks when the implementation is unable to immediately
- ;;; provide sufficient high-quality random data.
- ;;; This function may execute slowly, so when large mounts of random data are
- ;;; required, it's advisable to use this function to seed a pseudo-random
- ;;; number generator, rather than to provide the random data directly.
- (@interface func (export "random_get")
- ;;; The buffer to fill with random data.
- (param $buf (@witx pointer u8))
- (param $buf_len $size)
- (result $error (expected (error $errno)))
- )
-
- ;;; Receive a message from a socket.
- ;;; Note: This is similar to `recv` in POSIX, though it also supports reading
- ;;; the data into multiple buffers in the manner of `readv`.
- (@interface func (export "sock_recv")
- (param $fd $fd)
- ;;; List of scatter/gather vectors to which to store data.
- (param $ri_data $iovec_array)
- ;;; Message flags.
- (param $ri_flags $riflags)
- ;;; Number of bytes stored in ri_data and message flags.
- (result $error (expected (tuple $size $roflags) (error $errno)))
- )
-
- ;;; Send a message on a socket.
- ;;; Note: This is similar to `send` in POSIX, though it also supports writing
- ;;; the data from multiple buffers in the manner of `writev`.
- (@interface func (export "sock_send")
- (param $fd $fd)
- ;;; List of scatter/gather vectors to which to retrieve data
- (param $si_data $ciovec_array)
- ;;; Message flags.
- (param $si_flags $siflags)
- ;;; Number of bytes transmitted.
- (result $error (expected $size (error $errno)))
- )
-
- ;;; Shut down socket send and receive channels.
- ;;; Note: This is similar to `shutdown` in POSIX.
- (@interface func (export "sock_shutdown")
- (param $fd $fd)
- ;;; Which channels on the socket to shut down.
- (param $how $sdflags)
- (result $error (expected (error $errno)))
- )
-)
diff --git a/crates/wasi-common/witx/preview1/typenames.witx b/crates/wasi-common/witx/preview1/typenames.witx
deleted file mode 100644
index 82ea276456..0000000000
--- a/crates/wasi-common/witx/preview1/typenames.witx
+++ /dev/null
@@ -1,750 +0,0 @@
-;; Type names used by low-level WASI interfaces.
-;;
-;; Some content here is derived from [CloudABI](https://github.com/NuxiNL/cloudabi).
-;;
-;; This is a `witx` file. See [here](https://github.com/WebAssembly/WASI/blob/main/legacy/tools/witx-docs.md)
-;; for an explanation of what that means.
-
-(typename $size u32)
-
-;;; Non-negative file size or length of a region within a file.
-(typename $filesize u64)
-
-;;; Timestamp in nanoseconds.
-(typename $timestamp u64)
-
-;;; Identifiers for clocks.
-(typename $clockid
- (enum (@witx tag u32)
- ;;; The clock measuring real time. Time value zero corresponds with
- ;;; 1970-01-01T00:00:00Z.
- $realtime
- ;;; The store-wide monotonic clock, which is defined as a clock measuring
- ;;; real time, whose value cannot be adjusted and which cannot have negative
- ;;; clock jumps. The epoch of this clock is undefined. The absolute time
- ;;; value of this clock therefore has no meaning.
- $monotonic
- ;;; The CPU-time clock associated with the current process.
- $process_cputime_id
- ;;; The CPU-time clock associated with the current thread.
- $thread_cputime_id
- )
-)
-
-;;; Error codes returned by functions.
-;;; Not all of these error codes are returned by the functions provided by this
-;;; API; some are used in higher-level library layers, and others are provided
-;;; merely for alignment with POSIX.
-(typename $errno
- (enum (@witx tag u16)
- ;;; No error occurred. System call completed successfully.
- $success
- ;;; Argument list too long.
- $2big
- ;;; Permission denied.
- $acces
- ;;; Address in use.
- $addrinuse
- ;;; Address not available.
- $addrnotavail
- ;;; Address family not supported.
- $afnosupport
- ;;; Resource unavailable, or operation would block.
- $again
- ;;; Connection already in progress.
- $already
- ;;; Bad file descriptor.
- $badf
- ;;; Bad message.
- $badmsg
- ;;; Device or resource busy.
- $busy
- ;;; Operation canceled.
- $canceled
- ;;; No child processes.
- $child
- ;;; Connection aborted.
- $connaborted
- ;;; Connection refused.
- $connrefused
- ;;; Connection reset.
- $connreset
- ;;; Resource deadlock would occur.
- $deadlk
- ;;; Destination address required.
- $destaddrreq
- ;;; Mathematics argument out of domain of function.
- $dom
- ;;; Reserved.
- $dquot
- ;;; File exists.
- $exist
- ;;; Bad address.
- $fault
- ;;; File too large.
- $fbig
- ;;; Host is unreachable.
- $hostunreach
- ;;; Identifier removed.
- $idrm
- ;;; Illegal byte sequence.
- $ilseq
- ;;; Operation in progress.
- $inprogress
- ;;; Interrupted function.
- $intr
- ;;; Invalid argument.
- $inval
- ;;; I/O error.
- $io
- ;;; Socket is connected.
- $isconn
- ;;; Is a directory.
- $isdir
- ;;; Too many levels of symbolic links.
- $loop
- ;;; File descriptor value too large.
- $mfile
- ;;; Too many links.
- $mlink
- ;;; Message too large.
- $msgsize
- ;;; Reserved.
- $multihop
- ;;; Filename too long.
- $nametoolong
- ;;; Network is down.
- $netdown
- ;;; Connection aborted by network.
- $netreset
- ;;; Network unreachable.
- $netunreach
- ;;; Too many files open in system.
- $nfile
- ;;; No buffer space available.
- $nobufs
- ;;; No such device.
- $nodev
- ;;; No such file or directory.
- $noent
- ;;; Executable file format error.
- $noexec
- ;;; No locks available.
- $nolck
- ;;; Reserved.
- $nolink
- ;;; Not enough space.
- $nomem
- ;;; No message of the desired type.
- $nomsg
- ;;; Protocol not available.
- $noprotoopt
- ;;; No space left on device.
- $nospc
- ;;; Function not supported.
- $nosys
- ;;; The socket is not connected.
- $notconn
- ;;; Not a directory or a symbolic link to a directory.
- $notdir
- ;;; Directory not empty.
- $notempty
- ;;; State not recoverable.
- $notrecoverable
- ;;; Not a socket.
- $notsock
- ;;; Not supported, or operation not supported on socket.
- $notsup
- ;;; Inappropriate I/O control operation.
- $notty
- ;;; No such device or address.
- $nxio
- ;;; Value too large to be stored in data type.
- $overflow
- ;;; Previous owner died.
- $ownerdead
- ;;; Operation not permitted.
- $perm
- ;;; Broken pipe.
- $pipe
- ;;; Protocol error.
- $proto
- ;;; Protocol not supported.
- $protonosupport
- ;;; Protocol wrong type for socket.
- $prototype
- ;;; Result too large.
- $range
- ;;; Read-only file system.
- $rofs
- ;;; Invalid seek.
- $spipe
- ;;; No such process.
- $srch
- ;;; Reserved.
- $stale
- ;;; Connection timed out.
- $timedout
- ;;; Text file busy.
- $txtbsy
- ;;; Cross-device link.
- $xdev
- ;;; Extension: Capabilities insufficient.
- $notcapable
- )
-)
-
-;;; File descriptor rights, determining which actions may be performed.
-(typename $rights
- (flags (@witx repr u64)
- ;;; The right to invoke `fd_datasync`.
- ;;
- ;;; If `path_open` is set, includes the right to invoke
- ;;; `path_open` with `fdflags::dsync`.
- $fd_datasync
- ;;; The right to invoke `fd_read` and `sock_recv`.
- ;;
- ;;; If `rights::fd_seek` is set, includes the right to invoke `fd_pread`.
- $fd_read
- ;;; The right to invoke `fd_seek`. This flag implies `rights::fd_tell`.
- $fd_seek
- ;;; The right to invoke `fd_fdstat_set_flags`.
- $fd_fdstat_set_flags
- ;;; The right to invoke `fd_sync`.
- ;;
- ;;; If `path_open` is set, includes the right to invoke
- ;;; `path_open` with `fdflags::rsync` and `fdflags::dsync`.
- $fd_sync
- ;;; The right to invoke `fd_seek` in such a way that the file offset
- ;;; remains unaltered (i.e., `whence::cur` with offset zero), or to
- ;;; invoke `fd_tell`.
- $fd_tell
- ;;; The right to invoke `fd_write` and `sock_send`.
- ;;; If `rights::fd_seek` is set, includes the right to invoke `fd_pwrite`.
- $fd_write
- ;;; The right to invoke `fd_advise`.
- $fd_advise
- ;;; The right to invoke `fd_allocate`.
- $fd_allocate
- ;;; The right to invoke `path_create_directory`.
- $path_create_directory
- ;;; If `path_open` is set, the right to invoke `path_open` with `oflags::creat`.
- $path_create_file
- ;;; The right to invoke `path_link` with the file descriptor as the
- ;;; source directory.
- $path_link_source
- ;;; The right to invoke `path_link` with the file descriptor as the
- ;;; target directory.
- $path_link_target
- ;;; The right to invoke `path_open`.
- $path_open
- ;;; The right to invoke `fd_readdir`.
- $fd_readdir
- ;;; The right to invoke `path_readlink`.
- $path_readlink
- ;;; The right to invoke `path_rename` with the file descriptor as the source directory.
- $path_rename_source
- ;;; The right to invoke `path_rename` with the file descriptor as the target directory.
- $path_rename_target
- ;;; The right to invoke `path_filestat_get`.
- $path_filestat_get
- ;;; The right to change a file's size (there is no `path_filestat_set_size`).
- ;;; If `path_open` is set, includes the right to invoke `path_open` with `oflags::trunc`.
- $path_filestat_set_size
- ;;; The right to invoke `path_filestat_set_times`.
- $path_filestat_set_times
- ;;; The right to invoke `fd_filestat_get`.
- $fd_filestat_get
- ;;; The right to invoke `fd_filestat_set_size`.
- $fd_filestat_set_size
- ;;; The right to invoke `fd_filestat_set_times`.
- $fd_filestat_set_times
- ;;; The right to invoke `path_symlink`.
- $path_symlink
- ;;; The right to invoke `path_remove_directory`.
- $path_remove_directory
- ;;; The right to invoke `path_unlink_file`.
- $path_unlink_file
- ;;; If `rights::fd_read` is set, includes the right to invoke `poll_oneoff` to subscribe to `eventtype::fd_read`.
- ;;; If `rights::fd_write` is set, includes the right to invoke `poll_oneoff` to subscribe to `eventtype::fd_write`.
- $poll_fd_readwrite
- ;;; The right to invoke `sock_shutdown`.
- $sock_shutdown
- ;;; The right to invoke `sock_accept`.
- $sock_accept
- )
-)
-
-;;; A file descriptor handle.
-(typename $fd (handle))
-
-;;; A region of memory for scatter/gather reads.
-(typename $iovec
- (record
- ;;; The address of the buffer to be filled.
- (field $buf (@witx pointer u8))
- ;;; The length of the buffer to be filled.
- (field $buf_len $size)
- )
-)
-
-;;; A region of memory for scatter/gather writes.
-(typename $ciovec
- (record
- ;;; The address of the buffer to be written.
- (field $buf (@witx const_pointer u8))
- ;;; The length of the buffer to be written.
- (field $buf_len $size)
- )
-)
-
-(typename $iovec_array (list $iovec))
-(typename $ciovec_array (list $ciovec))
-
-;;; Relative offset within a file.
-(typename $filedelta s64)
-
-;;; The position relative to which to set the offset of the file descriptor.
-(typename $whence
- (enum (@witx tag u8)
- ;;; Seek relative to start-of-file.
- $set
- ;;; Seek relative to current position.
- $cur
- ;;; Seek relative to end-of-file.
- $end
- )
-)
-
-;;; A reference to the offset of a directory entry.
-;;;
-;;; The value 0 signifies the start of the directory.
-(typename $dircookie u64)
-
-;;; The type for the `dirent::d_namlen` field of `dirent` struct.
-(typename $dirnamlen u32)
-
-;;; File serial number that is unique within its file system.
-(typename $inode u64)
-
-;;; The type of a file descriptor or file.
-(typename $filetype
- (enum (@witx tag u8)
- ;;; The type of the file descriptor or file is unknown or is different from any of the other types specified.
- $unknown
- ;;; The file descriptor or file refers to a block device inode.
- $block_device
- ;;; The file descriptor or file refers to a character device inode.
- $character_device
- ;;; The file descriptor or file refers to a directory inode.
- $directory
- ;;; The file descriptor or file refers to a regular file inode.
- $regular_file
- ;;; The file descriptor or file refers to a datagram socket.
- $socket_dgram
- ;;; The file descriptor or file refers to a byte-stream socket.
- $socket_stream
- ;;; The file refers to a symbolic link inode.
- $symbolic_link
- )
-)
-
-;;; A directory entry.
-(typename $dirent
- (record
- ;;; The offset of the next directory entry stored in this directory.
- (field $d_next $dircookie)
- ;;; The serial number of the file referred to by this directory entry.
- (field $d_ino $inode)
- ;;; The length of the name of the directory entry.
- (field $d_namlen $dirnamlen)
- ;;; The type of the file referred to by this directory entry.
- (field $d_type $filetype)
- )
-)
-
-;;; File or memory access pattern advisory information.
-(typename $advice
- (enum (@witx tag u8)
- ;;; The application has no advice to give on its behavior with respect to the specified data.
- $normal
- ;;; The application expects to access the specified data sequentially from lower offsets to higher offsets.
- $sequential
- ;;; The application expects to access the specified data in a random order.
- $random
- ;;; The application expects to access the specified data in the near future.
- $willneed
- ;;; The application expects that it will not access the specified data in the near future.
- $dontneed
- ;;; The application expects to access the specified data once and then not reuse it thereafter.
- $noreuse
- )
-)
-
-;;; File descriptor flags.
-(typename $fdflags
- (flags (@witx repr u16)
- ;;; Append mode: Data written to the file is always appended to the file's end.
- $append
- ;;; Write according to synchronized I/O data integrity completion. Only the data stored in the file is synchronized.
- $dsync
- ;;; Non-blocking mode.
- $nonblock
- ;;; Synchronized read I/O operations.
- $rsync
- ;;; Write according to synchronized I/O file integrity completion. In
- ;;; addition to synchronizing the data stored in the file, the implementation
- ;;; may also synchronously update the file's metadata.
- $sync
- )
-)
-
-;;; File descriptor attributes.
-(typename $fdstat
- (record
- ;;; File type.
- (field $fs_filetype $filetype)
- ;;; File descriptor flags.
- (field $fs_flags $fdflags)
- ;;; Rights that apply to this file descriptor.
- (field $fs_rights_base $rights)
- ;;; Maximum set of rights that may be installed on new file descriptors that
- ;;; are created through this file descriptor, e.g., through `path_open`.
- (field $fs_rights_inheriting $rights)
- )
-)
-
-;;; Identifier for a device containing a file system. Can be used in combination
-;;; with `inode` to uniquely identify a file or directory in the filesystem.
-(typename $device u64)
-
-;;; Which file time attributes to adjust.
-(typename $fstflags
- (flags (@witx repr u16)
- ;;; Adjust the last data access timestamp to the value stored in `filestat::atim`.
- $atim
- ;;; Adjust the last data access timestamp to the time of clock `clockid::realtime`.
- $atim_now
- ;;; Adjust the last data modification timestamp to the value stored in `filestat::mtim`.
- $mtim
- ;;; Adjust the last data modification timestamp to the time of clock `clockid::realtime`.
- $mtim_now
- )
-)
-
-;;; Flags determining the method of how paths are resolved.
-(typename $lookupflags
- (flags (@witx repr u32)
- ;;; As long as the resolved path corresponds to a symbolic link, it is expanded.
- $symlink_follow
- )
-)
-
-;;; Open flags used by `path_open`.
-(typename $oflags
- (flags (@witx repr u16)
- ;;; Create file if it does not exist.
- $creat
- ;;; Fail if not a directory.
- $directory
- ;;; Fail if file already exists.
- $excl
- ;;; Truncate file to size 0.
- $trunc
- )
-)
-
-;;; Number of hard links to an inode.
-(typename $linkcount u64)
-
-;;; File attributes.
-(typename $filestat
- (record
- ;;; Device ID of device containing the file.
- (field $dev $device)
- ;;; File serial number.
- (field $ino $inode)
- ;;; File type.
- (field $filetype $filetype)
- ;;; Number of hard links to the file.
- (field $nlink $linkcount)
- ;;; For regular files, the file size in bytes. For symbolic links, the length in bytes of the pathname contained in the symbolic link.
- (field $size $filesize)
- ;;; Last data access timestamp.
- (field $atim $timestamp)
- ;;; Last data modification timestamp.
- (field $mtim $timestamp)
- ;;; Last file status change timestamp.
- (field $ctim $timestamp)
- )
-)
-
-;;; User-provided value that may be attached to objects that is retained when
-;;; extracted from the implementation.
-(typename $userdata u64)
-
-;;; Type of a subscription to an event or its occurrence.
-(typename $eventtype
- (enum (@witx tag u8)
- ;;; The time value of clock `subscription_clock::id` has
- ;;; reached timestamp `subscription_clock::timeout`.
- $clock
- ;;; File descriptor `subscription_fd_readwrite::file_descriptor` has data
- ;;; available for reading. This event always triggers for regular files.
- $fd_read
- ;;; File descriptor `subscription_fd_readwrite::file_descriptor` has capacity
- ;;; available for writing. This event always triggers for regular files.
- $fd_write
- )
-)
-
-;;; The state of the file descriptor subscribed to with
-;;; `eventtype::fd_read` or `eventtype::fd_write`.
-(typename $eventrwflags
- (flags (@witx repr u16)
- ;;; The peer of this socket has closed or disconnected.
- $fd_readwrite_hangup
- )
-)
-
-;;; The contents of an `event` when type is `eventtype::fd_read` or
-;;; `eventtype::fd_write`.
-(typename $event_fd_readwrite
- (record
- ;;; The number of bytes available for reading or writing.
- (field $nbytes $filesize)
- ;;; The state of the file descriptor.
- (field $flags $eventrwflags)
- )
-)
-
-;;; An event that occurred.
-(typename $event
- (record
- ;;; User-provided value that got attached to `subscription::userdata`.
- (field $userdata $userdata)
- ;;; If non-zero, an error that occurred while processing the subscription request.
- (field $error $errno)
- ;;; The type of event that occurred
- (field $type $eventtype)
- ;;; The contents of the event, if it is an `eventtype::fd_read` or
- ;;; `eventtype::fd_write`. `eventtype::clock` events ignore this field.
- (field $fd_readwrite $event_fd_readwrite)
- )
-)
-
-;;; Flags determining how to interpret the timestamp provided in
-;;; `subscription_clock::timeout`.
-(typename $subclockflags
- (flags (@witx repr u16)
- ;;; If set, treat the timestamp provided in
- ;;; `subscription_clock::timeout` as an absolute timestamp of clock
- ;;; `subscription_clock::id`. If clear, treat the timestamp
- ;;; provided in `subscription_clock::timeout` relative to the
- ;;; current time value of clock `subscription_clock::id`.
- $subscription_clock_abstime
- )
-)
-
-;;; The contents of a `subscription` when type is `eventtype::clock`.
-(typename $subscription_clock
- (record
- ;;; The clock against which to compare the timestamp.
- (field $id $clockid)
- ;;; The absolute or relative timestamp.
- (field $timeout $timestamp)
- ;;; The amount of time that the implementation may wait additionally
- ;;; to coalesce with other events.
- (field $precision $timestamp)
- ;;; Flags specifying whether the timeout is absolute or relative
- (field $flags $subclockflags)
- )
-)
-
-;;; The contents of a `subscription` when type is type is
-;;; `eventtype::fd_read` or `eventtype::fd_write`.
-(typename $subscription_fd_readwrite
- (record
- ;;; The file descriptor on which to wait for it to become ready for reading or writing.
- (field $file_descriptor $fd)
- )
-)
-
-;;; The contents of a `subscription`.
-(typename $subscription_u
- (union
- (@witx tag $eventtype)
- $subscription_clock
- $subscription_fd_readwrite
- $subscription_fd_readwrite
- )
-)
-
-;;; Subscription to an event.
-(typename $subscription
- (record
- ;;; User-provided value that is attached to the subscription in the
- ;;; implementation and returned through `event::userdata`.
- (field $userdata $userdata)
- ;;; The type of the event to which to subscribe, and its contents
- (field $u $subscription_u)
- )
-)
-
-;;; Exit code generated by a process when exiting.
-(typename $exitcode u32)
-
-;;; Signal condition.
-(typename $signal
- (enum (@witx tag u8)
- ;;; No signal. Note that POSIX has special semantics for `kill(pid, 0)`,
- ;;; so this value is reserved.
- $none
- ;;; Hangup.
- ;;; Action: Terminates the process.
- $hup
- ;;; Terminate interrupt signal.
- ;;; Action: Terminates the process.
- $int
- ;;; Terminal quit signal.
- ;;; Action: Terminates the process.
- $quit
- ;;; Illegal instruction.
- ;;; Action: Terminates the process.
- $ill
- ;;; Trace/breakpoint trap.
- ;;; Action: Terminates the process.
- $trap
- ;;; Process abort signal.
- ;;; Action: Terminates the process.
- $abrt
- ;;; Access to an undefined portion of a memory object.
- ;;; Action: Terminates the process.
- $bus
- ;;; Erroneous arithmetic operation.
- ;;; Action: Terminates the process.
- $fpe
- ;;; Kill.
- ;;; Action: Terminates the process.
- $kill
- ;;; User-defined signal 1.
- ;;; Action: Terminates the process.
- $usr1
- ;;; Invalid memory reference.
- ;;; Action: Terminates the process.
- $segv
- ;;; User-defined signal 2.
- ;;; Action: Terminates the process.
- $usr2
- ;;; Write on a pipe with no one to read it.
- ;;; Action: Ignored.
- $pipe
- ;;; Alarm clock.
- ;;; Action: Terminates the process.
- $alrm
- ;;; Termination signal.
- ;;; Action: Terminates the process.
- $term
- ;;; Child process terminated, stopped, or continued.
- ;;; Action: Ignored.
- $chld
- ;;; Continue executing, if stopped.
- ;;; Action: Continues executing, if stopped.
- $cont
- ;;; Stop executing.
- ;;; Action: Stops executing.
- $stop
- ;;; Terminal stop signal.
- ;;; Action: Stops executing.
- $tstp
- ;;; Background process attempting read.
- ;;; Action: Stops executing.
- $ttin
- ;;; Background process attempting write.
- ;;; Action: Stops executing.
- $ttou
- ;;; High bandwidth data is available at a socket.
- ;;; Action: Ignored.
- $urg
- ;;; CPU time limit exceeded.
- ;;; Action: Terminates the process.
- $xcpu
- ;;; File size limit exceeded.
- ;;; Action: Terminates the process.
- $xfsz
- ;;; Virtual timer expired.
- ;;; Action: Terminates the process.
- $vtalrm
- ;;; Profiling timer expired.
- ;;; Action: Terminates the process.
- $prof
- ;;; Window changed.
- ;;; Action: Ignored.
- $winch
- ;;; I/O possible.
- ;;; Action: Terminates the process.
- $poll
- ;;; Power failure.
- ;;; Action: Terminates the process.
- $pwr
- ;;; Bad system call.
- ;;; Action: Terminates the process.
- $sys
- )
-)
-
-;;; Flags provided to `sock_recv`.
-(typename $riflags
- (flags (@witx repr u16)
- ;;; Returns the message without removing it from the socket's receive queue.
- $recv_peek
- ;;; On byte-stream sockets, block until the full amount of data can be returned.
- $recv_waitall
- )
-)
-
-;;; Flags returned by `sock_recv`.
-(typename $roflags
- (flags (@witx repr u16)
- ;;; Returned by `sock_recv`: Message data has been truncated.
- $recv_data_truncated
- )
-)
-
-;;; Flags provided to `sock_send`. As there are currently no flags
-;;; defined, it must be set to zero.
-(typename $siflags u16)
-
-;;; Which channels on a socket to shut down.
-(typename $sdflags
- (flags (@witx repr u8)
- ;;; Disables further receive operations.
- $rd
- ;;; Disables further send operations.
- $wr
- )
-)
-
-;;; Identifiers for preopened capabilities.
-(typename $preopentype
- (enum (@witx tag u8)
- ;;; A pre-opened directory.
- $dir
- )
-)
-
-;;; The contents of a $prestat when type is `preopentype::dir`.
-(typename $prestat_dir
- (record
- ;;; The length of the directory name for use with `fd_prestat_dir_name`.
- (field $pr_name_len $size)
- )
-)
-
-;;; Information about a pre-opened capability.
-(typename $prestat
- (union (@witx tag $preopentype)
- $prestat_dir
- )
-)
-
diff --git a/crates/wasi-common/witx/preview1/wasi_snapshot_preview1.witx b/crates/wasi-common/witx/preview1/wasi_snapshot_preview1.witx
deleted file mode 100644
index f9e2aa2c67..0000000000
--- a/crates/wasi-common/witx/preview1/wasi_snapshot_preview1.witx
+++ /dev/null
@@ -1,521 +0,0 @@
-;; WASI Preview. This is an evolution of the API that WASI initially
-;; launched with.
-;;
-;; Some content here is derived from [CloudABI](https://github.com/NuxiNL/cloudabi).
-;;
-;; This is a `witx` file. See [here](https://github.com/WebAssembly/WASI/blob/main/legacy/tools/witx-docs.md)
-;; for an explanation of what that means.
-
-(use "typenames.witx")
-
-(module $wasi_snapshot_preview1
- ;;; Linear memory to be accessed by WASI functions that need it.
- (import "memory" (memory))
-
- ;;; Read command-line argument data.
- ;;; The size of the array should match that returned by `args_sizes_get`.
- ;;; Each argument is expected to be `\0` terminated.
- (@interface func (export "args_get")
- (param $argv (@witx pointer (@witx pointer u8)))
- (param $argv_buf (@witx pointer u8))
- (result $error (expected (error $errno)))
- )
- ;;; Return command-line argument data sizes.
- (@interface func (export "args_sizes_get")
- ;;; Returns the number of arguments and the size of the argument string
- ;;; data, or an error.
- (result $error (expected (tuple $size $size) (error $errno)))
- )
-
- ;;; Read environment variable data.
- ;;; The sizes of the buffers should match that returned by `environ_sizes_get`.
- ;;; Key/value pairs are expected to be joined with `=`s, and terminated with `\0`s.
- (@interface func (export "environ_get")
- (param $environ (@witx pointer (@witx pointer u8)))
- (param $environ_buf (@witx pointer u8))
- (result $error (expected (error $errno)))
- )
- ;;; Return environment variable data sizes.
- (@interface func (export "environ_sizes_get")
- ;;; Returns the number of environment variable arguments and the size of the
- ;;; environment variable data.
- (result $error (expected (tuple $size $size) (error $errno)))
- )
-
- ;;; Return the resolution of a clock.
- ;;; Implementations are required to provide a non-zero value for supported clocks. For unsupported clocks,
- ;;; return `errno::inval`.
- ;;; Note: This is similar to `clock_getres` in POSIX.
- (@interface func (export "clock_res_get")
- ;;; The clock for which to return the resolution.
- (param $id $clockid)
- ;;; The resolution of the clock, or an error if one happened.
- (result $error (expected $timestamp (error $errno)))
- )
- ;;; Return the time value of a clock.
- ;;; Note: This is similar to `clock_gettime` in POSIX.
- (@interface func (export "clock_time_get")
- ;;; The clock for which to return the time.
- (param $id $clockid)
- ;;; The maximum lag (exclusive) that the returned time value may have, compared to its actual value.
- (param $precision $timestamp)
- ;;; The time value of the clock.
- (result $error (expected $timestamp (error $errno)))
- )
-
- ;;; Provide file advisory information on a file descriptor.
- ;;; Note: This is similar to `posix_fadvise` in POSIX.
- (@interface func (export "fd_advise")
- (param $fd $fd)
- ;;; The offset within the file to which the advisory applies.
- (param $offset $filesize)
- ;;; The length of the region to which the advisory applies.
- (param $len $filesize)
- ;;; The advice.
- (param $advice $advice)
- (result $error (expected (error $errno)))
- )
-
- ;;; Force the allocation of space in a file.
- ;;; Note: This is similar to `posix_fallocate` in POSIX.
- (@interface func (export "fd_allocate")
- (param $fd $fd)
- ;;; The offset at which to start the allocation.
- (param $offset $filesize)
- ;;; The length of the area that is allocated.
- (param $len $filesize)
- (result $error (expected (error $errno)))
- )
-
- ;;; Close a file descriptor.
- ;;; Note: This is similar to `close` in POSIX.
- (@interface func (export "fd_close")
- (param $fd $fd)
- (result $error (expected (error $errno)))
- )
-
- ;;; Synchronize the data of a file to disk.
- ;;; Note: This is similar to `fdatasync` in POSIX.
- (@interface func (export "fd_datasync")
- (param $fd $fd)
- (result $error (expected (error $errno)))
- )
-
- ;;; Get the attributes of a file descriptor.
- ;;; Note: This returns similar flags to `fsync(fd, F_GETFL)` in POSIX, as well as additional fields.
- (@interface func (export "fd_fdstat_get")
- (param $fd $fd)
- ;;; The buffer where the file descriptor's attributes are stored.
- (result $error (expected $fdstat (error $errno)))
- )
-
- ;;; Adjust the flags associated with a file descriptor.
- ;;; Note: This is similar to `fcntl(fd, F_SETFL, flags)` in POSIX.
- (@interface func (export "fd_fdstat_set_flags")
- (param $fd $fd)
- ;;; The desired values of the file descriptor flags.
- (param $flags $fdflags)
- (result $error (expected (error $errno)))
- )
-
- ;;; Adjust the rights associated with a file descriptor.
- ;;; This can only be used to remove rights, and returns `errno::notcapable` if called in a way that would attempt to add rights
- (@interface func (export "fd_fdstat_set_rights")
- (param $fd $fd)
- ;;; The desired rights of the file descriptor.
- (param $fs_rights_base $rights)
- (param $fs_rights_inheriting $rights)
- (result $error (expected (error $errno)))
- )
-
- ;;; Return the attributes of an open file.
- (@interface func (export "fd_filestat_get")
- (param $fd $fd)
- ;;; The buffer where the file's attributes are stored.
- (result $error (expected $filestat (error $errno)))
- )
-
- ;;; Adjust the size of an open file. If this increases the file's size, the extra bytes are filled with zeros.
- ;;; Note: This is similar to `ftruncate` in POSIX.
- (@interface func (export "fd_filestat_set_size")
- (param $fd $fd)
- ;;; The desired file size.
- (param $size $filesize)
- (result $error (expected (error $errno)))
- )
-
- ;;; Adjust the timestamps of an open file or directory.
- ;;; Note: This is similar to `futimens` in POSIX.
- (@interface func (export "fd_filestat_set_times")
- (param $fd $fd)
- ;;; The desired values of the data access timestamp.
- (param $atim $timestamp)
- ;;; The desired values of the data modification timestamp.
- (param $mtim $timestamp)
- ;;; A bitmask indicating which timestamps to adjust.
- (param $fst_flags $fstflags)
- (result $error (expected (error $errno)))
- )
-
- ;;; Read from a file descriptor, without using and updating the file descriptor's offset.
- ;;; Note: This is similar to `preadv` in POSIX.
- (@interface func (export "fd_pread")
- (param $fd $fd)
- ;;; List of scatter/gather vectors in which to store data.
- (param $iovs $iovec_array)
- ;;; The offset within the file at which to read.
- (param $offset $filesize)
- ;;; The number of bytes read.
- (result $error (expected $size (error $errno)))
- )
-
- ;;; Return a description of the given preopened file descriptor.
- (@interface func (export "fd_prestat_get")
- (param $fd $fd)
- ;;; The buffer where the description is stored.
- (result $error (expected $prestat (error $errno)))
- )
-
- ;;; Return a description of the given preopened file descriptor.
- (@interface func (export "fd_prestat_dir_name")
- (param $fd $fd)
- ;;; A buffer into which to write the preopened directory name.
- (param $path (@witx pointer u8))
- (param $path_len $size)
- (result $error (expected (error $errno)))
- )
-
- ;;; Write to a file descriptor, without using and updating the file descriptor's offset.
- ;;; Note: This is similar to `pwritev` in POSIX.
- (@interface func (export "fd_pwrite")
- (param $fd $fd)
- ;;; List of scatter/gather vectors from which to retrieve data.
- (param $iovs $ciovec_array)
- ;;; The offset within the file at which to write.
- (param $offset $filesize)
- ;;; The number of bytes written.
- (result $error (expected $size (error $errno)))
- )
-
- ;;; Read from a file descriptor.
- ;;; Note: This is similar to `readv` in POSIX.
- (@interface func (export "fd_read")
- (param $fd $fd)
- ;;; List of scatter/gather vectors to which to store data.
- (param $iovs $iovec_array)
- ;;; The number of bytes read.
- (result $error (expected $size (error $errno)))
- )
-
- ;;; Read directory entries from a directory.
- ;;; When successful, the contents of the output buffer consist of a sequence of
- ;;; directory entries. Each directory entry consists of a `dirent` object,
- ;;; followed by `dirent::d_namlen` bytes holding the name of the directory
- ;;; entry.
- ;;
- ;;; This function fills the output buffer as much as possible, potentially
- ;;; truncating the last directory entry. This allows the caller to grow its
- ;;; read buffer size in case it's too small to fit a single large directory
- ;;; entry, or skip the oversized directory entry.
- (@interface func (export "fd_readdir")
- (param $fd $fd)
- ;;; The buffer where directory entries are stored
- (param $buf (@witx pointer u8))
- (param $buf_len $size)
- ;;; The location within the directory to start reading
- (param $cookie $dircookie)
- ;;; The number of bytes stored in the read buffer. If less than the size of the read buffer, the end of the directory has been reached.
- (result $error (expected $size (error $errno)))
- )
-
- ;;; Atomically replace a file descriptor by renumbering another file descriptor.
- ;;
- ;;; Due to the strong focus on thread safety, this environment does not provide
- ;;; a mechanism to duplicate or renumber a file descriptor to an arbitrary
- ;;; number, like `dup2()`. This would be prone to race conditions, as an actual
- ;;; file descriptor with the same number could be allocated by a different
- ;;; thread at the same time.
- ;;
- ;;; This function provides a way to atomically renumber file descriptors, which
- ;;; would disappear if `dup2()` were to be removed entirely.
- (@interface func (export "fd_renumber")
- (param $fd $fd)
- ;;; The file descriptor to overwrite.
- (param $to $fd)
- (result $error (expected (error $errno)))
- )
-
- ;;; Move the offset of a file descriptor.
- ;;; Note: This is similar to `lseek` in POSIX.
- (@interface func (export "fd_seek")
- (param $fd $fd)
- ;;; The number of bytes to move.
- (param $offset $filedelta)
- ;;; The base from which the offset is relative.
- (param $whence $whence)
- ;;; The new offset of the file descriptor, relative to the start of the file.
- (result $error (expected $filesize (error $errno)))
- )
-
- ;;; Synchronize the data and metadata of a file to disk.
- ;;; Note: This is similar to `fsync` in POSIX.
- (@interface func (export "fd_sync")
- (param $fd $fd)
- (result $error (expected (error $errno)))
- )
-
- ;;; Return the current offset of a file descriptor.
- ;;; Note: This is similar to `lseek(fd, 0, SEEK_CUR)` in POSIX.
- (@interface func (export "fd_tell")
- (param $fd $fd)
- ;;; The current offset of the file descriptor, relative to the start of the file.
- (result $error (expected $filesize (error $errno)))
- )
-
- ;;; Write to a file descriptor.
- ;;; Note: This is similar to `writev` in POSIX.
- (@interface func (export "fd_write")
- (param $fd $fd)
- ;;; List of scatter/gather vectors from which to retrieve data.
- (param $iovs $ciovec_array)
- (result $error (expected $size (error $errno)))
- )
-
- ;;; Create a directory.
- ;;; Note: This is similar to `mkdirat` in POSIX.
- (@interface func (export "path_create_directory")
- (param $fd $fd)
- ;;; The path at which to create the directory.
- (param $path string)
- (result $error (expected (error $errno)))
- )
-
- ;;; Return the attributes of a file or directory.
- ;;; Note: This is similar to `stat` in POSIX.
- (@interface func (export "path_filestat_get")
- (param $fd $fd)
- ;;; Flags determining the method of how the path is resolved.
- (param $flags $lookupflags)
- ;;; The path of the file or directory to inspect.
- (param $path string)
- ;;; The buffer where the file's attributes are stored.
- (result $error (expected $filestat (error $errno)))
- )
-
- ;;; Adjust the timestamps of a file or directory.
- ;;; Note: This is similar to `utimensat` in POSIX.
- (@interface func (export "path_filestat_set_times")
- (param $fd $fd)
- ;;; Flags determining the method of how the path is resolved.
- (param $flags $lookupflags)
- ;;; The path of the file or directory to operate on.
- (param $path string)
- ;;; The desired values of the data access timestamp.
- (param $atim $timestamp)
- ;;; The desired values of the data modification timestamp.
- (param $mtim $timestamp)
- ;;; A bitmask indicating which timestamps to adjust.
- (param $fst_flags $fstflags)
- (result $error (expected (error $errno)))
- )
-
- ;;; Create a hard link.
- ;;; Note: This is similar to `linkat` in POSIX.
- (@interface func (export "path_link")
- (param $old_fd $fd)
- ;;; Flags determining the method of how the path is resolved.
- (param $old_flags $lookupflags)
- ;;; The source path from which to link.
- (param $old_path string)
- ;;; The working directory at which the resolution of the new path starts.
- (param $new_fd $fd)
- ;;; The destination path at which to create the hard link.
- (param $new_path string)
- (result $error (expected (error $errno)))
- )
-
- ;;; Open a file or directory.
- ;;
- ;;; The returned file descriptor is not guaranteed to be the lowest-numbered
- ;;; file descriptor not currently open; it is randomized to prevent
- ;;; applications from depending on making assumptions about indexes, since this
- ;;; is error-prone in multi-threaded contexts. The returned file descriptor is
- ;;; guaranteed to be less than 2**31.
- ;;
- ;;; Note: This is similar to `openat` in POSIX.
- (@interface func (export "path_open")
- (param $fd $fd)
- ;;; Flags determining the method of how the path is resolved.
- (param $dirflags $lookupflags)
- ;;; The relative path of the file or directory to open, relative to the
- ;;; `path_open::fd` directory.
- (param $path string)
- ;;; The method by which to open the file.
- (param $oflags $oflags)
- ;;; The initial rights of the newly created file descriptor. The
- ;;; implementation is allowed to return a file descriptor with fewer rights
- ;;; than specified, if and only if those rights do not apply to the type of
- ;;; file being opened.
- ;;
- ;;; The *base* rights are rights that will apply to operations using the file
- ;;; descriptor itself, while the *inheriting* rights are rights that apply to
- ;;; file descriptors derived from it.
- (param $fs_rights_base $rights)
- (param $fs_rights_inheriting $rights)
- (param $fdflags $fdflags)
- ;;; The file descriptor of the file that has been opened.
- (result $error (expected $fd (error $errno)))
- )
-
- ;;; Read the contents of a symbolic link.
- ;;; Note: This is similar to `readlinkat` in POSIX.
- (@interface func (export "path_readlink")
- (param $fd $fd)
- ;;; The path of the symbolic link from which to read.
- (param $path string)
- ;;; The buffer to which to write the contents of the symbolic link.
- (param $buf (@witx pointer u8))
- (param $buf_len $size)
- ;;; The number of bytes placed in the buffer.
- (result $error (expected $size (error $errno)))
- )
-
- ;;; Remove a directory.
- ;;; Return `errno::notempty` if the directory is not empty.
- ;;; Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX.
- (@interface func (export "path_remove_directory")
- (param $fd $fd)
- ;;; The path to a directory to remove.
- (param $path string)
- (result $error (expected (error $errno)))
- )
-
- ;;; Rename a file or directory.
- ;;; Note: This is similar to `renameat` in POSIX.
- (@interface func (export "path_rename")
- (param $fd $fd)
- ;;; The source path of the file or directory to rename.
- (param $old_path string)
- ;;; The working directory at which the resolution of the new path starts.
- (param $new_fd $fd)
- ;;; The destination path to which to rename the file or directory.
- (param $new_path string)
- (result $error (expected (error $errno)))
- )
-
- ;;; Create a symbolic link.
- ;;; Note: This is similar to `symlinkat` in POSIX.
- (@interface func (export "path_symlink")
- ;;; The contents of the symbolic link.
- (param $old_path string)
- (param $fd $fd)
- ;;; The destination path at which to create the symbolic link.
- (param $new_path string)
- (result $error (expected (error $errno)))
- )
-
-
- ;;; Unlink a file.
- ;;; Return `errno::isdir` if the path refers to a directory.
- ;;; Note: This is similar to `unlinkat(fd, path, 0)` in POSIX.
- (@interface func (export "path_unlink_file")
- (param $fd $fd)
- ;;; The path to a file to unlink.
- (param $path string)
- (result $error (expected (error $errno)))
- )
-
- ;;; Concurrently poll for the occurrence of a set of events.
- (@interface func (export "poll_oneoff")
- ;;; The events to which to subscribe.
- (param $in (@witx const_pointer $subscription))
- ;;; The events that have occurred.
- (param $out (@witx pointer $event))
- ;;; Both the number of subscriptions and events.
- (param $nsubscriptions $size)
- ;;; The number of events stored.
- (result $error (expected $size (error $errno)))
- )
-
- ;;; Terminate the process normally. An exit code of 0 indicates successful
- ;;; termination of the program. The meanings of other values is dependent on
- ;;; the environment.
- (@interface func (export "proc_exit")
- ;;; The exit code returned by the process.
- (param $rval $exitcode)
- (@witx noreturn)
- )
-
- ;;; Send a signal to the process of the calling thread.
- ;;; Note: This is similar to `raise` in POSIX.
- (@interface func (export "proc_raise")
- ;;; The signal condition to trigger.
- (param $sig $signal)
- (result $error (expected (error $errno)))
- )
-
- ;;; Temporarily yield execution of the calling thread.
- ;;; Note: This is similar to `sched_yield` in POSIX.
- (@interface func (export "sched_yield")
- (result $error (expected (error $errno)))
- )
-
- ;;; Write high-quality random data into a buffer.
- ;;; This function blocks when the implementation is unable to immediately
- ;;; provide sufficient high-quality random data.
- ;;; This function may execute slowly, so when large mounts of random data are
- ;;; required, it's advisable to use this function to seed a pseudo-random
- ;;; number generator, rather than to provide the random data directly.
- (@interface func (export "random_get")
- ;;; The buffer to fill with random data.
- (param $buf (@witx pointer u8))
- (param $buf_len $size)
- (result $error (expected (error $errno)))
- )
-
- ;;; Accept a new incoming connection.
- ;;; Note: This is similar to `accept` in POSIX.
- (@interface func (export "sock_accept")
- ;;; The listening socket.
- (param $fd $fd)
- ;;; The desired values of the file descriptor flags.
- (param $flags $fdflags)
- ;;; New socket connection
- (result $error (expected $fd (error $errno)))
- )
-
- ;;; Receive a message from a socket.
- ;;; Note: This is similar to `recv` in POSIX, though it also supports reading
- ;;; the data into multiple buffers in the manner of `readv`.
- (@interface func (export "sock_recv")
- (param $fd $fd)
- ;;; List of scatter/gather vectors to which to store data.
- (param $ri_data $iovec_array)
- ;;; Message flags.
- (param $ri_flags $riflags)
- ;;; Number of bytes stored in ri_data and message flags.
- (result $error (expected (tuple $size $roflags) (error $errno)))
- )
-
- ;;; Send a message on a socket.
- ;;; Note: This is similar to `send` in POSIX, though it also supports writing
- ;;; the data from multiple buffers in the manner of `writev`.
- (@interface func (export "sock_send")
- (param $fd $fd)
- ;;; List of scatter/gather vectors to which to retrieve data
- (param $si_data $ciovec_array)
- ;;; Message flags.
- (param $si_flags $siflags)
- ;;; Number of bytes transmitted.
- (result $error (expected $size (error $errno)))
- )
-
- ;;; Shut down socket send and receive channels.
- ;;; Note: This is similar to `shutdown` in POSIX.
- (@interface func (export "sock_shutdown")
- (param $fd $fd)
- ;;; Which channels on the socket to shut down.
- (param $how $sdflags)
- (result $error (expected (error $errno)))
- )
-)
diff --git a/crates/wasi-threads/Cargo.toml b/crates/wasi-threads/Cargo.toml
deleted file mode 100644
index 18b29e4bc0..0000000000
--- a/crates/wasi-threads/Cargo.toml
+++ /dev/null
@@ -1,23 +0,0 @@
-[package]
-name = "wasmtime-wasi-threads"
-version.workspace = true
-authors.workspace = true
-description = "Wasmtime implementation of the wasi-threads API"
-documentation = "https://docs.rs/wasmtime-wasi-nn"
-license = "Apache-2.0 WITH LLVM-exception"
-categories = ["wasm"]
-keywords = ["webassembly", "wasm", "neural-network"]
-repository = "https://github.com/bytecodealliance/wasmtime"
-readme = "README.md"
-edition.workspace = true
-rust-version.workspace = true
-
-[lints]
-workspace = true
-
-[dependencies]
-log = { workspace = true }
-rand = { workspace = true }
-wasi-common = { workspace = true, features = ["exit"]}
-wasmtime = { workspace = true, features = ['threads'] }
-wasmtime-wasi = { workspace = true }
diff --git a/crates/wasi-threads/README.md b/crates/wasi-threads/README.md
deleted file mode 100644
index 31478778e0..0000000000
--- a/crates/wasi-threads/README.md
+++ /dev/null
@@ -1,12 +0,0 @@
-# wasmtime-wasi-threads
-
-Implement the `wasi-threads` [specification] in Wasmtime.
-
-[specification]: https://github.com/WebAssembly/wasi-threads
-
-> Note: this crate is experimental and not yet suitable for use in multi-tenant
-> embeddings. As specified, a trap or WASI exit in one thread must end execution
-> for all threads. Due to the complexity of stopping threads, however, this
-> implementation currently exits the process entirely. This will work for some
-> use cases (e.g., CLI usage) but not for embedders. This warning can be removed
-> once a suitable mechanism is implemented that avoids exiting the process.
diff --git a/crates/wasi-threads/src/lib.rs b/crates/wasi-threads/src/lib.rs
deleted file mode 100644
index 6edb59a1a0..0000000000
--- a/crates/wasi-threads/src/lib.rs
+++ /dev/null
@@ -1,206 +0,0 @@
-//! Implement [`wasi-threads`].
-//!
-//! [`wasi-threads`]: https://github.com/WebAssembly/wasi-threads
-
-use std::panic::{AssertUnwindSafe, catch_unwind};
-use std::sync::Arc;
-use std::sync::atomic::{AtomicI32, Ordering};
-use std::thread;
-use wasmtime::{
- Caller, ExternType, InstancePre, Linker, Module, Result, SharedMemory, Store, format_err,
-};
-
-// This name is a function export designated by the wasi-threads specification:
-// https://github.com/WebAssembly/wasi-threads/#detailed-design-discussion
-const WASI_ENTRY_POINT: &str = "wasi_thread_start";
-
-pub struct WasiThreadsCtx<T> {
- instance_pre: Arc<InstancePre<T>>,
- tid: AtomicI32,
- use_async: bool,
-}
-
-impl<T: Clone + Send + 'static> WasiThreadsCtx<T> {
- pub fn new(module: Module, linker: Arc<Linker<T>>, use_async: bool) -> Result<Self> {
- let instance_pre = Arc::new(linker.instantiate_pre(&module)?);
- let tid = AtomicI32::new(0);
- Ok(Self {
- instance_pre,
- tid,
- use_async,
- })
- }
-
- pub fn spawn(&self, host: T, thread_start_arg: i32) -> Result<i32> {
- let instance_pre = self.instance_pre.clone();
-
- // Check that the thread entry point is present. Why here? If we check
- // for this too early, then we cannot accept modules that do not have an
- // entry point but never spawn a thread. As pointed out in
- // https://github.com/bytecodealliance/wasmtime/issues/6153, checking
- // the entry point here allows wasi-threads to be compatible with more
- // modules.
- //
- // As defined in the wasi-threads specification, returning a negative
- // result here indicates to the guest module that the spawn failed.
- if !has_entry_point(instance_pre.module()) {
- log::error!(
- "failed to find a wasi-threads entry point function; expected an export with name: {WASI_ENTRY_POINT}"
- );
- return Ok(-1);
- }
- if !has_correct_signature(instance_pre.module()) {
- log::error!(
- "the exported entry point function has an incorrect signature: expected `(i32, i32) -> ()`"
- );
- return Ok(-1);
- }
-
- let wasi_thread_id = self.next_thread_id();
- if wasi_thread_id.is_none() {
- log::error!("ran out of valid thread IDs");
- return Ok(-1);
- }
- let wasi_thread_id = wasi_thread_id.unwrap();
-
- // Start a Rust thread running a new instance of the current module.
- let builder = thread::Builder::new().name(format!("wasi-thread-{wasi_thread_id}"));
- let use_async = self.use_async;
- builder.spawn(move || {
- // Catch any panic failures in host code; e.g., if a WASI module
- // were to crash, we want all threads to exit, not just this one.
- let result = catch_unwind(AssertUnwindSafe(|| {
- // Each new instance is created in its own store.
- let mut store = Store::new(&instance_pre.module().engine(), host);
-
- let instance = if use_async {
- wasmtime_wasi::runtime::in_tokio(instance_pre.instantiate_async(&mut store))
- } else {
- instance_pre.instantiate(&mut store)
- }
- .unwrap();
-
- let thread_entry_point = instance
- .get_typed_func::<(i32, i32), ()>(&mut store, WASI_ENTRY_POINT)
- .unwrap();
-
- // Start the thread's entry point. Any traps or calls to
- // `proc_exit`, by specification, should end execution for all
- // threads. This code uses `process::exit` to do so, which is
- // what the user expects from the CLI but probably not in a
- // Wasmtime embedding.
- log::trace!(
- "spawned thread id = {wasi_thread_id}; calling start function `{WASI_ENTRY_POINT}` with: {thread_start_arg}"
- );
- let res = if use_async {
- wasmtime_wasi::runtime::in_tokio(
- thread_entry_point
- .call_async(&mut store, (wasi_thread_id, thread_start_arg)),
- )
- } else {
- thread_entry_point.call(&mut store, (wasi_thread_id, thread_start_arg))
- };
- match res {
- Ok(_) => log::trace!("exiting thread id = {wasi_thread_id} normally"),
- Err(e) => {
- log::trace!("exiting thread id = {wasi_thread_id} due to error");
- let e = wasi_common::maybe_exit_on_error(e);
- eprintln!("Error: {e:?}");
- std::process::exit(1);
- }
- }
- }));
-
- if let Err(e) = result {
- eprintln!("wasi-thread-{wasi_thread_id} panicked: {e:?}");
- std::process::exit(1);
- }
- })?;
-
- Ok(wasi_thread_id)
- }
-
- /// Helper for generating valid WASI thread IDs (TID).
- ///
- /// Callers of `wasi_thread_spawn` expect a TID in range of 0 < TID <= 0x1FFFFFFF
- /// to indicate a successful spawning of the thread whereas a negative
- /// return value indicates an failure to spawn.
- fn next_thread_id(&self) -> Option<i32> {
- match self
- .tid
- .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |v| match v {
- ..=0x1ffffffe => Some(v + 1),
- _ => None,
- }) {
- Ok(v) => Some(v + 1),
- Err(_) => None,
- }
- }
-}
-
-/// Manually add the WASI `thread_spawn` function to the linker.
-///
-/// It is unclear what namespace the `wasi-threads` proposal should live under:
-/// it is not clear if it should be included in any of the `preview*` releases
-/// so for the time being its module namespace is simply `"wasi"` (TODO).
-pub fn add_to_linker<T: Clone + Send + 'static>(
- linker: &mut wasmtime::Linker<T>,
- store: &wasmtime::Store<T>,
- module: &Module,
- get_cx: impl Fn(&mut T) -> &WasiThreadsCtx<T> + Send + Sync + Copy + 'static,
-) -> wasmtime::Result<()> {
- linker.func_wrap(
- "wasi",
- "thread-spawn",
- move |mut caller: Caller<'_, T>, start_arg: i32| -> i32 {
- log::trace!("new thread requested via `wasi::thread_spawn` call");
- let host = caller.data().clone();
- let ctx = get_cx(caller.data_mut());
- match ctx.spawn(host, start_arg) {
- Ok(thread_id) => {
- assert!(thread_id >= 0, "thread_id = {thread_id}");
- thread_id
- }
- Err(e) => {
- log::error!("failed to spawn thread: {e}");
- -1
- }
- }
- },
- )?;
-
- // Find the shared memory import and satisfy it with a newly-created shared
- // memory import.
- for import in module.imports() {
- if let Some(m) = import.ty().memory() {
- if m.is_shared() {
- let mem = SharedMemory::new(module.engine(), m.clone())?;
- linker.define(store, import.module(), import.name(), mem.clone())?;
- } else {
- return Err(format_err!(
- "memory was not shared; a `wasi-threads` must import \
- a shared memory as \"memory\""
- ));
- }
- }
- }
- Ok(())
-}
-
-/// Check if wasi-threads' `wasi_thread_start` export is present.
-fn has_entry_point(module: &Module) -> bool {
- module.get_export(WASI_ENTRY_POINT).is_some()
-}
-
-/// Check if the entry function has the correct signature `(i32, i32) -> ()`.
-fn has_correct_signature(module: &Module) -> bool {
- match module.get_export(WASI_ENTRY_POINT) {
- Some(ExternType::Func(ty)) => {
- ty.params().len() == 2
- && ty.params().nth(0).unwrap().is_i32()
- && ty.params().nth(1).unwrap().is_i32()
- && ty.results().len() == 0
- }
- _ => false,
- }
-}
diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt
index 6857aa416b..5959fa3e81 100644
--- a/examples/CMakeLists.txt
+++ b/examples/CMakeLists.txt
@@ -111,7 +111,7 @@ if (BUILD_RUST_EXAMPLES)
create_rust_test(wasip1-async)
create_rust_test(wasip2)
create_rust_test(wasip2-async)
- create_rust_test(tokio wasi-common/tokio)
+ create_rust_test(tokio)
create_rust_test(component)
create_rust_test(resource-component)
endif()
diff --git a/scripts/publish.rs b/scripts/publish.rs
index 2f33c6c561..522efba7b7 100644
--- a/scripts/publish.rs
+++ b/scripts/publish.rs
@@ -63,9 +63,7 @@ const CRATES_TO_PUBLISH: &[&str] = &[
"winch-codegen",
"wasmtime-internal-winch",
"wasmtime",
- // wasi-common/wiggle
"wiggle",
- "wasi-common",
// other misc wasmtime crates
"wasmtime-wasi-io",
"wasmtime-wasi",
diff --git a/src/commands/run.rs b/src/commands/run.rs
index 1a69fab547..a43218c506 100644
--- a/src/commands/run.rs
+++ b/src/commands/run.rs
@@ -11,9 +11,7 @@ use std::ffi::OsString;
use std::path::{Path, PathBuf};
#[cfg(feature = "debug")]
use std::pin::Pin;
-use std::sync::{Arc, Mutex};
use std::thread;
-use wasi_common::sync::{Dir, TcpListener, WasiCtxBuilder, ambient_authority};
use wasmtime::{
Engine, Error, Func, Module, Result, Store, StoreLimits, Val, ValType, bail,
error::Context as _, format_err,
@@ -28,8 +26,6 @@ use wasmtime_wasi_http::WasiHttpCtx;
use wasmtime_wasi_keyvalue::{WasiKeyValue, WasiKeyValueCtx, WasiKeyValueCtxBuilder};
#[cfg(feature = "wasi-nn")]
use wasmtime_wasi_nn::wit::WasiNnView;
-#[cfg(feature = "wasi-threads")]
-use wasmtime_wasi_threads::WasiThreadsCtx;
fn parse_preloads(s: &str) -> Result<(String, PathBuf)> {
let parts: Vec<&str> = s.splitn(2, '=').collect();
@@ -293,7 +289,8 @@ impl RunCommand {
move |store| {
Box::pin(async move {
let engine_clone = store.engine().clone();
- let cancel = Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let cancel =
+ std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let cancel_clone = cancel.clone();
let epoch_thread = thread::spawn(move || {
while !cancel_clone.load(std::sync::atomic::Ordering::Relaxed) {
@@ -381,7 +378,7 @@ impl RunCommand {
let host = Host::default();
let mut store = Store::new(&engine, host);
- self.populate_with_wasi(&mut linker, &mut store, &main)?;
+ self.populate_with_wasi(&mut linker, &mut store)?;
store.data_mut().limits = self.run.store_limits();
store.limiter(|t| &mut t.limits);
@@ -488,9 +485,7 @@ impl RunCommand {
// Exit the process if Wasmtime understands the error;
// otherwise, fall back on Rust's default error printing/return
// code.
- if store.data().legacy_p1_ctx.is_some() {
- return Err(wasi_common::maybe_exit_on_error(e));
- } else if store.data().wasip1_ctx.is_some() {
+ if store.data().wasip1_ctx.is_some() {
if let Some(exit) = e.downcast_ref::<wasmtime_wasi::I32Exit>() {
std::process::exit(exit.0);
}
@@ -599,19 +594,19 @@ impl RunCommand {
let module_name = self.module_and_args[0].to_str().unwrap_or("<main module>");
store.data_mut().guest_profiler = match main_target {
- RunTarget::Core(_m) => Some(Arc::new(GuestProfiler::new(
+ RunTarget::Core(_m) => Some(GuestProfiler::new(
store.engine(),
module_name,
interval,
profiled_modules,
- )?)),
- RunTarget::Component(component) => Some(Arc::new(GuestProfiler::new_component(
+ )?),
+ RunTarget::Component(component) => Some(GuestProfiler::new_component(
store.engine(),
module_name,
interval,
component.clone(),
profiled_modules,
- )?)),
+ )?),
};
fn sample(
@@ -619,10 +614,7 @@ impl RunCommand {
f: impl FnOnce(&mut GuestProfiler, StoreContext<Host>),
) {
let mut profiler = store.data_mut().guest_profiler.take().unwrap();
- f(
- Arc::get_mut(&mut profiler).expect("profiling doesn't support threads yet"),
- store.as_context(),
- );
+ f(&mut profiler, store.as_context());
store.data_mut().guest_profiler = Some(profiler);
}
@@ -664,8 +656,7 @@ impl RunCommand {
let path = path.to_string();
Ok(Box::new(move |store| {
- let profiler = Arc::try_unwrap(store.data_mut().guest_profiler.take().unwrap())
- .expect("profiling doesn't support threads yet");
+ let profiler = store.data_mut().guest_profiler.take().unwrap();
if let Err(e) = std::fs::File::create(&path)
.map_err(wasmtime::Error::new)
.and_then(|output| profiler.finish(std::io::BufWriter::new(output)))
@@ -1104,12 +1095,7 @@ impl RunCommand {
}
/// Populates the given `Linker` with WASI APIs.
- fn populate_with_wasi(
- &self,
- linker: &mut CliLinker,
- store: &mut Store<Host>,
- module: &RunTarget,
- ) -> Result<()> {
+ fn populate_with_wasi(&self, linker: &mut CliLinker, store: &mut Store<Host>) -> Result<()> {
self.run.validate_p3_option()?;
let cli = self.run.validate_cli_enabled()?;
@@ -1117,26 +1103,13 @@ impl RunCommand {
match linker {
CliLinker::Core(linker) => {
match (self.run.common.wasi.preview2, self.run.common.wasi.threads) {
- // If preview2 is explicitly disabled, or if threads
- // are enabled, then use the historical preview1
- // implementation.
(Some(false), _) | (None, Some(true)) => {
let flag = if self.run.common.wasi.preview2 == Some(false) {
"-Spreview2=n"
} else {
"-Sthreads"
};
- eprintln!(
- "\
-WARNING: the `{flag}` flag will be a hard error in Wasmtime 47.0.0 on 2026-07-20. \
-For more information see https://github.com/bytecodealliance/rfcs/pull/47 and \
-please reach out on Zulip with questions.
- "
- );
- wasi_common::tokio::add_to_linker(linker, |host| {
- host.legacy_p1_ctx.as_mut().unwrap()
- })?;
- self.set_legacy_p1_ctx(store)?;
+ bail!("the `{flag}` flag is no longer supported")
}
// If preview2 was explicitly requested, always use it.
// Otherwise use it so long as threads are disabled.
@@ -1172,28 +1145,20 @@ please reach out on Zulip with questions.
match linker {
CliLinker::Core(linker) => {
wasmtime_wasi_nn::witx::add_to_linker(linker, |host| {
- Arc::get_mut(host.wasi_nn_witx.as_mut().unwrap())
- .expect("wasi-nn is not implemented with multi-threading support")
+ host.wasi_nn_witx.as_mut().unwrap()
})?;
- store.data_mut().wasi_nn_witx = Some(Arc::new(
- wasmtime_wasi_nn::witx::WasiNnCtx::new(backends, registry),
- ));
+ store.data_mut().wasi_nn_witx =
+ Some(wasmtime_wasi_nn::witx::WasiNnCtx::new(backends, registry));
}
#[cfg(feature = "component-model")]
CliLinker::Component(linker) => {
wasmtime_wasi_nn::wit::add_to_linker(linker, |h: &mut Host| {
let ctx = h.wasip1_ctx.as_mut().expect("wasi is not configured");
- let ctx = Arc::get_mut(ctx)
- .expect("wasmtime_wasi is not compatible with threads")
- .get_mut()
- .unwrap();
- let nn_ctx = Arc::get_mut(h.wasi_nn_wit.as_mut().unwrap())
- .expect("wasi-nn is not implemented with multi-threading support");
+ let nn_ctx = h.wasi_nn_wit.as_mut().unwrap();
WasiNnView::new(ctx.ctx().table, nn_ctx)
})?;
- store.data_mut().wasi_nn_wit = Some(Arc::new(
- wasmtime_wasi_nn::wit::WasiNnCtx::new(backends, registry),
- ));
+ store.data_mut().wasi_nn_wit =
+ Some(wasmtime_wasi_nn::wit::WasiNnCtx::new(backends, registry));
}
}
}
@@ -1223,9 +1188,9 @@ please reach out on Zulip with questions.
);
wasmtime_wasi_config::add_to_linker(linker, |h| {
- WasiConfig::new(Arc::get_mut(h.wasi_config.as_mut().unwrap()).unwrap())
+ WasiConfig::new(h.wasi_config.as_mut().unwrap())
})?;
- store.data_mut().wasi_config = Some(Arc::new(vars));
+ store.data_mut().wasi_config = Some(vars);
}
}
}
@@ -1258,45 +1223,16 @@ please reach out on Zulip with questions.
wasmtime_wasi_keyvalue::add_to_linker(linker, |h| {
let ctx = h.wasip1_ctx.as_mut().expect("wasip2 is not configured");
- let ctx = Arc::get_mut(ctx).unwrap().get_mut().unwrap();
- WasiKeyValue::new(
- Arc::get_mut(h.wasi_keyvalue.as_mut().unwrap()).unwrap(),
- ctx.ctx().table,
- )
+ WasiKeyValue::new(h.wasi_keyvalue.as_mut().unwrap(), ctx.ctx().table)
})?;
- store.data_mut().wasi_keyvalue = Some(Arc::new(ctx));
+ store.data_mut().wasi_keyvalue = Some(ctx);
}
}
}
}
if self.run.common.wasi.threads == Some(true) {
- #[cfg(not(feature = "wasi-threads"))]
- {
- // Silence the unused warning for `module` as it is only used in the
- // conditionally-compiled wasi-threads.
- let _ = &module;
-
- bail!(
- "Cannot enable wasi-threads when the binary is not compiled with this feature."
- );
- }
- #[cfg(feature = "wasi-threads")]
- {
- let linker = match linker {
- CliLinker::Core(linker) => linker,
- _ => bail!("wasi-threads does not support components yet"),
- };
- let module = module.unwrap_core();
- wasmtime_wasi_threads::add_to_linker(linker, store, &module, |host| {
- host.wasi_threads.as_ref().unwrap()
- })?;
- store.data_mut().wasi_threads = Some(Arc::new(WasiThreadsCtx::new(
- module.clone(),
- Arc::new(linker.clone()),
- true,
- )?));
- }
+ bail!("support for wasi-threads has been removed from Wasmtime");
}
if self.run.common.wasi.http == Some(true) {
@@ -1319,7 +1255,7 @@ please reach out on Zulip with questions.
}
}
let http = self.run.wasi_http_ctx()?;
- store.data_mut().wasi_http = Some(Arc::new(http));
+ store.data_mut().wasi_http = Some(http);
}
}
@@ -1345,7 +1281,7 @@ please reach out on Zulip with questions.
}
let ctx = wasmtime_wasi_tls::WasiTlsCtxBuilder::new().build();
- store.data_mut().wasi_tls = Some(Arc::new(ctx));
+ store.data_mut().wasi_tls = Some(ctx);
}
}
}
@@ -1354,70 +1290,7 @@ please reach out on Zulip with questions.
Ok(())
}
- fn set_legacy_p1_ctx(&self, store: &mut Store<Host>) -> Result<()> {
- let mut builder = WasiCtxBuilder::new();
- builder.args(&self.compute_argv()?)?;
-
- if self.run.common.wasi.inherit_stdin.unwrap_or(true) {
- builder.inherit_stdin();
- }
- if self.run.common.wasi.inherit_stdout.unwrap_or(true) {
- builder.inherit_stdout();
- }
- if self.run.common.wasi.inherit_stderr.unwrap_or(true) {
- builder.inherit_stderr();
- }
-
- if self.run.common.wasi.inherit_env == Some(true) {
- for (k, v) in std::env::vars() {
- builder.env(&k, &v)?;
- }
- }
- for (key, value) in self.run.vars.iter() {
- let value = match value {
- Some(value) => value.clone(),
- None => match std::env::var_os(key) {
- Some(val) => val
- .into_string()
- .map_err(|_| format_err!("environment variable `{key}` not valid utf-8"))?,
- None => {
- // leave the env var un-set in the guest
- continue;
- }
- },
- };
- builder.env(key, &value)?;
- }
-
- let mut num_fd: usize = 3;
-
- if self.run.common.wasi.listenfd == Some(true) {
- num_fd = ctx_set_listenfd(num_fd, &mut builder)?;
- }
-
- for listener in self.run.compute_preopen_sockets()? {
- let listener = TcpListener::from_std(listener);
- builder.preopened_socket(num_fd as _, listener)?;
- num_fd += 1;
- }
-
- for (host, guest) in self.run.dirs.iter() {
- let dir = Dir::open_ambient_dir(host, ambient_authority())
- .with_context(|| format!("failed to open directory '{host}'"))?;
- builder.preopened_dir(dir, guest)?;
- }
-
- store.data_mut().legacy_p1_ctx = Some(builder.build());
- Ok(())
- }
-
- /// Note the naming here is subtle, but this is effectively setting up a
- /// `wasmtime_wasi::WasiCtx` structure.
- ///
- /// This is stored in `Host` as `WasiP1Ctx` which internally contains the
- /// `WasiCtx` and `ResourceTable` used for WASI implementations. Exactly
- /// which "p" for WASIpN is more a reference to
- /// `wasmtime-wasi`-vs-`wasi-common` here more than anything else.
+ /// Configure `wasmtime_wasi::WasiCtx` and store it in `Host`.
fn set_wasi_ctx(&self, store: &mut Store<Host>) -> Result<()> {
let mut builder = wasmtime_wasi::WasiCtxBuilder::new();
builder.args(&self.compute_argv()?);
@@ -1442,7 +1315,7 @@ please reach out on Zulip with questions.
if let Some(fuel) = self.run.common.wasi.hostcall_fuel {
store.set_hostcall_fuel(fuel);
}
- store.data_mut().wasip1_ctx = Some(Arc::new(Mutex::new(ctx)));
+ store.data_mut().wasip1_ctx = Some(ctx);
Ok(())
}
@@ -1466,70 +1339,42 @@ please reach out on Zulip with questions.
///
/// This structures has a number of contexts used for various WASI proposals.
/// Note that all of them are optional meaning that they're `None` by default
-/// and enabled with various CLI flags (some CLI flags are on-by-default). Note
-/// additionally that this structure is `Clone` to implement the `wasi-threads`
-/// proposal. Many WASI proposals are not compatible with `wasi-threads` so to
-/// model this `Arc` and `Arc<Mutex<T>>` is used for many configurations. If a
-/// WASI proposal is inherently threadsafe it's protected with just an `Arc` to
-/// share its configuration across many threads.
-///
-/// If mutation is required then `Mutex` is used. Note though that the mutex is
-/// not actually locked as access always goes through `Arc::get_mut` which
-/// effectively asserts that there's only one thread. In short much of this is
-/// not compatible with `wasi-threads`.
-#[derive(Default, Clone)]
+/// and enabled with various CLI flags (some CLI flags are on-by-default).
+#[derive(Default)]
pub struct Host {
limits: StoreLimits,
#[cfg(feature = "profiling")]
- guest_profiler: Option<Arc<wasmtime::GuestProfiler>>,
-
- // Legacy wasip1 context using `wasi_common`, not set unless opted-in-to
- // with the CLI.
- legacy_p1_ctx: Option<wasi_common::WasiCtx>,
+ guest_profiler: Option<wasmtime::GuestProfiler>,
// Context for both WASIp1 and WASIp2 (and beyond) for the `wasmtime_wasi`
// crate. This has both `wasmtime_wasi::WasiCtx` as well as a
// `ResourceTable` internally to be used.
- //
- // The Mutex is only needed to satisfy the Sync constraint but we never
- // actually perform any locking on it as we use Mutex::get_mut for every
- // access.
- wasip1_ctx: Option<Arc<Mutex<wasmtime_wasi::p1::WasiP1Ctx>>>,
+ wasip1_ctx: Option<wasmtime_wasi::p1::WasiP1Ctx>,
#[cfg(feature = "wasi-nn")]
- wasi_nn_wit: Option<Arc<wasmtime_wasi_nn::wit::WasiNnCtx>>,
+ wasi_nn_wit: Option<wasmtime_wasi_nn::wit::WasiNnCtx>,
#[cfg(feature = "wasi-nn")]
- wasi_nn_witx: Option<Arc<wasmtime_wasi_nn::witx::WasiNnCtx>>,
+ wasi_nn_witx: Option<wasmtime_wasi_nn::witx::WasiNnCtx>,
- #[cfg(feature = "wasi-threads")]
- wasi_threads: Option<Arc<WasiThreadsCtx<Host>>>,
#[cfg(feature = "wasi-http")]
- wasi_http: Option<Arc<WasiHttpCtx>>,
+ wasi_http: Option<WasiHttpCtx>,
#[cfg(feature = "wasi-http")]
wasi_http_hooks: crate::common::HttpHooks,
#[cfg(feature = "wasi-config")]
- wasi_config: Option<Arc<WasiConfigVariables>>,
+ wasi_config: Option<WasiConfigVariables>,
#[cfg(feature = "wasi-keyvalue")]
- wasi_keyvalue: Option<Arc<WasiKeyValueCtx>>,
+ wasi_keyvalue: Option<WasiKeyValueCtx>,
#[cfg(feature = "wasi-tls")]
- wasi_tls: Option<Arc<wasmtime_wasi_tls::WasiTlsCtx>>,
+ wasi_tls: Option<wasmtime_wasi_tls::WasiTlsCtx>,
}
impl Host {
pub(crate) fn wasip1_ctx(&mut self) -> &mut wasmtime_wasi::p1::WasiP1Ctx {
- unwrap_singlethread_context(&mut self.wasip1_ctx)
+ self.wasip1_ctx.as_mut().unwrap()
}
}
-fn unwrap_singlethread_context<T>(ctx: &mut Option<Arc<Mutex<T>>>) -> &mut T {
- let ctx = ctx.as_mut().expect("context not configured");
- Arc::get_mut(ctx)
- .expect("context is not compatible with threads")
- .get_mut()
- .unwrap()
-}
-
impl WasiView for Host {
fn ctx(&mut self) -> WasiCtxView<'_> {
WasiView::ctx(self.wasip1_ctx())
@@ -1540,9 +1385,8 @@ impl WasiView for Host {
impl wasmtime_wasi_http::p2::WasiHttpView for Host {
fn http(&mut self) -> wasmtime_wasi_http::p2::WasiHttpCtxView<'_> {
let ctx = self.wasi_http.as_mut().unwrap();
- let ctx = Arc::get_mut(ctx).expect("wasmtime_wasi_http is not compatible with threads");
wasmtime_wasi_http::p2::WasiHttpCtxView {
- table: WasiView::ctx(unwrap_singlethread_context(&mut self.wasip1_ctx)).table,
+ table: WasiView::ctx(self.wasip1_ctx.as_mut().unwrap()).table,
ctx,
hooks: &mut self.wasi_http_hooks,
}
@@ -1553,9 +1397,8 @@ impl wasmtime_wasi_http::p2::WasiHttpView for Host {
impl wasmtime_wasi_http::p3::WasiHttpView for Host {
fn http(&mut self) -> wasmtime_wasi_http::p3::WasiHttpCtxView<'_> {
let ctx = self.wasi_http.as_mut().unwrap();
- let ctx = Arc::get_mut(ctx).expect("wasmtime_wasi_http is not compatible with threads");
wasmtime_wasi_http::p3::WasiHttpCtxView {
- table: WasiView::ctx(unwrap_singlethread_context(&mut self.wasip1_ctx)).table,
+ table: WasiView::ctx(self.wasip1_ctx.as_mut().unwrap()).table,
ctx,
hooks: &mut self.wasi_http_hooks,
}
@@ -1566,39 +1409,10 @@ impl wasmtime_wasi_http::p3::WasiHttpView for Host {
impl wasmtime_wasi_tls::WasiTlsView for Host {
fn tls(&mut self) -> wasmtime_wasi_tls::WasiTlsCtxView<'_> {
wasmtime_wasi_tls::WasiTlsCtxView {
- table: WasiView::ctx(unwrap_singlethread_context(&mut self.wasip1_ctx)).table,
- ctx: Arc::get_mut(self.wasi_tls.as_mut().unwrap()).unwrap(),
- }
- }
-}
-
-fn ctx_set_listenfd(mut num_fd: usize, builder: &mut WasiCtxBuilder) -> Result<usize> {
- let _ = &mut num_fd;
- let _ = &mut *builder;
-
- #[cfg(all(unix, feature = "run"))]
- {
- use listenfd::ListenFd;
-
- for env in ["LISTEN_FDS", "LISTEN_FDNAMES"] {
- if let Ok(val) = std::env::var(env) {
- builder.env(env, &val)?;
- }
- }
-
- let mut listenfd = ListenFd::from_env();
-
- for i in 0..listenfd.len() {
- if let Some(stdlistener) = listenfd.take_tcp_listener(i)? {
- let _ = stdlistener.set_nonblocking(true)?;
- let listener = TcpListener::from_std(stdlistener);
- builder.preopened_socket((3 + i) as _, listener)?;
- num_fd = 3 + i;
- }
+ table: WasiView::ctx(self.wasip1_ctx.as_mut().unwrap()).table,
+ ctx: self.wasi_tls.as_mut().unwrap(),
}
}
-
- Ok(num_fd)
}
#[cfg(feature = "coredump")]
diff --git a/supply-chain/config.toml b/supply-chain/config.toml
index 4851429d97..16d0abfb19 100644
--- a/supply-chain/config.toml
+++ b/supply-chain/config.toml
@@ -100,9 +100,6 @@ audit-as-crates-io = true
[policy.uap-bench]
criteria = []
-[policy.wasi-common]
-audit-as-crates-io = true
-
[policy.wasmtime]
audit-as-crates-io = true
@@ -196,9 +193,6 @@ audit-as-crates-io = true
[policy.wasmtime-wasi-nn]
audit-as-crates-io = true
-[policy.wasmtime-wasi-threads]
-audit-as-crates-io = true
-
[policy.wasmtime-wasi-tls]
audit-as-crates-io = true
diff --git a/supply-chain/imports.lock b/supply-chain/imports.lock
index ce7b19f148..be7c6b5e19 100644
--- a/supply-chain/imports.lock
+++ b/supply-chain/imports.lock
@@ -827,13 +827,6 @@ user-id = 6825
user-login = "sunfishcode"
user-name = "Dan Gohman"
-[[publisher.fd-lock]]
-version = "4.0.4"
-when = "2025-03-10"
-user-id = 6825
-user-login = "sunfishcode"
-user-name = "Dan Gohman"
-
[[publisher.filecheck]]
version = "0.5.0"
when = "2020-03-17"
@@ -1270,13 +1263,6 @@ user-id = 3618
user-login = "dtolnay"
user-name = "David Tolnay"
-[[publisher.system-interface]]
-version = "0.27.3"
-when = "2024-12-04"
-user-id = 6825
-user-login = "sunfishcode"
-user-name = "Dan Gohman"
-
[[publisher.tar]]
version = "0.4.45"
when = "2026-03-19"
@@ -1438,11 +1424,6 @@ user-id = 1
user-login = "alexcrichton"
user-name = "Alex Crichton"
-[[publisher.wasi-common]]
-version = "44.0.1"
-when = "2026-04-30"
-trusted-publisher = "github:bytecodealliance/wasmtime"
-
[[publisher.wasip1]]
version = "1.0.0"
when = "2025-09-09"
@@ -1695,11 +1676,6 @@ version = "44.0.1"
when = "2026-04-30"
trusted-publisher = "github:bytecodealliance/wasmtime"
-[[publisher.wasmtime-wasi-threads]]
-version = "44.0.1"
-when = "2026-04-30"
-trusted-publisher = "github:bytecodealliance/wasmtime"
-
[[publisher.wasmtime-wasi-tls]]
version = "44.0.1"
when = "2026-04-30"
diff --git a/tests/all/cli_tests.rs b/tests/all/cli_tests.rs
index a7f34fb7fc..c83fbfb592 100644
--- a/tests/all/cli_tests.rs
+++ b/tests/all/cli_tests.rs
@@ -172,14 +172,8 @@ fn assert_trap_code(status: &ExitStatus) {
// Run a simple WASI hello world, snapshot0 edition.
#[test]
fn hello_wasi_snapshot0() -> Result<()> {
- for preview2 in ["-Spreview2=n", "-Spreview2=y"] {
- let stdout = run_wasmtime(&[
- "-Ccache=n",
- preview2,
- "tests/all/cli_tests/hello_wasi_snapshot0.wat",
- ])?;
- assert_eq!(stdout, "Hello, world!\n");
- }
+ let stdout = run_wasmtime(&["-Ccache=n", "tests/all/cli_tests/hello_wasi_snapshot0.wat"])?;
+ assert_eq!(stdout, "Hello, world!\n");
Ok(())
}
@@ -240,13 +234,8 @@ fn timeout_in_invoke() -> Result<()> {
fn exit2_wasi_snapshot0() -> Result<()> {
let wasm = build_wasm("tests/all/cli_tests/exit2_wasi_snapshot0.wat")?;
- for preview2 in ["-Spreview2=n", "-Spreview2=y"] {
- let output = run_wasmtime_for_output(
- &["-Ccache=n", preview2, wasm.path().to_str().unwrap()],
- None,
- )?;
- assert_eq!(output.status.code().unwrap(), 2);
- }
+ let output = run_wasmtime_for_output(&["-Ccache=n", wasm.path().to_str().unwrap()], None)?;
+ assert_eq!(output.status.code().unwrap(), 2);
Ok(())
}
@@ -263,14 +252,9 @@ fn exit2_wasi_snapshot1() -> Result<()> {
#[test]
fn exit125_wasi_snapshot0() -> Result<()> {
let wasm = build_wasm("tests/all/cli_tests/exit125_wasi_snapshot0.wat")?;
- for preview2 in ["-Spreview2=n", "-Spreview2=y"] {
- let output = run_wasmtime_for_output(
- &["-Ccache=n", preview2, wasm.path().to_str().unwrap()],
- None,
- )?;
- dbg!(&output);
- assert_eq!(output.status.code().unwrap(), 125);
- }
+ let output = run_wasmtime_for_output(&["-Ccache=n", wasm.path().to_str().unwrap()], None)?;
+ dbg!(&output);
+ assert_eq!(output.status.code().unwrap(), 125);
Ok(())
}
@@ -288,15 +272,10 @@ fn exit125_wasi_snapshot1() -> Result<()> {
fn exit126_wasi_snapshot0() -> Result<()> {
let wasm = build_wasm("tests/all/cli_tests/exit126_wasi_snapshot0.wat")?;
- for preview2 in ["-Spreview2=n", "-Spreview2=y"] {
- let output = run_wasmtime_for_output(
- &["-Ccache=n", preview2, wasm.path().to_str().unwrap()],
- None,
- )?;
- assert_eq!(output.status.code().unwrap(), 1);
- assert!(output.stdout.is_empty());
- assert!(String::from_utf8_lossy(&output.stderr).contains("invalid exit status"));
- }
+ let output = run_wasmtime_for_output(&["-Ccache=n", wasm.path().to_str().unwrap()], None)?;
+ assert_eq!(output.status.code().unwrap(), 1);
+ assert!(output.stdout.is_empty());
+ assert!(String::from_utf8_lossy(&output.stderr).contains("invalid exit status"));
Ok(())
}
@@ -438,22 +417,20 @@ fn hello_wasi_snapshot0_from_stdin() -> Result<()> {
// Run a simple WASI hello world, snapshot0 edition.
// The module is piped from standard input.
let wasm = build_wasm("tests/all/cli_tests/hello_wasi_snapshot0.wat")?;
- for preview2 in ["-Spreview2=n", "-Spreview2=y"] {
- let stdout = {
- let path = wasm.path();
- let args: &[&str] = &["-Ccache=n", preview2, "-"];
- let output = run_wasmtime_for_output(args, Some(path))?;
- if !output.status.success() {
- bail!(
- "Failed to execute wasmtime with: {:?}\n{}",
- args,
- String::from_utf8_lossy(&output.stderr)
- );
- }
- Ok::<_, wasmtime::Error>(String::from_utf8(output.stdout).unwrap())
- }?;
- assert_eq!(stdout, "Hello, world!\n");
- }
+ let stdout = {
+ let path = wasm.path();
+ let args: &[&str] = &["-Ccache=n", "-"];
+ let output = run_wasmtime_for_output(args, Some(path))?;
+ if !output.status.success() {
+ bail!(
+ "Failed to execute wasmtime with: {:?}\n{}",
+ args,
+ String::from_utf8_lossy(&output.stderr)
+ );
+ }
+ Ok::<_, wasmtime::Error>(String::from_utf8(output.stdout).unwrap())
+ }?;
+ assert_eq!(stdout, "Hello, world!\n");
Ok(())
}
@@ -551,62 +528,6 @@ fn run_cwasm_from_stdin() -> Result<()> {
Ok(())
}
-#[cfg(feature = "wasi-threads")]
-#[test]
-fn run_threads() -> Result<()> {
- // Only run threaded tests on platforms that support threads. Also skip
- // these tests with ASAN as it, rightfully, complains about a memory leak.
- // The memory leak at this time is that child threads aren't joined with the
- // main thread, meaning that allocations done on child threads are indeed
- // leaked.
- if crate::threads::engine().is_none() || cfg!(asan) {
- return Ok(());
- }
- let wasm = build_wasm("tests/all/cli_tests/threads.wat")?;
- let stdout = run_wasmtime(&[
- "run",
- "-Wthreads,shared-memory",
- "-Sthreads",
- "-Ccache=n",
- wasm.path().to_str().unwrap(),
- ])?;
-
- assert!(
- stdout
- == "Called _start\n\
- Running wasi_thread_start\n\
- Running wasi_thread_start\n\
- Running wasi_thread_start\n\
- Done\n"
- );
- Ok(())
-}
-
-#[cfg(feature = "wasi-threads")]
-#[test]
-fn run_simple_with_wasi_threads() -> Result<()> {
- // Skip this test on platforms that don't support threads.
- if crate::threads::engine().is_none() {
- return Ok(());
- }
- // We expect to be able to run Wasm modules that do not have correct
- // wasi-thread entry points or imported shared memory as long as no threads
- // are spawned.
- let wasm = build_wasm("tests/all/cli_tests/simple.wat")?;
- let stdout = run_wasmtime(&[
- "run",
- "-Wthreads",
- "-Sthreads",
- "-Ccache=n",
- "--invoke",
- "simple",
- wasm.path().to_str().unwrap(),
- "4",
- ])?;
- assert_eq!(stdout, "4\n");
- Ok(())
-}
-
#[test]
fn wasm_flags() -> Result<()> {
// Any argument after the wasm module should be interpreted as for the
@@ -1434,7 +1355,6 @@ mod test_programs {
Ok(())
}
- run(&["run", "-Spreview2=n", P2_CLI_STDIO_WRITE_FLUSHES])?;
run(&["run", "-Spreview2=y", P2_CLI_STDIO_WRITE_FLUSHES])?;
run(&[
"run",
diff --git a/tests/all/cli_tests/threads.wat b/tests/all/cli_tests/threads.wat
deleted file mode 100644
index def5011f8e..0000000000
--- a/tests/all/cli_tests/threads.wat
+++ /dev/null
@@ -1,65 +0,0 @@
-(module
- ;; As we have discussed, it makes sense to make the shared memory an import
- ;; so that all
- (import "" "memory" (memory $shmem 1 1 shared))
- (import "wasi_snapshot_preview1" "fd_write"
- (func $__wasi_fd_write (param i32 i32 i32 i32) (result i32)))
- (import "wasi_snapshot_preview1" "proc_exit"
- (func $__wasi_proc_exit (param i32)))
- (import "wasi" "thread-spawn"
- (func $__wasi_thread_spawn (param i32) (result i32)))
-
- (func (export "_start")
- (local $i i32)
-
- ;; Print "Called _start".
- (call $print (i32.const 32) (i32.const 14))
-
- ;; Print "Running wasi_thread_start" in several threads.
- (drop (call $__wasi_thread_spawn (i32.const 0)))
- (drop (call $__wasi_thread_spawn (i32.const 0)))
- (drop (call $__wasi_thread_spawn (i32.const 0)))
-
- ;; Wait for all the threads to notify us that they are done.
- (local.set $i (i32.const 0))
- (loop $again
- ;; Wait for the i32 at address 128 to be incremented by each thread. We
- ;; maintain a local $i with the atomically loaded value as the expected
- ;; wait value and to check if all three threads are complete. This wait is
- ;; for 1ms or until notified, whichever is first.
- (drop (memory.atomic.wait32 (i32.const 128) (local.get $i) (i64.const 1000000)))
- (local.set $i (i32.atomic.load (i32.const 128)))
- (br_if $again (i32.lt_s (local.get $i) (i32.const 3)))
- )
-
- ;; Print "Done".
- (call $print (i32.const 64) (i32.const 5))
- )
-
- ;; A threads-enabled module must export this spec-designated entry point.
- (func (export "wasi_thread_start") (param $tid i32) (param $start_arg i32)
- (call $print (i32.const 96) (i32.const 26))
- ;; After printing, we atomically increment the value at address 128 and then
- ;; wake up the main thread's join loop.
- (drop (i32.atomic.rmw.add (i32.const 128) (i32.const 1)))
- (drop (memory.atomic.notify (i32.const 128) (i32.const 1)))
- )
-
- ;; A helper function for printing ptr-len strings.
- (func $print (param $ptr i32) (param $len i32)
- (i32.store (i32.const 8) (local.get $len))
- (i32.store (i32.const 4) (local.get $ptr))
- (drop (call $__wasi_fd_write
- (i32.const 1)
- (i32.const 4)
- (i32.const 1)
- (i32.const 0)))
- )
-
- ;; We still need to export the shared memory for Wiggle's sake.
- (export "memory" (memory $shmem))
-
- (data (i32.const 32) "Called _start\0a")
- (data (i32.const 64) "Done\0a")
- (data (i32.const 96) "Running wasi_thread_start\0a")
-)