| 1 |
use anyhow::{Context, Error, Result, bail}; |
| 2 |
use libtest_mimic::{Arguments, Trial}; |
| 3 |
use pretty_assertions::assert_eq; |
| 4 |
use std::{borrow::Cow, fs, path::Path}; |
| 5 |
use wasm_encoder::{Encode, Section}; |
| 6 |
use wasm_metadata::{Metadata, Payload}; |
| 7 |
use wasmparser::{Parser, Validator, WasmFeatures}; |
| 8 |
use wit_component::{ComponentEncoder, DecodedWasm, Linker, StringEncoding, WitPrinter}; |
| 9 |
use wit_parser::{PackageId, Resolve, UnresolvedPackageGroup}; |
| 10 |
|
| 11 |
/// Tests the encoding of components. |
| 12 |
/// |
| 13 |
/// This test looks in the `components/` directory for test cases. |
| 14 |
/// |
| 15 |
/// The expected input files for a test case are: |
| 16 |
/// |
| 17 |
/// * [required] `module.wat` *or* some combination of `lib-$name.wat` and |
| 18 |
/// `dlopen-lib-$name.wat` - contains the core module definition(s) to be |
| 19 |
/// encoded as a component. If one or more `lib-$name.wat` and/or |
| 20 |
/// `dlopen-lib-$name.wat` files exist, they will be linked using `Linker` |
| 21 |
/// such that the `lib-` ones are not `dlopen`-able but the `dlopen-lib-` ones |
| 22 |
/// are. |
| 23 |
/// * [required] `module.wit` *or* `lib-$name.wat` and `dlopen-lib-$name.wat` |
| 24 |
/// corresponding to the WAT files above - WIT package(s) describing the |
| 25 |
/// interfaces of the `module.wat` or `lib-$name.wat` and |
| 26 |
/// `dlopen-lib-$name.wat` files. Must have a `default world` |
| 27 |
/// * [optional] `adapt-$name.wat` - optional adapter for the module name |
| 28 |
/// `$name`, can be specified for multiple `$name`s. Alternatively, if $name |
| 29 |
/// doesn't work as part of a filename (e.g. contains forward slashes), it may |
| 30 |
/// be specified on the first line of the file with the prefix `;; module name: |
| 31 |
/// `, e.g. `;; module name: wasi:cli/[email protected]`. |
| 32 |
/// * [optional] `adapt-$name.wit` - required for each `*.wat` adapter to |
| 33 |
/// describe imports/exports of the adapter. |
| 34 |
/// * [optional] `stub-missing-functions` - if linking libraries and this file |
| 35 |
/// exists, `Linker::stub_missing_functions` will be set to `true`. The |
| 36 |
/// contents of the file are ignored. |
| 37 |
/// * [optional] `use-built-in-libdl` - if linking libraries and this file |
| 38 |
/// exists, `Linker::use_built_in_libdl` will be set to `true`. The contents |
| 39 |
/// of the file are ignored. |
| 40 |
/// |
| 41 |
/// And the output files are one of the following: |
| 42 |
/// |
| 43 |
/// * `component.wat` - the expected encoded component in text format if the |
| 44 |
/// encoding is expected to succeed. |
| 45 |
/// * `component.wit` - if `component.wat` exists this is the inferred interface |
| 46 |
/// of the component. |
| 47 |
/// * `error.txt` - the expected error message if the encoding is expected to |
| 48 |
/// fail. |
| 49 |
/// |
| 50 |
/// The test encodes a component based on the input files. If the encoding |
| 51 |
/// succeeds, it expects the output to match `component.wat`. If the encoding |
| 52 |
/// fails, it expects the output to match `error.txt`. |
| 53 |
/// |
| 54 |
/// Run the test with the environment variable `BLESS` set to update |
| 55 |
/// either `component.wat` or `error.txt` depending on the outcome of the encoding. |
| 56 |
fn main() -> Result<()> { |
| 57 |
drop(env_logger::try_init()); |
| 58 |
|
| 59 |
let mut trials = Vec::new(); |
| 60 |
for entry in fs::read_dir("tests/components")? { |
| 61 |
let path = entry?.path(); |
| 62 |
if !path.is_dir() { |
| 63 |
continue; |
| 64 |
} |
| 65 |
|
| 66 |
trials.push(Trial::test(path.to_str().unwrap().to_string(), move || { |
| 67 |
run_test(&path).map_err(|e| format!("{e:?}").into()) |
| 68 |
})); |
| 69 |
} |
| 70 |
|
| 71 |
let mut args = Arguments::from_args(); |
| 72 |
if cfg!(target_family = "wasm") && !cfg!(target_feature = "atomics") { |
| 73 |
args.test_threads = Some(1); |
| 74 |
} |
| 75 |
libtest_mimic::run(&args, trials).exit(); |
| 76 |
} |
| 77 |
|
| 78 |
fn run_test(path: &Path) -> Result<()> { |
| 79 |
let test_case = path.file_stem().unwrap().to_str().unwrap(); |
| 80 |
let mut resolve = Resolve::default(); |
| 81 |
let (pkg_id, _) = resolve.push_dir(&path)?; |
| 82 |
|
| 83 |
// If this test case contained multiple packages, create separate sub-directories for |
| 84 |
// each. |
| 85 |
let path = path.to_path_buf(); |
| 86 |
|
| 87 |
let module_path = path.join("module.wat"); |
| 88 |
let mut adapters = glob::glob(path.join("adapt-*.wat").to_str().unwrap())?; |
| 89 |
let result = if module_path.is_file() { |
| 90 |
let module = read_core_module(&module_path, &resolve, pkg_id) |
| 91 |
.with_context(|| format!("failed to read core module at {module_path:?}"))?; |
| 92 |
adapters |
| 93 |
.try_fold( |
| 94 |
ComponentEncoder::default().module(&module)?, |
| 95 |
|encoder, path| { |
| 96 |
let (name, wasm) = read_name_and_module("adapt-", &path?, &resolve, pkg_id)?; |
| 97 |
Ok::<_, Error>(encoder.adapter(&name, &wasm)?) |
| 98 |
}, |
| 99 |
)? |
| 100 |
.encode() |
| 101 |
} else { |
| 102 |
let mut libs = glob::glob(path.join("lib-*.wat").to_str().unwrap())? |
| 103 |
.map(|path| Ok(("lib-", path?, false))) |
| 104 |
.chain( |
| 105 |
glob::glob(path.join("dlopen-lib-*.wat").to_str().unwrap())? |
| 106 |
.map(|path| Ok(("dlopen-lib-", path?, true))), |
| 107 |
) |
| 108 |
.collect::<Result<Vec<_>>>()?; |
| 109 |
|
| 110 |
// Sort list to ensure deterministic order, which determines priority in cases of duplicate symbols: |
| 111 |
libs.sort_by(|(_, a, _), (_, b, _)| a.cmp(b)); |
| 112 |
|
| 113 |
let mut linker = Linker::default().validate(false); |
| 114 |
|
| 115 |
if path.join("stub-missing-functions").is_file() { |
| 116 |
linker = linker.stub_missing_functions(true); |
| 117 |
} |
| 118 |
|
| 119 |
if path.join("use-built-in-libdl").is_file() { |
| 120 |
linker = linker.use_built_in_libdl(true); |
| 121 |
} |
| 122 |
|
| 123 |
let linker = libs |
| 124 |
.into_iter() |
| 125 |
.try_fold(linker, |linker, (prefix, path, dl_openable)| { |
| 126 |
let (name, wasm) = read_name_and_module(prefix, &path, &resolve, pkg_id)?; |
| 127 |
Ok::<_, Error>(linker.library(&name, &wasm, dl_openable)?) |
| 128 |
})?; |
| 129 |
|
| 130 |
adapters |
| 131 |
.try_fold(linker, |linker, path| { |
| 132 |
let (name, wasm) = read_name_and_module("adapt-", &path?, &resolve, pkg_id)?; |
| 133 |
Ok::<_, Error>(linker.adapter(&name, &wasm)?) |
| 134 |
})? |
| 135 |
.encode() |
| 136 |
}; |
| 137 |
let component_path = path.join("component.wat"); |
| 138 |
let component_wit_path = path.join("component.wit.print"); |
| 139 |
let error_path = path.join("error.txt"); |
| 140 |
|
| 141 |
let bytes = match result { |
| 142 |
Ok(bytes) => { |
| 143 |
if test_case.starts_with("error-") { |
| 144 |
bail!("expected an error but got success"); |
| 145 |
} |
| 146 |
bytes |
| 147 |
} |
| 148 |
Err(err) => { |
| 149 |
if !test_case.starts_with("error-") { |
| 150 |
return Err(err); |
| 151 |
} |
| 152 |
assert_output(&format!("{err:#}"), &error_path)?; |
| 153 |
return Ok(()); |
| 154 |
} |
| 155 |
}; |
| 156 |
|
| 157 |
Validator::new_with_features(WasmFeatures::all()) |
| 158 |
.validate_all(&bytes) |
| 159 |
.context("failed to validate component output")?; |
| 160 |
|
| 161 |
let wat = wasmprinter::print_bytes(&bytes).context("failed to print bytes")?; |
| 162 |
assert_output(&wat, &component_path)?; |
| 163 |
let mut parser = Parser::new(0); |
| 164 |
parser.set_features(WasmFeatures::all()); |
| 165 |
let (pkg, resolve) = match wit_component::decode_reader(bytes.as_slice()) |
| 166 |
.context("failed to decode resolve")? |
| 167 |
{ |
| 168 |
DecodedWasm::WitPackage(..) => unreachable!(), |
| 169 |
DecodedWasm::Component(resolve, world) => (resolve.worlds[world].package.unwrap(), resolve), |
| 170 |
}; |
| 171 |
let mut printer = WitPrinter::default(); |
| 172 |
printer |
| 173 |
.print(&resolve, pkg, &[]) |
| 174 |
.context("failed to print WIT")?; |
| 175 |
let wit = printer.output.to_string(); |
| 176 |
assert_output(&wit, &component_wit_path)?; |
| 177 |
|
| 178 |
UnresolvedPackageGroup::parse(&component_wit_path, &wit) |
| 179 |
.context("failed to parse printed WIT")?; |
| 180 |
|
| 181 |
// Check that the producer data got piped through properly |
| 182 |
match Payload::from_binary(&bytes).unwrap() { |
| 183 |
// Depends on the ComponentEncoder always putting the first module as the 0th child: |
| 184 |
Payload::Component { children, .. } => match &children[0] { |
| 185 |
Payload::Module(Metadata { producers, .. }) => { |
| 186 |
let producers = producers.as_ref().expect("child module has producers"); |
| 187 |
let processed_by = producers |
| 188 |
.get("processed-by") |
| 189 |
.expect("child has processed-by section"); |
| 190 |
assert_eq!( |
| 191 |
processed_by |
| 192 |
.get("wit-component") |
| 193 |
.expect("wit-component producer present"), |
| 194 |
env!("CARGO_PKG_VERSION") |
| 195 |
); |
| 196 |
if module_path.is_file() { |
| 197 |
assert_eq!( |
| 198 |
processed_by |
| 199 |
.get("my-fake-bindgen") |
| 200 |
.expect("added bindgen field present"), |
| 201 |
"123.45" |
| 202 |
); |
| 203 |
} else { |
| 204 |
// Otherwise, we used `Linker`, which synthesizes the |
| 205 |
// "main" module and thus won't have `my-fake-bindgen` |
| 206 |
} |
| 207 |
} |
| 208 |
_ => panic!("expected child to be a module"), |
| 209 |
}, |
| 210 |
_ => panic!("expected top level metadata of component"), |
| 211 |
} |
| 212 |
|
| 213 |
Ok(()) |
| 214 |
} |
| 215 |
|
| 216 |
fn read_name_and_module( |
| 217 |
prefix: &str, |
| 218 |
path: &Path, |
| 219 |
resolve: &Resolve, |
| 220 |
pkg: PackageId, |
| 221 |
) -> Result<(String, Vec<u8>)> { |
| 222 |
let wasm = read_core_module(path, resolve, pkg) |
| 223 |
.with_context(|| format!("failed to read core module at {path:?}"))?; |
| 224 |
let stem = path.file_stem().unwrap().to_str().unwrap(); |
| 225 |
let name = if let Some(name) = fs::read_to_string(path)? |
| 226 |
.lines() |
| 227 |
.next() |
| 228 |
.and_then(|line| line.strip_prefix(";; module name: ")) |
| 229 |
{ |
| 230 |
name.to_owned() |
| 231 |
} else { |
| 232 |
stem.trim_start_matches(prefix).to_owned() |
| 233 |
}; |
| 234 |
Ok((name, wasm)) |
| 235 |
} |
| 236 |
|
| 237 |
/// Parses the core wasm module at `path`, expected as a `*.wat` file. |
| 238 |
/// |
| 239 |
/// The `resolve` and `pkg` are the parsed WIT package from this test's |
| 240 |
/// directory and the `path`'s filename is used to find a WIT document of the |
| 241 |
/// corresponding name which should have a world that `path` ascribes to. |
| 242 |
fn read_core_module(path: &Path, resolve: &Resolve, pkg: PackageId) -> Result<Vec<u8>> { |
| 243 |
let mut wasm = wat::parse_file(path)?; |
| 244 |
let name = path.file_stem().and_then(|s| s.to_str()).unwrap(); |
| 245 |
let world = resolve |
| 246 |
.select_world(&[pkg], Some(name)) |
| 247 |
.context("failed to select a world")?; |
| 248 |
|
| 249 |
// Add this producer data to the wit-component metadata so we can make sure it gets through the |
| 250 |
// translation: |
| 251 |
let mut producers = wasm_metadata::Producers::empty(); |
| 252 |
producers.add("processed-by", "my-fake-bindgen", "123.45"); |
| 253 |
|
| 254 |
let encoded = |
| 255 |
wit_component::metadata::encode(resolve, world, StringEncoding::UTF8, Some(&producers))?; |
| 256 |
|
| 257 |
let section = wasm_encoder::CustomSection { |
| 258 |
name: "component-type".into(), |
| 259 |
data: Cow::Borrowed(&encoded), |
| 260 |
}; |
| 261 |
wasm.push(section.id()); |
| 262 |
section.encode(&mut wasm); |
| 263 |
Ok(wasm) |
| 264 |
} |
| 265 |
|
| 266 |
fn assert_output(contents: &str, path: &Path) -> Result<()> { |
| 267 |
let contents = contents.replace("\r\n", "\n").replace( |
| 268 |
concat!("\"", env!("CARGO_PKG_VERSION"), "\""), |
| 269 |
"\"$CARGO_PKG_VERSION\"", |
| 270 |
); |
| 271 |
if std::env::var_os("BLESS").is_some() { |
| 272 |
fs::write(path, contents)?; |
| 273 |
} else { |
| 274 |
match fs::read_to_string(path) { |
| 275 |
Ok(expected) => { |
| 276 |
assert_eq!( |
| 277 |
expected.replace("\r\n", "\n").trim(), |
| 278 |
contents.trim(), |
| 279 |
"failed baseline comparison ({})", |
| 280 |
path.display(), |
| 281 |
); |
| 282 |
} |
| 283 |
Err(_) => { |
| 284 |
panic!("expected {path:?} to contain\n{contents}"); |
| 285 |
} |
| 286 |
} |
| 287 |
} |
| 288 |
Ok(()) |
| 289 |
} |