Skip to content

Commit

Permalink
feat: add wasm-dis
Browse files Browse the repository at this point in the history
  • Loading branch information
csmoe committed Mar 31, 2020
1 parent b7fe107 commit 4e6d586
Show file tree
Hide file tree
Showing 4 changed files with 80 additions and 29 deletions.
39 changes: 35 additions & 4 deletions src/command/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ pub struct Build {
pub out_dir: PathBuf,
pub out_name: Option<String>,
pub bindgen: Option<Status>,
pub wat: bool,
pub cache: Cache,
pub extra_options: Vec<String>,
}
Expand Down Expand Up @@ -141,6 +142,10 @@ pub struct BuildOptions {
/// Create a profiling build. Enable optimizations and debug info.
pub profiling: bool,

#[structopt(long = "wat")]
/// Dis-assemble .wasm(webassembly binary) into webassembly text.
pub wat: bool,

#[structopt(long = "out-dir", short = "d", default_value = "pkg")]
/// Sets the output directory with a relative path.
pub out_dir: String,
Expand All @@ -166,6 +171,7 @@ impl Default for BuildOptions {
dev: false,
release: false,
profiling: false,
wat: false,
out_dir: String::new(),
out_name: None,
extra_options: Vec::new(),
Expand Down Expand Up @@ -203,6 +209,7 @@ impl Build {
out_dir,
out_name: build_opts.out_name,
bindgen: None,
wat: build_opts.wat,
cache: cache::get_wasm_pack_cache()?,
extra_options: build_opts.extra_options,
})
Expand All @@ -215,7 +222,7 @@ impl Build {

/// Execute this `Build` command.
pub fn run(&mut self) -> Result<(), Error> {
let process_steps = Build::get_process_steps(self.mode);
let process_steps = self.get_process_steps(self.mode);

let started = Instant::now();

Expand All @@ -240,7 +247,7 @@ impl Build {
Ok(())
}

fn get_process_steps(mode: InstallMode) -> Vec<(&'static str, BuildStep)> {
fn get_process_steps(&mut self, mode: InstallMode) -> Vec<(&'static str, BuildStep)> {
macro_rules! steps {
($($name:ident),+) => {
{
Expand Down Expand Up @@ -271,6 +278,9 @@ impl Build {
step_run_wasm_opt,
step_create_json,
]);
if self.wat {
steps.extend(steps![step_run_wasm_dis]);
}
steps
}

Expand Down Expand Up @@ -377,9 +387,9 @@ impl Build {
None => return Ok(()),
};
info!("executing wasm-opt with {:?}", args);
let version = String::from("version_78");
let version = String::from("version_90");
let wasm_opt = Tool::new(Kind::WasmOpt, version);
wasm_opt.run(&self.cache,self.mode.install_permitted(), |exec: &Path| {
wasm_opt.run(&self.cache, self.mode.install_permitted(), |exec: &Path| {
for file in self.out_dir.read_dir()? {
let file = file?;
let path = file.path();
Expand All @@ -401,4 +411,25 @@ impl Build {
})?;
Ok(())
}

fn step_run_wasm_dis(&mut self) -> Result<(), Error> {
info!("executing wasm-opt ..");
let version = String::from("version_90");
let wasm_opt = Tool::new(Kind::WasmDis, version);
wasm_opt.run(&self.cache, self.mode.install_permitted(), |exec: &Path| {
for file in self.out_dir.read_dir()? {
let file = file?;
let path = file.path();
if path.extension().and_then(|s| s.to_str()) != Some("wasm") {
continue;
}
let tmp = path.with_extension("wast");
let mut cmd = Command::new(exec);
cmd.arg(&path).arg("-o").arg(&tmp);
child::run(cmd, "wasm-dis")?;
}
Ok(())
})?;
Ok(())
}
}
64 changes: 43 additions & 21 deletions src/tool/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,14 @@ pub struct Tool {
/// Represents the set of CLI tools wasm-pack uses
#[derive(Clone, Copy)]
pub enum Kind {
/// cargo-generate CLI tool
/// cargo-generate
CargoGenerate,
/// wasm-bindgen CLI tools
/// wasm-bindgen
WasmBindgen,
/// wasm-opt CLI tool
/// wasm-opt
WasmOpt,
/// wasm-dis
WasmDis,
}

impl Tool {
Expand All @@ -45,12 +47,12 @@ impl Tool {
Self { kind, version }
}

/// Run with closure
/// Execute the CLI
pub fn run(
&self,
cache: &Cache,
install_permitted: bool,
f: impl FnOnce(&Path) -> Result<(), failure::Error>,
execute: impl FnOnce(&Path) -> Result<(), failure::Error>,
) -> Result<(), failure::Error> {
let exec = match self.install(cache, install_permitted)? {
Status::Found(path) => path,
Expand All @@ -72,29 +74,28 @@ impl Tool {

let exec_path = exec.binary(&self.kind.to_string())?;
PBAR.info(&format!("Executing `{}`...", self.kind));
f(&exec_path)?;
execute(&exec_path)?;

Ok(())
}

/// Attempts to find `wasm-opt` in `PATH` locally, or failing that downloads a
/// Attempts to find CLIs in `PATH` locally, or failing that downloads a
/// precompiled binary.
///
/// Returns `Some` if a binary was found or it was successfully downloaded.
/// Returns `None` if a binary wasn't found in `PATH` and this platform doesn't
/// Returns `Ok` if a binary was found or it was successfully downloaded.
/// Returns `Err` if a binary wasn't found in `PATH` and this platform doesn't
/// have precompiled binaries. Returns an error if we failed to download the
/// binary.
pub fn install(
&self,
cache: &Cache,
install_permitted: bool,
) -> Result<Status, failure::Error> {
Ok(download_prebuilt_or_cargo_install(
self.kind,
cache,
&self.version,
install_permitted,
)?)
let status =
download_prebuilt_or_cargo_install(self.kind, cache, &self.version, install_permitted)?;
let msg = format!("`{}` installed successfully", self.kind);
PBAR.info(&msg);
Ok(status)
}
}

Expand All @@ -104,11 +105,22 @@ impl fmt::Display for Kind {
Self::CargoGenerate => "cargo-generate",
Self::WasmBindgen => "wasm-bindgen",
Self::WasmOpt => "wasm-opt",
Self::WasmDis => "wasm-dis",
};
write!(f, "{}", s)
}
}

impl Kind {
fn is_from_binaryen(self) -> bool {
use self::Kind::*;
match self {
WasmOpt | WasmDis => true,
_ => false,
}
}
}

/// Possible outcomes of attempting to find/install a tool
pub enum Status {
/// Couldn't install tool because downloads are forbidden by user
Expand Down Expand Up @@ -151,6 +163,9 @@ fn download_prebuilt_or_cargo_install(
match dl {
Ok(dl) => return Ok(dl),
Err(e) => {
if tool.is_from_binaryen() {
bail!("Could not install {} with {}", tool, version);
}
warn!(
"could not download pre-built `{}`: {}. Falling back to `cargo install`.",
tool, e
Expand Down Expand Up @@ -233,6 +248,13 @@ pub fn download_prebuilt(
None => Ok(Status::CannotInstall),
}
}
WasmDis => {
let binaries = &["wasm-dis"];
match cache.download(install_permitted, "wasm-dis", binaries, &url)? {
Some(dl) => Ok(Status::Found(dl)),
None => bail!("{} version({}) is not installed!", tool, version),
}
}
}
}

Expand All @@ -241,7 +263,7 @@ pub fn download_prebuilt(
fn prebuilt_url(tool: Kind, version: &str) -> Result<String, failure::Error> {
let target = if target::LINUX && target::x86_64 {
match tool {
Kind::WasmOpt => "x86-linux",
Kind::WasmOpt | Kind::WasmDis => "x86-linux",
_ => "x86_64-unknown-linux-musl",
}
} else if target::LINUX && target::x86 {
Expand All @@ -253,12 +275,12 @@ fn prebuilt_url(tool: Kind, version: &str) -> Result<String, failure::Error> {
"x86_64-apple-darwin"
} else if target::WINDOWS && target::x86_64 {
match tool {
Kind::WasmOpt => "x86-windows",
Kind::WasmOpt | Kind::WasmDis => "x86-windows",
_ => "x86_64-pc-windows-msvc",
}
} else if target::WINDOWS && target::x86 {
match tool {
Kind::WasmOpt => "x86-windows",
Kind::WasmOpt | Kind::WasmDis => "x86-windows",
_ => bail!("Unrecognized target!"),
}
} else {
Expand All @@ -280,10 +302,10 @@ fn prebuilt_url(tool: Kind, version: &str) -> Result<String, failure::Error> {
target
))
},
Kind::WasmOpt => {
Kind::WasmOpt | Kind::WasmDis => {
Ok(format!(
"https://github.com/WebAssembly/binaryen/releases/download/{vers}/binaryen-{vers}-{target}.tar.gz",
vers = "version_90",
vers = version,
target = target,
))
}
Expand Down Expand Up @@ -352,7 +374,7 @@ pub fn cargo_install(
let binaries: Result<Vec<&str>, failure::Error> = match tool {
Kind::WasmBindgen => Ok(vec!["wasm-bindgen", "wasm-bindgen-test-runner"]),
Kind::CargoGenerate => Ok(vec!["cargo-genrate"]),
Kind::WasmOpt => bail!("Cannot install wasm-opt with cargo."),
Kind::WasmOpt | Kind::WasmDis => bail!("Cannot install with cargo."),
};

for b in binaries?.iter().cloned() {
Expand Down
2 changes: 1 addition & 1 deletion tests/all/utils/fixture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ impl Fixture {
let cache = self.cache();

INSTALL_WASM_OPT.call_once(|| {
Tool::new(Kind::WasmOpt, "version_78".to_string())
Tool::new(Kind::WasmOpt, "version_90".to_string())
.install(&cache, true)
.unwrap();
});
Expand Down
4 changes: 1 addition & 3 deletions tests/all/wasm_opt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,7 @@ fn enable_in_dev() {
.arg("build")
.arg("--dev")
.assert()
.stderr(predicates::str::contains(
"Optimizing wasm binaries with `wasm-opt`",
))
.stderr(predicates::str::contains("Executing `wasm-opt`"))
.success();
}

Expand Down

0 comments on commit 4e6d586

Please sign in to comment.