1 use heck::*;
2 use std::collections::{BTreeMap, HashSet};
3 use std::env;
4 use std::fs;
5 use std::path::{Path, PathBuf};
6 use std::process::Command;
7 use wit_component::ComponentEncoder;
8 
9 fn main() {
10     let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
11 
12     Artifacts {
13         out_dir,
14         deps: HashSet::default(),
15     }
16     .build();
17 }
18 
19 struct Artifacts {
20     out_dir: PathBuf,
21     deps: HashSet<String>,
22 }
23 
24 struct Test {
25     /// Not all tests can be built at build-time, for example C/C++ tests require
26     /// the `WASI_SDK_PATH` environment variable which isn't available on all
27     /// machines. The `Option` here encapsulates tests that were not able to be
28     /// built.
29     ///
30     /// For tests that were not able to be built their error is deferred to
31     /// test-time when the test is actually run. For C/C++ tests this means that
32     /// only when running debuginfo tests does the error show up, for example.
33     core_wasm: Option<PathBuf>,
34 
35     name: String,
36 }
37 
38 impl Artifacts {
39     fn build(&mut self) {
40         // Build adapters used below for componentization.
41         let reactor_adapter = self.build_adapter("reactor", &[]);
42         let command_adapter =
43             self.build_adapter("command", &["--no-default-features", "--features=command"]);
44         let proxy_adapter =
45             self.build_adapter("proxy", &["--no-default-features", "--features=proxy"]);
46 
47         // Build all test programs both in Rust and C/C++.
48         let mut tests = Vec::new();
49         self.build_rust_tests(&mut tests);
50         self.build_non_rust_tests(&mut tests);
51 
52         // With all our `tests` now compiled generate various macos for each
53         // test along with constants pointing to various paths. Note that
54         // components are created here as well from core modules.
55         let mut kinds = BTreeMap::new();
56         let mut generated_code = String::new();
57         let missing_sdk_path =
58             PathBuf::from("Asset not compiled, WASI_SDK_PATH missing at compile time");
59         for test in tests.iter() {
60             let camel = test.name.to_shouty_snake_case();
61 
62             generated_code += &format!(
63                 "pub const {camel}: &'static str = {:?};\n",
64                 test.core_wasm.as_deref().unwrap_or(&missing_sdk_path)
65             );
66 
67             // Bucket, based on the name of the test, into a "kind" which
68             // generates a `foreach_*` macro below.
69             let kind = match test.name.as_str() {
70                 s if s.starts_with("http_") => "http",
71                 s if s.starts_with("preview1_") => "preview1",
72                 s if s.starts_with("preview2_") => "preview2",
73                 s if s.starts_with("cli_") => "cli",
74                 s if s.starts_with("api_") => "api",
75                 s if s.starts_with("nn_") => "nn",
76                 s if s.starts_with("piped_") => "piped",
77                 s if s.starts_with("dwarf_") => "dwarf",
78                 s if s.starts_with("config_") => "config",
79                 s if s.starts_with("keyvalue_") => "keyvalue",
80                 s if s.starts_with("tls_") => "tls",
81                 s if s.starts_with("async_") => "async",
82                 s if s.starts_with("p3_http_") => "p3_http",
83                 s if s.starts_with("p3_api_") => "p3_api",
84                 s if s.starts_with("p3_") => "p3",
85                 // If you're reading this because you hit this panic, either add
86                 // it to a test suite above or add a new "suite". The purpose of
87                 // the categorization above is to have a static assertion that
88                 // tests added are actually run somewhere, so as long as you're
89                 // also adding test code somewhere that's ok.
90                 other => {
91                     panic!("don't know how to classify test name `{other}` to a kind")
92                 }
93             };
94             if !kind.is_empty() {
95                 kinds.entry(kind).or_insert(Vec::new()).push(&test.name);
96             }
97 
98             // Generate a component from each test.
99             if test.name == "dwarf_imported_memory"
100                 || test.name == "dwarf_shared_memory"
101                 || test.name.starts_with("nn_witx")
102             {
103                 continue;
104             }
105             let adapter = match test.name.as_str() {
106                 "reactor" => &reactor_adapter,
107                 s if s.starts_with("p3_") => &reactor_adapter,
108                 s if s.starts_with("api_proxy") => &proxy_adapter,
109                 _ => &command_adapter,
110             };
111             let path = match &test.core_wasm {
112                 Some(path) => self.compile_component(path, adapter),
113                 None => missing_sdk_path.clone(),
114             };
115             generated_code += &format!("pub const {camel}_COMPONENT: &'static str = {path:?};\n");
116         }
117 
118         for (kind, targets) in kinds {
119             generated_code += &format!("#[macro_export]");
120             generated_code += &format!("macro_rules! foreach_{kind} {{\n");
121             generated_code += &format!("    ($mac:ident) => {{\n");
122             for target in targets {
123                 generated_code += &format!("$mac!({target});\n")
124             }
125             generated_code += &format!("    }}\n");
126             generated_code += &format!("}}\n");
127         }
128 
129         std::fs::write(self.out_dir.join("gen.rs"), generated_code).unwrap();
130     }
131 
132     fn build_rust_tests(&mut self, tests: &mut Vec<Test>) {
133         println!("cargo:rerun-if-env-changed=MIRI_TEST_CWASM_DIR");
134         let release_mode = env::var_os("MIRI_TEST_CWASM_DIR").is_some();
135 
136         let mut cmd = cargo();
137         cmd.arg("build");
138         if release_mode {
139             cmd.arg("--release");
140         }
141         cmd.arg("--target=wasm32-wasip1")
142             .arg("--package=test-programs")
143             .env("CARGO_TARGET_DIR", &self.out_dir)
144             .env("CARGO_PROFILE_DEV_DEBUG", "2")
145             .env("RUSTFLAGS", rustflags())
146             .env_remove("CARGO_ENCODED_RUSTFLAGS");
147         eprintln!("running: {cmd:?}");
148         let status = cmd.status().unwrap();
149         assert!(status.success());
150 
151         let meta = cargo_metadata::MetadataCommand::new().exec().unwrap();
152         let targets = meta
153             .packages
154             .iter()
155             .find(|p| p.name == "test-programs")
156             .unwrap()
157             .targets
158             .iter()
159             .filter(move |t| t.kind == &[cargo_metadata::TargetKind::Bin])
160             .map(|t| &t.name)
161             .collect::<Vec<_>>();
162 
163         for target in targets {
164             let wasm = self
165                 .out_dir
166                 .join("wasm32-wasip1")
167                 .join(if release_mode { "release" } else { "debug" })
168                 .join(format!("{target}.wasm"));
169             self.read_deps_of(&wasm);
170             tests.push(Test {
171                 core_wasm: Some(wasm),
172                 name: target.to_string(),
173             })
174         }
175     }
176 
177     // Build the WASI Preview 1 adapter, and get the binary:
178     fn build_adapter(&mut self, name: &str, features: &[&str]) -> Vec<u8> {
179         let mut cmd = cargo();
180         cmd.arg("build")
181             .arg("--release")
182             .arg("--package=wasi-preview1-component-adapter")
183             .arg("--target=wasm32-unknown-unknown")
184             .env("CARGO_TARGET_DIR", &self.out_dir)
185             .env("RUSTFLAGS", rustflags())
186             .env_remove("CARGO_ENCODED_RUSTFLAGS");
187         for f in features {
188             cmd.arg(f);
189         }
190         eprintln!("running: {cmd:?}");
191         let status = cmd.status().unwrap();
192         assert!(status.success());
193 
194         let artifact = self
195             .out_dir
196             .join("wasm32-unknown-unknown")
197             .join("release")
198             .join("wasi_snapshot_preview1.wasm");
199         let adapter = self
200             .out_dir
201             .join(format!("wasi_snapshot_preview1.{name}.wasm"));
202         std::fs::copy(&artifact, &adapter).unwrap();
203         self.read_deps_of(&artifact);
204         println!("wasi {name} adapter: {:?}", &adapter);
205         fs::read(&adapter).unwrap()
206     }
207 
208     // Compile a component, return the path of the binary:
209     fn compile_component(&self, wasm: &Path, adapter: &[u8]) -> PathBuf {
210         println!("creating a component from {wasm:?}");
211         let module = fs::read(wasm).expect("read wasm module");
212         let component = ComponentEncoder::default()
213             .module(module.as_slice())
214             .unwrap()
215             .validate(true)
216             .adapter("wasi_snapshot_preview1", adapter)
217             .unwrap()
218             .encode()
219             .expect("module can be translated to a component");
220         let out_dir = wasm.parent().unwrap();
221         let stem = wasm.file_stem().unwrap().to_str().unwrap();
222         let component_path = out_dir.join(format!("{stem}.component.wasm"));
223         fs::write(&component_path, component).expect("write component to disk");
224         component_path
225     }
226 
227     fn build_non_rust_tests(&mut self, tests: &mut Vec<Test>) {
228         const ASSETS_REL_SRC_DIR: &'static str = "../src/bin";
229         println!("cargo:rerun-if-changed={ASSETS_REL_SRC_DIR}");
230 
231         for entry in fs::read_dir(ASSETS_REL_SRC_DIR).unwrap() {
232             let entry = entry.unwrap();
233             let path = entry.path();
234             let name = path.file_stem().unwrap().to_str().unwrap().to_owned();
235             match path.extension().and_then(|s| s.to_str()) {
236                 // Compile C/C++ tests with clang
237                 Some("c") | Some("cpp") | Some("cc") => self.build_c_or_cpp_test(path, name, tests),
238 
239                 // just a header, part of another test.
240                 Some("h") => {}
241 
242                 // Convert the text format to binary and use it as a test.
243                 Some("wat") => {
244                     let wasm = wat::parse_file(&path).unwrap();
245                     let core_wasm = self.out_dir.join(&name).with_extension("wasm");
246                     fs::write(&core_wasm, &wasm).unwrap();
247                     tests.push(Test {
248                         name,
249                         core_wasm: Some(core_wasm),
250                     });
251                 }
252 
253                 // these are built above in `build_rust_tests`
254                 Some("rs") => {}
255 
256                 // Prevent stray files for now that we don't understand.
257                 Some(_) => panic!("unknown file extension on {path:?}"),
258 
259                 None => unreachable!(),
260             }
261         }
262     }
263 
264     fn build_c_or_cpp_test(&mut self, path: PathBuf, name: String, tests: &mut Vec<Test>) {
265         println!("compiling {path:?}");
266         println!("cargo:rerun-if-changed={}", path.display());
267         let contents = std::fs::read_to_string(&path).unwrap();
268         let config =
269             wasmtime_test_util::wast::parse_test_config::<CTestConfig>(&contents, "//!").unwrap();
270 
271         if config.skip {
272             return;
273         }
274 
275         // The debug tests relying on these assets are ignored by default,
276         // so we cannot force the requirement of having a working WASI SDK
277         // install on everyone. At the same time, those tests (due to their
278         // monolithic nature), are always compiled, so we still have to
279         // produce the path constants. To solve this, we move the failure
280         // of missing WASI SDK from compile time to runtime by producing
281         // fake paths (that themselves will serve as diagnostic messages).
282         let wasi_sdk_path = match env::var_os("WASI_SDK_PATH") {
283             Some(path) => PathBuf::from(path),
284             None => {
285                 tests.push(Test {
286                     name,
287                     core_wasm: None,
288                 });
289                 return;
290             }
291         };
292 
293         let wasm_path = self.out_dir.join(&name).with_extension("wasm");
294 
295         let mut cmd = Command::new(wasi_sdk_path.join("bin/wasm32-wasip1-clang"));
296         cmd.arg(&path);
297         for file in config.extra_files.iter() {
298             cmd.arg(path.parent().unwrap().join(file));
299         }
300         cmd.arg("-g");
301         cmd.args(&config.flags);
302         cmd.arg("-o");
303         cmd.arg(&wasm_path);
304         // If optimizations are enabled, clang will look for wasm-opt in PATH
305         // and run it. This will strip DWARF debug info, which we don't want.
306         cmd.env("PATH", "");
307         println!("running: {cmd:?}");
308         let result = cmd.status().expect("failed to spawn clang");
309         assert!(result.success());
310 
311         if config.dwp {
312             let mut dwp = Command::new(wasi_sdk_path.join("bin/llvm-dwp"));
313             dwp.arg("-e")
314                 .arg(&wasm_path)
315                 .arg("-o")
316                 .arg(self.out_dir.join(&name).with_extension("dwp"));
317             assert!(dwp.status().expect("failed to spawn llvm-dwp").success());
318         }
319 
320         tests.push(Test {
321             name,
322             core_wasm: Some(wasm_path),
323         });
324     }
325 
326     /// Helper function to read the `*.d` file that corresponds to `artifact`, an
327     /// artifact of a Cargo compilation.
328     ///
329     /// This function will "parse" the makefile-based dep-info format to learn about
330     /// what files each binary depended on to ensure that this build script reruns
331     /// if any of these files change.
332     ///
333     /// See
334     /// <https://doc.rust-lang.org/nightly/cargo/reference/build-cache.html#dep-info-files>
335     /// for more info.
336     fn read_deps_of(&mut self, artifact: &Path) {
337         let deps_file = artifact.with_extension("d");
338         let contents = std::fs::read_to_string(&deps_file).expect("failed to read deps file");
339         for line in contents.lines() {
340             let Some(pos) = line.find(": ") else {
341                 continue;
342             };
343             let line = &line[pos + 2..];
344             let mut parts = line.split_whitespace();
345             while let Some(part) = parts.next() {
346                 let mut file = part.to_string();
347                 while file.ends_with('\\') {
348                     file.pop();
349                     file.push(' ');
350                     file.push_str(parts.next().unwrap());
351                 }
352                 if !self.deps.contains(&file) {
353                     println!("cargo:rerun-if-changed={file}");
354                     self.deps.insert(file);
355                 }
356             }
357         }
358     }
359 }
360 
361 #[derive(serde_derive::Deserialize)]
362 #[serde(deny_unknown_fields, rename_all = "kebab-case")]
363 struct CTestConfig {
364     #[serde(default)]
365     flags: Vec<String>,
366     #[serde(default)]
367     extra_files: Vec<String>,
368     #[serde(default)]
369     dwp: bool,
370     #[serde(default)]
371     skip: bool,
372 }
373 
374 fn cargo() -> Command {
375     // Miri configures its own sysroot which we don't want to use, so remove
376     // miri's own wrappers around rustc to ensure that we're using the real
377     // rustc to build these programs.
378     let mut cargo = Command::new("cargo");
379     if std::env::var("CARGO_CFG_MIRI").is_ok() {
380         cargo.env_remove("RUSTC").env_remove("RUSTC_WRAPPER");
381     }
382     cargo
383 }
384 
385 fn rustflags() -> &'static str {
386     match option_env!("RUSTFLAGS") {
387         // If we're in CI which is denying warnings then deny warnings to code
388         // built here too to keep the tree warning-free.
389         Some(s) if s.contains("-D warnings") => "-D warnings",
390         _ => "",
391     }
392 }
393