1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
//! The commands available in the Wasmer binary.
mod add;
mod app;
mod auth;
#[cfg(target_os = "linux")]
mod binfmt;
mod cache;
#[cfg(feature = "compiler")]
mod compile;
mod config;
mod connect;
mod container;
#[cfg(any(feature = "static-artifact-create", feature = "wasmer-artifact-create"))]
mod create_exe;
#[cfg(feature = "static-artifact-create")]
mod create_obj;
pub(crate) mod domain;
#[cfg(feature = "static-artifact-create")]
mod gen_c_header;
mod gen_completions;
mod gen_manpage;
mod init;
mod inspect;
#[cfg(feature = "journal")]
mod journal;
pub(crate) mod namespace;
mod package;
mod run;
mod self_update;
pub mod ssh;
mod validate;
#[cfg(feature = "wast")]
mod wast;
use itertools::Itertools;
use std::io::IsTerminal as _;
use tokio::task::JoinHandle;
#[cfg(target_os = "linux")]
pub use binfmt::*;
use clap::{CommandFactory, Parser};
#[cfg(feature = "compiler")]
pub use compile::*;
#[cfg(any(feature = "static-artifact-create", feature = "wasmer-artifact-create"))]
pub use create_exe::*;
#[cfg(feature = "wast")]
pub use wast::*;
#[cfg(feature = "static-artifact-create")]
#[allow(unused_imports)]
pub use {create_obj::*, gen_c_header::*};
#[cfg(feature = "journal")]
pub use self::journal::*;
pub use self::{
add::*, auth::*, cache::*, config::*, container::*, init::*, inspect::*, package::*,
publish::*, run::Run, self_update::*, validate::*,
};
use crate::error::PrettyError;
use git_version::git_version;
/// An executable CLI command.
pub(crate) trait CliCommand {
type Output;
fn run(self) -> Result<(), anyhow::Error>;
}
/// An executable CLI command that runs in an async context.
///
/// An [`AsyncCliCommand`] automatically implements [`CliCommand`] by creating
/// a new tokio runtime and blocking.
#[async_trait::async_trait]
pub(crate) trait AsyncCliCommand: Send + Sync {
type Output: Send + Sync;
async fn run_async(self) -> Result<Self::Output, anyhow::Error>;
fn setup(
&self,
done: tokio::sync::oneshot::Receiver<()>,
) -> Option<JoinHandle<anyhow::Result<()>>> {
if std::io::stdin().is_terminal() {
return Some(tokio::task::spawn(async move {
tokio::select! {
_ = done => {}
_ = tokio::signal::ctrl_c() => {
let term = console::Term::stdout();
let _ = term.show_cursor();
// https://learn.microsoft.com/en-us/cpp/c-runtime-library/signal-constants
#[cfg(target_os = "windows")]
std::process::exit(3);
// POSIX compliant OSs: 128 + SIGINT (2)
#[cfg(not(target_os = "windows"))]
std::process::exit(130);
}
}
Ok::<(), anyhow::Error>(())
}));
}
None
}
}
impl<O: Send + Sync, C: AsyncCliCommand<Output = O>> CliCommand for C {
type Output = O;
fn run(self) -> Result<(), anyhow::Error> {
tokio::runtime::Runtime::new()?.block_on(async {
let (snd, rcv) = tokio::sync::oneshot::channel();
let handle = self.setup(rcv);
if let Err(e) = AsyncCliCommand::run_async(self).await {
if let Some(handle) = handle {
handle.abort();
}
return Err(e);
}
if let Some(handle) = handle {
if snd.send(()).is_err() {
tracing::warn!("Failed to send 'done' signal to setup thread!");
handle.abort();
} else {
handle.await??;
}
}
Ok::<(), anyhow::Error>(())
})?;
Ok(())
}
}
/// Command-line arguments for the Wasmer CLI.
#[derive(clap::Parser, Debug)]
#[clap(author, version)]
#[clap(disable_version_flag = true)] // handled manually
#[cfg_attr(feature = "headless", clap(
name = "wasmer-headless",
about = concat!("wasmer-headless ", env!("CARGO_PKG_VERSION")),
))]
#[cfg_attr(not(feature = "headless"), clap(
name = "wasmer",
about = concat!("wasmer ", env!("CARGO_PKG_VERSION")),
))]
pub struct WasmerCmd {
/// Print version info and exit.
#[clap(short = 'V', long)]
version: bool,
#[clap(flatten)]
output: crate::logging::Output,
#[clap(subcommand)]
cmd: Option<Cmd>,
}
impl WasmerCmd {
fn execute(self) -> Result<(), anyhow::Error> {
let WasmerCmd {
cmd,
version,
output,
} = self;
output.initialize_logging();
if version {
return print_version(output.is_verbose());
}
match cmd {
Some(Cmd::GenManPage(cmd)) => cmd.execute(),
Some(Cmd::GenCompletions(cmd)) => cmd.execute(),
Some(Cmd::Run(options)) => options.execute(output),
Some(Cmd::SelfUpdate(options)) => options.execute(),
Some(Cmd::Cache(cache)) => cache.execute(),
Some(Cmd::Validate(validate)) => validate.execute(),
#[cfg(feature = "compiler")]
Some(Cmd::Compile(compile)) => compile.execute(),
// CreateExe and CreateObj commands are temporarily disabled
// #[cfg(any(feature = "static-artifact-create", feature = "wasmer-artifact-create"))]
// Some(Cmd::CreateExe(create_exe)) => create_exe.run(),
// #[cfg(feature = "static-artifact-create")]
// Some(Cmd::CreateObj(create_obj)) => create_obj.execute(),
Some(Cmd::Config(config)) => config.run(),
Some(Cmd::Inspect(inspect)) => inspect.execute(),
Some(Cmd::Init(init)) => init.run(),
Some(Cmd::Login(login)) => login.run(),
Some(Cmd::Auth(auth)) => auth.run(),
Some(Cmd::Publish(publish)) => publish.run().map(|_| ()),
Some(Cmd::Package(cmd)) => match cmd {
Package::Download(cmd) => cmd.execute(),
Package::Build(cmd) => cmd.execute().map(|_| ()),
Package::Tag(cmd) => cmd.run(),
Package::Push(cmd) => cmd.run(),
Package::Publish(cmd) => cmd.run().map(|_| ()),
Package::Unpack(cmd) => cmd.execute(),
},
Some(Cmd::Container(cmd)) => match cmd {
crate::commands::Container::Unpack(cmd) => cmd.execute(),
},
#[cfg(feature = "static-artifact-create")]
Some(Cmd::GenCHeader(gen_heder)) => gen_heder.execute(),
#[cfg(feature = "wast")]
Some(Cmd::Wast(wast)) => wast.execute(),
#[cfg(target_os = "linux")]
Some(Cmd::Binfmt(binfmt)) => binfmt.execute(),
Some(Cmd::Whoami(whoami)) => whoami.run(),
Some(Cmd::Add(add)) => add.run(),
// Deploy commands.
Some(Cmd::Deploy(c)) => c.run(),
Some(Cmd::App(apps)) => apps.run(),
#[cfg(feature = "journal")]
Some(Cmd::Journal(journal)) => journal.run(),
Some(Cmd::Ssh(ssh)) => ssh.run(),
Some(Cmd::Namespace(namespace)) => namespace.run(),
Some(Cmd::Domain(namespace)) => namespace.run(),
None => {
WasmerCmd::command().print_long_help()?;
// Note: clap uses an exit code of 2 when CLI parsing fails
std::process::exit(2);
}
}
}
/// The main function for the Wasmer CLI tool.
pub fn run() {
// We allow windows to print properly colors
#[cfg(windows)]
colored::control::set_virtual_terminal(true).unwrap();
PrettyError::report(Self::run_inner())
}
fn run_inner() -> Result<(), anyhow::Error> {
let mut args_os = std::env::args_os();
let args = args_os.next().into_iter();
let mut binfmt_args = Vec::new();
if is_binfmt_interpreter() {
// In case of binfmt misc the first argument is wasmer-binfmt-interpreter, the second is the full path to the executable
// and the third is the original string for the executable as originally called by the user.
// For now we are only using the real path and ignoring the original executable name.
// Ideally we would use the real path to load the file and the original name to pass it as argv[0] to the wasm module.
let current_dir = std::env::current_dir().unwrap();
let mut mount_paths = ["/home", "/etc", "/tmp", "/var", "/nix", "/opt", "/root"]
.into_iter()
.map(std::path::PathBuf::from)
.filter(|path| {
if !path.is_dir() {
// Not a directory
return false;
}
if std::fs::read_dir(path).is_err() {
// No permissions
return false;
}
true
})
.collect_vec();
if mount_paths
.iter()
.all(|path| !current_dir.starts_with(path))
{
// Mount the current dir if it is not already covered by a common path
mount_paths.push(current_dir.clone());
}
binfmt_args.push("run".into());
binfmt_args.push("--net".into());
// TODO: This does not seem to work, needs further investigation.
binfmt_args.push("--forward-host-env".into());
for mount_path in mount_paths {
if let Some(mount_path_str) = mount_path.to_str() {
binfmt_args.push(format!("--volume={mount_path_str}:{mount_path_str}").into());
}
}
if let Some(current_dir_str) = current_dir.to_str() {
binfmt_args.push(format!("--cwd={current_dir_str}").into());
}
binfmt_args.push("--quiet".into());
binfmt_args.push("--".into());
binfmt_args.push(args_os.next().unwrap());
args_os.next().unwrap();
};
let args_vec = args.chain(binfmt_args).chain(args_os).collect_vec();
match WasmerCmd::try_parse_from(args_vec.iter()) {
Ok(args) => args.execute(),
Err(e) => {
let first_arg_is_subcommand = if let Some(first_arg) = args_vec.get(1) {
let mut ret = false;
let cmd = WasmerCmd::command();
for cmd in cmd.get_subcommands() {
if cmd.get_name() == first_arg {
ret = true;
break;
}
}
ret
} else {
false
};
let might_be_wasmer_run = matches!(
e.kind(),
clap::error::ErrorKind::InvalidSubcommand
| clap::error::ErrorKind::UnknownArgument
) && !first_arg_is_subcommand;
if might_be_wasmer_run && let Ok(run) = Run::try_parse_from(args_vec.iter()) {
// Try to parse the command using the `wasmer some/package`
// shorthand. Note that this has discoverability issues
// because it's not shown as part of the main argument
// parser's help, but that's fine.
let output = crate::logging::Output::default();
output.initialize_logging();
run.execute(output);
}
e.exit();
}
}
}
}
#[derive(clap::Parser, Debug)]
#[allow(clippy::large_enum_variant)]
/// The options for the wasmer Command Line Interface
enum Cmd {
/// Login into Wasmer
Login(Login),
#[clap(subcommand)]
Auth(CmdAuth),
/// Publish a package to a registry [alias: package publish]
#[clap(name = "publish")]
Publish(PackagePublish),
/// Manage the local Wasmer cache
Cache(Cache),
/// Validate a WebAssembly binary
Validate(Validate),
/// Compile a WebAssembly binary
#[cfg(feature = "compiler")]
Compile(Compile),
// Compile a WebAssembly binary into a native executable
//
// To use, you need to set the `WASMER_DIR` environment variable
// to the location of your Wasmer installation. This will probably be `~/.wasmer`. It
// should include a `lib`, `include` and `bin` subdirectories. To create an executable
// you will need `libwasmer`, so by setting `WASMER_DIR` the CLI knows where to look for
// header files and libraries.
//
// Example usage:
//
// ```text
// $ # in two lines:
// $ export WASMER_DIR=/home/user/.wasmer/
// $ wasmer create-exe qjs.wasm -o qjs.exe # or in one line:
// $ WASMER_DIR=/home/user/.wasmer/ wasmer create-exe qjs.wasm -o qjs.exe
// $ file qjs.exe
// qjs.exe: ELF 64-bit LSB pie executable, x86-64 ...
// ```
//
// ## Cross-compilation
//
// Accepted target triple values must follow the
// ['target_lexicon'](https://crates.io/crates/target-lexicon) crate format.
//
// The recommended targets we try to support are:
//
// - "x86_64-linux-gnu"
// - "aarch64-linux-gnu"
// - "arm64-apple-darwin"
// #[cfg(any(feature = "static-artifact-create", feature = "wasmer-artifact-create"))]
// #[clap(name = "create-exe", verbatim_doc_comment)]
// CreateExe(CreateExe),
/// Compile a WebAssembly binary into an object file
///
/// To use, you need to set the `WASMER_DIR` environment variable to the location of your
/// Wasmer installation. This will probably be `~/.wasmer`. It should include a `lib`,
/// `include` and `bin` subdirectories. To create an object you will need `libwasmer`, so by
/// setting `WASMER_DIR` the CLI knows where to look for header files and libraries.
///
/// Example usage:
///
/// ```text
/// $ # in two lines:
/// $ export WASMER_DIR=/home/user/.wasmer/
/// $ wasmer create-obj qjs.wasm --object-format symbols -o qjs.obj # or in one line:
/// $ WASMER_DIR=/home/user/.wasmer/ wasmer create-exe qjs.wasm --object-format symbols -o qjs.obj
/// $ file qjs.obj
/// qjs.obj: ELF 64-bit LSB relocatable, x86-64 ...
/// ```
///
/// ## Cross-compilation
///
/// Accepted target triple values must follow the
/// ['target_lexicon'](https://crates.io/crates/target-lexicon) crate format.
///
/// The recommended targets we try to support are:
///
/// - "x86_64-linux-gnu"
/// - "aarch64-linux-gnu"
/// - "arm64-apple-darwin"
// #[cfg(feature = "static-artifact-create")]
// #[structopt(name = "create-obj", verbatim_doc_comment)]
// CreateObj(CreateObj),
///
/// Generate the C static_defs.h header file for the input .wasm module
///
#[cfg(feature = "static-artifact-create")]
GenCHeader(GenCHeader),
/// Get various configuration information needed
/// to compile programs which use Wasmer
Config(Config),
/// Update wasmer to the latest version
#[clap(name = "self-update")]
SelfUpdate(SelfUpdate),
/// Inspect a WebAssembly file
Inspect(Inspect),
/// Initializes a new wasmer.toml file
#[clap(name = "init")]
Init(Init),
/// Run spec testsuite
#[cfg(feature = "wast")]
Wast(Wast),
/// Unregister and/or register wasmer as binfmt interpreter
#[cfg(target_os = "linux")]
Binfmt(Binfmt),
/// Shows the current logged in user for the current active registry
Whoami(Whoami),
/// Add a Wasmer package's bindings to your application
Add(CmdAdd),
/// Run a WebAssembly file or Wasmer container
#[clap(alias = "run-unstable")]
Run(Run),
/// Manage journals (compacting, inspecting, filtering, ...)
#[cfg(feature = "journal")]
#[clap(subcommand)]
Journal(CmdJournal),
#[clap(subcommand)]
Package(crate::commands::Package),
#[clap(subcommand)]
Container(crate::commands::Container),
// Edge commands
/// Deploy apps to Wasmer Edge [alias: app deploy]
Deploy(crate::commands::app::deploy::CmdAppDeploy),
/// Create and manage Wasmer Edge apps
#[clap(subcommand, alias = "apps")]
App(crate::commands::app::CmdApp),
/// Run commands/packages on Wasmer Edge in an interactive shell session
Ssh(crate::commands::ssh::CmdSsh),
/// Manage Wasmer namespaces
#[clap(subcommand, alias = "namespaces")]
Namespace(crate::commands::namespace::CmdNamespace),
/// Manage DNS records
#[clap(subcommand, alias = "domains")]
Domain(crate::commands::domain::CmdDomain),
/// Generate autocompletion for different shells
#[clap(name = "gen-completions")]
GenCompletions(crate::commands::gen_completions::CmdGenCompletions),
/// Generate man pages
#[clap(name = "gen-man", hide = true)]
GenManPage(crate::commands::gen_manpage::CmdGenManPage),
}
fn is_binfmt_interpreter() -> bool {
cfg_if::cfg_if! {
if #[cfg(target_os = "linux")] {
// Note: we'll be invoked by the kernel as Binfmt::FILENAME
let binary_path = match std::env::args_os().next() {
Some(path) => std::path::PathBuf::from(path),
None => return false,
};
binary_path.file_name().and_then(|f| f.to_str()) == Some(Binfmt::FILENAME)
} else {
false
}
}
}
fn print_version(verbose: bool) -> Result<(), anyhow::Error> {
if !verbose {
println!("wasmer {}", env!("CARGO_PKG_VERSION"));
return Ok(());
}
println!("wasmer {}", env!("CARGO_PKG_VERSION"));
println!("binary: {}", env!("CARGO_PKG_NAME"));
let git_hash = git_version!(
args = [
"--abbrev=40",
"--always",
"--dirty=-modified",
"--exclude=*"
],
fallback = "",
)
.to_string();
if !git_hash.is_empty() {
println!("commit-hash: {git_hash}",);
}
if !env!("WASMER_REPRODUCIBLE_BUILD")
.parse::<bool>()
.expect("build-time variable expected")
{
println!("commit-date: {}", env!("WASMER_BUILD_DATE"));
}
println!("host: {}", target_lexicon::HOST);
let cpu_features = wasmer_types::target::CpuFeature::for_host()
.iter()
.map(|f| f.to_string())
.join(" ");
println!("CPU flags: {cpu_features}");
let mut runtimes = Vec::new();
if cfg!(feature = "singlepass") {
runtimes.push("Singlepass");
}
if cfg!(feature = "cranelift") {
runtimes.push("Cranelift");
}
if cfg!(feature = "llvm") {
runtimes.push("LLVM");
}
if cfg!(feature = "v8") {
runtimes.push("V8");
}
println!("runtimes: {}", runtimes.join(", "));
#[allow(clippy::useless_vec)]
#[allow(unused_mut)]
let mut features = vec!["wasix".to_string()];
#[cfg(feature = "napi-v8")]
{
for napi_version in enum_iterator::all::<wasmer_napi::NapiVersion>() {
if !matches!(napi_version, wasmer_napi::NapiVersion::Unknown) {
features.push(napi_version.to_string());
}
}
features.push(wasmer_napi::NAPI_EXTENSION_WASMER_MODULE_NAME.to_string());
}
println!("features: {}", features.join(", "));
Ok(())
}