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