wasmtime_wasi/
bindings.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
//! Auto-generated bindings for WASI interfaces.
//!
//! This module contains the output of the [`bindgen!`] macro when run over
//! the `wasi:cli/command` world. That means this module has all the generated
//! types for WASI for all of its base interfaces used by the CLI world. This
//! module itself by default contains bindings for `async`-related traits. The
//! [`sync`] module contains bindings for a non-`async` version of types.
//!
//! [`bindgen!`]: https://docs.rs/wasmtime/latest/wasmtime/component/macro.bindgen.html
//!
//! # Examples
//!
//! If you have a WIT world which refers to WASI interfaces you probably want to
//! use this crate's bindings rather than generate fresh bindings. That can be
//! done using the `with` option to [`bindgen!`]:
//!
//! ```rust
//! use wasmtime_wasi::{WasiCtx, ResourceTable, WasiView};
//! use wasmtime::{Result, Engine, Config};
//! use wasmtime::component::Linker;
//!
//! wasmtime::component::bindgen!({
//!     inline: "
//!         package example:wasi;
//!
//!         // An example of extending the `wasi:cli/command` world with a
//!         // custom host interface.
//!         world my-world {
//!             include wasi:cli/command@0.2.2;
//!
//!             import custom-host;
//!         }
//!
//!         interface custom-host {
//!             my-custom-function: func();
//!         }
//!     ",
//!     path: "wit",
//!     with: {
//!         "wasi": wasmtime_wasi::bindings,
//!     },
//!     async: true,
//! });
//!
//! struct MyState {
//!     table: ResourceTable,
//!     ctx: WasiCtx,
//! }
//!
//! #[async_trait::async_trait]
//! impl example::wasi::custom_host::Host for MyState {
//!     async fn my_custom_function(&mut self) {
//!         // ..
//!     }
//! }
//!
//! impl WasiView for MyState {
//!     fn table(&mut self) -> &mut ResourceTable { &mut self.table }
//!     fn ctx(&mut self) -> &mut WasiCtx { &mut self.ctx }
//! }
//!
//! fn main() -> Result<()> {
//!     let mut config = Config::default();
//!     config.async_support(true);
//!     let engine = Engine::new(&config)?;
//!     let mut linker: Linker<MyState> = Linker::new(&engine);
//!     wasmtime_wasi::add_to_linker_async(&mut linker)?;
//!     example::wasi::custom_host::add_to_linker(&mut linker, |state| state)?;
//!
//!     // .. use `Linker` to instantiate component ...
//!
//!     Ok(())
//! }
//! ```

/// Synchronous-generated bindings for WASI interfaces.
///
/// This is the same as the top-level [`bindings`](crate::bindings) module of
/// this crate except that it's for synchronous calls.
///
/// # Examples
///
/// If you have a WIT world which refers to WASI interfaces you probably want to
/// use this crate's bindings rather than generate fresh bindings. That can be
/// done using the `with` option to `bindgen!`:
///
/// ```rust
/// use wasmtime_wasi::{WasiCtx, ResourceTable, WasiView};
/// use wasmtime::{Result, Engine};
/// use wasmtime::component::Linker;
///
/// wasmtime::component::bindgen!({
///     inline: "
///         package example:wasi;
///
///         // An example of extending the `wasi:cli/command` world with a
///         // custom host interface.
///         world my-world {
///             include wasi:cli/command@0.2.2;
///
///             import custom-host;
///         }
///
///         interface custom-host {
///             my-custom-function: func();
///         }
///     ",
///     path: "wit",
///     with: {
///         "wasi": wasmtime_wasi::bindings::sync,
///     },
///     // This is required for bindings using `wasmtime-wasi` and it otherwise
///     // isn't the default for non-async bindings.
///     require_store_data_send: true,
/// });
///
/// struct MyState {
///     table: ResourceTable,
///     ctx: WasiCtx,
/// }
///
/// impl example::wasi::custom_host::Host for MyState {
///     fn my_custom_function(&mut self) {
///         // ..
///     }
/// }
///
/// impl WasiView for MyState {
///     fn table(&mut self) -> &mut ResourceTable { &mut self.table }
///     fn ctx(&mut self) -> &mut WasiCtx { &mut self.ctx }
/// }
///
/// fn main() -> Result<()> {
///     let engine = Engine::default();
///     let mut linker: Linker<MyState> = Linker::new(&engine);
///     wasmtime_wasi::add_to_linker_sync(&mut linker)?;
///     example::wasi::custom_host::add_to_linker(&mut linker, |state| state)?;
///
///     // .. use `Linker` to instantiate component ...
///
///     Ok(())
/// }
/// ```
pub mod sync {
    mod generated {
        use crate::{FsError, SocketError, StreamError};

        wasmtime::component::bindgen!({
            path: "wit",
            world: "wasi:cli/command",
            tracing: true,
            trappable_error_type: {
                "wasi:io/streams/stream-error" => StreamError,
                "wasi:filesystem/types/error-code" => FsError,
                "wasi:sockets/network/error-code" => SocketError,
            },
            trappable_imports: true,
            with: {
                // These interfaces come from the outer module, as it's
                // sync/async agnostic.
                "wasi:clocks": crate::bindings::clocks,
                "wasi:random": crate::bindings::random,
                "wasi:cli": crate::bindings::cli,
                "wasi:io/error": crate::bindings::io::error,
                "wasi:filesystem/preopens": crate::bindings::filesystem::preopens,
                "wasi:sockets/network": crate::bindings::sockets::network,

                // Configure the resource types of the bound interfaces here
                // to be the same as the async versions of the resources, that
                // way everything has the same type.
                "wasi:filesystem/types/descriptor": super::super::filesystem::types::Descriptor,
                "wasi:filesystem/types/directory-entry-stream": super::super::filesystem::types::DirectoryEntryStream,
                "wasi:io/poll/pollable": super::super::io::poll::Pollable,
                "wasi:io/streams/input-stream": super::super::io::streams::InputStream,
                "wasi:io/streams/output-stream": super::super::io::streams::OutputStream,
                "wasi:sockets/tcp/tcp-socket": super::super::sockets::tcp::TcpSocket,
                "wasi:sockets/udp/incoming-datagram-stream": super::super::sockets::udp::IncomingDatagramStream,
                "wasi:sockets/udp/outgoing-datagram-stream": super::super::sockets::udp::OutgoingDatagramStream,
                "wasi:sockets/udp/udp-socket": super::super::sockets::udp::UdpSocket,
            },
            require_store_data_send: true,
        });
    }
    pub use self::generated::exports;
    pub use self::generated::wasi::*;

    /// Synchronous bindings to execute and run a `wasi:cli/command`.
    ///
    /// This structure is automatically generated by `bindgen!` and is intended
    /// to be used with [`Config::async_support(false)`][async]. For the
    /// asynchronous version see [`bindings::Command`](super::Command).
    ///
    /// This can be used for a more "typed" view of executing a command
    /// component through the [`Command::wasi_cli_run`] method plus
    /// [`Guest::call_run`](exports::wasi::cli::run::Guest::call_run).
    ///
    /// [async]: wasmtime::Config::async_support
    /// [`wasmtime_wasi::add_to_linker_sync`]: crate::add_to_linker_sync
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use wasmtime::{Engine, Result, Store, Config};
    /// use wasmtime::component::{ResourceTable, Linker, Component};
    /// use wasmtime_wasi::{WasiCtx, WasiView, WasiCtxBuilder};
    /// use wasmtime_wasi::bindings::sync::Command;
    ///
    /// // This example is an example shim of executing a component based on the
    /// // command line arguments provided to this program.
    /// fn main() -> Result<()> {
    ///     let args = std::env::args().skip(1).collect::<Vec<_>>();
    ///
    ///     // Configure and create `Engine`
    ///     let engine = Engine::default();
    ///
    ///     // Configure a `Linker` with WASI, compile a component based on
    ///     // command line arguments.
    ///     let mut linker = Linker::<MyState>::new(&engine);
    ///     wasmtime_wasi::add_to_linker_sync(&mut linker)?;
    ///     let component = Component::from_file(&engine, &args[0])?;
    ///
    ///
    ///     // Configure a `WasiCtx` based on this program's environment. Then
    ///     // build a `Store` to instantiate into.
    ///     let mut builder = WasiCtxBuilder::new();
    ///     builder.inherit_stdio().inherit_env().args(&args[2..]);
    ///     let mut store = Store::new(
    ///         &engine,
    ///         MyState {
    ///             ctx: builder.build(),
    ///             table: ResourceTable::new(),
    ///         },
    ///     );
    ///
    ///     // Instantiate the component and we're off to the races.
    ///     let command = Command::instantiate(&mut store, &component, &linker)?;
    ///     let program_result = command.wasi_cli_run().call_run(&mut store)?;
    ///     match program_result {
    ///         Ok(()) => Ok(()),
    ///         Err(()) => std::process::exit(1),
    ///     }
    /// }
    ///
    /// struct MyState {
    ///     ctx: WasiCtx,
    ///     table: ResourceTable,
    /// }
    ///
    /// impl WasiView for MyState {
    ///     fn ctx(&mut self) -> &mut WasiCtx { &mut self.ctx }
    ///     fn table(&mut self) -> &mut ResourceTable { &mut self.table }
    /// }
    /// ```
    ///
    /// ---
    pub use self::generated::Command;

    /// Pre-instantiated analogue of [`Command`].
    ///
    /// This works the same as [`Command`] but enables front-loading work such
    /// as export lookup to before instantiation.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use wasmtime::{Engine, Result, Store, Config};
    /// use wasmtime::component::{ResourceTable, Linker, Component};
    /// use wasmtime_wasi::{WasiCtx, WasiView, WasiCtxBuilder};
    /// use wasmtime_wasi::bindings::sync::CommandPre;
    ///
    /// // This example is an example shim of executing a component based on the
    /// // command line arguments provided to this program.
    /// fn main() -> Result<()> {
    ///     let args = std::env::args().skip(1).collect::<Vec<_>>();
    ///
    ///     // Configure and create `Engine`
    ///     let engine = Engine::default();
    ///
    ///     // Configure a `Linker` with WASI, compile a component based on
    ///     // command line arguments, and then pre-instantiate it.
    ///     let mut linker = Linker::<MyState>::new(&engine);
    ///     wasmtime_wasi::add_to_linker_sync(&mut linker)?;
    ///     let component = Component::from_file(&engine, &args[0])?;
    ///     let pre = CommandPre::new(linker.instantiate_pre(&component)?)?;
    ///
    ///
    ///     // Configure a `WasiCtx` based on this program's environment. Then
    ///     // build a `Store` to instantiate into.
    ///     let mut builder = WasiCtxBuilder::new();
    ///     builder.inherit_stdio().inherit_env().args(&args);
    ///     let mut store = Store::new(
    ///         &engine,
    ///         MyState {
    ///             ctx: builder.build(),
    ///             table: ResourceTable::new(),
    ///         },
    ///     );
    ///
    ///     // Instantiate the component and we're off to the races.
    ///     let command = pre.instantiate(&mut store)?;
    ///     let program_result = command.wasi_cli_run().call_run(&mut store)?;
    ///     match program_result {
    ///         Ok(()) => Ok(()),
    ///         Err(()) => std::process::exit(1),
    ///     }
    /// }
    ///
    /// struct MyState {
    ///     ctx: WasiCtx,
    ///     table: ResourceTable,
    /// }
    ///
    /// impl WasiView for MyState {
    ///     fn ctx(&mut self) -> &mut WasiCtx { &mut self.ctx }
    ///     fn table(&mut self) -> &mut ResourceTable { &mut self.table }
    /// }
    /// ```
    ///
    /// ---
    pub use self::generated::CommandPre;

    pub use self::generated::CommandIndices;

    pub use self::generated::LinkOptions;
}

mod async_io {
    wasmtime::component::bindgen!({
        path: "wit",
        world: "wasi:cli/command",
        tracing: true,
        trappable_imports: true,
        async: {
            // Only these functions are `async` and everything else is sync
            // meaning that it basically doesn't need to block. These functions
            // are the only ones that need to block.
            //
            // Note that at this time `only_imports` works on function names
            // which in theory can be shared across interfaces, so this may
            // need fancier syntax in the future.
            only_imports: [
                "[method]descriptor.access-at",
                "[method]descriptor.advise",
                "[method]descriptor.change-directory-permissions-at",
                "[method]descriptor.change-file-permissions-at",
                "[method]descriptor.create-directory-at",
                "[method]descriptor.get-flags",
                "[method]descriptor.get-type",
                "[method]descriptor.is-same-object",
                "[method]descriptor.link-at",
                "[method]descriptor.lock-exclusive",
                "[method]descriptor.lock-shared",
                "[method]descriptor.metadata-hash",
                "[method]descriptor.metadata-hash-at",
                "[method]descriptor.open-at",
                "[method]descriptor.read",
                "[method]descriptor.read-directory",
                "[method]descriptor.readlink-at",
                "[method]descriptor.remove-directory-at",
                "[method]descriptor.rename-at",
                "[method]descriptor.set-size",
                "[method]descriptor.set-times",
                "[method]descriptor.set-times-at",
                "[method]descriptor.stat",
                "[method]descriptor.stat-at",
                "[method]descriptor.symlink-at",
                "[method]descriptor.sync",
                "[method]descriptor.sync-data",
                "[method]descriptor.try-lock-exclusive",
                "[method]descriptor.try-lock-shared",
                "[method]descriptor.unlink-file-at",
                "[method]descriptor.unlock",
                "[method]descriptor.write",
                "[method]input-stream.blocking-read",
                "[method]input-stream.blocking-skip",
                "[drop]input-stream",
                "[method]output-stream.blocking-splice",
                "[method]output-stream.blocking-flush",
                "[method]output-stream.blocking-write",
                "[method]output-stream.blocking-write-and-flush",
                "[method]output-stream.blocking-write-zeroes-and-flush",
                "[drop]output-stream",
                "[method]directory-entry-stream.read-directory-entry",
                "poll",
                "[method]pollable.block",
                "[method]pollable.ready",
                "[method]tcp-socket.start-bind",
                "[method]tcp-socket.start-connect",
                "[method]udp-socket.start-bind",
                "[method]udp-socket.stream",
                "[method]outgoing-datagram-stream.send",
            ],
        },
        trappable_error_type: {
            "wasi:io/streams/stream-error" => crate::StreamError,
            "wasi:filesystem/types/error-code" => crate::FsError,
            "wasi:sockets/network/error-code" => crate::SocketError,
        },
        with: {
            // Configure all resources to be concrete types defined in this crate,
            // so that way we get to use nice typed helper methods with
            // `ResourceTable`.
            "wasi:sockets/network/network": crate::network::Network,
            "wasi:sockets/tcp/tcp-socket": crate::tcp::TcpSocket,
            "wasi:sockets/udp/udp-socket": crate::udp::UdpSocket,
            "wasi:sockets/udp/incoming-datagram-stream": crate::udp::IncomingDatagramStream,
            "wasi:sockets/udp/outgoing-datagram-stream": crate::udp::OutgoingDatagramStream,
            "wasi:sockets/ip-name-lookup/resolve-address-stream": crate::ip_name_lookup::ResolveAddressStream,
            "wasi:filesystem/types/directory-entry-stream": crate::filesystem::ReaddirIterator,
            "wasi:filesystem/types/descriptor": crate::filesystem::Descriptor,
            "wasi:io/streams/input-stream": crate::stream::InputStream,
            "wasi:io/streams/output-stream": crate::stream::OutputStream,
            "wasi:io/error/error": crate::stream::Error,
            "wasi:io/poll/pollable": crate::poll::Pollable,
            "wasi:cli/terminal-input/terminal-input": crate::stdio::TerminalInput,
            "wasi:cli/terminal-output/terminal-output": crate::stdio::TerminalOutput,
        },
    });
}

pub use self::async_io::exports;
pub use self::async_io::wasi::*;
pub use self::async_io::LinkOptions;

