1 #![cfg(not(miri))] 2 3 use anyhow::{Result, bail}; 4 use std::fs::File; 5 use std::io::Write; 6 use std::path::Path; 7 use std::process::{Command, ExitStatus, Output, Stdio}; 8 use tempfile::{NamedTempFile, TempDir}; 9 10 // Run the wasmtime CLI with the provided args and return the `Output`. 11 // If the `stdin` is `Some`, opens the file and redirects to the child's stdin. 12 pub fn run_wasmtime_for_output(args: &[&str], stdin: Option<&Path>) -> Result<Output> { 13 let mut cmd = get_wasmtime_command()?; 14 cmd.args(args); 15 if let Some(file) = stdin { 16 cmd.stdin(File::open(file)?); 17 } 18 cmd.output().map_err(Into::into) 19 } 20 21 /// Get the Wasmtime CLI as a [Command]. 22 pub fn get_wasmtime_command() -> Result<Command> { 23 let mut cmd = wasmtime_test_util::command(get_wasmtime_path()); 24 25 // Ignore this if it's specified in the environment to allow tests to run in 26 // "default mode" by default. 27 cmd.env_remove("WASMTIME_NEW_CLI"); 28 29 Ok(cmd) 30 } 31 32 fn get_wasmtime_path() -> &'static str { 33 env!("CARGO_BIN_EXE_wasmtime") 34 } 35 36 // Run the wasmtime CLI with the provided args and, if it succeeds, return 37 // the standard output in a `String`. 38 pub fn run_wasmtime(args: &[&str]) -> Result<String> { 39 let output = run_wasmtime_for_output(args, None)?; 40 if !output.status.success() { 41 bail!( 42 "Failed to execute wasmtime with: {:?}\nstatus: {}\n{}", 43 args, 44 output.status, 45 String::from_utf8_lossy(&output.stderr) 46 ); 47 } 48 Ok(String::from_utf8(output.stdout).unwrap()) 49 } 50 51 fn build_wasm(wat_path: impl AsRef<Path>) -> Result<NamedTempFile> { 52 let mut wasm_file = NamedTempFile::new()?; 53 let wasm = wat::parse_file(wat_path)?; 54 wasm_file.write(&wasm)?; 55 Ok(wasm_file) 56 } 57 58 // Very basic use case: compile binary wasm file and run specific function with arguments. 59 #[test] 60 fn run_wasmtime_simple() -> Result<()> { 61 let wasm = build_wasm("tests/all/cli_tests/simple.wat")?; 62 run_wasmtime(&[ 63 "run", 64 "--invoke", 65 "simple", 66 "-Ccache=n", 67 wasm.path().to_str().unwrap(), 68 "4", 69 ])?; 70 Ok(()) 71 } 72 73 // Wasmtime shall fail when not enough arguments were provided. 74 #[test] 75 fn run_wasmtime_simple_fail_no_args() -> Result<()> { 76 let wasm = build_wasm("tests/all/cli_tests/simple.wat")?; 77 assert!( 78 run_wasmtime(&[ 79 "run", 80 "-Ccache=n", 81 "--invoke", 82 "simple", 83 wasm.path().to_str().unwrap(), 84 ]) 85 .is_err(), 86 "shall fail" 87 ); 88 Ok(()) 89 } 90 91 #[test] 92 fn run_coredump_smoketest() -> Result<()> { 93 let wasm = build_wasm("tests/all/cli_tests/coredump_smoketest.wat")?; 94 let coredump_file = NamedTempFile::new()?; 95 let coredump_arg = format!("-Dcoredump={}", coredump_file.path().display()); 96 let err = run_wasmtime(&[ 97 "run", 98 "--invoke", 99 "a", 100 "-Ccache=n", 101 &coredump_arg, 102 wasm.path().to_str().unwrap(), 103 ]) 104 .unwrap_err(); 105 assert!(err.to_string().contains(&format!( 106 "core dumped at {}", 107 coredump_file.path().display() 108 ))); 109 Ok(()) 110 } 111 112 // Running simple wat 113 #[test] 114 fn run_wasmtime_simple_wat() -> Result<()> { 115 let wasm = build_wasm("tests/all/cli_tests/simple.wat")?; 116 run_wasmtime(&[ 117 "run", 118 "--invoke", 119 "simple", 120 "-Ccache=n", 121 wasm.path().to_str().unwrap(), 122 "4", 123 ])?; 124 assert_eq!( 125 run_wasmtime(&[ 126 "run", 127 "--invoke", 128 "get_f32", 129 "-Ccache=n", 130 wasm.path().to_str().unwrap(), 131 ])?, 132 "100\n" 133 ); 134 assert_eq!( 135 run_wasmtime(&[ 136 "run", 137 "--invoke", 138 "get_f64", 139 "-Ccache=n", 140 wasm.path().to_str().unwrap(), 141 ])?, 142 "100\n" 143 ); 144 Ok(()) 145 } 146 147 // Running a wat that traps. 148 #[test] 149 fn run_wasmtime_unreachable_wat() -> Result<()> { 150 let wasm = build_wasm("tests/all/cli_tests/unreachable.wat")?; 151 let output = run_wasmtime_for_output(&[wasm.path().to_str().unwrap(), "-Ccache=n"], None)?; 152 153 assert_ne!(output.stderr, b""); 154 assert_eq!(output.stdout, b""); 155 156 assert_trap_code(&output.status); 157 Ok(()) 158 } 159 160 fn assert_trap_code(status: &ExitStatus) { 161 let code = status 162 .code() 163 .expect("wasmtime process should exit normally"); 164 165 // Test for the specific error code Wasmtime uses to indicate a trap return. 166 #[cfg(unix)] 167 assert_eq!(code, 128 + libc::SIGABRT); 168 #[cfg(windows)] 169 assert_eq!(code, 3); 170 } 171 172 // Run a simple WASI hello world, snapshot0 edition. 173 #[test] 174 fn hello_wasi_snapshot0() -> Result<()> { 175 let wasm = build_wasm("tests/all/cli_tests/hello_wasi_snapshot0.wat")?; 176 for preview2 in ["-Spreview2=n", "-Spreview2=y"] { 177 let stdout = run_wasmtime(&["-Ccache=n", preview2, wasm.path().to_str().unwrap()])?; 178 assert_eq!(stdout, "Hello, world!\n"); 179 } 180 Ok(()) 181 } 182 183 // Run a simple WASI hello world, snapshot1 edition. 184 #[test] 185 fn hello_wasi_snapshot1() -> Result<()> { 186 let wasm = build_wasm("tests/all/cli_tests/hello_wasi_snapshot1.wat")?; 187 let stdout = run_wasmtime(&["-Ccache=n", wasm.path().to_str().unwrap()])?; 188 assert_eq!(stdout, "Hello, world!\n"); 189 Ok(()) 190 } 191 192 #[test] 193 fn timeout_in_start() -> Result<()> { 194 let wasm = build_wasm("tests/all/cli_tests/iloop-start.wat")?; 195 let output = run_wasmtime_for_output( 196 &[ 197 "run", 198 "-Wtimeout=1ms", 199 "-Ccache=n", 200 wasm.path().to_str().unwrap(), 201 ], 202 None, 203 )?; 204 assert!(!output.status.success()); 205 assert_eq!(output.stdout, b""); 206 let stderr = String::from_utf8_lossy(&output.stderr); 207 assert!( 208 stderr.contains("wasm trap: interrupt"), 209 "bad stderr: {stderr}" 210 ); 211 Ok(()) 212 } 213 214 #[test] 215 fn timeout_in_invoke() -> Result<()> { 216 let wasm = build_wasm("tests/all/cli_tests/iloop-invoke.wat")?; 217 let output = run_wasmtime_for_output( 218 &[ 219 "run", 220 "-Wtimeout=1ms", 221 "-Ccache=n", 222 wasm.path().to_str().unwrap(), 223 ], 224 None, 225 )?; 226 assert!(!output.status.success()); 227 assert_eq!(output.stdout, b""); 228 let stderr = String::from_utf8_lossy(&output.stderr); 229 assert!( 230 stderr.contains("wasm trap: interrupt"), 231 "bad stderr: {stderr}" 232 ); 233 Ok(()) 234 } 235 236 // Exit with a valid non-zero exit code, snapshot0 edition. 237 #[test] 238 fn exit2_wasi_snapshot0() -> Result<()> { 239 let wasm = build_wasm("tests/all/cli_tests/exit2_wasi_snapshot0.wat")?; 240 241 for preview2 in ["-Spreview2=n", "-Spreview2=y"] { 242 let output = run_wasmtime_for_output( 243 &["-Ccache=n", preview2, wasm.path().to_str().unwrap()], 244 None, 245 )?; 246 assert_eq!(output.status.code().unwrap(), 2); 247 } 248 Ok(()) 249 } 250 251 // Exit with a valid non-zero exit code, snapshot1 edition. 252 #[test] 253 fn exit2_wasi_snapshot1() -> Result<()> { 254 let wasm = build_wasm("tests/all/cli_tests/exit2_wasi_snapshot1.wat")?; 255 let output = run_wasmtime_for_output(&["-Ccache=n", wasm.path().to_str().unwrap()], None)?; 256 assert_eq!(output.status.code().unwrap(), 2); 257 Ok(()) 258 } 259 260 // Exit with a valid non-zero exit code, snapshot0 edition. 261 #[test] 262 fn exit125_wasi_snapshot0() -> Result<()> { 263 let wasm = build_wasm("tests/all/cli_tests/exit125_wasi_snapshot0.wat")?; 264 for preview2 in ["-Spreview2=n", "-Spreview2=y"] { 265 let output = run_wasmtime_for_output( 266 &["-Ccache=n", preview2, wasm.path().to_str().unwrap()], 267 None, 268 )?; 269 dbg!(&output); 270 assert_eq!(output.status.code().unwrap(), 125); 271 } 272 Ok(()) 273 } 274 275 // Exit with a valid non-zero exit code, snapshot1 edition. 276 #[test] 277 fn exit125_wasi_snapshot1() -> Result<()> { 278 let wasm = build_wasm("tests/all/cli_tests/exit125_wasi_snapshot1.wat")?; 279 let output = run_wasmtime_for_output(&["-Ccache=n", wasm.path().to_str().unwrap()], None)?; 280 assert_eq!(output.status.code().unwrap(), 125); 281 Ok(()) 282 } 283 284 // Exit with an invalid non-zero exit code, snapshot0 edition. 285 #[test] 286 fn exit126_wasi_snapshot0() -> Result<()> { 287 let wasm = build_wasm("tests/all/cli_tests/exit126_wasi_snapshot0.wat")?; 288 289 for preview2 in ["-Spreview2=n", "-Spreview2=y"] { 290 let output = run_wasmtime_for_output( 291 &["-Ccache=n", preview2, wasm.path().to_str().unwrap()], 292 None, 293 )?; 294 assert_eq!(output.status.code().unwrap(), 1); 295 assert!(output.stdout.is_empty()); 296 assert!(String::from_utf8_lossy(&output.stderr).contains("invalid exit status")); 297 } 298 Ok(()) 299 } 300 301 // Exit with an invalid non-zero exit code, snapshot1 edition. 302 #[test] 303 fn exit126_wasi_snapshot1() -> Result<()> { 304 let wasm = build_wasm("tests/all/cli_tests/exit126_wasi_snapshot1.wat")?; 305 let output = run_wasmtime_for_output(&[wasm.path().to_str().unwrap(), "-Ccache=n"], None)?; 306 assert_eq!(output.status.code().unwrap(), 1); 307 assert!(output.stdout.is_empty()); 308 assert!(String::from_utf8_lossy(&output.stderr).contains("invalid exit status")); 309 Ok(()) 310 } 311 312 // Run a minimal command program. 313 #[test] 314 fn minimal_command() -> Result<()> { 315 let wasm = build_wasm("tests/all/cli_tests/minimal-command.wat")?; 316 let stdout = run_wasmtime(&["-Ccache=n", wasm.path().to_str().unwrap()])?; 317 assert_eq!(stdout, ""); 318 Ok(()) 319 } 320 321 // Run a minimal reactor program. 322 #[test] 323 fn minimal_reactor() -> Result<()> { 324 let wasm = build_wasm("tests/all/cli_tests/minimal-reactor.wat")?; 325 let stdout = run_wasmtime(&["-Ccache=n", wasm.path().to_str().unwrap()])?; 326 assert_eq!(stdout, ""); 327 Ok(()) 328 } 329 330 // Attempt to call invoke on a command. 331 #[test] 332 fn command_invoke() -> Result<()> { 333 let wasm = build_wasm("tests/all/cli_tests/minimal-command.wat")?; 334 run_wasmtime(&[ 335 "run", 336 "--invoke", 337 "_start", 338 "-Ccache=n", 339 wasm.path().to_str().unwrap(), 340 ])?; 341 Ok(()) 342 } 343 344 // Attempt to call invoke on a command. 345 #[test] 346 fn reactor_invoke() -> Result<()> { 347 let wasm = build_wasm("tests/all/cli_tests/minimal-reactor.wat")?; 348 run_wasmtime(&[ 349 "run", 350 "--invoke", 351 "_initialize", 352 "-Ccache=n", 353 wasm.path().to_str().unwrap(), 354 ])?; 355 Ok(()) 356 } 357 358 // Run the greeter test, which runs a preloaded reactor and a command. 359 #[test] 360 fn greeter() -> Result<()> { 361 let wasm = build_wasm("tests/all/cli_tests/greeter_command.wat")?; 362 let stdout = run_wasmtime(&[ 363 "run", 364 "-Ccache=n", 365 "--preload", 366 "reactor=tests/all/cli_tests/greeter_reactor.wat", 367 wasm.path().to_str().unwrap(), 368 ])?; 369 assert_eq!( 370 stdout, 371 "Hello _initialize\nHello _start\nHello greet\nHello done\n" 372 ); 373 Ok(()) 374 } 375 376 // Run the greeter test, but this time preload a command. 377 #[test] 378 fn greeter_preload_command() -> Result<()> { 379 let wasm = build_wasm("tests/all/cli_tests/greeter_reactor.wat")?; 380 let stdout = run_wasmtime(&[ 381 "run", 382 "-Ccache=n", 383 "--preload", 384 "reactor=tests/all/cli_tests/hello_wasi_snapshot1.wat", 385 wasm.path().to_str().unwrap(), 386 ])?; 387 assert_eq!(stdout, "Hello _initialize\n"); 388 Ok(()) 389 } 390 391 // Run the greeter test, which runs a preloaded reactor and a command. 392 #[test] 393 fn greeter_preload_callable_command() -> Result<()> { 394 let wasm = build_wasm("tests/all/cli_tests/greeter_command.wat")?; 395 let stdout = run_wasmtime(&[ 396 "run", 397 "-Ccache=n", 398 "--preload", 399 "reactor=tests/all/cli_tests/greeter_callable_command.wat", 400 wasm.path().to_str().unwrap(), 401 ])?; 402 assert_eq!(stdout, "Hello _start\nHello callable greet\nHello done\n"); 403 Ok(()) 404 } 405 406 // Ensure successful WASI exit call with FPR saving frames on stack for Windows x64 407 // See https://github.com/bytecodealliance/wasmtime/issues/1967 408 #[test] 409 fn exit_with_saved_fprs() -> Result<()> { 410 let wasm = build_wasm("tests/all/cli_tests/exit_with_saved_fprs.wat")?; 411 let output = run_wasmtime_for_output(&["-Ccache=n", wasm.path().to_str().unwrap()], None)?; 412 assert_eq!(output.status.code().unwrap(), 0); 413 assert!(output.stdout.is_empty()); 414 Ok(()) 415 } 416 417 #[test] 418 fn run_cwasm() -> Result<()> { 419 let td = TempDir::new()?; 420 let cwasm = td.path().join("foo.cwasm"); 421 let stdout = run_wasmtime(&[ 422 "compile", 423 "tests/all/cli_tests/simple.wat", 424 "-o", 425 cwasm.to_str().unwrap(), 426 ])?; 427 assert_eq!(stdout, ""); 428 let stdout = run_wasmtime(&["run", "--allow-precompiled", cwasm.to_str().unwrap()])?; 429 assert_eq!(stdout, ""); 430 Ok(()) 431 } 432 433 #[cfg(unix)] 434 #[test] 435 fn hello_wasi_snapshot0_from_stdin() -> Result<()> { 436 // Run a simple WASI hello world, snapshot0 edition. 437 // The module is piped from standard input. 438 let wasm = build_wasm("tests/all/cli_tests/hello_wasi_snapshot0.wat")?; 439 for preview2 in ["-Spreview2=n", "-Spreview2=y"] { 440 let stdout = { 441 let path = wasm.path(); 442 let args: &[&str] = &["-Ccache=n", preview2, "-"]; 443 let output = run_wasmtime_for_output(args, Some(path))?; 444 if !output.status.success() { 445 bail!( 446 "Failed to execute wasmtime with: {:?}\n{}", 447 args, 448 String::from_utf8_lossy(&output.stderr) 449 ); 450 } 451 Ok::<_, anyhow::Error>(String::from_utf8(output.stdout).unwrap()) 452 }?; 453 assert_eq!(stdout, "Hello, world!\n"); 454 } 455 Ok(()) 456 } 457 458 #[test] 459 fn specify_env() -> Result<()> { 460 // By default no env is inherited 461 let output = get_wasmtime_command()? 462 .args(&["run", "tests/all/cli_tests/print_env.wat"]) 463 .env("THIS_WILL_NOT", "show up in the output") 464 .output()?; 465 assert!(output.status.success()); 466 assert_eq!(String::from_utf8_lossy(&output.stdout), ""); 467 468 // Specify a single env var 469 let output = get_wasmtime_command()? 470 .args(&[ 471 "run", 472 "--env", 473 "FOO=bar", 474 "tests/all/cli_tests/print_env.wat", 475 ]) 476 .output()?; 477 assert!(output.status.success()); 478 assert_eq!(String::from_utf8_lossy(&output.stdout), "FOO=bar\n"); 479 480 // Inherit a single env var 481 let output = get_wasmtime_command()? 482 .args(&["run", "--env", "FOO", "tests/all/cli_tests/print_env.wat"]) 483 .env("FOO", "bar") 484 .output()?; 485 assert!(output.status.success()); 486 assert_eq!(String::from_utf8_lossy(&output.stdout), "FOO=bar\n"); 487 488 // Inherit a nonexistent env var 489 let output = get_wasmtime_command()? 490 .args(&[ 491 "run", 492 "--env", 493 "SURELY_THIS_ENV_VAR_DOES_NOT_EXIST_ANYWHERE_RIGHT", 494 "tests/all/cli_tests/print_env.wat", 495 ]) 496 .output()?; 497 assert!(output.status.success()); 498 499 // Inherit all env vars 500 let output = get_wasmtime_command()? 501 .args(&["run", "-Sinherit-env", "tests/all/cli_tests/print_env.wat"]) 502 .env("FOO", "bar") 503 .output()?; 504 assert!(output.status.success()); 505 let stdout = String::from_utf8_lossy(&output.stdout); 506 assert!(stdout.contains("FOO=bar"), "bad output: {stdout}"); 507 508 Ok(()) 509 } 510 511 #[cfg(unix)] 512 #[test] 513 fn run_cwasm_from_stdin() -> Result<()> { 514 use std::process::Stdio; 515 516 let td = TempDir::new()?; 517 let cwasm = td.path().join("foo.cwasm"); 518 let stdout = run_wasmtime(&[ 519 "compile", 520 "tests/all/cli_tests/simple.wat", 521 "-o", 522 cwasm.to_str().unwrap(), 523 ])?; 524 assert_eq!(stdout, ""); 525 526 // If stdin is literally the file itself then that should work 527 let args: &[&str] = &["run", "--allow-precompiled", "-"]; 528 let output = get_wasmtime_command()? 529 .args(args) 530 .stdin(File::open(&cwasm)?) 531 .output()?; 532 assert!(output.status.success(), "a file as stdin should work"); 533 534 // If stdin is a pipe, that should also work 535 let input = std::fs::read(&cwasm)?; 536 let mut child = get_wasmtime_command()? 537 .args(args) 538 .stdin(Stdio::piped()) 539 .stdout(Stdio::piped()) 540 .stderr(Stdio::piped()) 541 .spawn()?; 542 let mut stdin = child.stdin.take().unwrap(); 543 let t = std::thread::spawn(move || { 544 let _ = stdin.write_all(&input); 545 }); 546 let output = child.wait_with_output()?; 547 assert!(output.status.success()); 548 t.join().unwrap(); 549 Ok(()) 550 } 551 552 #[cfg(feature = "wasi-threads")] 553 #[test] 554 fn run_threads() -> Result<()> { 555 // Only run threaded tests on platforms that support threads. Also skip 556 // these tests with ASAN as it, rightfully, complains about a memory leak. 557 // The memory leak at this time is that child threads aren't joined with the 558 // main thread, meaning that allocations done on child threads are indeed 559 // leaked. 560 if crate::threads::engine().is_none() || cfg!(asan) { 561 return Ok(()); 562 } 563 let wasm = build_wasm("tests/all/cli_tests/threads.wat")?; 564 let stdout = run_wasmtime(&[ 565 "run", 566 "-Wthreads", 567 "-Sthreads", 568 "-Ccache=n", 569 wasm.path().to_str().unwrap(), 570 ])?; 571 572 assert!( 573 stdout 574 == "Called _start\n\ 575 Running wasi_thread_start\n\ 576 Running wasi_thread_start\n\ 577 Running wasi_thread_start\n\ 578 Done\n" 579 ); 580 Ok(()) 581 } 582 583 #[cfg(feature = "wasi-threads")] 584 #[test] 585 fn run_simple_with_wasi_threads() -> Result<()> { 586 // Skip this test on platforms that don't support threads. 587 if crate::threads::engine().is_none() { 588 return Ok(()); 589 } 590 // We expect to be able to run Wasm modules that do not have correct 591 // wasi-thread entry points or imported shared memory as long as no threads 592 // are spawned. 593 let wasm = build_wasm("tests/all/cli_tests/simple.wat")?; 594 let stdout = run_wasmtime(&[ 595 "run", 596 "-Wthreads", 597 "-Sthreads", 598 "-Ccache=n", 599 "--invoke", 600 "simple", 601 wasm.path().to_str().unwrap(), 602 "4", 603 ])?; 604 assert_eq!(stdout, "4\n"); 605 Ok(()) 606 } 607 608 #[test] 609 fn wasm_flags() -> Result<()> { 610 // Any argument after the wasm module should be interpreted as for the 611 // command itself 612 let stdout = run_wasmtime(&[ 613 "run", 614 "--", 615 "tests/all/cli_tests/print-arguments.wat", 616 "--argument", 617 "-for", 618 "the", 619 "command", 620 ])?; 621 assert_eq!( 622 stdout, 623 "\ 624 print-arguments.wat\n\ 625 --argument\n\ 626 -for\n\ 627 the\n\ 628 command\n\ 629 " 630 ); 631 let stdout = run_wasmtime(&["run", "--", "tests/all/cli_tests/print-arguments.wat", "-"])?; 632 assert_eq!( 633 stdout, 634 "\ 635 print-arguments.wat\n\ 636 -\n\ 637 " 638 ); 639 let stdout = run_wasmtime(&["run", "--", "tests/all/cli_tests/print-arguments.wat", "--"])?; 640 assert_eq!( 641 stdout, 642 "\ 643 print-arguments.wat\n\ 644 --\n\ 645 " 646 ); 647 let stdout = run_wasmtime(&[ 648 "run", 649 "--", 650 "tests/all/cli_tests/print-arguments.wat", 651 "--", 652 "--", 653 "-a", 654 "b", 655 ])?; 656 assert_eq!( 657 stdout, 658 "\ 659 print-arguments.wat\n\ 660 --\n\ 661 --\n\ 662 -a\n\ 663 b\n\ 664 " 665 ); 666 Ok(()) 667 } 668 669 #[test] 670 fn name_same_as_builtin_command() -> Result<()> { 671 // a bare subcommand shouldn't run successfully 672 let output = get_wasmtime_command()? 673 .current_dir("tests/all/cli_tests") 674 .arg("run") 675 .output()?; 676 assert!(!output.status.success()); 677 678 // a `--` prefix should let everything else get interpreted as a wasm 679 // module and arguments, even if the module has a name like `run` 680 let output = get_wasmtime_command()? 681 .current_dir("tests/all/cli_tests") 682 .arg("--") 683 .arg("run") 684 .output()?; 685 assert!(output.status.success(), "expected success got {output:#?}"); 686 687 // Passing options before the subcommand should work and doesn't require 688 // `--` to disambiguate 689 let output = get_wasmtime_command()? 690 .current_dir("tests/all/cli_tests") 691 .arg("-Ccache=n") 692 .arg("run") 693 .output()?; 694 assert!(output.status.success(), "expected success got {output:#?}"); 695 Ok(()) 696 } 697 698 #[test] 699 #[cfg(unix)] 700 fn run_just_stdin_argument() -> Result<()> { 701 let output = get_wasmtime_command()? 702 .arg("-") 703 .stdin(File::open("tests/all/cli_tests/simple.wat")?) 704 .output()?; 705 assert!(output.status.success()); 706 Ok(()) 707 } 708 709 #[test] 710 fn wasm_flags_without_subcommand() -> Result<()> { 711 let output = get_wasmtime_command()? 712 .current_dir("tests/all/cli_tests/") 713 .arg("print-arguments.wat") 714 .arg("-foo") 715 .arg("bar") 716 .output()?; 717 assert!(output.status.success()); 718 assert_eq!( 719 String::from_utf8_lossy(&output.stdout), 720 "\ 721 print-arguments.wat\n\ 722 -foo\n\ 723 bar\n\ 724 " 725 ); 726 Ok(()) 727 } 728 729 #[test] 730 fn wasi_misaligned_pointer() -> Result<()> { 731 let output = get_wasmtime_command()? 732 .arg("./tests/all/cli_tests/wasi_misaligned_pointer.wat") 733 .output()?; 734 assert!(!output.status.success()); 735 let stderr = String::from_utf8_lossy(&output.stderr); 736 assert!( 737 stderr.contains("Pointer not aligned"), 738 "bad stderr: {stderr}", 739 ); 740 Ok(()) 741 } 742 743 #[test] 744 #[cfg_attr(not(feature = "component-model"), ignore)] 745 fn hello_with_preview2() -> Result<()> { 746 let wasm = build_wasm("tests/all/cli_tests/hello_wasi_snapshot1.wat")?; 747 let stdout = run_wasmtime(&["-Ccache=n", "-Spreview2", wasm.path().to_str().unwrap()])?; 748 assert_eq!(stdout, "Hello, world!\n"); 749 Ok(()) 750 } 751 752 #[test] 753 #[cfg_attr(not(feature = "component-model"), ignore)] 754 fn component_missing_feature() -> Result<()> { 755 let path = "tests/all/cli_tests/empty-component.wat"; 756 let wasm = build_wasm(path)?; 757 let output = get_wasmtime_command()? 758 .arg("-Ccache=n") 759 .arg("-Wcomponent-model=n") 760 .arg(wasm.path()) 761 .output()?; 762 assert!(!output.status.success()); 763 let stderr = String::from_utf8_lossy(&output.stderr); 764 assert!( 765 stderr.contains("cannot execute a component without `--wasm component-model`"), 766 "bad stderr: {stderr}" 767 ); 768 769 // also tests with raw *.wat input 770 let output = get_wasmtime_command()? 771 .arg("-Ccache=n") 772 .arg("-Wcomponent-model=n") 773 .arg(path) 774 .output()?; 775 assert!(!output.status.success()); 776 let stderr = String::from_utf8_lossy(&output.stderr); 777 assert!( 778 stderr.contains("cannot execute a component without `--wasm component-model`"), 779 "bad stderr: {stderr}" 780 ); 781 782 Ok(()) 783 } 784 785 #[test] 786 #[cfg_attr(not(feature = "component-model"), ignore)] 787 fn component_enabled_by_default() -> Result<()> { 788 let path = "tests/all/cli_tests/component-basic.wat"; 789 let wasm = build_wasm(path)?; 790 let output = get_wasmtime_command()? 791 .arg("-Ccache=n") 792 .arg(wasm.path()) 793 .output()?; 794 assert!(output.status.success()); 795 796 // also tests with raw *.wat input 797 let output = get_wasmtime_command()? 798 .arg("-Ccache=n") 799 .arg(path) 800 .output()?; 801 assert!(output.status.success()); 802 803 Ok(()) 804 } 805 806 // If the text format is invalid then the filename should be mentioned in the 807 // error message. 808 #[test] 809 fn bad_text_syntax() -> Result<()> { 810 let output = get_wasmtime_command()? 811 .arg("-Ccache=n") 812 .arg("tests/all/cli_tests/bad-syntax.wat") 813 .output()?; 814 assert!(!output.status.success()); 815 let stderr = String::from_utf8_lossy(&output.stderr); 816 assert!( 817 stderr.contains("--> tests/all/cli_tests/bad-syntax.wat"), 818 "bad stderr: {stderr}" 819 ); 820 Ok(()) 821 } 822 823 #[test] 824 #[cfg_attr(not(feature = "component-model"), ignore)] 825 fn run_basic_component() -> Result<()> { 826 let path = "tests/all/cli_tests/component-basic.wat"; 827 let wasm = build_wasm(path)?; 828 829 // Run both the `*.wasm` binary and the text format 830 run_wasmtime(&[ 831 "-Ccache=n", 832 "-Wcomponent-model", 833 wasm.path().to_str().unwrap(), 834 ])?; 835 run_wasmtime(&["-Ccache=n", "-Wcomponent-model", path])?; 836 837 Ok(()) 838 } 839 840 #[test] 841 #[cfg_attr(not(feature = "component-model"), ignore)] 842 fn run_precompiled_component() -> Result<()> { 843 let td = TempDir::new()?; 844 let cwasm = td.path().join("component-basic.cwasm"); 845 let stdout = run_wasmtime(&[ 846 "compile", 847 "tests/all/cli_tests/component-basic.wat", 848 "-o", 849 cwasm.to_str().unwrap(), 850 "-Wcomponent-model", 851 ])?; 852 assert_eq!(stdout, ""); 853 let stdout = run_wasmtime(&[ 854 "run", 855 "-Wcomponent-model", 856 "--allow-precompiled", 857 cwasm.to_str().unwrap(), 858 ])?; 859 assert_eq!(stdout, ""); 860 861 Ok(()) 862 } 863 864 // Disable test on s390x because the large allocation may actually succeed; 865 // the whole 64-bit address space is available on this platform. 866 #[test] 867 #[cfg(not(target_arch = "s390x"))] 868 fn memory_growth_failure() -> Result<()> { 869 let output = get_wasmtime_command()? 870 .args(&[ 871 "run", 872 "-Wmemory64", 873 "-Wtrap-on-grow-failure", 874 "tests/all/cli_tests/memory-grow-failure.wat", 875 ]) 876 .output()?; 877 assert!(!output.status.success()); 878 let stderr = String::from_utf8_lossy(&output.stderr); 879 assert!( 880 stderr.contains("forcing a memory growth failure to be a trap"), 881 "bad stderr: {stderr}" 882 ); 883 Ok(()) 884 } 885 886 #[test] 887 fn table_growth_failure() -> Result<()> { 888 let output = get_wasmtime_command()? 889 .args(&[ 890 "run", 891 "-Wtrap-on-grow-failure", 892 "tests/all/cli_tests/table-grow-failure.wat", 893 ]) 894 .output()?; 895 assert!(!output.status.success()); 896 let stderr = String::from_utf8_lossy(&output.stderr); 897 assert!( 898 stderr.contains("forcing trap when growing table"), 899 "bad stderr: {stderr}" 900 ); 901 Ok(()) 902 } 903 904 #[test] 905 fn table_growth_failure2() -> Result<()> { 906 let output = get_wasmtime_command()? 907 .args(&[ 908 "run", 909 "-Wtrap-on-grow-failure", 910 "tests/all/cli_tests/table-grow-failure2.wat", 911 ]) 912 .output()?; 913 assert!(!output.status.success()); 914 let stderr = String::from_utf8_lossy(&output.stderr); 915 let expected = if cfg!(target_pointer_width = "32") { 916 "overflow calculating new table size" 917 } else { 918 "forcing trap when growing table to 4294967296 elements" 919 }; 920 assert!(stderr.contains(expected), "bad stderr: {stderr}"); 921 Ok(()) 922 } 923 924 #[test] 925 fn option_group_help() -> Result<()> { 926 run_wasmtime(&["run", "-Whelp"])?; 927 run_wasmtime(&["run", "-O", "help"])?; 928 run_wasmtime(&["run", "--codegen", "help"])?; 929 run_wasmtime(&["run", "--debug=help"])?; 930 run_wasmtime(&["run", "-Shelp"])?; 931 run_wasmtime(&["run", "-Whelp-long"])?; 932 Ok(()) 933 } 934 935 #[test] 936 fn option_group_comma_separated() -> Result<()> { 937 run_wasmtime(&[ 938 "run", 939 "-Wrelaxed-simd,simd", 940 "tests/all/cli_tests/simple.wat", 941 ])?; 942 Ok(()) 943 } 944 945 #[test] 946 fn option_group_boolean_parsing() -> Result<()> { 947 run_wasmtime(&["run", "-Wrelaxed-simd", "tests/all/cli_tests/simple.wat"])?; 948 run_wasmtime(&["run", "-Wrelaxed-simd=n", "tests/all/cli_tests/simple.wat"])?; 949 run_wasmtime(&["run", "-Wrelaxed-simd=y", "tests/all/cli_tests/simple.wat"])?; 950 run_wasmtime(&["run", "-Wrelaxed-simd=no", "tests/all/cli_tests/simple.wat"])?; 951 run_wasmtime(&[ 952 "run", 953 "-Wrelaxed-simd=yes", 954 "tests/all/cli_tests/simple.wat", 955 ])?; 956 run_wasmtime(&[ 957 "run", 958 "-Wrelaxed-simd=true", 959 "tests/all/cli_tests/simple.wat", 960 ])?; 961 run_wasmtime(&[ 962 "run", 963 "-Wrelaxed-simd=false", 964 "tests/all/cli_tests/simple.wat", 965 ])?; 966 Ok(()) 967 } 968 969 #[test] 970 fn preview2_stdin() -> Result<()> { 971 let test = "tests/all/cli_tests/count-stdin.wat"; 972 let cmd = || -> Result<_> { 973 let mut cmd = get_wasmtime_command()?; 974 cmd.arg("--invoke=count").arg("-Spreview2").arg(test); 975 Ok(cmd) 976 }; 977 978 // read empty pipe is ok 979 let output = cmd()?.output()?; 980 assert!(output.status.success()); 981 assert_eq!(String::from_utf8_lossy(&output.stdout), "0\n"); 982 983 // read itself is ok 984 let file = File::open(test)?; 985 let size = file.metadata()?.len(); 986 let output = cmd()?.stdin(File::open(test)?).output()?; 987 assert!(output.status.success()); 988 assert_eq!(String::from_utf8_lossy(&output.stdout), format!("{size}\n")); 989 990 // read piped input ok is ok 991 let mut child = cmd()? 992 .stdin(Stdio::piped()) 993 .stdout(Stdio::piped()) 994 .stderr(Stdio::piped()) 995 .spawn()?; 996 let mut stdin = child.stdin.take().unwrap(); 997 std::thread::spawn(move || { 998 stdin.write_all(b"hello").unwrap(); 999 }); 1000 let output = child.wait_with_output()?; 1001 assert!(output.status.success()); 1002 assert_eq!(String::from_utf8_lossy(&output.stdout), "5\n"); 1003 1004 let count_up_to = |n: usize| -> Result<_> { 1005 let mut child = get_wasmtime_command()? 1006 .arg("--invoke=count-up-to") 1007 .arg("-Spreview2") 1008 .arg(test) 1009 .arg(n.to_string()) 1010 .stdin(Stdio::piped()) 1011 .stdout(Stdio::piped()) 1012 .stderr(Stdio::piped()) 1013 .spawn()?; 1014 let mut stdin = child.stdin.take().unwrap(); 1015 let t = std::thread::spawn(move || { 1016 let mut written = 0; 1017 let bytes = [0; 64 * 1024]; 1018 loop { 1019 written += match stdin.write(&bytes) { 1020 Ok(n) => n, 1021 Err(_) => break written, 1022 }; 1023 } 1024 }); 1025 let output = child.wait_with_output()?; 1026 assert!(output.status.success()); 1027 let written = t.join().unwrap(); 1028 let read = String::from_utf8_lossy(&output.stdout) 1029 .trim() 1030 .parse::<usize>() 1031 .unwrap(); 1032 // The test reads in 1000 byte chunks so make sure that it doesn't read 1033 // more than 1000 bytes than requested. 1034 assert!(read < n + 1000, "test read too much {read}"); 1035 Ok(written) 1036 }; 1037 1038 // wasmtime shouldn't eat information that the guest never actually tried to 1039 // read. 1040 // 1041 // NB: this may be a bit flaky. Exactly how much we wrote in the above 1042 // helper thread depends on how much the OS buffers for us. For now give 1043 // some some slop and assume that OSes are unlikely to buffer more than 1044 // that. 1045 let slop = 256 * 1024; 1046 for amt in [0, 100, 100_000] { 1047 let written = count_up_to(amt)?; 1048 assert!(written < slop + amt, "wrote too much {written}"); 1049 } 1050 Ok(()) 1051 } 1052 1053 #[test] 1054 fn float_args() -> Result<()> { 1055 let result = run_wasmtime(&[ 1056 "--invoke", 1057 "echo_f32", 1058 "tests/all/cli_tests/simple.wat", 1059 "1.0", 1060 ])?; 1061 assert_eq!(result, "1\n"); 1062 let result = run_wasmtime(&[ 1063 "--invoke", 1064 "echo_f64", 1065 "tests/all/cli_tests/simple.wat", 1066 "1.1", 1067 ])?; 1068 assert_eq!(result, "1.1\n"); 1069 Ok(()) 1070 } 1071 1072 #[test] 1073 fn mpk_without_pooling() -> Result<()> { 1074 let output = get_wasmtime_command()? 1075 .args(&[ 1076 "run", 1077 "-O", 1078 "memory-protection-keys=y", 1079 "--invoke", 1080 "echo_f32", 1081 "tests/all/cli_tests/simple.wat", 1082 "1.0", 1083 ]) 1084 .env("WASMTIME_NEW_CLI", "1") 1085 .output()?; 1086 assert!(!output.status.success()); 1087 Ok(()) 1088 } 1089 1090 // Very basic use case: compile binary wasm file and run specific function with arguments. 1091 #[test] 1092 fn increase_stack_size() -> Result<()> { 1093 run_wasmtime(&[ 1094 "run", 1095 "--invoke", 1096 "simple", 1097 &format!("-Wmax-wasm-stack={}", 5 << 20), 1098 "-Ccache=n", 1099 "tests/all/cli_tests/simple.wat", 1100 "4", 1101 ])?; 1102 Ok(()) 1103 } 1104 1105 mod test_programs { 1106 use super::{get_wasmtime_command, run_wasmtime}; 1107 use anyhow::{Context, Result, bail}; 1108 use http_body_util::BodyExt; 1109 use hyper::header::HeaderValue; 1110 use std::io::{self, BufRead, BufReader, Read, Write}; 1111 use std::iter; 1112 use std::net::SocketAddr; 1113 use std::process::{Child, Command, Stdio}; 1114 use std::thread::{self, JoinHandle}; 1115 use test_programs_artifacts::*; 1116 use tokio::net::TcpStream; 1117 1118 macro_rules! assert_test_exists { 1119 ($name:ident) => { 1120 #[expect(unused_imports, reason = "just here to assert the test is here")] 1121 use self::$name as _; 1122 }; 1123 } 1124 foreach_cli!(assert_test_exists); 1125 1126 #[test] 1127 fn cli_hello_stdout() -> Result<()> { 1128 run_wasmtime(&["run", "-Wcomponent-model", CLI_HELLO_STDOUT_COMPONENT])?; 1129 Ok(()) 1130 } 1131 1132 #[test] 1133 fn cli_args() -> Result<()> { 1134 run_wasmtime(&[ 1135 "run", 1136 "-Wcomponent-model", 1137 CLI_ARGS_COMPONENT, 1138 "hello", 1139 "this", 1140 "", 1141 "is an argument", 1142 "with emoji", 1143 ])?; 1144 Ok(()) 1145 } 1146 1147 #[test] 1148 fn cli_stdin_empty() -> Result<()> { 1149 let mut child = get_wasmtime_command()? 1150 .args(&["run", "-Wcomponent-model", CLI_STDIN_EMPTY_COMPONENT]) 1151 .stdout(Stdio::piped()) 1152 .stderr(Stdio::piped()) 1153 .stdin(Stdio::piped()) 1154 .spawn()?; 1155 child 1156 .stdin 1157 .take() 1158 .unwrap() 1159 .write_all(b"not to be read") 1160 .unwrap(); 1161 let output = child.wait_with_output()?; 1162 println!("stdout: {}", String::from_utf8_lossy(&output.stdout)); 1163 println!("stderr: {}", String::from_utf8_lossy(&output.stderr)); 1164 assert!(output.status.success()); 1165 Ok(()) 1166 } 1167 1168 #[test] 1169 fn cli_stdin() -> Result<()> { 1170 let mut child = get_wasmtime_command()? 1171 .args(&["run", "-Wcomponent-model", CLI_STDIN_COMPONENT]) 1172 .stdout(Stdio::piped()) 1173 .stderr(Stdio::piped()) 1174 .stdin(Stdio::piped()) 1175 .spawn()?; 1176 child 1177 .stdin 1178 .take() 1179 .unwrap() 1180 .write_all(b"So rested he by the Tumtum tree") 1181 .unwrap(); 1182 let output = child.wait_with_output()?; 1183 println!("stdout: {}", String::from_utf8_lossy(&output.stdout)); 1184 println!("stderr: {}", String::from_utf8_lossy(&output.stderr)); 1185 assert!(output.status.success()); 1186 Ok(()) 1187 } 1188 1189 #[test] 1190 fn cli_splice_stdin() -> Result<()> { 1191 let mut child = get_wasmtime_command()? 1192 .args(&["run", "-Wcomponent-model", CLI_SPLICE_STDIN_COMPONENT]) 1193 .stdout(Stdio::piped()) 1194 .stderr(Stdio::piped()) 1195 .stdin(Stdio::piped()) 1196 .spawn()?; 1197 let msg = "So rested he by the Tumtum tree"; 1198 child 1199 .stdin 1200 .take() 1201 .unwrap() 1202 .write_all(msg.as_bytes()) 1203 .unwrap(); 1204 let output = child.wait_with_output()?; 1205 assert!(output.status.success()); 1206 let stdout = String::from_utf8_lossy(&output.stdout); 1207 let stderr = String::from_utf8_lossy(&output.stderr); 1208 if !stderr.is_empty() { 1209 eprintln!("{stderr}"); 1210 } 1211 1212 assert_eq!( 1213 format!( 1214 "before splice\n{msg}\ncompleted splicing {} bytes\n", 1215 msg.as_bytes().len() 1216 ), 1217 stdout 1218 ); 1219 Ok(()) 1220 } 1221 1222 #[test] 1223 fn cli_env() -> Result<()> { 1224 run_wasmtime(&[ 1225 "run", 1226 "-Wcomponent-model", 1227 "--env=frabjous=day", 1228 "--env=callooh=callay", 1229 CLI_ENV_COMPONENT, 1230 ])?; 1231 Ok(()) 1232 } 1233 1234 #[test] 1235 fn cli_file_read() -> Result<()> { 1236 let dir = tempfile::tempdir()?; 1237 1238 std::fs::write(dir.path().join("bar.txt"), b"And stood awhile in thought")?; 1239 1240 run_wasmtime(&[ 1241 "run", 1242 "-Wcomponent-model", 1243 &format!("--dir={}::/", dir.path().to_str().unwrap()), 1244 CLI_FILE_READ_COMPONENT, 1245 ])?; 1246 Ok(()) 1247 } 1248 1249 #[test] 1250 fn cli_file_append() -> Result<()> { 1251 let dir = tempfile::tempdir()?; 1252 1253 std::fs::File::create(dir.path().join("bar.txt"))? 1254 .write_all(b"'Twas brillig, and the slithy toves.\n")?; 1255 1256 run_wasmtime(&[ 1257 "run", 1258 "-Wcomponent-model", 1259 &format!("--dir={}::/", dir.path().to_str().unwrap()), 1260 CLI_FILE_APPEND_COMPONENT, 1261 ])?; 1262 1263 let contents = std::fs::read(dir.path().join("bar.txt"))?; 1264 assert_eq!( 1265 std::str::from_utf8(&contents).unwrap(), 1266 "'Twas brillig, and the slithy toves.\n\ 1267 Did gyre and gimble in the wabe;\n\ 1268 All mimsy were the borogoves,\n\ 1269 And the mome raths outgrabe.\n" 1270 ); 1271 Ok(()) 1272 } 1273 1274 #[test] 1275 fn cli_file_dir_sync() -> Result<()> { 1276 let dir = tempfile::tempdir()?; 1277 1278 std::fs::File::create(dir.path().join("bar.txt"))? 1279 .write_all(b"'Twas brillig, and the slithy toves.\n")?; 1280 1281 run_wasmtime(&[ 1282 "run", 1283 "-Wcomponent-model", 1284 &format!("--dir={}::/", dir.path().to_str().unwrap()), 1285 CLI_FILE_DIR_SYNC_COMPONENT, 1286 ])?; 1287 1288 Ok(()) 1289 } 1290 1291 #[test] 1292 fn cli_exit_success() -> Result<()> { 1293 run_wasmtime(&["run", "-Wcomponent-model", CLI_EXIT_SUCCESS_COMPONENT])?; 1294 Ok(()) 1295 } 1296 1297 #[test] 1298 fn cli_exit_default() -> Result<()> { 1299 run_wasmtime(&["run", "-Wcomponent-model", CLI_EXIT_DEFAULT_COMPONENT])?; 1300 Ok(()) 1301 } 1302 1303 #[test] 1304 fn cli_exit_failure() -> Result<()> { 1305 let output = get_wasmtime_command()? 1306 .args(&["run", "-Wcomponent-model", CLI_EXIT_FAILURE_COMPONENT]) 1307 .output()?; 1308 assert!(!output.status.success()); 1309 assert_eq!(output.status.code(), Some(1)); 1310 Ok(()) 1311 } 1312 1313 #[test] 1314 fn cli_exit_with_code() -> Result<()> { 1315 let output = get_wasmtime_command()? 1316 .args(&[ 1317 "run", 1318 "-Wcomponent-model", 1319 "-Scli-exit-with-code", 1320 CLI_EXIT_WITH_CODE_COMPONENT, 1321 ]) 1322 .output()?; 1323 assert!(!output.status.success()); 1324 assert_eq!(output.status.code(), Some(42)); 1325 Ok(()) 1326 } 1327 1328 #[test] 1329 fn cli_exit_panic() -> Result<()> { 1330 let output = get_wasmtime_command()? 1331 .args(&["run", "-Wcomponent-model", CLI_EXIT_PANIC_COMPONENT]) 1332 .output()?; 1333 assert!(!output.status.success()); 1334 let stderr = String::from_utf8_lossy(&output.stderr); 1335 assert!(stderr.contains("Curiouser and curiouser!")); 1336 Ok(()) 1337 } 1338 1339 #[test] 1340 fn cli_directory_list() -> Result<()> { 1341 let dir = tempfile::tempdir()?; 1342 1343 std::fs::File::create(dir.path().join("foo.txt"))?; 1344 std::fs::File::create(dir.path().join("bar.txt"))?; 1345 std::fs::File::create(dir.path().join("baz.txt"))?; 1346 std::fs::create_dir(dir.path().join("sub"))?; 1347 std::fs::File::create(dir.path().join("sub").join("wow.txt"))?; 1348 std::fs::File::create(dir.path().join("sub").join("yay.txt"))?; 1349 1350 run_wasmtime(&[ 1351 "run", 1352 "-Wcomponent-model", 1353 &format!("--dir={}::/", dir.path().to_str().unwrap()), 1354 CLI_DIRECTORY_LIST_COMPONENT, 1355 ])?; 1356 Ok(()) 1357 } 1358 1359 #[test] 1360 fn cli_default_clocks() -> Result<()> { 1361 run_wasmtime(&["run", "-Wcomponent-model", CLI_DEFAULT_CLOCKS_COMPONENT])?; 1362 Ok(()) 1363 } 1364 1365 #[test] 1366 fn cli_export_cabi_realloc() -> Result<()> { 1367 run_wasmtime(&[ 1368 "run", 1369 "-Wcomponent-model", 1370 CLI_EXPORT_CABI_REALLOC_COMPONENT, 1371 ])?; 1372 Ok(()) 1373 } 1374 1375 #[test] 1376 fn run_wasi_http_component() -> Result<()> { 1377 let output = super::run_wasmtime_for_output( 1378 &[ 1379 "-Ccache=no", 1380 "-Wcomponent-model", 1381 "-Scli,http,preview2", 1382 HTTP_OUTBOUND_REQUEST_RESPONSE_BUILD_COMPONENT, 1383 ], 1384 None, 1385 )?; 1386 println!("{}", String::from_utf8_lossy(&output.stderr)); 1387 let stdout = String::from_utf8_lossy(&output.stdout); 1388 println!("{stdout}"); 1389 assert!(stdout.starts_with("Called _start\n")); 1390 assert!(stdout.ends_with("Done\n")); 1391 assert!(output.status.success()); 1392 Ok(()) 1393 } 1394 1395 // Test to ensure that prints in the guest aren't buffered on the host by 1396 // accident. The test here will print something without a newline and then 1397 // wait for input on stdin, and the test here is to ensure that the 1398 // character shows up here even as the guest is waiting on input via stdin. 1399 #[test] 1400 fn cli_stdio_write_flushes() -> Result<()> { 1401 fn run(args: &[&str]) -> Result<()> { 1402 println!("running {args:?}"); 1403 let mut child = get_wasmtime_command()? 1404 .args(args) 1405 .stdin(Stdio::piped()) 1406 .stdout(Stdio::piped()) 1407 .spawn()?; 1408 let mut stdout = child.stdout.take().unwrap(); 1409 let mut buf = [0; 10]; 1410 match stdout.read(&mut buf) { 1411 Ok(2) => assert_eq!(&buf[..2], b"> "), 1412 e => panic!("unexpected read result {e:?}"), 1413 } 1414 drop(stdout); 1415 drop(child.stdin.take().unwrap()); 1416 let status = child.wait()?; 1417 assert!(status.success()); 1418 Ok(()) 1419 } 1420 1421 run(&["run", "-Spreview2=n", CLI_STDIO_WRITE_FLUSHES])?; 1422 run(&["run", "-Spreview2=y", CLI_STDIO_WRITE_FLUSHES])?; 1423 run(&[ 1424 "run", 1425 "-Wcomponent-model", 1426 CLI_STDIO_WRITE_FLUSHES_COMPONENT, 1427 ])?; 1428 Ok(()) 1429 } 1430 1431 #[test] 1432 fn cli_no_tcp() -> Result<()> { 1433 let output = super::run_wasmtime_for_output( 1434 &[ 1435 "-Wcomponent-model", 1436 // Turn on network but turn off TCP 1437 "-Sinherit-network,tcp=no", 1438 CLI_NO_TCP_COMPONENT, 1439 ], 1440 None, 1441 )?; 1442 println!("{}", String::from_utf8_lossy(&output.stderr)); 1443 assert!(output.status.success()); 1444 Ok(()) 1445 } 1446 1447 #[test] 1448 fn cli_no_udp() -> Result<()> { 1449 let output = super::run_wasmtime_for_output( 1450 &[ 1451 "-Wcomponent-model", 1452 // Turn on network but turn off UDP 1453 "-Sinherit-network,udp=no", 1454 CLI_NO_UDP_COMPONENT, 1455 ], 1456 None, 1457 )?; 1458 println!("{}", String::from_utf8_lossy(&output.stderr)); 1459 assert!(output.status.success()); 1460 Ok(()) 1461 } 1462 1463 #[test] 1464 fn cli_no_ip_name_lookup() -> Result<()> { 1465 let output = super::run_wasmtime_for_output( 1466 &[ 1467 "-Wcomponent-model", 1468 // Turn on network but ensure name lookup is disabled 1469 "-Sinherit-network,allow-ip-name-lookup=no", 1470 CLI_NO_IP_NAME_LOOKUP_COMPONENT, 1471 ], 1472 None, 1473 )?; 1474 println!("{}", String::from_utf8_lossy(&output.stderr)); 1475 assert!(output.status.success()); 1476 Ok(()) 1477 } 1478 1479 #[test] 1480 fn cli_sleep() -> Result<()> { 1481 run_wasmtime(&["run", CLI_SLEEP])?; 1482 run_wasmtime(&["run", CLI_SLEEP_COMPONENT])?; 1483 Ok(()) 1484 } 1485 1486 #[test] 1487 fn cli_sleep_forever() -> Result<()> { 1488 for timeout in [ 1489 // Tests still pass when we race with going to sleep. 1490 "-Wtimeout=1ns", 1491 // Tests pass when we wait till the Wasm has (likely) gone to sleep. 1492 "-Wtimeout=250ms", 1493 ] { 1494 let e = run_wasmtime(&["run", timeout, CLI_SLEEP_FOREVER]).unwrap_err(); 1495 let e = e.to_string(); 1496 println!("Got error: {e}"); 1497 assert!(e.contains("interrupt")); 1498 1499 let e = run_wasmtime(&["run", timeout, CLI_SLEEP_FOREVER_COMPONENT]).unwrap_err(); 1500 let e = e.to_string(); 1501 println!("Got error: {e}"); 1502 assert!(e.contains("interrupt")); 1503 } 1504 1505 Ok(()) 1506 } 1507 1508 /// Helper structure to manage an invocation of `wasmtime serve` 1509 struct WasmtimeServe { 1510 child: Option<Child>, 1511 stdout: Option<JoinHandle<io::Result<Vec<u8>>>>, 1512 stderr: Option<JoinHandle<io::Result<Vec<u8>>>>, 1513 addr: SocketAddr, 1514 shutdown_addr: SocketAddr, 1515 } 1516 1517 impl WasmtimeServe { 1518 /// Creates a new server which will serve the wasm component pointed to 1519 /// by `wasm`. 1520 /// 1521 /// A `configure` callback is provided to specify how `wasmtime serve` 1522 /// will be invoked and configure arguments such as headers. 1523 fn new(wasm: &str, configure: impl FnOnce(&mut Command)) -> Result<WasmtimeServe> { 1524 // Spawn `wasmtime serve` on port 0 which will randomly assign it a 1525 // port. 1526 let mut cmd = super::get_wasmtime_command()?; 1527 cmd.arg("serve").arg("--addr=127.0.0.1:0").arg(wasm); 1528 configure(&mut cmd); 1529 Self::spawn(&mut cmd) 1530 } 1531 1532 fn spawn(cmd: &mut Command) -> Result<WasmtimeServe> { 1533 cmd.arg("--shutdown-addr=127.0.0.1:0"); 1534 cmd.stdin(Stdio::null()); 1535 cmd.stdout(Stdio::piped()); 1536 cmd.stderr(Stdio::piped()); 1537 let mut child = cmd.spawn()?; 1538 1539 // Read the first few lines of stderr which will say which address 1540 // it's listening on. The first line is the shutdown line (with 1541 // `--shutdown-addr`) and the second is what `--addr` was bound to. 1542 // This is done to figure out what `:0` was bound to in the child 1543 // process. 1544 let mut line = String::new(); 1545 let mut stderr = BufReader::new(child.stderr.take().unwrap()); 1546 let mut read_addr_from_line = |prefix: &str| -> Result<SocketAddr> { 1547 stderr.read_line(&mut line)?; 1548 1549 if !line.starts_with(prefix) { 1550 bail!("input line `{line}` didn't start with `{prefix}`"); 1551 } 1552 match line.find("127.0.0.1").and_then(|addr_start| { 1553 let addr = &line[addr_start..]; 1554 let addr_end = addr.find("/")?; 1555 addr[..addr_end].parse().ok() 1556 }) { 1557 Some(addr) => { 1558 line.truncate(0); 1559 Ok(addr) 1560 } 1561 None => bail!("failed to address from: {line}"), 1562 } 1563 }; 1564 let shutdown_addr = read_addr_from_line("Listening for shutdown"); 1565 let addr = read_addr_from_line("Serving HTTP on"); 1566 let (shutdown_addr, addr) = match (shutdown_addr, addr) { 1567 (Ok(a), Ok(b)) => (a, b), 1568 // If either failed kill the child and otherwise try to shepherd 1569 // along any contextual information we have. 1570 (Err(a), _) | (_, Err(a)) => { 1571 child.kill()?; 1572 child.wait()?; 1573 stderr.read_to_string(&mut line)?; 1574 return Err(a.context(line)); 1575 } 1576 }; 1577 let mut stdout = child.stdout.take().unwrap(); 1578 Ok(WasmtimeServe { 1579 stdout: Some(thread::spawn(move || { 1580 let mut dst = Vec::new(); 1581 stdout.read_to_end(&mut dst).map(|_| dst) 1582 })), 1583 1584 stderr: Some(thread::spawn(move || { 1585 let mut dst = Vec::new(); 1586 stderr.read_to_end(&mut dst).map(|_| dst) 1587 })), 1588 1589 child: Some(child), 1590 addr, 1591 shutdown_addr, 1592 }) 1593 } 1594 1595 /// Completes this server gracefully by printing the output on failure. 1596 fn finish(mut self) -> Result<(String, String)> { 1597 self._finish() 1598 } 1599 1600 fn _finish(&mut self) -> Result<(String, String)> { 1601 let mut child = self.child.take().unwrap(); 1602 1603 // If the child process has already exited, then great! Otherwise 1604 // the server is still running and it shouldn't be possible to exit 1605 // until a shutdown signal is sent, so do that here. Make a TCP 1606 // connection to the shutdown port which is used as a shutdown 1607 // signal. 1608 if child.try_wait()?.is_none() { 1609 std::net::TcpStream::connect(&self.shutdown_addr) 1610 .context("failed to initiate graceful shutdown")?; 1611 } 1612 1613 // Regardless of whether we just shut the server down or whether it 1614 // was already shut down (e.g. panicked or similar), wait for the 1615 // result here. The result should succeed (e.g. 0 exit status), and 1616 // if it did then the stdout/stderr are the caller's problem. 1617 let mut output = child.wait_with_output()?; 1618 output.stdout = self.stdout.take().unwrap().join().unwrap()?; 1619 output.stderr = self.stderr.take().unwrap().join().unwrap()?; 1620 if !output.status.success() { 1621 bail!("child failed {output:?}"); 1622 } 1623 1624 Ok(( 1625 String::from_utf8_lossy(&output.stdout).into_owned(), 1626 String::from_utf8_lossy(&output.stderr).into_owned(), 1627 )) 1628 } 1629 1630 /// Send a request to this server and wait for the response. 1631 async fn send_request(&self, req: http::Request<String>) -> Result<http::Response<String>> { 1632 let (mut send, conn_task) = self.start_requests().await?; 1633 1634 let response = send 1635 .send_request(req) 1636 .await 1637 .context("error sending request")?; 1638 drop(send); 1639 let (parts, body) = response.into_parts(); 1640 1641 let body = body.collect().await.context("failed to read body")?; 1642 assert!(body.trailers().is_none()); 1643 let body = std::str::from_utf8(&body.to_bytes())?.to_string(); 1644 1645 conn_task.await??; 1646 1647 Ok(http::Response::from_parts(parts, body)) 1648 } 1649 1650 async fn start_requests( 1651 &self, 1652 ) -> Result<( 1653 hyper::client::conn::http1::SendRequest<String>, 1654 tokio::task::JoinHandle<hyper::Result<()>>, 1655 )> { 1656 let tcp = TcpStream::connect(&self.addr) 1657 .await 1658 .context("failed to connect")?; 1659 let tcp = wasmtime_wasi_http::io::TokioIo::new(tcp); 1660 let (send, conn) = hyper::client::conn::http1::handshake(tcp) 1661 .await 1662 .context("failed http handshake")?; 1663 Ok((send, tokio::task::spawn(conn))) 1664 } 1665 } 1666 1667 // Don't leave child processes running by accident so kill the child process 1668 // if our server goes away. 1669 impl Drop for WasmtimeServe { 1670 fn drop(&mut self) { 1671 match &mut self.child { 1672 Some(child) => match child.kill() { 1673 Ok(()) => {} 1674 Err(e) => { 1675 eprintln!("failed to kill child process {e}"); 1676 return; 1677 } 1678 }, 1679 None => return, 1680 } 1681 match self._finish() { 1682 Ok((stdout, stderr)) => { 1683 if !stdout.is_empty() { 1684 println!("server stdout:\n{stdout}"); 1685 } 1686 if !stderr.is_empty() { 1687 println!("server stderr:\n{stderr}"); 1688 } 1689 } 1690 Err(e) => println!("failed to wait for child or read stdio: {e}"), 1691 } 1692 } 1693 } 1694 1695 #[tokio::test] 1696 async fn cli_serve_echo_env() -> Result<()> { 1697 let server = WasmtimeServe::new(CLI_SERVE_ECHO_ENV_COMPONENT, |cmd| { 1698 cmd.arg("--env=FOO=bar"); 1699 cmd.arg("--env=BAR"); 1700 cmd.arg("-Scli"); 1701 cmd.env_remove("BAR"); 1702 })?; 1703 1704 let foo_env = server 1705 .send_request( 1706 hyper::Request::builder() 1707 .uri("http://localhost/") 1708 .header("env", "FOO") 1709 .body(String::new()) 1710 .context("failed to make request")?, 1711 ) 1712 .await?; 1713 1714 assert!(foo_env.status().is_success()); 1715 assert!(foo_env.body().is_empty()); 1716 let headers = foo_env.headers(); 1717 assert_eq!(headers.get("env"), Some(&HeaderValue::from_static("bar"))); 1718 1719 let bar_env = server 1720 .send_request( 1721 hyper::Request::builder() 1722 .uri("http://localhost/") 1723 .header("env", "BAR") 1724 .body(String::new()) 1725 .context("failed to make request")?, 1726 ) 1727 .await?; 1728 1729 assert!(bar_env.status().is_success()); 1730 assert!(bar_env.body().is_empty()); 1731 let headers = bar_env.headers(); 1732 assert_eq!(headers.get("env"), None); 1733 1734 server.finish()?; 1735 Ok(()) 1736 } 1737 1738 #[tokio::test] 1739 async fn cli_serve_outgoing_body_config() -> Result<()> { 1740 let server = WasmtimeServe::new(CLI_SERVE_ECHO_ENV_COMPONENT, |cmd| { 1741 cmd.arg("-Scli"); 1742 cmd.arg("-Shttp-outgoing-body-buffer-chunks=2"); 1743 cmd.arg("-Shttp-outgoing-body-chunk-size=1024"); 1744 })?; 1745 1746 let resp = server 1747 .send_request( 1748 hyper::Request::builder() 1749 .uri("http://localhost/") 1750 .header("env", "FOO") 1751 .body(String::new()) 1752 .context("failed to make request")?, 1753 ) 1754 .await?; 1755 1756 assert!(resp.status().is_success()); 1757 1758 server.finish()?; 1759 Ok(()) 1760 } 1761 1762 #[tokio::test] 1763 #[ignore] // TODO: printing stderr in the child and killing the child at the 1764 // end of this test race so the stderr may be present or not. Need 1765 // to implement a more graceful shutdown routine for `wasmtime 1766 // serve`. 1767 async fn cli_serve_respect_pooling_options() -> Result<()> { 1768 let server = WasmtimeServe::new(CLI_SERVE_ECHO_ENV_COMPONENT, |cmd| { 1769 cmd.arg("-Opooling-total-memories=0").arg("-Scli"); 1770 })?; 1771 1772 let result = server 1773 .send_request( 1774 hyper::Request::builder() 1775 .uri("http://localhost/") 1776 .header("env", "FOO") 1777 .body(String::new()) 1778 .context("failed to make request")?, 1779 ) 1780 .await; 1781 assert!(result.is_err()); 1782 let (_, stderr) = server.finish()?; 1783 assert!( 1784 stderr.contains("maximum concurrent memory limit of 0 reached"), 1785 "bad stderr: {stderr}", 1786 ); 1787 Ok(()) 1788 } 1789 1790 #[test] 1791 fn cli_large_env() -> Result<()> { 1792 for wasm in [CLI_LARGE_ENV, CLI_LARGE_ENV_COMPONENT] { 1793 println!("run {wasm:?}"); 1794 let mut cmd = get_wasmtime_command()?; 1795 cmd.arg("run").arg("-Sinherit-env").arg(wasm); 1796 1797 let debug_cmd = format!("{cmd:?}"); 1798 for i in 0..512 { 1799 let var = format!("KEY{i}"); 1800 let val = (0..1024).map(|_| 'x').collect::<String>(); 1801 cmd.env(&var, &val); 1802 } 1803 let output = cmd.output()?; 1804 if !output.status.success() { 1805 bail!( 1806 "Failed to execute wasmtime with: {debug_cmd}\n{}", 1807 String::from_utf8_lossy(&output.stderr) 1808 ); 1809 } 1810 } 1811 Ok(()) 1812 } 1813 1814 #[tokio::test] 1815 async fn cli_serve_only_one_process_allowed() -> Result<()> { 1816 let wasm = CLI_SERVE_ECHO_ENV_COMPONENT; 1817 let server = WasmtimeServe::new(wasm, |cmd| { 1818 cmd.arg("-Scli"); 1819 })?; 1820 1821 let err = WasmtimeServe::spawn( 1822 super::get_wasmtime_command()? 1823 .arg("serve") 1824 .arg("-Scli") 1825 .arg(format!("--addr={}", server.addr)) 1826 .arg(wasm), 1827 ) 1828 .err() 1829 .expect("server spawn should have failed but it succeeded"); 1830 drop(server); 1831 1832 let err = format!("{err:?}"); 1833 println!("{err}"); 1834 assert!(err.contains("os error")); 1835 Ok(()) 1836 } 1837 1838 // Technically this test is a little racy. This binds port 0 to acquire a 1839 // random port, issues a single request to this port, but then kills this 1840 // server while the request is still processing. The port is then rebound 1841 // in the next process while it technically could be stolen by another 1842 // process. 1843 #[tokio::test] 1844 async fn cli_serve_quick_rebind_allowed() -> Result<()> { 1845 let wasm = CLI_SERVE_ECHO_ENV_COMPONENT; 1846 let server = WasmtimeServe::new(wasm, |cmd| { 1847 cmd.arg("-Scli"); 1848 })?; 1849 let addr = server.addr; 1850 1851 // Start up a `send` and `conn_task` which represents a connection to 1852 // this server. 1853 let (mut send, conn_task) = server.start_requests().await?; 1854 let _ = send 1855 .send_request( 1856 hyper::Request::builder() 1857 .uri("http://localhost/") 1858 .header("env", "FOO") 1859 .body(String::new()) 1860 .context("failed to make request")?, 1861 ) 1862 .await; 1863 1864 // ... once a response has been received (or at least the status 1865 // code/headers) then kill the server. THis is done while `conn_task` 1866 // and `send` are still alive so we're guaranteed that the other side 1867 // got a request (we got a response) and our connection is still open. 1868 // 1869 // This forces the address/port into the `TIME_WAIT` state. The rebind 1870 // below in the next process will fail if `SO_REUSEADDR` isn't set. 1871 drop(server); 1872 drop(send); 1873 let _ = conn_task.await; 1874 1875 // If this is successfully bound then we'll create `WasmtimeServe` 1876 // which reads off the first line of output to know which address was 1877 // bound. 1878 let _server2 = WasmtimeServe::spawn( 1879 super::get_wasmtime_command()? 1880 .arg("serve") 1881 .arg("-Scli") 1882 .arg(format!("--addr={addr}")) 1883 .arg(wasm), 1884 )?; 1885 1886 Ok(()) 1887 } 1888 1889 #[tokio::test] 1890 async fn cli_serve_with_print() -> Result<()> { 1891 let server = WasmtimeServe::new(CLI_SERVE_WITH_PRINT_COMPONENT, |cmd| { 1892 cmd.arg("-Scli"); 1893 })?; 1894 1895 for _ in 0..2 { 1896 let resp = server 1897 .send_request( 1898 hyper::Request::builder() 1899 .uri("http://localhost/") 1900 .body(String::new()) 1901 .context("failed to make request")?, 1902 ) 1903 .await?; 1904 assert!(resp.status().is_success()); 1905 } 1906 1907 let (out, err) = server.finish()?; 1908 assert_eq!( 1909 out, 1910 "\ 1911 stdout [0] :: this is half a print to stdout 1912 stdout [0] :: \n\ 1913 stdout [0] :: after empty 1914 stdout [1] :: this is half a print to stdout 1915 stdout [1] :: \n\ 1916 stdout [1] :: after empty 1917 " 1918 ); 1919 assert!( 1920 err.contains( 1921 "\ 1922 stderr [0] :: this is half a print to stderr 1923 stderr [0] :: \n\ 1924 stderr [0] :: after empty 1925 stderr [0] :: start a print 1234 1926 stderr [1] :: this is half a print to stderr 1927 stderr [1] :: \n\ 1928 stderr [1] :: after empty 1929 stderr [1] :: start a print 1234 1930 " 1931 ), 1932 "bad stderr: {err}" 1933 ); 1934 1935 Ok(()) 1936 } 1937 1938 #[tokio::test] 1939 async fn cli_serve_with_print_no_prefix() -> Result<()> { 1940 let server = WasmtimeServe::new(CLI_SERVE_WITH_PRINT_COMPONENT, |cmd| { 1941 cmd.arg("-Scli"); 1942 cmd.arg("--no-logging-prefix"); 1943 })?; 1944 1945 for _ in 0..2 { 1946 let resp = server 1947 .send_request( 1948 hyper::Request::builder() 1949 .uri("http://localhost/") 1950 .body(String::new()) 1951 .context("failed to make request")?, 1952 ) 1953 .await?; 1954 assert!(resp.status().is_success()); 1955 } 1956 1957 let (out, err) = server.finish()?; 1958 assert_eq!( 1959 out, 1960 "\ 1961 this is half a print to stdout 1962 \n\ 1963 after empty 1964 this is half a print to stdout 1965 \n\ 1966 after empty 1967 " 1968 ); 1969 assert!( 1970 err.contains( 1971 "\ 1972 this is half a print to stderr 1973 \n\ 1974 after empty 1975 start a print 1234 1976 this is half a print to stderr 1977 \n\ 1978 after empty 1979 start a print 1234 1980 " 1981 ), 1982 "bad stderr {err}", 1983 ); 1984 1985 Ok(()) 1986 } 1987 1988 #[tokio::test] 1989 async fn cli_serve_authority_and_scheme() -> Result<()> { 1990 let server = WasmtimeServe::new(CLI_SERVE_AUTHORITY_AND_SCHEME_COMPONENT, |cmd| { 1991 cmd.arg("-Scli"); 1992 })?; 1993 1994 let resp = server 1995 .send_request( 1996 hyper::Request::builder() 1997 .uri("/") 1998 .header("Host", "localhost") 1999 .body(String::new()) 2000 .context("failed to make request")?, 2001 ) 2002 .await?; 2003 assert!(resp.status().is_success()); 2004 2005 let resp = server 2006 .send_request( 2007 hyper::Request::builder() 2008 .method("CONNECT") 2009 .uri("http://localhost/") 2010 .body(String::new()) 2011 .context("failed to make request")?, 2012 ) 2013 .await?; 2014 assert!(resp.status().is_success()); 2015 2016 Ok(()) 2017 } 2018 2019 #[test] 2020 fn cli_argv0() -> Result<()> { 2021 run_wasmtime(&["run", "--argv0=a", CLI_ARGV0, "a"])?; 2022 run_wasmtime(&["run", "--argv0=b", CLI_ARGV0_COMPONENT, "b"])?; 2023 run_wasmtime(&["run", "--argv0=foo.wasm", CLI_ARGV0, "foo.wasm"])?; 2024 Ok(()) 2025 } 2026 2027 #[tokio::test] 2028 async fn cli_serve_config() -> Result<()> { 2029 let server = WasmtimeServe::new(CLI_SERVE_CONFIG_COMPONENT, |cmd| { 2030 cmd.arg("-Scli"); 2031 cmd.arg("-Sconfig"); 2032 cmd.arg("-Sconfig-var=hello=world"); 2033 })?; 2034 2035 let resp = server 2036 .send_request( 2037 hyper::Request::builder() 2038 .uri("http://localhost/") 2039 .body(String::new()) 2040 .context("failed to make request")?, 2041 ) 2042 .await?; 2043 2044 assert!(resp.status().is_success()); 2045 assert_eq!(resp.body(), "world"); 2046 Ok(()) 2047 } 2048 2049 #[test] 2050 fn cli_config() -> Result<()> { 2051 run_wasmtime(&[ 2052 "run", 2053 "-Sconfig", 2054 "-Sconfig-var=hello=world", 2055 CONFIG_GET_COMPONENT, 2056 ])?; 2057 Ok(()) 2058 } 2059 2060 #[tokio::test] 2061 async fn cli_serve_keyvalue() -> Result<()> { 2062 let server = WasmtimeServe::new(CLI_SERVE_KEYVALUE_COMPONENT, |cmd| { 2063 cmd.arg("-Scli"); 2064 cmd.arg("-Skeyvalue"); 2065 cmd.arg("-Skeyvalue-in-memory-data=hello=world"); 2066 })?; 2067 2068 let resp = server 2069 .send_request( 2070 hyper::Request::builder() 2071 .uri("http://localhost/") 2072 .body(String::new()) 2073 .context("failed to make request")?, 2074 ) 2075 .await?; 2076 2077 assert!(resp.status().is_success()); 2078 assert_eq!(resp.body(), "world"); 2079 Ok(()) 2080 } 2081 2082 #[test] 2083 fn cli_keyvalue() -> Result<()> { 2084 run_wasmtime(&[ 2085 "run", 2086 "-Skeyvalue", 2087 "-Skeyvalue-in-memory-data=atomics_key=5", 2088 KEYVALUE_MAIN_COMPONENT, 2089 ])?; 2090 Ok(()) 2091 } 2092 2093 #[test] 2094 fn cli_multiple_preopens() -> Result<()> { 2095 run_wasmtime(&[ 2096 "run", 2097 "--dir=/::/a", 2098 "--dir=/::/b", 2099 "--dir=/::/c", 2100 CLI_MULTIPLE_PREOPENS_COMPONENT, 2101 ])?; 2102 Ok(()) 2103 } 2104 2105 async fn cli_serve_guest_never_invoked_set(wasm: &str) -> Result<()> { 2106 let server = WasmtimeServe::new(wasm, |cmd| { 2107 cmd.arg("-Scli"); 2108 })?; 2109 2110 for _ in 0..2 { 2111 let res = server 2112 .send_request( 2113 hyper::Request::builder() 2114 .uri("http://localhost/") 2115 .body(String::new()) 2116 .context("failed to make request")?, 2117 ) 2118 .await 2119 .expect("got response from wasmtime"); 2120 assert_eq!(res.status(), http::StatusCode::INTERNAL_SERVER_ERROR); 2121 } 2122 2123 let (stdout, stderr) = server.finish()?; 2124 println!("stdout: {stdout}"); 2125 println!("stderr: {stderr}"); 2126 assert!(stderr.contains("guest never invoked `response-outparam::set` method")); 2127 assert!(!stderr.contains("panicked")); 2128 Ok(()) 2129 } 2130 2131 #[tokio::test] 2132 async fn cli_serve_return_before_set() -> Result<()> { 2133 cli_serve_guest_never_invoked_set(CLI_SERVE_RETURN_BEFORE_SET_COMPONENT).await 2134 } 2135 2136 #[tokio::test] 2137 async fn cli_serve_trap_before_set() -> Result<()> { 2138 cli_serve_guest_never_invoked_set(CLI_SERVE_TRAP_BEFORE_SET_COMPONENT).await 2139 } 2140 2141 #[test] 2142 fn cli_p3_hello_stdout() -> Result<()> { 2143 let output = run_wasmtime(&[ 2144 "run", 2145 "-Wcomponent-model-async", 2146 "-Sp3", 2147 CLI_P3_HELLO_STDOUT_COMPONENT, 2148 ]); 2149 if cfg!(feature = "component-model-async") { 2150 let output = output?; 2151 assert_eq!(output, "hello, world\n"); 2152 } else { 2153 assert!(output.is_err()); 2154 } 2155 Ok(()) 2156 } 2157 2158 mod invoke { 2159 use super::*; 2160 2161 #[test] 2162 fn cli_hello_stdout() -> Result<()> { 2163 println!("{CLI_HELLO_STDOUT_COMPONENT}"); 2164 let output = run_wasmtime(&[ 2165 "run", 2166 "-Wcomponent-model", 2167 "--invoke", 2168 "run()", 2169 CLI_HELLO_STDOUT_COMPONENT, 2170 ])?; 2171 // First this component prints "hello, world", then the invoke 2172 // result is printed as "ok". 2173 assert_eq!(output, "hello, world\nok\n"); 2174 Ok(()) 2175 } 2176 } 2177 2178 #[test] 2179 #[cfg_attr(not(feature = "component-model-async"), ignore)] 2180 fn cli_invoke_async() -> Result<()> { 2181 let output = run_wasmtime(&[ 2182 "run", 2183 "-Wcomponent-model-async", 2184 "--invoke", 2185 "echo(\"hello?\")", 2186 CLI_INVOKE_ASYNC_COMPONENT, 2187 ])?; 2188 assert_eq!(output, "\"hello?\"\n"); 2189 Ok(()) 2190 } 2191 2192 fn run_much_stdout(component: &str, extra_flags: &[&str]) -> Result<()> { 2193 let total_write_size = 1 << 18; 2194 let expected = iter::repeat('a').take(total_write_size).collect::<String>(); 2195 2196 for i in 10..15 { 2197 let string = iter::repeat('a').take(1 << i).collect::<String>(); 2198 let times = (total_write_size >> i).to_string(); 2199 println!("writing {} bytes {times} times", string.len()); 2200 2201 let mut args = Vec::new(); 2202 args.push("run"); 2203 args.extend_from_slice(extra_flags); 2204 args.push(component); 2205 args.push(&string); 2206 args.push(×); 2207 let output = run_wasmtime(&args)?; 2208 println!( 2209 "expected {} bytes, got {} bytes", 2210 expected.len(), 2211 output.len() 2212 ); 2213 assert!(output == expected); 2214 } 2215 2216 Ok(()) 2217 } 2218 2219 #[test] 2220 fn cli_p1_much_stdout() -> Result<()> { 2221 run_much_stdout(CLI_P1_MUCH_STDOUT_COMPONENT, &[]) 2222 } 2223 2224 #[test] 2225 fn cli_p2_much_stdout() -> Result<()> { 2226 run_much_stdout(CLI_P2_MUCH_STDOUT_COMPONENT, &[]) 2227 } 2228 2229 #[test] 2230 #[cfg_attr(not(feature = "component-model-async"), ignore)] 2231 fn cli_p3_much_stdout() -> Result<()> { 2232 run_much_stdout( 2233 CLI_P3_MUCH_STDOUT_COMPONENT, 2234 &["-Wcomponent-model-async", "-Sp3"], 2235 ) 2236 } 2237 2238 #[tokio::test] 2239 #[cfg_attr(not(feature = "component-model-async"), ignore)] 2240 async fn cli_serve_p3_hello_world() -> Result<()> { 2241 let server = WasmtimeServe::new(CLI_SERVE_P3_HELLO_WORLD_COMPONENT, |cmd| { 2242 cmd.arg("-Wcomponent-model-async"); 2243 cmd.arg("-Sp3,cli"); 2244 })?; 2245 2246 let result = server 2247 .send_request( 2248 hyper::Request::builder() 2249 .uri("http://localhost/") 2250 .body(String::new()) 2251 .context("failed to make request")?, 2252 ) 2253 .await?; 2254 2255 assert!(result.status().is_success()); 2256 assert_eq!(result.body(), "Hello, WASI!"); 2257 2258 server.finish()?; 2259 Ok(()) 2260 } 2261 } 2262 2263 #[test] 2264 fn settings_command() -> Result<()> { 2265 // Skip this test on platforms that Cranelift doesn't support. 2266 if cranelift_native::builder().is_err() { 2267 return Ok(()); 2268 } 2269 let output = run_wasmtime(&["settings"])?; 2270 assert!(output.contains("Cranelift settings for target")); 2271 Ok(()) 2272 } 2273 2274 #[cfg(target_arch = "x86_64")] 2275 #[test] 2276 fn profile_with_vtune() -> Result<()> { 2277 if !is_vtune_available() { 2278 println!("> `vtune` is not available on the system path; skipping test"); 2279 return Ok(()); 2280 } 2281 2282 let mut bin = Command::new("vtune"); 2283 bin.args(&[ 2284 // Configure VTune... 2285 "-verbose", 2286 "-collect", 2287 "hotspots", 2288 "-user-data-dir", 2289 &std::env::temp_dir().to_string_lossy(), 2290 // ...then run Wasmtime with profiling enabled: 2291 get_wasmtime_path(), 2292 "--profile=vtune", 2293 "tests/all/cli_tests/simple.wat", 2294 ]); 2295 2296 println!("> executing: {bin:?}"); 2297 let output = bin.output()?; 2298 2299 assert!(output.status.success()); 2300 let stdout = String::from_utf8_lossy(&output.stdout); 2301 let stderr = String::from_utf8_lossy(&output.stderr); 2302 println!("> stdout:\n{stdout}"); 2303 assert!(stdout.contains("CPU Time")); 2304 println!("> stderr:\n{stderr}"); 2305 assert!(!stderr.contains("Error")); 2306 Ok(()) 2307 } 2308 2309 #[cfg(target_arch = "x86_64")] 2310 fn is_vtune_available() -> bool { 2311 Command::new("vtune").arg("-version").output().is_ok() 2312 } 2313 2314 #[test] 2315 fn profile_guest() -> Result<()> { 2316 let tmpdir = std::env::temp_dir(); 2317 let dir = tmpdir.to_string_lossy(); 2318 2319 let output = run_wasmtime_for_output( 2320 &[ 2321 &format!("--profile=guest,{dir}/out.json"), 2322 "--env", 2323 "FOO=bar", 2324 "tests/all/cli_tests/print_env.wat", 2325 ], 2326 None, 2327 )?; 2328 2329 assert!(output.status.success()); 2330 let stdout = String::from_utf8_lossy(&output.stdout); 2331 let stderr = String::from_utf8_lossy(&output.stderr); 2332 println!("> stdout:\n{stdout}"); 2333 println!("> stderr:\n{stderr}"); 2334 assert!(!stderr.contains("Error")); 2335 let out_json = std::fs::read_to_string(format!("{dir}/out.json")).unwrap(); 2336 println!("> out.json:\n{out_json}"); 2337 Ok(()) 2338 } 2339 2340 #[test] 2341 fn unreachable_without_wasi() -> Result<()> { 2342 let output = run_wasmtime_for_output( 2343 &[ 2344 "-Scli=n", 2345 "-Ccache=n", 2346 "tests/all/cli_tests/unreachable.wat", 2347 ], 2348 None, 2349 )?; 2350 2351 assert_ne!(output.stderr, b""); 2352 assert_eq!(output.stdout, b""); 2353 assert_trap_code(&output.status); 2354 Ok(()) 2355 } 2356 2357 #[test] 2358 fn config_cli_flag() -> Result<()> { 2359 let wasm = build_wasm("tests/all/cli_tests/simple.wat")?; 2360 2361 // Test some valid TOML values 2362 let (mut cfg, cfg_path) = tempfile::NamedTempFile::new()?.into_parts(); 2363 cfg.write_all( 2364 br#" 2365 [optimize] 2366 opt-level = 2 2367 signals-based-traps = false 2368 2369 [codegen] 2370 collector = "null" 2371 2372 [debug] 2373 address-map = true 2374 2375 [wasm] 2376 max-wasm-stack = 65536 2377 2378 [wasi] 2379 cli = true 2380 "#, 2381 )?; 2382 let output = run_wasmtime(&[ 2383 "run", 2384 "--config", 2385 cfg_path.to_str().unwrap(), 2386 "--invoke", 2387 "get_f64", 2388 wasm.path().to_str().unwrap(), 2389 ])?; 2390 assert_eq!(output, "100\n"); 2391 2392 // Make sure CLI flags overrides TOML values 2393 let output = run_wasmtime(&[ 2394 "run", 2395 "--config", 2396 cfg_path.to_str().unwrap(), 2397 "--invoke", 2398 "get_f64", 2399 "-W", 2400 "max-wasm-stack=0", // should override TOML value 65536 specified above and execution should fail 2401 wasm.path().to_str().unwrap(), 2402 ]); 2403 assert!( 2404 output 2405 .as_ref() 2406 .unwrap_err() 2407 .to_string() 2408 .contains("max_wasm_stack size cannot be zero"), 2409 "'{output:?}' did not contain expected error message", 2410 ); 2411 2412 // Test invalid TOML key 2413 let (mut cfg, cfg_path) = tempfile::NamedTempFile::new()?.into_parts(); 2414 cfg.write_all( 2415 br#" 2416 [optimize] 2417 this-key-does-not-exist = true 2418 "#, 2419 )?; 2420 let output = run_wasmtime(&[ 2421 "run", 2422 "--config", 2423 cfg_path.to_str().unwrap(), 2424 wasm.path().to_str().unwrap(), 2425 ]); 2426 assert!( 2427 output 2428 .as_ref() 2429 .unwrap_err() 2430 .to_string() 2431 .contains("unknown field `this-key-does-not-exist`"), 2432 "'{output:?}' did not contain expected error message" 2433 ); 2434 2435 // Test invalid TOML table 2436 let (mut cfg, cfg_path) = tempfile::NamedTempFile::new()?.into_parts(); 2437 cfg.write_all( 2438 br#" 2439 [invalid_table] 2440 "#, 2441 )?; 2442 let output = run_wasmtime(&[ 2443 "run", 2444 "--config", 2445 cfg_path.to_str().unwrap(), 2446 wasm.path().to_str().unwrap(), 2447 ]); 2448 assert!( 2449 output 2450 .as_ref() 2451 .unwrap_err() 2452 .to_string() 2453 .contains("unknown field `invalid_table`, expected one of `optimize`, `codegen`, `debug`, `wasm`, `wasi`"), 2454 "'{output:?}' did not contain expected error message", 2455 ); 2456 2457 Ok(()) 2458 } 2459 2460 #[test] 2461 fn invalid_subcommand() -> Result<()> { 2462 let output = run_wasmtime_for_output(&["invalid-subcommand"], None)?; 2463 dbg!(&output); 2464 assert!(!output.status.success()); 2465 assert!(String::from_utf8_lossy(&output.stderr).contains("invalid-subcommand")); 2466 Ok(()) 2467 } 2468 2469 #[test] 2470 fn numeric_args() -> Result<()> { 2471 let wasm = build_wasm("tests/all/cli_tests/numeric_args.wat")?; 2472 // Test decimal i32 2473 let output = run_wasmtime_for_output( 2474 &[ 2475 "run", 2476 "--invoke", 2477 "i32_test", 2478 wasm.path().to_str().unwrap(), 2479 "42", 2480 ], 2481 None, 2482 )?; 2483 assert_eq!(output.status.success(), true); 2484 assert_eq!(output.stdout, b"42\n"); 2485 // Test hexadecimal i32 with lowercase prefix 2486 let output = run_wasmtime_for_output( 2487 &[ 2488 "run", 2489 "--invoke", 2490 "i32_test", 2491 wasm.path().to_str().unwrap(), 2492 "0x2A", 2493 ], 2494 None, 2495 )?; 2496 assert_eq!(output.status.success(), true); 2497 assert_eq!(output.stdout, b"42\n"); 2498 // Test hexadecimal i32 with uppercase prefix 2499 let output = run_wasmtime_for_output( 2500 &[ 2501 "run", 2502 "--invoke", 2503 "i32_test", 2504 wasm.path().to_str().unwrap(), 2505 "0X2a", 2506 ], 2507 None, 2508 )?; 2509 assert_eq!(output.status.success(), true); 2510 assert_eq!(output.stdout, b"42\n"); 2511 // Test that non-prefixed hex strings are not interpreted as hex 2512 let output = run_wasmtime_for_output( 2513 &[ 2514 "run", 2515 "--invoke", 2516 "i32_test", 2517 wasm.path().to_str().unwrap(), 2518 "ff", 2519 ], 2520 None, 2521 )?; 2522 assert!(!output.status.success()); // Should fail as "ff" is not a valid decimal number 2523 2524 // Test decimal i64 2525 let output = run_wasmtime_for_output( 2526 &[ 2527 "run", 2528 "--invoke", 2529 "i64_test", 2530 wasm.path().to_str().unwrap(), 2531 "42", 2532 ], 2533 None, 2534 )?; 2535 assert_eq!(output.status.success(), true); 2536 assert_eq!(output.stdout, b"42\n"); 2537 // Test hexadecimal i64 2538 let output = run_wasmtime_for_output( 2539 &[ 2540 "run", 2541 "--invoke", 2542 "i64_test", 2543 wasm.path().to_str().unwrap(), 2544 "0x2A", 2545 ], 2546 None, 2547 )?; 2548 assert_eq!(output.status.success(), true); 2549 assert_eq!(output.stdout, b"42\n"); 2550 Ok(()) 2551 } 2552 2553 #[test] 2554 fn compilation_logs() -> Result<()> { 2555 let temp = tempfile::NamedTempFile::new()?; 2556 let output = get_wasmtime_command()? 2557 .args(&[ 2558 "compile", 2559 "-Wgc", 2560 "tests/all/cli_tests/issue-10353.wat", 2561 "--output", 2562 &temp.path().display().to_string(), 2563 ]) 2564 .env("WASMTIME_LOG", "trace") 2565 .env("RUST_BACKTRACE", "1") 2566 .output()?; 2567 if !output.status.success() { 2568 println!("stdout: {}", String::from_utf8_lossy(&output.stdout)); 2569 println!("stderr: {}", String::from_utf8_lossy(&output.stderr)); 2570 panic!("wasmtime compilation failed when logs requested"); 2571 } 2572 Ok(()) 2573 } 2574 2575 #[test] 2576 fn big_table_in_pooling_allocator() -> Result<()> { 2577 // Works by default 2578 run_wasmtime(&["tests/all/cli_tests/big_table.wat"])?; 2579 2580 // Does not work by default in the pooling allocator, and the error message 2581 // should mention something about the pooling allocator. 2582 let output = run_wasmtime_for_output( 2583 &["-Opooling-allocator", "tests/all/cli_tests/big_table.wat"], 2584 None, 2585 )?; 2586 assert!(!output.status.success()); 2587 println!("{}", String::from_utf8_lossy(&output.stderr)); 2588 assert!(String::from_utf8_lossy(&output.stderr).contains("pooling allocator")); 2589 2590 // Does work with `-Wmax-table-elements` 2591 run_wasmtime(&[ 2592 "-Opooling-allocator", 2593 "-Wmax-table-elements=25000", 2594 "tests/all/cli_tests/big_table.wat", 2595 ])?; 2596 // Also works with `-Opooling-table-elements` 2597 run_wasmtime(&[ 2598 "-Opooling-allocator", 2599 "-Opooling-table-elements=25000", 2600 "tests/all/cli_tests/big_table.wat", 2601 ])?; 2602 Ok(()) 2603 } 2604