├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── IDEAS.md ├── LICENSE ├── README.md ├── cli ├── Cargo.toml └── bin │ └── wasmo.rs ├── clippy.toml ├── media └── resolution.png ├── runtime ├── Cargo.toml ├── examples │ └── module.rs └── lib │ ├── api.rs │ ├── api │ ├── imports.rs │ ├── imports │ │ ├── imports.rs │ │ ├── memory.rs │ │ └── table.rs │ ├── instance.rs │ ├── module.rs │ ├── options.rs │ ├── store.rs │ └── store │ │ └── store.rs │ ├── compiler.rs │ ├── compiler │ ├── compiler.rs │ ├── data.rs │ ├── elem.rs │ ├── exports.rs │ ├── function.rs │ ├── global.rs │ ├── imports.rs │ ├── llvm.rs │ ├── llvm │ │ ├── basic_block.rs │ │ ├── context.rs │ │ ├── function.rs │ │ ├── llvm.rs │ │ ├── module.rs │ │ ├── orc.rs │ │ ├── target.rs │ │ ├── target_machine.rs │ │ └── types.rs │ ├── memory.rs │ ├── table.rs │ ├── utils.rs │ └── value.rs │ ├── context.rs │ ├── context │ ├── address.rs │ └── sizes.rs │ ├── errors.rs │ ├── intrinsics.rs │ ├── intrinsics │ └── memory.rs │ ├── lib.rs │ └── types.rs └── tests ├── Cargo.toml ├── lib.rs ├── runtime.rs ├── runtime └── module.rs └── samples ├── add.wat └── fibonacci.wat /.gitignore: -------------------------------------------------------------------------------- 1 | **/target 2 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "aho-corasick" 7 | version = "0.7.18" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f" 10 | dependencies = [ 11 | "memchr", 12 | ] 13 | 14 | [[package]] 15 | name = "anyhow" 16 | version = "1.0.56" 17 | source = "registry+https://github.com/rust-lang/crates.io-index" 18 | checksum = "4361135be9122e0870de935d7c439aef945b9f9ddd4199a553b5270b49c82a27" 19 | 20 | [[package]] 21 | name = "atty" 22 | version = "0.2.14" 23 | source = "registry+https://github.com/rust-lang/crates.io-index" 24 | checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" 25 | dependencies = [ 26 | "hermit-abi", 27 | "libc", 28 | "winapi", 29 | ] 30 | 31 | [[package]] 32 | name = "autocfg" 33 | version = "1.1.0" 34 | source = "registry+https://github.com/rust-lang/crates.io-index" 35 | checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" 36 | 37 | [[package]] 38 | name = "bincode" 39 | version = "1.3.3" 40 | source = "registry+https://github.com/rust-lang/crates.io-index" 41 | checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" 42 | dependencies = [ 43 | "serde", 44 | ] 45 | 46 | [[package]] 47 | name = "bitflags" 48 | version = "1.3.2" 49 | source = "registry+https://github.com/rust-lang/crates.io-index" 50 | checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" 51 | 52 | [[package]] 53 | name = "bytecheck" 54 | version = "0.6.7" 55 | source = "registry+https://github.com/rust-lang/crates.io-index" 56 | checksum = "314889ea31cda264cb7c3d6e6e5c9415a987ecb0e72c17c00d36fbb881d34abe" 57 | dependencies = [ 58 | "bytecheck_derive", 59 | "ptr_meta", 60 | ] 61 | 62 | [[package]] 63 | name = "bytecheck_derive" 64 | version = "0.6.7" 65 | source = "registry+https://github.com/rust-lang/crates.io-index" 66 | checksum = "4a2b3b92c135dae665a6f760205b89187638e83bed17ef3e44e83c712cf30600" 67 | dependencies = [ 68 | "proc-macro2", 69 | "quote", 70 | "syn", 71 | ] 72 | 73 | [[package]] 74 | name = "cc" 75 | version = "1.0.73" 76 | source = "registry+https://github.com/rust-lang/crates.io-index" 77 | checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11" 78 | 79 | [[package]] 80 | name = "cfg-if" 81 | version = "1.0.0" 82 | source = "registry+https://github.com/rust-lang/crates.io-index" 83 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 84 | 85 | [[package]] 86 | name = "clap" 87 | version = "3.1.8" 88 | source = "registry+https://github.com/rust-lang/crates.io-index" 89 | checksum = "71c47df61d9e16dc010b55dba1952a57d8c215dbb533fd13cdd13369aac73b1c" 90 | dependencies = [ 91 | "atty", 92 | "bitflags", 93 | "clap_derive", 94 | "indexmap", 95 | "lazy_static", 96 | "os_str_bytes", 97 | "strsim", 98 | "termcolor", 99 | "textwrap", 100 | ] 101 | 102 | [[package]] 103 | name = "clap_derive" 104 | version = "3.1.7" 105 | source = "registry+https://github.com/rust-lang/crates.io-index" 106 | checksum = "a3aab4734e083b809aaf5794e14e756d1c798d2c69c7f7de7a09a2f5214993c1" 107 | dependencies = [ 108 | "heck", 109 | "proc-macro-error", 110 | "proc-macro2", 111 | "quote", 112 | "syn", 113 | ] 114 | 115 | [[package]] 116 | name = "env_logger" 117 | version = "0.9.0" 118 | source = "registry+https://github.com/rust-lang/crates.io-index" 119 | checksum = "0b2cf0344971ee6c64c31be0d530793fba457d322dfec2810c453d0ef228f9c3" 120 | dependencies = [ 121 | "atty", 122 | "humantime", 123 | "log", 124 | "regex", 125 | "termcolor", 126 | ] 127 | 128 | [[package]] 129 | name = "hashbrown" 130 | version = "0.11.2" 131 | source = "registry+https://github.com/rust-lang/crates.io-index" 132 | checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" 133 | 134 | [[package]] 135 | name = "heck" 136 | version = "0.4.0" 137 | source = "registry+https://github.com/rust-lang/crates.io-index" 138 | checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9" 139 | 140 | [[package]] 141 | name = "hermit-abi" 142 | version = "0.1.19" 143 | source = "registry+https://github.com/rust-lang/crates.io-index" 144 | checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" 145 | dependencies = [ 146 | "libc", 147 | ] 148 | 149 | [[package]] 150 | name = "humantime" 151 | version = "2.1.0" 152 | source = "registry+https://github.com/rust-lang/crates.io-index" 153 | checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" 154 | 155 | [[package]] 156 | name = "indexmap" 157 | version = "1.8.1" 158 | source = "registry+https://github.com/rust-lang/crates.io-index" 159 | checksum = "0f647032dfaa1f8b6dc29bd3edb7bbef4861b8b8007ebb118d6db284fd59f6ee" 160 | dependencies = [ 161 | "autocfg", 162 | "hashbrown", 163 | ] 164 | 165 | [[package]] 166 | name = "lazy_static" 167 | version = "1.4.0" 168 | source = "registry+https://github.com/rust-lang/crates.io-index" 169 | checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" 170 | 171 | [[package]] 172 | name = "leb128" 173 | version = "0.2.5" 174 | source = "registry+https://github.com/rust-lang/crates.io-index" 175 | checksum = "884e2677b40cc8c339eaefcb701c32ef1fd2493d71118dc0ca4b6a736c93bd67" 176 | 177 | [[package]] 178 | name = "libc" 179 | version = "0.2.121" 180 | source = "registry+https://github.com/rust-lang/crates.io-index" 181 | checksum = "efaa7b300f3b5fe8eb6bf21ce3895e1751d9665086af2d64b42f19701015ff4f" 182 | 183 | [[package]] 184 | name = "llvm-sys" 185 | version = "130.0.3" 186 | source = "registry+https://github.com/rust-lang/crates.io-index" 187 | checksum = "95eb03b4f7ae21f48ef7c565a3e3aa22c50616aea64645fb1fd7f6f56b51c274" 188 | dependencies = [ 189 | "cc", 190 | "lazy_static", 191 | "libc", 192 | "regex", 193 | "semver", 194 | ] 195 | 196 | [[package]] 197 | name = "log" 198 | version = "0.4.16" 199 | source = "registry+https://github.com/rust-lang/crates.io-index" 200 | checksum = "6389c490849ff5bc16be905ae24bc913a9c8892e19b2341dbc175e14c341c2b8" 201 | dependencies = [ 202 | "cfg-if", 203 | ] 204 | 205 | [[package]] 206 | name = "memchr" 207 | version = "2.4.1" 208 | source = "registry+https://github.com/rust-lang/crates.io-index" 209 | checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a" 210 | 211 | [[package]] 212 | name = "os_str_bytes" 213 | version = "6.0.0" 214 | source = "registry+https://github.com/rust-lang/crates.io-index" 215 | checksum = "8e22443d1643a904602595ba1cd8f7d896afe56d26712531c5ff73a15b2fbf64" 216 | dependencies = [ 217 | "memchr", 218 | ] 219 | 220 | [[package]] 221 | name = "pest" 222 | version = "2.1.3" 223 | source = "registry+https://github.com/rust-lang/crates.io-index" 224 | checksum = "10f4872ae94d7b90ae48754df22fd42ad52ce740b8f370b03da4835417403e53" 225 | dependencies = [ 226 | "ucd-trie", 227 | ] 228 | 229 | [[package]] 230 | name = "proc-macro-error" 231 | version = "1.0.4" 232 | source = "registry+https://github.com/rust-lang/crates.io-index" 233 | checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" 234 | dependencies = [ 235 | "proc-macro-error-attr", 236 | "proc-macro2", 237 | "quote", 238 | "syn", 239 | "version_check", 240 | ] 241 | 242 | [[package]] 243 | name = "proc-macro-error-attr" 244 | version = "1.0.4" 245 | source = "registry+https://github.com/rust-lang/crates.io-index" 246 | checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" 247 | dependencies = [ 248 | "proc-macro2", 249 | "quote", 250 | "version_check", 251 | ] 252 | 253 | [[package]] 254 | name = "proc-macro2" 255 | version = "1.0.36" 256 | source = "registry+https://github.com/rust-lang/crates.io-index" 257 | checksum = "c7342d5883fbccae1cc37a2353b09c87c9b0f3afd73f5fb9bba687a1f733b029" 258 | dependencies = [ 259 | "unicode-xid", 260 | ] 261 | 262 | [[package]] 263 | name = "ptr_meta" 264 | version = "0.1.4" 265 | source = "registry+https://github.com/rust-lang/crates.io-index" 266 | checksum = "0738ccf7ea06b608c10564b31debd4f5bc5e197fc8bfe088f68ae5ce81e7a4f1" 267 | dependencies = [ 268 | "ptr_meta_derive", 269 | ] 270 | 271 | [[package]] 272 | name = "ptr_meta_derive" 273 | version = "0.1.4" 274 | source = "registry+https://github.com/rust-lang/crates.io-index" 275 | checksum = "16b845dbfca988fa33db069c0e230574d15a3088f147a87b64c7589eb662c9ac" 276 | dependencies = [ 277 | "proc-macro2", 278 | "quote", 279 | "syn", 280 | ] 281 | 282 | [[package]] 283 | name = "quote" 284 | version = "1.0.17" 285 | source = "registry+https://github.com/rust-lang/crates.io-index" 286 | checksum = "632d02bff7f874a36f33ea8bb416cd484b90cc66c1194b1a1110d067a7013f58" 287 | dependencies = [ 288 | "proc-macro2", 289 | ] 290 | 291 | [[package]] 292 | name = "regex" 293 | version = "1.5.5" 294 | source = "registry+https://github.com/rust-lang/crates.io-index" 295 | checksum = "1a11647b6b25ff05a515cb92c365cec08801e83423a235b51e231e1808747286" 296 | dependencies = [ 297 | "aho-corasick", 298 | "memchr", 299 | "regex-syntax", 300 | ] 301 | 302 | [[package]] 303 | name = "regex-syntax" 304 | version = "0.6.25" 305 | source = "registry+https://github.com/rust-lang/crates.io-index" 306 | checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b" 307 | 308 | [[package]] 309 | name = "semver" 310 | version = "0.11.0" 311 | source = "registry+https://github.com/rust-lang/crates.io-index" 312 | checksum = "f301af10236f6df4160f7c3f04eec6dbc70ace82d23326abad5edee88801c6b6" 313 | dependencies = [ 314 | "semver-parser", 315 | ] 316 | 317 | [[package]] 318 | name = "semver-parser" 319 | version = "0.10.2" 320 | source = "registry+https://github.com/rust-lang/crates.io-index" 321 | checksum = "00b0bef5b7f9e0df16536d3961cfb6e84331c065b4066afb39768d0e319411f7" 322 | dependencies = [ 323 | "pest", 324 | ] 325 | 326 | [[package]] 327 | name = "serde" 328 | version = "1.0.136" 329 | source = "registry+https://github.com/rust-lang/crates.io-index" 330 | checksum = "ce31e24b01e1e524df96f1c2fdd054405f8d7376249a5110886fb4b658484789" 331 | dependencies = [ 332 | "serde_derive", 333 | ] 334 | 335 | [[package]] 336 | name = "serde_derive" 337 | version = "1.0.136" 338 | source = "registry+https://github.com/rust-lang/crates.io-index" 339 | checksum = "08597e7152fcd306f41838ed3e37be9eaeed2b61c42e2117266a554fab4662f9" 340 | dependencies = [ 341 | "proc-macro2", 342 | "quote", 343 | "syn", 344 | ] 345 | 346 | [[package]] 347 | name = "strsim" 348 | version = "0.10.0" 349 | source = "registry+https://github.com/rust-lang/crates.io-index" 350 | checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" 351 | 352 | [[package]] 353 | name = "syn" 354 | version = "1.0.90" 355 | source = "registry+https://github.com/rust-lang/crates.io-index" 356 | checksum = "704df27628939572cd88d33f171cd6f896f4eaca85252c6e0a72d8d8287ee86f" 357 | dependencies = [ 358 | "proc-macro2", 359 | "quote", 360 | "unicode-xid", 361 | ] 362 | 363 | [[package]] 364 | name = "termcolor" 365 | version = "1.1.3" 366 | source = "registry+https://github.com/rust-lang/crates.io-index" 367 | checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" 368 | dependencies = [ 369 | "winapi-util", 370 | ] 371 | 372 | [[package]] 373 | name = "textwrap" 374 | version = "0.15.0" 375 | source = "registry+https://github.com/rust-lang/crates.io-index" 376 | checksum = "b1141d4d61095b28419e22cb0bbf02755f5e54e0526f97f1e3d1d160e60885fb" 377 | 378 | [[package]] 379 | name = "ucd-trie" 380 | version = "0.1.3" 381 | source = "registry+https://github.com/rust-lang/crates.io-index" 382 | checksum = "56dee185309b50d1f11bfedef0fe6d036842e3fb77413abef29f8f8d1c5d4c1c" 383 | 384 | [[package]] 385 | name = "unicode-width" 386 | version = "0.1.9" 387 | source = "registry+https://github.com/rust-lang/crates.io-index" 388 | checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973" 389 | 390 | [[package]] 391 | name = "unicode-xid" 392 | version = "0.2.2" 393 | source = "registry+https://github.com/rust-lang/crates.io-index" 394 | checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" 395 | 396 | [[package]] 397 | name = "version_check" 398 | version = "0.9.4" 399 | source = "registry+https://github.com/rust-lang/crates.io-index" 400 | checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" 401 | 402 | [[package]] 403 | name = "wasmo_cli" 404 | version = "0.1.0" 405 | dependencies = [ 406 | "clap", 407 | ] 408 | 409 | [[package]] 410 | name = "wasmo_runtime" 411 | version = "0.1.0" 412 | dependencies = [ 413 | "anyhow", 414 | "bincode", 415 | "bytecheck", 416 | "env_logger", 417 | "llvm-sys", 418 | "log", 419 | "serde", 420 | "wasmparser", 421 | "wat", 422 | ] 423 | 424 | [[package]] 425 | name = "wasmo_tests" 426 | version = "0.1.0" 427 | dependencies = [ 428 | "env_logger", 429 | "wasmo_runtime", 430 | "wat", 431 | ] 432 | 433 | [[package]] 434 | name = "wasmparser" 435 | version = "0.82.0" 436 | source = "registry+https://github.com/rust-lang/crates.io-index" 437 | checksum = "0559cc0f1779240d6f894933498877ea94f693d84f3ee39c9a9932c6c312bd70" 438 | 439 | [[package]] 440 | name = "wast" 441 | version = "39.0.0" 442 | source = "registry+https://github.com/rust-lang/crates.io-index" 443 | checksum = "e9bbbd53432b267421186feee3e52436531fa69a7cfee9403f5204352df3dd05" 444 | dependencies = [ 445 | "leb128", 446 | "memchr", 447 | "unicode-width", 448 | ] 449 | 450 | [[package]] 451 | name = "wat" 452 | version = "1.0.41" 453 | source = "registry+https://github.com/rust-lang/crates.io-index" 454 | checksum = "ab98ed25494f97c69f28758617f27c3e92e5336040b5c3a14634f2dd3fe61830" 455 | dependencies = [ 456 | "wast", 457 | ] 458 | 459 | [[package]] 460 | name = "winapi" 461 | version = "0.3.9" 462 | source = "registry+https://github.com/rust-lang/crates.io-index" 463 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 464 | dependencies = [ 465 | "winapi-i686-pc-windows-gnu", 466 | "winapi-x86_64-pc-windows-gnu", 467 | ] 468 | 469 | [[package]] 470 | name = "winapi-i686-pc-windows-gnu" 471 | version = "0.4.0" 472 | source = "registry+https://github.com/rust-lang/crates.io-index" 473 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 474 | 475 | [[package]] 476 | name = "winapi-util" 477 | version = "0.1.5" 478 | source = "registry+https://github.com/rust-lang/crates.io-index" 479 | checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" 480 | dependencies = [ 481 | "winapi", 482 | ] 483 | 484 | [[package]] 485 | name = "winapi-x86_64-pc-windows-gnu" 486 | version = "0.4.0" 487 | source = "registry+https://github.com/rust-lang/crates.io-index" 488 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 489 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = [ 3 | 'cli', 4 | 'runtime', 5 | 'tests' 6 | ] 7 | -------------------------------------------------------------------------------- /IDEAS.md: -------------------------------------------------------------------------------- 1 | ### GOALS 2 | 3 | In this order. 4 | 5 | 1. Simple implementation. 6 | 2. Single-pass compilation. 7 | 3. Serializable. 8 | 4. Progressive optimisation. 9 | 10 | ## 11 | 12 | ### MODES 13 | 14 | Wasmo supports two modes of compilation: 15 | 16 | 1. Highly-Optimised Mode 17 | 2. Lift-Off Mode 18 | 19 | The highly-optimised mode compiles the wasm binary once into executable code with important optimisations enabled. This is useful when the module is going to be cached for subsequent reuse, that is AOT use. 20 | 21 | The lift-off mode compiles the wasm binary multiple times, progressively generating a more optimised executable with each iteration. Right now there will only be two iterations. Lift-off mode requires a hand-off process that can be a bit costly. This mode is useful for JIT scenarios where you need the module to start as fast as possible with deferred optimization. 22 | 23 | We are using OrcV2 because it promises concurrent compilation and makes JITing a lot easier with support for loading and dumping object code. It also opens up the opportunity of profile-guided optimization in the future. 24 | 25 | https://v8.dev/blog/liftoff 26 | 27 | ## 28 | 29 | ### LINKING AND RESOLUTION 30 | 31 | When a wasm module is compiled, the internal functions and globals are resolved to their final addresses. But runtime context-dependent objects are not. 32 | 33 | Context-dependent objects include: 34 | 35 | 1. Imported functions 36 | 2. Imported globals 37 | 3. All memories 38 | 4. All tables 39 | 40 | These are resolved at instantiation time. Wasmo solves this borrowing ideas from PIC implementation using PLT and GOT. 41 | 42 | One thing to note is that traditional linking is different from wasm module instantiation because the order in which external call are made is reversed. 43 | 44 | In traditional linking, the in-memory executable asks for an external symbol (in a shared library) to be resolved, so the shared library is loaded into memory on as needed basis. 45 | The shared library doesn't have to know anything about the in-memory executable. 46 | 47 | In wasm's case however, you can think of the in-memory executables as the runtime context. Runtime context refers to imported functions, imported globals, memories and tables instantiated by the host. These objects are dynamic. Memories and globals for example cannot be shared between processes. On the other hand, the compiled module becomes the _shared library_ in this situation because it can be shared between different runtime contexts. But unlike traditional linking, the module (the _shared library_) calls the runtime con text. This makes typical PIC and load-time relocation strategies unapplicable. It needs to modified. 48 | 49 | For wasmo, we generate a `add_imported_function_resolver` function and a _special data section_ for every module. These properties are inaccessible to internal WebAssembly objects. 50 | The `add_imported_function_resolver` function is called during instantiation and it sets the address of the external resolver function in the special data section. 51 | 52 | ![diagram](media/resolution.png) 53 | 54 | ## 55 | 56 | ### PROPOSED API 57 | 58 | ```rs 59 | let imports = Imports::default()?; // Memories, Tables, Globals, Functions 60 | let module = Module::new(&bytes, options)?; // Compiles with unresolved symbols. Creates trampolines. 61 | let instance = Instance::new(&module, &imports)?; // Links memory pieces. Makes imported functions where accessible. 62 | ``` 63 | 64 | ```rs 65 | module.dump(); // Module should be serializable to Vec. 66 | ``` 67 | 68 | ```rs 69 | module.clone(); // Module should be cloneable. 70 | ``` 71 | 72 | ## 73 | 74 | ### EMBEDDING 75 | 76 | ``` 77 | Store { 78 | init() -> { funcs, mems, globals, tables } 79 | } 80 | 81 | Module { 82 | decode(Vec) -> Module? // wasm binary 83 | parse(String) -> Module? // wat text 84 | validate(&self) -> ()? 85 | instantiate() => (Store, Instance?) 86 | imports() -> Vec<(String, String, ExternType)> 87 | exports() -> Vec<(String, ExternType)> 88 | } 89 | 90 | Instance { 91 | export(Module, String) -> (String, ExternType) 92 | } 93 | 94 | Function { 95 | alloc(Store, FuncType, HostFunc) -> (Store, FuncAddr) 96 | type(Store, FuncAddr) -> FuncType 97 | invoke(Store, FuncAddr, Vec) -> (Store, Vec) 98 | } 99 | 100 | Table { 101 | alloc(Store, FuncType, Ref) -> (Store, TableAddr) 102 | ... 103 | } 104 | 105 | Memory { 106 | ... 107 | } 108 | 109 | Global { 110 | ... 111 | } 112 | ``` 113 | 114 | https://webassembly.github.io/spec/core/appendix/embedding.html 115 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 | Wasmo Logo 4 | 5 |
6 | 7 |

Wasmo

8 | 9 | `wasmo` is a WebAssembly compiler and runtime. It compiles WebAssembly code to native code with runtime memory, control integrity security as outlined by the WebAssembly spec. 10 | 11 | ## 12 | 13 | ### GOALS 14 | 15 | In this order. 16 | 17 | 1. Simple implementation. 18 | 2. Single-pass compilation. 19 | 3. Serializable. 20 | 4. Progressive optimisation. 21 | 22 | ### Getting Started 23 | 24 | ### Building Project 25 | -------------------------------------------------------------------------------- /cli/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "wasmo_cli" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | clap = { version = "3.1.0", features = ["derive"] } 10 | 11 | [[bin]] 12 | name = "wasmo" 13 | path = "bin/wasmo.rs" 14 | -------------------------------------------------------------------------------- /cli/bin/wasmo.rs: -------------------------------------------------------------------------------- 1 | use clap::{Parser, Subcommand}; 2 | 3 | #[derive(Parser, Debug)] 4 | #[clap(about, version, author)] 5 | struct Args { 6 | #[clap(subcommand)] 7 | commands: Commands, 8 | } 9 | 10 | #[derive(Subcommand, Debug)] 11 | enum Commands { 12 | Run {}, 13 | } 14 | 15 | fn main() { 16 | let _ = Args::parse(); 17 | println!("wasmo: The Wasmo CLI"); 18 | } 19 | -------------------------------------------------------------------------------- /clippy.toml: -------------------------------------------------------------------------------- 1 | cognitive-complexity-threshold = 10 2 | -------------------------------------------------------------------------------- /media/resolution.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/appcypher/wasmo/31bc8ba906114d01a4d947c84badf687bae10a57/media/resolution.png -------------------------------------------------------------------------------- /runtime/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "wasmo_runtime" 3 | version = "0.1.0" 4 | edition = "2021" 5 | description = "The Wasmo Runtime" 6 | license-file = "../LICENSE" 7 | repository = "https://github.com/appcypher/wasmo" 8 | 9 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 10 | 11 | [dependencies] 12 | anyhow = "1.0" 13 | wasmparser = "0.82.0" 14 | env_logger = "0.9.0" 15 | wat = "1.0.41" 16 | serde = { version = "1.0", features = ["derive"] } 17 | bincode = "1.3.3" 18 | bytecheck = "0.6.7" 19 | llvm-sys = "130.0" 20 | log = "0.4.14" 21 | 22 | [lib] 23 | path = "lib/lib.rs" 24 | -------------------------------------------------------------------------------- /runtime/examples/module.rs: -------------------------------------------------------------------------------- 1 | use wasmo_runtime::{Module, Options}; 2 | 3 | fn main() { 4 | env_logger::init(); 5 | let wasm = wat::parse_str(include_str!("../../tests/samples/fibonacci.wat")).unwrap(); 6 | Module::new(&wasm, Options::default()).unwrap(); 7 | } 8 | -------------------------------------------------------------------------------- /runtime/lib/api.rs: -------------------------------------------------------------------------------- 1 | mod imports; 2 | mod instance; 3 | mod module; 4 | mod options; 5 | mod store; 6 | 7 | pub use imports::*; 8 | pub use instance::*; 9 | pub use module::*; 10 | pub use options::*; 11 | pub use store::*; 12 | -------------------------------------------------------------------------------- /runtime/lib/api/imports.rs: -------------------------------------------------------------------------------- 1 | mod imports; 2 | mod memory; 3 | mod table; 4 | 5 | pub use imports::*; 6 | pub use memory::*; 7 | pub use table::*; 8 | -------------------------------------------------------------------------------- /runtime/lib/api/imports/imports.rs: -------------------------------------------------------------------------------- 1 | /// `Imports` is a set of user-supplied objects that are exposed to a WebAssembly `Instance`. 2 | /// 3 | /// It is different from compiler `Imports` type because it does not necessarily contain a resolution of all the imports an Instance needs. 4 | pub struct Imports {} 5 | -------------------------------------------------------------------------------- /runtime/lib/api/imports/memory.rs: -------------------------------------------------------------------------------- 1 | use crate::types::Limits; 2 | 3 | pub struct Memory { 4 | pub limits: Limits, 5 | // pub size: T, // TODO(appcypher): Make this machine-dependent 6 | } 7 | -------------------------------------------------------------------------------- /runtime/lib/api/imports/table.rs: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /runtime/lib/api/instance.rs: -------------------------------------------------------------------------------- 1 | use super::Store; 2 | use crate::compiler::value::Value; 3 | use crate::{Imports, Module}; 4 | use anyhow::Result; 5 | 6 | /// An Instance is a fully resolved wasm runtime context. 7 | /// External references (globals, functions, memories, tables) are resolved. 8 | /// And memories and tables have been created. 9 | #[derive(Debug, Default)] 10 | pub struct Instance<'a> { 11 | _module: Option<&'a Module>, 12 | _store: Option, 13 | } 14 | 15 | impl<'a> Instance<'a> { 16 | /// Creates a WebAssembly instance. 17 | pub fn new(module: &'a Module, imports: &Imports) -> Result { 18 | module.initialize(imports, Default::default()) 19 | } 20 | 21 | /// Invokes the function with the given name. 22 | pub fn invoke(_name: String, _params: &[Value]) -> Result { 23 | // TODO(appcypher): Implement this. 24 | todo!() 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /runtime/lib/api/module.rs: -------------------------------------------------------------------------------- 1 | use crate::{compiler::Compiler, Imports, Instance, Options, Store}; 2 | use anyhow::Result; 3 | use serde::{Deserialize, Serialize}; 4 | 5 | /// A WebAssembly module with compiled code but with unresolved external references. 6 | /// Memories and tables are also not created yet. 7 | /// 8 | /// Module is serializable and can be shared across threads. 9 | #[derive(Debug, Serialize, Deserialize, Default)] 10 | pub struct Module { 11 | pub options: Options, 12 | compiler: Compiler, 13 | } 14 | 15 | /// Options available for initialiazing a module. 16 | #[derive(Debug, Default)] 17 | pub struct InitializeOpts { 18 | store: Option, 19 | } 20 | 21 | impl Module { 22 | /// Creates a new `Module` with the given options. 23 | pub fn new(wasm: &[u8], options: Options) -> Result { 24 | // Create compiler and compile wasm bytes. 25 | let mut compiler = Compiler::new(options.liftoff); 26 | 27 | // Compile wasm bytes. 28 | compiler.compile(wasm)?; 29 | 30 | Ok(Self { options, compiler }) 31 | } 32 | 33 | /// Creates a WebAssembly instance. 34 | /// 35 | /// Resolves and initialises the instance. 36 | /// 37 | /// Five main operations performed are: 38 | /// 1. Fix up resolver address. 39 | /// 2. Resolve imported memories, tables and globals. 40 | /// 3. Create local memories, tables and globals. 41 | /// 4. Populate memories, tables and globals. 42 | /// 5. Call start function. 43 | pub fn initialize(&self, _imports: &Imports, _opts: InitializeOpts) -> Result { 44 | // TODO(appcypher): Create Store or use the one in opts. 45 | // TODO(appcypher): Implement. 46 | todo!() 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /runtime/lib/api/options.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | 3 | /// The different options for configuring the runtime. 4 | #[derive(Debug, Serialize, Deserialize, Default)] 5 | pub struct Options { 6 | /// Whether to use the Liftoff compiler. 7 | pub liftoff: bool, 8 | } 9 | -------------------------------------------------------------------------------- /runtime/lib/api/store.rs: -------------------------------------------------------------------------------- 1 | mod store; 2 | 3 | pub use store::*; 4 | -------------------------------------------------------------------------------- /runtime/lib/api/store/store.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | 3 | /// Store manages the entire global state accessible to a WebAssembly instance. 4 | #[derive(Debug, Serialize, Deserialize)] 5 | pub struct Store { 6 | // Imported Memories 7 | // Imported Tables 8 | // Imported Globals 9 | // Local Memories 10 | // Local Tables 11 | // Local Globals 12 | 13 | // Imported Functions 14 | // Intrinsics 15 | // Version 16 | } 17 | -------------------------------------------------------------------------------- /runtime/lib/compiler.rs: -------------------------------------------------------------------------------- 1 | mod compiler; 2 | mod data; 3 | mod elem; 4 | mod exports; 5 | mod function; 6 | mod global; 7 | mod imports; 8 | mod llvm; 9 | mod memory; 10 | mod table; 11 | mod utils; 12 | pub(crate) mod value; 13 | 14 | pub use compiler::*; 15 | pub use data::*; 16 | pub use elem::*; 17 | pub use function::*; 18 | pub use global::*; 19 | pub use memory::*; 20 | pub use table::*; 21 | -------------------------------------------------------------------------------- /runtime/lib/compiler/compiler.rs: -------------------------------------------------------------------------------- 1 | use std::pin::Pin; 2 | 3 | use serde::{Deserialize, Serialize}; 4 | 5 | use anyhow::Result; 6 | use log::debug; 7 | use wasmparser::{ 8 | DataSectionReader, ElementSectionReader, ExportSectionReader, FunctionBody, 9 | FunctionSectionReader, GlobalSectionReader, ImportSectionEntryType, ImportSectionReader, 10 | MemorySectionReader, Parser, Payload, TableSectionReader, TypeDef, TypeSectionReader, 11 | }; 12 | 13 | use crate::{ 14 | compiler::exports::ExportKind, 15 | errors::CompilerError, 16 | types::{FuncType, Limits}, 17 | }; 18 | 19 | use super::{ 20 | exports::{Export, Exports}, 21 | imports::{Import, Imports}, 22 | llvm::LLVM, 23 | utils::convert, 24 | value::Value, 25 | Data, Element, Function, Global, Memory, Table, 26 | }; 27 | 28 | /// The compiler is responsible for compiling a module. 29 | #[derive(Debug, Serialize, Deserialize, Default)] 30 | pub struct Compiler { 31 | /// The LLVM context. 32 | #[serde(skip)] 33 | pub(crate) llvm: Option>>, 34 | /// Option for enabling lift-off compilation. 35 | pub liftoff: bool, 36 | /// Compiler data. 37 | pub info: ModuleInfo, 38 | } 39 | 40 | /// It contains artefacts generated during compilation. 41 | /// They help with Webassembly semantics. 42 | #[derive(Debug, Serialize, Deserialize, Default)] 43 | pub struct ModuleInfo { 44 | /// List of imported components of a module. 45 | pub imports: Imports, 46 | /// List of exported members of a module. 47 | pub exports: Exports, 48 | /// An ordered list of types from the type section. 49 | pub types: Vec, 50 | /// An ordered list of functions from the function section. 51 | pub functions: Vec, 52 | /// An ordered list of tables from the table section. 53 | pub tables: Vec, 54 | /// An ordered list of memories from the memory section. 55 | pub memories: Vec, 56 | /// An ordered list of globals from the global section. 57 | pub globals: Vec, 58 | /// An ordered list of elements from the element section. 59 | pub elements: Vec, 60 | /// An ordered list of data from the data section. 61 | pub data: Vec, 62 | /// Represents the current function being compiled. 63 | pub current_frame: Option, 64 | /// The start function. 65 | pub start_function: Option, 66 | } 67 | 68 | /// Represents the current function being compiled. 69 | #[derive(Debug, Serialize, Deserialize, Default)] 70 | pub struct FunctionFrame { 71 | /// Local variables. 72 | pub locals: Vec, 73 | /// An implicit stack only needed during compilation. 74 | pub stack: Vec, 75 | } 76 | 77 | impl Compiler { 78 | /// Creates a new `Compiler` with the given options. 79 | pub fn new(liftoff: bool) -> Self { 80 | Self { 81 | liftoff, 82 | ..Default::default() 83 | } 84 | } 85 | 86 | /// Compiles provided wasm bytes. 87 | pub fn compile(&mut self, wasm: &[u8]) -> Result<()> { 88 | let mut llvm = LLVM::new()?; 89 | 90 | for payload in Parser::new(0).parse_all(wasm) { 91 | match payload? { 92 | Payload::Version { .. } => (), 93 | Payload::TypeSection(reader) => { 94 | debug!("======= TypeSection ======="); 95 | self.compile_types(reader, &mut llvm)?; 96 | } 97 | Payload::ImportSection(reader) => { 98 | debug!("======= ImportSection ======="); 99 | self.compile_imports(reader)?; 100 | } 101 | Payload::FunctionSection(reader) => { 102 | debug!("======= FunctionSection ======="); 103 | self.compile_functions(reader)?; 104 | } 105 | Payload::TableSection(reader) => { 106 | debug!("======= TableSection ======="); 107 | self.compile_tables(reader)?; 108 | } 109 | Payload::MemorySection(reader) => { 110 | debug!("======= MemorySection ======="); 111 | self.compile_memories(reader)?; 112 | } 113 | Payload::GlobalSection(reader) => { 114 | debug!("======= GlobalSection ======="); 115 | self.compile_globals(reader)?; 116 | } 117 | Payload::ExportSection(reader) => { 118 | debug!("======= ExportSection ======="); 119 | self.compile_exports(reader)?; 120 | } 121 | Payload::StartSection { func, .. } => { 122 | debug!("======= StartSection ======="); 123 | self.compile_start_function(func)?; 124 | } 125 | Payload::ElementSection(reader) => { 126 | debug!("======= ElementSection ======="); 127 | self.compile_elements(reader)?; 128 | } 129 | Payload::DataCountSection { .. } => { 130 | debug!("======= DataCountSection ======="); 131 | } 132 | Payload::DataSection(reader) => { 133 | debug!("======= DataSection ======="); 134 | self.compile_data(reader)?; 135 | } 136 | Payload::CustomSection { name, .. } => { 137 | debug!("======= CustomSection ======="); 138 | debug!("custom section name: {:?}", name); 139 | } 140 | Payload::CodeSectionStart { .. } => { 141 | debug!("======= CodeSectionStart ======="); 142 | } 143 | Payload::CodeSectionEntry(body) => { 144 | debug!("======= CodeSectionEntry ======="); 145 | self.compile_function_body(body)?; 146 | } 147 | Payload::ModuleSectionStart { .. } => { 148 | debug!("======= ModuleSectionStart ======="); 149 | } 150 | Payload::ModuleSectionEntry { .. } => { 151 | debug!("======= ModuleSectionEntry ======="); 152 | } 153 | Payload::UnknownSection { .. } => { 154 | debug!("======= UnknownSection ======="); 155 | } 156 | Payload::End => { 157 | debug!("======= End ======="); 158 | } 159 | t => { 160 | return Err(CompilerError::UnsupportedSection(format!("{:?}", t)).into()); 161 | } 162 | } 163 | } 164 | 165 | // Print module. 166 | llvm.module.as_ref().unwrap().print(); 167 | 168 | self.llvm = Some(llvm); 169 | 170 | Ok(()) 171 | } 172 | } 173 | 174 | impl Compiler { 175 | /// Compiles function types in type section. 176 | pub(crate) fn compile_types(&mut self, reader: TypeSectionReader, llvm: &mut LLVM) -> Result<()> { 177 | for result in reader.into_iter() { 178 | let typedef = result?; 179 | 180 | debug!("type: {:?}", typedef); 181 | 182 | match typedef { 183 | TypeDef::Func(ty) => { 184 | let wasmo_func_ty = convert::to_wasmo_functype(&ty)?; 185 | let llvm_func_ty = convert::to_llvm_functype(&llvm.context, &wasmo_func_ty); 186 | // TODO(appcypher): Store llvm func type in llvm.types. 187 | self.info.types.push(wasmo_func_ty); 188 | } 189 | t => { 190 | return Err( 191 | CompilerError::UnsupportedTypeSectionEntry(format!("{:?}", t)).into(), 192 | ) 193 | } 194 | }; 195 | } 196 | 197 | Ok(()) 198 | } 199 | 200 | /// Compiles imports in import section. 201 | pub fn compile_imports(&mut self, reader: ImportSectionReader) -> Result<()> { 202 | for result in reader.into_iter() { 203 | let import = result?; 204 | 205 | debug!("import: {:?}", import); 206 | 207 | match import.ty { 208 | ImportSectionEntryType::Function(index) => { 209 | self.info.imports.functions.push(Import::new( 210 | import.module.to_string(), 211 | import.field.map(|s| s.to_string()), 212 | self.info.functions.len() as u32, 213 | )); 214 | 215 | self.info.functions.push(Function::new(index)); 216 | } 217 | ImportSectionEntryType::Table(ty) => { 218 | self.info.imports.tables.push(Import::new( 219 | import.module.to_string(), 220 | import.field.map(|s| s.to_string()), 221 | self.info.tables.len() as u32, 222 | )); 223 | 224 | self.info.tables.push(Table::new( 225 | Limits::new(ty.initial as u64, ty.maximum.map(|x| x as u64)), 226 | convert::to_wasmo_valtype(&ty.element_type)?, 227 | )); 228 | } 229 | ImportSectionEntryType::Memory(ty) => { 230 | // TODO(appcypher): Wasmo does not support memory64 proposal yet. 231 | if ty.memory64 { 232 | return Err(CompilerError::UnsupportedMemory64Proposal.into()); 233 | } 234 | 235 | self.info.imports.memories.push(Import::new( 236 | import.module.to_string(), 237 | import.field.map(|s| s.to_string()), 238 | self.info.memories.len() as u32, 239 | )); 240 | 241 | self.info 242 | .memories 243 | .push(Memory::new(Limits::new(ty.initial, ty.maximum), ty.shared)); 244 | } 245 | ImportSectionEntryType::Global(ty) => { 246 | self.info.imports.globals.push(Import::new( 247 | import.module.to_string(), 248 | import.field.map(|s| s.to_string()), 249 | self.info.globals.len() as u32, 250 | )); 251 | 252 | self.info.globals.push(Global::new( 253 | convert::to_wasmo_valtype(&ty.content_type)?, 254 | ty.mutable, 255 | )); 256 | } 257 | t => { 258 | return Err( 259 | CompilerError::UnsupportedImportSectionEntry(format!("{:?}", t)).into(), 260 | ) 261 | } 262 | } 263 | } 264 | 265 | Ok(()) 266 | } 267 | 268 | /// Compiles functions in function section. 269 | pub fn compile_functions(&mut self, reader: FunctionSectionReader) -> Result<()> { 270 | for result in reader.into_iter() { 271 | let type_index = result?; 272 | 273 | debug!("function type_index: {:?}", type_index); 274 | 275 | self.info.functions.push(Function::new(type_index)); 276 | } 277 | 278 | Ok(()) 279 | } 280 | 281 | /// Compiles tables in table section. 282 | pub fn compile_tables(&mut self, reader: TableSectionReader) -> Result<()> { 283 | for result in reader.into_iter() { 284 | let ty = result?; 285 | 286 | debug!("table type: {:?}", ty); 287 | 288 | self.info.tables.push(Table::new( 289 | Limits::new(ty.initial as u64, ty.maximum.map(|x| x as u64)), 290 | convert::to_wasmo_valtype(&ty.element_type)?, 291 | )); 292 | } 293 | 294 | Ok(()) 295 | } 296 | 297 | /// Compiles memories in memory section. 298 | pub fn compile_memories(&mut self, reader: MemorySectionReader) -> Result<()> { 299 | for result in reader.into_iter() { 300 | let ty = result?; 301 | 302 | debug!("memory type: {:?}", ty); 303 | 304 | self.info 305 | .memories 306 | .push(Memory::new(Limits::new(ty.initial, ty.maximum), ty.shared)); 307 | } 308 | 309 | Ok(()) 310 | } 311 | 312 | /// Compiles globals in global section. 313 | pub fn compile_globals(&mut self, reader: GlobalSectionReader) -> Result<()> { 314 | for result in reader.into_iter() { 315 | let global = result?; 316 | 317 | debug!("global: {:?}", global); 318 | 319 | self.info.globals.push(Global::new( 320 | convert::to_wasmo_valtype(&global.ty.content_type)?, 321 | global.ty.mutable, 322 | )); 323 | 324 | // llvm.codegen_global(reader)?; 325 | } 326 | 327 | Ok(()) 328 | } 329 | 330 | /// Compiles data in data section. 331 | pub fn compile_data(&mut self, reader: DataSectionReader) -> Result<()> { 332 | for result in reader.into_iter() { 333 | let data = result?; 334 | 335 | debug!("data: {:?}", data); 336 | 337 | self.info 338 | .data 339 | .push(Data::new(convert::to_wasmo_data_kind(&data.kind))); 340 | 341 | // llvm.codegen_data(reader)?; 342 | } 343 | 344 | Ok(()) 345 | } 346 | 347 | /// Compiles elements in element section. 348 | pub fn compile_elements(&mut self, reader: ElementSectionReader) -> Result<()> { 349 | for result in reader.into_iter() { 350 | let elem = result?; 351 | 352 | debug!("elem items: {:?}", elem.items); 353 | 354 | self.info 355 | .elements 356 | .push(Element::new(convert::to_wasmo_element_kind(&elem.kind))); 357 | 358 | // llvm.codegen_element(reader)?; 359 | } 360 | 361 | Ok(()) 362 | } 363 | 364 | /// Compiles exports in export section. 365 | pub fn compile_exports(&mut self, reader: ExportSectionReader) -> Result<()> { 366 | for result in reader.into_iter() { 367 | let export = result?; 368 | 369 | debug!("export: {:?}", export); 370 | 371 | match export.kind { 372 | wasmparser::ExternalKind::Function => { 373 | self.info.exports.inner.insert( 374 | export.field.to_string(), 375 | Export::new(ExportKind::Function, export.index), 376 | ); 377 | } 378 | wasmparser::ExternalKind::Table => { 379 | self.info.exports.inner.insert( 380 | export.field.to_string(), 381 | Export::new(ExportKind::Table, export.index), 382 | ); 383 | } 384 | wasmparser::ExternalKind::Memory => { 385 | self.info.exports.inner.insert( 386 | export.field.to_string(), 387 | Export::new(ExportKind::Memory, export.index), 388 | ); 389 | } 390 | wasmparser::ExternalKind::Global => { 391 | self.info.exports.inner.insert( 392 | export.field.to_string(), 393 | Export::new(ExportKind::Global, export.index), 394 | ); 395 | } 396 | t => { 397 | return Err( 398 | CompilerError::UnsupportedExportSectionEntry(format!("{:?}", t)).into(), 399 | ) 400 | } 401 | } 402 | } 403 | 404 | Ok(()) 405 | } 406 | 407 | /// Compiles start function. 408 | pub fn compile_start_function(&mut self, _func: u32) -> Result<()> { 409 | self.info.start_function = Some(_func); 410 | // llvm.codegen_start_function(reader)?; 411 | Ok(()) 412 | } 413 | 414 | /// Compiles function body. 415 | pub fn compile_function_body(&mut self, body: FunctionBody) -> Result<()> { 416 | debug!("function body: {:?}", body); 417 | 418 | body.get_locals_reader().into_iter().for_each(|r| { 419 | r.into_iter().for_each(|i| { 420 | debug!("local: {:?}", i); 421 | }); 422 | }); 423 | 424 | body.get_operators_reader().into_iter().for_each(|r| { 425 | r.into_iter().for_each(|i| { 426 | debug!("operator: {:?}", i); 427 | }); 428 | }); 429 | 430 | Ok(()) 431 | } 432 | } 433 | -------------------------------------------------------------------------------- /runtime/lib/compiler/data.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | 3 | /// The `Data` section contains the initial values of the linear memory. 4 | #[derive(Debug, Serialize, Deserialize)] 5 | pub struct Data { 6 | pub kind: DataKind, 7 | } 8 | 9 | /// The kind of data segment. 10 | /// 11 | /// https://github.com/WebAssembly/multi-memory/blob/main/proposals/bulk-memory-operations/Overview.md#data-segments 12 | #[derive(Debug, Serialize, Deserialize)] 13 | pub enum DataKind { 14 | /// Passive represents a data segment that is not initialized by the program. 15 | Passive, 16 | /// Active represents a data segment that is initialized by the program. 17 | /// 18 | /// `memory_index` is the index of the memory to use. 19 | Active { memory_index: u32 }, 20 | } 21 | 22 | impl Data { 23 | pub fn new(kind: DataKind) -> Self { 24 | Self { kind } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /runtime/lib/compiler/elem.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | 3 | #[derive(Debug, Serialize, Deserialize)] 4 | pub struct Element { 5 | pub kind: ElementKind, 6 | } 7 | 8 | #[derive(Debug, Serialize, Deserialize)] 9 | pub enum ElementKind { 10 | Passive, 11 | Active { table_index: u32 }, 12 | Declared, 13 | } 14 | 15 | impl Element { 16 | pub fn new(kind: ElementKind) -> Self { 17 | Self { kind } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /runtime/lib/compiler/exports.rs: -------------------------------------------------------------------------------- 1 | 2 | use std::collections::HashMap; 3 | 4 | use serde::{Deserialize, Serialize}; 5 | 6 | #[derive(Debug, Serialize, Deserialize, Default)] 7 | pub struct Exports { 8 | pub(crate) inner: HashMap, 9 | } 10 | 11 | #[derive(Debug, Serialize, Deserialize)] 12 | pub struct Export { 13 | pub kind: ExportKind, 14 | pub index: u32, 15 | } 16 | 17 | #[derive(Debug, Serialize, Deserialize)] 18 | pub enum ExportKind { 19 | Memory, 20 | Table, 21 | Function, 22 | Global, 23 | } 24 | 25 | impl Export { 26 | pub fn new(kind: ExportKind, index: u32) -> Self { 27 | Self { kind, index } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /runtime/lib/compiler/function.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | 3 | #[derive(Debug, Serialize, Deserialize, Default)] 4 | pub struct Function { 5 | pub type_index: u32, 6 | } 7 | 8 | impl Function { 9 | pub fn new(type_index: u32) -> Self { 10 | Self { type_index } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /runtime/lib/compiler/global.rs: -------------------------------------------------------------------------------- 1 | use crate::types::ValType; 2 | 3 | use serde::{Deserialize, Serialize}; 4 | 5 | #[derive(Debug, Serialize, Deserialize)] 6 | pub struct Global { 7 | pub content_type: ValType, 8 | pub is_mutable: bool, 9 | } 10 | 11 | impl Global { 12 | pub fn new(content_type: ValType, is_mutable: bool) -> Self { 13 | Self { 14 | content_type, 15 | is_mutable, 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /runtime/lib/compiler/imports.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | 3 | #[derive(Debug, Serialize, Deserialize, Default)] 4 | pub struct Imports { 5 | pub memories: Vec, 6 | pub tables: Vec, 7 | pub functions: Vec, 8 | pub globals: Vec, 9 | } 10 | 11 | #[derive(Debug, Serialize, Deserialize, Default)] 12 | pub struct Import { 13 | pub module: String, 14 | pub field: Option, 15 | pub index: u32, 16 | } 17 | 18 | impl Import { 19 | pub fn new(module: String, field: Option, index: u32) -> Self { 20 | Self { 21 | module, 22 | field, 23 | index, 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /runtime/lib/compiler/llvm.rs: -------------------------------------------------------------------------------- 1 | pub(crate) mod basic_block; 2 | pub(crate) mod context; 3 | pub(crate) mod function; 4 | pub(crate) mod llvm; 5 | pub(crate) mod module; 6 | pub(crate) mod types; 7 | 8 | pub(crate) use llvm::*; 9 | -------------------------------------------------------------------------------- /runtime/lib/compiler/llvm/basic_block.rs: -------------------------------------------------------------------------------- 1 | use llvm_sys::prelude::LLVMBasicBlockRef; 2 | 3 | pub(crate) struct BasicBlock { 4 | basic_block_ref: LLVMBasicBlockRef, 5 | } 6 | -------------------------------------------------------------------------------- /runtime/lib/compiler/llvm/context.rs: -------------------------------------------------------------------------------- 1 | use anyhow::Result; 2 | use llvm_sys::{ 3 | core::{LLVMContextCreate, LLVMContextDispose}, 4 | prelude::LLVMContextRef, 5 | }; 6 | 7 | use super::{ 8 | module::LLModule, 9 | types::{LLFunctionType, LLNumType, LLNumTypeKind, LLResultType, LLStructType, LLVoidType}, 10 | }; 11 | 12 | /// This a wrapper for LLVM Context. 13 | /// 14 | /// # Ownership 15 | /// Owns the LLVM Module. 16 | #[derive(Debug)] 17 | pub(crate) struct LLContext { 18 | context_ref: LLVMContextRef, 19 | } 20 | 21 | impl LLContext { 22 | pub(crate) fn new() -> Self { 23 | Self { 24 | context_ref: unsafe { LLVMContextCreate() }, 25 | } 26 | } 27 | 28 | pub(crate) fn create_module(&self, name: &str) -> Result { 29 | LLModule::new(name, self) 30 | } 31 | 32 | pub(crate) unsafe fn as_ptr(&self) -> LLVMContextRef { 33 | self.context_ref 34 | } 35 | 36 | pub(crate) fn i32_type(&self) -> LLNumType { 37 | LLNumType::new(self, LLNumTypeKind::I32) 38 | } 39 | 40 | pub(crate) fn i64_type(&self) -> LLNumType { 41 | LLNumType::new(self, LLNumTypeKind::I64) 42 | } 43 | 44 | pub(crate) fn i128_type(&self) -> LLNumType { 45 | LLNumType::new(self, LLNumTypeKind::I128) 46 | } 47 | 48 | pub(crate) fn f32_type(&self) -> LLNumType { 49 | LLNumType::new(self, LLNumTypeKind::F32) 50 | } 51 | 52 | pub(crate) fn f64_type(&self) -> LLNumType { 53 | LLNumType::new(self, LLNumTypeKind::F64) 54 | } 55 | 56 | pub(crate) fn void_type(&self) -> LLVoidType { 57 | LLVoidType::new(self) 58 | } 59 | 60 | pub(crate) fn struct_type(&self, types: &[LLNumType], is_packed: bool) -> LLStructType { 61 | LLStructType::new(types, is_packed) 62 | } 63 | 64 | pub(crate) fn function_type( 65 | &self, 66 | params: &[LLNumType], 67 | result: &LLResultType, 68 | is_varargs: bool, 69 | ) -> LLFunctionType { 70 | LLFunctionType::new(params, result, is_varargs) 71 | } 72 | } 73 | 74 | impl Drop for LLContext { 75 | fn drop(&mut self) { 76 | // Dispose of the LLVM context. 77 | unsafe { 78 | LLVMContextDispose(self.context_ref); 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /runtime/lib/compiler/llvm/function.rs: -------------------------------------------------------------------------------- 1 | use anyhow::Result; 2 | use std::{ffi::CString, rc::Rc}; 3 | 4 | use llvm_sys::{core::LLVMAddFunction, prelude::LLVMValueRef}; 5 | 6 | use super::{module::LLModule, types::LLFunctionType}; 7 | 8 | /// This is a wrapper for LLVM Function. 9 | /// 10 | /// # Safety 11 | /// It is unsafe to use the reference of `LLFunctionType` because its params can be independently freed. 12 | /// Holding an `Rc` to it ensures that that does not happen. 13 | /// 14 | /// WARNING: This is safe only if we can only create a Function from a Module. 15 | /// 16 | /// # Ownership 17 | /// Owns the basic blocks and arguments added to it. 18 | /// 19 | /// - https://llvm.org/doxygen/Function_8cpp_source.html#l00409 20 | /// - https://llvm.org/doxygen/Function_8cpp_source.html#l00509 21 | #[derive(Debug)] 22 | pub(crate) struct LLFunction { 23 | function_ref: LLVMValueRef, 24 | function_type: Rc, 25 | } 26 | 27 | impl LLFunction { 28 | /// Creates a new LLVM function. 29 | /// 30 | /// This is the only way to create an LLFunction to ensure it has an associated Module that can dispose it. 31 | /// 32 | /// # Safety 33 | /// Looks like a pointer to the `CString` is held here. 34 | /// 35 | /// - https://llvm.org/doxygen/Twine_8h_source.html#l00271 36 | /// - https://llvm.org/doxygen/Twine_8h_source.html#l00477 37 | /// - https://llvm.org/doxygen/Value_8cpp_source.html#l00315 38 | /// - https://llvm.org/doxygen/StringRef_8h_source.html#l00107 39 | /// 40 | /// A function is owned by a module but we also need to mutate function and since we cannot create a function without its module, 41 | /// We decided to create an `Rc` of the function that can be shared. This simplifies what would have turned out tbe a lifetime hell. 42 | pub(crate) fn new( 43 | name: &str, 44 | module: &mut LLModule, 45 | function_type: Rc, 46 | ) -> Result> { 47 | let function = Rc::new(Self { 48 | function_ref: unsafe { 49 | LLVMAddFunction( 50 | module.as_ptr(), 51 | CString::new(name)?.as_ptr(), 52 | function_type.as_ptr(), 53 | ) 54 | }, 55 | function_type, 56 | }); 57 | 58 | module.add_function(Rc::clone(&function)); 59 | 60 | Ok(function) 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /runtime/lib/compiler/llvm/llvm.rs: -------------------------------------------------------------------------------- 1 | use std::pin::Pin; 2 | 3 | use super::{context::LLContext, module::LLModule, types::LLFunctionType}; 4 | use anyhow::Result; 5 | use llvm_sys::core::LLVMShutdown; 6 | 7 | /// Converts WebAssembly semantics to LLVM code and handles materialization. 8 | /// 9 | /// # Safety 10 | /// This type is self-referential. We can only construct it as a pinned object. 11 | /// This prevents pointer issues that comes with moving the object. 12 | /// 13 | /// The codegen phase generates some boilerplate code that is used during initialization, and execution. 14 | /// They include: 15 | /// 16 | /// #### The Resolvers Functions 17 | /// - `add_function_resolver(resolver_addr)` // save address to designated data section 18 | /// - `resolve_imported_memories(store_ref_addr)` // call intrinsics, save address to designated data section 19 | /// - `resolve_imported_tables(store_ref_addr)` // call intrinsics, save address to designated data section 20 | /// - `resolve_imported_globals(store_ref_addr)` // call intrinsics, save address to designated data section 21 | /// 22 | /// #### The Local Setup Functions 23 | /// - `setup_local_memories(store_ref_addr)` // call intrinsics, call initializers, save address to designated data section 24 | /// - `setup_local_tables(store_ref_addr)` // call intrinsics, call initializers, save address to designated data section 25 | /// - `setup_local_globals(store_ref_addr)` // call intrinsics, call initializers, save content to designated data section 26 | /// 27 | /// #### The Initializer Functions 28 | /// - `initialize_mem_0_data_0(store_ref_addr)` // call intrinsics, save content to designated data section 29 | /// - ... 30 | /// 31 | /// #### The Start Function 32 | /// - `_start` 33 | /// 34 | /// #### Materializer Stubs 35 | /// - calling imported functions 36 | /// - calling indirect functions 37 | /// 38 | /// #### The Store Data Section 39 | /// #### The Store Data Section 40 | /// - `function_resolver -> func_addr` // resolves intrinsics and imported functions 41 | /// - `intrinsics -> (length, func_addr*)` // intrinsic function fixup 42 | /// - `functions -> (length, (type, func_addr)*)` // imported fn fixup and indirect calls 43 | /// - `memories -> (length, memory_base_addr*)` // memory base address fixup 44 | /// - `tables -> (length, table_base_addr*)` // table base address fixup 45 | /// - `globals -> (length, global_addr*)` // global address fixup 46 | /// 47 | /// #### Misc 48 | /// - loading important values like memory address into registers from the store data section 49 | #[derive(Debug)] 50 | pub(crate) struct LLVM { 51 | pub(crate) context: LLContext, 52 | pub(crate) module: Option, 53 | pub(crate) info: LLVMInfo, 54 | } 55 | 56 | /// Compilation information about an LLVM Module. 57 | #[derive(Debug, Default)] 58 | pub(crate) struct LLVMInfo { 59 | types: Vec, 60 | } 61 | 62 | impl LLVM { 63 | /// Creates pinned LLVM instance. 64 | pub(crate) fn new() -> Result>> { 65 | // TODO(appcypher): Initialize target, asm printer. 66 | 67 | let mut this = Box::pin(Self { 68 | context: LLContext::new(), 69 | module: None, 70 | info: LLVMInfo::default(), 71 | }); 72 | 73 | // The module field references the context field so this is self-referential. 74 | this.module = Some(LLModule::new("initial", &this.context)?); 75 | 76 | Ok(this) 77 | } 78 | } 79 | 80 | impl Drop for LLVM { 81 | fn drop(&mut self) { 82 | unsafe { LLVMShutdown() } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /runtime/lib/compiler/llvm/module.rs: -------------------------------------------------------------------------------- 1 | use std::{ffi::CString, rc::Rc}; 2 | 3 | use anyhow::Result; 4 | 5 | use llvm_sys::{ 6 | core::{LLVMDumpModule, LLVMModuleCreateWithNameInContext}, 7 | prelude::LLVMModuleRef, 8 | }; 9 | 10 | use super::{context::LLContext, function::LLFunction}; 11 | 12 | /// A wrapper for LLVM Module. 13 | /// 14 | /// # Safety 15 | /// 16 | /// When a Module references a Context, the Context frees it when it gets dropped. 17 | /// 18 | /// We leverage this behavior by not disposing the Module explicitly on drop, letting associated Context do the job. 19 | /// 20 | /// WARNING: This is safe only if we can only create a Module from a Context. 21 | /// 22 | /// NOTE: We can't use lifetime parameter since it leads to unresolvable self-referential structs when an `LLModule` is stored in the same struct as the associated `LLContext`. 23 | /// 24 | /// - https://lists.llvm.org/pipermail/llvm-dev/2018-September/126134.html 25 | /// - https://llvm.org/doxygen/Module_8cpp_source.html#l00079 26 | /// - https://llvm.org/doxygen/LLVMContextImpl_8cpp_source.html#l00052 27 | /// 28 | /// # Ownership 29 | /// Owns the functions and globals added to it. 30 | /// 31 | /// - https://llvm.org/doxygen/Module_8cpp_source.html#l00079 32 | #[derive(Debug)] 33 | pub(crate) struct LLModule { 34 | module_ref: LLVMModuleRef, 35 | functions: Vec>, 36 | } 37 | 38 | impl LLModule { 39 | /// This is the only way to create an LLModule to ensure it has an associated Context that can dispose it. 40 | /// 41 | /// # Safety 42 | /// A temporary `CString` name is safe to use here because it is copied into the LLVM Module. 43 | /// 44 | /// - https://llvm.org/doxygen/Module_8cpp_source.html#l00072 45 | pub(crate) fn new(name: &str, context: &LLContext) -> Result { 46 | Ok(Self { 47 | module_ref: unsafe { 48 | LLVMModuleCreateWithNameInContext(CString::new(name)?.as_ptr(), context.as_ptr()) 49 | }, 50 | functions: vec![], 51 | }) 52 | } 53 | 54 | /// Adds a function to the module. 55 | /// 56 | /// # Safety 57 | /// Function added to module gets released when the module is dropped. 58 | /// 59 | /// - https://llvm.org/doxygen/Module_8cpp_source.html#l00079 60 | pub(crate) fn add_function(&mut self, function: Rc) { 61 | self.functions.push(function) 62 | } 63 | 64 | pub(crate) unsafe fn as_ptr(&self) -> LLVMModuleRef { 65 | self.module_ref 66 | } 67 | 68 | pub(crate) fn print(&self) { 69 | unsafe { 70 | LLVMDumpModule(self.module_ref); 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /runtime/lib/compiler/llvm/orc.rs: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /runtime/lib/compiler/llvm/target.rs: -------------------------------------------------------------------------------- 1 | pub(crate) struct Target; 2 | -------------------------------------------------------------------------------- /runtime/lib/compiler/llvm/target_machine.rs: -------------------------------------------------------------------------------- 1 | pub(crate) struct LLTargetMachine { 2 | target_machine: LLVMTargetMachineRef, 3 | } 4 | -------------------------------------------------------------------------------- /runtime/lib/compiler/llvm/types.rs: -------------------------------------------------------------------------------- 1 | use llvm_sys::{ 2 | core::{ 3 | LLVMDoubleTypeInContext, LLVMFloatTypeInContext, LLVMFunctionType, LLVMInt128TypeInContext, 4 | LLVMInt32TypeInContext, LLVMInt64TypeInContext, LLVMStructType, LLVMVoidTypeInContext, 5 | }, 6 | prelude::LLVMTypeRef, 7 | }; 8 | 9 | use super::context::LLContext; 10 | 11 | /// This is based on wasm num and vector types. 12 | pub(crate) enum LLNumTypeKind { 13 | I32, 14 | I64, 15 | I128, 16 | F32, 17 | F64, 18 | } 19 | 20 | /// Wrapper for LLVM number types (e.g. i64, f32) which is based on wasm num and vector types. 21 | /// 22 | /// # Safety 23 | /// Only a kind of each `LLVMTypeRef` is ever created. They are singletons and are never freed. 24 | /// 25 | /// - https://llvm.org/doxygen/classllvm_1_1Type.html#details 26 | /// - https://llvm.org/docs/LangRef.html#integer-type 27 | pub(crate) struct LLNumType(LLVMTypeRef); 28 | 29 | /// Wrapper for LLVM pointer types (e.g. i64*, [2 x double]*). 30 | /// 31 | /// # Safety 32 | /// See [`LLNumType`](struct.LLNumType.html) 33 | /// 34 | /// - https://llvm.org/docs/LangRef.html#pointer-type 35 | pub(crate) struct LLPointerType(LLVMTypeRef); 36 | 37 | /// Wrapper for LLVM vector types (e.g. <4 x i64>). 38 | /// 39 | /// # Safety 40 | /// See [`LLNumType`](struct.LLNumType.html) 41 | /// 42 | /// - https://llvm.org/docs/LangRef.html#vector-type 43 | pub(crate) struct LLVectorType(LLVMTypeRef); 44 | 45 | /// Wrapper for LLVM array type (e.g. [4 x double]). 46 | /// 47 | /// # Safety 48 | /// See [`LLNumType`](struct.LLNumType.html) 49 | /// 50 | /// - https://llvm.org/docs/LangRef.html#array-type 51 | pub(crate) struct LLArrayType(LLVMTypeRef); 52 | 53 | /// Wrapper for LLVM void type. 54 | /// 55 | /// # Safety 56 | /// See [`LLNumType`](struct.LLNumType.html) 57 | /// 58 | /// - https://llvm.org/docs/LangRef.html#void-type 59 | pub(crate) struct LLVoidType(LLVMTypeRef); 60 | 61 | /// Wrapper for LLVM struct type. 62 | /// 63 | /// # Safety 64 | /// Structure types are a bit more complicated than scalar types because we need to allocate the array of types that gets passed to it. 65 | /// 66 | /// The good thing however is that LLVM does not depend on our base pointer. It reallocates the params within the LLVM context. 67 | /// 68 | /// - https://llvm.org/doxygen/Type_8cpp_source.html#l00361 69 | pub(crate) struct LLStructType(LLVMTypeRef); 70 | 71 | /// Wrapper for LLVM function type. 72 | /// 73 | /// # Safety 74 | /// Function types are a bit more complicated than scalar types because we need to allocate the array of types that gets passed to it. 75 | /// 76 | /// The good thing however is that LLVM does not depend on our base pointer. It reallocates the params within the LLVM context. 77 | /// 78 | /// - https://llvm.org/doxygen/Type_8cpp_source.html#l00361 79 | #[derive(Debug)] 80 | pub(crate) struct LLFunctionType(LLVMTypeRef); 81 | 82 | /// A limited variants of types that can be returned by an LLVM function 83 | pub(crate) enum LLResultType { 84 | Void(LLVoidType), 85 | Num(LLNumType), 86 | Struct(LLStructType), 87 | } 88 | 89 | impl LLNumType { 90 | /// Creates an LLVM number type. 91 | /// 92 | /// # Safety 93 | /// LLContext does not own type here. 94 | pub(crate) fn new(context: &LLContext, kind: LLNumTypeKind) -> Self { 95 | use LLNumTypeKind::*; 96 | let context_ref = unsafe { context.as_ptr() }; 97 | let type_ref = unsafe { 98 | match kind { 99 | I32 => LLVMInt32TypeInContext(context_ref), 100 | I64 => LLVMInt64TypeInContext(context_ref), 101 | I128 => LLVMInt128TypeInContext(context_ref), 102 | F32 => LLVMFloatTypeInContext(context_ref), 103 | F64 => LLVMDoubleTypeInContext(context_ref), 104 | } 105 | }; 106 | 107 | Self(type_ref) 108 | } 109 | 110 | pub(crate) unsafe fn as_ptr(&self) -> LLVMTypeRef { 111 | self.0 112 | } 113 | } 114 | 115 | impl LLVoidType { 116 | /// Creates an LLVM void type. 117 | /// 118 | /// # Safety 119 | /// See [`LLNumType`](struct.LLNumType.html) 120 | pub(crate) fn new(context: &LLContext) -> Self { 121 | Self(unsafe { LLVMVoidTypeInContext(context.as_ptr()) }) 122 | } 123 | 124 | pub(crate) unsafe fn as_ptr(&self) -> LLVMTypeRef { 125 | self.0 126 | } 127 | } 128 | 129 | impl LLStructType { 130 | /// Creates a new LLVM array type. 131 | /// 132 | /// # Safety 133 | /// See [LLStructType](struct.LLStructType.html) for safety. 134 | pub(crate) fn new(types: &[LLNumType], is_packed: bool) -> Self { 135 | let types = types 136 | .iter() 137 | .map(|p| unsafe { p.as_ptr() }) 138 | .collect::>(); 139 | 140 | Self(unsafe { 141 | LLVMStructType( 142 | types.as_ptr() as *mut LLVMTypeRef, 143 | types.len() as u32, 144 | is_packed as i32, 145 | ) 146 | }) 147 | } 148 | 149 | pub(super) unsafe fn as_ptr(&self) -> LLVMTypeRef { 150 | self.0 151 | } 152 | } 153 | 154 | impl LLFunctionType { 155 | /// Creates a new LLVM function type. 156 | /// # Safety 157 | /// See [LLFunctionType](struct.LLFunctionType.html) for safety. 158 | pub(crate) fn new(params: &[LLNumType], result: &LLResultType, is_varargs: bool) -> Self { 159 | let params = params 160 | .iter() 161 | .map(|p| unsafe { p.as_ptr() }) 162 | .collect::>(); 163 | 164 | Self(unsafe { 165 | LLVMFunctionType( 166 | result.as_ptr(), 167 | params.as_ptr() as *mut LLVMTypeRef, 168 | params.len() as u32, 169 | is_varargs as i32, 170 | ) 171 | }) 172 | } 173 | 174 | pub(super) unsafe fn as_ptr(&self) -> LLVMTypeRef { 175 | self.0 176 | } 177 | } 178 | 179 | impl LLResultType { 180 | pub(crate) unsafe fn as_ptr(&self) -> LLVMTypeRef { 181 | use LLResultType::*; 182 | match self { 183 | Void(v) => v.as_ptr(), 184 | Num(n) => n.as_ptr(), 185 | Struct(s) => s.as_ptr(), 186 | } 187 | } 188 | } 189 | -------------------------------------------------------------------------------- /runtime/lib/compiler/memory.rs: -------------------------------------------------------------------------------- 1 | use crate::types::Limits; 2 | 3 | use serde::{Deserialize, Serialize}; 4 | 5 | #[derive(Debug, Serialize, Deserialize, Default)] 6 | pub struct Memory { 7 | pub is_memory_64: bool, // TODO(appcypher): Wasmo does not support memory64 proposal yet. 8 | pub is_shared: bool, 9 | pub limits: Limits, 10 | } 11 | 12 | impl Memory { 13 | pub fn new(limits: Limits, is_shared: bool) -> Self { 14 | Self { 15 | is_memory_64: false, 16 | is_shared, 17 | limits, 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /runtime/lib/compiler/table.rs: -------------------------------------------------------------------------------- 1 | use crate::types::{Limits, ValType}; 2 | use serde::{Deserialize, Serialize}; 3 | 4 | #[derive(Debug, Serialize, Deserialize)] 5 | pub struct Table { 6 | pub limits: Limits, 7 | pub element_type: ValType, 8 | } 9 | 10 | impl Table { 11 | pub fn new(limits: Limits, element_type: ValType) -> Self { 12 | Self { 13 | limits, 14 | element_type, 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /runtime/lib/compiler/utils.rs: -------------------------------------------------------------------------------- 1 | pub mod convert { 2 | use std::rc::Rc; 3 | 4 | use crate::{ 5 | compiler::{ 6 | llvm::{ 7 | context::LLContext, 8 | types::{LLFunctionType, LLNumType, LLResultType}, 9 | }, 10 | DataKind, ElementKind, 11 | }, 12 | errors::CompilerError, 13 | types::{FuncType, NumType, RefType, ValType}, 14 | }; 15 | use anyhow::Result; 16 | 17 | /// Converts `wasmparser` `FuncType` to `wasmo` `FuncType`. 18 | pub fn to_wasmo_functype(ty: &wasmparser::FuncType) -> Result { 19 | let params = ty 20 | .params 21 | .iter() 22 | .map(to_wasmo_valtype) 23 | .collect::>>()?; 24 | 25 | let results = ty 26 | .returns 27 | .iter() 28 | .map(to_wasmo_valtype) 29 | .collect::>>()?; 30 | 31 | Ok(FuncType { params, results }) 32 | } 33 | 34 | /// Converts `wasmparser` `ValType` to `wasmo` `ValType`. 35 | pub fn to_wasmo_valtype(ty: &wasmparser::Type) -> Result { 36 | match ty { 37 | wasmparser::Type::I32 => Ok(ValType::Num(NumType::I32)), 38 | wasmparser::Type::I64 => Ok(ValType::Num(NumType::I64)), 39 | wasmparser::Type::F32 => Ok(ValType::Num(NumType::F32)), 40 | wasmparser::Type::F64 => Ok(ValType::Num(NumType::F64)), 41 | wasmparser::Type::V128 => Ok(ValType::Vec), 42 | wasmparser::Type::FuncRef => Ok(ValType::Ref(RefType::FuncRef)), 43 | wasmparser::Type::ExternRef => Ok(ValType::Ref(RefType::ExternRef)), 44 | t => Err(CompilerError::UnsupportedWasmoValType(format!("{:?}", t)).into()), 45 | } 46 | } 47 | 48 | /// Converts `wasmparser` `DataKind` to `wasmo` `DataKind`. 49 | pub fn to_wasmo_data_kind(ty: &wasmparser::DataKind) -> DataKind { 50 | match ty { 51 | wasmparser::DataKind::Passive => DataKind::Passive, 52 | wasmparser::DataKind::Active { memory_index, .. } => DataKind::Active { 53 | memory_index: *memory_index, 54 | }, 55 | } 56 | } 57 | 58 | /// Converts `wasmparser` `ElementKind` to `wasmo` `ElementKind`. 59 | pub fn to_wasmo_element_kind(ty: &wasmparser::ElementKind) -> ElementKind { 60 | match ty { 61 | wasmparser::ElementKind::Passive => ElementKind::Passive, 62 | wasmparser::ElementKind::Declared => ElementKind::Declared, 63 | wasmparser::ElementKind::Active { table_index, .. } => ElementKind::Active { 64 | table_index: *table_index, 65 | }, 66 | } 67 | } 68 | 69 | /// Converts `wasmo` `ValType` to `LLNumType`. 70 | pub(crate) fn to_llvm_valtype(ctx: &LLContext, ty: &ValType) -> LLNumType { 71 | use ValType::*; 72 | match ty { 73 | Num(NumType::I32) => ctx.i32_type(), 74 | Num(NumType::I64) => ctx.i64_type(), 75 | Num(NumType::F32) => ctx.f32_type(), 76 | Num(NumType::F64) => ctx.f64_type(), 77 | Ref(_) => ctx.i64_type(), // TODO(appcypher): Use ctx.target_ptr_type() 78 | Vec => ctx.i128_type(), 79 | } 80 | } 81 | 82 | /// Converts `wasmo` `ValType` to `LLFunctionType`. 83 | pub(crate) fn to_llvm_functype(ctx: &LLContext, ty: &FuncType) -> LLFunctionType { 84 | let params = ty 85 | .params 86 | .iter() 87 | .map(|i| to_llvm_valtype(ctx, i)) 88 | .collect::>(); 89 | 90 | // If no result type, use a void. 91 | // If single result type, use a single valtype. 92 | // If multiple result types, use a tuple of valtypes. 93 | let result = match &ty.results[..] { 94 | &[] => LLResultType::Void(ctx.void_type()), 95 | &[ref single_ty] => LLResultType::Num(to_llvm_valtype(ctx, single_ty)), 96 | result_types => { 97 | let types = result_types 98 | .iter() 99 | .map(|i| to_llvm_valtype(ctx, i)) 100 | .collect::>(); 101 | 102 | LLResultType::Struct(ctx.struct_type(&types, true)) 103 | } 104 | }; 105 | 106 | ctx.function_type(¶ms, &result, false) 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /runtime/lib/compiler/value.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | 3 | #[derive(Debug, Serialize, Deserialize)] 4 | pub enum Value { 5 | Num(NumVal), 6 | Ref(RefVal), 7 | Vec(i128), 8 | } 9 | 10 | #[derive(Debug, Serialize, Deserialize)] 11 | pub enum NumVal { 12 | I32(i32), 13 | I64(i64), 14 | F32(f32), 15 | F64(f64), 16 | } 17 | 18 | #[derive(Debug, Serialize, Deserialize)] 19 | pub enum RefVal { 20 | FuncAddr(i32), 21 | ExternAddr(i64), 22 | } 23 | -------------------------------------------------------------------------------- /runtime/lib/context.rs: -------------------------------------------------------------------------------- 1 | mod address; 2 | mod sizes; 3 | 4 | pub use address::*; 5 | pub use sizes::*; 6 | -------------------------------------------------------------------------------- /runtime/lib/context/address.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | 3 | #[derive(Debug, Serialize, Deserialize, Default)] 4 | pub struct BaseAddress { 5 | // pub address: T, // TODO(appcypher): Make this machine-dependent 6 | } 7 | -------------------------------------------------------------------------------- /runtime/lib/context/sizes.rs: -------------------------------------------------------------------------------- 1 | pub const _POINTER_SIZE: u8 = std::mem::size_of::() as u8; 2 | pub const _LENGTH_SIZE: u8 = std::mem::size_of::() as u8; 3 | pub const _TYPE_INDEX_SIZE: u8 = std::mem::size_of::() as u8; 4 | pub const _LIMIT_MIN_SIZE: u8 = std::mem::size_of::() as u8; 5 | pub const _LIMIT_MAX_SIZE: u8 = std::mem::size_of::() as u8; 6 | -------------------------------------------------------------------------------- /runtime/lib/errors.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::Display; 2 | 3 | #[derive(Debug, Clone, PartialEq, Eq)] 4 | pub enum CompilerError { 5 | UnsupportedTypeSectionEntry(String), 6 | UnsupportedExportSectionEntry(String), 7 | UnsupportedImportSectionEntry(String), 8 | UnsupportedWasmoValType(String), 9 | UnsupportedMemory64Proposal, 10 | UnsupportedSection(String), 11 | } 12 | 13 | impl std::error::Error for CompilerError {} 14 | 15 | impl Display for CompilerError { 16 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 17 | write!(f, "{:?}", self) 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /runtime/lib/intrinsics.rs: -------------------------------------------------------------------------------- 1 | mod memory; 2 | 3 | pub use memory::*; 4 | -------------------------------------------------------------------------------- /runtime/lib/intrinsics/memory.rs: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /runtime/lib/lib.rs: -------------------------------------------------------------------------------- 1 | mod api; 2 | mod compiler; 3 | mod context; 4 | mod errors; 5 | mod intrinsics; 6 | mod types; 7 | 8 | pub use api::*; 9 | -------------------------------------------------------------------------------- /runtime/lib/types.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | 3 | /// WebAssembly function type as defined in the spec. 4 | /// 5 | /// https://webassembly.github.io/spec/core/syntax/types.html#syntax-functype 6 | #[derive(Debug, Serialize, Deserialize)] 7 | pub struct FuncType { 8 | pub params: Vec, 9 | pub results: Vec, 10 | } 11 | 12 | /// WebAssembly value types as defined in the spec. 13 | /// 14 | /// https://webassembly.github.io/spec/core/syntax/types.html#syntax-valtype 15 | #[derive(Debug, Serialize, Deserialize)] 16 | pub enum ValType { 17 | Num(NumType), // i32, i64, f32, f64 18 | Ref(RefType), // funcref, externref 19 | Vec, // v128 20 | } 21 | 22 | /// WebAssembly num types as defined in the spec. 23 | /// 24 | /// https://webassembly.github.io/spec/core/syntax/types.html#syntax-numtype 25 | #[derive(Debug, Serialize, Deserialize)] 26 | pub enum NumType { 27 | I32, 28 | I64, 29 | F32, 30 | F64, 31 | } 32 | 33 | /// WebAssembly num types as defined in the spec. 34 | /// 35 | /// https://webassembly.github.io/spec/core/syntax/types.html#syntax-reftype 36 | #[derive(Debug, Serialize, Deserialize)] 37 | pub enum RefType { 38 | FuncRef, 39 | ExternRef, 40 | } 41 | 42 | /// WebAssembly limits almost as defined in the spec. 43 | /// 44 | /// A slight deviation from the current spec. Wasmo uses 64-bit types as there will be support for memory64 in the future. 45 | /// 46 | /// https://webassembly.github.io/spec/core/syntax/types.html#syntax-limits 47 | #[derive(Debug, Serialize, Deserialize, Default)] 48 | pub struct Limits { 49 | /// Intial page count. 50 | pub min: u64, 51 | /// Maximum page count. 52 | pub max: Option, 53 | } 54 | 55 | /// Webassembly memory and table page size. 56 | /// 64KiB. 57 | pub const _PAGE_SIZE: u32 = 65536; 58 | 59 | impl Limits { 60 | pub fn new(min: u64, max: Option) -> Self { 61 | Self { min, max } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /tests/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "wasmo_tests" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | wasmo_runtime = { path = "../runtime" } 10 | wat = "1.0.41" 11 | env_logger = "0.9.0" 12 | 13 | [lib] 14 | path = "lib.rs" 15 | -------------------------------------------------------------------------------- /tests/lib.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod runtime; 3 | -------------------------------------------------------------------------------- /tests/runtime.rs: -------------------------------------------------------------------------------- 1 | mod module; 2 | -------------------------------------------------------------------------------- /tests/runtime/module.rs: -------------------------------------------------------------------------------- 1 | mod test { 2 | use wasmo_runtime::{Module, Options}; 3 | 4 | #[test] 5 | fn test_parser() { 6 | env_logger::init(); 7 | let wasm = wat::parse_str(include_str!("../samples/fibonacci.wat")).unwrap(); 8 | let _module = Module::new(&wasm, Options::default()).unwrap(); 9 | assert!(true) 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /tests/samples/add.wat: -------------------------------------------------------------------------------- 1 | (module 2 | (func $_start (result i32) 3 | (call $add (i32.const 45) (i32.const 5)) 4 | ) 5 | 6 | (func $add (param i32 i32) (result i32) 7 | (i32.add (local.get 0) (local.get 1)) 8 | ) 9 | 10 | (export "add" (func $add)) 11 | (export "_start" (func $_start)) 12 | ) 13 | -------------------------------------------------------------------------------- /tests/samples/fibonacci.wat: -------------------------------------------------------------------------------- 1 | (module 2 | (import "host" "func" (func (param i32) (result i32 i32))) 3 | (import "host" "mem" (memory 1 10)) 4 | (import "host" "table" (table 1 10 funcref)) 5 | (import "host" "global" (global i32)) 6 | 7 | (memory $mem 1 10) 8 | 9 | (table $table 1 10 funcref) 10 | 11 | (global $global i32) 12 | 13 | (data $data (memory $mem) (offset (i32.const 0)) "\00\01\02\03") 14 | 15 | (elem $elem (table $table) (offset (i32.const 0)) funcref 16 | (item (i32.const 1)) 17 | (item (i32.const 2)) 18 | ) 19 | 20 | (func $_start (result i32) 21 | (call $fibonacci (i32.const 10)) 22 | ) 23 | 24 | (func $dummy_func (result i32) 25 | (local $dummy i32) 26 | 27 | (local.set $dummy (i32.const 100)) 28 | 29 | (i32.load (i32.const 0)) 30 | 31 | (drop) 32 | 33 | (i32.add (local.get $dummy) (i32.const 100)) 34 | ) 35 | 36 | (func $fibonacci (param $number i32) (result i32) 37 | ;; base condition 1 38 | (if (i32.eq (local.get $number) (i32.const 0)) 39 | (then (return (i32.const 1))) 40 | ) 41 | 42 | ;; base condition 2 43 | (if (i32.eq (local.get $number) (i32.const 1)) 44 | (then (return (i32.const 1))) 45 | ) 46 | 47 | ;; recursive call 48 | (i32.add 49 | (call $fibonacci 50 | (i32.sub (local.get $number) (i32.const 1)) 51 | ) 52 | 53 | (call $fibonacci 54 | (i32.sub (local.get $number) (i32.const 2)) 55 | ) 56 | ) 57 | ) 58 | 59 | (export "_start" (func $_start)) 60 | ) 61 | --------------------------------------------------------------------------------