/// Asynchronous bindings to execute and run a `wasi:cli/command`.
///
/// This structure is automatically generated by `bindgen!` and is intended to
/// be used with [`Config::async_support(true)`][async]. For the synchronous
/// version see [`bindings::sync::Command`](sync::Command).
///
/// This can be used for a more "typed" view of executing a command component
/// through the [`Command::wasi_cli_run`] method plus
/// [`Guest::call_run`](exports::wasi::cli::run::Guest::call_run).
///
/// [async]: wasmtime::Config::async_support
/// [`wasmtime_wasi::add_to_linker_async`]: crate::add_to_linker_async
///
/// # Examples
///
/// ```no_run
/// use wasmtime::{Engine, Result, Store, Config};
/// use wasmtime::component::{ResourceTable, Linker, Component};
/// use wasmtime_wasi::{WasiCtx, WasiView, WasiCtxBuilder};
/// use wasmtime_wasi::bindings::Command;
///
/// // This example is an example shim of executing a component based on the
/// // command line arguments provided to this program.
/// #[tokio::main]
/// async fn main() -> Result<()> {
///     let args = std::env::args().skip(1).collect::<Vec<_>>();
///
///     // Configure and create `Engine`
///     let mut config = Config::new();
///     config.async_support(true);
///     let engine = Engine::new(&config)?;
///
///     // Configure a `Linker` with WASI, compile a component based on
///     // command line arguments, and then pre-instantiate it.
///     let mut linker = Linker::<MyState>::new(&engine);
///     wasmtime_wasi::add_to_linker_async(&mut linker)?;
///     let component = Component::from_file(&engine, &args[0])?;
///
///
///     // Configure a `WasiCtx` based on this program's environment. Then
///     // build a `Store` to instantiate into.
///     let mut builder = WasiCtxBuilder::new();
///     builder.inherit_stdio().inherit_env().args(&args);
///     let mut store = Store::new(
///         &engine,
///         MyState {
///             ctx: builder.build(),
///             table: ResourceTable::new(),
///         },
///     );
///
///     // Instantiate the component and we're off to the races.
///     let command = Command::instantiate_async(&mut store, &component, &linker).await?;
///     let program_result = command.wasi_cli_run().call_run(&mut store).await?;
///     match program_result {
///         Ok(()) => Ok(()),
///         Err(()) => std::process::exit(1),
///     }
/// }
///
/// struct MyState {
///     ctx: WasiCtx,
///     table: ResourceTable,
/// }
///
/// impl WasiView for MyState {
///     fn ctx(&mut self) -> &mut WasiCtx { &mut self.ctx }
///     fn table(&mut self) -> &mut ResourceTable { &mut self.table }
/// }
/// ```
///
/// ---
pub use self::async_io::Command;

/// Pre-instantiated analog of [`Command`]
///
/// This can be used to front-load work such as export lookup before
/// instantiation.
///
/// # Examples
///
/// ```no_run
/// use wasmtime::{Engine, Result, Store, Config};
/// use wasmtime::component::{ResourceTable, Linker, Component};
/// use wasmtime_wasi::{WasiCtx, WasiView, WasiCtxBuilder};
/// use wasmtime_wasi::bindings::CommandPre;
///
/// // This example is an example shim of executing a component based on the
/// // command line arguments provided to this program.
/// #[tokio::main]
/// async fn main() -> Result<()> {
///     let args = std::env::args().skip(1).collect::<Vec<_>>();
///
///     // Configure and create `Engine`
///     let mut config = Config::new();
///     config.async_support(true);
///     let engine = Engine::new(&config)?;
///
///     // Configure a `Linker` with WASI, compile a component based on
///     // command line arguments, and then pre-instantiate it.
///     let mut linker = Linker::<MyState>::new(&engine);
///     wasmtime_wasi::add_to_linker_async(&mut linker)?;
///     let component = Component::from_file(&engine, &args[0])?;
///     let pre = CommandPre::new(linker.instantiate_pre(&component)?)?;
///
///
///     // Configure a `WasiCtx` based on this program's environment. Then
///     // build a `Store` to instantiate into.
///     let mut builder = WasiCtxBuilder::new();
///     builder.inherit_stdio().inherit_env().args(&args);
///     let mut store = Store::new(
///         &engine,
///         MyState {
///             ctx: builder.build(),
///             table: ResourceTable::new(),
///         },
///     );
///
///     // Instantiate the component and we're off to the races.
///     let command = pre.instantiate_async(&mut store).await?;
///     let program_result = command.wasi_cli_run().call_run(&mut store).await?;
///     match program_result {
///         Ok(()) => Ok(()),
///         Err(()) => std::process::exit(1),
///     }
/// }
///
/// struct MyState {
///     ctx: WasiCtx,
///     table: ResourceTable,
/// }
///
/// impl WasiView for MyState {
///     fn ctx(&mut self) -> &mut WasiCtx { &mut self.ctx }
///     fn table(&mut self) -> &mut ResourceTable { &mut self.table }
/// }
/// ```
///
/// ---
pub use self::async_io::CommandPre;

pub use self::async_io::CommandIndices;