Giter Club home page Giter Club logo

wabt-rs's Introduction

WABT bindings for Rust

crates.io docs.rs

Rust bindings for WABT.

Usage

Add this to your Cargo.toml:

[dependencies]
wabt = "0.9.0"

Use cases

Assemble a given program in WebAssembly text format (aka wat) and translate it into binary.

extern crate wabt;
use wabt::wat2wasm;

fn main() {
    assert_eq!(
        wat2wasm("(module)").unwrap(),
        &[
            0, 97, 115, 109, // \0ASM - magic
            1, 0, 0, 0       //  0x01 - version
        ]
    );
}

or disassemble a wasm binary into the text format.

extern crate wabt;
use wabt::wasm2wat;
fn main() {
    assert_eq!(
        wasm2wat(&[
            0, 97, 115, 109, // \0ASM - magic
            1, 0, 0, 0       //    01 - version
        ]),
        Ok("(module)\n".to_owned()),
    );
}

wabt can be also used for parsing the official testsuite scripts.

use wabt::script::{ScriptParser, Command, CommandKind, Action, Value};

let wast = r#"
;; Define anonymous module with function export named `sub`.
(module
  (func (export "sub") (param $x i32) (param $y i32) (result i32)
    ;; return x - y;
    (i32.sub
      (get_local $x) (get_local $y)
    )
  )
)

;; Assert that invoking export `sub` with parameters (8, 3)
;; should return 5.
(assert_return
  (invoke "sub"
    (i32.const 8) (i32.const 3)
  )
  (i32.const 5)
)
"#;

let mut parser = ScriptParser::<f32, f64>::from_str(wast)?;
while let Some(Command { kind, .. }) = parser.next()? {
    match kind {
        CommandKind::Module { module, name } => {
            // The module is declared as anonymous.
            assert_eq!(name, None);

            // Convert the module into the binary representation and check the magic number.
            let module_binary = module.into_vec();
            assert_eq!(&module_binary[0..4], &[0, 97, 115, 109]);
        }
        CommandKind::AssertReturn { action, expected } => {
            assert_eq!(action, Action::Invoke {
                module: None,
                field: "sub".to_string(),
                args: vec![
                    Value::I32(8),
                    Value::I32(3)
                ],
            });
            assert_eq!(expected, vec![Value::I32(5)]);
        },
        _ => panic!("there are no other commands apart from that defined above"),
    }
}

Alternatives

You might find wat or wast crate useful if you only want to parse .wat or .wast source. The advantage of using them is that they are implemented completely in Rust. Moreover, wast among other things allows you to add your own extensions to WebAssembly text format.

For print the text representation of a wasm binary, wasmprinter can work better for you, since it is implemented completely in Rust.

wabt-rs's People

Contributors

abrown avatar acfoltzer avatar awortman-fastly avatar axic avatar bors[bot] avatar dependabot-preview[bot] avatar eira-fransham avatar igrep avatar kimundi avatar kogai avatar nlewycky avatar nwtgck avatar pepyakin avatar sunfishcode avatar waywardmonkeys avatar xmclark avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

wabt-rs's Issues

AssertUninstantiable ParseError

I unexpectedly saw AssertUninstantiable while parsing wast files that do not contain assert_uninstantiable.

Expected:

$ cargo run
in AssertTrap

Actual:

$ cargo run
in AssertUninstantiable

Example:

use wabt::script::{Action, Command, CommandKind, Error, ScriptParser, Value};

fn main() -> Result<(), wabt::script::Error> {
    let wast = r#"
(assert_trap
  (module (func $main (unreachable)) (start $main))
  "unreachable"
)
"#;

    let mut parser: ScriptParser = ScriptParser::from_str(wast)?;
    while let Some(Command { kind, .. }) = parser.next()? {
        match kind {
            CommandKind::Module { module, name } => {
                println!("in Module");
            },
            CommandKind::AssertReturn { action, expected } => {
                println!("in AssertReturn");
            },
            CommandKind::AssertTrap { action, message: _ } => {
                println!("in AssertTrap");
            },
            CommandKind::AssertUninstantiable {module: _, message: _,} => {
                 println!("in AssertUninstantiable");
            },
            _ => panic!("there are no other commands apart from that defined above"),
        }
    }
    Ok(())
}

Python is an undocumented build dependency

Is this intentional?

$ cargo build > /dev/null
   Compiling wabt-sys v0.5.3 (/home/michi/projects/wabt-rs/wabt-sys)                                                                                           
error: failed to run custom build command for `wabt-sys v0.5.3 (/home/michi/projects/wabt-rs/wabt-sys)`                                                        
process didn't exit successfully: `/home/michi/projects/wabt-rs/target/debug/build/wabt-sys-2d6c1600125d0201/build-script-build` (exit code: 101)
--- stdout
running: "cmake" "/home/michi/projects/wabt-rs/wabt-sys/wabt" "-DBUILD_TESTS=OFF" "-DBUILD_TOOLS=OFF" "-DCMAKE_INSTALL_PREFIX=/home/michi/projects/wabt-rs/target/debug/build/wabt-sys-cbde6678bb51aab5/out" "-DCMAKE_C_FLAGS= -ffunction-sections -fdata-sections -fPIC -m64" "-DCMAKE_C_COMPILER=/bin/cc" "-DCMAKE_CXX_FLAGS= -ffunction-sections -fdata-sections -fPIC -m64" "-DCMAKE_CXX_COMPILER=/bin/c++" "-DCMAKE_BUILD_TYPE=Debug"
-- Using prebuilt re2c lexer
-- Configuring incomplete, errors occurred!
See also "/home/michi/projects/wabt-rs/target/debug/build/wabt-sys-cbde6678bb51aab5/out/build/CMakeFiles/CMakeOutput.log".
See also "/home/michi/projects/wabt-rs/target/debug/build/wabt-sys-cbde6678bb51aab5/out/build/CMakeFiles/CMakeError.log".

--- stderr
CMake Error at /usr/share/cmake-3.13/Modules/FindPackageHandleStandardArgs.cmake:137 (message):
  Could NOT find PythonInterp (missing: PYTHON_EXECUTABLE) (Required is at
  least version "2.7")
Call Stack (most recent call first):
  /usr/share/cmake-3.13/Modules/FindPackageHandleStandardArgs.cmake:378 (_FPHSA_FAILURE_MESSAGE)
  /usr/share/cmake-3.13/Modules/FindPythonInterp.cmake:159 (FIND_PACKAGE_HANDLE_STANDARD_ARGS)
  CMakeLists.txt:443 (find_package)


thread 'main' panicked at '
command did not execute successfully, got: exit code: 1

build script failed, must exit now', /home/michi/.cargo/registry/src/github.com-1ecc6299db9ec823/cmake-0.1.35/src/lib.rs:778:5
note: Run with `RUST_BACKTRACE=1` for a backtrace.

Unable to build master branch

$ cargo build
    Updating crates.io index
   Compiling proc-macro2 v1.0.21
   Compiling cc v1.0.60
   Compiling unicode-xid v0.2.1
   Compiling ryu v1.0.5
   Compiling serde v1.0.116
   Compiling syn v1.0.41
   Compiling serde_derive v1.0.116
   Compiling serde_json v1.0.57
   Compiling itoa v0.4.6
   Compiling cmake v0.1.44
   Compiling quote v1.0.7
   Compiling wabt-sys v0.7.1 (/home/omer/rust/wabt-rs/wabt-sys)
error: failed to run custom build command for `wabt-sys v0.7.1 (/home/omer/rust/wabt-rs/wabt-sys)`

Caused by:
  process didn't exit successfully: `/home/omer/rust/wabt-rs/target/debug/build/wabt-sys-23a181636fa2ebea/build-script-build` (exit code: 101)
  --- stdout
  cargo:rerun-if-env-changed=WABT_CXXSTDLIB
  cargo:rerun-if-env-changed=CXXSTDLIB
  running: "cmake" "/home/omer/rust/wabt-rs/wabt-sys/wabt" "-DBUILD_TESTS=OFF" "-DBUILD_TOOLS=OFF" "-DCMAKE_INSTALL_PREFIX=/home/omer/rust/wabt-rs/target/debug/build/wabt-sys-c311a52f1621dc69/out" "-DCMAKE_C_FLAGS= -ffunction-sections -fdata-sections -fPIC -m64" "-DCMAKE_C_COMPILER=/usr/bin/cc" "-DCMAKE_CXX_FLAGS= -ffunction-sections -fdata-sections -fPIC -m64" "-DCMAKE_CXX_COMPILER=/usr/bin/c++" "-DCMAKE_ASM_FLAGS= -ffunction-sections -fdata-sections -fPIC -m64" "-DCMAKE_ASM_COMPILER=/usr/bin/cc" "-DCMAKE_BUILD_TYPE=Debug"

  --- stderr
  CMake Error: The source directory "/home/omer/rust/wabt-rs/wabt-sys/wabt" does not appear to contain CMakeLists.txt.
  Specify --help for usage, or press the help button on the CMake GUI.
  thread 'main' panicked at '
  command did not execute successfully, got: exit code: 1

  build script failed, must exit now', /home/omer/.cargo/registry/src/github.com-1ecc6299db9ec823/cmake-0.1.44/src/lib.rs:885:5
  note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
warning: build failed, waiting for other jobs to finish...
error: build failed

I can install wabt from the source so I think this isn't a missing dependency/tool problem.

Wabt 0.3.0 does not compile on macOS.

When compiling cranelift which just added wabt I get the following error.

 Updating registry `https://github.com/rust-lang/crates.io-index`
 Downloading wabt v0.5.0
 Downloading wabt-sys v0.3.0
   Compiling ryu v0.2.6
   Compiling cranelift-codegen-meta v0.20.0 (file:///Users/aep/src/rust/cranelift/lib/codegen/meta)
   Compiling cranelift-entity v0.20.1 (file:///Users/aep/src/rust/cranelift/lib/entity)
   Compiling wabt-sys v0.3.0
   Compiling serde_derive v1.0.75
error[E0599]: no method named `no_build_target` found for type `&mut cmake::Config` in the current scope
  --> /Users/aep/.cargo/registry/src/github.com-1ecc6299db9ec823/wabt-sys-0.3.0/build.rs:17:10
   |
17 |         .no_build_target(true)
   |          ^^^^^^^^^^^^^^^
   |
   = help: did you mean `build_target`?

error: aborting due to previous error

For more information about this error, try `rustc --explain E0599`.
error: Could not compile `wabt-sys`.
warning: build failed, waiting for other jobs to finish...
error: build failed

Version

rustc 1.28.0 (9634041f0 2018-07-30)
binary: rustc
commit-hash: 9634041f0e8c0f3191d2867311276f19d0a42564
commit-date: 2018-07-30
host: x86_64-apple-darwin
release: 1.28.0
LLVM version: 6.0

Wabt 0.9.2 yanked

Hello Sergei,

Just out of curiosity, why was wabt 0.9.2 yanked from crates.io? I'm wondering whether I need to update to 10, with the possible breaking changes that might entail. If it's just a question of deprecation, I can chill out, if there is some deep security flaw or nasty bug I might have to sit up and do something. 0.9.1 hasn't been yanked. Is rolling back a safe option?

Best wishes, Max

Compilation on Windows with msvc

Hi. I noticed a problem when compiling on windows (10) with stable-x86_64-pc-windows-msvc. Cmake works on wabt, but rustc fails during rustc --crate-name wabt_sys ..... It cannot link to wabt.lib since the file is not in the corresponding folder target\debug\build\wabt-sys-....\out where there is wabtshim.lib. After copying it manually there from target\debug\build\wabt-sys...\out\build\Debug, the compilation works. Looks like a -L is missing or the path is somehow incorrect.

Add travis

We need to add travis CI testing to this repo to ensure everything builds correctly

Build error due to GCC 8.0 warning

Checking out git tag 0.3.0 and doing a local build results in this:

> cargo build
   Compiling tempdir v0.3.7
   Compiling wabt-sys v0.1.4 (file:///home/marvin/dev/rust/wasm/wabt-rs/wabt-sys)
   Compiling serde_json v1.0.19
   Compiling serde_derive v1.0.66
error: failed to run custom build command for `wabt-sys v0.1.4 (file:///home/marvin/dev/rust/wasm/wabt-rs/wabt-sys)`
process didn't exit successfully: `/home/marvin/dev/rust/wasm/wabt-rs/target/debug/build/wabt-sys-08efe8949d9c6dab/build-script-build` (exit code: 101)
--- stdout
running: "cmake" "/home/marvin/dev/rust/wasm/wabt-rs/wabt-sys/wabt" "-DBUILD_TESTS=OFF" "-DCMAKE_INSTALL_PREFIX=/home/marvin/dev/rust/wasm/wabt-rs/target/debug/build/wabt-sys-a8dd70a1b2be33af/out" "-DCMAKE_C_FLAGS= -ffunction-sections -fdata-sections -fPIC -m64" "-DCMAKE_C_COMPILER=/usr/lib/ccache/bin/cc" "-DCMAKE_CXX_FLAGS= -ffunction-sections -fdata-sections -fPIC -m64" "-DCMAKE_CXX_COMPILER=/usr/lib/ccache/bin/c++" "-DCMAKE_BUILD_TYPE=Debug"

--- stderr
CMake Error: The source directory "/home/marvin/dev/rust/wasm/wabt-rs/wabt-sys/wabt" does not appear to contain CMakeLists.txt.
Specify --help for usage, or press the help button on the CMake GUI.
thread 'main' panicked at '
command did not execute successfully, got: exit code: 1

build script failed, must exit now', /home/marvin/.cargo/registry/src/github.com-1ecc6299db9ec823/cmake-0.1.31/src/lib.rs:643:5
note: Run with `RUST_BACKTRACE=1` for a backtrace.

warning: build failed, waiting for other jobs to finish...
error: build failed

I actually discovered this with the nanowasm crate, which depends on wabt, where the error message seems somewhat more useful:

> cargo build
   Compiling wabt-sys v0.1.4
error: failed to run custom build command for `wabt-sys v0.1.4`
process didn't exit successfully: `/home/marvin/dev/rust/wasm/nanowasm/target/debug/build/wabt-sys-e49b86f7f525a8f8/build-script-build` (exit code: 101)
--- stdout
running: "cmake" "/home/marvin/.cargo/registry/src/github.com-1ecc6299db9ec823/wabt-sys-0.1.4/wabt" "-DBUILD_TESTS=OFF" "-DCMAKE_INSTALL_PREFIX=/home/marvin/dev/rust/wasm/nanowasm/target/debug/build/wabt-sys-b7286d542fed26ff/out" "-DCMAKE_C_FLAGS= -ffunction-sections -fdata-sections -fPIC -m64" "-DCMAKE_C_COMPILER=/usr/lib/ccache/bin/cc" "-DCMAKE_CXX_FLAGS= -ffunction-sections -fdata-sections -fPIC -m64" "-DCMAKE_CXX_COMPILER=/usr/lib/ccache/bin/c++" "-DCMAKE_BUILD_TYPE=Debug"
-- Using prebuilt re2c lexer
-- Configuring done
-- Generating done
-- Build files have been written to: /home/marvin/dev/rust/wasm/nanowasm/target/debug/build/wabt-sys-b7286d542fed26ff/out/build
running: "cmake" "--build" "." "--target" "install" "--config" "Debug" "--"
[ 60%] Built target libwabt
[ 69%] Building CXX object CMakeFiles/wasm-interp.dir/src/tools/wasm-interp.cc.o
[ 69%] Built target wast2json
[ 69%] Building CXX object CMakeFiles/spectest-interp.dir/src/tools/spectest-interp.cc.o
[ 69%] Built target wat-desugar
Scanning dependencies of target wat2wasm
Scanning dependencies of target wasm-validate
[ 70%] Building CXX object CMakeFiles/wasm-validate.dir/src/tools/wasm-validate.cc.o
[ 72%] Building CXX object CMakeFiles/wat2wasm.dir/src/tools/wat2wasm.cc.o
[ 73%] Linking CXX executable wasm-validate
[ 75%] Linking CXX executable wat2wasm
[ 75%] Built target wasm-validate
[ 75%] Built target wat2wasm

--- stderr
/home/marvin/.cargo/registry/src/github.com-1ecc6299db9ec823/wabt-sys-0.1.4/wabt/src/tools/wasm-interp.cc: In static member function ‘static wabt::interp::Result WasmInterpHostImportDelegate::PrintCallback(const wabt::interp::HostFunc*, const wabt::interp::FuncSignature*, wabt::Index, wabt::interp::TypedValue*, wabt::Index, wabt::interp::TypedValue*, void*)’:
/home/marvin/.cargo/registry/src/github.com-1ecc6299db9ec823/wabt-sys-0.1.4/wabt/src/tools/wasm-interp.cc:203:60: error: ‘void* memset(void*, int, size_t)’ clearing an object of non-trivial type ‘struct wabt::interp::TypedValue’; use assignment or value-initialization instead [-Werror=class-memaccess]
     memset(out_results, 0, sizeof(TypedValue) * num_results);
                                                            ^
In file included from /home/marvin/.cargo/registry/src/github.com-1ecc6299db9ec823/wabt-sys-0.1.4/wabt/src/tools/wasm-interp.cc:31:
/home/marvin/.cargo/registry/src/github.com-1ecc6299db9ec823/wabt-sys-0.1.4/wabt/src/interp.h:148:8: note: ‘struct wabt::interp::TypedValue’ declared here
 struct TypedValue {
        ^~~~~~~~~~
cc1plus: all warnings being treated as errors
make[2]: *** [CMakeFiles/wasm-interp.dir/build.make:63: CMakeFiles/wasm-interp.dir/src/tools/wasm-interp.cc.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:216: CMakeFiles/wasm-interp.dir/all] Error 2
make[1]: *** Waiting for unfinished jobs....
/home/marvin/.cargo/registry/src/github.com-1ecc6299db9ec823/wabt-sys-0.1.4/wabt/src/tools/spectest-interp.cc: In function ‘wabt::interp::Result spectest::DefaultHostCallback(const wabt::interp::HostFunc*, const wabt::interp::FuncSignature*, wabt::Index, wabt::interp::TypedValue*, wabt::Index, wabt::interp::TypedValue*, void*)’:
/home/marvin/.cargo/registry/src/github.com-1ecc6299db9ec823/wabt-sys-0.1.4/wabt/src/tools/spectest-interp.cc:828:58: error: ‘void* memset(void*, int, size_t)’ clearing an object of non-trivial type ‘struct wabt::interp::TypedValue’; use assignment or value-initialization instead [-Werror=class-memaccess]
   memset(out_results, 0, sizeof(TypedValue) * num_results);
                                                          ^
In file included from /home/marvin/.cargo/registry/src/github.com-1ecc6299db9ec823/wabt-sys-0.1.4/wabt/src/tools/spectest-interp.cc:31:
/home/marvin/.cargo/registry/src/github.com-1ecc6299db9ec823/wabt-sys-0.1.4/wabt/src/interp.h:148:8: note: ‘struct wabt::interp::TypedValue’ declared here
 struct TypedValue {
        ^~~~~~~~~~
cc1plus: all warnings being treated as errors
make[2]: *** [CMakeFiles/spectest-interp.dir/build.make:63: CMakeFiles/spectest-interp.dir/src/tools/spectest-interp.cc.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:142: CMakeFiles/spectest-interp.dir/all] Error 2
make: *** [Makefile:130: all] Error 2
thread 'main' panicked at '
command did not execute successfully, got: exit code: 2

build script failed, must exit now', /home/marvin/.cargo/registry/src/github.com-1ecc6299db9ec823/cmake-0.1.31/src/lib.rs:643:5
note: Run with `RUST_BACKTRACE=1` for a backtrace.

The error seems to originate in a new warning class-memaccess in GCC 8.0. (Which seems to cause a few issues in different projects: https://www.google.com/search?q=W%3Dclass-memaccess)

Expose the wabt interpreter API

This would be useful for some use cases since benchmarks show that wabt's speed currently is much better than any other interpreter.

Upgrade upstream wabt

It looks like wabt in https://github.com/pepyakin/wabt-rs/tree/master/wabt-sys is quite old now (9 months old), while upstream has gained many new features (e.g. parsing of NAN), changed defaults (e.g. multi-value and sign extension ops are now part of stable), changed some opcodes (e.g. recent SIMD renumbering) and more meanwhile.

Would it be possible to upgrade to the latest release and publish a new version of bindings?

Can't run script with path containing directores

This test program:

use wabt::script::ScriptParser;

fn main() {
    let filename = "dir/test.wast";
    let buffer = b"(module)";

    let mut parser = ScriptParser::<f32, f64>::from_source_and_name(buffer, filename).unwrap();

    while parser.next().expect("parser").is_some() {}
}

prints this:

thread 'main' panicked at 'Module referenced in JSON does not exist.', src/libcore/option.rs:1166:5

If I change the filename to just "test.wast", I get no error.

Supporting new wasm features.

The wabt implementations (conditionally) supports newer wasm features, like multi-value returns, threads, etc. Can wabt-rs be extended to allow support for those?

Parse Error in names.wast spec

I am getting a parse error for parts of the names.wast from the WebAssembly spec suite:
https://github.com/WebAssembly/spec/blob/master/test/core/names.wast

Error

$ RUST_BACKTRACE=1 cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.02s
     Running `target/debug/wabt_parse`
in Module
in AssertReturn
in AssertReturn
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: FromUtf8Error { bytes: [255], error: Utf8Error { valid_up_to: 0, error_len: Some(1) } }', src/libcore/result.rs:999:5
stack backtrace:
   0: std::sys::unix::backtrace::tracing::imp::unwind_backtrace
             at src/libstd/sys/unix/backtrace/tracing/gcc_s.rs:39
   1: std::sys_common::backtrace::_print
             at src/libstd/sys_common/backtrace.rs:71
   2: std::panicking::default_hook::{{closure}}
             at src/libstd/sys_common/backtrace.rs:59
             at src/libstd/panicking.rs:197
   3: std::panicking::default_hook
             at src/libstd/panicking.rs:211
   4: <std::panicking::begin_panic::PanicPayload<A> as core::panic::BoxMeUp>::get
             at src/libstd/panicking.rs:474
   5: std::panicking::continue_panic_fmt
             at src/libstd/panicking.rs:381
   6: std::panicking::try::do_call
             at src/libstd/panicking.rs:308
   7: <T as core::any::Any>::type_id
             at src/libcore/panicking.rs:85
   8: hashbrown::raw::bitmask::BitMask::invert
             at /rustc/a53f9df32fbb0b5f4382caaad8f1a46f36ea887c/src/libcore/macros.rs:18
   9: hashbrown::raw::bitmask::BitMask::invert
             at /rustc/a53f9df32fbb0b5f4382caaad8f1a46f36ea887c/src/libcore/result.rs:800
  10: core::ptr::swap_nonoverlapping_bytes
             at /Users/brandonfish/.cargo/registry/src/github.com-1ecc6299db9ec823/wabt-0.9.0/src/script/mod.rs:267
  11: wabt::script::parse_action
             at /Users/brandonfish/.cargo/registry/src/github.com-1ecc6299db9ec823/wabt-0.9.0/src/script/mod.rs:280
  12: wabt::script::ScriptParser<F32,F64>::next
             at /Users/brandonfish/.cargo/registry/src/github.com-1ecc6299db9ec823/wabt-0.9.0/src/script/mod.rs:530
  13: wabt_parse::main
             at src/main.rs:30
  14: std::rt::lang_start::{{closure}}
             at /rustc/a53f9df32fbb0b5f4382caaad8f1a46f36ea887c/src/libstd/rt.rs:64
  15: std::panicking::try::do_call
             at src/libstd/rt.rs:49
             at src/libstd/panicking.rs:293
  16: panic_unwind::dwarf::eh::read_encoded_pointer
             at src/libpanic_unwind/lib.rs:85
  17: <std::panicking::begin_panic::PanicPayload<A> as core::panic::BoxMeUp>::get
             at src/libstd/panicking.rs:272
             at src/libstd/panic.rs:394
             at src/libstd/rt.rs:48
  18: std::rt::lang_start
             at /rustc/a53f9df32fbb0b5f4382caaad8f1a46f36ea887c/src/libstd/rt.rs:64
  19: wabt_parse::main

Example:
Around lines: https://github.com/WebAssembly/spec/blob/a221f2574d7106e92cf8abaf05d5bb1131b19d76/test/core/names.wast#L58

use wabt::script::{Action, Command, CommandKind, Error, ScriptParser, Value};

fn main() -> Result<(), wabt::script::Error> {
    let wast = r#"
(module 
  ;; Test that names are case-sensitive.
  (func (export "a") (result i32) (i32.const 13))
  (func (export "A") (result i32) (i32.const 14))

  ;; Test that UTF-8 BOM code points can appear in identifiers.
  (func (export "") (result i32) (i32.const 15))

  ;; Test that Unicode normalization is not applied. These function names
  ;; contain different codepoints which normalize to the same thing under
  ;; NFC or NFD.
  (func (export "Å") (result i32) (i32.const 16))
  (func (export "Å") (result i32) (i32.const 17))
  (func (export "Å") (result i32) (i32.const 18))
)
 
(assert_return (invoke "a") (i32.const 13))
(assert_return (invoke "A") (i32.const 14))
(assert_return (invoke "") (i32.const 15))
(assert_return (invoke "Å") (i32.const 16))
(assert_return (invoke "Å") (i32.const 17))
(assert_return (invoke "Å") (i32.const 18))
"#;

    let mut parser: ScriptParser = ScriptParser::from_str(wast)?;
    while let Some(Command { kind, .. }) = parser.next()? {
        match kind {
            CommandKind::Module { module, name } => {
                println!("in Module");
            }
            CommandKind::AssertReturn { action, expected } => {
                println!("in AssertReturn");
            }
            _ => panic!("there are no other commands apart from that defined above"),
        }
    }
    Ok(())
}

Compiling to WebAssembly

Hey there! Is there an option to allow using this crate in a project aimed at the "wasm32-wasi" target?

As far as I can see, allowing this might require some tricks, but it seems like Wasmer guys already did it for their Wapm project, making a fork of wabt that supports WebAssembly compilation.

What do you think about this?

cross compilation fault to RISCV

Hi~ May I get some guidance on fixing this issue?

I was cross compiling wasmer to riscv using cargo

LLVM_SYS_100_PREFIX="/usr/local/llvm/" \
	cargo build --release $(backend_features) \
	--target riscv64gc-unknown-linux-gnu  -j8

with .cargo/config defining

[bulid]
target = "riscv64gc-unknown-linux-gnu"

[target.riscv64gc-unknown-linux-gnu]
linker = "/opt/riscv/bin/riscv64-unknown-linux-gnu-ld"

Then I got fault from wabt of version 0.7.2 like belowing

error: failed to run custom build command for `wabt-sys v0.7.2`

Caused by:
  process didn't exit successfully: `/home/chao/wasmer/target/release/build/wabt-sys-a3477b667f324396/build-script-build` (exit code: 101)
--- stdout
cargo:rerun-if-env-changed=WABT_CXXSTDLIB
cargo:rerun-if-env-changed=CXXSTDLIB
running: "cmake" "/home/chao/.cargo/registry/src/github.com-1ecc6299db9ec823/wabt-sys-0.7.2/wabt" "-DBUILD_TESTS=OFF" "-DBUILD_TOOLS=OFF" "-DCMAKE_INSTALL_PREFIX=/home/chao/wasmer/target/riscv64gc-unknown-linux-gnu/release/build/wabt-sys-9bc5fbaa32222f35/out" "-DCMAKE_C_FLAGS= -ffunction-sections -fdata-sections -fPIC -march=rv64gc -mabi=lp64d -mcmodel=medany" "-DCMAKE_C_COMPILER=/opt/riscv/bin/riscv64-linux-gnu-gcc" "-DCMAKE_CXX_FLAGS= -ffunction-sections -fdata-sections -fPIC -march=rv64gc -mabi=lp64d -mcmodel=medany" "-DCMAKE_CXX_COMPILER=/opt/riscv/bin/riscv64-linux-gnu-g++" "-DCMAKE_ASM_FLAGS= -ffunction-sections -fdata-sections -fPIC -march=rv64gc -mabi=lp64d -mcmodel=medany" "-DCMAKE_ASM_COMPILER=/opt/riscv/bin/riscv64-linux-gnu-gcc" "-DCMAKE_BUILD_TYPE=Release"
-- The C compiler identification is GNU 9.2.0
-- The CXX compiler identification is GNU 9.2.0
-- Check for working C compiler: /opt/riscv/bin/riscv64-linux-gnu-gcc
-- Check for working C compiler: /opt/riscv/bin/riscv64-linux-gnu-gcc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /opt/riscv/bin/riscv64-linux-gnu-g++
-- Check for working CXX compiler: /opt/riscv/bin/riscv64-linux-gnu-g++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Looking for alloca.h
-- Looking for alloca.h - found
-- Looking for unistd.h
-- Looking for unistd.h - found
-- Looking for snprintf
-- Looking for snprintf - found
-- Looking for strcasecmp
-- Looking for strcasecmp - found
-- Looking for sys/types.h
-- Looking for sys/types.h - found
-- Looking for stdint.h
-- Looking for stdint.h - found
-- Looking for stddef.h
-- Looking for stddef.h - found
-- Check size of ssize_t
-- Check size of ssize_t - done
-- Check size of size_t
-- Check size of size_t - done
-- Found PythonInterp: /usr/bin/python3 (found suitable version "3.6.9", minimum required is "3.5") 
-- Looking for pthread.h
-- Looking for pthread.h - found
-- Looking for pthread_create
-- Looking for pthread_create - not found
-- Looking for pthread_create in pthreads
-- Looking for pthread_create in pthreads - not found
-- Looking for pthread_create in pthread
-- Looking for pthread_create in pthread - found
-- Found Threads: TRUE  
-- Configuring done
-- Generating done
-- Build files have been written to: /home/chao/wasmer/target/riscv64gc-unknown-linux-gnu/release/build/wabt-sys-9bc5fbaa32222f35/out/build
running: "cmake" "--build" "." "--config" "Release" "--"
make[1]: Entering directory '/home/chao/wasmer/target/riscv64gc-unknown-linux-gnu/release/build/wabt-sys-9bc5fbaa32222f35/out/build'
make[2]: Entering directory '/home/chao/wasmer/target/riscv64gc-unknown-linux-gnu/release/build/wabt-sys-9bc5fbaa32222f35/out/build'
make[3]: Entering directory '/home/chao/wasmer/target/riscv64gc-unknown-linux-gnu/release/build/wabt-sys-9bc5fbaa32222f35/out/build'
Scanning dependencies of target wabt
make[3]: Leaving directory '/home/chao/wasmer/target/riscv64gc-unknown-linux-gnu/release/build/wabt-sys-9bc5fbaa32222f35/out/build'
make[3]: Entering directory '/home/chao/wasmer/target/riscv64gc-unknown-linux-gnu/release/build/wabt-sys-9bc5fbaa32222f35/out/build'
[  1%] Building CXX object CMakeFiles/wabt.dir/src/apply-names.cc.o
[  2%] Building CXX object CMakeFiles/wabt.dir/src/binary.cc.o
[  3%] Building CXX object CMakeFiles/wabt.dir/src/binary-reader.cc.o
[  4%] Building CXX object CMakeFiles/wabt.dir/src/binary-reader-ir.cc.o
[  5%] Building CXX object CMakeFiles/wabt.dir/src/binary-reader-logging.cc.o
[  6%] Building CXX object CMakeFiles/wabt.dir/src/binary-writer.cc.o
[  7%] Building CXX object CMakeFiles/wabt.dir/src/binary-writer-spec.cc.o
[  8%] Building CXX object CMakeFiles/wabt.dir/src/binding-hash.cc.o
[ 10%] Building CXX object CMakeFiles/wabt.dir/src/color.cc.o
[ 11%] Building CXX object CMakeFiles/wabt.dir/src/common.cc.o
[ 12%] Building CXX object CMakeFiles/wabt.dir/src/config.cc.o
[ 13%] Building CXX object CMakeFiles/wabt.dir/src/decompiler.cc.o
[ 14%] Building CXX object CMakeFiles/wabt.dir/src/error-formatter.cc.o
[ 15%] Building CXX object CMakeFiles/wabt.dir/src/expr-visitor.cc.o
[ 16%] Building CXX object CMakeFiles/wabt.dir/src/feature.cc.o
[ 17%] Building CXX object CMakeFiles/wabt.dir/src/filenames.cc.o
[ 19%] Building CXX object CMakeFiles/wabt.dir/src/generate-names.cc.o
[ 20%] Building CXX object CMakeFiles/wabt.dir/src/hash-util.cc.o
[ 21%] Building CXX object CMakeFiles/wabt.dir/src/ir.cc.o
[ 22%] Building CXX object CMakeFiles/wabt.dir/src/ir-util.cc.o
[ 23%] Building CXX object CMakeFiles/wabt.dir/src/leb128.cc.o
[ 24%] Building CXX object CMakeFiles/wabt.dir/src/lexer-source.cc.o
[ 25%] Building CXX object CMakeFiles/wabt.dir/src/lexer-source-line-finder.cc.o
[ 26%] Building CXX object CMakeFiles/wabt.dir/src/literal.cc.o
[ 28%] Building CXX object CMakeFiles/wabt.dir/src/opcode.cc.o
[ 29%] Building C object CMakeFiles/wabt.dir/src/opcode-code-table.c.o
[ 30%] Building CXX object CMakeFiles/wabt.dir/src/option-parser.cc.o
[ 31%] Building CXX object CMakeFiles/wabt.dir/src/resolve-names.cc.o
[ 32%] Building CXX object CMakeFiles/wabt.dir/src/shared-validator.cc.o
CMakeFiles/wabt.dir/build.make:686: recipe for target 'CMakeFiles/wabt.dir/src/option-parser.cc.o' failed
make[3]: Leaving directory '/home/chao/wasmer/target/riscv64gc-unknown-linux-gnu/release/build/wabt-sys-9bc5fbaa32222f35/out/build'
CMakeFiles/Makefile2:136: recipe for target 'CMakeFiles/wabt.dir/all' failed
make[2]: Leaving directory '/home/chao/wasmer/target/riscv64gc-unknown-linux-gnu/release/build/wabt-sys-9bc5fbaa32222f35/out/build'
Makefile:83: recipe for target 'all' failed
make[1]: Leaving directory '/home/chao/wasmer/target/riscv64gc-unknown-linux-gnu/release/build/wabt-sys-9bc5fbaa32222f35/out/build'

--- stderr
CMake Warning at CMakeLists.txt:174 (message):
  Unknown target architecture!


CMake Warning:
  Manually-specified variables were not used by the project:

    CMAKE_ASM_COMPILER
    CMAKE_ASM_FLAGS


/home/chao/.cargo/registry/src/github.com-1ecc6299db9ec823/wabt-sys-0.7.2/wabt/src/option-parser.cc: In lambda function:
/home/chao/.cargo/registry/src/github.com-1ecc6299db9ec823/wabt-sys-0.7.2/wabt/src/option-parser.cc:60:20: error: 'CMAKE_PROJECT_VERSION' was not declared in this scope
   60 |     printf("%s\n", CMAKE_PROJECT_VERSION);
      |                    ^~~~~~~~~~~~~~~~~~~~~
make[3]: *** [CMakeFiles/wabt.dir/src/option-parser.cc.o] Error 1
make[3]: *** Waiting for unfinished jobs....
make[2]: *** [CMakeFiles/wabt.dir/all] Error 2
make[1]: *** [all] Error 2
thread 'main' panicked at '
command did not execute successfully, got: exit code: 2

build script failed, must exit now', /home/chao/.cargo/registry/src/github.com-1ecc6299db9ec823/cmake-0.1.44/src/lib.rs:885:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

warning: build failed, waiting for other jobs to finish...
error: build failed
Makefile:333: recipe for target 'release' failed
make: *** [release] Error 101

Update the README to include spec test usecase

Recently, support of the parsing wast scripts (these scripts are used in current testsuite) is landed (#6) but this wasn't reflected in README.

This scripts might be useful to integrate the official spec testsuite into implementations of the wasm execution engines (such as wasmi) and for developing fine-grained tests of runtimes or/and if it isn't desired to use full fledged compilers.

wasm2wat doesn't validate input by default

By default wasm2wat only checks whether input module is malformed (i.e. incorrect size of a section, unexpected magic number or reserved byte isn't equal to 0), but doesn't validate a module (i.e. if module does an addition of i32 and f32 it is well formed module but not valid).

I think it is good to validate an input by default.
Users can opt-out with Wasm2Wat struct if they don't want to validate module.

specify `c++` from environment variable

Right now the wabt-rs build uses some heuristics to figure out what standard c++ library to include, and whether or not to link it statically:

fn get_cpp_stdlib() -> Option<String> {
env::var("TARGET").ok().and_then(|target| {
if target.contains("msvc") {
None
} else if target.contains("darwin") {
Some("c++".to_string())
} else if target.contains("freebsd") {
Some("c++".to_string())
} else if target.contains("musl") {
Some("static=stdc++".to_string())
} else {
Some("stdc++".to_string())
}
})

I'd love to be able to specify the dependency (and how it's linked) with an environment variable, much like openssl-sys does: https://docs.rs/openssl/0.10.25/openssl/#manual

(quoted)

A set of environment variables can be used to point openssl-sys towards an OpenSSL installation. They will override the automatic detection logic.

  • OPENSSL_DIR - If specified, the directory of an OpenSSL installation. The directory should contain lib and include subdirectories containing the libraries and headers respectively.
  • OPENSSL_LIB_DIR and OPENSSL_INCLUDE_DIR - If specified, the directories containing the OpenSSL libraries and headers respectively. This can be used if the OpenSSL installation is split in a nonstandard directory layout.
  • OPENSSL_STATIC - If set, the crate will statically link to OpenSSL rather than dynamically link.
  • OPENSSL_LIBS - If set, a :-separated list of library names to link to (e.g. ssl:crypto). This can be used if nonstandard library names were used for whatever reason.

Generate wasm dynamically?

Can you recommend a good way to generate wasm dynamically from an ast?

I want to make a language that produces an ast which I then want to compile into wasm. I don't want to use an existing language like C or Rust to statically compile it but I want to do it dynamically and as cleanly and directly as wat.

I could theoretically use my ast to generate wat and then run it through this api but I was hoping to skip the wat generation step. I was imagining that this library had a ast2wasm step but I don't think it does.

Do you have any recommendations on this approach before I go any further?

Build failed: build failed on mac M1 chip

Build failed: build failed on mac M1 chip
Build Env:
cargo 1.58.0-nightly (2e2a16e98 2021-11-08)
rustc 1.58.0-nightly (936238a92 2021-11-11)

Error msg
Compiling quote v1.0.10
Compiling wabt-sys v0.8.0 (/Users/jacksoom/programer/rust/tools/wabt-rs/wabt-sys)
Compiling serde_json v1.0.72
Compiling syn v1.0.82
Compiling serde_derive v1.0.130
Compiling wabt v0.10.0 (/Users/jacksoom/programer/rust/tools/wabt-rs)
error: failed to add native library /Users/jacksoom/programer/rust/tools/wabt-rs/target/debug/build/wabt-sys-161fabea683d9915/out/build/libwabt.a: file too small to be an archive

error: could not compile wabt-sys due to previous error
warning: build failed, waiting for other jobs to finish...
error: build failed

Reimplement wast scripts to use an external iteration?

#6 implements script parsing as an internal iteration via visitor.

I wondering, woundn't it be more useful to expose API as an external iterator.

I.e.

let script = parse_script(script_path)?;
loop {
  let cmd = script.next_cmd();
  match cmd {
    Command::DefineModule { .. } => {},
    Command::AssertTrap { .. } => {},
    Command::End => break,
    _ => {},
  }
}

This kind of setup have several advantages. It doesn't require us to wrap user errors into our Error and woundn't impose on user any particular way of error handling (i.e. user can choose to panic on a failure instead of returning Errors). Also, this setup doesn't require user to declare a struct and implement a trait for it, thus might make the code less verbose for the simple use-cases such as testing parsers.

I get an error when trying to compile on Mac M3

$ cargo test
   Compiling scrypto-schema v0.11.0 (https://github.com/radixdlt/radixdlt-scrypto?tag=v0.11.0#f9a4ef37)
   Compiling wabt-sys v0.8.0
The following warnings were emitted during compilation:

warning: [email protected]: xcrun: error: unable to lookup item 'PlatformVersion' from command line tools installation
warning: [email protected]: xcrun: error: unable to lookup item 'PlatformVersion' in SDK '/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk'
warning: [email protected]: xcrun: error: unable to lookup item 'PlatformVersion' from command line tools installation
warning: [email protected]: xcrun: error: unable to lookup item 'PlatformVersion' in SDK '/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk'
warning: [email protected]: macOS deployment target (10.7) too low, it will be increased
warning: [email protected]: xcrun: error: unable to lookup item 'PlatformVersion' from command line tools installation
warning: [email protected]: xcrun: error: unable to lookup item 'PlatformVersion' in SDK '/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk'

error: failed to run custom build command for `wabt-sys v0.8.0`

Caused by:
  process didn't exit successfully: `/Users/danicuki/dev/sandbox/radix/my-first-scrypto/target/debug/build/wabt-sys-74d5738d2db8a539/build-script-build` (exit status: 101)
  --- stdout
  cargo:rerun-if-env-changed=WABT_CXXSTDLIB
  cargo:rerun-if-env-changed=CXXSTDLIB
  CMAKE_TOOLCHAIN_FILE_x86_64-apple-darwin = None
  CMAKE_TOOLCHAIN_FILE_x86_64_apple_darwin = None
  HOST_CMAKE_TOOLCHAIN_FILE = None
  CMAKE_TOOLCHAIN_FILE = None
  CMAKE_GENERATOR_x86_64-apple-darwin = None
  CMAKE_GENERATOR_x86_64_apple_darwin = None
  HOST_CMAKE_GENERATOR = None
  CMAKE_GENERATOR = None
  cargo:warning=xcrun: error: unable to lookup item 'PlatformVersion' from command line tools installation
  cargo:warning=xcrun: error: unable to lookup item 'PlatformVersion' in SDK '/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk'
  cargo:warning=xcrun: error: unable to lookup item 'PlatformVersion' from command line tools installation
  cargo:warning=xcrun: error: unable to lookup item 'PlatformVersion' in SDK '/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk'
  cargo:warning=macOS deployment target (10.7) too low, it will be increased
  cargo:warning=xcrun: error: unable to lookup item 'PlatformVersion' from command line tools installation
  cargo:warning=xcrun: error: unable to lookup item 'PlatformVersion' in SDK '/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk'
  CMAKE_PREFIX_PATH_x86_64-apple-darwin = None
  CMAKE_PREFIX_PATH_x86_64_apple_darwin = None
  HOST_CMAKE_PREFIX_PATH = None
  CMAKE_PREFIX_PATH = None
  CMAKE_x86_64-apple-darwin = None
  CMAKE_x86_64_apple_darwin = None
  HOST_CMAKE = None
  CMAKE = None

  --- stderr
  /Users/danicuki/.cargo/registry/src/index.crates.io-6f17d22bba15001f/wabt-sys-0.8.0/wabt/src/option-parser.cc:60:20: error: use of undeclared identifier 'CMAKE_PROJECT_VERSION'
      printf("%s\n", CMAKE_PROJECT_VERSION);
                     ^
  1 error generated.
  make[2]: *** [CMakeFiles/wabt.dir/src/option-parser.cc.o] Error 1
  make[1]: *** [CMakeFiles/wabt.dir/all] Error 2
  make: *** [all] Error 2
  thread 'main' panicked at /Users/danicuki/.cargo/registry/src/index.crates.io-6f17d22bba15001f/cmake-0.1.50/src/lib.rs:1098:5:

  command did not execute successfully, got: exit status: 2

  build script failed, must exit now
  note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
warning: build failed, waiting for other jobs to finish...

Any idea what this issue can be? I am running on MacOS 14.2.1 on a MacBook Pro M3

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.