#1.8. WASM 组件模型:ffi::wit
本页内容
WebAssembly 组件模型(Component Model,bytecodealliance.org;Preview 2 于 2024 年 1 月稳定)是定义带类型的跨语言接口的基础。它用 record / variant / resource 这些丰富的类型,取代传统 C ABI FFI(1.7)所依赖的“裸指针 + 长度”模型。
#1.8.1. WIT:WebAssembly Interface Types
WIT 是一种与语言无关的接口定义语言。
package example:fs;
interface fs {
record stat {
size: u64,
mtime: u64,
is-dir: bool,
}
variant error {
not-found,
permission-denied,
io-error(string),
}
resource file {
constructor(path: string);
read: func(buf-size: u32) -> result<list<u8>, error>;
close: func();
}
open: func(path: string) -> result<file, error>;
}
这样定义的接口可以在任何语言中导入或导出:Rust、Go、Python、Nabi 等。
#1.8.2. Nabi 一侧的绑定形式
导入一侧使用外部组件。这里 wit/fs.wit 保存的是 1.8.1 的接口,文件顶部是 package example:fs;。
ffi::wit::import { "wit/fs.wit" } // relative to this source file
use example::fs::fs::{File, Error};
let f = File::new("data.txt");
let bytes = try f.read(1024); // throws (Error) -> List<u8>
f.close();
导出一侧提供组件;calculator.wit 在一个 world 中声明 add: func(a: s32, b: s32) -> s32。
ffi::wit::export { "calculator.wit" }
#[wit::export]
fn add(a: i32, b: i32) -> i32 { a + b }
#路径与位置
- 路径相对于源文件。它指向一个
.wit文件或一个包目录,包目录的deps/中存放其依赖。 - 该项可以出现在程序的包中,也可以出现在依赖中。它的绑定放在包含它的模块中(在依赖中就是该依赖的模块),位于
ns::pkg::iface(wasi::filesystem::types)之下。 - WIT 类型变为 PascalCase 的 Nabi 类型(
descriptor-type→DescriptorType,file→File);函数和字段变为 snake_case。
#World
具名文件中的 world 就是组件。否则由关键字决定:ffi::wit::import 导入这些接口,ffi::wit::export 导出它们。include ... with { a as b } 重命名被包含的项。
#类型映射
| WIT | Nabi |
|---|---|
record | struct |
variant、enum | enum |
flags | 由 bool 字段组成、带 Default 的 struct(最多 32 个标志) |
option<T> | T?(嵌套的 option 保留层次:option<option<T>> → T??) |
result<T, E> | Result<T, E>;返回它的函数是 throws (E) -> T |
tuple<..> | 元组 |
list<T> | List<T> |
list<T, N> | [T; N] |
string | str(UTF-8) |
char、bool、f32、f64 | 相同 |
sN / uN | iN / uN |
future<T> | AsyncFuture<T> |
stream<T> | core::channel::Receiver<T>(关闭发送端即结束) |
error-context | bare::ffi::wit::ErrorContext |
导入的 resource | 句柄结构体,通过 using / Drop 释放 |
导出的 resource | 用户的 #[wit::export] pub struct |
#异步
async func 就是 async fn,导入和导出都是如此。同步任务(preview 2 的 main、同步导出)不能等待组件模型;这样做会在运行时触发 panic,所以异步导入要在异步导出内部等待。preview 3 的命令把 wasi:cli/[email protected] 导出为 #[wit::export] async fn run() -> Result<(), ()>。异步导出调用并发运行,每个调用都是一个组件模型任务;一个调用在自己的轮次中返回结果。在异步导出内部,套接字和定时器在宿主的事件之间等待;同时还有待处理的组件模型事件时,至少每 10 ms 检查一次(preview 2 的 pollable 和组件模型的事件不能同时等待)。等待没有任何东西会送达的内容的异步导出会一直等待;另一个调用仍可能送达它。
生成的绑定所调用的异步规范 ABI(canonical ABI)位于 std::wit 中:它运行在执行器上,stream<T> 映射到一个 core 类型。内存辅助函数、块、句柄和 ErrorContext 留在 bare::ffi::wit 中。
#导出
导出的函数是该项所在模块中的 #[wit::export] fn,按 snake_case 名称与 WIT 函数对应。导出的资源是一个 #[wit::export] pub struct,它的 impl 提供 new(构造函数)、方法和静态函数;可能失败的构造函数(result<r, ..>)是会抛出错误的 new,资源的析构函数运行它的 Drop。缺少导出是编译错误。
导出 WIT 且入口文件既没有 fn main 也没有顶层语句的包是一个 reactor:它不导出 wasi:cli/run(4.16.1)。
#目标
WIT 需要 wasm32-wasip2(WASI preview 2 组件);在其他任何目标上都是编译错误。导出可以在 main 之前被调用:运行时在第一次导出调用时启动。
预构建的依赖会在其 NABIHIR 中携带其 ffi::wit 项所读取的 .wit 文件(refs-lang 9.4.7);依赖它的包不会从磁盘读取这些文件。
#限制
导入的接口不能使用组件所导出接口的类型;这是编译错误。
#绑定运行时:bare::ffi::wit
生成的绑定调用这些辅助函数;普通代码使用绑定。块来自 C 分配器,包括宿主通过 cabi_realloc 填充的块;提升(lift)出的字符串或列表在复制到 GC 内存后释放其块。一次导入调用降低(lower)到块中的值在调用之后一起释放;导出的值由它的 post-return 函数释放。
// bare::ffi::wit: linear memory at canonical ABI addresses (i32)
unsafe fn load_u8(a: i32) -> u8; // also load_u16 / load_i32 / load_i64 / load_f32 / load_f64
unsafe fn store_u8(a: i32, v: u8); // also store_u16 / store_i32 / store_i64 / store_f32 / store_f64
// joined flat slots of a variant
fn f32_bits(x: f32) -> i32;
fn f32_from(x: i32) -> f32;
fn f64_bits(x: f64) -> i64;
fn f64_from(x: i64) -> f64;
fn char_from(x: i32) -> char; // panics on a non-scalar
fn bad_case() -> !; // panics: discriminant out of range
const BLOCKED: i32 = -1; // a copy or call did not finish at once
const DROPPED: i32 = 1; // a copy's other end was dropped
unsafe fn free(a: i32);
unsafe fn str_take(p: i32, n: i32) -> str; // copies, then frees the block
unsafe fn bytes_take(p: i32, n: i32) -> List<u8>; // copies, then frees the block
struct Blocks { /* private */ }
impl Blocks {
fn new() -> Blocks;
fn alloc(self, size: i32, align: i32) -> i32; // an empty block is the address `align`
fn str(self, s: str) -> (i32, i32); // (address, length)
fn bytes(self, l: List<u8>) -> (i32, i32); // (address, length)
fn free(self); // frees every block
}
struct Handle { /* private */ }
impl Handle {
fn own(h: i32) -> Handle;
fn borrowed(h: i32) -> Handle;
fn get(self) -> i32; // panics once dropped or passed on
fn take(self) -> i32; // gives an own away; panics on a borrow
fn release(self) -> i32 | none; // the handle to drop, if still owned
}
struct Table<T> { /* private */ }
unsafe impl<T> Sync for Table<T> {}
impl<T> Table<T> {
unsafe fn new() -> Table<T>; // the caller keeps it to one thread at a time
fn insert(self, v: T) -> i32; // the rep
fn get(self, rep: i32) -> T; // panics once taken
fn take(self, rep: i32) -> T?; // frees the slot; none if taken already
}
struct ErrorContext { /* private */ }
impl ErrorContext { // WASI targets only
fn new(msg: str) -> ErrorContext;
fn debug_message(self) -> str; // the host may give an empty one
fn raw(self) -> i32;
fn from_raw(h: i32) -> ErrorContext;
}
impl Drop for ErrorContext { /* error-context.drop */ }
Handle 的副本共享同一个单元:把 own 传递出去或释放它,会清空每一个副本。Table<T> 按表示(rep)保存导出资源的值,直到宿主释放其句柄([dtor])。
ErrorContext 类型在每个目标上都存在;它的方法和 Drop 只在 WASI 目标上存在。Blocks、Handle 和 Table<T> 实现的 Debug 输出其类型名,ErrorContext 输出 ErrorContext { handle: n }(0.5.12);std::wit 的类型 Waiting、FutureOps<T> 和 StreamOps<T> 也是如此。在参数错误时触发 panic 的函数(char_from、bad_case、Handle::get / take、Table::get)都是 #[track_caller],它们的消息遵循 0.5.10 的规则 6(wit::char_from: not a Unicode scalar value、Handle::get: resource used after it was dropped or passed on)。槽辅助函数 f32_bits、f32_from、f64_bits、f64_from 和 char_from 保留生成的绑定所调用的名称;它们是规范 ABI 的名称,不在 0.5.11 的命名表之内。
#1.8.3. C FFI 与 WIT 的区别
两种方式在多个维度上有明显区别。
| 方面 | C FFI(1.7) | WIT(本章) |
|---|---|---|
| 类型系统 | C 原始类型 + 用户结构体 | record / variant / resource |
| 安全性 | 低(手动管理裸指针) | 高(带类型) |
| 内存管理 | malloc/free | resource(自动析构) |
| 错误处理 | errno / 返回值约定 | 一等的 result<T, E> |
| 字符串 | 以 null 结尾 | 带长度前缀的 UTF-8 |
| 列表 | (ptr, len) 手动 | list<T> 自动 |
| 调用开销 | 几乎没有(直接调用) | 跳板(trampoline,约 ns 级) |
| 适用范围 | 所有原生目标 | wasm32-wasip2(preview 2 组件) |
| 需要 unsafe | ✓ | ✗ |
#1.8.4. 选择标准
标准很简单:取决于调用的是什么以及部署在哪里。
| 场景 | 推荐 |
|---|---|
| 调用传统 C 库 | C FFI(1.7) |
| 系统调用(libc、Win32) | C FFI |
| GPU / SIMD 内建函数 | C FFI |
| 与其他语言的安全接口 | WIT |
| 部署到 WASM 环境 | WIT |
| 插件 / 沙箱隔离 | WIT |
| 多语言(Modular / Mojo 等) | WIT |
本章的主要意义在于 Nabi 同时支持传统 C FFI 和 WIT。用户根据安全性、性能和目标环境的约束选择其中之一。
#1.8.5. 参考资料
延伸阅读:
发现错误? 在 GitHub 上编辑此页 最后更新: