Merge branch 'master' into feature/improve-thread-safety-of-core-types

This commit is contained in:
Mark McCaskey
2020-07-09 13:57:58 -07:00
100 changed files with 1344 additions and 1127 deletions

View File

@@ -76,8 +76,7 @@ jobs:
target/*/.* target/*/.*
target/*/build target/*/build
target/*/deps target/*/deps
key: key: ${{ matrix.os }}-${{ hashFiles('Cargo.lock') }}
${{ matrix.os }}-${{ hashFiles('Cargo.lock') }}
restore-keys: | restore-keys: |
${{ matrix.os }}- ${{ matrix.os }}-
- name: Install LLVM (Windows) - name: Install LLVM (Windows)
@@ -123,3 +122,20 @@ jobs:
# TODO: build wapm # TODO: build wapm
# make build-wapm # make build-wapm
make package make package
audit:
name: Audit
env:
CARGO_AUDIT_VERSION: 0.12.0
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/cache@master
with:
path: ${{ runner.tool_cache }}/cargo-audit
key: cargo-audit-bin-${{ env.CARGO_AUDIT_VERSION }}
- run: |
echo "::add-path::${{ runner.tool_cache }}/cargo-audit/bin"
- run: |
cargo install cargo-audit --version ${{ env.CARGO_AUDIT_VERSION }} --root ${{ runner.tool_cache }}/cargo-audit
cargo audit

348
Cargo.lock generated
View File

@@ -8,24 +8,30 @@ checksum = "955f37ac58af2416bac687c8ab66a4ccba282229bd7422a28d2281a5e66a6116"
[[package]] [[package]]
name = "addr2line" name = "addr2line"
version = "0.12.1" version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a49806b9dadc843c61e7c97e72490ad7f7220ae249012fbda9ad0609457c0543" checksum = "1b6a2d3371669ab3ca9797670853d61402b03d0b4b9ebf33d677dfa720203072"
dependencies = [ dependencies = [
"gimli", "gimli 0.22.0",
] ]
[[package]] [[package]]
name = "ahash" name = "adler"
version = "0.3.5" version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f3e0bf23f51883cce372d5d5892211236856e4bb37fb942e1eb135ee0f146e3" checksum = "ccc9a9dd069569f212bc4330af9f17c4afb5e8ce185e83dbb14f1349dda18b10"
[[package]]
name = "ahash"
version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8fd72866655d1904d6b0997d0b07ba561047d070fbe29de039031c641b61217"
[[package]] [[package]]
name = "aho-corasick" name = "aho-corasick"
version = "0.7.10" version = "0.7.13"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8716408b8bc624ed7f65d223ddb9ac2d044c0547b6fa4b0d554f3a9540496ada" checksum = "043164d8ba5c4c3035fec9bbee8647c0261d788f3474306f93bb65901cae0e86"
dependencies = [ dependencies = [
"memchr", "memchr",
] ]
@@ -82,22 +88,23 @@ checksum = "f8aac770f1885fd7e387acedd76065302551364496e46b3dd00860b2f8359b9d"
[[package]] [[package]]
name = "backtrace" name = "backtrace"
version = "0.3.48" version = "0.3.50"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0df2f85c8a2abbe3b7d7e748052fdd9b76a0458fdeb16ad4223f5eca78c7c130" checksum = "46254cf2fdcdf1badb5934448c1bcbe046a56537b3987d96c51a7afc5d03f293"
dependencies = [ dependencies = [
"addr2line", "addr2line",
"cfg-if", "cfg-if",
"libc", "libc",
"object", "miniz_oxide",
"object 0.20.0",
"rustc-demangle", "rustc-demangle",
] ]
[[package]] [[package]]
name = "bincode" name = "bincode"
version = "1.2.1" version = "1.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5753e2a71534719bf3f4e57006c3a4f0d2c672a4b676eec84161f763eca87dbf" checksum = "f30d3a39baa26f9651f17b375061f3233dde33424a8b72b0dbe93a68a0bc896d"
dependencies = [ dependencies = [
"byteorder", "byteorder",
"serde", "serde",
@@ -198,8 +205,8 @@ dependencies = [
[[package]] [[package]]
name = "cbindgen" name = "cbindgen"
version = "0.14.2" version = "0.14.3"
source = "git+https://github.com/eqrion/cbindgen#bb00d1c4a8e53c56880586987f0e1512fb252b9a" source = "git+https://github.com/eqrion/cbindgen#cc2876f709808a52d132a5f84e53ca1964eb92db"
dependencies = [ dependencies = [
"clap", "clap",
"heck", "heck",
@@ -215,9 +222,9 @@ dependencies = [
[[package]] [[package]]
name = "cc" name = "cc"
version = "1.0.54" version = "1.0.57"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7bbb73db36c1246e9034e307d0fba23f9a2e251faa47ade70c1bd252220c8311" checksum = "0fde55d2a2bfaa4c9668bbc63f531fbdeee3ffe188f4662511ce2c22b3eedebe"
[[package]] [[package]]
name = "cexpr" name = "cexpr"
@@ -306,8 +313,8 @@ dependencies = [
"cranelift-codegen-meta", "cranelift-codegen-meta",
"cranelift-codegen-shared", "cranelift-codegen-shared",
"cranelift-entity", "cranelift-entity",
"gimli", "gimli 0.21.0",
"hashbrown", "hashbrown 0.7.2",
"log", "log",
"regalloc", "regalloc",
"serde", "serde",
@@ -348,7 +355,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f6fe1d3e968576f4b60d23f40ee90281f8de2cdf23d2110f3b0296ff420555e" checksum = "0f6fe1d3e968576f4b60d23f40ee90281f8de2cdf23d2110f3b0296ff420555e"
dependencies = [ dependencies = [
"cranelift-codegen", "cranelift-codegen",
"hashbrown", "hashbrown 0.7.2",
"log", "log",
"smallvec", "smallvec",
"target-lexicon", "target-lexicon",
@@ -365,9 +372,9 @@ dependencies = [
[[package]] [[package]]
name = "criterion" name = "criterion"
version = "0.3.2" version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63f696897c88b57f4ffe3c69d8e1a0613c7d0e6c4833363c8560fbde9c47b966" checksum = "70daa7ceec6cf143990669a04c7df13391d55fb27bd4079d252fca774ba244d8"
dependencies = [ dependencies = [
"atty", "atty",
"cast", "cast",
@@ -382,6 +389,7 @@ dependencies = [
"rayon", "rayon",
"regex", "regex",
"serde", "serde",
"serde_cbor",
"serde_derive", "serde_derive",
"serde_json", "serde_json",
"tinytemplate", "tinytemplate",
@@ -390,9 +398,9 @@ dependencies = [
[[package]] [[package]]
name = "criterion-plot" name = "criterion-plot"
version = "0.4.2" version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ddeaf7989f00f2e1d871a26a110f3ed713632feac17f65f03ca938c542618b60" checksum = "e022feadec601fba1649cfa83586381a4ad31c6bf3a9ab7d408118b05dd9889d"
dependencies = [ dependencies = [
"cast", "cast",
"itertools", "itertools",
@@ -426,12 +434,13 @@ dependencies = [
[[package]] [[package]]
name = "crossbeam-queue" name = "crossbeam-queue"
version = "0.2.2" version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ab6bffe714b6bb07e42f201352c34f51fefd355ace793f9e638ebd52d23f98d2" checksum = "774ba60a54c213d409d5353bda12d49cd68d14e45036a285234c8d6f91f92570"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"crossbeam-utils", "crossbeam-utils",
"maybe-uninit",
] ]
[[package]] [[package]]
@@ -479,9 +488,9 @@ dependencies = [
[[package]] [[package]]
name = "ctor" name = "ctor"
version = "0.1.14" version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf6b25ee9ac1995c54d7adb2eff8cfffb7260bc774fb63c601ec65467f43cd9d" checksum = "39858aa5bac06462d4dd4b9164848eb81ffc4aa5c479746393598fd193afa227"
dependencies = [ dependencies = [
"quote", "quote",
"syn", "syn",
@@ -548,9 +557,9 @@ dependencies = [
[[package]] [[package]]
name = "downcast-rs" name = "downcast-rs"
version = "1.1.1" version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52ba6eb47c2131e784a38b726eb54c1e1484904f013e576a25354d0124161af6" checksum = "9ea835d29036a4087793836fa931b08837ad5e957da9e23886b29586fb9b6650"
[[package]] [[package]]
name = "dynasm" name = "dynasm"
@@ -620,9 +629,9 @@ dependencies = [
[[package]] [[package]]
name = "erased-serde" name = "erased-serde"
version = "0.3.11" version = "0.3.12"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d88b6d1705e16a4d62e05ea61cc0496c2bd190f4fa8e5c1f11ce747be6bcf3d1" checksum = "6ca8b296792113e1500fd935ae487be6e00ce318952a6880555554824d6ebf38"
dependencies = [ dependencies = [
"serde", "serde",
] ]
@@ -677,9 +686,9 @@ dependencies = [
[[package]] [[package]]
name = "ghost" name = "ghost"
version = "0.1.1" version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a36606a68532b5640dc86bb1f33c64b45c4682aad4c50f3937b317ea387f3d6" checksum = "1a5bcf1bbeab73aa4cf2fde60a846858dc036163c7c33bec309f8d17de785479"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@@ -697,6 +706,12 @@ dependencies = [
"stable_deref_trait", "stable_deref_trait",
] ]
[[package]]
name = "gimli"
version = "0.22.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aaf91faf136cb47367fa430cd46e37a788775e7fa104f8b4bcb3861dc389b724"
[[package]] [[package]]
name = "glob" name = "glob"
version = "0.3.0" version = "0.3.0"
@@ -714,6 +729,12 @@ dependencies = [
"scroll", "scroll",
] ]
[[package]]
name = "half"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d36fab90f82edc3c747f9d438e06cf0a491055896f2a279638bb5beed6c40177"
[[package]] [[package]]
name = "hashbrown" name = "hashbrown"
version = "0.7.2" version = "0.7.2"
@@ -724,6 +745,16 @@ dependencies = [
"autocfg 1.0.0", "autocfg 1.0.0",
] ]
[[package]]
name = "hashbrown"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ab9b7860757ce258c89fd48d28b68c41713e597a7b09e793f6c6a6e2ea37c827"
dependencies = [
"ahash",
"autocfg 1.0.0",
]
[[package]] [[package]]
name = "heck" name = "heck"
version = "0.3.1" version = "0.3.1"
@@ -735,9 +766,9 @@ dependencies = [
[[package]] [[package]]
name = "hermit-abi" name = "hermit-abi"
version = "0.1.13" version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91780f809e750b0a89f5544be56617ff6b1227ee485bcb06ebe10cdf89bd3b71" checksum = "3deed196b6e7f9e44a2ae8d94225d80302d81208b1bb673fd21fe634645c85a9"
dependencies = [ dependencies = [
"libc", "libc",
] ]
@@ -765,9 +796,9 @@ checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
[[package]] [[package]]
name = "indexmap" name = "indexmap"
version = "1.3.2" version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "076f042c5b7b98f31d205f1249267e12a6518c1481e9dae9764af19b707d2292" checksum = "c398b2b113b55809ceb9ee3e753fcbac793f1956663f3c36549c1346015c2afe"
dependencies = [ dependencies = [
"autocfg 1.0.0", "autocfg 1.0.0",
"serde", "serde",
@@ -799,9 +830,9 @@ dependencies = [
[[package]] [[package]]
name = "inventory" name = "inventory"
version = "0.1.6" version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "82d3f4b90287725c97b17478c60dda0c6324e7c84ee1ed72fb9179d0fdf13956" checksum = "621b50c176968fd3b0bd71f821a28a0ea98db2b5aea966b2fbb8bd1b7d310328"
dependencies = [ dependencies = [
"ctor", "ctor",
"ghost", "ghost",
@@ -810,9 +841,9 @@ dependencies = [
[[package]] [[package]]
name = "inventory-impl" name = "inventory-impl"
version = "0.1.6" version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9092a4fefc9d503e9287ef137f03180a6e7d1b04c419563171ee14947c5e80ec" checksum = "f99a4111304bade76468d05beab3487c226e4fe4c4de1c4e8f006e815762db73"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@@ -830,15 +861,15 @@ dependencies = [
[[package]] [[package]]
name = "itoa" name = "itoa"
version = "0.4.5" version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8b7a7c0c47db5545ed3fef7468ee7bb5b74691498139e4b3f6a20685dc6dd8e" checksum = "dc6f3ad7b9d11a0c00842ff8de1b60ee58661048eb8049ed33c73594f359d7e6"
[[package]] [[package]]
name = "js-sys" name = "js-sys"
version = "0.3.40" version = "0.3.41"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce10c23ad2ea25ceca0093bd3192229da4c5b3c0f2de499c1ecac0d98d452177" checksum = "c4b9172132a62451e56142bff9afc91c8e4a4500aa5b847da36815b63bfda916"
dependencies = [ dependencies = [
"wasm-bindgen", "wasm-bindgen",
] ]
@@ -863,9 +894,9 @@ checksum = "3576a87f2ba00f6f106fdfcd16db1d698d648a26ad8e0573cad8537c3c362d2a"
[[package]] [[package]]
name = "libc" name = "libc"
version = "0.2.71" version = "0.2.72"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9457b06509d27052635f90d6466700c65095fdf75409b3fbdd903e988b886f49" checksum = "a9f8082297d534141b30c8d39e9b1773713ab50fdbe4ff30f750d063b3bfd701"
[[package]] [[package]]
name = "libffi" name = "libffi"
@@ -979,9 +1010,9 @@ dependencies = [
[[package]] [[package]]
name = "memoffset" name = "memoffset"
version = "0.5.4" version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4fc2c02a7e374099d4ee95a193111f72d2110197fe200272371758f6c3643d8" checksum = "c198b026e1bbf08a937e94c6c60f9ec4a2267f5b0d2eec9c1b21b061ce2be55f"
dependencies = [ dependencies = [
"autocfg 1.0.0", "autocfg 1.0.0",
] ]
@@ -1007,6 +1038,15 @@ dependencies = [
"xkbcommon-sys", "xkbcommon-sys",
] ]
[[package]]
name = "miniz_oxide"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be0f75932c1f6cfae3c04000e40114adf955636e19040f9c0a2c380702aa1c7f"
dependencies = [
"adler",
]
[[package]] [[package]]
name = "more-asserts" name = "more-asserts"
version = "0.2.1" version = "0.2.1"
@@ -1049,9 +1089,9 @@ dependencies = [
[[package]] [[package]]
name = "num-integer" name = "num-integer"
version = "0.1.42" version = "0.1.43"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f6ea62e9d81a77cd3ee9a2a5b9b609447857f3d358704331e4ef39eb247fcba" checksum = "8d59457e662d541ba17869cf51cf177c0b5f0cbf476c66bdc90bf1edac4f875b"
dependencies = [ dependencies = [
"autocfg 1.0.0", "autocfg 1.0.0",
"num-traits", "num-traits",
@@ -1059,9 +1099,9 @@ dependencies = [
[[package]] [[package]]
name = "num-iter" name = "num-iter"
version = "0.1.40" version = "0.1.41"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfb0800a0291891dd9f4fe7bd9c19384f98f7fbe0cd0f39a2c6b88b9868bbc00" checksum = "7a6e6b7c748f995c4c29c5f5ae0248536e04a5739927c74ec0fa564805094b9f"
dependencies = [ dependencies = [
"autocfg 1.0.0", "autocfg 1.0.0",
"num-integer", "num-integer",
@@ -1070,9 +1110,9 @@ dependencies = [
[[package]] [[package]]
name = "num-traits" name = "num-traits"
version = "0.2.11" version = "0.2.12"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c62be47e61d1842b9170f0fdeec8eba98e60e90e5446449a0545e5152acd7096" checksum = "ac267bcc07f48ee5f8935ab0d24f316fb722d7a1292e2913f0cc196b29ffd611"
dependencies = [ dependencies = [
"autocfg 1.0.0", "autocfg 1.0.0",
] ]
@@ -1097,6 +1137,12 @@ dependencies = [
"indexmap", "indexmap",
] ]
[[package]]
name = "object"
version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ab52be62400ca80aa00285d25253d7f7c437b7375c4de678f5405d3afe82ca5"
[[package]] [[package]]
name = "once_cell" name = "once_cell"
version = "1.4.0" version = "1.4.0"
@@ -1105,9 +1151,9 @@ checksum = "0b631f7e854af39a1739f401cf34a8a013dfe09eac4fa4dba91e9768bd28168d"
[[package]] [[package]]
name = "oorandom" name = "oorandom"
version = "11.1.1" version = "11.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94af325bc33c7f60191be4e2c984d48aaa21e2854f473b85398344b60c9b6358" checksum = "a170cebd8021a008ea92e4db85a72f80b35df514ec664b296fdcbb654eac0b2c"
[[package]] [[package]]
name = "orbclient" name = "orbclient"
@@ -1154,9 +1200,9 @@ dependencies = [
[[package]] [[package]]
name = "paste" name = "paste"
version = "0.1.15" version = "0.1.18"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d53181dcd37421c08d3b69f887784956674d09c3f9a47a04fece2b130a5b346b" checksum = "45ca20c77d80be666aef2b45486da86238fabe33e38306bd3118fe4af33fa880"
dependencies = [ dependencies = [
"paste-impl", "paste-impl",
"proc-macro-hack", "proc-macro-hack",
@@ -1164,14 +1210,11 @@ dependencies = [
[[package]] [[package]]
name = "paste-impl" name = "paste-impl"
version = "0.1.15" version = "0.1.18"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05ca490fa1c034a71412b4d1edcb904ec5a0981a4426c9eb2128c0fda7a68d17" checksum = "d95a7db200b97ef370c8e6de0088252f7e0dfff7d047a28528e47456c0fc98b6"
dependencies = [ dependencies = [
"proc-macro-hack", "proc-macro-hack",
"proc-macro2",
"quote",
"syn",
] ]
[[package]] [[package]]
@@ -1212,9 +1255,9 @@ checksum = "237a5ed80e274dbc66f86bd59c1e25edc039660be53194b5fe0a482e0f2612ea"
[[package]] [[package]]
name = "proc-macro-error" name = "proc-macro-error"
version = "1.0.2" version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98e9e4b82e0ef281812565ea4751049f1bdcdfccda7d3f459f2e138a40c08678" checksum = "fc175e9777c3116627248584e8f8b3e2987405cabe1c0adf7d1dd28f09dc7880"
dependencies = [ dependencies = [
"proc-macro-error-attr", "proc-macro-error-attr",
"proc-macro2", "proc-macro2",
@@ -1225,9 +1268,9 @@ dependencies = [
[[package]] [[package]]
name = "proc-macro-error-attr" name = "proc-macro-error-attr"
version = "1.0.2" version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f5444ead4e9935abd7f27dc51f7e852a0569ac888096d5ec2499470794e2e53" checksum = "3cc9795ca17eb581285ec44936da7fc2335a3f34f2ddd13118b6f4d515435c50"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@@ -1244,9 +1287,9 @@ checksum = "7e0456befd48169b9f13ef0f0ad46d492cf9d2dbb918bcf38e01eed4ce3ec5e4"
[[package]] [[package]]
name = "proc-macro2" name = "proc-macro2"
version = "1.0.17" version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1502d12e458c49a4c9cbff560d0fe0060c252bc29799ed94ca2ed4bb665a0101" checksum = "beae6331a816b1f65d04c45b078fd8e6c93e8071771f41b8163255bbd8d7c8fa"
dependencies = [ dependencies = [
"unicode-xid", "unicode-xid",
] ]
@@ -1259,9 +1302,9 @@ checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
[[package]] [[package]]
name = "quote" name = "quote"
version = "1.0.6" version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "54a21852a652ad6f610c9510194f398ff6f8692e334fd1145fed931f7fbe44ea" checksum = "aa563d17ecb180e500da1cfd2b028310ac758de548efdd203e18f283af693f37"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
] ]
@@ -1435,10 +1478,11 @@ dependencies = [
[[package]] [[package]]
name = "rayon" name = "rayon"
version = "1.3.0" version = "1.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db6ce3297f9c85e16621bb8cca38a06779ffc31bb8184e1be4bed2be4678a098" checksum = "62f02856753d04e03e26929f820d0a0a337ebe71f849801eea335d464b349080"
dependencies = [ dependencies = [
"autocfg 1.0.0",
"crossbeam-deque", "crossbeam-deque",
"either", "either",
"rayon-core", "rayon-core",
@@ -1446,9 +1490,9 @@ dependencies = [
[[package]] [[package]]
name = "rayon-core" name = "rayon-core"
version = "1.7.0" version = "1.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08a89b46efaf957e52b18062fb2f4660f8b8a4dde1807ca002690868ef2c85a9" checksum = "e92e15d89083484e11353891f1af602cc661426deb9564c298b270c726973280"
dependencies = [ dependencies = [
"crossbeam-deque", "crossbeam-deque",
"crossbeam-queue", "crossbeam-queue",
@@ -1530,9 +1574,9 @@ dependencies = [
[[package]] [[package]]
name = "remove_dir_all" name = "remove_dir_all"
version = "0.5.2" version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a83fa3702a688b9359eccba92d153ac33fd2e8462f9e0e3fdf155239ea7792e" checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7"
dependencies = [ dependencies = [
"winapi", "winapi",
] ]
@@ -1560,9 +1604,9 @@ dependencies = [
[[package]] [[package]]
name = "ryu" name = "ryu"
version = "1.0.4" version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed3d612bc64430efeb3f7ee6ef26d590dce0c43249217bddc62112540c7941e1" checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e"
[[package]] [[package]]
name = "same-file" name = "same-file"
@@ -1646,27 +1690,37 @@ checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3"
[[package]] [[package]]
name = "serde" name = "serde"
version = "1.0.111" version = "1.0.114"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c9124df5b40cbd380080b2cc6ab894c040a3070d995f5c9dc77e18c34a8ae37d" checksum = "5317f7588f0a5078ee60ef675ef96735a1442132dc645eb1d12c018620ed8cd3"
dependencies = [ dependencies = [
"serde_derive", "serde_derive",
] ]
[[package]] [[package]]
name = "serde_bytes" name = "serde_bytes"
version = "0.11.4" version = "0.11.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bf487fbf5c6239d7ea2ff8b10cb6b811cd4b5080d1c2aeed1dec18753c06e10" checksum = "16ae07dd2f88a366f15bd0632ba725227018c69a1c8550a927324f8eb8368bb9"
dependencies = [ dependencies = [
"serde", "serde",
] ]
[[package]] [[package]]
name = "serde_derive" name = "serde_cbor"
version = "1.0.111" version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f2c3ac8e6ca1e9c80b8be1023940162bf81ae3cffbb1809474152f2ce1eb250" checksum = "1e18acfa2f90e8b735b2836ab8d538de304cbb6729a7360729ea5a895d15a622"
dependencies = [
"half",
"serde",
]
[[package]]
name = "serde_derive"
version = "1.0.114"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a0be94b04690fbaed37cddffc5c134bf537c8e3329d53e982fe04c374978f8e"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@@ -1675,9 +1729,9 @@ dependencies = [
[[package]] [[package]]
name = "serde_json" name = "serde_json"
version = "1.0.53" version = "1.0.56"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "993948e75b189211a9b31a7528f950c6adc21f9720b6438ff80a7fa2f864cea2" checksum = "3433e879a558dde8b5e8feb2a04899cf34fdde1fafb894687e52105fc1162ac3"
dependencies = [ dependencies = [
"itoa", "itoa",
"ryu", "ryu",
@@ -1692,9 +1746,9 @@ checksum = "7fdf1b9db47230893d76faad238fd6097fd6d6a9245cd7a4d90dbd639536bbd2"
[[package]] [[package]]
name = "smallvec" name = "smallvec"
version = "1.4.0" version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7cb5678e1615754284ec264d9bb5b4c27d2018577fd90ac0ceb578591ed5ee4" checksum = "3757cb9d89161a2f24e1cf78efa0c1fcff485d18e3f55e0aa3480824ddaa0f3f"
[[package]] [[package]]
name = "stable_deref_trait" name = "stable_deref_trait"
@@ -1716,9 +1770,9 @@ checksum = "6446ced80d6c486436db5c078dde11a9f73d42b57fb273121e160b84f63d894c"
[[package]] [[package]]
name = "structopt" name = "structopt"
version = "0.3.14" version = "0.3.15"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "863246aaf5ddd0d6928dfeb1a9ca65f505599e4e1b399935ef7e75107516b4ef" checksum = "de2f5e239ee807089b62adce73e48c625e0ed80df02c7ab3f068f5db5281065c"
dependencies = [ dependencies = [
"clap", "clap",
"lazy_static", "lazy_static",
@@ -1727,9 +1781,9 @@ dependencies = [
[[package]] [[package]]
name = "structopt-derive" name = "structopt-derive"
version = "0.4.7" version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d239ca4b13aee7a2142e6795cbd69e457665ff8037aed33b3effdc430d2f927a" checksum = "510413f9de616762a4fbeab62509bf15c729603b72d7cd71280fbca431b1c118"
dependencies = [ dependencies = [
"heck", "heck",
"proc-macro-error", "proc-macro-error",
@@ -1746,9 +1800,9 @@ checksum = "2d67a5a62ba6e01cb2192ff309324cb4875d0c451d55fe2319433abe7a05a8ee"
[[package]] [[package]]
name = "syn" name = "syn"
version = "1.0.29" version = "1.0.33"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb37da98a55b1d08529362d9cbb863be17556873df2585904ab9d2bc951291d0" checksum = "e8d5d96e8cbb005d6959f119f773bfaebb5684296108fb32600c00cde305b2cd"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@@ -1814,18 +1868,18 @@ dependencies = [
[[package]] [[package]]
name = "thiserror" name = "thiserror"
version = "1.0.19" version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b13f926965ad00595dd129fa12823b04bbf866e9085ab0a5f2b05b850fbfc344" checksum = "7dfdd070ccd8ccb78f4ad66bf1982dc37f620ef696c6b5028fe2ed83dd3d0d08"
dependencies = [ dependencies = [
"thiserror-impl", "thiserror-impl",
] ]
[[package]] [[package]]
name = "thiserror-impl" name = "thiserror-impl"
version = "1.0.19" version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "893582086c2f98cde18f906265a65b5030a074b1046c674ae898be6519a7f479" checksum = "bd80fc12f73063ac132ac92aceea36734f04a1d93c1240c6944e23a3b8841793"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@@ -1872,9 +1926,9 @@ dependencies = [
[[package]] [[package]]
name = "tracing" name = "tracing"
version = "0.1.14" version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7c6b59d116d218cb2d990eb06b77b64043e0268ef7323aae63d8b30ae462923" checksum = "a41f40ed0e162c911ac6fcb53ecdc8134c46905fdbbae8c50add462a538b495f"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"tracing-attributes", "tracing-attributes",
@@ -1939,15 +1993,15 @@ checksum = "e83e153d1053cbb5a118eeff7fd5be06ed99153f00dbcd8ae310c5fb2b22edc0"
[[package]] [[package]]
name = "unicode-width" name = "unicode-width"
version = "0.1.7" version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "caaa9d531767d1ff2150b9332433f32a24622147e5ebb1f26409d5da67afd479" checksum = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3"
[[package]] [[package]]
name = "unicode-xid" name = "unicode-xid"
version = "0.2.0" version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c" checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564"
[[package]] [[package]]
name = "vec_map" name = "vec_map"
@@ -1992,9 +2046,9 @@ checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519"
[[package]] [[package]]
name = "wasm-bindgen" name = "wasm-bindgen"
version = "0.2.63" version = "0.2.64"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c2dc4aa152834bc334f506c1a06b866416a8b6697d5c9f75b9a689c8486def0" checksum = "6a634620115e4a229108b71bde263bb4220c483b3f07f5ba514ee8d15064c4c2"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"wasm-bindgen-macro", "wasm-bindgen-macro",
@@ -2002,9 +2056,9 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-backend" name = "wasm-bindgen-backend"
version = "0.2.63" version = "0.2.64"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ded84f06e0ed21499f6184df0e0cb3494727b0c5da89534e0fcc55c51d812101" checksum = "3e53963b583d18a5aa3aaae4b4c1cb535218246131ba22a71f05b518098571df"
dependencies = [ dependencies = [
"bumpalo", "bumpalo",
"lazy_static", "lazy_static",
@@ -2017,9 +2071,9 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-macro" name = "wasm-bindgen-macro"
version = "0.2.63" version = "0.2.64"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "838e423688dac18d73e31edce74ddfac468e37b1506ad163ffaf0a46f703ffe3" checksum = "3fcfd5ef6eec85623b4c6e844293d4516470d8f19cd72d0d12246017eb9060b8"
dependencies = [ dependencies = [
"quote", "quote",
"wasm-bindgen-macro-support", "wasm-bindgen-macro-support",
@@ -2027,9 +2081,9 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-macro-support" name = "wasm-bindgen-macro-support"
version = "0.2.63" version = "0.2.64"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3156052d8ec77142051a533cdd686cba889537b213f948cd1d20869926e68e92" checksum = "9adff9ee0e94b926ca81b57f57f86d5545cdcb1d259e21ec9bdd95b901754c75"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@@ -2040,9 +2094,9 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-shared" name = "wasm-bindgen-shared"
version = "0.2.63" version = "0.2.64"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c9ba19973a58daf4db6f352eda73dc0e289493cd29fb2632eb172085b6521acd" checksum = "7f7b90ea6c632dd06fd765d44542e234d5e63d9bb917ecd64d79778a13bd79ae"
[[package]] [[package]]
name = "wasm-common" name = "wasm-common"
@@ -2073,7 +2127,7 @@ dependencies = [
"wasmer-engine-dummy", "wasmer-engine-dummy",
"wasmer-engine-jit", "wasmer-engine-jit",
"wasmer-engine-native", "wasmer-engine-native",
"wasmer-runtime", "wasmer-vm",
"wat", "wat",
"winapi", "winapi",
] ]
@@ -2153,7 +2207,7 @@ name = "wasmer-compiler"
version = "1.0.0-alpha.1" version = "1.0.0-alpha.1"
dependencies = [ dependencies = [
"enumset", "enumset",
"hashbrown", "hashbrown 0.8.0",
"raw-cpuid", "raw-cpuid",
"serde", "serde",
"serde_bytes", "serde_bytes",
@@ -2161,7 +2215,7 @@ dependencies = [
"target-lexicon", "target-lexicon",
"thiserror", "thiserror",
"wasm-common", "wasm-common",
"wasmer-runtime", "wasmer-vm",
"wasmparser", "wasmparser",
] ]
@@ -2171,8 +2225,8 @@ version = "1.0.0-alpha.1"
dependencies = [ dependencies = [
"cranelift-codegen", "cranelift-codegen",
"cranelift-frontend", "cranelift-frontend",
"gimli", "gimli 0.21.0",
"hashbrown", "hashbrown 0.8.0",
"lazy_static", "lazy_static",
"more-asserts", "more-asserts",
"rayon", "rayon",
@@ -2181,7 +2235,7 @@ dependencies = [
"tracing", "tracing",
"wasm-common", "wasm-common",
"wasmer-compiler", "wasmer-compiler",
"wasmer-runtime", "wasmer-vm",
] ]
[[package]] [[package]]
@@ -2203,7 +2257,7 @@ dependencies = [
"target-lexicon", "target-lexicon",
"wasm-common", "wasm-common",
"wasmer-compiler", "wasmer-compiler",
"wasmer-runtime", "wasmer-vm",
] ]
[[package]] [[package]]
@@ -2213,7 +2267,7 @@ dependencies = [
"byteorder", "byteorder",
"dynasm", "dynasm",
"dynasmrt", "dynasmrt",
"hashbrown", "hashbrown 0.8.0",
"lazy_static", "lazy_static",
"more-asserts", "more-asserts",
"rayon", "rayon",
@@ -2221,7 +2275,7 @@ dependencies = [
"smallvec", "smallvec",
"wasm-common", "wasm-common",
"wasmer-compiler", "wasmer-compiler",
"wasmer-runtime", "wasmer-vm",
] ]
[[package]] [[package]]
@@ -2245,7 +2299,6 @@ dependencies = [
"bincode", "bincode",
"lazy_static", "lazy_static",
"more-asserts", "more-asserts",
"region",
"rustc-demangle", "rustc-demangle",
"serde", "serde",
"serde_bytes", "serde_bytes",
@@ -2253,7 +2306,7 @@ dependencies = [
"thiserror", "thiserror",
"wasm-common", "wasm-common",
"wasmer-compiler", "wasmer-compiler",
"wasmer-runtime", "wasmer-vm",
"winapi", "winapi",
] ]
@@ -2267,7 +2320,7 @@ dependencies = [
"wasm-common", "wasm-common",
"wasmer-compiler", "wasmer-compiler",
"wasmer-engine", "wasmer-engine",
"wasmer-runtime", "wasmer-vm",
] ]
[[package]] [[package]]
@@ -2282,7 +2335,7 @@ dependencies = [
"wasm-common", "wasm-common",
"wasmer-compiler", "wasmer-compiler",
"wasmer-engine", "wasmer-engine",
"wasmer-runtime", "wasmer-vm",
"winapi", "winapi",
] ]
@@ -2302,21 +2355,21 @@ dependencies = [
"wasmer-compiler", "wasmer-compiler",
"wasmer-engine", "wasmer-engine",
"wasmer-object", "wasmer-object",
"wasmer-runtime", "wasmer-vm",
] ]
[[package]] [[package]]
name = "wasmer-object" name = "wasmer-object"
version = "1.0.0-alpha.1" version = "1.0.0-alpha.1"
dependencies = [ dependencies = [
"object", "object 0.19.0",
"thiserror", "thiserror",
"wasm-common", "wasm-common",
"wasmer-compiler", "wasmer-compiler",
] ]
[[package]] [[package]]
name = "wasmer-runtime" name = "wasmer-vm"
version = "1.0.0-alpha.1" version = "1.0.0-alpha.1"
dependencies = [ dependencies = [
"backtrace", "backtrace",
@@ -2374,7 +2427,7 @@ dependencies = [
"typetag", "typetag",
"wasmer", "wasmer",
"wasmer-wasi", "wasmer-wasi",
"wast", "wast 17.0.0",
] ]
[[package]] [[package]]
@@ -2393,12 +2446,21 @@ dependencies = [
] ]
[[package]] [[package]]
name = "wat" name = "wast"
version = "1.0.18" version = "21.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b50f9e5e5c81e6fd987ae6997a9f4bbb751df2dec1d8cadb0b5778f1ec13bbe" checksum = "0b1844f66a2bc8526d71690104c0e78a8e59ffa1597b7245769d174ebb91deb5"
dependencies = [ dependencies = [
"wast", "leb128",
]
[[package]]
name = "wat"
version = "1.0.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce85d72b74242c340e9e3492cfb602652d7bb324c3172dd441b5577e39a2e18c"
dependencies = [
"wast 21.0.0",
] ]
[[package]] [[package]]
@@ -2473,9 +2535,9 @@ dependencies = [
[[package]] [[package]]
name = "web-sys" name = "web-sys"
version = "0.3.40" version = "0.3.41"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b72fe77fd39e4bd3eaa4412fd299a0be6b3dfe9d2597e2f1c20beb968f41d17" checksum = "863539788676619aac1a23e2df3655e96b32b0e05eb72ca34ba045ad573c625d"
dependencies = [ dependencies = [
"js-sys", "js-sys",
"wasm-bindgen", "wasm-bindgen",
@@ -2492,9 +2554,9 @@ dependencies = [
[[package]] [[package]]
name = "winapi" name = "winapi"
version = "0.3.8" version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [ dependencies = [
"winapi-i686-pc-windows-gnu", "winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu",

View File

@@ -109,7 +109,7 @@ test-llvm:
test-packages: test-packages:
cargo test -p wasmer --release cargo test -p wasmer --release
cargo test -p wasmer-runtime --release cargo test -p wasmer-vm --release
cargo test -p wasm-common --release cargo test -p wasm-common --release
cargo test -p wasmer-wasi --release cargo test -p wasmer-wasi --release
@@ -125,7 +125,7 @@ test-capi-llvm: build-capi-llvm
cargo test --manifest-path lib/c-api/Cargo.toml --release \ cargo test --manifest-path lib/c-api/Cargo.toml --release \
--no-default-features --features jit,llvm,wasi -- --nocapture --no-default-features --features jit,llvm,wasi -- --nocapture
test-capi: test-capi-singlepass test-capi-cranelift test-capi-llvm test-capi-emscripten test-capi: test-capi-singlepass test-capi-cranelift test-capi-llvm
test-wasi-unit: test-wasi-unit:
cargo test --manifest-path lib/wasi/Cargo.toml --release cargo test --manifest-path lib/wasi/Cargo.toml --release
@@ -181,8 +181,8 @@ package-docs: build-docs build-docs-capi
mkdir -p "package/docs/c" mkdir -p "package/docs/c"
cp -R target/doc package/docs/crates cp -R target/doc package/docs/crates
cp -R lib/c-api/doc/html package/docs/c-api cp -R lib/c-api/doc/html package/docs/c-api
echo '<!-- Build $(SOURCE_VERSION) --><meta http-equiv="refresh" content="0; url=rust/wasmer_runtime/index.html">' > package/docs/index.html echo '<!-- Build $(SOURCE_VERSION) --><meta http-equiv="refresh" content="0; url=rust/wasmer_vm/index.html">' > package/docs/index.html
echo '<!-- Build $(SOURCE_VERSION) --><meta http-equiv="refresh" content="0; url=wasmer_runtime/index.html">' > package/docs/crates/index.html echo '<!-- Build $(SOURCE_VERSION) --><meta http-equiv="refresh" content="0; url=wasmer_vm/index.html">' > package/docs/crates/index.html
package: package-wapm package-wasmer package-capi package: package-wapm package-wasmer package-capi
cp LICENSE package/LICENSE cp LICENSE package/LICENSE

View File

@@ -88,7 +88,7 @@ Wasmer runtime can be used as a library embedded in different languages, so you
| &nbsp; | Language | Docs | Author(s) | Maintenance | Release | Stars | | &nbsp; | Language | Docs | Author(s) | Maintenance | Release | Stars |
|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|
| ![Rust logo](./assets/languages/rust.svg) | [**Rust**](https://github.com/wasmerio/wasmer-rust-example) | [Docs](https://wasmerio.github.io/wasmer/crates/wasmer_runtime/) | Wasmer | actively developed | <a href="https://crates.io/crates/wasmer-runtime/" target="_blank">![last release](https://img.shields.io/crates/v/wasmer-runtime?style=flat-square)</a> | ![number of Github stars](https://img.shields.io/github/stars/wasmerio/wasmer?style=flat-square) | | ![Rust logo](./assets/languages/rust.svg) | [**Rust**](https://github.com/wasmerio/wasmer-rust-example) | [Docs](https://wasmerio.github.io/wasmer/crates/wasmer_vm/) | Wasmer | actively developed | <a href="https://crates.io/crates/wasmer-vm/" target="_blank">![last release](https://img.shields.io/crates/v/wasmer-vm?style=flat-square)</a> | ![number of Github stars](https://img.shields.io/github/stars/wasmerio/wasmer?style=flat-square) |
| ![C logo](./assets/languages/c.svg) | [**C/C++**](https://github.com/wasmerio/wasmer-c-api) | [Docs](https://wasmerio.github.io/wasmer/c/runtime-c-api/) | Wasmer | actively developed | <a href="https://github.com/wasmerio/wasmer-c-api/" target="_blank">![last release](https://img.shields.io/github/v/release/wasmerio/wasmer?style=flat-square)</a> | ![number of Github stars](https://img.shields.io/github/stars/wasmerio/wasmer?style=flat-square) | | ![C logo](./assets/languages/c.svg) | [**C/C++**](https://github.com/wasmerio/wasmer-c-api) | [Docs](https://wasmerio.github.io/wasmer/c/runtime-c-api/) | Wasmer | actively developed | <a href="https://github.com/wasmerio/wasmer-c-api/" target="_blank">![last release](https://img.shields.io/github/v/release/wasmerio/wasmer?style=flat-square)</a> | ![number of Github stars](https://img.shields.io/github/stars/wasmerio/wasmer?style=flat-square) |
| ![Python logo](./assets/languages/python.svg) | [**Python**](https://github.com/wasmerio/python-ext-wasm) | [Docs](https://github.com/wasmerio/python-ext-wasm#api-of-the-wasmer-extensionmodule) | Wasmer | actively developed | <a href="https://pypi.org/project/wasmer/" target="_blank">![last release](https://img.shields.io/pypi/v/wasmer?style=flat-square)</a> | ![number of Github stars](https://img.shields.io/github/stars/wasmerio/python-ext-wasm?style=flat-square) | | ![Python logo](./assets/languages/python.svg) | [**Python**](https://github.com/wasmerio/python-ext-wasm) | [Docs](https://github.com/wasmerio/python-ext-wasm#api-of-the-wasmer-extensionmodule) | Wasmer | actively developed | <a href="https://pypi.org/project/wasmer/" target="_blank">![last release](https://img.shields.io/pypi/v/wasmer?style=flat-square)</a> | ![number of Github stars](https://img.shields.io/github/stars/wasmerio/python-ext-wasm?style=flat-square) |
| ![Go logo](./assets/languages/go.svg) | [**Go**](https://github.com/wasmerio/go-ext-wasm) | [Docs](https://github.com/wasmerio/go-ext-wasm#basic-example-exported-function) | Wasmer | actively developed | <a href="https://github.com/wasmerio/go-ext-wasm" target="_blank">![last release](https://img.shields.io/github/v/release/wasmerio/go-ext-wasm?style=flat-square)</a> | ![number of Github stars](https://img.shields.io/github/stars/wasmerio/go-ext-wasm?style=flat-square) | | ![Go logo](./assets/languages/go.svg) | [**Go**](https://github.com/wasmerio/go-ext-wasm) | [Docs](https://github.com/wasmerio/go-ext-wasm#basic-example-exported-function) | Wasmer | actively developed | <a href="https://github.com/wasmerio/go-ext-wasm" target="_blank">![last release](https://img.shields.io/github/v/release/wasmerio/go-ext-wasm?style=flat-square)</a> | ![number of Github stars](https://img.shields.io/github/stars/wasmerio/go-ext-wasm?style=flat-square) |

View File

@@ -9,7 +9,7 @@ readme = "README.md"
edition = "2018" edition = "2018"
[dependencies] [dependencies]
wasmer-runtime = { path = "../runtime", version = "1.0.0-alpha.1" } wasmer-vm = { path = "../vm", version = "1.0.0-alpha.1" }
wasmer-compiler-singlepass = { path = "../compiler-singlepass", version = "1.0.0-alpha.1", optional = true } wasmer-compiler-singlepass = { path = "../compiler-singlepass", version = "1.0.0-alpha.1", optional = true }
wasmer-compiler-cranelift = { path = "../compiler-cranelift", version = "1.0.0-alpha.1", optional = true } wasmer-compiler-cranelift = { path = "../compiler-cranelift", version = "1.0.0-alpha.1", optional = true }
wasmer-compiler-llvm = { path = "../compiler-llvm", version = "1.0.0-alpha.1", optional = true } wasmer-compiler-llvm = { path = "../compiler-llvm", version = "1.0.0-alpha.1", optional = true }
@@ -18,7 +18,7 @@ wasmer-engine = { path = "../engine", version = "1.0.0-alpha.1" }
wasmer-engine-jit = { path = "../engine-jit", version = "1.0.0-alpha.1", optional = true } wasmer-engine-jit = { path = "../engine-jit", version = "1.0.0-alpha.1", optional = true }
wasmer-engine-native = { path = "../engine-native", version = "1.0.0-alpha.1", optional = true } wasmer-engine-native = { path = "../engine-native", version = "1.0.0-alpha.1", optional = true }
wasm-common = { path = "../wasm-common", version = "1.0.0-alpha.1" } wasm-common = { path = "../wasm-common", version = "1.0.0-alpha.1" }
indexmap = { version = "1.3", features = ["serde-1"] } indexmap = { version = "1.4", features = ["serde-1"] }
cfg-if = "0.1" cfg-if = "0.1"
wat = { version = "1.0", optional = true } wat = { version = "1.0", optional = true }
thiserror = "1.0" thiserror = "1.0"

View File

@@ -8,7 +8,7 @@ use std::{
sync::Arc, sync::Arc,
}; };
use thiserror::Error; use thiserror::Error;
use wasmer_runtime::Export; use wasmer_vm::Export;
/// The `ExportError` can happen when trying to get a specific /// The `ExportError` can happen when trying to get a specific
/// export [`Extern`] from the [`Instance`] exports. /// export [`Extern`] from the [`Instance`] exports.

View File

@@ -8,7 +8,7 @@ use crate::RuntimeError;
pub use inner::{FromToNativeWasmType, HostFunction, WasmTypeList, WithEnv, WithoutEnv}; pub use inner::{FromToNativeWasmType, HostFunction, WasmTypeList, WithEnv, WithoutEnv};
use std::cell::RefCell; use std::cell::RefCell;
use std::cmp::max; use std::cmp::max;
use wasmer_runtime::{ use wasmer_vm::{
raise_user_trap, resume_panic, wasmer_call_trampoline, Export, ExportFunction, raise_user_trap, resume_panic, wasmer_call_trampoline, Export, ExportFunction,
VMCallerCheckedAnyfunc, VMContext, VMDynamicFunctionContext, VMFunctionBody, VMFunctionKind, VMCallerCheckedAnyfunc, VMContext, VMDynamicFunctionContext, VMFunctionBody, VMFunctionKind,
VMTrampoline, VMTrampoline,
@@ -42,8 +42,6 @@ pub enum FunctionDefinition {
pub struct Function { pub struct Function {
pub(crate) store: Store, pub(crate) store: Store,
pub(crate) definition: FunctionDefinition, pub(crate) definition: FunctionDefinition,
// If the Function is owned by the Store, not the instance
pub(crate) owned_by_store: bool,
pub(crate) exported: ExportFunction, pub(crate) exported: ExportFunction,
} }
@@ -69,7 +67,6 @@ impl Function {
Self { Self {
store: store.clone(), store: store.clone(),
owned_by_store: true,
definition: FunctionDefinition::Host(HostFunctionDefinition { has_env: false }), definition: FunctionDefinition::Host(HostFunctionDefinition { has_env: false }),
exported: ExportFunction { exported: ExportFunction {
address, address,
@@ -108,7 +105,6 @@ impl Function {
Self { Self {
store: store.clone(), store: store.clone(),
owned_by_store: true,
definition: FunctionDefinition::Host(HostFunctionDefinition { has_env: true }), definition: FunctionDefinition::Host(HostFunctionDefinition { has_env: true }),
exported: ExportFunction { exported: ExportFunction {
address, address,
@@ -144,7 +140,6 @@ impl Function {
Self { Self {
store: store.clone(), store: store.clone(),
owned_by_store: true,
definition: FunctionDefinition::Host(HostFunctionDefinition { has_env: false }), definition: FunctionDefinition::Host(HostFunctionDefinition { has_env: false }),
exported: ExportFunction { exported: ExportFunction {
address, address,
@@ -182,7 +177,6 @@ impl Function {
Self { Self {
store: store.clone(), store: store.clone(),
owned_by_store: true,
definition: FunctionDefinition::Host(HostFunctionDefinition { has_env: true }), definition: FunctionDefinition::Host(HostFunctionDefinition { has_env: true }),
exported: ExportFunction { exported: ExportFunction {
address, address,
@@ -309,7 +303,6 @@ impl Function {
.expect("Can't get call trampoline for the function"); .expect("Can't get call trampoline for the function");
Self { Self {
store: store.clone(), store: store.clone(),
owned_by_store: false,
definition: FunctionDefinition::Wasm(WasmFunctionDefinition { trampoline }), definition: FunctionDefinition::Wasm(WasmFunctionDefinition { trampoline }),
exported: wasmer_export, exported: wasmer_export,
} }
@@ -503,7 +496,7 @@ mod inner {
use std::marker::PhantomData; use std::marker::PhantomData;
use std::panic::{self, AssertUnwindSafe}; use std::panic::{self, AssertUnwindSafe};
use wasm_common::{FunctionType, NativeWasmType, Type}; use wasm_common::{FunctionType, NativeWasmType, Type};
use wasmer_runtime::{raise_user_trap, resume_panic, VMFunctionBody}; use wasmer_vm::{raise_user_trap, resume_panic, VMFunctionBody};
/// A trait to convert a Rust value to a `WasmNativeType` value, /// A trait to convert a Rust value to a `WasmNativeType` value,
/// or to convert `WasmNativeType` value to a Rust value. /// or to convert `WasmNativeType` value to a Rust value.
@@ -692,6 +685,50 @@ mod inner {
} }
} }
#[cfg(test)]
mod test_into_result {
use super::*;
use std::convert::Infallible;
#[test]
fn test_into_result_over_t() {
let x: i32 = 42;
let result_of_x: Result<i32, Infallible> = x.into_result();
assert_eq!(result_of_x.unwrap(), x);
}
#[test]
fn test_into_result_over_result() {
{
let x: Result<i32, Infallible> = Ok(42);
let result_of_x: Result<i32, Infallible> = x.into_result();
assert_eq!(result_of_x, x);
}
{
use std::{error, fmt};
#[derive(Debug, PartialEq)]
struct E;
impl fmt::Display for E {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "E")
}
}
impl error::Error for E {}
let x: Result<Infallible, E> = Err(E);
let result_of_x: Result<Infallible, E> = x.into_result();
assert_eq!(result_of_x.unwrap_err(), E);
}
}
}
/// The `HostFunction` trait represents the set of functions that /// The `HostFunction` trait represents the set of functions that
/// can be used as host function. To uphold this statement, it is /// can be used as host function. To uphold this statement, it is
/// necessary for a function to be transformed into a pointer to /// necessary for a function to be transformed into a pointer to
@@ -881,7 +918,7 @@ mod inner {
/// This is a function that wraps the real host /// This is a function that wraps the real host
/// function. Its address will be used inside the /// function. Its address will be used inside the
/// runtime. /// runtime.
extern fn func_wrapper<$( $x, )* Rets, RetsAsResult, Func>( _: usize, $($x: $x::Native, )* ) -> Rets::CStruct extern fn func_wrapper<$( $x, )* Rets, RetsAsResult, Func>( _: usize, $( $x: $x::Native, )* ) -> Rets::CStruct
where where
$( $x: FromToNativeWasmType, )* $( $x: FromToNativeWasmType, )*
Rets: WasmTypeList, Rets: WasmTypeList,
@@ -900,10 +937,12 @@ mod inner {
} }
} }
func_wrapper::<$( $x, )* Rets, RetsAsResult, Self> as *const VMFunctionBody func_wrapper::< $( $x, )* Rets, RetsAsResult, Self > as *const VMFunctionBody
} }
} }
// Implement `HostFunction` for a function that has the same arity than the tuple.
// This specific function has an environment.
#[allow(unused_parens)] #[allow(unused_parens)]
impl< $( $x, )* Rets, RetsAsResult, Env, Func > impl< $( $x, )* Rets, RetsAsResult, Env, Func >
HostFunction<( $( $x ),* ), Rets, WithEnv, Env> HostFunction<( $( $x ),* ), Rets, WithEnv, Env>
@@ -942,7 +981,7 @@ mod inner {
} }
} }
func_wrapper::<$( $x, )* Rets, RetsAsResult, Env, Self> as *const VMFunctionBody func_wrapper::< $( $x, )* Rets, RetsAsResult, Env, Self > as *const VMFunctionBody
} }
} }
@@ -993,7 +1032,8 @@ mod inner {
// Implement `WasmTypeList` on `Infallible`, which means that // Implement `WasmTypeList` on `Infallible`, which means that
// `Infallible` can be used as a returned type of a host function // `Infallible` can be used as a returned type of a host function
// to express that it doesn't return. // to express that it doesn't return, or to express that it cannot
// fail (with `Result<_, Infallible>`).
impl WasmTypeList for Infallible { impl WasmTypeList for Infallible {
type CStruct = Self; type CStruct = Self;
type Array = [i128; 0]; type Array = [i128; 0];

View File

@@ -7,7 +7,7 @@ use crate::Mutability;
use crate::RuntimeError; use crate::RuntimeError;
use std::fmt; use std::fmt;
use std::sync::Arc; use std::sync::Arc;
use wasmer_runtime::{Export, ExportGlobal, Global as RuntimeGlobal}; use wasmer_vm::{Export, ExportGlobal, Global as RuntimeGlobal};
#[derive(Clone)] #[derive(Clone)]
pub struct Global { pub struct Global {

View File

@@ -1,47 +1,32 @@
use crate::exports::{ExportError, Exportable}; use crate::exports::{ExportError, Exportable};
use crate::externals::Extern; use crate::externals::Extern;
use crate::memory_view::MemoryView;
use crate::store::Store; use crate::store::Store;
use crate::MemoryType; use crate::{MemoryType, MemoryView};
use std::ptr::NonNull;
use std::slice; use std::slice;
use std::sync::Arc;
use wasm_common::{Pages, ValueType}; use wasm_common::{Pages, ValueType};
use wasmer_runtime::{ use wasmer_vm::{Export, ExportMemory, Memory as RuntimeMemory, MemoryError};
Export, ExportMemory, Memory as MemoryTrait, MemoryError, VMMemoryDefinition,
};
#[derive(Clone)] #[derive(Clone)]
pub struct Memory { pub struct Memory {
store: Store, store: Store,
// If the Memory is owned by the Store, not the instance memory: Arc<dyn RuntimeMemory>,
owned_by_store: bool,
exported: ExportMemory,
} }
impl Memory { impl Memory {
pub fn new(store: &Store, ty: MemoryType) -> Result<Memory, MemoryError> { pub fn new(store: &Store, ty: MemoryType) -> Result<Memory, MemoryError> {
let tunables = store.tunables(); let tunables = store.tunables();
let memory_plan = tunables.memory_plan(ty); let style = tunables.memory_style(&ty);
let memory = tunables.create_memory(memory_plan)?; let memory = tunables.create_memory(&ty, &style)?;
let definition = memory.vmmemory();
Ok(Memory { Ok(Memory {
store: store.clone(), store: store.clone(),
owned_by_store: true, memory,
exported: ExportMemory {
from: memory,
definition,
},
}) })
} }
fn definition(&self) -> NonNull<VMMemoryDefinition> {
self.memory().vmmemory()
}
pub fn ty(&self) -> &MemoryType { pub fn ty(&self) -> &MemoryType {
&self.exported.plan().memory self.memory.ty()
} }
pub fn store(&self) -> &Store { pub fn store(&self) -> &Store {
@@ -65,36 +50,32 @@ impl Memory {
/// To be defined (TODO). /// To be defined (TODO).
#[allow(clippy::mut_from_ref)] #[allow(clippy::mut_from_ref)]
pub unsafe fn data_unchecked_mut(&self) -> &mut [u8] { pub unsafe fn data_unchecked_mut(&self) -> &mut [u8] {
let definition = self.definition(); let definition = self.memory.vmmemory();
let def = definition.as_ref(); let def = definition.as_ref();
slice::from_raw_parts_mut(def.base, def.current_length) slice::from_raw_parts_mut(def.base, def.current_length)
} }
pub fn data_ptr(&self) -> *mut u8 { pub fn data_ptr(&self) -> *mut u8 {
let definition = self.definition(); let definition = self.memory.vmmemory();
let def = unsafe { definition.as_ref() }; let def = unsafe { definition.as_ref() };
def.base def.base
} }
pub fn data_size(&self) -> usize { pub fn data_size(&self) -> usize {
let definition = self.definition(); let definition = self.memory.vmmemory();
let def = unsafe { definition.as_ref() }; let def = unsafe { definition.as_ref() };
def.current_length def.current_length
} }
pub fn size(&self) -> Pages { pub fn size(&self) -> Pages {
self.memory().size() self.memory.size()
}
fn memory(&self) -> &dyn MemoryTrait {
&*self.exported.from
} }
pub fn grow<IntoPages>(&self, delta: IntoPages) -> Result<Pages, MemoryError> pub fn grow<IntoPages>(&self, delta: IntoPages) -> Result<Pages, MemoryError>
where where
IntoPages: Into<Pages>, IntoPages: Into<Pages>,
{ {
self.memory().grow(delta.into()) self.memory.grow(delta.into())
} }
/// Return a "view" of the currently accessible memory. By /// Return a "view" of the currently accessible memory. By
@@ -139,21 +120,24 @@ impl Memory {
pub(crate) fn from_export(store: &Store, wasmer_export: ExportMemory) -> Memory { pub(crate) fn from_export(store: &Store, wasmer_export: ExportMemory) -> Memory {
Memory { Memory {
store: store.clone(), store: store.clone(),
owned_by_store: false, memory: wasmer_export.from,
exported: wasmer_export,
} }
} }
/// Returns whether or not these two globals refer to the same data. /// Returns whether or not these two globals refer to the same data.
pub fn same(&self, other: &Memory) -> bool { pub fn same(&self, other: &Memory) -> bool {
self.exported.same(&other.exported) Arc::ptr_eq(&self.memory, &other.memory)
} }
} }
impl<'a> Exportable<'a> for Memory { impl<'a> Exportable<'a> for Memory {
fn to_export(&self) -> Export { fn to_export(&self) -> Export {
self.exported.clone().into() ExportMemory {
from: self.memory.clone(),
} }
.into()
}
fn get_self_from_extern(_extern: &'a Extern) -> Result<&'a Self, ExportError> { fn get_self_from_extern(_extern: &'a Extern) -> Result<&'a Self, ExportError> {
match _extern { match _extern {
Extern::Memory(memory) => Ok(memory), Extern::Memory(memory) => Ok(memory),
@@ -161,12 +145,3 @@ impl<'a> Exportable<'a> for Memory {
} }
} }
} }
impl Drop for Memory {
fn drop(&mut self) {
if self.owned_by_store {
// let r = unsafe { libc::munmap(self.ptr as *mut libc::c_void, self.len) };
// assert_eq!(r, 0, "munmap failed: {}", std::io::Error::last_os_error());
}
}
}

View File

@@ -13,7 +13,7 @@ pub use self::table::Table;
use crate::exports::{ExportError, Exportable}; use crate::exports::{ExportError, Exportable};
use crate::store::{Store, StoreObject}; use crate::store::{Store, StoreObject};
use crate::ExternType; use crate::ExternType;
use wasmer_runtime::Export; use wasmer_vm::Export;
#[derive(Clone)] #[derive(Clone)]
pub enum Extern { pub enum Extern {

View File

@@ -4,7 +4,8 @@ use crate::store::Store;
use crate::types::{Val, ValFuncRef}; use crate::types::{Val, ValFuncRef};
use crate::RuntimeError; use crate::RuntimeError;
use crate::TableType; use crate::TableType;
use wasmer_runtime::{Export, ExportTable, Table as RuntimeTable, VMCallerCheckedAnyfunc}; use std::sync::Arc;
use wasmer_vm::{Export, ExportTable, Table as RuntimeTable, VMCallerCheckedAnyfunc};
/// The `Table` struct is an array-like structure representing a WebAssembly Table, /// The `Table` struct is an array-like structure representing a WebAssembly Table,
/// which stores function references. /// which stores function references.
@@ -14,9 +15,7 @@ use wasmer_runtime::{Export, ExportTable, Table as RuntimeTable, VMCallerChecked
#[derive(Clone)] #[derive(Clone)]
pub struct Table { pub struct Table {
store: Store, store: Store,
// If the Table is owned by the Store, not the instance table: Arc<dyn RuntimeTable>,
owned_by_store: bool,
exported: ExportTable,
} }
fn set_table_item( fn set_table_item(
@@ -34,9 +33,9 @@ impl Table {
pub fn new(store: &Store, ty: TableType, init: Val) -> Result<Table, RuntimeError> { pub fn new(store: &Store, ty: TableType, init: Val) -> Result<Table, RuntimeError> {
let item = init.into_checked_anyfunc(store)?; let item = init.into_checked_anyfunc(store)?;
let tunables = store.tunables(); let tunables = store.tunables();
let table_plan = tunables.table_plan(ty); let style = tunables.table_style(&ty);
let table = tunables let table = tunables
.create_table(table_plan) .create_table(&ty, &style)
.map_err(RuntimeError::new)?; .map_err(RuntimeError::new)?;
let num_elements = table.size(); let num_elements = table.size();
@@ -44,24 +43,15 @@ impl Table {
set_table_item(table.as_ref(), i, item.clone())?; set_table_item(table.as_ref(), i, item.clone())?;
} }
let definition = table.vmtable();
Ok(Table { Ok(Table {
store: store.clone(), store: store.clone(),
owned_by_store: true, table,
exported: ExportTable {
from: table,
definition,
},
}) })
} }
fn table(&self) -> &dyn RuntimeTable {
&*self.exported.from
}
/// Gets the underlying [`TableType`]. /// Gets the underlying [`TableType`].
pub fn ty(&self) -> &TableType { pub fn ty(&self) -> &TableType {
&self.exported.plan().table self.table.ty()
} }
pub fn store(&self) -> &Store { pub fn store(&self) -> &Store {
@@ -70,19 +60,19 @@ impl Table {
/// Retrieves an element of the table at the provided `index`. /// Retrieves an element of the table at the provided `index`.
pub fn get(&self, index: u32) -> Option<Val> { pub fn get(&self, index: u32) -> Option<Val> {
let item = self.table().get(index)?; let item = self.table.get(index)?;
Some(ValFuncRef::from_checked_anyfunc(item, &self.store)) Some(ValFuncRef::from_checked_anyfunc(item, &self.store))
} }
/// Sets an element `val` in the Table at the provided `index`. /// Sets an element `val` in the Table at the provided `index`.
pub fn set(&self, index: u32, val: Val) -> Result<(), RuntimeError> { pub fn set(&self, index: u32, val: Val) -> Result<(), RuntimeError> {
let item = val.into_checked_anyfunc(&self.store)?; let item = val.into_checked_anyfunc(&self.store)?;
set_table_item(self.table(), index, item) set_table_item(self.table.as_ref(), index, item)
} }
/// Retrieves the size of the `Table` (in elements) /// Retrieves the size of the `Table` (in elements)
pub fn size(&self) -> u32 { pub fn size(&self) -> u32 {
self.table().size() self.table.size()
} }
/// Grows the size of the `Table` by `delta`, initializating /// Grows the size of the `Table` by `delta`, initializating
@@ -96,11 +86,10 @@ impl Table {
/// Returns an error if the `delta` is out of bounds for the table. /// Returns an error if the `delta` is out of bounds for the table.
pub fn grow(&self, delta: u32, init: Val) -> Result<u32, RuntimeError> { pub fn grow(&self, delta: u32, init: Val) -> Result<u32, RuntimeError> {
let item = init.into_checked_anyfunc(&self.store)?; let item = init.into_checked_anyfunc(&self.store)?;
let table = self.table(); match self.table.grow(delta) {
match table.grow(delta) {
Some(len) => { Some(len) => {
for i in 0..delta { for i in 0..delta {
set_table_item(table, len + i, item.clone())?; set_table_item(self.table.as_ref(), len + i, item.clone())?;
} }
Ok(len) Ok(len)
} }
@@ -131,8 +120,8 @@ impl Table {
)); ));
} }
RuntimeTable::copy( RuntimeTable::copy(
dst_table.table(), dst_table.table.as_ref(),
src_table.table(), src_table.table.as_ref(),
dst_index, dst_index,
src_index, src_index,
len, len,
@@ -144,21 +133,24 @@ impl Table {
pub(crate) fn from_export(store: &Store, wasmer_export: ExportTable) -> Table { pub(crate) fn from_export(store: &Store, wasmer_export: ExportTable) -> Table {
Table { Table {
store: store.clone(), store: store.clone(),
owned_by_store: false, table: wasmer_export.from,
exported: wasmer_export,
} }
} }
/// Returns whether or not these two tables refer to the same data. /// Returns whether or not these two tables refer to the same data.
pub fn same(&self, other: &Self) -> bool { pub fn same(&self, other: &Self) -> bool {
self.exported.same(&other.exported) Arc::ptr_eq(&self.table, &other.table)
} }
} }
impl<'a> Exportable<'a> for Table { impl<'a> Exportable<'a> for Table {
fn to_export(&self) -> Export { fn to_export(&self) -> Export {
self.exported.clone().into() ExportTable {
from: self.table.clone(),
} }
.into()
}
fn get_self_from_extern(_extern: &'a Extern) -> Result<&'a Self, ExportError> { fn get_self_from_extern(_extern: &'a Extern) -> Result<&'a Self, ExportError> {
match _extern { match _extern {
Extern::Table(table) => Ok(table), Extern::Table(table) => Ok(table),

View File

@@ -9,7 +9,7 @@ use std::{
sync::{Arc, Mutex}, sync::{Arc, Mutex},
}; };
use wasmer_engine::NamedResolver; use wasmer_engine::NamedResolver;
use wasmer_runtime::Export; use wasmer_vm::Export;
/// The `LikeNamespace` trait represents objects that act as a namespace for imports. /// The `LikeNamespace` trait represents objects that act as a namespace for imports.
/// For example, an `Instance` or `Namespace` could be /// For example, an `Instance` or `Namespace` could be
@@ -62,7 +62,7 @@ impl ImportObject {
/// ///
/// # Usage /// # Usage
/// ```ignore /// ```ignore
/// # use wasmer_runtime::{ImportObject, Instance, Namespace}; /// # use wasmer_vm::{ImportObject, Instance, Namespace};
/// let mut import_object = ImportObject::new(); /// let mut import_object = ImportObject::new();
/// import_object.get_export("module", "name"); /// import_object.get_export("module", "name");
/// ``` /// ```
@@ -103,7 +103,7 @@ impl ImportObject {
/// ///
/// # Usage: /// # Usage:
/// ```ignore /// ```ignore
/// # use wasmer_runtime::{ImportObject, Instance, Namespace}; /// # use wasmer_vm::{ImportObject, Instance, Namespace};
/// let mut import_object = ImportObject::new(); /// let mut import_object = ImportObject::new();
/// ///
/// import_object.register("namespace0", instance); /// import_object.register("namespace0", instance);
@@ -250,7 +250,7 @@ mod test {
use crate::{Global, Store, Val}; use crate::{Global, Store, Val};
use wasm_common::Type; use wasm_common::Type;
use wasmer_engine::ChainableNamedResolver; use wasmer_engine::ChainableNamedResolver;
use wasmer_runtime::Export; use wasmer_vm::Export;
#[test] #[test]
fn chaining_works() { fn chaining_works() {

View File

@@ -4,7 +4,7 @@ use crate::module::Module;
use crate::store::Store; use crate::store::Store;
use crate::InstantiationError; use crate::InstantiationError;
use wasmer_engine::Resolver; use wasmer_engine::Resolver;
use wasmer_runtime::InstanceHandle; use wasmer_vm::InstanceHandle;
/// A WebAssembly Instance is a stateful, executable /// A WebAssembly Instance is a stateful, executable
/// instance of a WebAssembly [`Module`]. /// instance of a WebAssembly [`Module`].

View File

@@ -5,14 +5,10 @@ mod exports;
mod externals; mod externals;
mod import_object; mod import_object;
mod instance; mod instance;
mod memory;
mod memory_view;
mod module; mod module;
mod native; mod native;
mod ordered_resolver;
mod ptr; mod ptr;
mod store; mod store;
mod table;
mod tunables; mod tunables;
mod types; mod types;
mod utils; mod utils;
@@ -20,7 +16,7 @@ mod utils;
pub mod internals { pub mod internals {
//! We use the internals module for exporting types that are only //! We use the internals module for exporting types that are only
//! intended to use in internal crates such as the compatibility crate //! intended to use in internal crates such as the compatibility crate
//! `wasmer-runtime`. Please don't use any of this types directly, as //! `wasmer-vm`. Please don't use any of this types directly, as
//! they might change frequently or be removed in the future. //! they might change frequently or be removed in the future.
pub use crate::externals::{WithEnv, WithoutEnv}; pub use crate::externals::{WithEnv, WithoutEnv};
@@ -32,10 +28,8 @@ pub use crate::externals::{
}; };
pub use crate::import_object::{ImportObject, ImportObjectIterator, LikeNamespace}; pub use crate::import_object::{ImportObject, ImportObjectIterator, LikeNamespace};
pub use crate::instance::Instance; pub use crate::instance::Instance;
pub use crate::memory_view::{Atomically, MemoryView};
pub use crate::module::Module; pub use crate::module::Module;
pub use crate::native::NativeFunc; pub use crate::native::NativeFunc;
pub use crate::ordered_resolver::OrderedResolver;
pub use crate::ptr::{Array, Item, WasmPtr}; pub use crate::ptr::{Array, Item, WasmPtr};
pub use crate::store::{Store, StoreObject}; pub use crate::store::{Store, StoreObject};
pub use crate::tunables::Tunables; pub use crate::tunables::Tunables;
@@ -47,8 +41,8 @@ pub use crate::types::{Val as Value, ValType as Type};
pub use crate::utils::is_wasm; pub use crate::utils::is_wasm;
pub use target_lexicon::{Architecture, CallingConvention, OperatingSystem, Triple, HOST}; pub use target_lexicon::{Architecture, CallingConvention, OperatingSystem, Triple, HOST};
pub use wasm_common::{ pub use wasm_common::{
Bytes, GlobalInit, LocalFunctionIndex, Pages, ValueType, WASM_MAX_PAGES, WASM_MIN_PAGES, Atomically, Bytes, GlobalInit, LocalFunctionIndex, MemoryView, Pages, ValueType,
WASM_PAGE_SIZE, WASM_MAX_PAGES, WASM_MIN_PAGES, WASM_PAGE_SIZE,
}; };
#[cfg(feature = "compiler")] #[cfg(feature = "compiler")]
pub use wasmer_compiler::CompilerConfig; pub use wasmer_compiler::CompilerConfig;
@@ -60,7 +54,7 @@ pub use wasmer_engine::{
ChainableNamedResolver, DeserializeError, Engine, InstantiationError, LinkError, NamedResolver, ChainableNamedResolver, DeserializeError, Engine, InstantiationError, LinkError, NamedResolver,
NamedResolverChain, Resolver, RuntimeError, SerializeError, NamedResolverChain, Resolver, RuntimeError, SerializeError,
}; };
pub use wasmer_runtime::{raise_user_trap, MemoryError}; pub use wasmer_vm::{raise_user_trap, Export, MemoryError};
#[cfg(feature = "wat")] #[cfg(feature = "wat")]
pub use wat::parse_bytes as wat2wasm; pub use wat::parse_bytes as wat2wasm;

View File

@@ -9,7 +9,7 @@ use wasmer_compiler::CompileError;
#[cfg(feature = "wat")] #[cfg(feature = "wat")]
use wasmer_compiler::WasmError; use wasmer_compiler::WasmError;
use wasmer_engine::{Artifact, DeserializeError, Resolver, SerializeError}; use wasmer_engine::{Artifact, DeserializeError, Resolver, SerializeError};
use wasmer_runtime::{ExportsIterator, ImportsIterator, InstanceHandle, ModuleInfo}; use wasmer_vm::{ExportsIterator, ImportsIterator, InstanceHandle, ModuleInfo};
#[derive(Error, Debug)] #[derive(Error, Debug)]
pub enum IoCompileError { pub enum IoCompileError {

View File

@@ -16,7 +16,7 @@ use crate::externals::function::{
use crate::{FromToNativeWasmType, Function, FunctionType, RuntimeError, Store, WasmTypeList}; use crate::{FromToNativeWasmType, Function, FunctionType, RuntimeError, Store, WasmTypeList};
use std::panic::{catch_unwind, AssertUnwindSafe}; use std::panic::{catch_unwind, AssertUnwindSafe};
use wasm_common::NativeWasmType; use wasm_common::NativeWasmType;
use wasmer_runtime::{ use wasmer_vm::{
ExportFunction, VMContext, VMDynamicFunctionContext, VMFunctionBody, VMFunctionKind, ExportFunction, VMContext, VMDynamicFunctionContext, VMFunctionBody, VMFunctionKind,
}; };
@@ -81,7 +81,6 @@ where
Self { Self {
store: other.store, store: other.store,
definition: other.definition, definition: other.definition,
owned_by_store: true, // todo
exported: ExportFunction { exported: ExportFunction {
address: other.address, address: other.address,
vmctx: other.vmctx, vmctx: other.vmctx,
@@ -123,7 +122,7 @@ macro_rules! impl_native_traits {
rets_list.as_mut() rets_list.as_mut()
}; };
unsafe { unsafe {
wasmer_runtime::wasmer_call_trampoline( wasmer_vm::wasmer_call_trampoline(
self.vmctx, self.vmctx,
trampoline, trampoline,
self.address, self.address,
@@ -147,7 +146,7 @@ macro_rules! impl_native_traits {
// but we can't currently detect whether that's safe. // but we can't currently detect whether that's safe.
// //
// let results = unsafe { // let results = unsafe {
// wasmer_runtime::catch_traps_with_result(self.vmctx, || { // wasmer_vm::catch_traps_with_result(self.vmctx, || {
// let f = std::mem::transmute::<_, unsafe extern "C" fn( *mut VMContext, $( $x, )*) -> Rets::CStruct>(self.address); // let f = std::mem::transmute::<_, unsafe extern "C" fn( *mut VMContext, $( $x, )*) -> Rets::CStruct>(self.address);
// // We always pass the vmctx // // We always pass the vmctx
// f( self.vmctx, $( $x, )* ) // f( self.vmctx, $( $x, )* )

View File

@@ -1,130 +0,0 @@
use crate::ValType;
use std::borrow::{Borrow, BorrowMut};
use std::cell::UnsafeCell;
use std::convert::TryFrom;
use std::ptr::NonNull;
use std::sync::Mutex;
use wasmer_runtime::{
Table, TablePlan, TableStyle, Trap, TrapCode, VMCallerCheckedAnyfunc, VMTableDefinition,
};
/// A table instance.
#[derive(Debug)]
pub struct LinearTable {
// TODO: we can remove the mutex by using atomic swaps and preallocating the max table size
vec: Mutex<Vec<VMCallerCheckedAnyfunc>>,
maximum: Option<u32>,
plan: TablePlan,
vm_table_definition: Box<UnsafeCell<VMTableDefinition>>,
}
/// This is correct because there is no thread-specific data tied to this type.
unsafe impl Send for LinearTable {}
/// This is correct because all internal mutability is protected by a mutex.
unsafe impl Sync for LinearTable {}
impl LinearTable {
/// Create a new table instance with specified minimum and maximum number of elements.
pub fn new(plan: &TablePlan) -> Result<Self, String> {
match plan.table.ty {
ValType::FuncRef => (),
ty => return Err(format!("tables of types other than anyfunc ({})", ty)),
};
if let Some(max) = plan.table.maximum {
if max < plan.table.minimum {
return Err(format!(
"Table minimum ({}) is larger than maximum ({})!",
plan.table.minimum, max
));
}
}
let table_minimum = usize::try_from(plan.table.minimum)
.map_err(|_| "Table minimum is bigger than usize".to_string())?;
let mut vec = vec![VMCallerCheckedAnyfunc::default(); table_minimum];
let base = vec.as_mut_ptr();
match plan.style {
TableStyle::CallerChecksSignature => Ok(Self {
vec: Mutex::new(vec),
maximum: plan.table.maximum,
plan: plan.clone(),
vm_table_definition: Box::new(UnsafeCell::new(VMTableDefinition {
base: base as _,
current_elements: table_minimum as _,
})),
}),
}
}
}
impl Table for LinearTable {
/// Returns the table plan for this Table.
fn plan(&self) -> &TablePlan {
&self.plan
}
/// Returns the number of allocated elements.
fn size(&self) -> u32 {
unsafe {
let ptr = self.vm_table_definition.get();
(*ptr).current_elements
}
}
/// Grow table by the specified amount of elements.
///
/// Returns `None` if table can't be grown by the specified amount
/// of elements, otherwise returns the previous size of the table.
fn grow(&self, delta: u32) -> Option<u32> {
let mut vec_guard = self.vec.lock().unwrap();
let vec = vec_guard.borrow_mut();
let size = self.size();
let new_len = size.checked_add(delta)?;
if self.maximum.map_or(false, |max| new_len > max) {
return None;
}
vec.resize(
usize::try_from(new_len).unwrap(),
VMCallerCheckedAnyfunc::default(),
);
// update table definition
unsafe {
let td = &mut *self.vm_table_definition.get();
td.current_elements = new_len;
td.base = vec.as_mut_ptr() as _;
}
Some(size)
}
/// Get reference to the specified element.
///
/// Returns `None` if the index is out of bounds.
fn get(&self, index: u32) -> Option<VMCallerCheckedAnyfunc> {
let vec_guard = self.vec.lock().unwrap();
vec_guard.borrow().get(index as usize).cloned()
}
/// Set reference to the specified element.
///
/// # Errors
///
/// Returns an error if the index is out of bounds.
fn set(&self, index: u32, func: VMCallerCheckedAnyfunc) -> Result<(), Trap> {
let mut vec_guard = self.vec.lock().unwrap();
let vec = vec_guard.borrow_mut();
match vec.get_mut(index as usize) {
Some(slot) => {
*slot = func;
Ok(())
}
None => Err(Trap::wasm(TrapCode::TableAccessOutOfBounds)),
}
}
/// Return a `VMTableDefinition` for exposing the table to compiled wasm code.
fn vmtable(&self) -> NonNull<VMTableDefinition> {
let _vec_guard = self.vec.lock().unwrap();
let ptr = self.vm_table_definition.as_ref() as *const UnsafeCell<VMTableDefinition>
as *const VMTableDefinition as *mut VMTableDefinition;
unsafe { NonNull::new_unchecked(ptr) }
}
}

View File

@@ -1,5 +1,3 @@
use crate::memory::LinearMemory;
use crate::table::LinearTable;
use crate::{MemoryType, Pages, TableType}; use crate::{MemoryType, Pages, TableType};
use more_asserts::assert_ge; use more_asserts::assert_ge;
use std::cmp::min; use std::cmp::min;
@@ -7,8 +5,8 @@ use std::sync::Arc;
use target_lexicon::{OperatingSystem, PointerWidth}; use target_lexicon::{OperatingSystem, PointerWidth};
use wasmer_compiler::Target; use wasmer_compiler::Target;
use wasmer_engine::Tunables as BaseTunables; use wasmer_engine::Tunables as BaseTunables;
use wasmer_runtime::MemoryError; use wasmer_vm::MemoryError;
use wasmer_runtime::{Memory, MemoryPlan, MemoryStyle, Table, TablePlan, TableStyle}; use wasmer_vm::{LinearMemory, LinearTable, Memory, MemoryStyle, Table, TableStyle};
/// Tunable parameters for WebAssembly compilation. /// Tunable parameters for WebAssembly compilation.
#[derive(Clone)] #[derive(Clone)]
@@ -61,8 +59,8 @@ impl Tunables {
} }
impl BaseTunables for Tunables { impl BaseTunables for Tunables {
/// Get a `MemoryPlan` for the provided `MemoryType` /// Get a `MemoryStyle` for the provided `MemoryType`
fn memory_plan(&self, memory: MemoryType) -> MemoryPlan { fn memory_style(&self, memory: &MemoryType) -> MemoryStyle {
// A heap with a maximum that doesn't exceed the static memory bound specified by the // A heap with a maximum that doesn't exceed the static memory bound specified by the
// tunables make it static. // tunables make it static.
// //
@@ -70,37 +68,33 @@ impl BaseTunables for Tunables {
let maximum = memory.maximum.unwrap_or_else(Pages::max_value); let maximum = memory.maximum.unwrap_or_else(Pages::max_value);
if maximum <= self.static_memory_bound { if maximum <= self.static_memory_bound {
assert_ge!(self.static_memory_bound, memory.minimum); assert_ge!(self.static_memory_bound, memory.minimum);
MemoryPlan { MemoryStyle::Static {
memory,
style: MemoryStyle::Static {
bound: self.static_memory_bound, bound: self.static_memory_bound,
},
offset_guard_size: self.static_memory_offset_guard_size, offset_guard_size: self.static_memory_offset_guard_size,
} }
} else { } else {
MemoryPlan { MemoryStyle::Dynamic {
memory,
style: MemoryStyle::Dynamic,
offset_guard_size: self.dynamic_memory_offset_guard_size, offset_guard_size: self.dynamic_memory_offset_guard_size,
} }
} }
} }
/// Get a `TablePlan` for the provided `TableType` /// Get a [`TableStyle`] for the provided [`TableType`].
fn table_plan(&self, table: TableType) -> TablePlan { fn table_style(&self, _table: &TableType) -> TableStyle {
TablePlan { TableStyle::CallerChecksSignature
table,
style: TableStyle::CallerChecksSignature,
}
} }
/// Create a memory given a memory type /// Create a memory given a [`MemoryType`] and a [`MemoryStyle`].
fn create_memory(&self, plan: MemoryPlan) -> Result<Arc<dyn Memory>, MemoryError> { fn create_memory(
Ok(Arc::new(LinearMemory::new(&plan)?)) &self,
ty: &MemoryType,
style: &MemoryStyle,
) -> Result<Arc<dyn Memory>, MemoryError> {
Ok(Arc::new(LinearMemory::new(&ty, &style)?))
} }
/// Create a memory given a memory type /// Create a table given a [`TableType`] and a [`TableStyle`].
fn create_table(&self, plan: TablePlan) -> Result<Arc<dyn Table>, String> { fn create_table(&self, ty: &TableType, style: &TableStyle) -> Result<Arc<dyn Table>, String> {
Ok(Arc::new(LinearTable::new(&plan)?)) Ok(Arc::new(LinearTable::new(&ty, &style)?))
} }
} }

View File

@@ -33,23 +33,23 @@ pub trait ValFuncRef {
fn into_checked_anyfunc( fn into_checked_anyfunc(
&self, &self,
store: &Store, store: &Store,
) -> Result<wasmer_runtime::VMCallerCheckedAnyfunc, RuntimeError>; ) -> Result<wasmer_vm::VMCallerCheckedAnyfunc, RuntimeError>;
fn from_checked_anyfunc(item: wasmer_runtime::VMCallerCheckedAnyfunc, store: &Store) -> Self; fn from_checked_anyfunc(item: wasmer_vm::VMCallerCheckedAnyfunc, store: &Store) -> Self;
} }
impl ValFuncRef for Val { impl ValFuncRef for Val {
fn into_checked_anyfunc( fn into_checked_anyfunc(
&self, &self,
store: &Store, store: &Store,
) -> Result<wasmer_runtime::VMCallerCheckedAnyfunc, RuntimeError> { ) -> Result<wasmer_vm::VMCallerCheckedAnyfunc, RuntimeError> {
if !self.comes_from_same_store(store) { if !self.comes_from_same_store(store) {
return Err(RuntimeError::new("cross-`Store` values are not supported")); return Err(RuntimeError::new("cross-`Store` values are not supported"));
} }
Ok(match self { Ok(match self {
Val::ExternRef(ExternRef::Null) => wasmer_runtime::VMCallerCheckedAnyfunc { Val::ExternRef(ExternRef::Null) => wasmer_vm::VMCallerCheckedAnyfunc {
func_ptr: ptr::null(), func_ptr: ptr::null(),
type_index: wasmer_runtime::VMSharedSignatureIndex::default(), type_index: wasmer_vm::VMSharedSignatureIndex::default(),
vmctx: ptr::null_mut(), vmctx: ptr::null_mut(),
}, },
Val::FuncRef(f) => f.checked_anyfunc(), Val::FuncRef(f) => f.checked_anyfunc(),
@@ -57,20 +57,20 @@ impl ValFuncRef for Val {
}) })
} }
fn from_checked_anyfunc(item: wasmer_runtime::VMCallerCheckedAnyfunc, store: &Store) -> Val { fn from_checked_anyfunc(item: wasmer_vm::VMCallerCheckedAnyfunc, store: &Store) -> Val {
if item.type_index == wasmer_runtime::VMSharedSignatureIndex::default() { if item.type_index == wasmer_vm::VMSharedSignatureIndex::default() {
return Val::ExternRef(ExternRef::Null); return Val::ExternRef(ExternRef::Null);
} }
let signature = store let signature = store
.engine() .engine()
.lookup_signature(item.type_index) .lookup_signature(item.type_index)
.expect("Signature not found in store"); .expect("Signature not found in store");
let export = wasmer_runtime::ExportFunction { let export = wasmer_vm::ExportFunction {
address: item.func_ptr, address: item.func_ptr,
signature, signature,
// All functions in tables are already Static (as dynamic functions // All functions in tables are already Static (as dynamic functions
// are converted to use the trampolines with static signatures). // are converted to use the trampolines with static signatures).
kind: wasmer_runtime::VMFunctionKind::Static, kind: wasmer_vm::VMFunctionKind::Static,
vmctx: item.vmctx, vmctx: item.vmctx,
}; };
let f = Function::from_export(store, export); let f = Function::from_export(store, export);

View File

@@ -175,16 +175,14 @@ fn memory_grow() -> Result<()> {
// due to stack overflow with a modern nightly, we can't update CI to use a version of nightly which will make this work // due to stack overflow with a modern nightly, we can't update CI to use a version of nightly which will make this work
/*assert!(matches!( /*assert!(matches!(
bad_result, bad_result,
Err(MemoryError::InvalidMemoryPlan { .. }) Err(MemoryError::InvalidMemory { .. })
));*/ ));*/
assert!( assert!(if let Err(MemoryError::InvalidMemory { .. }) = bad_result {
if let Err(MemoryError::InvalidMemoryPlan { .. }) = bad_result {
true true
} else { } else {
false false
} });
);
Ok(()) Ok(())
} }

View File

@@ -22,7 +22,7 @@
</a> </a>
</p> </p>
# Wasmer Runtime C API # Wasmer C API
Wasmer is a standalone WebAssembly runtime, aiming to be fully Wasmer is a standalone WebAssembly runtime, aiming to be fully
compatible with WASI, Emscripten, Rust and Go. [Learn compatible with WASI, Emscripten, Rust and Go. [Learn

View File

@@ -41,7 +41,7 @@ pub(crate) struct CAPIInstance {
pub(crate) ctx_data: Option<NonNull<c_void>>, pub(crate) ctx_data: Option<NonNull<c_void>>,
} }
/// Opaque pointer to a `wasmer_runtime::Ctx` value in Rust. /// Opaque pointer to a `wasmer_vm::Ctx` value in Rust.
/// ///
/// An instance context is passed to any host function (aka imported /// An instance context is passed to any host function (aka imported
/// function) as the first argument. It is necessary to read the /// function) as the first argument. It is necessary to read the

View File

@@ -112,6 +112,7 @@ pub mod import;
pub mod instance; pub mod instance;
pub mod memory; pub mod memory;
pub mod module; pub mod module;
mod ordered_resolver;
pub mod table; pub mod table;
// `not(target_family = "windows")` is simpler than `unix`. See build.rs // `not(target_family = "windows")` is simpler than `unix`. See build.rs
// if you want to change the meaning of these `cfg`s in the header file. // if you want to change the meaning of these `cfg`s in the header file.

View File

@@ -7,9 +7,9 @@ use crate::{
use std::{cell::Cell, ptr}; use std::{cell::Cell, ptr};
use wasmer::{Bytes, Memory, MemoryType, Pages}; use wasmer::{Bytes, Memory, MemoryType, Pages};
/// Opaque pointer to a `wasmer_runtime::Memory` value in Rust. /// Opaque pointer to a `wasmer_vm::Memory` value in Rust.
/// ///
/// A `wasmer_runtime::Memory` represents a WebAssembly memory. It is /// A `wasmer_vm::Memory` represents a WebAssembly memory. It is
/// possible to create one with `wasmer_memory_new()` and pass it as /// possible to create one with `wasmer_memory_new()` and pass it as
/// imports of an instance, or to read it from exports of an instance /// imports of an instance, or to read it from exports of an instance
/// with `wasmer_export_to_memory()`. /// with `wasmer_export_to_memory()`.

View File

@@ -5,11 +5,7 @@
//! by index and not by module and name. //! by index and not by module and name.
use std::iter::FromIterator; use std::iter::FromIterator;
use wasmer_engine::Resolver; use wasmer::{Export, Exportable, Extern, Resolver};
use crate::exports::Exportable;
use crate::Extern;
use wasmer_runtime::Export;
/// An `OrderedResolver` stores all the `externs` provided to an Instance /// An `OrderedResolver` stores all the `externs` provided to an Instance
/// in a Vec, so we can retrieve them later based on index. /// in a Vec, so we can retrieve them later based on index.
@@ -18,6 +14,7 @@ pub struct OrderedResolver {
/// The externs to be resolved by inddex /// The externs to be resolved by inddex
externs: Vec<Extern>, externs: Vec<Extern>,
} }
impl Resolver for OrderedResolver { impl Resolver for OrderedResolver {
fn resolve(&self, index: u32, _module: &str, _name: &str) -> Option<Export> { fn resolve(&self, index: u32, _module: &str, _name: &str) -> Option<Export> {
self.externs self.externs

View File

@@ -2,7 +2,7 @@
use std::ffi::c_void; use std::ffi::c_void;
use std::mem; use std::mem;
use wasmer_runtime_core::trampoline::*; use wasmer_vm_core::trampoline::*;
#[repr(C)] #[repr(C)]
pub struct wasmer_trampoline_buffer_builder_t; pub struct wasmer_trampoline_buffer_builder_t;

View File

@@ -7,10 +7,11 @@ use std::ptr::{self, NonNull};
use std::slice; use std::slice;
use std::sync::Arc; use std::sync::Arc;
use crate::ordered_resolver::OrderedResolver;
use wasmer::{ use wasmer::{
Engine, ExportType, Extern, ExternType, Function, FunctionType, Global, GlobalType, Instance, Engine, ExportType, Extern, ExternType, Function, FunctionType, Global, GlobalType, Instance,
Memory, MemoryType, Module, Mutability, OrderedResolver, Pages, RuntimeError, Store, Table, Memory, MemoryType, Module, Mutability, Pages, RuntimeError, Store, Table, TableType, Val,
TableType, Val, ValType, ValType,
}; };
#[cfg(feature = "jit")] #[cfg(feature = "jit")]
use wasmer_engine_jit::JIT; use wasmer_engine_jit::JIT;

View File

@@ -58,7 +58,7 @@ int main()
char *error_str2 = malloc(error_len2); char *error_str2 = malloc(error_len2);
wasmer_last_error_message(error_str2, error_len2); wasmer_last_error_message(error_str2, error_len2);
printf("Error str 2: `%s`\n", error_str2); printf("Error str 2: `%s`\n", error_str2);
assert(0 == strcmp(error_str2, "The memory plan is invalid because the maximum (10 pages) is less than the minimum (15 pages)")); assert(0 == strcmp(error_str2, "The memory is invalid because the maximum (10 pages) is less than the minimum (15 pages)"));
free(error_str2); free(error_str2);
printf("Destroy memory\n"); printf("Destroy memory\n");

View File

@@ -243,9 +243,9 @@ typedef struct {
} wasmer_export_t; } wasmer_export_t;
/** /**
* Opaque pointer to a `wasmer_runtime::Memory` value in Rust. * Opaque pointer to a `wasmer_vm::Memory` value in Rust.
* *
* A `wasmer_runtime::Memory` represents a WebAssembly memory. It is * A `wasmer_vm::Memory` represents a WebAssembly memory. It is
* possible to create one with `wasmer_memory_new()` and pass it as * possible to create one with `wasmer_memory_new()` and pass it as
* imports of an instance, or to read it from exports of an instance * imports of an instance, or to read it from exports of an instance
* with `wasmer_export_to_memory()`. * with `wasmer_export_to_memory()`.
@@ -312,7 +312,7 @@ typedef struct {
} wasmer_import_object_iter_t; } wasmer_import_object_iter_t;
/** /**
* Opaque pointer to a `wasmer_runtime::Ctx` value in Rust. * Opaque pointer to a `wasmer_vm::Ctx` value in Rust.
* *
* An instance context is passed to any host function (aka imported * An instance context is passed to any host function (aka imported
* function) as the first argument. It is necessary to read the * function) as the first argument. It is necessary to read the

View File

@@ -185,9 +185,9 @@ struct wasmer_export_t {
}; };
/// Opaque pointer to a `wasmer_runtime::Memory` value in Rust. /// Opaque pointer to a `wasmer_vm::Memory` value in Rust.
/// ///
/// A `wasmer_runtime::Memory` represents a WebAssembly memory. It is /// A `wasmer_vm::Memory` represents a WebAssembly memory. It is
/// possible to create one with `wasmer_memory_new()` and pass it as /// possible to create one with `wasmer_memory_new()` and pass it as
/// imports of an instance, or to read it from exports of an instance /// imports of an instance, or to read it from exports of an instance
/// with `wasmer_export_to_memory()`. /// with `wasmer_export_to_memory()`.
@@ -248,7 +248,7 @@ struct wasmer_import_object_iter_t {
}; };
/// Opaque pointer to a `wasmer_runtime::Ctx` value in Rust. /// Opaque pointer to a `wasmer_vm::Ctx` value in Rust.
/// ///
/// An instance context is passed to any host function (aka imported /// An instance context is passed to any host function (aka imported
/// function) as the first argument. It is necessary to read the /// function) as the first argument. It is necessary to read the

View File

@@ -13,12 +13,12 @@ edition = "2018"
[dependencies] [dependencies]
wasmer-compiler = { path = "../compiler", version = "1.0.0-alpha.1", features = ["translator"], default-features = false } wasmer-compiler = { path = "../compiler", version = "1.0.0-alpha.1", features = ["translator"], default-features = false }
wasmer-runtime = { path = "../runtime", version = "1.0.0-alpha.1" } wasmer-vm = { path = "../vm", version = "1.0.0-alpha.1" }
wasm-common = { path = "../wasm-common", version = "1.0.0-alpha.1", default-features = false } wasm-common = { path = "../wasm-common", version = "1.0.0-alpha.1", default-features = false }
cranelift-codegen = { version = "0.65", default-features = false } cranelift-codegen = { version = "0.65", default-features = false }
cranelift-frontend = { version = "0.65", default-features = false } cranelift-frontend = { version = "0.65", default-features = false }
tracing = "0.1" tracing = "0.1"
hashbrown = { version = "0.7", optional = true } hashbrown = { version = "0.8", optional = true }
rayon = "1.3" rayon = "1.3"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
more-asserts = "0.2" more-asserts = "0.2"

View File

@@ -60,8 +60,8 @@ impl Compiler for CraneliftCompiler {
) -> Result<Compilation, CompileError> { ) -> Result<Compilation, CompileError> {
let isa = self.config().isa(target); let isa = self.config().isa(target);
let frontend_config = isa.frontend_config(); let frontend_config = isa.frontend_config();
let memory_plans = &compile_info.memory_plans; let memory_styles = &compile_info.memory_styles;
let table_plans = &compile_info.table_plans; let table_styles = &compile_info.table_styles;
let module = &compile_info.module; let module = &compile_info.module;
let signatures = module let signatures = module
.signatures .signatures
@@ -100,8 +100,8 @@ impl Compiler for CraneliftCompiler {
isa.frontend_config(), isa.frontend_config(),
module, module,
&signatures, &signatures,
&memory_plans, &memory_styles,
&table_plans, &table_styles,
); );
context.func.name = get_func_name(func_index); context.func.name = get_func_name(func_index);
context.func.signature = signatures[module.functions[func_index]].clone(); context.func.signature = signatures[module.functions[func_index]].clone();
@@ -219,7 +219,7 @@ impl Compiler for CraneliftCompiler {
.into_iter() .into_iter()
.collect::<PrimaryMap<SignatureIndex, FunctionBody>>(); .collect::<PrimaryMap<SignatureIndex, FunctionBody>>();
use wasmer_runtime::VMOffsets; use wasmer_vm::VMOffsets;
let offsets = VMOffsets::new_for_trampolines(frontend_config.pointer_bytes()); let offsets = VMOffsets::new_for_trampolines(frontend_config.pointer_bytes());
// dynamic function trampolines (only for imported functions) // dynamic function trampolines (only for imported functions)
let dynamic_function_trampolines = module let dynamic_function_trampolines = module

View File

@@ -16,9 +16,9 @@ use wasm_common::entity::EntityRef;
use wasm_common::entity::PrimaryMap; use wasm_common::entity::PrimaryMap;
use wasm_common::{FunctionIndex, GlobalIndex, MemoryIndex, SignatureIndex, TableIndex}; use wasm_common::{FunctionIndex, GlobalIndex, MemoryIndex, SignatureIndex, TableIndex};
use wasmer_compiler::{WasmError, WasmResult}; use wasmer_compiler::{WasmError, WasmResult};
use wasmer_runtime::VMBuiltinFunctionIndex; use wasmer_vm::VMBuiltinFunctionIndex;
use wasmer_runtime::VMOffsets; use wasmer_vm::VMOffsets;
use wasmer_runtime::{MemoryPlan, MemoryStyle, ModuleInfo, TablePlan, TableStyle}; use wasmer_vm::{MemoryStyle, ModuleInfo, TableStyle};
/// Compute an `ir::ExternalName` for a given wasm function index. /// Compute an `ir::ExternalName` for a given wasm function index.
pub fn get_func_name(func_index: FunctionIndex) -> ir::ExternalName { pub fn get_func_name(func_index: FunctionIndex) -> ir::ExternalName {
@@ -84,11 +84,11 @@ pub struct FuncEnvironment<'module_environment> {
/// Offsets to struct fields accessed by JIT code. /// Offsets to struct fields accessed by JIT code.
offsets: VMOffsets, offsets: VMOffsets,
/// The memory plans /// The memory styles
memory_plans: &'module_environment PrimaryMap<MemoryIndex, MemoryPlan>, memory_styles: &'module_environment PrimaryMap<MemoryIndex, MemoryStyle>,
/// The table plans /// The table styles
table_plans: &'module_environment PrimaryMap<TableIndex, TablePlan>, table_styles: &'module_environment PrimaryMap<TableIndex, TableStyle>,
} }
impl<'module_environment> FuncEnvironment<'module_environment> { impl<'module_environment> FuncEnvironment<'module_environment> {
@@ -96,8 +96,8 @@ impl<'module_environment> FuncEnvironment<'module_environment> {
target_config: TargetFrontendConfig, target_config: TargetFrontendConfig,
module: &'module_environment ModuleInfo, module: &'module_environment ModuleInfo,
signatures: &'module_environment PrimaryMap<SignatureIndex, ir::Signature>, signatures: &'module_environment PrimaryMap<SignatureIndex, ir::Signature>,
memory_plans: &'module_environment PrimaryMap<MemoryIndex, MemoryPlan>, memory_styles: &'module_environment PrimaryMap<MemoryIndex, MemoryStyle>,
table_plans: &'module_environment PrimaryMap<TableIndex, TablePlan>, table_styles: &'module_environment PrimaryMap<TableIndex, TableStyle>,
) -> Self { ) -> Self {
Self { Self {
target_config, target_config,
@@ -114,8 +114,8 @@ impl<'module_environment> FuncEnvironment<'module_environment> {
memory_init_sig: None, memory_init_sig: None,
data_drop_sig: None, data_drop_sig: None,
offsets: VMOffsets::new(target_config.pointer_bytes(), module), offsets: VMOffsets::new(target_config.pointer_bytes(), module),
memory_plans, memory_styles,
table_plans, table_styles,
} }
} }
@@ -521,7 +521,7 @@ impl<'module_environment> BaseFuncEnvironment for FuncEnvironment<'module_enviro
readonly: false, readonly: false,
}); });
let element_size = match self.table_plans[index].style { let element_size = match self.table_styles[index] {
TableStyle::CallerChecksSignature => { TableStyle::CallerChecksSignature => {
u64::from(self.offsets.size_of_vmcaller_checked_anyfunc()) u64::from(self.offsets.size_of_vmcaller_checked_anyfunc())
} }
@@ -642,12 +642,8 @@ impl<'module_environment> BaseFuncEnvironment for FuncEnvironment<'module_enviro
// If we have a declared maximum, we can make this a "static" heap, which is // If we have a declared maximum, we can make this a "static" heap, which is
// allocated up front and never moved. // allocated up front and never moved.
let (offset_guard_size, heap_style, readonly_base) = match self.memory_plans[index] { let (offset_guard_size, heap_style, readonly_base) = match self.memory_styles[index] {
MemoryPlan { MemoryStyle::Dynamic { offset_guard_size } => {
style: MemoryStyle::Dynamic,
offset_guard_size,
memory: _,
} => {
let heap_bound = func.create_global_value(ir::GlobalValueData::Load { let heap_bound = func.create_global_value(ir::GlobalValueData::Load {
base: ptr, base: ptr,
offset: Offset32::new(current_length_offset), offset: Offset32::new(current_length_offset),
@@ -662,10 +658,9 @@ impl<'module_environment> BaseFuncEnvironment for FuncEnvironment<'module_enviro
false, false,
) )
} }
MemoryPlan { MemoryStyle::Static {
style: MemoryStyle::Static { bound }, bound,
offset_guard_size, offset_guard_size,
memory: _,
} => ( } => (
Uimm64::new(offset_guard_size), Uimm64::new(offset_guard_size),
ir::HeapStyle::Static { ir::HeapStyle::Static {
@@ -773,7 +768,7 @@ impl<'module_environment> BaseFuncEnvironment for FuncEnvironment<'module_enviro
pos.ins().trapz(func_addr, ir::TrapCode::IndirectCallToNull); pos.ins().trapz(func_addr, ir::TrapCode::IndirectCallToNull);
// If necessary, check the signature. // If necessary, check the signature.
match self.table_plans[table_index].style { match self.table_styles[table_index] {
TableStyle::CallerChecksSignature => { TableStyle::CallerChecksSignature => {
let sig_id_size = self.offsets.size_of_vmshared_signature_index(); let sig_id_size = self.offsets.size_of_vmshared_signature_index();
let sig_id_type = Type::int(u16::from(sig_id_size) * 8).unwrap(); let sig_id_type = Type::int(u16::from(sig_id_size) * 8).unwrap();

View File

@@ -6,7 +6,7 @@ use cranelift_codegen::ir::{self, ExternalName};
use wasm_common::entity::EntityRef; use wasm_common::entity::EntityRef;
use wasm_common::{FunctionIndex, LocalFunctionIndex}; use wasm_common::{FunctionIndex, LocalFunctionIndex};
use wasmer_compiler::{JumpTable, Relocation, RelocationTarget, SourceLoc, TrapInformation}; use wasmer_compiler::{JumpTable, Relocation, RelocationTarget, SourceLoc, TrapInformation};
use wasmer_runtime::{ModuleInfo, TrapCode}; use wasmer_vm::{ModuleInfo, TrapCode};
/// Implementation of a relocation sink that just saves all the information for later /// Implementation of a relocation sink that just saves all the information for later
pub(crate) struct RelocSink<'a> { pub(crate) struct RelocSink<'a> {

View File

@@ -18,7 +18,7 @@ use std::mem;
use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext}; use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext};
use wasm_common::FunctionType; use wasm_common::FunctionType;
use wasmer_compiler::{CompileError, FunctionBody}; use wasmer_compiler::{CompileError, FunctionBody};
use wasmer_runtime::VMOffsets; use wasmer_vm::VMOffsets;
/// Create a trampoline for invoking a WebAssembly function. /// Create a trampoline for invoking a WebAssembly function.
pub fn make_trampoline_dynamic_function( pub fn make_trampoline_dynamic_function(

View File

@@ -13,7 +13,7 @@ use wasmer_compiler::wasm_unsupported;
use wasmer_compiler::wasmparser; use wasmer_compiler::wasmparser;
use wasmer_compiler::{JumpTable, RelocationKind}; use wasmer_compiler::{JumpTable, RelocationKind};
use wasmer_compiler::{WasmError, WasmResult}; use wasmer_compiler::{WasmError, WasmResult};
use wasmer_runtime::libcalls::LibCall; use wasmer_vm::libcalls::LibCall;
/// Helper function translate a Function signature into Cranelift Ir /// Helper function translate a Function signature into Cranelift Ir
pub fn signature_to_cranelift_ir( pub fn signature_to_cranelift_ir(

View File

@@ -11,7 +11,7 @@ readme = "README.md"
[dependencies] [dependencies]
wasmer-compiler = { path = "../compiler", version = "1.0.0-alpha.1", features = ["translator"] } wasmer-compiler = { path = "../compiler", version = "1.0.0-alpha.1", features = ["translator"] }
wasmer-runtime = { path = "../runtime", version = "1.0.0-alpha.1" } wasmer-vm = { path = "../vm", version = "1.0.0-alpha.1" }
wasm-common = { path = "../wasm-common", version = "1.0.0-alpha.1" } wasm-common = { path = "../wasm-common", version = "1.0.0-alpha.1" }
target-lexicon = { version = "0.10", default-features = false } target-lexicon = { version = "0.10", default-features = false }
smallvec = "1" smallvec = "1"

View File

@@ -44,8 +44,8 @@ impl Compiler for LLVMCompiler {
) -> Result<Compilation, CompileError> { ) -> Result<Compilation, CompileError> {
//let data = Arc::new(Mutex::new(0)); //let data = Arc::new(Mutex::new(0));
let mut func_names = SecondaryMap::new(); let mut func_names = SecondaryMap::new();
let memory_plans = &compile_info.memory_plans; let memory_styles = &compile_info.memory_styles;
let table_plans = &compile_info.table_plans; let table_styles = &compile_info.table_styles;
let module = &compile_info.module; let module = &compile_info.module;
// TODO: merge constants in sections. // TODO: merge constants in sections.
@@ -78,8 +78,8 @@ impl Compiler for LLVMCompiler {
i, i,
input, input,
self.config(), self.config(),
&memory_plans, memory_styles,
&table_plans, &table_styles,
&func_names, &func_names,
) )
}, },

View File

@@ -7,7 +7,7 @@ use wasmer_compiler::{
CustomSections, FunctionAddressMap, FunctionBody, InstructionAddressMap, Relocation, CustomSections, FunctionAddressMap, FunctionBody, InstructionAddressMap, Relocation,
RelocationKind, RelocationTarget, SectionBody, SectionIndex, SourceLoc, RelocationKind, RelocationTarget, SectionBody, SectionIndex, SourceLoc,
}; };
use wasmer_runtime::libcalls::LibCall; use wasmer_vm::libcalls::LibCall;
use wasm_common::entity::entity_impl; use wasm_common::entity::entity_impl;
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)] #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]

View File

@@ -34,7 +34,7 @@ use wasmer_compiler::{
to_wasm_error, wptype_to_type, CompileError, FunctionBodyData, GenerateMiddlewareChain, to_wasm_error, wptype_to_type, CompileError, FunctionBodyData, GenerateMiddlewareChain,
MiddlewareBinaryReader, ModuleTranslationState, RelocationTarget, MiddlewareBinaryReader, ModuleTranslationState, RelocationTarget,
}; };
use wasmer_runtime::{MemoryPlan, ModuleInfo, TablePlan}; use wasmer_vm::{MemoryStyle, ModuleInfo, TableStyle};
fn to_compile_error(err: impl std::error::Error) -> CompileError { fn to_compile_error(err: impl std::error::Error) -> CompileError {
CompileError::Codegen(format!("{}", err)) CompileError::Codegen(format!("{}", err))
@@ -72,8 +72,8 @@ impl FuncTranslator {
local_func_index: &LocalFunctionIndex, local_func_index: &LocalFunctionIndex,
function_body: &FunctionBodyData, function_body: &FunctionBodyData,
config: &LLVM, config: &LLVM,
memory_plans: &PrimaryMap<MemoryIndex, MemoryPlan>, memory_styles: &PrimaryMap<MemoryIndex, MemoryStyle>,
_table_plans: &PrimaryMap<TableIndex, TablePlan>, _table_styles: &PrimaryMap<TableIndex, TableStyle>,
func_names: &SecondaryMap<FunctionIndex, String>, func_names: &SecondaryMap<FunctionIndex, String>,
) -> Result<CompiledFunction, CompileError> { ) -> Result<CompiledFunction, CompileError> {
// The function type, used for the callbacks. // The function type, used for the callbacks.
@@ -198,8 +198,8 @@ impl FuncTranslator {
locals: params_locals, locals: params_locals,
ctx: CtxType::new(wasm_module, &func, &cache_builder), ctx: CtxType::new(wasm_module, &func, &cache_builder),
unreachable_depth: 0, unreachable_depth: 0,
memory_plans, memory_styles,
_table_plans, _table_styles,
module: &module, module: &module,
module_translation, module_translation,
wasm_module, wasm_module,
@@ -908,7 +908,7 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> {
memory_index, memory_index,
self.intrinsics, self.intrinsics,
self.module, self.module,
self.memory_plans, self.memory_styles,
) { ) {
// The best we've got is `volatile`. // The best we've got is `volatile`.
// TODO: convert unwrap fail to CompileError // TODO: convert unwrap fail to CompileError
@@ -962,14 +962,14 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> {
let base_ptr = let base_ptr =
match self match self
.ctx .ctx
.memory(memory_index, intrinsics, self.module, self.memory_plans) .memory(memory_index, intrinsics, self.module, self.memory_styles)
{ {
MemoryCache::Dynamic { MemoryCache::Dynamic {
ptr_to_base_ptr, ptr_to_base_ptr,
current_length_ptr, current_length_ptr,
} => { } => {
// Bounds check it. // Bounds check it.
let minimum = self.memory_plans[memory_index].memory.minimum; let minimum = self.wasm_module.memories[memory_index].minimum;
let value_size_v = intrinsics.i64_ty.const_int(value_size as u64, false); let value_size_v = intrinsics.i64_ty.const_int(value_size as u64, false);
let ptr_in_bounds = if offset.is_const() { let ptr_in_bounds = if offset.is_const() {
// When the offset is constant, if it's below the minimum // When the offset is constant, if it's below the minimum
@@ -1264,8 +1264,8 @@ pub struct LLVMFunctionCodeGenerator<'ctx, 'a> {
locals: Vec<PointerValue<'ctx>>, // Contains params and locals locals: Vec<PointerValue<'ctx>>, // Contains params and locals
ctx: CtxType<'ctx, 'a>, ctx: CtxType<'ctx, 'a>,
unreachable_depth: usize, unreachable_depth: usize,
memory_plans: &'a PrimaryMap<MemoryIndex, MemoryPlan>, memory_styles: &'a PrimaryMap<MemoryIndex, MemoryStyle>,
_table_plans: &'a PrimaryMap<TableIndex, TablePlan>, _table_styles: &'a PrimaryMap<TableIndex, TableStyle>,
// This is support for stackmaps: // This is support for stackmaps:
/* /*

View File

@@ -26,8 +26,8 @@ use wasm_common::{
TableIndex, Type, TableIndex, Type,
}; };
use wasmer_compiler::CompileError; use wasmer_compiler::CompileError;
use wasmer_runtime::ModuleInfo as WasmerCompilerModule; use wasmer_vm::ModuleInfo as WasmerCompilerModule;
use wasmer_runtime::{MemoryPlan, MemoryStyle, TrapCode, VMBuiltinFunctionIndex, VMOffsets}; use wasmer_vm::{MemoryStyle, TrapCode, VMBuiltinFunctionIndex, VMOffsets};
pub fn type_to_llvm_ptr<'ctx>( pub fn type_to_llvm_ptr<'ctx>(
intrinsics: &Intrinsics<'ctx>, intrinsics: &Intrinsics<'ctx>,
@@ -569,7 +569,7 @@ impl<'ctx, 'a> CtxType<'ctx, 'a> {
index: MemoryIndex, index: MemoryIndex,
intrinsics: &Intrinsics<'ctx>, intrinsics: &Intrinsics<'ctx>,
module: &Module<'ctx>, module: &Module<'ctx>,
memory_plans: &PrimaryMap<MemoryIndex, MemoryPlan>, memory_styles: &PrimaryMap<MemoryIndex, MemoryStyle>,
) -> MemoryCache<'ctx> { ) -> MemoryCache<'ctx> {
let (cached_memories, wasm_module, ctx_ptr_value, cache_builder, offsets) = ( let (cached_memories, wasm_module, ctx_ptr_value, cache_builder, offsets) = (
&mut self.cached_memories, &mut self.cached_memories,
@@ -578,7 +578,7 @@ impl<'ctx, 'a> CtxType<'ctx, 'a> {
&self.cache_builder, &self.cache_builder,
&self.offsets, &self.offsets,
); );
let memory_plan = &memory_plans[index]; let memory_style = &memory_styles[index];
*cached_memories.entry(index).or_insert_with(|| { *cached_memories.entry(index).or_insert_with(|| {
let memory_definition_ptr = let memory_definition_ptr =
if let Some(local_memory_index) = wasm_module.local_memory_index(index) { if let Some(local_memory_index) = wasm_module.local_memory_index(index) {
@@ -622,7 +622,7 @@ impl<'ctx, 'a> CtxType<'ctx, 'a> {
"", "",
) )
.unwrap(); .unwrap();
if memory_plan.style == MemoryStyle::Dynamic { if let MemoryStyle::Dynamic { .. } = memory_style {
let current_length_ptr = cache_builder let current_length_ptr = cache_builder
.build_struct_gep( .build_struct_gep(
memory_definition_ptr, memory_definition_ptr,

View File

@@ -2,8 +2,8 @@
use byteorder::{LittleEndian, ReadBytesExt}; use byteorder::{LittleEndian, ReadBytesExt};
use std::io::{self, Cursor}; use std::io::{self, Cursor};
use wasmer_runtime_core::vm::Ctx; use wasmer_vm_core::vm::Ctx;
use wasmer_runtime_core::{ use wasmer_vm_core::{
module::Module, module::Module,
structures::TypedIndex, structures::TypedIndex,
types::{GlobalIndex, LocalOrImport, TableIndex}, types::{GlobalIndex, LocalOrImport, TableIndex},
@@ -65,15 +65,15 @@ impl StackmapEntry {
size_record: &StkSizeRecord, size_record: &StkSizeRecord,
map_record: &StkMapRecord, map_record: &StkMapRecord,
end: Option<(&StackmapEntry, &StkMapRecord)>, end: Option<(&StackmapEntry, &StkMapRecord)>,
msm: &mut wasmer_runtime_core::state::ModuleStateMap, msm: &mut wasmer_vm_core::state::ModuleStateMap,
) { ) {
use std::collections::{BTreeMap, HashMap}; use std::collections::{BTreeMap, HashMap};
use wasmer_runtime_core::state::{ use wasmer_vm_core::state::{
x64::{new_machine_state, X64Register, GPR}, x64::{new_machine_state, X64Register, GPR},
FunctionStateMap, MachineStateDiff, MachineValue, OffsetInfo, RegisterIndex, FunctionStateMap, MachineStateDiff, MachineValue, OffsetInfo, RegisterIndex,
SuspendOffset, WasmAbstractValue, SuspendOffset, WasmAbstractValue,
}; };
use wasmer_runtime_core::vm; use wasmer_vm_core::vm;
let func_base_addr = (size_record.function_address as usize) let func_base_addr = (size_record.function_address as usize)
.checked_sub(code_addr) .checked_sub(code_addr)

View File

@@ -13,10 +13,10 @@ edition = "2018"
[dependencies] [dependencies]
wasmer-compiler = { path = "../compiler", version = "1.0.0-alpha.1", features = ["translator"], default-features = false } wasmer-compiler = { path = "../compiler", version = "1.0.0-alpha.1", features = ["translator"], default-features = false }
wasmer-runtime = { path = "../runtime", version = "1.0.0-alpha.1" } wasmer-vm = { path = "../vm", version = "1.0.0-alpha.1" }
wasm-common = { path = "../wasm-common", version = "1.0.0-alpha.1", default-features = false } wasm-common = { path = "../wasm-common", version = "1.0.0-alpha.1", default-features = false }
rayon = "1.3" rayon = "1.3"
hashbrown = { version = "0.7", optional = true } hashbrown = { version = "0.8", optional = true }
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
more-asserts = "0.2" more-asserts = "0.2"
dynasm = "0.6" dynasm = "0.6"

View File

@@ -19,9 +19,7 @@ use wasmer_compiler::{
FunctionBody, Relocation, RelocationKind, RelocationTarget, SectionBody, SectionIndex, FunctionBody, Relocation, RelocationKind, RelocationTarget, SectionBody, SectionIndex,
TrapInformation, TrapInformation,
}; };
use wasmer_runtime::{ use wasmer_vm::{MemoryStyle, ModuleInfo, TableStyle, TrapCode, VMBuiltinFunctionIndex, VMOffsets};
MemoryPlan, MemoryStyle, ModuleInfo, TablePlan, TrapCode, VMBuiltinFunctionIndex, VMOffsets,
};
/// The singlepass per-function code generator. /// The singlepass per-function code generator.
pub struct FuncGen<'a> { pub struct FuncGen<'a> {
@@ -36,10 +34,10 @@ pub struct FuncGen<'a> {
vmoffsets: &'a VMOffsets, vmoffsets: &'a VMOffsets,
// // Memory plans. // // Memory plans.
memory_plans: &'a PrimaryMap<MemoryIndex, MemoryPlan>, memory_styles: &'a PrimaryMap<MemoryIndex, MemoryStyle>,
// // Table plans. // // Table plans.
// table_plans: &'a PrimaryMap<TableIndex, TablePlan>, // table_styles: &'a PrimaryMap<TableIndex, TableStyle>,
/// Function signature. /// Function signature.
signature: FunctionType, signature: FunctionType,
@@ -1226,9 +1224,9 @@ impl<'a> FuncGen<'a> {
value_size: usize, value_size: usize,
cb: F, cb: F,
) -> Result<(), CodegenError> { ) -> Result<(), CodegenError> {
let need_check = match self.memory_plans[MemoryIndex::new(0)].style { let need_check = match self.memory_styles[MemoryIndex::new(0)] {
MemoryStyle::Static { .. } => false, MemoryStyle::Static { .. } => false,
MemoryStyle::Dynamic => true, MemoryStyle::Dynamic { .. } => true,
}; };
let tmp_addr = self.machine.acquire_temp_gpr().unwrap(); let tmp_addr = self.machine.acquire_temp_gpr().unwrap();
@@ -1778,8 +1776,8 @@ impl<'a> FuncGen<'a> {
module: &'a ModuleInfo, module: &'a ModuleInfo,
config: &'a Singlepass, config: &'a Singlepass,
vmoffsets: &'a VMOffsets, vmoffsets: &'a VMOffsets,
memory_plans: &'a PrimaryMap<MemoryIndex, MemoryPlan>, memory_styles: &'a PrimaryMap<MemoryIndex, MemoryStyle>,
_table_plans: &'a PrimaryMap<TableIndex, TablePlan>, _table_styles: &'a PrimaryMap<TableIndex, TableStyle>,
local_func_index: LocalFunctionIndex, local_func_index: LocalFunctionIndex,
local_types_excluding_arguments: &[WpType], local_types_excluding_arguments: &[WpType],
) -> Result<FuncGen<'a>, CodegenError> { ) -> Result<FuncGen<'a>, CodegenError> {
@@ -1816,8 +1814,8 @@ impl<'a> FuncGen<'a> {
module, module,
config, config,
vmoffsets, vmoffsets,
memory_plans, memory_styles,
// table_plans, // table_styles,
signature, signature,
assembler, assembler,
locals: vec![], // initialization deferred to emit_head locals: vec![], // initialization deferred to emit_head

View File

@@ -19,7 +19,7 @@ use wasmer_compiler::{
ModuleTranslationState, Target, ModuleTranslationState, Target,
}; };
use wasmer_compiler::{FunctionBody, FunctionBodyData}; use wasmer_compiler::{FunctionBody, FunctionBodyData};
use wasmer_runtime::{ModuleInfo, TrapCode, VMOffsets}; use wasmer_vm::{ModuleInfo, TrapCode, VMOffsets};
/// A compiler that compiles a WebAssembly module with Singlepass. /// A compiler that compiles a WebAssembly module with Singlepass.
/// It does the compilation in one pass /// It does the compilation in one pass
@@ -55,8 +55,8 @@ impl Compiler for SinglepassCompiler {
return Err(CompileError::UnsupportedFeature("multivalue".to_string())); return Err(CompileError::UnsupportedFeature("multivalue".to_string()));
} }
let vmoffsets = VMOffsets::new(8, &compile_info.module); let vmoffsets = VMOffsets::new(8, &compile_info.module);
let memory_plans = &compile_info.memory_plans; let memory_styles = &compile_info.memory_styles;
let table_plans = &compile_info.table_plans; let table_styles = &compile_info.table_styles;
let module = &compile_info.module; let module = &compile_info.module;
let import_trampolines: PrimaryMap<SectionIndex, _> = (0..module.num_imported_funcs) let import_trampolines: PrimaryMap<SectionIndex, _> = (0..module.num_imported_funcs)
.map(FunctionIndex::new) .map(FunctionIndex::new)
@@ -95,8 +95,8 @@ impl Compiler for SinglepassCompiler {
module, module,
&self.config, &self.config,
&vmoffsets, &vmoffsets,
&memory_plans, &memory_styles,
&table_plans, &table_styles,
*i, *i,
&locals, &locals,
) )

View File

@@ -11,12 +11,12 @@ keywords = ["webassembly", "wasm", "compiler"]
edition = "2018" edition = "2018"
[dependencies] [dependencies]
wasmer-runtime = { path = "../runtime", version = "1.0.0-alpha.1" } wasmer-vm = { path = "../vm", version = "1.0.0-alpha.1" }
wasm-common = { path = "../wasm-common", version = "1.0.0-alpha.1" } wasm-common = { path = "../wasm-common", version = "1.0.0-alpha.1" }
wasmparser = { version = "0.57", optional = true, default-features = false } wasmparser = { version = "0.57", optional = true, default-features = false }
target-lexicon = { version = "0.10", default-features = false } target-lexicon = { version = "0.10", default-features = false }
enumset = "1.0" enumset = "1.0"
hashbrown = { version = "0.7", optional = true } hashbrown = { version = "0.8", optional = true }
serde = { version = "1.0", features = ["derive"], optional = true } serde = { version = "1.0", features = ["derive"], optional = true }
thiserror = "1.0" thiserror = "1.0"
serde_bytes = { version = "0.11", optional = true } serde_bytes = { version = "0.11", optional = true }

View File

@@ -3,13 +3,13 @@ use serde::{Deserialize, Serialize};
use std::sync::Arc; use std::sync::Arc;
use wasm_common::entity::PrimaryMap; use wasm_common::entity::PrimaryMap;
use wasm_common::{Features, MemoryIndex, TableIndex}; use wasm_common::{Features, MemoryIndex, TableIndex};
use wasmer_runtime::{MemoryPlan, ModuleInfo, TablePlan}; use wasmer_vm::{MemoryStyle, ModuleInfo, TableStyle};
/// The required info for compiling a module. /// The required info for compiling a module.
/// ///
/// This differs from [`ModuleInfo`] because it have extra info only /// This differs from [`ModuleInfo`] because it have extra info only
/// possible after translation (such as the features used for compiling, /// possible after translation (such as the features used for compiling,
/// or the `MemoryPlan` and `TablePlan`). /// or the `MemoryStyle` and `TableStyle`).
#[derive(Debug)] #[derive(Debug)]
#[cfg_attr(feature = "enable-serde", derive(Deserialize, Serialize))] #[cfg_attr(feature = "enable-serde", derive(Deserialize, Serialize))]
pub struct CompileModuleInfo { pub struct CompileModuleInfo {
@@ -17,11 +17,11 @@ pub struct CompileModuleInfo {
pub features: Features, pub features: Features,
/// The module information /// The module information
pub module: Arc<ModuleInfo>, pub module: Arc<ModuleInfo>,
/// The memory plans used for compiling. /// The memory styles used for compiling.
/// ///
/// The compiler will emit the most optimal code based /// The compiler will emit the most optimal code based
/// on the memory style (static or dynamic) chosen. /// on the memory style (static or dynamic) chosen.
pub memory_plans: PrimaryMap<MemoryIndex, MemoryPlan>, pub memory_styles: PrimaryMap<MemoryIndex, MemoryStyle>,
/// The table plans used for compiling. /// The table plans used for compiling.
pub table_plans: PrimaryMap<TableIndex, TablePlan>, pub table_styles: PrimaryMap<TableIndex, TableStyle>,
} }

View File

@@ -17,7 +17,7 @@ use crate::{Addend, CodeOffset, JumpTable};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use wasm_common::entity::PrimaryMap; use wasm_common::entity::PrimaryMap;
use wasm_common::LocalFunctionIndex; use wasm_common::LocalFunctionIndex;
use wasmer_runtime::libcalls::LibCall; use wasmer_vm::libcalls::LibCall;
/// Relocation kinds for every ISA. /// Relocation kinds for every ISA.
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]

View File

@@ -16,7 +16,7 @@ use wasm_common::{
ExportIndex, FunctionIndex, GlobalIndex, GlobalInit, GlobalType, ImportIndex, ExportIndex, FunctionIndex, GlobalIndex, GlobalInit, GlobalType, ImportIndex,
LocalFunctionIndex, MemoryIndex, MemoryType, SignatureIndex, TableIndex, TableType, LocalFunctionIndex, MemoryIndex, MemoryType, SignatureIndex, TableIndex, TableType,
}; };
use wasmer_runtime::{ModuleInfo, TableElements}; use wasmer_vm::{ModuleInfo, TableElements};
/// Contains function data: bytecode and its offset in the module. /// Contains function data: bytecode and its offset in the module.
#[derive(Hash)] #[derive(Hash)]

View File

@@ -2,7 +2,7 @@ use crate::sourceloc::SourceLoc;
use crate::CodeOffset; use crate::CodeOffset;
#[cfg(feature = "enable-serde")] #[cfg(feature = "enable-serde")]
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use wasmer_runtime::TrapCode; use wasmer_vm::TrapCode;
/// Information about trap. /// Information about trap.
#[cfg_attr(feature = "enable-serde", derive(Deserialize, Serialize))] #[cfg_attr(feature = "enable-serde", derive(Deserialize, Serialize))]

View File

@@ -12,7 +12,7 @@ edition = "2018"
[dependencies] [dependencies]
byteorder = "1.3" byteorder = "1.3"
lazy_static = "1.4" lazy_static = "1.4"
libc = "0.2.60" libc = "0.2.72"
log = "0.4" log = "0.4"
time = "0.1" time = "0.1"
wasmer = { path = "../api", version = "1.0.0-alpha.1" } wasmer = { path = "../api", version = "1.0.0-alpha.1" }

View File

@@ -13,13 +13,13 @@ edition = "2018"
[dependencies] [dependencies]
wasm-common = { path = "../wasm-common", version = "1.0.0-alpha.1" } wasm-common = { path = "../wasm-common", version = "1.0.0-alpha.1" }
wasmer-compiler = { path = "../compiler", version = "1.0.0-alpha.1", default-features = false } wasmer-compiler = { path = "../compiler", version = "1.0.0-alpha.1", default-features = false }
wasmer-runtime = { path = "../runtime", version = "1.0.0-alpha.1" } wasmer-vm = { path = "../vm", version = "1.0.0-alpha.1" }
wasmer-engine = { path = "../engine", version = "1.0.0-alpha.1" } wasmer-engine = { path = "../engine", version = "1.0.0-alpha.1" }
# flexbuffers = { path = "../../../flatbuffers/rust/flexbuffers", version = "0.1.0" } # flexbuffers = { path = "../../../flatbuffers/rust/flexbuffers", version = "0.1.0" }
region = "2.1" region = "2.2"
serde = { version = "1.0", features = ["derive", "rc"] } serde = { version = "1.0", features = ["derive", "rc"] }
serde_bytes = { version = "0.11" } serde_bytes = { version = "0.11" }
bincode = "1.2" bincode = "1.3"
cfg-if = "0.1" cfg-if = "0.1"
[target.'cfg(target_os = "windows")'.dependencies] [target.'cfg(target_os = "windows")'.dependencies]

View File

@@ -22,7 +22,7 @@ use wasmer_engine::{
}; };
#[cfg(feature = "compiler")] #[cfg(feature = "compiler")]
use wasmer_engine::{Engine, SerializableFunctionFrameInfo}; use wasmer_engine::{Engine, SerializableFunctionFrameInfo};
use wasmer_runtime::{FunctionBodyPtr, MemoryPlan, ModuleInfo, TablePlan, VMSharedSignatureIndex}; use wasmer_vm::{FunctionBodyPtr, MemoryStyle, ModuleInfo, TableStyle, VMSharedSignatureIndex};
/// A compiled wasm module, ready to be instantiated. /// A compiled wasm module, ready to be instantiated.
pub struct JITArtifact { pub struct JITArtifact {
@@ -55,24 +55,24 @@ impl JITArtifact {
let translation = environ.translate(data).map_err(CompileError::Wasm)?; let translation = environ.translate(data).map_err(CompileError::Wasm)?;
let memory_plans: PrimaryMap<MemoryIndex, MemoryPlan> = translation let memory_styles: PrimaryMap<MemoryIndex, MemoryStyle> = translation
.module .module
.memories .memories
.values() .values()
.map(|memory_type| tunables.memory_plan(*memory_type)) .map(|memory_type| tunables.memory_style(memory_type))
.collect(); .collect();
let table_plans: PrimaryMap<TableIndex, TablePlan> = translation let table_styles: PrimaryMap<TableIndex, TableStyle> = translation
.module .module
.tables .tables
.values() .values()
.map(|table_type| tunables.table_plan(*table_type)) .map(|table_type| tunables.table_style(table_type))
.collect(); .collect();
let compile_info = CompileModuleInfo { let compile_info = CompileModuleInfo {
module: Arc::new(translation.module), module: Arc::new(translation.module),
features: features.clone(), features: features.clone(),
memory_plans, memory_styles,
table_plans, table_styles,
}; };
let compiler = inner_jit.compiler()?; let compiler = inner_jit.compiler()?;
@@ -271,12 +271,12 @@ impl Artifact for JITArtifact {
&*self.serializable.data_initializers &*self.serializable.data_initializers
} }
fn memory_plans(&self) -> &PrimaryMap<MemoryIndex, MemoryPlan> { fn memory_styles(&self) -> &PrimaryMap<MemoryIndex, MemoryStyle> {
&self.serializable.compile_info.memory_plans &self.serializable.compile_info.memory_styles
} }
fn table_plans(&self) -> &PrimaryMap<TableIndex, TablePlan> { fn table_styles(&self) -> &PrimaryMap<TableIndex, TableStyle> {
&self.serializable.compile_info.table_plans &self.serializable.compile_info.table_styles
} }
fn finished_functions(&self) -> &BoxedSlice<LocalFunctionIndex, FunctionBodyPtr> { fn finished_functions(&self) -> &BoxedSlice<LocalFunctionIndex, FunctionBodyPtr> {

View File

@@ -8,7 +8,7 @@ use std::sync::Arc;
use std::{cmp, mem}; use std::{cmp, mem};
use wasm_common::entity::{EntityRef, PrimaryMap}; use wasm_common::entity::{EntityRef, PrimaryMap};
use wasmer_compiler::{CompiledFunctionUnwindInfo, FunctionBody, SectionBody}; use wasmer_compiler::{CompiledFunctionUnwindInfo, FunctionBody, SectionBody};
use wasmer_runtime::{FunctionBodyPtr, Mmap, VMFunctionBody}; use wasmer_vm::{FunctionBodyPtr, Mmap, VMFunctionBody};
/// The optimal alignment for functions. /// The optimal alignment for functions.
/// ///

View File

@@ -13,7 +13,7 @@ use wasmer_compiler::{
CompileError, CustomSection, CustomSectionProtection, FunctionBody, SectionIndex, Target, CompileError, CustomSection, CustomSectionProtection, FunctionBody, SectionIndex, Target,
}; };
use wasmer_engine::{Artifact, DeserializeError, Engine, EngineId, Tunables}; use wasmer_engine::{Artifact, DeserializeError, Engine, EngineId, Tunables};
use wasmer_runtime::{ use wasmer_vm::{
FunctionBodyPtr, ModuleInfo, SignatureRegistry, VMFunctionBody, VMSharedSignatureIndex, FunctionBodyPtr, ModuleInfo, SignatureRegistry, VMFunctionBody, VMSharedSignatureIndex,
VMTrampoline, VMTrampoline,
}; };

View File

@@ -7,8 +7,8 @@ use wasmer_compiler::{
JumpTable, JumpTableOffsets, Relocation, RelocationKind, RelocationTarget, Relocations, JumpTable, JumpTableOffsets, Relocation, RelocationKind, RelocationTarget, Relocations,
SectionIndex, SectionIndex,
}; };
use wasmer_runtime::ModuleInfo; use wasmer_vm::ModuleInfo;
use wasmer_runtime::{FunctionBodyPtr, VMFunctionBody}; use wasmer_vm::{FunctionBodyPtr, VMFunctionBody};
fn apply_relocation( fn apply_relocation(
body: usize, body: usize,

View File

@@ -13,14 +13,14 @@ edition = "2018"
[dependencies] [dependencies]
wasm-common = { path = "../wasm-common", version = "1.0.0-alpha.1" } wasm-common = { path = "../wasm-common", version = "1.0.0-alpha.1" }
wasmer-compiler = { path = "../compiler", version = "1.0.0-alpha.1", default-features = false } wasmer-compiler = { path = "../compiler", version = "1.0.0-alpha.1", default-features = false }
wasmer-runtime = { path = "../runtime", version = "1.0.0-alpha.1" } wasmer-vm = { path = "../vm", version = "1.0.0-alpha.1" }
wasmer-engine = { path = "../engine", version = "1.0.0-alpha.1" } wasmer-engine = { path = "../engine", version = "1.0.0-alpha.1" }
wasmer-object = { path = "../object", version = "1.0.0-alpha.1" } wasmer-object = { path = "../object", version = "1.0.0-alpha.1" }
serde = { version = "1.0", features = ["derive", "rc"] } serde = { version = "1.0", features = ["derive", "rc"] }
serde_bytes = { version = "0.11" } serde_bytes = { version = "0.11" }
cfg-if = "0.1" cfg-if = "0.1"
tracing = "0.1" tracing = "0.1"
bincode = "1.2" bincode = "1.3"
leb128 = "0.2" leb128 = "0.2"
libloading = "0.6" libloading = "0.6"
tempfile = "3.1" tempfile = "3.1"

View File

@@ -32,10 +32,10 @@ use wasmer_engine::{
}; };
#[cfg(feature = "compiler")] #[cfg(feature = "compiler")]
use wasmer_object::{emit_compilation, emit_data, get_object_for_target, CompilationNamer}; use wasmer_object::{emit_compilation, emit_data, get_object_for_target, CompilationNamer};
use wasmer_runtime::{ use wasmer_vm::{
FunctionBodyPtr, ModuleInfo, VMFunctionBody, VMSharedSignatureIndex, VMTrampoline, FunctionBodyPtr, ModuleInfo, VMFunctionBody, VMSharedSignatureIndex, VMTrampoline,
}; };
use wasmer_runtime::{MemoryPlan, TablePlan}; use wasmer_vm::{MemoryStyle, TableStyle};
/// A compiled wasm module, ready to be instantiated. /// A compiled wasm module, ready to be instantiated.
pub struct NativeArtifact { pub struct NativeArtifact {
@@ -103,24 +103,24 @@ impl NativeArtifact {
) -> Result<(CompileModuleInfo, Compilation, Vec<DataInitializer<'data>>), CompileError> { ) -> Result<(CompileModuleInfo, Compilation, Vec<DataInitializer<'data>>), CompileError> {
let environ = ModuleEnvironment::new(); let environ = ModuleEnvironment::new();
let translation = environ.translate(data).map_err(CompileError::Wasm)?; let translation = environ.translate(data).map_err(CompileError::Wasm)?;
let memory_plans: PrimaryMap<MemoryIndex, MemoryPlan> = translation let memory_styles: PrimaryMap<MemoryIndex, MemoryStyle> = translation
.module .module
.memories .memories
.values() .values()
.map(|memory_type| tunables.memory_plan(*memory_type)) .map(|memory_type| tunables.memory_style(memory_type))
.collect(); .collect();
let table_plans: PrimaryMap<TableIndex, TablePlan> = translation let table_styles: PrimaryMap<TableIndex, TableStyle> = translation
.module .module
.tables .tables
.values() .values()
.map(|table_type| tunables.table_plan(*table_type)) .map(|table_type| tunables.table_style(table_type))
.collect(); .collect();
let compile_info = CompileModuleInfo { let compile_info = CompileModuleInfo {
module: Arc::new(translation.module), module: Arc::new(translation.module),
features: features.clone(), features: features.clone(),
memory_plans, memory_styles,
table_plans, table_styles,
}; };
// Compile the Module // Compile the Module
@@ -519,12 +519,12 @@ impl Artifact for NativeArtifact {
&*self.metadata.data_initializers &*self.metadata.data_initializers
} }
fn memory_plans(&self) -> &PrimaryMap<MemoryIndex, MemoryPlan> { fn memory_styles(&self) -> &PrimaryMap<MemoryIndex, MemoryStyle> {
&self.metadata.compile_info.memory_plans &self.metadata.compile_info.memory_styles
} }
fn table_plans(&self) -> &PrimaryMap<TableIndex, TablePlan> { fn table_styles(&self) -> &PrimaryMap<TableIndex, TableStyle> {
&self.metadata.compile_info.table_plans &self.metadata.compile_info.table_styles
} }
fn finished_functions(&self) -> &BoxedSlice<LocalFunctionIndex, FunctionBodyPtr> { fn finished_functions(&self) -> &BoxedSlice<LocalFunctionIndex, FunctionBodyPtr> {

View File

@@ -10,7 +10,7 @@ use wasm_common::{Features, FunctionType};
use wasmer_compiler::Compiler; use wasmer_compiler::Compiler;
use wasmer_compiler::{CompileError, Target}; use wasmer_compiler::{CompileError, Target};
use wasmer_engine::{Artifact, DeserializeError, Engine, EngineId, Tunables}; use wasmer_engine::{Artifact, DeserializeError, Engine, EngineId, Tunables};
use wasmer_runtime::{SignatureRegistry, VMSharedSignatureIndex, VMTrampoline}; use wasmer_vm::{SignatureRegistry, VMSharedSignatureIndex, VMTrampoline};
/// A WebAssembly `Native` Engine. /// A WebAssembly `Native` Engine.
#[derive(Clone)] #[derive(Clone)]

View File

@@ -13,17 +13,16 @@ edition = "2018"
[dependencies] [dependencies]
wasm-common = { path = "../wasm-common", version = "1.0.0-alpha.1" } wasm-common = { path = "../wasm-common", version = "1.0.0-alpha.1" }
wasmer-compiler = { path = "../compiler", version = "1.0.0-alpha.1", default-features = false } wasmer-compiler = { path = "../compiler", version = "1.0.0-alpha.1", default-features = false }
wasmer-runtime = { path = "../runtime", version = "1.0.0-alpha.1" } wasmer-vm = { path = "../vm", version = "1.0.0-alpha.1" }
target-lexicon = { version = "0.10", default-features = false } target-lexicon = { version = "0.10", default-features = false }
# flexbuffers = { path = "../../../flatbuffers/rust/flexbuffers", version = "0.1.0" } # flexbuffers = { path = "../../../flatbuffers/rust/flexbuffers", version = "0.1.0" }
backtrace = "0.3" backtrace = "0.3"
rustc-demangle = "0.1" rustc-demangle = "0.1"
more-asserts = "0.2" more-asserts = "0.2"
thiserror = "1.0" thiserror = "1.0"
region = "2.1"
serde = { version = "1.0", features = ["derive", "rc"] } serde = { version = "1.0", features = ["derive", "rc"] }
serde_bytes = { version = "0.11" } serde_bytes = { version = "0.11" }
bincode = "1.2" bincode = "1.3"
lazy_static = "1.4" lazy_static = "1.4"
[target.'cfg(target_os = "windows")'.dependencies] [target.'cfg(target_os = "windows")'.dependencies]

View File

@@ -11,8 +11,8 @@ use wasm_common::{
SignatureIndex, TableIndex, SignatureIndex, TableIndex,
}; };
use wasmer_compiler::Features; use wasmer_compiler::Features;
use wasmer_runtime::{ use wasmer_vm::{
FunctionBodyPtr, InstanceHandle, MemoryPlan, ModuleInfo, TablePlan, VMSharedSignatureIndex, FunctionBodyPtr, InstanceHandle, MemoryStyle, ModuleInfo, TableStyle, VMSharedSignatureIndex,
}; };
/// An `Artifact` is the product that the `Engine` /// An `Artifact` is the product that the `Engine`
@@ -41,11 +41,11 @@ pub trait Artifact: Send + Sync {
/// Returns the features for this Artifact /// Returns the features for this Artifact
fn features(&self) -> &Features; fn features(&self) -> &Features;
/// Returns the memory plans associated with this `Artifact`. /// Returns the memory styles associated with this `Artifact`.
fn memory_plans(&self) -> &PrimaryMap<MemoryIndex, MemoryPlan>; fn memory_styles(&self) -> &PrimaryMap<MemoryIndex, MemoryStyle>;
/// Returns the table plans associated with this `Artifact`. /// Returns the table plans associated with this `Artifact`.
fn table_plans(&self) -> &PrimaryMap<TableIndex, TablePlan>; fn table_styles(&self) -> &PrimaryMap<TableIndex, TableStyle>;
/// Returns data initializers to pass to `InstanceHandle::initialize` /// Returns data initializers to pass to `InstanceHandle::initialize`
fn data_initializers(&self) -> &[OwnedDataInitializer]; fn data_initializers(&self) -> &[OwnedDataInitializer];
@@ -94,16 +94,16 @@ pub trait Artifact: Send + Sync {
&module, &module,
resolver, resolver,
&self.finished_dynamic_function_trampolines(), &self.finished_dynamic_function_trampolines(),
self.memory_plans(), self.memory_styles(),
self.table_plans(), self.table_styles(),
) )
.map_err(InstantiationError::Link)?; .map_err(InstantiationError::Link)?;
let finished_memories = tunables let finished_memories = tunables
.create_memories(&module, self.memory_plans()) .create_memories(&module, self.memory_styles())
.map_err(InstantiationError::Link)? .map_err(InstantiationError::Link)?
.into_boxed_slice(); .into_boxed_slice();
let finished_tables = tunables let finished_tables = tunables
.create_tables(&module, self.table_plans()) .create_tables(&module, self.table_styles())
.map_err(InstantiationError::Link)? .map_err(InstantiationError::Link)?
.into_boxed_slice(); .into_boxed_slice();
let finished_globals = tunables let finished_globals = tunables

View File

@@ -7,7 +7,7 @@ use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
use std::sync::Arc; use std::sync::Arc;
use wasm_common::FunctionType; use wasm_common::FunctionType;
use wasmer_compiler::{CompileError, Target}; use wasmer_compiler::{CompileError, Target};
use wasmer_runtime::{VMSharedSignatureIndex, VMTrampoline}; use wasmer_vm::{VMSharedSignatureIndex, VMTrampoline};
/// A unimplemented Wasmer `Engine`. /// A unimplemented Wasmer `Engine`.
/// ///

View File

@@ -5,13 +5,11 @@ use crate::{ImportError, LinkError};
use more_asserts::assert_ge; use more_asserts::assert_ge;
use wasm_common::entity::{BoxedSlice, EntityRef, PrimaryMap}; use wasm_common::entity::{BoxedSlice, EntityRef, PrimaryMap};
use wasm_common::{ExternType, FunctionIndex, ImportIndex, MemoryIndex, TableIndex}; use wasm_common::{ExternType, FunctionIndex, ImportIndex, MemoryIndex, TableIndex};
use wasmer_runtime::{
Export, FunctionBodyPtr, Imports, VMFunctionBody, VMFunctionImport, VMFunctionKind,
VMGlobalImport, VMMemoryImport, VMTableImport,
};
use wasmer_runtime::{MemoryPlan, TablePlan}; use wasmer_vm::{
use wasmer_runtime::{MemoryStyle, ModuleInfo}; Export, FunctionBodyPtr, Imports, MemoryStyle, ModuleInfo, TableStyle, VMFunctionBody,
VMFunctionImport, VMFunctionKind, VMGlobalImport, VMMemoryImport, VMTableImport,
};
/// Import resolver connects imports with available exported values. /// Import resolver connects imports with available exported values.
pub trait Resolver { pub trait Resolver {
@@ -106,7 +104,7 @@ fn get_extern_from_import(module: &ModuleInfo, import_index: &ImportIndex) -> Ex
fn get_extern_from_export(_module: &ModuleInfo, export: &Export) -> ExternType { fn get_extern_from_export(_module: &ModuleInfo, export: &Export) -> ExternType {
match export { match export {
Export::Function(ref f) => ExternType::Function(f.signature.clone()), Export::Function(ref f) => ExternType::Function(f.signature.clone()),
Export::Table(ref t) => { /* Export::Table(ref t) => {
let table = t.plan().table; let table = t.plan().table;
ExternType::Table(table) ExternType::Table(table)
} }
@@ -114,6 +112,12 @@ fn get_extern_from_export(_module: &ModuleInfo, export: &Export) -> ExternType {
let memory = m.plan().memory; let memory = m.plan().memory;
ExternType::Memory(memory) ExternType::Memory(memory)
} }
Export::Global(ref g) => {
let global = g.from.ty();
ExternType::Global(*global)
}*/
Export::Table(ref t) => ExternType::Table(t.ty().clone()),
Export::Memory(ref m) => ExternType::Memory(m.ty().clone()),
Export::Global(ref g) => { Export::Global(ref g) => {
let global = g.from.ty(); let global = g.from.ty();
ExternType::Global(*global) ExternType::Global(*global)
@@ -129,8 +133,8 @@ pub fn resolve_imports(
module: &ModuleInfo, module: &ModuleInfo,
resolver: &dyn Resolver, resolver: &dyn Resolver,
finished_dynamic_function_trampolines: &BoxedSlice<FunctionIndex, FunctionBodyPtr>, finished_dynamic_function_trampolines: &BoxedSlice<FunctionIndex, FunctionBodyPtr>,
memory_plans: &PrimaryMap<MemoryIndex, MemoryPlan>, memory_styles: &PrimaryMap<MemoryIndex, MemoryStyle>,
_table_plans: &PrimaryMap<TableIndex, TablePlan>, _table_styles: &PrimaryMap<TableIndex, TableStyle>,
) -> Result<Imports, LinkError> { ) -> Result<Imports, LinkError> {
let mut function_imports = PrimaryMap::with_capacity(module.num_imported_funcs); let mut function_imports = PrimaryMap::with_capacity(module.num_imported_funcs);
let mut table_imports = PrimaryMap::with_capacity(module.num_imported_tables); let mut table_imports = PrimaryMap::with_capacity(module.num_imported_tables);
@@ -180,7 +184,7 @@ pub fn resolve_imports(
} }
Export::Table(ref t) => { Export::Table(ref t) => {
table_imports.push(VMTableImport { table_imports.push(VMTableImport {
definition: t.definition, definition: t.from.vmtable(),
from: t.from.clone(), from: t.from.clone(),
}); });
} }
@@ -189,20 +193,21 @@ pub fn resolve_imports(
ImportIndex::Memory(index) => { ImportIndex::Memory(index) => {
// Sanity-check: Ensure that the imported memory has at least // Sanity-check: Ensure that the imported memory has at least
// guard-page protections the importing module expects it to have. // guard-page protections the importing module expects it to have.
let export_memory_plan = m.plan(); let export_memory_style = m.style();
let import_memory_plan = &memory_plans[*index]; let import_memory_style = &memory_styles[*index];
if let ( if let (
MemoryStyle::Static { bound }, MemoryStyle::Static { bound, .. },
MemoryStyle::Static { MemoryStyle::Static {
bound: import_bound, bound: import_bound,
..
}, },
) = (export_memory_plan.style.clone(), &import_memory_plan.style) ) = (export_memory_style.clone(), &import_memory_style)
{ {
assert_ge!(bound, *import_bound); assert_ge!(bound, *import_bound);
} }
assert_ge!( assert_ge!(
export_memory_plan.offset_guard_size, export_memory_style.offset_guard_size(),
import_memory_plan.offset_guard_size import_memory_style.offset_guard_size()
); );
} }
_ => { _ => {
@@ -213,7 +218,7 @@ pub fn resolve_imports(
} }
memory_imports.push(VMMemoryImport { memory_imports.push(VMMemoryImport {
definition: m.definition, definition: m.from.vmmemory(),
from: m.from.clone(), from: m.from.clone(),
}); });
} }

View File

@@ -4,7 +4,7 @@ use std::error::Error;
use std::fmt; use std::fmt;
use std::sync::Arc; use std::sync::Arc;
use std::sync::RwLockReadGuard; use std::sync::RwLockReadGuard;
use wasmer_runtime::{raise_user_trap, Trap, TrapCode}; use wasmer_vm::{raise_user_trap, Trap, TrapCode};
/// A struct representing an aborted instruction execution, with a message /// A struct representing an aborted instruction execution, with a message
/// indicating the cause. /// indicating the cause.
@@ -44,8 +44,9 @@ impl RuntimeError {
// theory) we should only see user errors which were originally // theory) we should only see user errors which were originally
// created from our own `Trap` type (see the trampoline module // created from our own `Trap` type (see the trampoline module
// with functions). // with functions).
// Self::new(format!("{}", error)) *error
*error.downcast().expect("only `Trap` errors are supported") .downcast()
.expect("only `RuntimeError` errors are supported")
} }
Trap::Runtime { Trap::Runtime {
pc, pc,

View File

@@ -5,7 +5,7 @@
//! //!
//! # Example //! # Example
//! ```ignore //! ```ignore
//! use wasmer_runtime::{ModuleInfo, FRAME_INFO}; //! use wasmer_vm::{ModuleInfo, FRAME_INFO};
//! //!
//! let module: ModuleInfo = ...; //! let module: ModuleInfo = ...;
//! FRAME_INFO.register(module, compiled_functions); //! FRAME_INFO.register(module, compiled_functions);
@@ -17,7 +17,7 @@ use std::sync::{Arc, RwLock};
use wasm_common::entity::{BoxedSlice, EntityRef, PrimaryMap}; use wasm_common::entity::{BoxedSlice, EntityRef, PrimaryMap};
use wasm_common::LocalFunctionIndex; use wasm_common::LocalFunctionIndex;
use wasmer_compiler::{CompiledFunctionFrameInfo, SourceLoc, TrapInformation}; use wasmer_compiler::{CompiledFunctionFrameInfo, SourceLoc, TrapInformation};
use wasmer_runtime::{FunctionBodyPtr, ModuleInfo}; use wasmer_vm::{FunctionBodyPtr, ModuleInfo};
lazy_static::lazy_static! { lazy_static::lazy_static! {
/// This is a global cache of backtrace frame information for all active /// This is a global cache of backtrace frame information for all active

View File

@@ -5,23 +5,27 @@ use wasm_common::{
GlobalInit, GlobalType, LocalGlobalIndex, LocalMemoryIndex, LocalTableIndex, MemoryIndex, GlobalInit, GlobalType, LocalGlobalIndex, LocalMemoryIndex, LocalTableIndex, MemoryIndex,
MemoryType, Mutability, TableIndex, TableType, MemoryType, Mutability, TableIndex, TableType,
}; };
use wasmer_runtime::MemoryError; use wasmer_vm::MemoryError;
use wasmer_runtime::{Global, Imports, Memory, ModuleInfo, Table}; use wasmer_vm::{Global, Imports, Memory, ModuleInfo, Table};
use wasmer_runtime::{MemoryPlan, TablePlan}; use wasmer_vm::{MemoryStyle, TableStyle};
/// Tunables for an engine /// Tunables for an engine
pub trait Tunables { pub trait Tunables {
/// Construct a `MemoryPlan` for the provided `MemoryType` /// Construct a `MemoryStyle` for the provided `MemoryType`
fn memory_plan(&self, memory: MemoryType) -> MemoryPlan; fn memory_style(&self, memory: &MemoryType) -> MemoryStyle;
/// Construct a `TablePlan` for the provided `TableType` /// Construct a `TableStyle` for the provided `TableType`
fn table_plan(&self, table: TableType) -> TablePlan; fn table_style(&self, table: &TableType) -> TableStyle;
/// Create a memory given a memory type /// Create a memory given a memory type
fn create_memory(&self, memory_type: MemoryPlan) -> Result<Arc<dyn Memory>, MemoryError>; fn create_memory(
&self,
ty: &MemoryType,
style: &MemoryStyle,
) -> Result<Arc<dyn Memory>, MemoryError>;
/// Create a memory given a memory type /// Create a memory given a memory type
fn create_table(&self, table_type: TablePlan) -> Result<Arc<dyn Table>, String>; fn create_table(&self, ty: &TableType, style: &TableStyle) -> Result<Arc<dyn Table>, String>;
/// Create a global with the given value. /// Create a global with the given value.
fn create_initialized_global( fn create_initialized_global(
@@ -43,15 +47,17 @@ pub trait Tunables {
fn create_memories( fn create_memories(
&self, &self,
module: &ModuleInfo, module: &ModuleInfo,
memory_plans: &PrimaryMap<MemoryIndex, MemoryPlan>, memory_styles: &PrimaryMap<MemoryIndex, MemoryStyle>,
) -> Result<PrimaryMap<LocalMemoryIndex, Arc<dyn Memory>>, LinkError> { ) -> Result<PrimaryMap<LocalMemoryIndex, Arc<dyn Memory>>, LinkError> {
let num_imports = module.num_imported_memories; let num_imports = module.num_imported_memories;
let mut memories: PrimaryMap<LocalMemoryIndex, _> = let mut memories: PrimaryMap<LocalMemoryIndex, _> =
PrimaryMap::with_capacity(module.memories.len() - num_imports); PrimaryMap::with_capacity(module.memories.len() - num_imports);
for index in num_imports..module.memories.len() { for index in num_imports..module.memories.len() {
let plan = memory_plans[MemoryIndex::new(index)].clone(); let mi = MemoryIndex::new(index);
let ty = &module.memories[mi];
let style = &memory_styles[mi];
memories.push( memories.push(
self.create_memory(plan) self.create_memory(ty, style)
.map_err(|e| LinkError::Resource(format!("Failed to create memory: {}", e)))?, .map_err(|e| LinkError::Resource(format!("Failed to create memory: {}", e)))?,
); );
} }
@@ -62,14 +68,16 @@ pub trait Tunables {
fn create_tables( fn create_tables(
&self, &self,
module: &ModuleInfo, module: &ModuleInfo,
table_plans: &PrimaryMap<TableIndex, TablePlan>, table_styles: &PrimaryMap<TableIndex, TableStyle>,
) -> Result<PrimaryMap<LocalTableIndex, Arc<dyn Table>>, LinkError> { ) -> Result<PrimaryMap<LocalTableIndex, Arc<dyn Table>>, LinkError> {
let num_imports = module.num_imported_tables; let num_imports = module.num_imported_tables;
let mut tables: PrimaryMap<LocalTableIndex, _> = let mut tables: PrimaryMap<LocalTableIndex, _> =
PrimaryMap::with_capacity(module.tables.len() - num_imports); PrimaryMap::with_capacity(module.tables.len() - num_imports);
for index in num_imports..module.tables.len() { for index in num_imports..module.tables.len() {
let plan = table_plans[TableIndex::new(index)].clone(); let ti = TableIndex::new(index);
tables.push(self.create_table(plan).map_err(LinkError::Resource)?); let ty = &module.tables[ti];
let style = &table_styles[ti];
tables.push(self.create_table(ty, style).map_err(LinkError::Resource)?);
} }
Ok(tables) Ok(tables)
} }

View File

@@ -1,80 +0,0 @@
// This file contains code from external sources.
// Attributions: https://github.com/wasmerio/wasmer-reborn/blob/master/ATTRIBUTIONS.md
//! Memory management for linear memories.
//!
//! `LinearMemory` is to WebAssembly linear memories what `Table` is to WebAssembly tables.
use crate::vmcontext::VMMemoryDefinition;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::ptr::NonNull;
use thiserror::Error;
use wasm_common::{MemoryType, Pages};
/// Error type describing things that can go wrong when operating on Wasm Memories.
#[derive(Error, Debug, Clone, PartialEq, Hash)]
pub enum MemoryError {
/// Low level error with mmap.
#[error("Error when allocating memory: {0}")]
Region(String),
/// The operation would cause the size of the memory to exceed the maximum or would cause
/// an overflow leading to unindexable memory.
#[error("The memory could not grow: current size {} pages, requested increase: {} pages", current.0, attempted_delta.0)]
CouldNotGrow {
/// The current size in pages.
current: Pages,
/// The attempted amount to grow by in pages.
attempted_delta: Pages,
},
/// The operation would cause the size of the memory size exceed the maximum.
#[error("The memory plan is invalid because {}", reason)]
InvalidMemoryPlan {
/// The reason why the memory plan is invalid.
reason: String,
},
/// A user defined error value, used for error cases not listed above.
#[error("A user-defined error occurred: {0}")]
Generic(String),
}
/// Implementation styles for WebAssembly linear memory.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum MemoryStyle {
/// The actual memory can be resized and moved.
Dynamic,
/// Address space is allocated up front.
Static {
/// The number of mapped and unmapped pages.
bound: Pages,
},
}
/// A WebAssembly linear memory description along with our chosen style for
/// implementing it.
#[derive(Debug, Clone, Hash, Serialize, Deserialize)]
pub struct MemoryPlan {
/// The WebAssembly linear memory description.
pub memory: MemoryType,
/// Our chosen implementation style.
pub style: MemoryStyle,
/// Our chosen offset-guard size.
pub offset_guard_size: u64,
}
/// Trait for implementing Wasm Memory used by Wasmer.
pub trait Memory: fmt::Debug + Send + Sync {
/// Returns the memory plan for this memory.
fn plan(&self) -> &MemoryPlan;
/// Returns the number of allocated wasm pages.
fn size(&self) -> Pages;
/// Grow memory by the specified amount of wasm pages.
fn grow(&self, delta: Pages) -> Result<Pages, MemoryError>;
/// Return a [`VMMemoryDefinition`] for exposing the memory to compiled wasm code.
///
/// The pointer returned in [`VMMemoryDefinition`] must be valid for the lifetime of this memory.
fn vmmemory(&self) -> NonNull<VMMemoryDefinition>;
}

View File

@@ -1,119 +0,0 @@
// This file contains code from external sources.
// Attributions: https://github.com/wasmerio/wasmer-reborn/blob/master/ATTRIBUTIONS.md
//! Memory management for tables.
//!
//! `Table` is to WebAssembly tables what `LinearMemory` is to WebAssembly linear memories.
use crate::trap::{Trap, TrapCode};
use crate::vmcontext::{VMCallerCheckedAnyfunc, VMTableDefinition};
use serde::{Deserialize, Serialize};
use std::fmt;
use std::ptr::NonNull;
use wasm_common::{FunctionIndex, GlobalIndex, TableIndex, TableType};
/// A WebAssembly table initializer.
#[derive(Clone, Debug, Hash, Serialize, Deserialize)]
pub struct TableElements {
/// The index of a table to initialize.
pub table_index: TableIndex,
/// Optionally, a global variable giving a base index.
pub base: Option<GlobalIndex>,
/// The offset to add to the base.
pub offset: usize,
/// The values to write into the table elements.
pub elements: Box<[FunctionIndex]>,
}
/// Implementation styles for WebAssembly tables.
#[derive(Debug, Clone, Hash, Serialize, Deserialize)]
pub enum TableStyle {
/// Signatures are stored in the table and checked in the caller.
CallerChecksSignature,
}
/// A WebAssembly table description along with our chosen style for
/// implementing it.
#[derive(Debug, Clone, Hash, Serialize, Deserialize)]
pub struct TablePlan {
/// The WebAssembly table description.
pub table: TableType,
/// Our chosen implementation style.
pub style: TableStyle,
}
/// Trait for implementing the interface of a Wasm table.
pub trait Table: fmt::Debug + Send + Sync {
/// Returns the table plan for this Table.
fn plan(&self) -> &TablePlan;
/// Returns the number of allocated elements.
fn size(&self) -> u32;
/// Grow table by the specified amount of elements.
///
/// Returns `None` if table can't be grown by the specified amount
/// of elements, otherwise returns the previous size of the table.
fn grow(&self, delta: u32) -> Option<u32>;
/// Get reference to the specified element.
///
/// Returns `None` if the index is out of bounds.
fn get(&self, index: u32) -> Option<VMCallerCheckedAnyfunc>;
/// Set reference to the specified element.
///
/// # Errors
///
/// Returns an error if the index is out of bounds.
fn set(&self, index: u32, func: VMCallerCheckedAnyfunc) -> Result<(), Trap>;
/// Return a `VMTableDefinition` for exposing the table to compiled wasm code.
fn vmtable(&self) -> NonNull<VMTableDefinition>;
/// Copy `len` elements from `src_table[src_index..]` into `dst_table[dst_index..]`.
///
/// # Errors
///
/// Returns an error if the range is out of bounds of either the source or
/// destination tables.
fn copy(
&self,
src_table: &dyn Table,
dst_index: u32,
src_index: u32,
len: u32,
) -> Result<(), Trap> {
// https://webassembly.github.io/bulk-memory-operations/core/exec/instructions.html#exec-table-copy
if src_index
.checked_add(len)
.map_or(true, |n| n > src_table.size())
{
return Err(Trap::wasm(TrapCode::TableAccessOutOfBounds));
}
if dst_index.checked_add(len).map_or(true, |m| m > self.size()) {
return Err(Trap::wasm(TrapCode::TableSetterOutOfBounds));
}
let srcs = src_index..src_index + len;
let dsts = dst_index..dst_index + len;
// Note on the unwraps: the bounds check above means that these will
// never panic.
//
// TODO: investigate replacing this get/set loop with a `memcpy`.
if dst_index <= src_index {
for (s, d) in (srcs).zip(dsts) {
self.set(d, src_table.get(s).unwrap())?;
}
} else {
for (s, d) in srcs.rev().zip(dsts.rev()) {
self.set(d, src_table.get(s).unwrap())?;
}
}
Ok(())
}
}

View File

@@ -1,5 +1,5 @@
[package] [package]
name = "wasmer-runtime" name = "wasmer-vm"
version = "1.0.0-alpha.1" version = "1.0.0-alpha.1"
authors = ["Wasmer Engineering Team <engineering@wasmer.io>"] authors = ["Wasmer Engineering Team <engineering@wasmer.io>"]
description = "Runtime library support for Wasmer" description = "Runtime library support for Wasmer"
@@ -12,10 +12,10 @@ edition = "2018"
[dependencies] [dependencies]
wasm-common = { path = "../wasm-common", version = "1.0.0-alpha.1", features = ["enable-serde"] } wasm-common = { path = "../wasm-common", version = "1.0.0-alpha.1", features = ["enable-serde"] }
region = "2.1" region = "2.2"
libc = { version = "0.2", default-features = false } libc = { version = "0.2", default-features = false }
memoffset = "0.5" memoffset = "0.5"
indexmap = { version = "1.3", features = ["serde-1"] } indexmap = { version = "1.4", features = ["serde-1"] }
thiserror = "1.0" thiserror = "1.0"
more-asserts = "0.2" more-asserts = "0.2"
cfg-if = "0.1" cfg-if = "0.1"

View File

@@ -1,6 +1,6 @@
# Wasmer Runtime # Wasmer VM
This is the `wasmer-runtime` crate, which contains wasm runtime library This is the `wasmer-vm` crate, which contains wasm VM runtime library
support, supporting the wasm ABI used by any [`wasmer-engine`] implementation. support, supporting the wasm ABI used by any [`wasmer-engine`] implementation.
[`wasmer-engine`]: https://crates.io/crates/wasmer-engine [`wasmer-engine`]: https://crates.io/crates/wasmer-engine

View File

@@ -2,15 +2,12 @@
// Attributions: https://github.com/wasmerio/wasmer-reborn/blob/master/ATTRIBUTIONS.md // Attributions: https://github.com/wasmerio/wasmer-reborn/blob/master/ATTRIBUTIONS.md
use crate::global::Global; use crate::global::Global;
use crate::memory::{Memory, MemoryPlan}; use crate::memory::{Memory, MemoryStyle};
use crate::table::{Table, TablePlan}; use crate::table::{Table, TableStyle};
use crate::vmcontext::{ use crate::vmcontext::{VMContext, VMFunctionBody, VMFunctionKind, VMGlobalDefinition};
VMContext, VMFunctionBody, VMFunctionKind, VMGlobalDefinition, VMMemoryDefinition,
VMTableDefinition,
};
use std::ptr::NonNull; use std::ptr::NonNull;
use std::sync::Arc; use std::sync::Arc;
use wasm_common::FunctionType; use wasm_common::{FunctionType, MemoryType, TableType};
/// The value of an export passed from one instance to another. /// The value of an export passed from one instance to another.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@@ -57,14 +54,6 @@ impl From<ExportFunction> for Export {
/// A table export value. /// A table export value.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct ExportTable { pub struct ExportTable {
/// The address of the table descriptor.
///
/// The `VMTableDefinition` this points to should be considered immutable from
/// this pointer. The data may be updated though.
/// TODO: better define this behavior and document it
// TODO: consider a special wrapper pointer type for this kind of logic
// (so we don't need to `unsafe impl Send` in the places that use it)
pub definition: NonNull<VMTableDefinition>,
/// Pointer to the containing `Table`. /// Pointer to the containing `Table`.
pub from: Arc<dyn Table>, pub from: Arc<dyn Table>,
} }
@@ -81,15 +70,19 @@ unsafe impl Send for ExportTable {}
unsafe impl Sync for ExportTable {} unsafe impl Sync for ExportTable {}
impl ExportTable { impl ExportTable {
/// Get the plan for this exported memory /// Get the table type for this exported table
pub fn plan(&self) -> &TablePlan { pub fn ty(&self) -> &TableType {
self.from.plan() self.from.ty()
}
/// Get the style for this exported table
pub fn style(&self) -> &TableStyle {
self.from.style()
} }
/// Returns whether or not the two `ExportTable`s refer to the same Memory. /// Returns whether or not the two `ExportTable`s refer to the same Memory.
pub fn same(&self, other: &Self) -> bool { pub fn same(&self, other: &Self) -> bool {
// TODO: comparing Arc::ptr_eq(&self.from, &other.from)
self.definition == other.definition //&& self.from == other.from
} }
} }
@@ -102,14 +95,6 @@ impl From<ExportTable> for Export {
/// A memory export value. /// A memory export value.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct ExportMemory { pub struct ExportMemory {
/// The address of the memory descriptor.
///
/// The `VMMemoryDefinition` this points to should be considered immutable from
/// this pointer. The data may be updated though.
/// TODO: better define this behavior and document it
// TODO: consider a special wrapper pointer type for this kind of logic
// (so we don't need to `unsafe impl Send` in the places that use it)
pub definition: NonNull<VMMemoryDefinition>,
/// Pointer to the containing `Memory`. /// Pointer to the containing `Memory`.
pub from: Arc<dyn Memory>, pub from: Arc<dyn Memory>,
} }
@@ -126,15 +111,19 @@ unsafe impl Send for ExportMemory {}
unsafe impl Sync for ExportMemory {} unsafe impl Sync for ExportMemory {}
impl ExportMemory { impl ExportMemory {
/// Get the plan for this exported memory /// Get the type for this exported memory
pub fn plan(&self) -> &MemoryPlan { pub fn ty(&self) -> &MemoryType {
self.from.plan() self.from.ty()
}
/// Get the style for this exported memory
pub fn style(&self) -> &MemoryStyle {
self.from.style()
} }
/// Returns whether or not the two `ExportMemory`s refer to the same Memory. /// Returns whether or not the two `ExportMemory`s refer to the same Memory.
pub fn same(&self, other: &Self) -> bool { pub fn same(&self, other: &Self) -> bool {
// TODO: implement comparison Arc::ptr_eq(&self.from, &other.from)
self.definition == other.definition //&& self.from == other.from
} }
} }

View File

@@ -315,24 +315,22 @@ impl Instance {
.into() .into()
} }
ExportIndex::Table(index) => { ExportIndex::Table(index) => {
let (definition, from) = let from = if let Some(def_index) = self.module.local_table_index(*index) {
if let Some(def_index) = self.module.local_table_index(*index) { self.tables[def_index].clone()
(self.table_ptr(def_index), self.tables[def_index].clone())
} else { } else {
let import = self.imported_table(*index); let import = self.imported_table(*index);
(import.definition, import.from.clone()) import.from.clone()
}; };
ExportTable { definition, from }.into() ExportTable { from }.into()
} }
ExportIndex::Memory(index) => { ExportIndex::Memory(index) => {
let (definition, from) = let from = if let Some(def_index) = self.module.local_memory_index(*index) {
if let Some(def_index) = self.module.local_memory_index(*index) { self.memories[def_index].clone()
(self.memory_ptr(def_index), self.memories[def_index].clone())
} else { } else {
let import = self.imported_memory(*index); let import = self.imported_memory(*index);
(import.definition, import.from.clone()) import.from.clone()
}; };
ExportMemory { definition, from }.into() ExportMemory { from }.into()
} }
ExportIndex::Global(index) => { ExportIndex::Global(index) => {
let (definition, from) = { let (definition, from) = {

View File

@@ -41,12 +41,12 @@ pub use crate::export::*;
pub use crate::global::*; pub use crate::global::*;
pub use crate::imports::Imports; pub use crate::imports::Imports;
pub use crate::instance::InstanceHandle; pub use crate::instance::InstanceHandle;
pub use crate::memory::{Memory, MemoryError, MemoryPlan, MemoryStyle}; pub use crate::memory::{LinearMemory, Memory, MemoryError, MemoryStyle};
pub use crate::mmap::Mmap; pub use crate::mmap::Mmap;
pub use crate::module::{ExportsIterator, ImportsIterator, ModuleInfo}; pub use crate::module::{ExportsIterator, ImportsIterator, ModuleInfo};
pub use crate::probestack::PROBESTACK; pub use crate::probestack::PROBESTACK;
pub use crate::sig_registry::SignatureRegistry; pub use crate::sig_registry::SignatureRegistry;
pub use crate::table::{Table, TableElements, TablePlan, TableStyle}; pub use crate::table::{LinearTable, Table, TableElements, TableStyle};
pub use crate::trap::*; pub use crate::trap::*;
pub use crate::vmcontext::{ pub use crate::vmcontext::{
VMBuiltinFunctionIndex, VMCallerCheckedAnyfunc, VMContext, VMDynamicFunctionContext, VMBuiltinFunctionIndex, VMCallerCheckedAnyfunc, VMContext, VMDynamicFunctionContext,

View File

@@ -1,10 +1,102 @@
use crate::{Bytes, Pages}; // This file contains code from external sources.
// Attributions: https://github.com/wasmerio/wasmer-reborn/blob/master/ATTRIBUTIONS.md
//! Memory management for linear memories.
//!
//! `LinearMemory` is to WebAssembly linear memories what `Table` is to WebAssembly tables.
use crate::mmap::Mmap;
use crate::vmcontext::VMMemoryDefinition;
use more_asserts::{assert_ge, assert_le}; use more_asserts::{assert_ge, assert_le};
use serde::{Deserialize, Serialize};
use std::borrow::BorrowMut; use std::borrow::BorrowMut;
use std::cell::UnsafeCell; use std::cell::UnsafeCell;
use std::fmt;
use std::ptr::NonNull; use std::ptr::NonNull;
use std::sync::Mutex; use std::sync::Mutex;
use wasmer_runtime::{Memory, MemoryError, MemoryPlan, MemoryStyle, Mmap, VMMemoryDefinition}; use thiserror::Error;
use wasm_common::{Bytes, MemoryType, Pages};
/// Error type describing things that can go wrong when operating on Wasm Memories.
#[derive(Error, Debug, Clone, PartialEq, Hash)]
pub enum MemoryError {
/// Low level error with mmap.
#[error("Error when allocating memory: {0}")]
Region(String),
/// The operation would cause the size of the memory to exceed the maximum or would cause
/// an overflow leading to unindexable memory.
#[error("The memory could not grow: current size {} pages, requested increase: {} pages", current.0, attempted_delta.0)]
CouldNotGrow {
/// The current size in pages.
current: Pages,
/// The attempted amount to grow by in pages.
attempted_delta: Pages,
},
/// The operation would cause the size of the memory size exceed the maximum.
#[error("The memory is invalid because {}", reason)]
InvalidMemory {
/// The reason why the provided memory is invalid.
reason: String,
},
/// A user defined error value, used for error cases not listed above.
#[error("A user-defined error occurred: {0}")]
Generic(String),
}
/// Implementation styles for WebAssembly linear memory.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum MemoryStyle {
/// The actual memory can be resized and moved.
Dynamic {
/// Our chosen offset-guard size.
///
/// It represents the size in bytes of extra guard pages after the end
/// to optimize loads and stores with constant offsets.
offset_guard_size: u64,
},
/// Address space is allocated up front.
Static {
/// The number of mapped and unmapped pages.
bound: Pages,
/// Our chosen offset-guard size.
///
/// It represents the size in bytes of extra guard pages after the end
/// to optimize loads and stores with constant offsets.
offset_guard_size: u64,
},
}
impl MemoryStyle {
/// Returns the offset-guard size
pub fn offset_guard_size(&self) -> u64 {
match self {
Self::Dynamic { offset_guard_size } => *offset_guard_size,
Self::Static {
offset_guard_size, ..
} => *offset_guard_size,
}
}
}
/// Trait for implementing Wasm Memory used by Wasmer.
pub trait Memory: fmt::Debug + Send + Sync {
/// Returns the memory type for this memory.
fn ty(&self) -> &MemoryType;
/// Returns the memory style for this memory.
fn style(&self) -> &MemoryStyle;
/// Returns the number of allocated wasm pages.
fn size(&self) -> Pages;
/// Grow memory by the specified amount of wasm pages.
fn grow(&self, delta: Pages) -> Result<Pages, MemoryError>;
/// Return a [`VMMemoryDefinition`] for exposing the memory to compiled wasm code.
///
/// The pointer returned in [`VMMemoryDefinition`] must be valid for the lifetime of this memory.
fn vmmemory(&self) -> NonNull<VMMemoryDefinition>;
}
/// A linear memory instance. /// A linear memory instance.
#[derive(Debug)] #[derive(Debug)]
@@ -15,13 +107,16 @@ pub struct LinearMemory {
// The optional maximum size in wasm pages of this linear memory. // The optional maximum size in wasm pages of this linear memory.
maximum: Option<Pages>, maximum: Option<Pages>,
/// The WebAssembly linear memory description.
memory: MemoryType,
/// Our chosen implementation style.
style: MemoryStyle,
// Size in bytes of extra guard pages after the end to optimize loads and stores with // Size in bytes of extra guard pages after the end to optimize loads and stores with
// constant offsets. // constant offsets.
offset_guard_size: usize, offset_guard_size: usize,
// The memory plan for this memory
plan: MemoryPlan,
/// The owned memory definition used by the generated code /// The owned memory definition used by the generated code
vm_memory_definition: Box<UnsafeCell<VMMemoryDefinition>>, vm_memory_definition: Box<UnsafeCell<VMMemoryDefinition>>,
@@ -43,78 +138,82 @@ struct WasmMmap {
impl LinearMemory { impl LinearMemory {
/// Create a new linear memory instance with specified minimum and maximum number of wasm pages. /// Create a new linear memory instance with specified minimum and maximum number of wasm pages.
pub fn new(plan: &MemoryPlan) -> Result<Self, MemoryError> { pub fn new(memory: &MemoryType, style: &MemoryStyle) -> Result<Self, MemoryError> {
// `maximum` cannot be set to more than `65536` pages. // `maximum` cannot be set to more than `65536` pages.
assert_le!(plan.memory.minimum, Pages::max_value()); assert_le!(memory.minimum, Pages::max_value());
assert!( assert!(memory.maximum.is_none() || memory.maximum.unwrap() <= Pages::max_value());
plan.memory.maximum.is_none() || plan.memory.maximum.unwrap() <= Pages::max_value()
);
if plan.memory.maximum.is_some() && plan.memory.maximum.unwrap() < plan.memory.minimum { if memory.maximum.is_some() && memory.maximum.unwrap() < memory.minimum {
return Err(MemoryError::InvalidMemoryPlan { return Err(MemoryError::InvalidMemory {
reason: format!( reason: format!(
"the maximum ({} pages) is less than the minimum ({} pages)", "the maximum ({} pages) is less than the minimum ({} pages)",
plan.memory.maximum.unwrap().0, memory.maximum.unwrap().0,
plan.memory.minimum.0 memory.minimum.0
), ),
}); });
} }
let offset_guard_bytes = plan.offset_guard_size as usize; let offset_guard_bytes = style.offset_guard_size() as usize;
// If we have an offset guard, or if we're doing the static memory // If we have an offset guard, or if we're doing the static memory
// allocation strategy, we need signal handlers to catch out of bounds // allocation strategy, we need signal handlers to catch out of bounds
// acceses. // acceses.
let needs_signal_handlers = offset_guard_bytes > 0 let needs_signal_handlers = offset_guard_bytes > 0
|| match plan.style { || match style {
MemoryStyle::Dynamic => false, MemoryStyle::Dynamic { .. } => false,
MemoryStyle::Static { .. } => true, MemoryStyle::Static { .. } => true,
}; };
let minimum_pages = match plan.style { let minimum_pages = match style {
MemoryStyle::Dynamic => plan.memory.minimum, MemoryStyle::Dynamic { .. } => memory.minimum,
MemoryStyle::Static { bound } => { MemoryStyle::Static { bound, .. } => {
assert_ge!(bound, plan.memory.minimum); assert_ge!(*bound, memory.minimum);
bound *bound
} }
}; };
let minimum_bytes = minimum_pages.bytes().0; let minimum_bytes = minimum_pages.bytes().0;
let request_bytes = minimum_bytes.checked_add(offset_guard_bytes).unwrap(); let request_bytes = minimum_bytes.checked_add(offset_guard_bytes).unwrap();
let mapped_pages = plan.memory.minimum; let mapped_pages = memory.minimum;
let mapped_bytes = mapped_pages.bytes(); let mapped_bytes = mapped_pages.bytes();
let mut mmap = WasmMmap { let mut mmap = WasmMmap {
alloc: Mmap::accessible_reserved(mapped_bytes.0, request_bytes) alloc: Mmap::accessible_reserved(mapped_bytes.0, request_bytes)
.map_err(MemoryError::Region)?, .map_err(MemoryError::Region)?,
size: plan.memory.minimum, size: memory.minimum,
}; };
let base_ptr = mmap.alloc.as_mut_ptr(); let base_ptr = mmap.alloc.as_mut_ptr();
Ok(Self { Ok(Self {
mmap: Mutex::new(mmap), mmap: Mutex::new(mmap),
maximum: plan.memory.maximum, maximum: memory.maximum,
offset_guard_size: offset_guard_bytes, offset_guard_size: offset_guard_bytes,
needs_signal_handlers, needs_signal_handlers,
vm_memory_definition: Box::new(UnsafeCell::new(VMMemoryDefinition { vm_memory_definition: Box::new(UnsafeCell::new(VMMemoryDefinition {
base: base_ptr, base: base_ptr,
current_length: plan.memory.minimum.bytes().0, current_length: memory.minimum.bytes().0,
})), })),
plan: plan.clone(), memory: memory.clone(),
style: style.clone(),
}) })
} }
} }
impl Memory for LinearMemory { impl Memory for LinearMemory {
/// Returns the memory plan for this memory. /// Returns the type for this memory.
fn plan(&self) -> &MemoryPlan { fn ty(&self) -> &MemoryType {
&self.plan &self.memory
}
/// Returns the memory style for this memory.
fn style(&self) -> &MemoryStyle {
&self.style
} }
/// Returns the number of allocated wasm pages. /// Returns the number of allocated wasm pages.
fn size(&self) -> Pages { fn size(&self) -> Pages {
unsafe { unsafe {
let ptr = self.vm_memory_definition.get(); let ptr = self.vm_memory_definition.get();
Bytes((*ptr).current_length as _).into() Bytes((*ptr).current_length).into()
} }
} }

View File

@@ -91,7 +91,7 @@ pub struct ModuleInfo {
/// WebAssembly tables (imported and local). /// WebAssembly tables (imported and local).
pub tables: PrimaryMap<TableIndex, TableType>, pub tables: PrimaryMap<TableIndex, TableType>,
/// WebAssembly linear memory plans (imported and local). /// WebAssembly linear memories (imported and local).
pub memories: PrimaryMap<MemoryIndex, MemoryType>, pub memories: PrimaryMap<MemoryIndex, MemoryType>,
/// WebAssembly global variables (imported and local). /// WebAssembly global variables (imported and local).

246
lib/vm/src/table.rs Normal file
View File

@@ -0,0 +1,246 @@
// This file contains code from external sources.
// Attributions: https://github.com/wasmerio/wasmer-reborn/blob/master/ATTRIBUTIONS.md
//! Memory management for tables.
//!
//! `Table` is to WebAssembly tables what `LinearMemory` is to WebAssembly linear memories.
use crate::trap::{Trap, TrapCode};
use crate::vmcontext::{VMCallerCheckedAnyfunc, VMTableDefinition};
use serde::{Deserialize, Serialize};
use std::borrow::{Borrow, BorrowMut};
use std::cell::UnsafeCell;
use std::convert::TryFrom;
use std::fmt;
use std::ptr::NonNull;
use std::sync::Mutex;
use wasm_common::{FunctionIndex, GlobalIndex, TableIndex, TableType, Type as ValType};
/// A WebAssembly table initializer.
#[derive(Clone, Debug, Hash, Serialize, Deserialize)]
pub struct TableElements {
/// The index of a table to initialize.
pub table_index: TableIndex,
/// Optionally, a global variable giving a base index.
pub base: Option<GlobalIndex>,
/// The offset to add to the base.
pub offset: usize,
/// The values to write into the table elements.
pub elements: Box<[FunctionIndex]>,
}
/// Implementation styles for WebAssembly tables.
#[derive(Debug, Clone, Hash, Serialize, Deserialize)]
pub enum TableStyle {
/// Signatures are stored in the table and checked in the caller.
CallerChecksSignature,
}
/// Trait for implementing the interface of a Wasm table.
pub trait Table: fmt::Debug + Send + Sync {
/// Returns the style for this Table.
fn style(&self) -> &TableStyle;
/// Returns the type for this Table.
fn ty(&self) -> &TableType;
/// Returns the number of allocated elements.
fn size(&self) -> u32;
/// Grow table by the specified amount of elements.
///
/// Returns `None` if table can't be grown by the specified amount
/// of elements, otherwise returns the previous size of the table.
fn grow(&self, delta: u32) -> Option<u32>;
/// Get reference to the specified element.
///
/// Returns `None` if the index is out of bounds.
fn get(&self, index: u32) -> Option<VMCallerCheckedAnyfunc>;
/// Set reference to the specified element.
///
/// # Errors
///
/// Returns an error if the index is out of bounds.
fn set(&self, index: u32, func: VMCallerCheckedAnyfunc) -> Result<(), Trap>;
/// Return a `VMTableDefinition` for exposing the table to compiled wasm code.
fn vmtable(&self) -> NonNull<VMTableDefinition>;
/// Copy `len` elements from `src_table[src_index..]` into `dst_table[dst_index..]`.
///
/// # Errors
///
/// Returns an error if the range is out of bounds of either the source or
/// destination tables.
fn copy(
&self,
src_table: &dyn Table,
dst_index: u32,
src_index: u32,
len: u32,
) -> Result<(), Trap> {
// https://webassembly.github.io/bulk-memory-operations/core/exec/instructions.html#exec-table-copy
if src_index
.checked_add(len)
.map_or(true, |n| n > src_table.size())
{
return Err(Trap::wasm(TrapCode::TableAccessOutOfBounds));
}
if dst_index.checked_add(len).map_or(true, |m| m > self.size()) {
return Err(Trap::wasm(TrapCode::TableSetterOutOfBounds));
}
let srcs = src_index..src_index + len;
let dsts = dst_index..dst_index + len;
// Note on the unwraps: the bounds check above means that these will
// never panic.
//
// TODO: investigate replacing this get/set loop with a `memcpy`.
if dst_index <= src_index {
for (s, d) in (srcs).zip(dsts) {
self.set(d, src_table.get(s).unwrap())?;
}
} else {
for (s, d) in srcs.rev().zip(dsts.rev()) {
self.set(d, src_table.get(s).unwrap())?;
}
}
Ok(())
}
}
/// A table instance.
#[derive(Debug)]
pub struct LinearTable {
// TODO: we can remove the mutex by using atomic swaps and preallocating the max table size
vec: Mutex<Vec<VMCallerCheckedAnyfunc>>,
maximum: Option<u32>,
/// The WebAssembly table description.
table: TableType,
/// Our chosen implementation style.
style: TableStyle,
vm_table_definition: Box<UnsafeCell<VMTableDefinition>>,
}
/// This is correct because there is no thread-specific data tied to this type.
unsafe impl Send for LinearTable {}
/// This is correct because all internal mutability is protected by a mutex.
unsafe impl Sync for LinearTable {}
impl LinearTable {
/// Create a new table instance with specified minimum and maximum number of elements.
pub fn new(table: &TableType, style: &TableStyle) -> Result<Self, String> {
match table.ty {
ValType::FuncRef => (),
ty => return Err(format!("tables of types other than anyfunc ({})", ty)),
};
if let Some(max) = table.maximum {
if max < table.minimum {
return Err(format!(
"Table minimum ({}) is larger than maximum ({})!",
table.minimum, max
));
}
}
let table_minimum = usize::try_from(table.minimum)
.map_err(|_| "Table minimum is bigger than usize".to_string())?;
let mut vec = vec![VMCallerCheckedAnyfunc::default(); table_minimum];
let base = vec.as_mut_ptr();
match style {
TableStyle::CallerChecksSignature => Ok(Self {
vec: Mutex::new(vec),
maximum: table.maximum,
table: table.clone(),
style: style.clone(),
vm_table_definition: Box::new(UnsafeCell::new(VMTableDefinition {
base: base as _,
current_elements: table_minimum as _,
})),
}),
}
}
}
impl Table for LinearTable {
/// Returns the type for this Table.
fn ty(&self) -> &TableType {
&self.table
}
/// Returns the style for this Table.
fn style(&self) -> &TableStyle {
&self.style
}
/// Returns the number of allocated elements.
fn size(&self) -> u32 {
unsafe {
let ptr = self.vm_table_definition.get();
(*ptr).current_elements
}
}
/// Grow table by the specified amount of elements.
///
/// Returns `None` if table can't be grown by the specified amount
/// of elements, otherwise returns the previous size of the table.
fn grow(&self, delta: u32) -> Option<u32> {
let mut vec_guard = self.vec.lock().unwrap();
let vec = vec_guard.borrow_mut();
let size = self.size();
let new_len = size.checked_add(delta)?;
if self.maximum.map_or(false, |max| new_len > max) {
return None;
}
vec.resize(
usize::try_from(new_len).unwrap(),
VMCallerCheckedAnyfunc::default(),
);
// update table definition
unsafe {
let td = &mut *self.vm_table_definition.get();
td.current_elements = new_len;
td.base = vec.as_mut_ptr() as _;
}
Some(size)
}
/// Get reference to the specified element.
///
/// Returns `None` if the index is out of bounds.
fn get(&self, index: u32) -> Option<VMCallerCheckedAnyfunc> {
let vec_guard = self.vec.lock().unwrap();
vec_guard.borrow().get(index as usize).cloned()
}
/// Set reference to the specified element.
///
/// # Errors
///
/// Returns an error if the index is out of bounds.
fn set(&self, index: u32, func: VMCallerCheckedAnyfunc) -> Result<(), Trap> {
let mut vec_guard = self.vec.lock().unwrap();
let vec = vec_guard.borrow_mut();
match vec.get_mut(index as usize) {
Some(slot) => {
*slot = func;
Ok(())
}
None => Err(Trap::wasm(TrapCode::TableAccessOutOfBounds)),
}
}
/// Return a `VMTableDefinition` for exposing the table to compiled wasm code.
fn vmtable(&self) -> NonNull<VMTableDefinition> {
let _vec_guard = self.vec.lock().unwrap();
let ptr = self.vm_table_definition.as_ref() as *const UnsafeCell<VMTableDefinition>
as *const VMTableDefinition as *mut VMTableDefinition;
unsafe { NonNull::new_unchecked(ptr) }
}
}

View File

@@ -447,7 +447,7 @@ where
{ {
// Ensure that we have our sigaltstack installed. // Ensure that we have our sigaltstack installed.
#[cfg(unix)] #[cfg(unix)]
setup_unix_signalstack()?; setup_unix_sigaltstack()?;
return CallThreadState::new(vmctx).with(|cx| { return CallThreadState::new(vmctx).with(|cx| {
RegisterSetjmp( RegisterSetjmp(
@@ -705,7 +705,7 @@ mod tls {
/// and registering our own alternate stack that is large enough and has a guard /// and registering our own alternate stack that is large enough and has a guard
/// page. /// page.
#[cfg(unix)] #[cfg(unix)]
fn setup_unix_signalstack() -> Result<(), Trap> { fn setup_unix_sigaltstack() -> Result<(), Trap> {
use std::cell::RefCell; use std::cell::RefCell;
use std::convert::TryInto; use std::convert::TryInto;
use std::ptr::null_mut; use std::ptr::null_mut;

View File

@@ -1,7 +1,7 @@
// This file contains code from external sources. // This file contains code from external sources.
// Attributions: https://github.com/wasmerio/wasmer-reborn/blob/master/ATTRIBUTIONS.md // Attributions: https://github.com/wasmerio/wasmer-reborn/blob/master/ATTRIBUTIONS.md
//! Offsets and sizes of various structs in wasmer-runtime's vmcontext //! Offsets and sizes of various structs in wasmer-vm's vmcontext
//! module. //! module.
#![deny(intra_doc_link_resolution_failure)] #![deny(intra_doc_link_resolution_failure)]

View File

@@ -25,6 +25,7 @@
mod data_initializer; mod data_initializer;
mod features; mod features;
mod indexes; mod indexes;
mod memory_view;
mod native; mod native;
mod r#ref; mod r#ref;
mod types; mod types;
@@ -43,6 +44,7 @@ pub use crate::indexes::{
LocalFunctionIndex, LocalGlobalIndex, LocalMemoryIndex, LocalTableIndex, MemoryIndex, LocalFunctionIndex, LocalGlobalIndex, LocalMemoryIndex, LocalTableIndex, MemoryIndex,
SignatureIndex, TableIndex, SignatureIndex, TableIndex,
}; };
pub use crate::memory_view::{Atomically, MemoryView};
pub use crate::native::{NativeWasmType, ValueType}; pub use crate::native::{NativeWasmType, ValueType};
pub use crate::r#ref::{ExternRef, HostInfo, HostRef}; pub use crate::r#ref::{ExternRef, HostInfo, HostRef};
pub use crate::units::{Bytes, Pages, WASM_MAX_PAGES, WASM_MIN_PAGES, WASM_PAGE_SIZE}; pub use crate::units::{Bytes, Pages, WASM_MAX_PAGES, WASM_MIN_PAGES, WASM_PAGE_SIZE};

View File

@@ -1,5 +1,4 @@
use wasm_common::ValueType; use crate::native::ValueType;
use std::sync::atomic::{ use std::sync::atomic::{
AtomicI16, AtomicI32, AtomicI64, AtomicI8, AtomicU16, AtomicU32, AtomicU64, AtomicU8, AtomicI16, AtomicI32, AtomicI64, AtomicI8, AtomicU16, AtomicU32, AtomicU64, AtomicU8,
}; };
@@ -54,7 +53,8 @@ impl<'a, T> MemoryView<'a, T, NonAtomically>
where where
T: ValueType, T: ValueType,
{ {
pub(super) unsafe fn new(ptr: *mut T, length: u32) -> Self { /// Creates a new MemoryView given a `pointer` and `length`.
pub unsafe fn new(ptr: *mut T, length: u32) -> Self {
Self { Self {
ptr, ptr,
length: length as usize, length: length as usize,

View File

@@ -11,9 +11,7 @@ pub fn wasmer_should_print_color() -> bool {
.unwrap_or_else(|| atty::is(atty::Stream::Stdout)) .unwrap_or_else(|| atty::is(atty::Stream::Stdout))
} }
/// Parses a mapdir from a string fn retrieve_alias_pathbuf(alias: &str, real_dir: &str) -> Result<(String, PathBuf)> {
pub fn parse_mapdir(entry: &str) -> Result<(String, PathBuf)> {
if let [alias, real_dir] = entry.split(':').collect::<Vec<&str>>()[..] {
let pb = PathBuf::from(&real_dir); let pb = PathBuf::from(&real_dir);
if let Ok(pb_metadata) = pb.metadata() { if let Ok(pb_metadata) = pb.metadata() {
if !pb_metadata.is_dir() { if !pb_metadata.is_dir() {
@@ -23,11 +21,23 @@ pub fn parse_mapdir(entry: &str) -> Result<(String, PathBuf)> {
bail!("Directory \"{}\" does not exist", &real_dir); bail!("Directory \"{}\" does not exist", &real_dir);
} }
return Ok((alias.to_string(), pb)); return Ok((alias.to_string(), pb));
}
/// Parses a mapdir from a string
pub fn parse_mapdir(entry: &str) -> Result<(String, PathBuf)> {
// We try first splitting by `::`
if let [alias, real_dir] = entry.split("::").collect::<Vec<&str>>()[..] {
retrieve_alias_pathbuf(alias, real_dir)
} }
// And then we try splitting by `:` (for compatibility with previous API)
else if let [alias, real_dir] = entry.split(':').collect::<Vec<&str>>()[..] {
retrieve_alias_pathbuf(alias, real_dir)
} else {
bail!( bail!(
"Directory mappings must consist of two paths separate by a colon. Found {}", "Directory mappings must consist of two paths separate by a `::` or `:`. Found {}",
&entry &entry
) )
}
} }
/// Parses a mapdir from an env var /// Parses a mapdir from an env var

View File

@@ -1,170 +0,0 @@
use crate::utils::get_store;
use anyhow::Result;
use std::cell::RefCell;
use std::rc::Rc;
use wasmer::*;
#[test]
fn native_function_works_for_wasm() -> Result<()> {
let store = get_store();
let wat = r#"(module
(func $multiply (import "env" "multiply") (param i32 i32) (result i32))
(func (export "add") (param i32 i32) (result i32)
(i32.add (local.get 0)
(local.get 1)))
(func (export "double_then_add") (param i32 i32) (result i32)
(i32.add (call $multiply (local.get 0) (i32.const 2))
(call $multiply (local.get 1) (i32.const 2))))
)"#;
let module = Module::new(&store, wat).unwrap();
let import_object = imports! {
"env" => {
"multiply" => Function::new(&store, |a: i32, b: i32| a * b),
},
};
let instance = Instance::new(&module, &import_object)?;
let f: NativeFunc<(i32, i32), i32> = instance.exports.get_native_function("add")?;
let result = f.call(4, 6)?;
assert_eq!(result, 10);
let dyn_f: &Function = instance.exports.get("double_then_add")?;
let dyn_result = dyn_f.call(&[Val::I32(4), Val::I32(6)])?;
assert_eq!(dyn_result[0], Val::I32(20));
let f: NativeFunc<(i32, i32), i32> = dyn_f.native().unwrap();
let result = f.call(4, 6)?;
assert_eq!(result, 20);
Ok(())
}
#[test]
fn static_raw_call_no_env() -> anyhow::Result<()> {
let store = get_store();
fn reverse_duplicate_host(a: i32, b: i64, c: f32, d: f64) -> (f64, f32, i64, i32) {
(d * 4.0, c * 3.0, b * 2, a * 1)
}
let reverse_duplicate = wasmer::Function::new(&store, reverse_duplicate_host);
let reverse_duplicate_native: NativeFunc<(i32, i64, f32, f64), (f64, f32, i64, i32)> =
reverse_duplicate.native().unwrap();
let result = reverse_duplicate_native.call(1, 3, 5.0, 7.0)?;
assert_eq!(result, (28.0, 15.0, 6, 1));
Ok(())
}
#[test]
fn static_raw_call_with_env() -> anyhow::Result<()> {
let store = get_store();
#[derive(Clone)]
struct Env {
val: Rc<RefCell<i32>>,
};
let env = Env {
val: Rc::new(RefCell::new(100)),
};
fn reverse_duplicate_host(
env: &mut Env,
a: i32,
b: i64,
c: f32,
d: f64,
) -> (f64, f32, i64, i32) {
assert_eq!(*env.val.borrow(), 100);
env.val.replace(101);
(d * 4.0, c * 3.0, b * 2, a * 1)
}
let reverse_duplicate = wasmer::Function::new_env(&store, env.clone(), reverse_duplicate_host);
let reverse_duplicate_native: NativeFunc<(i32, i64, f32, f64), (f64, f32, i64, i32)> =
reverse_duplicate.native().unwrap();
assert_eq!(*env.val.borrow(), 100);
let result = reverse_duplicate_native.call(1, 3, 5.0, 7.0)?;
assert_eq!(result, (28.0, 15.0, 6, 1));
assert_eq!(*env.val.borrow(), 101);
Ok(())
}
#[test]
fn dynamic_raw_call_no_env() -> anyhow::Result<()> {
let store = get_store();
let reverse_duplicate = wasmer::Function::new_dynamic(
&store,
&wasmer::FunctionType::new(
vec![
wasmer::ValType::I32,
wasmer::ValType::I64,
wasmer::ValType::F32,
wasmer::ValType::F64,
],
vec![
wasmer::ValType::F64,
wasmer::ValType::F32,
wasmer::ValType::I64,
wasmer::ValType::I32,
],
),
|values| {
Ok(vec![
Value::F64(values[3].unwrap_f64() * 4.0),
Value::F32(values[2].unwrap_f32() * 3.0),
Value::I64(values[1].unwrap_i64() * 2),
Value::I32(values[0].unwrap_i32() * 1),
])
},
);
let reverse_duplicate_native: NativeFunc<(i32, i64, f32, f64), (f64, f32, i64, i32)> =
reverse_duplicate.native().unwrap();
let result = reverse_duplicate_native.call(1, 3, 5.0, 7.0)?;
assert_eq!(result, (28.0, 15.0, 6, 1));
Ok(())
}
#[test]
fn dynamic_raw_call_with_env() -> anyhow::Result<()> {
let store = get_store();
#[derive(Clone)]
struct Env {
val: Rc<RefCell<i32>>,
};
let env = Env {
val: Rc::new(RefCell::new(100)),
};
let reverse_duplicate = wasmer::Function::new_dynamic_env(
&store,
&wasmer::FunctionType::new(
vec![
wasmer::ValType::I32,
wasmer::ValType::I64,
wasmer::ValType::F32,
wasmer::ValType::F64,
],
vec![
wasmer::ValType::F64,
wasmer::ValType::F32,
wasmer::ValType::I64,
wasmer::ValType::I32,
],
),
env.clone(),
|env, values| {
assert_eq!(*env.val.borrow(), 100);
env.val.replace(101);
Ok(vec![
Value::F64(values[3].unwrap_f64() * 4.0),
Value::F32(values[2].unwrap_f32() * 3.0),
Value::I64(values[1].unwrap_i64() * 2),
Value::I32(values[0].unwrap_i32() * 1),
])
},
);
let reverse_duplicate_native: NativeFunc<(i32, i64, f32, f64), (f64, f32, i64, i32)> =
reverse_duplicate.native().unwrap();
assert_eq!(*env.val.borrow(), 100);
let result = reverse_duplicate_native.call(1, 3, 5.0, 7.0)?;
assert_eq!(result, (28.0, 15.0, 6, 1));
assert_eq!(*env.val.borrow(), 101);
Ok(())
}

View File

@@ -4,8 +4,11 @@
use crate::utils::get_store; use crate::utils::get_store;
use anyhow::Result; use anyhow::Result;
use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; use std::convert::Infallible;
use std::sync::Arc; use std::sync::{
atomic::{AtomicUsize, Ordering::SeqCst},
Arc,
};
use wasmer::*; use wasmer::*;
fn get_module(store: &Store) -> Result<Module> { fn get_module(store: &Store) -> Result<Module> {
@@ -120,7 +123,7 @@ fn dynamic_function_with_env() -> Result<()> {
} }
#[test] #[test]
fn native_function() -> Result<()> { fn static_function() -> Result<()> {
let store = get_store(); let store = get_store();
let module = get_module(&store)?; let module = get_module(&store)?;
@@ -158,7 +161,45 @@ fn native_function() -> Result<()> {
} }
#[test] #[test]
fn native_function_with_env() -> Result<()> { fn static_function_with_results() -> Result<()> {
let store = get_store();
let module = get_module(&store)?;
static HITS: AtomicUsize = AtomicUsize::new(0);
Instance::new(
&module,
&imports! {
"host" => {
"0" => Function::new(&store, || {
assert_eq!(HITS.fetch_add(1, SeqCst), 0);
}),
"1" => Function::new(&store, |x: i32| -> Result<i32, Infallible> {
assert_eq!(x, 0);
assert_eq!(HITS.fetch_add(1, SeqCst), 1);
Ok(1)
}),
"2" => Function::new(&store, |x: i32, y: i64| {
assert_eq!(x, 2);
assert_eq!(y, 3);
assert_eq!(HITS.fetch_add(1, SeqCst), 2);
}),
"3" => Function::new(&store, |a: i32, b: i64, c: i32, d: f32, e: f64| {
assert_eq!(a, 100);
assert_eq!(b, 200);
assert_eq!(c, 300);
assert_eq!(d, 400.0);
assert_eq!(e, 500.0);
assert_eq!(HITS.fetch_add(1, SeqCst), 3);
}),
},
},
)?;
assert_eq!(HITS.load(SeqCst), 4);
Ok(())
}
#[test]
fn static_function_with_env() -> Result<()> {
let store = get_store(); let store = get_store();
let module = get_module(&store)?; let module = get_module(&store)?;
@@ -194,3 +235,42 @@ fn native_function_with_env() -> Result<()> {
assert_eq!(env.load(SeqCst), 4); assert_eq!(env.load(SeqCst), 4);
Ok(()) Ok(())
} }
#[test]
fn static_function_that_fails() -> Result<()> {
use std::{error, fmt};
let store = get_store();
let wat = r#"
(import "host" "0" (func))
(func $foo
call 0
)
(start $foo)
"#;
let module = Module::new(&store, &wat)?;
let result = Instance::new(
&module,
&imports! {
"host" => {
"0" => Function::new(&store, || -> Result<Infallible, RuntimeError> {
Err(RuntimeError::new("oops"))
}),
},
},
);
assert!(result.is_err());
match result {
Err(InstantiationError::Start(runtime_error)) => {
assert_eq!(runtime_error.message(), "oops")
}
_ => assert!(false),
}
Ok(())
}

View File

@@ -4,10 +4,10 @@
//! implementation, such as: singlepass, cranelift or llvm depending //! implementation, such as: singlepass, cranelift or llvm depending
//! on what's available on the target. //! on what's available on the target.
mod functions;
mod imports; mod imports;
mod middlewares; mod middlewares;
mod multi_value_imports; mod multi_value_imports;
mod native_functions;
mod serialize; mod serialize;
mod traps; mod traps;
mod utils; mod utils;

View File

@@ -0,0 +1,210 @@
use crate::utils::get_store;
use anyhow::Result;
use std::cell::RefCell;
use std::convert::Infallible;
use std::rc::Rc;
use wasmer::*;
#[test]
fn native_function_works_for_wasm() -> Result<()> {
let store = get_store();
let wat = r#"(module
(func $multiply (import "env" "multiply") (param i32 i32) (result i32))
(func (export "add") (param i32 i32) (result i32)
(i32.add (local.get 0)
(local.get 1)))
(func (export "double_then_add") (param i32 i32) (result i32)
(i32.add (call $multiply (local.get 0) (i32.const 2))
(call $multiply (local.get 1) (i32.const 2))))
)"#;
let module = Module::new(&store, wat).unwrap();
let import_object = imports! {
"env" => {
"multiply" => Function::new(&store, |a: i32, b: i32| a * b),
},
};
let instance = Instance::new(&module, &import_object)?;
{
let f: NativeFunc<(i32, i32), i32> = instance.exports.get_native_function("add")?;
let result = f.call(4, 6)?;
assert_eq!(result, 10);
}
{
let f: &Function = instance.exports.get("double_then_add")?;
let result = f.call(&[Val::I32(4), Val::I32(6)])?;
assert_eq!(result[0], Val::I32(20));
}
{
let dyn_f: &Function = instance.exports.get("double_then_add")?;
let f: NativeFunc<(i32, i32), i32> = dyn_f.native().unwrap();
let result = f.call(4, 6)?;
assert_eq!(result, 20);
}
Ok(())
}
#[test]
fn static_host_function_without_env() -> anyhow::Result<()> {
let store = get_store();
fn f(a: i32, b: i64, c: f32, d: f64) -> (f64, f32, i64, i32) {
(d * 4.0, c * 3.0, b * 2, a * 1)
}
fn f_ok(a: i32, b: i64, c: f32, d: f64) -> Result<(f64, f32, i64, i32), Infallible> {
Ok((d * 4.0, c * 3.0, b * 2, a * 1))
}
// Native static host function that returns a tuple.
{
let f = Function::new(&store, f);
let f_native: NativeFunc<(i32, i64, f32, f64), (f64, f32, i64, i32)> = f.native().unwrap();
let result = f_native.call(1, 3, 5.0, 7.0)?;
assert_eq!(result, (28.0, 15.0, 6, 1));
}
// Native static host function that returns a result of a tuple.
{
let f = Function::new(&store, f_ok);
let f_native: NativeFunc<(i32, i64, f32, f64), (f64, f32, i64, i32)> = f.native().unwrap();
let result = f_native.call(1, 3, 5.0, 7.0)?;
assert_eq!(result, (28.0, 15.0, 6, 1));
}
Ok(())
}
#[test]
fn static_host_function_with_env() -> anyhow::Result<()> {
let store = get_store();
fn f(env: &mut Env, a: i32, b: i64, c: f32, d: f64) -> (f64, f32, i64, i32) {
assert_eq!(*env.0.borrow(), 100);
env.0.replace(101);
(d * 4.0, c * 3.0, b * 2, a * 1)
}
fn f_ok(
env: &mut Env,
a: i32,
b: i64,
c: f32,
d: f64,
) -> Result<(f64, f32, i64, i32), Infallible> {
assert_eq!(*env.0.borrow(), 100);
env.0.replace(101);
Ok((d * 4.0, c * 3.0, b * 2, a * 1))
}
#[derive(Clone)]
struct Env(Rc<RefCell<i32>>);
// Native static host function that returns a tuple.
{
let env = Env(Rc::new(RefCell::new(100)));
let f = Function::new_env(&store, env.clone(), f);
let f_native: NativeFunc<(i32, i64, f32, f64), (f64, f32, i64, i32)> = f.native().unwrap();
assert_eq!(*env.0.borrow(), 100);
let result = f_native.call(1, 3, 5.0, 7.0)?;
assert_eq!(result, (28.0, 15.0, 6, 1));
assert_eq!(*env.0.borrow(), 101);
}
// Native static host function that returns a result of a tuple.
{
let env = Env(Rc::new(RefCell::new(100)));
let f = Function::new_env(&store, env.clone(), f);
let f_native: NativeFunc<(i32, i64, f32, f64), (f64, f32, i64, i32)> = f.native().unwrap();
assert_eq!(*env.0.borrow(), 100);
let result = f_native.call(1, 3, 5.0, 7.0)?;
assert_eq!(result, (28.0, 15.0, 6, 1));
assert_eq!(*env.0.borrow(), 101);
}
Ok(())
}
#[test]
fn dynamic_host_function_without_env() -> anyhow::Result<()> {
let store = get_store();
let f = Function::new_dynamic(
&store,
&FunctionType::new(
vec![ValType::I32, ValType::I64, ValType::F32, ValType::F64],
vec![ValType::F64, ValType::F32, ValType::I64, ValType::I32],
),
|values| {
Ok(vec![
Value::F64(values[3].unwrap_f64() * 4.0),
Value::F32(values[2].unwrap_f32() * 3.0),
Value::I64(values[1].unwrap_i64() * 2),
Value::I32(values[0].unwrap_i32() * 1),
])
},
);
let f_native: NativeFunc<(i32, i64, f32, f64), (f64, f32, i64, i32)> = f.native().unwrap();
let result = f_native.call(1, 3, 5.0, 7.0)?;
assert_eq!(result, (28.0, 15.0, 6, 1));
Ok(())
}
#[test]
fn dynamic_host_function_with_env() -> anyhow::Result<()> {
let store = get_store();
#[derive(Clone)]
struct Env(Rc<RefCell<i32>>);
let env = Env(Rc::new(RefCell::new(100)));
let f = Function::new_dynamic_env(
&store,
&FunctionType::new(
vec![ValType::I32, ValType::I64, ValType::F32, ValType::F64],
vec![ValType::F64, ValType::F32, ValType::I64, ValType::I32],
),
env.clone(),
|env, values| {
assert_eq!(*env.0.borrow(), 100);
env.0.replace(101);
Ok(vec![
Value::F64(values[3].unwrap_f64() * 4.0),
Value::F32(values[2].unwrap_f32() * 3.0),
Value::I64(values[1].unwrap_i64() * 2),
Value::I32(values[0].unwrap_i32() * 1),
])
},
);
let f_native: NativeFunc<(i32, i64, f32, f64), (f64, f32, i64, i32)> = f.native().unwrap();
assert_eq!(*env.0.borrow(), 100);
let result = f_native.call(1, 3, 5.0, 7.0)?;
assert_eq!(result, (28.0, 15.0, 6, 1));
assert_eq!(*env.0.borrow(), 101);
Ok(())
}

View File

@@ -9,7 +9,7 @@ publish = false
[dependencies] [dependencies]
wasm-common = { path = "../../../lib/wasm-common", version = "1.0.0-alpha.1" } wasm-common = { path = "../../../lib/wasm-common", version = "1.0.0-alpha.1" }
wasmer-compiler = { path = "../../../lib/compiler", version = "1.0.0-alpha.1" } wasmer-compiler = { path = "../../../lib/compiler", version = "1.0.0-alpha.1" }
wasmer-runtime = { path = "../../../lib/runtime", version = "1.0.0-alpha.1" } wasmer-vm = { path = "../../../lib/vm", version = "1.0.0-alpha.1" }
wasmer-engine = { path = "../../../lib/engine", version = "1.0.0-alpha.1" } wasmer-engine = { path = "../../../lib/engine", version = "1.0.0-alpha.1" }
serde = { version = "1.0", features = ["derive", "rc"], optional = true } serde = { version = "1.0", features = ["derive", "rc"], optional = true }
serde_bytes = { version = "0.11", optional = true } serde_bytes = { version = "0.11", optional = true }

View File

@@ -14,8 +14,8 @@ use wasmer_compiler::CompileError;
#[cfg(feature = "compiler")] #[cfg(feature = "compiler")]
use wasmer_compiler::ModuleEnvironment; use wasmer_compiler::ModuleEnvironment;
use wasmer_engine::{Artifact, DeserializeError, Engine as _, SerializeError, Tunables}; use wasmer_engine::{Artifact, DeserializeError, Engine as _, SerializeError, Tunables};
use wasmer_runtime::{ use wasmer_vm::{
FunctionBodyPtr, MemoryPlan, ModuleInfo, TablePlan, VMContext, VMFunctionBody, FunctionBodyPtr, MemoryStyle, ModuleInfo, TableStyle, VMContext, VMFunctionBody,
VMSharedSignatureIndex, VMSharedSignatureIndex,
}; };
@@ -26,8 +26,8 @@ pub struct DummyArtifactMetadata {
pub features: Features, pub features: Features,
pub data_initializers: Box<[OwnedDataInitializer]>, pub data_initializers: Box<[OwnedDataInitializer]>,
// Plans for that module // Plans for that module
pub memory_plans: PrimaryMap<MemoryIndex, MemoryPlan>, pub memory_styles: PrimaryMap<MemoryIndex, MemoryStyle>,
pub table_plans: PrimaryMap<TableIndex, TablePlan>, pub table_styles: PrimaryMap<TableIndex, TableStyle>,
} }
/// A Dummy artifact. /// A Dummy artifact.
@@ -65,17 +65,17 @@ impl DummyArtifact {
let translation = environ.translate(data).map_err(CompileError::Wasm)?; let translation = environ.translate(data).map_err(CompileError::Wasm)?;
let memory_plans: PrimaryMap<MemoryIndex, MemoryPlan> = translation let memory_styles: PrimaryMap<MemoryIndex, MemoryStyle> = translation
.module .module
.memories .memories
.values() .values()
.map(|memory_type| tunables.memory_plan(*memory_type)) .map(|memory_type| tunables.memory_style(memory_type))
.collect(); .collect();
let table_plans: PrimaryMap<TableIndex, TablePlan> = translation let table_styles: PrimaryMap<TableIndex, TableStyle> = translation
.module .module
.tables .tables
.values() .values()
.map(|table_type| tunables.table_plan(*table_type)) .map(|table_type| tunables.table_style(table_type))
.collect(); .collect();
let data_initializers = translation let data_initializers = translation
@@ -89,8 +89,8 @@ impl DummyArtifact {
module: Arc::new(translation.module), module: Arc::new(translation.module),
features: Features::default(), features: Features::default(),
data_initializers, data_initializers,
memory_plans, memory_styles,
table_plans, table_styles,
}; };
Self::from_parts(&engine, metadata) Self::from_parts(&engine, metadata)
} }
@@ -203,12 +203,12 @@ impl Artifact for DummyArtifact {
&*self.metadata.data_initializers &*self.metadata.data_initializers
} }
fn memory_plans(&self) -> &PrimaryMap<MemoryIndex, MemoryPlan> { fn memory_styles(&self) -> &PrimaryMap<MemoryIndex, MemoryStyle> {
&self.metadata.memory_plans &self.metadata.memory_styles
} }
fn table_plans(&self) -> &PrimaryMap<TableIndex, TablePlan> { fn table_styles(&self) -> &PrimaryMap<TableIndex, TableStyle> {
&self.metadata.table_plans &self.metadata.table_styles
} }
fn finished_functions(&self) -> &BoxedSlice<LocalFunctionIndex, FunctionBodyPtr> { fn finished_functions(&self) -> &BoxedSlice<LocalFunctionIndex, FunctionBodyPtr> {

View File

@@ -5,7 +5,7 @@ use std::sync::Arc;
use wasm_common::FunctionType; use wasm_common::FunctionType;
use wasmer_compiler::{CompileError, Features, Target}; use wasmer_compiler::{CompileError, Features, Target};
use wasmer_engine::{Artifact, DeserializeError, Engine, EngineId, Tunables}; use wasmer_engine::{Artifact, DeserializeError, Engine, EngineId, Tunables};
use wasmer_runtime::{ use wasmer_vm::{
SignatureRegistry, VMContext, VMFunctionBody, VMSharedSignatureIndex, VMTrampoline, SignatureRegistry, VMContext, VMFunctionBody, VMSharedSignatureIndex, VMTrampoline,
}; };

View File

@@ -360,9 +360,15 @@ fn extract_args_from_source_file(source_code: &str) -> Option<WasiOptions> {
match command_name.as_ref() { match command_name.as_ref() {
"mapdir" => { "mapdir" => {
if let [alias, real_dir] = &tokenized[1].split(':').collect::<Vec<&str>>()[..] { // We try first splitting by `::`
if let [alias, real_dir] = &tokenized[1].split("::").collect::<Vec<&str>>()[..] {
args.mapdir.push((alias.to_string(), real_dir.to_string())); args.mapdir.push((alias.to_string(), real_dir.to_string()));
} else { }
// And then we try splitting by `:` (for compatibility with previous API)
else if let [alias, real_dir] = &tokenized[1].split(':').collect::<Vec<&str>>()[..] {
args.mapdir.push((alias.to_string(), real_dir.to_string()));
}
else {
eprintln!( eprintln!(
"Parse error in mapdir {} not parsed correctly", "Parse error in mapdir {} not parsed correctly",
&tokenized[1] &tokenized[1]
@@ -372,7 +378,8 @@ fn extract_args_from_source_file(source_code: &str) -> Option<WasiOptions> {
"env" => { "env" => {
if let [name, val] = &tokenized[1].split('=').collect::<Vec<&str>>()[..] { if let [name, val] = &tokenized[1].split('=').collect::<Vec<&str>>()[..] {
args.env.push((name.to_string(), val.to_string())); args.env.push((name.to_string(), val.to_string()));
} else { }
else {
eprintln!("Parse error in env {} not parsed correctly", &tokenized[1]); eprintln!("Parse error in env {} not parsed correctly", &tokenized[1]);
} }
} }