├── .gitignore ├── BinaryEncoding.md ├── CAndC++.md ├── CodeOfConduct.md ├── Contributing.md ├── DynamicLinking.md ├── Events.md ├── FAQ.md ├── FeatureTest.md ├── FutureFeatures.md ├── HighLevelGoals.md ├── JITLibrary.md ├── JS.md ├── LICENSE ├── MVP.md ├── Modules.md ├── NonWeb.md ├── Nondeterminism.md ├── Portability.md ├── README.md ├── Rationale.md ├── Security.md ├── Semantics.md ├── TextFormat.md ├── Tooling.md ├── UseCases.md └── Web.md /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *# 3 | .#* 4 | .*.swp 5 | out 6 | -------------------------------------------------------------------------------- /BinaryEncoding.md: -------------------------------------------------------------------------------- 1 | # Binary Encoding 2 | 3 | This file historically contained the description of WebAssembly's binary encoding. 4 | 5 | For the current description, see the [normative documentation](http://webassembly.github.io/spec/core/binary/index.html). 6 | -------------------------------------------------------------------------------- /CAndC++.md: -------------------------------------------------------------------------------- 1 | # Guide for C/C++ developers 2 | 3 | WebAssembly is being designed to support C and C++ code well, right from 4 | the start in [the MVP](MVP.md). The following explains the outlook for 5 | C and C++ developers. 6 | 7 | ## Porting C and C++ code to WebAssembly 8 | 9 | ### Platform features 10 | 11 | WebAssembly has a pretty conventional ISA: 8-bit bytes, two's complement 12 | integers, little-endian, and a lot of other normal properties. Reasonably 13 | portable C/C++ code should port to WebAssembly without difficultly. 14 | 15 | WebAssembly has 32-bit and 64-bit architecture variants, called wasm32 and 16 | wasm64. wasm32 has an ILP32 data model, meaning that `int`, `long`, and 17 | pointer types are all 32-bit, while the `long long` type is 64-bit. wasm64 18 | has an LP64 data model, meaning that `long` and pointer types will be 19 | 64-bit, while `int` is 32-bit. 20 | 21 | [The MVP](MVP.md) will support only wasm32; support for wasm64 will be 22 | added in the future to support 23 | [64-bit address spaces :unicorn:][future 64-bit]. 24 | 25 | `float` and `double` are the IEEE 754-2019 single- and double-precision types, 26 | which are native in WebAssembly. `long double` is the IEEE 754-2019 27 | quad-precision type, which is a software-emulated type. WebAssembly does 28 | not have a builtin quad-precision type or associated operators. The long 29 | double type here is software-emulated in library code linked into WebAssembly 30 | applications that need it. 31 | 32 | For performance and compatibility with other platforms, `float` and 33 | `double` are recommended for most uses. 34 | 35 | ### Language Support 36 | 37 | C and C++ language conformance is largely determined by individual compiler 38 | support, but WebAssembly includes all the functionality that popular C and C++ 39 | compilers need to support high-quality implementations. 40 | 41 | While [the MVP](MVP.md) will be fully functional, additional features enabling 42 | greater performance will be added soon after, including: 43 | 44 | * Support for [multi-threaded execution with shared memory][future threads]. 45 | 46 | * [Zero-cost C++ exception handling][future exceptions]. 47 | C++ exceptions can be implemented without this, but this feature will 48 | enable them to have lower runtime overhead. 49 | 50 | * Support for [128-bit SIMD][future simd]. SIMD will be 51 | exposed to C/C++ though explicit APIs such as [LLVM's vector extensions] 52 | and [GCC's vector extensions], auto-vectorization, and emulated APIs from 53 | other platforms such as ``. 54 | 55 | [LLVM's vector extensions]: https://clang.llvm.org/docs/LanguageExtensions.html#vectors-and-extended-vectors 56 | [GCC's vector extensions]: https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html 57 | 58 | ### APIs 59 | 60 | WebAssembly applications can use high-level C/C++ APIs such as the C 61 | and C++ standard libraries, OpenGL, SDL, pthreads, and others, just as 62 | in normal C/C++ development. Under the covers, these libraries 63 | implement their functionality by using low-level facilities provided by 64 | WebAssembly implementations. On [the Web](Web.md), they utilize 65 | Web APIs (for example, OpenGL is executed on WebGL, libc date and 66 | time methods use the browser's Date functionality, etc.). 67 | [In other contexts](NonWeb.md), other low-level mechanisms may be used. 68 | 69 | ### ABIs 70 | 71 | In [the MVP](MVP.md), WebAssembly does not yet have a stable ABI for 72 | libraries. Developers will need to ensure that all code linked into an 73 | application are compiled with the same compiler and options. 74 | 75 | In the future, when WebAssembly is extended to support 76 | [dynamic linking](DynamicLinking.md), stable ABIs are 77 | expected to be defined in accompaniment. 78 | 79 | ### Undefined and Implementation-defined Behavior 80 | 81 | #### Undefined Behavior 82 | 83 | WebAssembly doesn't change the C or C++ languages. Things which cause 84 | undefined behavior in C or C++ are still bugs when compiling for WebAssembly 85 | [even when the corresponding behavior in WebAssembly itself is defined](Nondeterminism.md#note-for-users-of-c-c-and-similar-languages). 86 | C and C++ optimizers still assume that undefined behavior won't occur, 87 | so such bugs can still lead to surprising behavior. 88 | 89 | For example, while unaligned memory access is 90 | [fully defined](Semantics.md#alignment) in WebAssembly, C and C++ compilers 91 | make no guarantee that a (non-packed) unaligned memory access at the source 92 | level is harmlessly translated into an unaligned memory access in WebAssembly. 93 | And in practice, popular C and C++ compilers do optimize on the assumption that 94 | alignment rules are followed, meaning that they don't always preserve program 95 | behavior otherwise. 96 | 97 | On WebAssembly, the primary [nondeterminism](Nondeterminism.md) and 98 | [security](Security.md) invariants are always maintained. Demons can't actually 99 | fly out your nose, as that would constitute an escape from the sandbox. And, 100 | callstacks can't become corrupted. 101 | 102 | Other than that, programs which invoke undefined behavior at the source language 103 | level may be compiled into WebAssembly programs which do anything else, 104 | including corrupting the contents of the application's linear memory, calling APIs with 105 | arbitrary parameters, hanging, trapping, or consuming arbitrary amounts of 106 | resources (within the limits). 107 | 108 | [Tools are being developed and ported](Tooling.md) to help developers find 109 | and fix such bugs in their code. 110 | 111 | #### Implementation-Defined Behavior 112 | 113 | Most implementation-defined behavior in C and C++ is dependent on the compiler 114 | rather than on the underlying platform. For those details that are dependent 115 | on the platform, on WebAssembly they follow naturally from having 8-bit bytes, 116 | 32-bit and 64-bit two's complement integers, and 117 | [32-bit and 64-bit IEEE-754-2019-style floating point support](https://webassembly.github.io/spec/core/exec/numerics.html#floating-point). 118 | 119 | ## Portability of compiled code 120 | 121 | WebAssembly can be efficiently implemented on a wide variety of platforms, 122 | provided they can satisfy certain 123 | [basic expectations](Portability.md#assumptions-for-efficient-execution). 124 | 125 | WebAssembly has very limited [nondeterminism](Nondeterminism.md), so it is 126 | expected that compiled WebAssembly programs will behave very consistently 127 | across different implementations, and across different versions of the same 128 | implementation. 129 | 130 | [future 64-bit]: https://github.com/WebAssembly/memory64 131 | [future threads]: https://github.com/WebAssembly/design/issues/1073 132 | [future simd]: https://github.com/WebAssembly/design/issues/1075 133 | [future exceptions]: https://github.com/WebAssembly/design/issues/1078 134 | 135 | -------------------------------------------------------------------------------- /CodeOfConduct.md: -------------------------------------------------------------------------------- 1 | The code of conduct has moved to https://github.com/WebAssembly/meetings/blob/main/CODE_OF_CONDUCT.md. 2 | -------------------------------------------------------------------------------- /Contributing.md: -------------------------------------------------------------------------------- 1 | # Contributing to WebAssembly 2 | 3 | Interested in contributing to WebAssembly? We suggest you start by: 4 | 5 | * Acquainting yourself with the 6 | [Code of Ethics and Professional Conduct](CodeOfConduct.md). 7 | 8 | * Joining the 9 | [W3C Community Group]. Please do this before starting new proposals, 10 | attending meetings, or making significant contributions. It provides the legal 11 | framework that protects participants and supports standardization. And make 12 | sure you're registered as affiliated with your company or organization in the 13 | Community Group, if any. 14 | 15 | * Then, you may wish to: 16 | - [ask questions], 17 | - discuss existing [phase-0 proposals] and [phase-1+ proposals], 18 | - attend [meetings], 19 | - discuss [tooling conventions], 20 | - or make [new proposals]! 21 | 22 | Happy assembly! 23 | 24 | [W3C Community Group]: https://www.w3.org/community/webassembly/ 25 | [Code of Ethics and Professional Conduct]: https://github.com/WebAssembly/meetings/blob/main/CODE_OF_CONDUCT.md 26 | [meetings]: https://github.com/WebAssembly/meetings 27 | [phase-1+ proposals]: https://github.com/WebAssembly/proposals 28 | [phase-0 proposals]: https://github.com/WebAssembly/design/issues 29 | [ask questions]: https://github.com/WebAssembly/design/discussions 30 | [new proposals]: https://github.com/WebAssembly/meetings/blob/main/process/proposal.md 31 | [tooling conventions]: https://github.com/WebAssembly/tool-conventions 32 | -------------------------------------------------------------------------------- /DynamicLinking.md: -------------------------------------------------------------------------------- 1 | # Dynamic linking 2 | 3 | WebAssembly enables load-time and run-time (`dlopen`) dynamic linking in the 4 | MVP by having multiple [instantiated modules](Modules.md) 5 | share functions, [linear memories](Semantics.md#linear-memory), 6 | [tables](Semantics.md#table) and [constants](Semantics.md#constants) 7 | using module [imports](Modules.md#imports) and [exports](Modules.md#exports). In 8 | particular, since all (non-local) state that a module can access can be imported 9 | and exported and thus shared between separate modules' instances, toolchains 10 | have the building blocks to implement dynamic loaders. 11 | 12 | Since the manner in which modules are loaded and instantiated is defined by the 13 | host environment (e.g., the [JavaScript API](JS.md)), dynamic linking requires 14 | use of host-specific functionality to link two modules. At a minimum, the host 15 | environment must provide a way to dynamically instantiate modules while 16 | connecting exports to imports. 17 | 18 | The simplest load-time dynamic linking scheme between modules A and B can be 19 | achieved by having module A export functions, tables and memories that are 20 | imported by B. A C++ toolchain can expose this functionality by using the 21 | same function attributes currently used to export/import symbols from 22 | native DSOs/DLLs: 23 | 24 | ``` 25 | #ifdef _WIN32 26 | # define EXPORT __declspec(dllexport) 27 | # define IMPORT __declspec(dllimport) 28 | #else 29 | # define EXPORT __attribute__ ((visibility ("default"))) 30 | # define IMPORT __attribute__ ((visibility ("default"))) 31 | #endif 32 | 33 | typedef void (**PF)(); 34 | 35 | IMPORT PF imp(); 36 | EXPORT void exp() { (*imp())(); } 37 | ``` 38 | 39 | This code would, at a minimum, generate a WebAssembly module with imports for: 40 | 41 | * the function `imp` 42 | * the heap used to perfom the load, when dereferencing the return value of `imp` 43 | * the table used to perform the pointer-to-function call 44 | 45 | and exports for: 46 | 47 | * the function `exp` 48 | 49 | A more realistic module using libc would have more imports including: 50 | 51 | * an immutable `i32` global import for the offset in linear memory to place 52 | global [data segments](Modules.md#data-section) and later use as a constant 53 | base address when loading and storing from globals 54 | * an immutable `i32` global import for the offset into the indirect function 55 | table at which to place the modules' indirectly called functions and later 56 | compute their indices for address-of 57 | 58 | One extra detail is what to use as the [module name](Modules.md#imports) for 59 | imports (since WebAssembly has a two-level namespace). One option is to have a 60 | single default module name for all C/C++ imports/exports (which then allows the 61 | toolchain to put implementation-internal names in a separate namespace, avoiding 62 | the need for `__`-prefix conventions). 63 | 64 | To implement run-time dynamic linking (e.g., `dlopen` and `dlsym`): 65 | 66 | * `dlopen` would compile and instantiate a new module, storing the compiled 67 | instance in a host-environment table, returning the index to the caller. 68 | * `dlsym` would be given this index, pull the instance out of the table, 69 | search the instances's exports, append the found function to the function 70 | table (using host-defined functionality in the MVP, but directly from 71 | WebAssembly code in the 72 | [future :unicorn:][future types]) and return the 73 | table index of the appended element to the caller. 74 | 75 | Note that the representation of a C function-pointer in WebAssembly is an index 76 | into a function table, so the above scheme lines up perfectly with the 77 | function-pointer return value of `dlsym`. 78 | 79 | More complicated dynamic linking functionality (e.g., interposition, weak 80 | symbols, etc) can be simulated efficiently by assigning a function table 81 | index to each weak/mutable symbol, calling the symbol via `call_indirect` on that 82 | index, and mutating the underlying element as needed. 83 | 84 | After the MVP, we would like to standardize a single [ABI][] per source 85 | language, allowing for WebAssembly libraries to interface with each other 86 | regardless of compiler. Specifying an ABI requires that all ABI-related 87 | future features (like SIMD, multiple return values and exception handling) 88 | have been implemented. While it is highly recommended for compilers targeting 89 | WebAssembly to adhere to the specified ABI for interoperability, WebAssembly 90 | runtimes will be ABI agnostic, so it will be possible to use a non-standard ABI 91 | for specialized purposes. 92 | 93 | [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface 94 | 95 | [future types]: https://github.com/WebAssembly/reference-types/blob/master/proposals/reference-types/Overview.md#language-extensions 96 | -------------------------------------------------------------------------------- /Events.md: -------------------------------------------------------------------------------- 1 | ## Past Events 2 | 3 | | Date | Title | Slides | Video | Presenter(s) | 4 | |-----:|-------|:------:|:-----:|--------------| 5 | | October 29th 2015 | LLVM Developers' Meeting | [slides](https://llvm.org/devmtg/2015-10/slides/BastienGohman-WebAssembly-HereBeDragons.pdf) | [video](https://www.youtube.com/watch?v=5W7NkofUtAw) | JF Bastien and Dan Gohman | 6 | | November 10th 2015 | BlinkOn 5: WebAssembly | | [video](https://youtu.be/iCSAUHpPbiU) | Nick Bray | 7 | | December 9th 2015 | Emscripten and WebAssembly | [slides](https://kripken.github.io/talks/wasm.html) | | Alon Zakai | 8 | | January 31st 2016 | FOSDEM LLVM room | [slides](https://fosdem.org/2016/schedule/event/llvm_webassembly) | | JF Bastien and Dan Gohman | 9 | | June 13th 2016 | NYLUG Presents: WebAssembly: A New Compiler Target For The Web | | [video](https://www.youtube.com/watch?v=RByPdCN1RQ4) | Luke Wagner | 10 | | July 7th 2016 | VMSS16: A Little on V8 and WebAssembly | [slides](https://ia601208.us.archive.org/16/items/vmss16/titzer.pdf) | [video](https://www.youtube.com/watch?v=BRNxM8szTPA) | Ben L. Titzer | 11 | | September 14th 2016 | WebAssembly: birth of a virtual ISA | | [video](https://www.youtube.com/watch?v=vmzz17JGPHI) | Ben Smith | 12 | | September 21st 2016 | C++ on the Web: Let's have some serious fun | | [video](https://www.youtube.com/watch?v=jXMtQ2fTl4c) | Dan Gohman | 13 | | September 22nd 2016 | WebAssembly: high speed at low cost for everyone | [paper](http://www.mlworkshop.org/2016-1.pdf) | | Andreas Rossberg | 14 | | October 31st 2016 | VMIL16: WebAssembly from wire to machine code: a view inside V8's implementation | | | Ben L. Titzer | 15 | | November 7th 2016 | Empire Node: How Webassembly Will Change the Way You Write Javascript | | [video](https://www.youtube.com/watch?v=kq2HBddiyh0) | Seth Samuel | 16 | | November 12th 2016 | Chrome Dev Summit Advanced JS performance with V8 and WebAssembly | | [video](https://www.youtube.com/watch?v=PvZdTZ1Nl5o) | Seth Thompson | 17 | | June 26th 2017 | Bringing the Web up to Speed with WebAssembly | [paper](https://github.com/WebAssembly/spec/blob/master/papers/pldi2017.pdf) | [video](https://www.youtube.com/watch?v=AFy5TdrFG9Y) | Andreas Rossberg 18 | | October 5th 2017 | Node.js Interactive: WebAssembly and the Future of the Web | [paper](https://kgryte.github.io/talks-nodejs-interactive-2017/#/splash) | [video](https://www.youtube.com/watch?v=iJL59lh4IJA) | Athan Reines 19 | | October 5th 2017 | Node.js Interactive: What's a Wasm? | | [video](https://www.youtube.com/watch?v=gk9ERa7UYPM) | Paul Milham 20 | 21 | 22 | ## Upcoming 23 | 24 | | Date | Title | Slides | Video | Presenter(s) | 25 | |-----:|-------|:------:|:-----:|--------------| 26 | -------------------------------------------------------------------------------- /FAQ.md: -------------------------------------------------------------------------------- 1 | # FAQ 2 | 3 | ## Why create a new standard when there is already asm.js? 4 | 5 | ... especially since pthreads ([Mozilla pthreads][], [Chromium pthreads][]) and 6 | SIMD ([simd.js][], [Chromium SIMD][], [simd.js in asm.js][]) are coming to 7 | JavaScript. 8 | 9 | [Mozilla pthreads]: https://blog.mozilla.org/javascript/2015/02/26/the-path-to-parallel-javascript/ 10 | [Chromium pthreads]: https://groups.google.com/a/chromium.org/forum/#!topic/blink-dev/d-0ibJwCS24 11 | [simd.js]: https://hacks.mozilla.org/2014/10/introducing-simd-js/ 12 | [Chromium SIMD]: https://groups.google.com/a/chromium.org/forum/#!topic/blink-dev/2PIOEJG_aYY 13 | [simd.js in asm.js]: http://discourse.specifiction.org/t/request-for-comments-simd-js-in-asm-js/676 14 | 15 | There are two main benefits WebAssembly provides: 16 | 17 | 1. The kind of binary format being considered for WebAssembly can be natively 18 | decoded much faster than JavaScript can be parsed ([experiments][] show more 19 | than 20× faster). On mobile, large compiled codes can easily take 20–40 20 | seconds *just to parse*, so native decoding (especially when combined with 21 | other techniques like [streaming][] for better-than-gzip compression) is 22 | critical to providing a good cold-load user experience. 23 | 24 | 2. By avoiding the simultaneous asm.js constraints of [AOT][]-[compilability][] 25 | and good performance even on engines without 26 | [specific asm.js optimizations][], a new standard makes it *much easier* to 27 | add the [features :unicorn:][future general] required to reach native 28 | levels of performance. 29 | 30 | [experiments]: BinaryEncoding.md#why-a-binary-encoding-instead-of-a-text-only-representation 31 | [streaming]: https://www.w3.org/TR/streams-api/ 32 | [AOT]: http://asmjs.org/spec/latest/#ahead-of-time-compilation 33 | [compilability]: https://blog.mozilla.org/luke/2014/01/14/asm-js-aot-compilation-and-startup-performance/ 34 | [specific asm.js optimizations]: https://blog.mozilla.org/luke/2015/02/18/microsoft-announces-asm-js-optimizations/#asmjs-opts 35 | 36 | Of course, every new standard introduces new costs (maintenance, attack surface, 37 | code size) that must be offset by the benefits. WebAssembly minimizes costs by 38 | having a design that allows (though not requires) a browser to implement 39 | WebAssembly inside its *existing* JavaScript engine (thereby reusing the 40 | JavaScript engine's existing compiler backend, ES6 module loading frontend, 41 | security sandboxing mechanisms and other supporting VM components). Thus, in 42 | cost, WebAssembly should be comparable to a big new JavaScript feature, not a 43 | fundamental extension to the browser model. 44 | 45 | Comparing the two, even for engines which already optimize asm.js, the benefits 46 | outweigh the costs. 47 | 48 | 49 | ## What are WebAssembly's use cases? 50 | 51 | WebAssembly was designed with [a variety of use cases in mind](UseCases.md). 52 | 53 | 54 | ## Can WebAssembly be polyfilled? 55 | 56 | We think so. There was an early 57 | [prototype](https://github.com/WebAssembly/polyfill-prototype-1) with demos 58 | [[1](https://lukewagner.github.io/AngryBotsPacked), 59 | [2](https://lukewagner.github.io/PlatformerGamePacked)], which showed 60 | that decoding a binary WebAssembly-like format into asm.js can be efficient. 61 | And as the WebAssembly design has changed there have been 62 | [more](https://github.com/WebAssembly/polyfill-prototype-2) 63 | [experiments](https://github.com/WebAssembly/binaryen/blob/master/src/wasm2asm.h) 64 | with polyfilling. 65 | 66 | Overall, optimism has been increasing for quick adoption of WebAssembly in 67 | browsers, which is great, but it has decreased the motivation to work on a 68 | polyfill. 69 | 70 | It is also the case that polyfilling WebAssembly to asm.js is less urgent 71 | because of the existence of alternatives, for example, a reverse polyfill - 72 | compiling 73 | [asm.js to WebAssembly](https://github.com/WebAssembly/binaryen/blob/master/src/asm2wasm.h) - 74 | exists, and it allows shipping a single build that can run as either 75 | asm.js or WebAssembly. It is also possible to build a project into 76 | two parallel asm.js and WebAssembly builds by just 77 | [flipping a switch](https://github.com/kripken/emscripten/wiki/WebAssembly) 78 | in emscripten, which avoids polyfill time on the client entirely. A third 79 | option, for non-performant code, is to use a compiled WebAssembly interpreter 80 | such as 81 | [binaryen.js](https://github.com/WebAssembly/binaryen/blob/master/test/binaryen.js/test.js). 82 | 83 | However, a WebAssembly polyfill is still an interesting idea and should in 84 | principle be possible. 85 | 86 | 87 | ## Is WebAssembly only for C/C++ programmers? 88 | 89 | As explained in the [high-level goals](HighLevelGoals.md), to achieve a Minimum 90 | Viable Product, the initial focus is on [C/C++](CAndC++.md). 91 | 92 | However, by [integrating with JavaScript at the ES6 Module interface](Modules.md#integration-with-es6-modules), 93 | web developers don't need to write C++ to take advantage of libraries that others have written; 94 | reusing a modular C++ library can be as simple as [using a module from JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules). 95 | 96 | Beyond the MVP, another [high-level goal](HighLevelGoals.md) 97 | is to improve support for languages other than C/C++. This includes [allowing WebAssembly code to 98 | allocate and access garbage-collected (JavaScript, DOM, Web API) objects 99 | :unicorn:][future garbage collection]. 100 | Even before GC support is added to WebAssembly, it is possible to compile a language's VM 101 | to WebAssembly (assuming it's written in portable C/C++) and this has already been demonstrated 102 | ([1](https://ruby.dj), [2](https://kripken.github.io/lua.vm.js/lua.vm.js.html), 103 | [3](https://syntensity.blogspot.com/2010/12/python-demo.html)). However, "compile the VM" strategies 104 | increase the size of distributed code, lose browser devtools integration, can have cross-language 105 | cycle-collection problems and miss optimizations that require integration with the browser. 106 | 107 | 108 | ## Which compilers can I use to build WebAssembly programs? 109 | 110 | WebAssembly initially focuses on [C/C++](CAndC++.md), and a new, clean 111 | WebAssembly backend is being developed in upstream clang/LLVM, which can then be 112 | used by LLVM-based projects like [Emscripten][] and [PNaCl][]. 113 | 114 | As WebAssembly evolves it will support more languages than C/C++, and we hope 115 | that other compilers will support it as well, even for the C/C++ language, for 116 | example [GCC][]. The WebAssembly working group found it easier to start with 117 | LLVM support because they had more experience with that toolchain from their 118 | [Emscripten][] and [PNaCl][] work. 119 | 120 | [Emscripten]: http://emscripten.org 121 | [PNaCl]: https://developer.chrome.com/docs/native-client/ 122 | [GCC]: https://gcc.gnu.org 123 | 124 | We hope that proprietary compilers also gain WebAssembly support, but we'll let 125 | vendors speak about their own platforms. 126 | 127 | The [WebAssembly Community Group][] would be delighted to collaborate with more 128 | compiler vendors, take their input into consideration in WebAssembly itself, and 129 | work with them on ABI matters. 130 | 131 | [WebAssembly Community Group]: https://www.w3.org/community/webassembly/ 132 | 133 | 134 | ## Will WebAssembly support View Source on the Web? 135 | 136 | Yes! WebAssembly defines a [text format](TextFormat.md) to be rendered when 137 | developers view the source of a WebAssembly module in any developer tool. Also, 138 | a specific goal of the text format is to allow developers to write WebAssembly 139 | modules by hand for testing, experimenting, optimizing, learning and teaching 140 | purposes. In fact, by dropping all the 141 | [coercions required by asm.js validation](http://asmjs.org/spec/latest/#introduction), 142 | the WebAssembly text format should be much more natural to read and write than 143 | asm.js. Outside the browser, command-line and online tools that convert between 144 | text and binary will also be made readily available. Lastly, a scalable form of 145 | source maps is also being considered as part of the WebAssembly 146 | [tooling story](Tooling.md). 147 | 148 | 149 | ## What's the story for Emscripten users? 150 | 151 | Existing Emscripten users will get the option to build their projects to 152 | WebAssembly, by flipping a flag. Initially, Emscripten's asm.js output would be 153 | converted to WebAssembly, but eventually Emscripten would use WebAssembly 154 | throughout the pipeline. This painless transition is enabled by the 155 | [high-level goal](HighLevelGoals.md) that WebAssembly integrate well with the 156 | Web platform (including allowing synchronous calls into and out of JavaScript) 157 | which makes WebAssembly compatible with Emscripten's current asm.js compilation 158 | model. 159 | 160 | 161 | ## Is WebAssembly trying to replace JavaScript? 162 | 163 | No! WebAssembly is designed to be a complement to, not replacement of, 164 | JavaScript. While WebAssembly will, over time, allow many languages to be 165 | compiled to the Web, JavaScript has an incredible amount of momentum and will 166 | remain the single, privileged (as described 167 | [above](FAQ.md#is-webassembly-only-for-cc-programmers)) dynamic language of the 168 | Web. Furthermore, it is expected that JavaScript and WebAssembly will be used 169 | together in a number of configurations: 170 | 171 | * Whole, compiled C++ apps that leverage JavaScript to glue things together. 172 | * HTML/CSS/JavaScript UI around a main WebAssembly-controlled center canvas, 173 | allowing developers to leverage the power of web frameworks to build 174 | accessible, web-native-feeling experiences. 175 | * Mostly HTML/CSS/JavaScript app with a few high-performance WebAssembly modules 176 | (e.g., graphing, simulation, image/sound/video processing, visualization, 177 | animation, compression, etc., examples which we can already see in asm.js 178 | today) allowing developers to reuse popular WebAssembly libraries just like 179 | JavaScript libraries today. 180 | * When WebAssembly 181 | [gains the ability to access garbage-collected objects :unicorn:][future garbage collection], 182 | those objects will be shared with JavaScript, and not live in a walled-off 183 | world of their own. 184 | 185 | 186 | ## Why not just use LLVM bitcode as a binary format? 187 | 188 | The [LLVM](https://llvm.org/) compiler infrastructure has a lot of attractive 189 | qualities: it has an existing intermediate representation (LLVM IR) and binary 190 | encoding format (bitcode). It has code generation backends targeting many 191 | architectures and is actively developed and maintained by a large community. In 192 | fact PNaCl already uses LLVM as a basis for its binary 193 | format. However, the goals and requirements that LLVM was designed to meet are 194 | subtly mismatched with those of WebAssembly. 195 | 196 | WebAssembly has several requirements and goals for its Instruction Set 197 | Architecture (ISA) and binary encoding: 198 | 199 | * Portability: The ISA must be the same for every machine architecture. 200 | * Stability: The ISA and binary encoding must not change over time (or change 201 | only in ways that can be kept backward-compatible). 202 | * Small encoding: The representation of a program should be as small as possible 203 | for transmission over the Internet. 204 | * Fast decoding: The binary format should be fast to decompress and decode for 205 | fast startup of programs. 206 | * Fast compiling: The ISA should be fast to compile (and suitable for either 207 | AOT- or JIT-compilation) for fast startup of programs. 208 | * Minimal [nondeterminism](Nondeterminism.md): The behavior of programs should 209 | be as predictable and deterministic as possible (and should be the same on 210 | every architecture, a stronger form of the portability requirement stated 211 | above). 212 | 213 | LLVM IR is meant to make compiler optimizations easy to implement, and to 214 | represent the constructs and semantics required by C, C++, and other languages 215 | on a large variety of operating systems and architectures. This means that by 216 | default the IR is not portable (the same program has different representations 217 | for different architectures) or stable (it changes over time as optimization and 218 | language requirements change). It has representations for a huge variety of 219 | information that is useful for implementing mid-level compiler optimizations but 220 | is not useful for code generation (but which represents a large surface area for 221 | codegen implementers to deal with). It also has undefined behavior (largely 222 | similar to that of C and C++) which makes some classes of optimization feasible 223 | or more powerful, but can lead to unpredictable behavior at runtime. LLVM's 224 | binary format (bitcode) was designed for temporary on-disk serialization 225 | of the IR for link-time optimization, and not for stability or compressibility 226 | (although it does have some features for both of those). 227 | 228 | None of these problems are insurmountable. For example PNaCl defines a small 229 | portable 230 | [subset](https://developer.chrome.com/native-client/reference/pnacl-bitcode-abi) 231 | of the IR with reduced undefined behavior, and a stable version of the bitcode 232 | encoding. It also employs several techniques to improve startup 233 | performance. However, each customization, workaround, and special solution means 234 | less benefit from the common infrastructure. We believe that by taking our 235 | experience with LLVM and designing an IR and binary encoding for our goals and 236 | requirements, we can do much better than adapting a system designed for other 237 | purposes. 238 | 239 | Note that this discussion applies to use of LLVM IR as a standardized 240 | format. LLVM's clang frontend and midlevel optimizers can still be used to 241 | generate WebAssembly code from C and C++, and will use LLVM IR in their 242 | implementation similarly to how PNaCl and Emscripten do today. 243 | 244 | 245 | ## Why is there no fast-math mode with relaxed floating point semantics? 246 | 247 | Optimizing compilers commonly have fast-math flags which permit the compiler to 248 | relax the rules around floating point in order to optimize more 249 | aggressively. This can include assuming that NaNs or infinities don't occur, 250 | ignoring the difference between negative zero and positive zero, making 251 | algebraic manipulations which change how rounding is performed or when overflow 252 | might occur, or replacing operators with approximations that are cheaper to 253 | compute. 254 | 255 | These optimizations effectively introduce nondeterminism; it isn't possible to 256 | determine how the code will behave without knowing the specific choices made by 257 | the optimizer. This often isn't a serious problem in native code scenarios, 258 | because all the nondeterminism is resolved by the time native code is 259 | produced. Since most hardware doesn't have floating point nondeterminism, 260 | developers have an opportunity to test the generated code, and then count on it 261 | behaving consistently for all users thereafter. 262 | 263 | WebAssembly implementations run on the user side, so there is no opportunity for 264 | developers to test the final behavior of the code. Nondeterminism at this level 265 | could cause distributed WebAssembly programs to behave differently in different 266 | implementations, or change over time. WebAssembly does have 267 | [some nondeterminism](Nondeterminism.md) in cases where the tradeoffs warrant 268 | it, but fast-math flags are not believed to be important enough: 269 | 270 | * Many of the important fast-math optimizations happen in the mid-level 271 | optimizer of a compiler, before WebAssembly code is emitted. For example, 272 | loop vectorization that depends on floating point reassociation can still be 273 | done at this level if the user applies the appropriate fast-math flags, so 274 | WebAssembly programs can still enjoy these benefits. As another example, 275 | compilers can replace floating point division with floating point 276 | multiplication by a reciprocal in WebAssembly programs just as they do for 277 | other platforms. 278 | * Mid-level compiler optimizations may also be augmented by implementing them 279 | in a [JIT library](JITLibrary.md) in WebAssembly. This would allow them to 280 | perform optimizations that benefit from having 281 | [information about the target](FeatureTest.md) and information about the 282 | source program semantics such as fast-math flags at the same time. For 283 | example, if SIMD types wider than 128-bit are added, it's expected that there 284 | would be feature tests allowing WebAssembly code to determine which SIMD 285 | types to use on a given platform. 286 | * When WebAssembly 287 | [adds an FMA operator :unicorn:][future floating point], 288 | folding multiply and add sequences into FMA operators will be possible. 289 | * WebAssembly doesn't include its own math functions like `sin`, `cos`, `exp`, 290 | `pow`, and so on. WebAssembly's strategy for such functions is to allow them 291 | to be implemented as library routines in WebAssembly itself (note that x86's 292 | `sin` and `cos` instructions are slow and imprecise and are generally avoided 293 | these days anyway). Users wishing to use faster and less precise math 294 | functions on WebAssembly can simply select a math library implementation 295 | which does so. 296 | * Most of the individual floating point operators that WebAssembly does have 297 | already map to individual fast instructions in hardware. Telling `add`, 298 | `sub`, or `mul` they don't have to worry about NaN for example doesn't make 299 | them any faster, because NaN is handled quickly and transparently in hardware 300 | on all modern platforms. 301 | * WebAssembly has no floating point traps, status register, dynamic rounding 302 | modes, or signalling NaNs, so optimizations that depend on the absence of 303 | these features are all safe. 304 | 305 | 306 | ## What about `mmap`? 307 | 308 | The [`mmap`](https://pubs.opengroup.org/onlinepubs/009695399/functions/mmap.html) 309 | syscall has many useful features. While these are all packed into one overloaded 310 | syscall in POSIX, WebAssembly unpacks this functionality into multiple 311 | operators: 312 | 313 | * the MVP starts with the ability to grow linear memory via a 314 | [`memory.grow`] operator; 315 | * proposed 316 | [future features :unicorn:][future memory control] would 317 | allow the application to change the protection and mappings for pages in the 318 | contiguous range `0` to `memory.size`. 319 | 320 | A significant feature of `mmap` that is missing from the above list is the 321 | ability to allocate disjoint virtual address ranges. The reasoning for this 322 | omission is: 323 | 324 | * The above functionality is sufficient to allow a user-level libc to implement 325 | full, compatible `mmap` with what appears to be noncontiguous memory 326 | allocation (but, under the hood is just coordinated use of `memory_resize` and 327 | `mprotect`/`map_file`/`map_shmem`/`madvise`). 328 | * The benefit of allowing noncontiguous virtual address allocation would be if 329 | it allowed the engine to interleave a WebAssembly module's linear memory with 330 | other memory allocations in the same process (in order to mitigate virtual 331 | address space fragmentation). There are two problems with this: 332 | 333 | - This interleaving with unrelated allocations does not currently admit 334 | efficient security checks to prevent one module from corrupting data outside 335 | its heap (see discussion in 336 | [#285](https://github.com/WebAssembly/design/pull/285)). 337 | - This interleaving would require making allocation nondeterministic and 338 | nondeterminism is something that WebAssembly generally 339 | [tries to avoid](Nondeterminism.md). 340 | 341 | 342 | ## Why have wasm32 and wasm64, instead of just an abstract `size_t`? 343 | 344 | The amount of linear memory needed to hold an abstract `size_t` would then also 345 | need to be determined by an abstraction, and then partitioning the linear memory 346 | address space into segments for different purposes would be more complex. The 347 | size of each segment would depend on how many `size_t`-sized objects are stored 348 | in it. This is theoretically doable, but it would add complexity and there would 349 | be more work to do at application startup time. 350 | 351 | Also, allowing applications to statically know the pointer size can allow them 352 | to be optimized more aggressively. Optimizers can better fold and simplify 353 | integer expressions when they have full knowledge of the bitwidth. And, knowing 354 | memory sizes and layouts for various types allows one to know how many trailing 355 | zeros there are in various pointer types. 356 | 357 | Also, C and C++ deeply conflict with the concept of an abstract `size_t`. 358 | Constructs like `sizeof` are required to be fully evaluated in the front-end 359 | of the compiler because they can participate in type checking. And even before 360 | that, it's common to have predefined macros which indicate pointer sizes, 361 | allowing code to be specialized for pointer sizes at the very earliest stages of 362 | compilation. Once specializations are made, information is lost, scuttling 363 | attempts to introduce abstractions. 364 | 365 | And finally, it's still possible to add an abstract `size_t` in the future if 366 | the need arises and practicalities permit it. 367 | 368 | 369 | ## Why have wasm32 and wasm64, instead of just using 8 bytes for storing pointers? 370 | 371 | A great number of applications don't ever need as much as 4 GiB of memory. 372 | Forcing all these applications to use 8 bytes for every pointer they store would 373 | significantly increase the amount of memory they require, and decrease their 374 | effective utilization of important hardware resources such as cache and memory 375 | bandwidth. 376 | 377 | The motivations and performance effects here should be essentially the same as 378 | those that motivated the development of the 379 | [x32 ABI](https://en.wikipedia.org/wiki/X32_ABI) for Linux. 380 | 381 | Even Knuth found it worthwhile to give us his opinion on this issue at some point, 382 | [a flame about 64-bit pointers](https://www-cs-faculty.stanford.edu/~uno/news08.html). 383 | 384 | ## Will I be able to access proprietary platform APIs (e.g. Android / iOS)? 385 | 386 | Yes but it will depend on the _WebAssembly embedder_. Inside a browser you'll 387 | get access to the same HTML5 and other browser-specific APIs which are also 388 | accessible through regular JavaScript. However, if a wasm VM is provided as an 389 | [“app execution platform”](NonWeb.md) by a specific vendor, it might provide 390 | access to [proprietary platform-specific APIs](Portability.md#api) of e.g. 391 | Android / iOS. 392 | 393 | [future general]: FutureFeatures.md 394 | [future garbage collection]: https://github.com/WebAssembly/proposals/issues/16 395 | [future floating point]: https://github.com/WebAssembly/design/issues/1391 396 | [future memory control]: https://github.com/WebAssembly/memory-control 397 | [`memory.grow`]: https://webassembly.github.io/spec/core/syntax/instructions.html#syntax-instr-memory 398 | -------------------------------------------------------------------------------- /FeatureTest.md: -------------------------------------------------------------------------------- 1 | See [rationale](Rationale.md#feature-testing---motivating-scenarios) for motivating scenarios. 2 | 3 | # Feature Test 4 | 5 | [Post-MVP :unicorn:][future general], applications will be able to query which features are 6 | supported via 7 | [`has_feature` or a similar API :unicorn:][future feature testing]. This 8 | accounts for the pragmatic reality that features are shipped in different orders 9 | at different times by different engines. 10 | 11 | What follows is a sketch of what such a feature testing capability could look 12 | like. 13 | 14 | Since some WebAssembly features add operators and all WebAssembly code in a 15 | module is validated ahead-of-time, the usual JavaScript feature detection 16 | pattern: 17 | 18 | ``` 19 | if (foo) 20 | foo(); 21 | else 22 | alternativeToFoo(); 23 | ``` 24 | 25 | won't work in WebAssembly (if `foo` isn't supported, `foo()` will fail to 26 | validate). 27 | 28 | Instead, applications may use one of the following strategies: 29 | 30 | 1. Compile several versions of a module, each assuming different feature support 31 | and use `has_feature` tests to determine which version to load. 32 | 33 | 2. During the ["specific" layer decoding](BinaryEncoding.md), which will happen 34 | in user code in the MVP *anyway*, use `has_feature` to determine which features 35 | are supported and then translate unsupported feature use into either a polyfill 36 | or a trap. 37 | 38 | Both of these options could be automatically provided by the toolchain and 39 | controlled by compiler flags. Since `has_feature` is a constant expression, 40 | it can be constant-folded by WebAssembly engines. 41 | 42 | To illustrate, consider 4 examples: 43 | 44 | * [`i32.bitrev` :unicorn:][future integer] - Strategy 2 45 | could be used to translate `(i32.bitrev lhs rhs)` into an equivalent expression 46 | that stores `lhs` and `rhs` in locals then uses `i32.lt_s` and `select`. 47 | * [Threads :unicorn:][future threads] - If an application uses `#ifdef` extensively 48 | to produce thread-enabled/disabled builds, Strategy 1 would be appropriate. 49 | However, if the application was able to abstract use of threading to a few 50 | primitives, Strategy 2 could be used to patch in the right primitive 51 | implementation. 52 | * [`mprotect` :unicorn:][future memory control] - If engines 53 | aren't able to use OS signal handling to implement `mprotect` efficiently, 54 | `mprotect` may become a permanently optional feature. For uses of `mprotect` 55 | that are not necessary for correctness (but rather just catching bugs), 56 | `mprotect` could be replaced with `nop`. If `mprotect` was necessary for 57 | correctness but an alternative strategy existed that did not rely on 58 | `mprotect`, `mprotect` could be replaced with an `abort()` call, relying on 59 | the application to test `(has_feature "mprotect")` to avoid calling the 60 | `abort()`. The `has_feature` query could be exposed to C++ code via 61 | the existing `__builtin_cpu_supports`. 62 | * [SIMD][future simd] - When SIMD operators have a good-enough 63 | polyfill, e.g., `f32x4.fma` via `f32x4.mul`/`add`, Strategy 2 could be used 64 | (similar to the `i32.bitrev` example above). However, when a SIMD feature has no 65 | efficient polyfill (e.g., `f64x2`, which introduces both operators *and* 66 | types), alternative algorithms need to be provided and selected at load time. 67 | 68 | As a hypothetical (not implemented) example polyfilling the SIMD `f64x2` 69 | feature, the C++ compiler could provide a new function attribute that indicated 70 | that one function was an optimized, but feature-dependent, version of another 71 | function (similar to the 72 | [`ifunc` attribute](https://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/Function-Attributes.html#index-g_t_0040code_007bifunc_007d-attribute-2529), 73 | but without the callback): 74 | 75 | ``` 76 | #include 77 | void foo(...) { 78 | __m128 x, y; // -> f32x4 locals 79 | ... 80 | x = _mm_add_ps(x, y); // -> f32x4.add 81 | ... 82 | } 83 | void foo_f64x2(...) __attribute__((optimizes("foo","f64x2"))) { 84 | __m256 x, y; // -> f64x2 locals 85 | ... 86 | x = _m_add_pd(x, y); // -> f64x2.add 87 | ... 88 | } 89 | ... 90 | foo(...); // calls either foo or foo_f64x2 91 | ``` 92 | 93 | In this example, the toolchain could emit both `foo` and `foo_f64x2` as 94 | function definitions in the "specific layer" binary format. The load-time 95 | polyfill would then replace `foo` with `foo_f64x2` if 96 | `(has_feature "f64x2")`. Many other strategies are possible to allow finer or 97 | coarser granularity substitution. Since this is all in userspace, the strategy 98 | can evolve over time. 99 | 100 | See also the [better feature testing support :unicorn:][future feature testing] 101 | future feature. 102 | 103 | [future general]: FutureFeatures.md 104 | [future feature testing]: https://github.com/WebAssembly/design/issues/1280 105 | [future integer]: https://github.com/WebAssembly/design/issues/1382 106 | [future threads]: https://github.com/WebAssembly/design/issues/1073 107 | [future simd]: https://github.com/WebAssembly/design/issues/1075 108 | [future memory control]: https://github.com/WebAssembly/memory-control 109 | -------------------------------------------------------------------------------- /FutureFeatures.md: -------------------------------------------------------------------------------- 1 | # Future Features for WebAssembly 2 | 3 | For a list of standard and standard-track features and their implementation 4 | status in major WebAssembly implementations, see 5 | [the WebAssembly features page]. 6 | 7 | For a list of all currently active proposals and their champions, see 8 | [the proposals page]. 9 | 10 | For a list of discussions about possible future features, see 11 | [the design repo's issue tracker]. 12 | 13 | [the WebAssembly features page]: https://webassembly.org/features/ 14 | [the proposals page]: https://github.com/WebAssembly/proposals/ 15 | [the design repo's issue tracker]: https://github.com/WebAssembly/design/issues 16 | -------------------------------------------------------------------------------- /HighLevelGoals.md: -------------------------------------------------------------------------------- 1 | # WebAssembly High-Level Goals 2 | 3 | 1. Define a [portable](Portability.md), size- and load-time-efficient 4 | [binary format](MVP.md#binary-format) to serve as a compilation target which 5 | can be compiled to execute at native speed by taking advantage of common 6 | hardware capabilities available on a wide range of platforms, including 7 | [mobile](https://en.wikipedia.org/wiki/Mobile_device) and 8 | [IoT](https://en.wikipedia.org/wiki/Internet_of_Things). 9 | 2. Specify and implement incrementally: 10 | * develop new features as independent [proposals]; 11 | * maintain [layering], with a core spec focused on pure sandboxed 12 | computation, with host interactions factored out into higher 13 | specification layers; 14 | * preserve backwards compatibility; 15 | * prioritize new features according to feedback and experience; and 16 | * avoid biasing towards any one programming language family. 17 | 3. Design to execute within and integrate well with the *existing* 18 | [Web platform](Web.md): 19 | * maintain the versionless, [feature-tested](FeatureTest.md) and backwards-compatible evolution story of the Web; 20 | * execute in the same semantic universe as JavaScript; 21 | * allow synchronous calls to and from JavaScript; 22 | * enforce the same-origin and permissions security policies; 23 | * access browser functionality through the same Web APIs that are accessible 24 | to JavaScript; and 25 | * define a human-editable text format that is convertible to and from the 26 | binary format, supporting View Source functionality. 27 | 4. Design to support [non-browser embeddings](NonWeb.md) as well. 28 | 5. Make a great platform: 29 | * promote [compilers and tools targeting WebAssembly]; 30 | * enable other useful [tooling](Tooling.md); 31 | * maintain a high level of [determinism]; and 32 | * specify using [formal semantics]. 33 | 34 | [compilers and tools targeting WebAssembly]: https://webassembly.org/getting-started/developers-guide/ 35 | [proposals]: https://github.com/WebAssembly/proposals/ 36 | [layering]: https://webassembly.org/specs/ 37 | [determinism]: Nondeterminism.md 38 | [formal semantics]: https://github.com/WebAssembly/spec 39 | -------------------------------------------------------------------------------- /JITLibrary.md: -------------------------------------------------------------------------------- 1 | # JIT and Optimization Library 2 | 3 | WebAssembly's Just-in-Time compilation (JIT) 4 | interface will likely be fairly low-level, exposing general-purpose primitives 5 | rather than higher-level functionality. Still, there is a need for higher-level 6 | functionality, and for greater flexibility than the WebAssembly spec can provide. 7 | There is also a need for experimentation, particularly in the area of 8 | applications wishing to dynamically generate new code, to determine which features 9 | and interfaces are most appropriate. JIT and Optimization libraries that would run 10 | inside WebAssembly and provide support and higher-level features would fit this 11 | need very well. 12 | 13 | Such libraries wouldn't be part of the WebAssembly spec itself, but the concept 14 | is relevant to discuss here because features that we can expect to address in 15 | libraries are features that we may not need to add to the spec. This strategy 16 | can help keep the spec itself simple and reduce the surface area of features 17 | required of every spec implementation. 18 | 19 | And, libraries will facilitate light-weight experimentation with new features 20 | that we may eventually want to add to WebAssembly itself. In a library layer, 21 | we can quickly iterate, experiment, and gain real-world insight, before adding 22 | features to the spec itself and freezing all the details. And as new features 23 | are standardized, libraries will become the polyfills which will help those 24 | features gain adoption. 25 | 26 | This raises the question of how we should decide which features belong in the 27 | spec, and which belong in a library. Some of the fundamental advantages of 28 | putting functionality in a library rather than in the spec and in implementations 29 | themselves include: 30 | 31 | * A library can freely choose to offer greater degrees of undefined behavior, 32 | implementation-defined behavior, unspecified behavior, and so on. This means 33 | it can perform much more aggressive optimizations, including many that are 34 | extremely common in optimizing compilers and might otherwise seem missing in 35 | the WebAssembly spec itself: 36 | * Constant folding, strength reduction, and code motion of math functions 37 | such as `sin`, `cos`, `exp`, `log`, `pow`, and `atan2`. 38 | * Performing aggressive expression simplifications that depend on assuming 39 | that integer arithmetic doesn't overflow. 40 | * Performing GVN with redundant load elimination, and other optimizations 41 | based on aliasing rules that incur undefined behavior if they are violated. 42 | * Vectorization that utilizes both floating point reassociation and 43 | awareness of the underlying platform through 44 | [feature testing](FeatureTest.md). 45 | 46 | * A library can support higher-level features, and features that are tailored 47 | to certain applications, whereas the WebAssembly spec itself is limited to 48 | general-purpose primitives. Possible examples of this are: 49 | * A richer type system, which could include things like complex, rational, 50 | arbitrary bitwidth integers, non-power-of-2 SIMD types, interval 51 | arithmetic, etc. 52 | * A higher-level type system, which could include basic polymorphism of 53 | various kinds (either with true dynamism or with monomorphisation). 54 | * Richer control flow constructs. 55 | * A broader set of operators, such as string-handling operators, 56 | data type serialization, testing facilities, and linear algebra 57 | operators, all of which can benefit from being integrated at the 58 | language level. 59 | Since every feature required in the spec itself will need to be implemented 60 | by all implementations, domain-specific features run the risk of making 61 | people "pay for what they don't use". With features libraries, people need 62 | only pay for the features they choose to use. 63 | 64 | * A library can evolve over time to meet the changing needs of higher-level 65 | languages. In practice, compiler IRs such as LLVM IR evolve to add new 66 | features, change existing features, and sometimes remove features, and these 67 | kinds of changes are much harder to do in a spec. 68 | 69 | The library approach also means that applications using a particular version 70 | of a library can get consistent behavior and performance, because of the 71 | determinism of the underlying WebAssembly platform. 72 | 73 | A significant range of approaches are possible: 74 | 75 | * "Customized WebAssembly". This might involve a library whose input format 76 | is conceptually WebAssembly but with some additional features. The library 77 | could optimize and then lower those features leaving standard WebAssembly 78 | to present to the underlying implementation. 79 | 80 | * "Bring Your Own Compiler" There's nothing stopping one from bundling 81 | full-fledged AOT-style compilers that compile an independent source language 82 | or IR into WebAssembly right there in WebAssembly itself. Obviously this 83 | will involve tradeoffs in terms of download size and startup time, but it 84 | would allow a unique degree of flexibility. 85 | 86 | * And many things in between. 87 | -------------------------------------------------------------------------------- /JS.md: -------------------------------------------------------------------------------- 1 | # JavaScript API 2 | 3 | This file historically contained the description of WebAssembly's JavaScript API. 4 | 5 | For the current description, see the [normative documentation](http://webassembly.github.io/spec/js-api/index.html). 6 | -------------------------------------------------------------------------------- /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 | 203 | -------------------------------------------------------------------------------- /MVP.md: -------------------------------------------------------------------------------- 1 | # Minimum Viable Product 2 | 3 | WebAssembly initially launched with a "minimum viable product" version (the "MVP"), 4 | which was complete enough for some use cases, however many important features were 5 | deferred. WebAssembly has added many [features] since then. 6 | 7 | [features]: https://webassembly.org/features/ 8 | -------------------------------------------------------------------------------- /Modules.md: -------------------------------------------------------------------------------- 1 | # Modules 2 | 3 | This file historically contained the description of WebAssembly's module structure. 4 | 5 | For the current description, see the [normative documentation](https://webassembly.github.io/spec/core/syntax/modules.html). 6 | -------------------------------------------------------------------------------- /NonWeb.md: -------------------------------------------------------------------------------- 1 | # Non-Web Embeddings 2 | 3 | While WebAssembly is designed to run [on the Web](Web.md), it is 4 | also desirable for it to be able to execute well in other environments, 5 | including everything from minimal shells for testing to full-blown 6 | application environments e.g. on servers in datacenters, on IoT devices, 7 | or mobile/desktop apps. It may even be desirable to execute WebAssembly 8 | embedded within larger programs. 9 | 10 | Non-Web environments may provide different APIs than Web 11 | environments. 12 | 13 | Non-Web environments include JavaScript VMs (e.g. [node.js]), however 14 | WebAssembly is also capable of being executed without a JavaScript VM present. 15 | The table in the [features page] of the website lists several such 16 | implementations. 17 | 18 | [node.js]: https://nodejs.org 19 | [features page]: https://webassembly.org/features/ 20 | 21 | [WASI] is a set of standards-track APIs being developed by the [WASI Subgroup] 22 | intended for use in many environments, including in non-browser and non-JS 23 | engines. 24 | 25 | [WASI]: https://wasi.dev 26 | [WASI Subgroup]: https://github.com/WebAssembly/wasi 27 | 28 | The WebAssembly spec itself will not try to define any large portable libc-like 29 | library. However, certain features that are core to WebAssembly semantics that 30 | are similar to functions found in native libc *would* be part of the core 31 | WebAssembly spec as primitive operators (e.g., the `memory.grow` operator, which 32 | is similar to the `sbrk` function on many systems, and in the future, perhaps 33 | operators supporting `dlopen` functionality). 34 | 35 | Where there is overlap between the Web and popular non-Web environments, 36 | shared specs could be proposed, but these would be separate from the WebAssembly 37 | spec. A symmetric example in JavaScript would be the in-progress 38 | [Loader](https://whatwg.github.io/loader) spec, which is proposed for both 39 | Web and node.js environments and is distinct from the JavaScript spec. 40 | 41 | However, for most cases it is expected that, to achieve portability at the 42 | source code level, communities would build libraries that mapped from a 43 | source-level interface such as POSIX or SDL to the host environment's builtin 44 | capabilities, either at build time or runtime, possibly making use of 45 | [feature testing](FeatureTest.md), [dynamic linking](DynamicLinking.md), 46 | static linking, or polyfilling. 47 | 48 | In general, by preserving spec layering, and the core WebAssembly spec 49 | independent of the host environment and linking specs, WebAssembly can be 50 | used as a portable binary format on many platforms, in many environments, for 51 | many use cases, bringing great benefits in portability, tooling and 52 | language-agnosticity. 53 | 54 | [shared-everything linking]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/examples/SharedEverythingDynamicLinking.md 55 | -------------------------------------------------------------------------------- /Nondeterminism.md: -------------------------------------------------------------------------------- 1 | # Nondeterminism in WebAssembly 2 | 3 | WebAssembly is a [portable](Portability.md) [sandboxed](Security.md) platform 4 | with limited, local, nondeterminism. 5 | 6 | * *Limited*: nondeterministic execution can only occur in a small number of 7 | well-defined cases (described below) and, in those cases, the implementation 8 | may select from a limited set of possible behaviors. 9 | * *Local*: when nondeterministic execution occurs, the effect is local, 10 | there is no "spooky action at a distance". 11 | 12 | The [rationale](Rationale.md) document details why WebAssembly is designed as 13 | detailed in this document. 14 | 15 | The following is a list of the places where the WebAssembly specification 16 | currently admits nondeterminism: 17 | 18 | * New features will be added to WebAssembly, which means different implementations 19 | will have different support for each feature. 20 | * The sequence of calls of exported functions, and the values of the incoming 21 | arguments and return values from the outside environment, are not 22 | determined by the Wasm spec. 23 | * With `shared` memory that can be accessed by multiple threads, the results of 24 | load, read-modify-write, wait, and awake operators are nondeterministic. 25 | * Except when otherwise specified, when an arithmetic operator returns NaN, 26 | there is nondeterminism in determining the specific bits of the NaN. However, 27 | wasm does still provide the guarantee that NaN values returned from an operation 28 | will not have 1 bits in their fraction field that aren't set in any NaN values 29 | in the input operands, except for the most significant bit of the fraction field 30 | (which most operators set to 1). 31 | * Except when otherwise specified, when an arithmetic operator with a floating 32 | point result type receives no NaN input values and produces a NaN result 33 | value, the sign bit of the NaN result value is nondeterministic. 34 | * The [relaxed SIMD] instructions have nondeterministic results. 35 | * Environment-dependent resource limits may be exhausted. A few examples: 36 | - Memory allocation may fail. 37 | - The runtime can fail to allocate a physical page when a memory location is first 38 | accessed (e.g. through a load or store), even if that memory was virtually reserved 39 | by the maximum size property of the [memory section](Modules.md#linear-memory-section). 40 | - Program stack may get exhausted (e.g., because function call depth is too big, 41 | or functions have too many locals, or infinite recursion). Note that this stack 42 | isn't located in the program-accessible linear memory. 43 | - Resources such as handles may get exhausted. 44 | - Any other resource could get exhausted at any time. Caveat emptor. 45 | 46 | The following proposals would add additional nondeterminism: 47 | 48 | * [Flexible-vectors], adding nondeterminism in the length of the vectors. 49 | 50 | Users of C, C++, and similar languages should be aware that operators which 51 | have defined or constrained behavior in WebAssembly itself may nonetheless still 52 | have undefined behavior 53 | [at the source code level](CAndC++.md#undefined-behavior). 54 | 55 | [relaxed SIMD]: https://github.com/WebAssembly/relaxed-simd 56 | [Flexible-vectors]: https://github.com/WebAssembly/flexible-vectors 57 | -------------------------------------------------------------------------------- /Portability.md: -------------------------------------------------------------------------------- 1 | # Portability 2 | 3 | WebAssembly's [binary format](BinaryEncoding.md) is designed to be executable 4 | efficiently on a variety of operating systems and instruction set architectures, 5 | [on the Web](Web.md) and [off the Web](NonWeb.md). 6 | 7 | ## Assumptions for Efficient Execution 8 | 9 | Execution environments which, despite 10 | [limited, local, nondeterminism](Nondeterminism.md), don't offer 11 | the following characteristics may be able to execute WebAssembly modules 12 | nonetheless. In some cases they may have to emulate behavior that the host 13 | hardware or operating system don't offer so that WebAssembly modules execute 14 | *as-if* the behavior were supported. This sometimes will lead to poor 15 | performance. 16 | 17 | As WebAssembly's standardization goes forward we expect to formalize these 18 | requirements, and how WebAssembly will adapt to new platforms that didn't 19 | necessarily exist when WebAssembly was first designed. 20 | 21 | WebAssembly portability assumes that execution environments offer the following 22 | characteristics: 23 | 24 | * 8-bit bytes. 25 | * Addressable at a byte memory granularity. 26 | * Support unaligned memory accesses or reliable trapping that allows software 27 | emulation thereof. 28 | * Two's complement signed integers in 32 bits and optionally 64 bits. 29 | * IEEE 754-2019 32-bit and 64-bit floating point, except for 30 | [a few exceptions][floating-point operations]. 31 | * Little-endian byte ordering. 32 | * Memory regions which can be efficiently addressed with 32-bit 33 | pointers or indices. 34 | * wasm64 additionally supports linear memory bigger than 35 | [4 GiB with 64-bit pointers or indices][future 64-bit]. 36 | * Enforce secure isolation between WebAssembly modules and other modules or 37 | processes executing on the same machine. 38 | * An execution environment which offers forward progress guarantees to all 39 | threads of execution (even when executing in a non-parallel manner). 40 | * Availability of lock-free atomic memory operators, when naturally aligned, for 41 | 8- 16- and 32-bit accesses. At a minimum this must include an atomic 42 | compare-and-exchange operator (or equivalent load-linked/store-conditional). 43 | * wasm64 additionally requires lock-free atomic memory operators, when naturally 44 | aligned, for 64-bit accesses. 45 | 46 | ## API 47 | 48 | WebAssembly does not specify any APIs or syscalls, only an 49 | [import mechanism](Modules.md) where the set of available imports is defined 50 | by the host environment. In a [Web](Web.md) environment, functionality is 51 | accessed through the Web APIs defined by the 52 | [Web Platform](https://en.wikipedia.org/wiki/Open_Web_Platform). 53 | [Non-Web](NonWeb.md) environments can choose to implement standard Web APIs, 54 | standard non-Web APIs (e.g. POSIX), or invent their own. 55 | 56 | ## Source-level 57 | 58 | Portability at the C/C++ level can be achieved by programming to 59 | a standard API (e.g., POSIX) and relying on the compiler and/or libraries to map 60 | the standard interface to the host environment's available imports either at 61 | compile-time (via `#ifdef`) or run-time (via [feature detection] 62 | and dynamic [loading](Modules.md)/[linking](DynamicLinking.md)). 63 | 64 | [future 64-bit]: https://github.com/WebAssembly/memory64/blob/main/proposals/memory64/Overview.md 65 | [floating-point operations]: https://webassembly.github.io/spec/core/exec/numerics.html#floating-point-operations 66 | [feature detection]: https://github.com/WebAssembly/design/issues/1280 67 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WebAssembly Design 2 | 3 | This repository is part of the [WebAssembly Community Group] and hosts the 4 | [issue tracker] for [phase 0 proposals], a [discussion forum] for questions 5 | and general discussion, and a collection of high-level non-normative 6 | [design documents]. 7 | 8 | For more information about WebAssembly itself, see [the website]! For 9 | information about Contributing to WebAssembly see [the Contributing document]. 10 | 11 | Please follow our [Code of Ethics and Professional Conduct]. 12 | 13 | ## Design documents 14 | 15 | Some of the design documents in this repository are out of date. We're 16 | gradually working updating these documents. The following are some documents 17 | which are fairly up to date: 18 | 19 | - [WebAssembly High-Level Goals](HighLevelGoals.md) 20 | - [What does Portability mean in Wasm?](Portability.md) 21 | - [Design Rationale](Rationale.md) 22 | - [WebAssembly's Security model](Security.md) 23 | - [Nondeterminism in WebAssembly](Nondeterminism.md) 24 | 25 | [issue tracker]: https://github.com/WebAssembly/design/issues 26 | [phase 0 proposals]: https://github.com/WebAssembly/meetings/blob/main/process/phases.md#0-pre-proposal-individual-contributor 27 | [discussion forum]: https://github.com/WebAssembly/design/discussions 28 | [the Contributing document]: Contributing.md 29 | [the website]: https://webassembly.org 30 | [Code of Ethics and Professional Conduct]: https://github.com/WebAssembly/meetings/blob/main/CODE_OF_CONDUCT.md 31 | [design documents]: #design-documents 32 | [WebAssembly Community Group]: https://www.w3.org/community/webassembly/ 33 | -------------------------------------------------------------------------------- /Rationale.md: -------------------------------------------------------------------------------- 1 | # Design Rationale 2 | 3 | This document describes rationales for WebAssembly's design decisions, acting as 4 | footnotes to the main design text, keeping the main specification easier to 5 | read, and making it easier to revisit decisions later without having to plow 6 | through all the issues and pull requests. This rationale document tries to list 7 | how decisions were made, and where tradeoffs were made for the sake of language 8 | ergonomics, portability, performance, security, and Getting Things Done. 9 | 10 | WebAssembly was designed incrementally, with multiple implementations being 11 | pursued concurrently. As the MVP stabilizes and we get experience from real-world 12 | codebases, we'll revisit the alternatives listed below, reevaluate the tradeoffs 13 | and update the [design](Semantics.md) before the MVP is finalized. 14 | 15 | 16 | ## Why a stack machine? 17 | 18 | Why not an AST, or a register- or SSA-based bytecode? 19 | 20 | * We started with an AST and generalized to a [structured stack machine](Semantics.md). ASTs allow a 21 | dense encoding and efficient decoding, compilation, and interpretation. 22 | The structured stack machine of WebAssembly is a generalization of ASTs allowed in previous versions while allowing 23 | efficiency gains in interpretation and baseline compilation, as well as a straightforward 24 | design for multi-return functions. 25 | * The stack machine allows smaller binary encoding than registers or SSA [JSZap][], [Slim Binaries][], 26 | and structured control flow allows simpler and more efficient verification, including decoding directly 27 | to a compiler's internal SSA form. 28 | * [Polyfill prototype][] shows simple and efficient translation to asm.js. 29 | 30 | [JSZap]: https://research.microsoft.com/en-us/projects/jszap/ 31 | [Slim Binaries]: https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.108.1711 32 | [Polyfill prototype]: https://github.com/WebAssembly/polyfill-prototype-1 33 | 34 | 35 | ## Why not a fully-general stack machine? 36 | 37 | The WebAssembly stack machine is restricted to structured control flow and structured 38 | use of the stack. This greatly simplifies one-pass verification, avoiding a fixpoint computation 39 | like that of other stack machines such as the Java Virtual Machine (prior to [stack maps](https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html)). 40 | This also simplifies compilation and manipulation of WebAssembly code by other tools. 41 | Further generalization of the WebAssembly stack machine is planned post-MVP, such as the 42 | addition of multiple return values from control flow constructs and function calls. 43 | 44 | ## Basic Types Only 45 | 46 | WebAssembly only represents [a few types](Semantics.md#Types). 47 | 48 | * More complex types can be formed from these basic types. It's up to the source 49 | language compiler to express its own types in terms of the basic machine 50 | types. This allows WebAssembly to present itself as a virtual ISA, and lets 51 | compilers target it as they would any other ISA. 52 | * These types are directly representable on all modern CPU architectures. 53 | * Smaller types (such as `i8` and `i16`) are usually no more efficient and in 54 | languages like C/C++ are only semantically meaningful for memory accesses 55 | since arithmetic get widened to `i32` or `i64`. Avoiding them at least for MVP 56 | makes it easier to implement a WebAssembly VM. 57 | * Other types (such as `f16`, `i128`) aren't widely supported by existing 58 | hardware and can be supported by runtime libraries if developers wish to use 59 | them. Hardware support is sometimes uneven, e.g. some support load/store of 60 | `f16` only whereas other hardware also supports scalar arithmetic on `f16`, 61 | and yet other hardware only supports SIMD arithmetic on `f16`. They can be 62 | added to WebAssembly later without compromising MVP. 63 | * More complex object types aren't semantically useful for MVP: WebAssembly 64 | seeks to provide the primitive building blocks upon which higher-level 65 | constructs can be built. They may become useful to support other languages, 66 | especially when considering [garbage collection][future garbage collection]. 67 | 68 | 69 | ## Load/Store Addressing 70 | 71 | Load/store instructions include an immediate offset used for 72 | [addressing](Semantics.md#Addressing). This is intended to simplify folding 73 | of offsets into complex address modes in hardware, and to simplify bounds 74 | checking optimizations. It offloads some of the optimization work to the 75 | compiler that targets WebAssembly, executing on the developer's machine, instead 76 | of performing that work in the WebAssembly compiler on the user's machine. 77 | 78 | 79 | ## Alignment Hints 80 | 81 | Load/store instructions contain 82 | [alignment hints](Semantics.md#Alignment). This makes it easier to generate 83 | efficient code on certain hardware architectures. 84 | 85 | Either tooling or an explicit opt-in "debug mode" in the spec could allow 86 | execution of a module in a mode that threw exceptions on misaligned access. 87 | This mode would incur some runtime cost for branching on most platforms which is 88 | why it isn't the specified default. 89 | 90 | 91 | ## Out of Bounds 92 | 93 | The ideal semantics is for 94 | [out-of-bounds accesses](Semantics.md#Out-of-Bounds) to trap, but the 95 | implications are not yet fully clear. 96 | 97 | There are several possible variations on this design being discussed and 98 | experimented with. More measurement is required to understand the associated 99 | tradeoffs. 100 | 101 | * After an out-of-bounds access, the instance can no longer execute code and 102 | any outstanding JavaScript [ArrayBuffer][] aliasing the linear memory are 103 | detached. 104 | * This would primarily allow hoisting bounds checks above effectful 105 | operators. 106 | * This can be viewed as a mild security measure under the assumption that 107 | while the sandbox is still ensuring safety, the instance's internal state 108 | is incoherent and further execution could lead to Bad Things (e.g., XSS 109 | attacks). 110 | * To allow for potentially more-efficient memory sandboxing, the semantics 111 | could allow for a nondeterministic choice between one of the following when 112 | an out-of-bounds access occurred. 113 | * The ideal trap semantics. 114 | * Loads return an unspecified value. 115 | * Stores are either ignored or store to an unspecified location in the 116 | linear memory. 117 | * Either tooling or an explicit opt-in "debug mode" in the spec should allow 118 | execution of a module in a mode that threw exceptions on out-of-bounds 119 | access. 120 | 121 | [ArrayBuffer]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer 122 | 123 | 124 | ## Linear Memory Resizing 125 | 126 | To allow efficient engines to employ virtual-memory based techniques for bounds 127 | checking, memory sizes are required to be page-aligned. 128 | For portability across a range of CPU architectures and operating systems, 129 | WebAssembly defines a fixed page size. 130 | Programs can depend on this fixed page size and still remain portable across all 131 | WebAssembly engines. 132 | 64KiB represents the least common multiple of many platforms and CPUs. 133 | In the future, WebAssembly may offer the ability to use larger page sizes on 134 | some platforms for increased TLB efficiency. 135 | 136 | The `memory.grow` operator returns the old memory size. This is desirable for 137 | using `memory.grow` independently on multiple threads, so that each thread can 138 | know where the region it allocated starts. The obvious alternative would be for 139 | such threads to communicate manually, however WebAssembly implementations will likely 140 | already be communicating between threads in order to properly allocate the sum 141 | of the allocation requests, so it's expected that they can provide the needed 142 | information without significant extra effort. 143 | 144 | The [optional maximum size](Modules.md#linear-memory-section) is designed to 145 | address a number of competing constraints: 146 | 147 | 1. Allow WebAssembly modules to grab large regions of contiguous memory in a 148 | 32-bit address space early in an application's startup before the virtual 149 | address space becomes fragmented by execution of the application. 150 | 2. Allow many small WebAssembly instances to execute in a single 32-bit process. 151 | (For example, it is common for a single web application to use dozens of 152 | libraries, each of which may, over time, include WebAssembly modules as 153 | implementation details.) 154 | 3. Avoid *forcing* every developer using WebAssembly to understand their precise 155 | maximum heap usage. 156 | 4. When [threading and shared memory][future threads] are added to WebAssembly 157 | post-MVP, the design should not require memory growth 158 | to `realloc` since this implies significant implementation complexity, 159 | security hazards, and optimization challenges. 160 | 161 | The optional maximum addresses these constraints: 162 | 163 | * (1) is addressed by specifying a large maximum memory size. Simply setting a 164 | large *initial* memory size has problems due to (3) and the fact that a 165 | failure to allocate initial is a fatal error which makes the choice of "how 166 | big?" difficult. 167 | * (2) and (3) are addressed by making the maximum optional combined with the 168 | implied implementation that, on 32-bit, engines will not allocate 169 | significantly more than the current memory size, *and* the compiler sets the 170 | initial size to just enough to hold static data. 171 | * (4) is addressed assuming that, when threading is added, a new, optional 172 | "shared" flag is added to the memory section that must be set to enable shared 173 | memory and the shared flag forces the maximum to be specified. In this case, 174 | shared memory never moves; the only thing that changes is that the bounds 175 | grows which does not have all the abovementioned hazards. In particular, any 176 | extant `SharedArrayBuffer`s that alias linear memory stay valid without 177 | any updates. 178 | 179 | ## Linear memory disabled if no linear memory section 180 | 181 | See [#107](https://github.com/WebAssembly/spec/pull/107). 182 | 183 | 184 | ## Control Flow 185 | 186 | Structured control flow provides simple and size-efficient binary encoding and 187 | compilation. Any control flow--even irreducible--can be transformed into structured 188 | control flow with the 189 | [Relooper](https://github.com/kripken/emscripten/raw/master/docs/paper.pdf) 190 | [algorithm](https://dl.acm.org/citation.cfm?id=2048224&CFID=670868333&CFTOKEN=46181900), 191 | with guaranteed low code size overhead, and typically minimal throughput 192 | overhead (except for pathological cases of irreducible control 193 | flow). Alternative approaches can generate reducible control flow via node 194 | splitting, which can reduce throughput overhead, at the cost of increasing 195 | code size (potentially very significantly in pathological cases). 196 | Also, 197 | [more expressive control flow constructs :unicorn:][future flow control] 198 | may be added in the future. 199 | 200 | ## Nop 201 | 202 | The nop operator does not produce a value or cause side effects. 203 | It is nevertheless useful for compilers and tools, which sometimes need to replace instructions with a `nop`. Without a `nop` instruction, code generators would use alternative *does-nothing* opcode patterns that consume space in a module and may have a runtime cost. Finding an appropriate opcode that does nothing but has the appropriate type for the node's location is nontrivial. The existence of many different ways to encode `nop` - often mixed in the same module - would reduce the efficiency of compression algorithms. 204 | 205 | 206 | ## Locals 207 | 208 | C/C++ makes it possible to take the address of a function's local values and 209 | pass this pointer to callees or to other threads. Since WebAssembly's local 210 | variables are outside the address space, C/C++ compilers implement address-taken 211 | variables by creating a separate stack data structure within linear memory. This 212 | stack is sometimes called the "aliased" stack, since it is used for variables 213 | which may be pointed to by pointers. 214 | 215 | Since the aliased stack appears to the WebAssembly engine as normal memory, 216 | WebAssembly optimizations that would target the aliased stack need to be more 217 | general, and thus more complicated. We observe that common compiler 218 | optimizations done before the WebAssembly code is produced, such as LLVM's 219 | global value numbering, effectively split address-taken variables into many 220 | small ranges that can often be allocated as local variables. Thus our 221 | expectation that any loss of optimization potential here is minimal. 222 | 223 | Conversely, non-address taken values which are usually on the stack are instead 224 | represented as locals inside functions. This effectively means that WebAssembly 225 | has an infinite set of registers, and can choose to spill values as it sees fit 226 | in a manner unobservable to the hosted code. This implies that there's a 227 | separate stack, unaddressable from hosted code, which is also used to spill 228 | return values. This allows strong security properties to be enforced, but does 229 | mean that two stacks are maintained (one by the VM, the other by the compiler 230 | which targets WebAssembly) which can lead to some inefficiencies. 231 | 232 | Local variables are not in Static Single Assignment (SSA) form, meaning that 233 | multiple incoming SSA values which have separate liveness can "share" the 234 | storage represented by a local through the `set_local` operator. From an SSA 235 | perspective, this means that multiple independent values can share a local 236 | variable in WebAssembly, which is effectively a kind of pre-coloring that clever 237 | producers can use to pre-color variables and give hints to a WebAssembly VM's 238 | register allocation algorithms, offloading some of the optimization work from 239 | the WebAssembly VM. 240 | 241 | 242 | ## Variable-Length Argument Lists ("varargs") 243 | 244 | C and C++ compilers are expected to implement variable-length argument lists by 245 | storing arguments in a buffer in linear memory and passing a pointer to the 246 | buffer. This greatly simplifies WebAssembly VM implementations by punting this 247 | ABI consideration to the front-end compiler. It does negatively impact 248 | performance, but variable-length calls are already somewhat slow. 249 | 250 | 251 | ## Multiple Return Values 252 | 253 | WebAssembly's MVP does not support multiple return values from functions because 254 | they aren't strictly necessary for the earliest anticipated use cases (and it's 255 | a *minimum* viable product), and they would introduce some complexity for some 256 | implementations. However, multiple return values are a very useful feature, and 257 | are relevant to ABIs, so it's likely to be added soon after the MVP. 258 | 259 | 260 | ## Indirect Calls 261 | 262 | The table-based scheme for indirect function calls was motivated by the need 263 | to represent function pointers as integer values that can be stored into the 264 | linear memory, as well as to enforce basic safety properties such as 265 | calling a function with the wrong signature does not destroy the safety 266 | guarantees of WebAssembly. In particular, an exact signature match implies 267 | an internal machine-level ABI match, which some engines require to ensure safety. 268 | An indirection also avoids a possible information leak through raw code addresses. 269 | 270 | Languages like C and C++ that compile to WebAssembly also imposed 271 | requirements, such as the uniqueness of function pointers and the ability 272 | to compare function pointers to data pointers, or treat data as function 273 | pointers. 274 | 275 | Several alternatives to direct indices with a heterogeneous indirect function table 276 | were considered, from alternatives with multiple tables to statically typed function 277 | pointers that can be mapped back and forth to integers. With the added complication 278 | of dynamic linking and dynamic code generation, none of these alternatives perfectly 279 | fit the requirements. 280 | 281 | The current design requires two dynamic checks when invoking a function pointer: 282 | a bounds check against the size of the indirect function table and a signature check 283 | for the function at that index against an expected signature. Some dynamic optimization 284 | techniques (e.g. inline caches, or a one-element cache), can reduce the number of 285 | checks in common cases. Other techniques such as trading a bounds check for a mask or 286 | segregating the table per signature to require only a bounds check could be considered 287 | in the future. Also, if tables are small enough, an engine can internally use per-signature 288 | tables filled with failure handlers to avoid one check. 289 | 290 | ## Control Flow Instructions with Values 291 | 292 | Control flow instructions such as `br`, `br_if`, `br_table`, `if` and `if-else` can 293 | transfer stack values in WebAssembly. These primitives are useful building blocks for 294 | WebAssembly producers, e.g. in compiling expression languages. It offers significant 295 | size reduction by avoiding the need for `set_local`/`get_local` pairs in the common case 296 | of an expression with only one immediate use. Control flow instructions can then model 297 | expressions with result values, thus allowing even more opportunities to further reduce 298 | `set_local`/`get_local` usage (which constitute 30-40% of total bytes in the 299 | [polyfill prototype](https://github.com/WebAssembly/polyfill-prototype-1)). 300 | `br`-with-value and `if` constructs that return values can also model `phis` which 301 | appear in SSA representations of programs. 302 | 303 | 304 | ## Limited Local Nondeterminism 305 | 306 | There are a few obvious cases where nondeterminism is essential to the API, such 307 | as random number generators, date/time functions or input events. The 308 | WebAssembly specification is strict when it comes to other sources of 309 | [limited local nondeterminism](Nondeterminism.md) of operators: it specifies 310 | all possible corner cases, and specifies a single outcome when this can be done 311 | reasonably. 312 | 313 | Ideally, WebAssembly would be fully deterministic because a fully deterministic 314 | platform is easier to: 315 | 316 | * Reason about. 317 | * Implement. 318 | * Test portably. 319 | 320 | Nondeterminism is only specified as a compromise when there is no other 321 | practical way to: 322 | 323 | * Achieve [portable](Portability.md) native performance. 324 | * Lower resource usage. 325 | * Reduce implementation complexity (both of WebAssembly VMs as well as compilers 326 | generating WebAssembly binaries). 327 | * Allow usage of new hardware features. 328 | * Allows implementations to [security-harden](Security.md) certain usecases. 329 | 330 | When nondeterminism is allowed into WebAssembly it is always done in a limited 331 | and local manner. This prevents the entire program from being invalid, as would 332 | be the case with C++ undefined behavior. 333 | 334 | As WebAssembly gets implemented and tested with multiple languages on multiple 335 | architectures we may revisit some of the design decisions: 336 | 337 | * When all relevant hardware implements an operation the same way, there's no 338 | need for nondeterminism in WebAssembly semantics. One such 339 | example is floating-point: at a high-level most operators follow 340 | IEEE-754 semantics, it is therefore not necessary to specify WebAssembly's 341 | floating-point operators differently from IEEE-754. 342 | * When different languages have different expectations then it's unfortunate if 343 | WebAssembly measurably penalizes one's performance by enforcing determinism 344 | which that language doesn't care about, but which another language may want. 345 | 346 | 347 | ## NaN bit-pattern nondeterminism. 348 | 349 | NaNs produced by floating-point instructions in WebAssembly have 350 | nondeterministic bit patterns in most circumstances. The bit pattern of a NaN 351 | is not usually significant, however there are a few ways that it can be 352 | observed: 353 | - a `reinterpret` conversion to an integer type 354 | - a `store` to linear memory followed by a load with a different type or index 355 | - a NaN stored to an imported or exported global variable or linear memory may 356 | be observed by the outside environment 357 | - a NaN passed to a `call` or `call_indirect` to an imported function may 358 | be observed by the outside environment 359 | - a return value of an exported function may be observed by the outside 360 | environment 361 | - `copysign` can be used to copy the sign bit onto a non-NaN value, where 362 | it then be observed 363 | 364 | The motivation for nondeterminism in NaN bit patterns is that popular platforms 365 | have differing behavior. IEEE 754-2019 makes some recommendations, but has few 366 | hard requirements in this area, and in practice there is significant divergence, 367 | for example: 368 | - When an instruction with no NaN inputs produces a NaN output, x86 produces 369 | a NaN with the sign bit set, while ARM and others produce a NaN with it 370 | unset. 371 | - When an instruction has multiple NaN inputs, x86 always returns the first 372 | NaN (converted to a quiet NaN if needed), while ARMv8 returns the first 373 | signaling NaN (converted to a quiet NaN) if one is present, and otherwise 374 | returns the first quiet NaN. 375 | - Some hardware architectures have found that returning one of the input NaNs 376 | has a cost, and prefer to return a NaN with a fixed bit pattern instead. 377 | - LLVM (used in some WebAssembly implementations) doesn't guarantee that it 378 | won't commute `fadd`, `fmul` and other instructions, so it's not possible 379 | to rely on the "first" NaN being preserved as such. 380 | - IEEE 754-2019 itself recommends architectures use NaN bits to provide 381 | architecture-specific debugging facilities. 382 | 383 | IEEE 754-2019 6.2 says that instructions returning a NaN *should* return one of 384 | their input NaNs. In WebAssembly, implementations may do this, however they are 385 | not required to. Since IEEE 754-2019 states this as a "should" (as opposed to a 386 | "shall"), it isn't a requirement for IEEE 754-2019 conformance. 387 | 388 | An alternative design would be to require engines to always "canonicalize" 389 | NaNs whenever their bits could be observed. This would eliminate the 390 | nondeterminism and provide slightly better portability, since it would hide 391 | hardware-specific NaN propagation behavior. However, it is theorized that this 392 | would add an unacceptable amount of overhead, and that the benefit is marginal 393 | since most programs are unaffected by this issue. 394 | 395 | 396 | ## Support for NaN-boxing. 397 | 398 | In general, WebAssembly's floating point instructions provide the guarantee that 399 | if all NaNs passed to an instruction are "canonical", the result is "canonical", 400 | where canonical means the most significant bit of the fraction field is 1, and 401 | the trailing bits are all 0. 402 | 403 | This is intended to support interpreters running on WebAssembly that use 404 | NaN-boxing, because they don't have to canonicalize the output of an arithmetic 405 | instruction if they know the inputs are canonical. 406 | 407 | When one or more of the inputs of an instruction are non-canonical NaNs, the 408 | resulting NaN bit pattern is nondeterministic. This is intended to accommodate 409 | the diversity in NaN behavior among popular hardware architectures. 410 | 411 | Note that the sign bit is still nondeterministic in a canonical NaN. This is 412 | also to accommodate popular hardware architectures; for example, x86 generates 413 | NaNs with the sign bit set to 1 while other architectures generate NaNs with it 414 | set to 0. And as above, the cost of canonicalizing NaNs is believed to be 415 | greater than the benefit. 416 | 417 | NaNs generated by JS or other entities in the external environment are not 418 | required to be canonical, so exported function arguments, imported function 419 | return values, and values stored in exported variables or memory may be 420 | non-canonical. 421 | 422 | 423 | ## Integer operations 424 | 425 | WebAssembly's signed integer divide rounds its result toward zero. This is not 426 | because of a lack of sympathy for 427 | [better alternatives](https://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html), 428 | but out of practicality. Because all popular hardware today implements 429 | rounding toward zero, and because C and many other languages now specify 430 | rounding to zero, having WebAssembly in the middle doing something different 431 | would mean divisions would have to be doubly complicated. 432 | 433 | Similarly, WebAssembly's shift operators mask their shift counts to the number 434 | of bits in the shifted value. Confusingly, this means that shifting a 32-bit 435 | value by 32 bits is an identity operation, and that a left shift is not 436 | equivalent to a multiplication by a power of 2 because the overflow behavior 437 | is different. Nevertheless, because several popular hardware architectures 438 | today implement this masking behavior, and those that don't can typically 439 | emulate it with a single extra mask instruction, and because several popular 440 | source languages, including JavaScript and C#, have come to specify this 441 | behavior too, we reluctantly adopt this behavior as well. 442 | 443 | WebAssembly has three classes of integer operations: signed, unsigned, and 444 | sign-agnostic. The signed and unsigned instructions have the property that 445 | whenever they can't return their mathematically expected value (such as when 446 | an overflow occurs, or when their operand is outside their domain), they 447 | trap, in order to avoid silently returning an incorrect value. 448 | 449 | Note that the `add`, `sub`, and `mul` operators are categorized as 450 | sign-agnostic. Because of the magic of two's complement representation, they 451 | may be used for both signed and unsigned purposes. Note that this (very 452 | conveniently!) means that engines don't need to add extra overflow-checking 453 | code for these most common of arithmetic operators on the most popular 454 | hardware platforms. 455 | 456 | 457 | ## Motivating Scenarios for Feature Testing 458 | 459 | 1. [Post-MVP :unicorn:][future general], 460 | [`i32.bitrev` :unicorn:][future bitrev] is introduced. A 461 | WebAssembly developer updates their toolkit so that the compiler may leverage 462 | `i32.bitrev`. The developer's WebAssembly module works correctly both on 463 | execution environments at MVP, as well as those supporting `i32.bitrev`. 464 | 465 | * A variant of this, where a few more new opcodes are available, the compiler 466 | is updated to be able to leverage all of them, but not all execution targets 467 | support all of them. The developer wants to reach as many of their customers as 468 | possible, while at the same time providing them with the best experience 469 | possible. The developer has to balance the cost of the test matrix resulting 470 | from the combinations of possible feature configurations. 471 | 472 | 2. [Post-MVP :unicorn:][future general], module authors may now use 473 | [Threading][future threads] 474 | APIs in the browser. A developer wants to leverage multithreading in their 475 | module. 476 | 477 | * In one variant of the scenario, our developer does not want to pay the 478 | engineering cost of developing and supporting a threaded and non-threaded 479 | version of their code. They opt not to support MVP targets, and only support 480 | post-MVP targets. End-users (browser users) get some message indicating they 481 | need MVP support. 482 | 483 | * In another variant, our developer explicitly authors both MVP-only and post- 484 | MVP (with threads) code. 485 | 486 | 3. [SIMD][future simd] support is not universally 487 | equivalent on all targets. While polyfill variants of SIMD APIs are available, 488 | a developer prefers writing dedicated SIMD and non-SIMD versions of their 489 | compression algorithm, because the non-SIMD version performs better in 490 | environments without SIMD support, when compared to the SIMD polyfill. They 491 | package their compression code for reuse by third parties. 492 | 493 | 4. An application author is assembling together an application by reusing 494 | modules such as those developed in the scenarios above. The application author's 495 | development environment is able to quickly and correctly identify the platform 496 | dependencies (e.g. threading, SIMD) and communicate back to the application 497 | author the implications these dependencies have on the end-application. Some 498 | APIs exposed from the threading-aware module are only pertinent to environments 499 | supporting threading. As a consequence, the application author needs to write 500 | specialized code when threads are/are not supported. (Note: we should understand 501 | this scenario for both forms of WebAssembly reuse currently imagined: dynamic 502 | linking and static imports.) 503 | 504 | 5. The compression algorithm described in scenario 3 is deployed on a 505 | restrictive execution environment, as part of an application. In this 506 | environment, a process may not change memory page access protection flags (e.g. 507 | certain gaming consoles, to investigate server side deployment scenarios). The 508 | compression module is compiled by the WebAssembly environment, enabling the 509 | configuration most specific to the target (i.e. with/without Threads, SIMD, 510 | etc). 511 | 512 | * A variant of this scenario where the environment is additionally separating 513 | storage into system-visible and application-visible, the latter not being able 514 | to contain machine-executable code (certain phones, to investigate if gaming 515 | consoles or server side have a similar sandboxing mechanism). 516 | 517 | 518 | ## Why a binary encoding? 519 | 520 | Given that text is so compressible and it is well known that it is hard to beat 521 | gzipped source, is there any win from having a binary format over a text format? 522 | Yes: 523 | 524 | * Large reductions in payload size can still significantly decrease the 525 | compressed file size. 526 | * Experimental results from a 527 | [polyfill prototype](https://github.com/WebAssembly/polyfill-prototype-1) show the 528 | gzipped binary format to be about 20-30% smaller than the corresponding 529 | gzipped asm.js. 530 | * A binary format that represents the names of variables and functions with raw 531 | indices instead of strings is much faster to decode: array indexing 532 | vs. dictionary lookup. 533 | * Experimental results from a 534 | [polyfill prototype](https://github.com/WebAssembly/polyfill-prototype-1) show that 535 | decoding the binary format is about 23× faster than parsing the 536 | corresponding asm.js source (using 537 | [this demo](https://github.com/lukewagner/AngryBotsPacked), comparing 538 | *just* parsing in SpiderMonkey (no validation, IR generation) to *just* 539 | decoding in the polyfill (no asm.js code generation). 540 | * A binary format allows many optimizations for code size and decoding speed that would 541 | not be possible on a source form. 542 | 543 | 544 | ## Why a layered binary encoding? 545 | * We can do better than generic compression because we are aware of the code 546 | structure and other details: 547 | * For example, macro compression that 548 | [deduplicates AST trees](https://github.com/WebAssembly/design/issues/58#issuecomment-101863032) 549 | can focus on ASTs + their children, thus having `O(nodes)` entities 550 | to worry about, compared to generic compression which in principle would 551 | need to look at `O(bytes*bytes)` entities. Such macros would allow the 552 | logical equivalent of `#define ADD1(x) (x+1)`, i.e., to be 553 | parameterized. Simpler macros (`#define ADDX1 (x+1)`) can implement useful 554 | features like constant pools. 555 | * Another example is reordering of functions and some internal nodes, which 556 | we know does not change semantics, but 557 | [can improve general compression](https://www.rfk.id.au/blog/entry/cromulate-improve-compressibility/). 558 | * JITs and simple developer tooling do not benefit from compression, so layering allows 559 | the related development and maintenance burden to be offloaded to reusable tools/libraries. 560 | * Each of the layers works to find compression opportunities to the best of 561 | its abilities, without encroaching upon the subsequent layer's compression 562 | opportunities. 563 | * [Existing web standards](https://www.w3.org/TR/PNG/) demonstrate many of 564 | the advantages of a layered encoding strategy. 565 | 566 | 567 | ## Why "polymorphic" stack typing after control transfer? 568 | 569 | For a stack machine, the fundamental property that type checking must ensure is that for every _edge_ in a control flow graph (formed by the individual instructions), the assumptions about the stack match up. 570 | At the same time, type checking should be fast, so be expressible by a linear traversal. 571 | 572 | There is no control edge from an unconditional control transfer instruction (like `br`, `br_table`, `return`, or `unreachable`) to the textually following instruction -- the next instruction is unreachable. 573 | Consequently, no constraint has to be imposed between the two regarding the stack. 574 | In a linear type checking algorithm this can be expressed by allowing to assume any type of stack. 575 | In type system terms, the instruction can thus be said to be _polymorphic_ in its stack type. 576 | 577 | This solution is canonical in the sense that it induces the minimal type constraints necessary to ensure soundness, while also maintaining the following useful structural properties about valid (i.e., well-typed) code: 578 | 579 | * It is composable: if instruction sequences A and B are valid, then block(A,B) is valid (e.g. at empty stack type). 580 | * It is decomposable: if block(A,B) is valid, then both A and B are valid. 581 | * It generalises an expression language: every expression is directly expressible, even if it contains control transfer. 582 | * It is agnostic to reachability: neither the specification nor producers need to define, check, or otherwise care about reachability (unless they choose to, e.g. to perform dead code elimination). 583 | * It maintains basic transformations: for example, (i32.const 1) (br_if $l) can always be replaced with (br $l). 584 | 585 | Some of these properties are relevant to support certain compilation techniques without artificial complication for producers. 586 | As a small but representative example, consider a textbook one-pass compiler, which would often use something like the following scheme for compiling expressions: 587 | ``` 588 | compile(A + B) = compile(A); compile(B); emit(i32.add) 589 | compile(A / B) = compile(A); compile(B); emit(dup i32.eqz (br_if $div_zero) drop i32.div) 590 | compile(A / 0) = compile(A); emit(br $div_zero) 591 | ``` 592 | The third case is a specialisation of the second, a simple optimisation. 593 | Without polymorphic typing of the `br` instruction, however, this simple scheme would not work, since `compile((x/0)+y)` would result in invalid code. Worse, it can lead to subtle compiler bugs. 594 | Similar situations arise in production compilers, for example, in the asm.js-to-wasm compilers that some of the WebAssembly VMs/tools are implementing. 595 | 596 | Other solutions that have been discussed would lose most of the above properties. For example: 597 | 598 | * Disallowing certain forms of unreachable code (whether by rules or by construction) would break all but decomposability. 599 | * Allowing but not type-checking unreachable code would break decomposability and requires the spec to provide a syntactic definition of reachability (which is unlikely to match the definition otherwise used by producers). 600 | * Requiring the stack to be empty after a jump remains agnostic to reachability and maintains decomposability, but still breaks all other properties. 601 | 602 | It is worth noting that this kind of type checking, in general, is not unusual. 603 | For example, the JVM also poses no constraint on the stack type after a jump (however, in its modern form, it recommends type annotations in the form of _stack maps_, which are then required after jumps to make the instantiation of the polymorphic typing rule explicit). 604 | Moreover, programming languages that allow control transfer _expressions_ usually type them polymorphically as well (e.g., `throw`/`raise`, which is an expression in some languages). 605 | 606 | 607 | [future general]: FutureFeatures.md 608 | [future flow control]: https://github.com/WebAssembly/design/issues/796 609 | [future bitrev]: https://github.com/WebAssembly/design/issues/1382 610 | [future threads]: https://github.com/WebAssembly/design/issues/1073 611 | [future simd]: https://github.com/WebAssembly/design/issues/1075 612 | [future garbage collection]: https://github.com/WebAssembly/proposals/issues/16 613 | -------------------------------------------------------------------------------- /Security.md: -------------------------------------------------------------------------------- 1 | # Security 2 | 3 | The security model of WebAssembly has two important goals: (1) protect *users* 4 | from buggy or malicious modules, and (2) provide *developers* with useful 5 | primitives and mitigations for developing safe applications, within the 6 | constraints of (1). 7 | 8 | ## Users 9 | 10 | Each WebAssembly module executes within a sandboxed environment separated from 11 | the host runtime using fault isolation techniques. This implies: 12 | 13 | * Applications execute independently, and can't escape the sandbox without 14 | going through appropriate APIs. 15 | * Applications generally execute deterministically 16 | [with limited exceptions](Nondeterminism.md). 17 | 18 | Additionally, each module is subject to the security policies of its embedding. 19 | Within a [web browser](Web.md), this includes restrictions on information flow 20 | through [same-origin policy][]. On a [non-web](NonWeb.md) platform, this could 21 | include the POSIX security model. 22 | 23 | ## Developers 24 | 25 | The design of WebAssembly promotes safe programs by eliminating dangerous 26 | features from its execution semantics, while maintaining compatibility with 27 | programs written for [C/C++](CAndC%2B%2B.md). 28 | 29 | Modules must declare all accessible functions and their associated types 30 | at load time, even when [dynamic linking](DynamicLinking.md) is used. This 31 | allows implicit enforcement of [control-flow integrity][] (CFI) through 32 | structured control-flow. Since compiled code is immutable and not observable at 33 | runtime, WebAssembly programs are protected from control flow hijacking attacks. 34 | 35 | * [Function calls](Semantics.md#calls) must specify the index of a target 36 | that corresponds to a valid entry in the 37 | [function index space](Modules.md#function-index-space) or 38 | [table index space](Modules.md#table-index-space). 39 | * [Indirect function calls](Rationale.md#indirect-calls) are subject to a type 40 | signature check at runtime; the type signature of the selected indirect 41 | function must match the type signature specified at the call site. 42 | * A protected call stack that is invulnerable to buffer overflows in the 43 | module heap ensures safe function returns. 44 | * [Branches](Semantics.md#branches-and-nesting) must point to valid 45 | destinations within the enclosing function. 46 | 47 | Variables in C/C++ can be lowered to two different primitives in WebAssembly, 48 | depending on their scope. [Local variables](Semantics.md#local-variables) 49 | with fixed scope and [global variables](Semantics.md#global-variables) are 50 | represented as fixed-type values stored by index. The former are initialized 51 | to zero by default and are stored in the protected call stack, whereas 52 | the latter are located in the [global index space](Modules.md#global-index-space) 53 | and can be imported from external modules. Local variables with 54 | [unclear static scope](Rationale.md#locals) (e.g. are used by the address-of 55 | operator, or are of type `struct` and returned by value) are stored in a separate 56 | user-addressable stack in [linear memory](Semantics.md#linear-memory) at 57 | compile time. This is an isolated memory region with fixed maximum size that is 58 | zero initialized by default. References to this memory are computed with 59 | infinite precision to avoid wrapping and simplify bounds checking. WebAssembly 60 | modules may also have [multiple linear memory sections], which are independent 61 | of each other. In the future, 62 | [finer-grained memory operations][future memory control] 63 | (e.g. shared memory, page protection, large pages, etc.) may be implemented. 64 | 65 | [Traps](Semantics.md#traps) are used to immediately terminate execution and 66 | signal abnormal behavior to the execution environment. In a browser, this is 67 | represented as a JavaScript exception. Support for 68 | module-defined trap handlers 69 | may be implemented in the future. Operations that can trap include: 70 | 71 | * specifying an invalid index in any index space, 72 | * performing an indirect function call with a mismatched signature, 73 | * exceeding the maximum size of the protected call stack, 74 | * accessing [out-of-bounds](#Rationale.md#out-of-bounds) addresses in linear 75 | memory, 76 | * executing an illegal arithmetic operations (e.g. division or remainder by 77 | zero, signed division overflow, etc). 78 | 79 | ### Memory Safety 80 | Compared to traditional C/C++ programs, these semantics obviate certain classes 81 | of memory safety bugs in WebAssembly. Buffer overflows, which occur when data 82 | exceeds the boundaries of an object and accesses adjacent memory regions, cannot 83 | affect local or global variables stored in index space, they are fixed-size and 84 | addressed by index. Data stored in linear memory can overwrite adjacent objects, 85 | since bounds checking is performed at linear memory region granularity and is 86 | not context-sensitive. However, the presence of control-flow integrity and 87 | protected call stacks prevents direct code injection attacks. Thus, 88 | common mitigations such as [data execution prevention][] (DEP) and 89 | [stack smashing protection][] (SSP) are not needed by WebAssembly programs. 90 | 91 | Another common class of memory safety errors involves unsafe pointer usage and 92 | [undefined behavior](CAndC%2B%2B.md#undefined-behavior). This includes 93 | dereferencing pointers to unallocated memory (e.g. `NULL`), or freed memory 94 | allocations. In WebAssembly, the semantics of pointers have been eliminated for 95 | function calls and variables with fixed static scope, allowing references to 96 | invalid indexes in any index space to trigger a validation error at load time, 97 | or at worst a trap at runtime. Accesses to linear memory are bounds-checked at 98 | the region level, potentially resulting in a trap at runtime. These memory 99 | region(s) are isolated from the internal memory of the runtime, and are set to 100 | zero by default unless otherwise initialized. 101 | 102 | Nevertheless, other classes of bugs are not obviated by the semantics of 103 | WebAssembly. Although attackers cannot perform direct code injection attacks, 104 | it is possible to hijack the control flow of a module using code reuse attacks 105 | against indirect calls. However, conventional [return-oriented programming][] 106 | (ROP) attacks using short sequences of instructions ("gadgets") are not possible 107 | in WebAssembly, because control-flow integrity ensures that call targets are 108 | valid functions declared at load time. Likewise, race conditions, such as 109 | [time of check to time of use][] (TOCTOU) vulnerabilities, are possible in 110 | WebAssembly, since no execution or scheduling guarantees are provided beyond 111 | in-order execution and [atomic memory primitives][threads]. 112 | Similarly, [side channel attacks][] can occur, such as timing attacks against 113 | modules. In the future, additional protections may be provided by runtimes or 114 | the toolchain, such as code diversification or memory randomization (similar to 115 | [address space layout randomization][] (ASLR)), or [bounded pointers][] ("fat" 116 | pointers). 117 | 118 | ### Control-Flow Integrity 119 | The effectiveness of control-flow integrity can be measured based on its 120 | completeness. Generally, there are three types of external control-flow 121 | transitions that need to be protected, because the callee may not be trusted: 122 | 1. Direct function calls, 123 | 2. Indirect function calls, 124 | 3. Returns. 125 | 126 | Together, (1) and (2) are commonly referred to as "forward-edge", since they 127 | correspond to forward edges in a directed control-flow graph. Likewise (3) is 128 | commonly referred to as "back-edge", since it corresponds to back edges in a 129 | directed control-flow graph. More specialized function calls, such as tail 130 | calls, can be viewed as a combination of (1) and (3). 131 | 132 | Typically, this is implemented using runtime instrumentation. During 133 | compilation, the compiler generates an expected control flow graph of program 134 | execution, and inserts runtime instrumentation at each call site to verify that 135 | the transition is safe. Sets of expected call targets are constructed from the 136 | set of all possible call targets in the program, unique identifiers are assigned 137 | to each set, and the instrumentation checks whether the current call target is 138 | a member of the expected call target set. If this check succeeds, then the 139 | original call is allowed to proceed, otherwise a failure handler is executed, 140 | which typically terminates the program. 141 | 142 | In WebAssembly, the execution semantics implicitly guarantee the safety of (1) 143 | through usage of explicit function section indexes, and (3) through a protected 144 | call stack. Additionally, the type signature of indirect function calls is 145 | already checked at runtime, effectively implementing coarse-grained type-based 146 | control-flow integrity for (2). All of this is achieved without explicit runtime 147 | instrumentation in the module. However, as discussed 148 | [previously](#memory-safety), this protection does not prevent code reuse 149 | attacks with function-level granularity against indirect calls. 150 | 151 | #### Clang/LLVM CFI 152 | The Clang/LLVM compiler infrastructure includes a [built-in implementation] of 153 | fine-grained control flow integrity, which has been extended to support the 154 | WebAssembly target. It is available in Clang/LLVM with the 155 | [WebAssembly backend]. 156 | 157 | Enabling fine-grained control-flow integrity (by passing `-fsanitize=cfi` to 158 | emscripten) has a number of advantages over the default WebAssembly 159 | configuration. Not only does this better defend against code reuse attacks that 160 | leverage indirect function calls (2), but it also enhances the built-in function 161 | signature checks by operating at the C/C++ type level, which is semantically 162 | richer that the WebAssembly [type level](Semantics.md#types), which consists 163 | of only four value types. Currently, enabling this feature has a small 164 | performance cost for each indirect call, because an integer range check is 165 | used to verify that the target index is trusted, but this may be eliminated in 166 | the future by leveraging built-in support for 167 | [multiple indirect tables] with homogeneous type 168 | in WebAssembly. 169 | 170 | [address space layout randomization]: https://en.wikipedia.org/wiki/Address_space_layout_randomization 171 | [bounded pointers]: https://en.wikipedia.org/wiki/Bounded_pointer 172 | [built-in implementation]: https://clang.llvm.org/docs/ControlFlowIntegrity.html 173 | [control-flow integrity]: https://research.microsoft.com/apps/pubs/default.aspx?id=64250 174 | [data execution prevention]: https://en.wikipedia.org/wiki/Executable_space_protection 175 | [forward-edge control-flow integrity]: https://www.usenix.org/node/184460 176 | [new WebAssembly backend]: https://github.com/WebAssembly/binaryen#cc-source--webassembly-llvm-backend--s2wasm--webassembly 177 | [return-oriented programming]: https://en.wikipedia.org/wiki/Return-oriented_programming 178 | [same-origin policy]: https://www.w3.org/Security/wiki/Same_Origin_Policy 179 | [side channel attacks]: https://en.wikipedia.org/wiki/Side-channel_attack 180 | [stack smashing protection]: https://en.wikipedia.org/wiki/Buffer_overflow_protection#Random_canaries 181 | [time of check to time of use]: https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use 182 | 183 | [multiple linear memory sections]: https://github.com/WebAssembly/multi-memory/blob/main/proposals/multi-memory/Overview.md 184 | [multiple indirect tables]: https://github.com/WebAssembly/reference-types/blob/master/proposals/reference-types/Overview.md 185 | [threads]: https://github.com/WebAssembly/threads/blob/main/proposals/threads/Overview.md 186 | [future memory control]: https://github.com/WebAssembly/memory-control 187 | -------------------------------------------------------------------------------- /Semantics.md: -------------------------------------------------------------------------------- 1 | # Semantics 2 | 3 | This file historically contained the description of WebAssembly's instruction set. 4 | 5 | For the current description, see the [normative documentation](http://webassembly.github.io/spec/core/exec/index.html). 6 | -------------------------------------------------------------------------------- /TextFormat.md: -------------------------------------------------------------------------------- 1 | # Text Format 2 | 3 | This file historically contained the description of WebAssembly's text format. 4 | 5 | For the current description, see the [normative documentation](http://webassembly.github.io/spec/core/text/index.html). 6 | -------------------------------------------------------------------------------- /Tooling.md: -------------------------------------------------------------------------------- 1 | # Tooling support 2 | 3 | Tooling for in-browser execution is often of uneven quality. WebAssembly aims at 4 | making it possible to support truly great tooling by exposing 5 | [low-level capabilities][] instead of prescribing which tooling should be 6 | built. This enables: 7 | 8 | * Porting of existing and familiar tooling to WebAssembly; 9 | * Building new tooling that's particularly well suited to WebAssembly. 10 | 11 | [low-level capabilities]: https://extensiblewebmanifesto.org 12 | 13 | WebAssembly development should be self-hosting, and not just as a cute hack but 14 | as enjoyable platform that developers actively seek out because the tools they 15 | want and need *just work*. Developers have high expectations, and meeting these 16 | expectations on tooling means WebAssembly has the features required to build 17 | rich applications for non-developers. 18 | 19 | The tooling we expect to support includes: 20 | 21 | * Editors: 22 | - Editors such as vim and emacs should *just work*. 23 | * Compilers and language virtual machines: 24 | - Compilers for languages which can target WebAssembly (C/C++, Rust, Go, C#) 25 | should be able to run in WebAssembly themselves, emit a WebAssembly module 26 | that can then be executed. 27 | - Virtual machines for languages such as bash, Python, Ruby should work. 28 | - Virtual machines which use a just-in-time compiler (JavaScript VMs, luajit, 29 | pypy) should be able to support a new just-in-time backend for WebAssembly. 30 | * Debuggers: 31 | - Basic browser integration can be done through source map support. 32 | - Full integration for languages like C++ require more standardization effort 33 | on debugging information format as well as permissions for interrupting 34 | programs, inspecting their state, modifying their state. 35 | - Debug information is better delivered on-demand instead of built-in to a 36 | WebAssembly module. 37 | * Sanitizers for [non-memory-safe](Security.md#memory-safety) languages: asan, 38 | tsan, msan, ubsan. Efficient support of sanitizers may require improving: 39 | - Trapping support; 40 | - Shadow stack techniques (often implemented through `mmap`'s `MAP_FIXED`). 41 | * Opt-in [security](Security.md) enhancements for developers' own code: 42 | developers targeting WebAssembly may want their own code to be sandboxed 43 | further than what WebAssembly implementations require to protect users. 44 | * Profilers: 45 | - Sample-based; 46 | - Instrumentation-based. 47 | * Process dump: local variables, call stack, heap, global variables, list of 48 | threads. 49 | * JavaScript+WebAssembly size optimization tool: huge WebAssembly+JavaScript 50 | mixed applications, WebAssembly calling to JavaScript libraries which 51 | communicate with the rest of the Web platform, need tooling to perform 52 | dead code stripping and global optimization across the API boundary. 53 | 54 | In many cases, the tooling will be pure WebAssembly without any tool-specific 55 | support from WebAssembly. This won't be possible for debugging, but should be 56 | entirely possible for sanitizers. 57 | -------------------------------------------------------------------------------- /UseCases.md: -------------------------------------------------------------------------------- 1 | # Use Cases 2 | 3 | WebAssembly's [high-level goals](HighLevelGoals.md) define *what* WebAssembly 4 | aims to achieve, and in *which order*. *How* WebAssembly achieves its goals is 5 | documented for [Web](Web.md) and [non-Web](NonWeb.md) platforms. The following 6 | is an unordered and incomplete list of applications/domains/computations that 7 | would benefit from WebAssembly and are being considered as use cases during the 8 | design of WebAssembly. 9 | 10 | ## Inside the browser 11 | 12 | * Better execution for languages and toolkits that are currently cross-compiled 13 | to the Web (C/C++, GWT, …). 14 | * Image / video editing. 15 | * Games: 16 | - Casual games that need to start quickly. 17 | - AAA games that have heavy assets. 18 | - Game portals (mixed-party/origin content). 19 | * Peer-to-peer applications (games, collaborative editing, decentralized and 20 | centralized). 21 | * Music applications (streaming, caching). 22 | * Image recognition. 23 | * Live video augmentation (e.g. putting hats on people's heads). 24 | * VR and augmented reality (very low latency). 25 | * CAD applications. 26 | * Scientific visualization and simulation. 27 | * Interactive educational software, and news articles. 28 | * Platform simulation / emulation (ARC, DOSBox, QEMU, MAME, …). 29 | * Language interpreters and virtual machines. 30 | * POSIX user-space environment, allowing porting of existing POSIX applications. 31 | * Developer tooling (editors, compilers, debuggers, …). 32 | * Remote desktop. 33 | * VPN. 34 | * Encryption. 35 | * Local web server. 36 | * Common NPAPI users, within the web's security model and APIs. 37 | * Fat client for enterprise applications (e.g. databases). 38 | 39 | ## Outside the browser 40 | 41 | * Game distribution service (portable and secure). 42 | * Server-side compute of untrusted code. 43 | * Server-side application. 44 | * Hybrid native apps on mobile devices. 45 | * Symmetric computations across multiple nodes 46 | 47 | ## How WebAssembly can be used 48 | 49 | * Entire code base in WebAssembly. 50 | * Main frame in WebAssembly, but the UI is in JavaScript / HTML. 51 | * Re-use existing code by targeting WebAssembly, embedded in a larger 52 | JavaScript / HTML application. This could be anything from simple helper 53 | libraries, to compute-oriented task offload. 54 | -------------------------------------------------------------------------------- /Web.md: -------------------------------------------------------------------------------- 1 | # Web Embedding 2 | 3 | Unsurprisingly, one of WebAssembly's primary purposes is to run on the Web, 4 | for example embedded in Web browsers (though this is 5 | [not its only purpose](NonWeb.md)). 6 | 7 | This means integrating with the Web ecosystem, leveraging Web APIs, supporting 8 | the Web's security model, preserving the Web's portability, and designing in 9 | room for evolutionary development. Many of these goals are clearly 10 | reflected in WebAssembly's [high-level goals](HighLevelGoals.md). In 11 | particular, WebAssembly MVP will be no looser from a security point of view 12 | than if the module was JavaScript. 13 | 14 | More concretely, the following is a list of points of contact between WebAssembly 15 | and the rest of the Web platform that have been considered: 16 | 17 | ## JavaScript API 18 | 19 | A [JavaScript API](JS.md) is provided which allows JavaScript to compile 20 | WebAssembly modules, perform limited reflection on compiled modules, store 21 | and retrieve compiled modules from offline storage, instantiate compiled modules 22 | with JavaScript imports, call the exported functions of instantiated modules, 23 | alias the exported memory of instantiated modules, etc. 24 | 25 | The Web embedding includes additional methods useful in that context. 26 | In non-web embeddings, these APIs may not be present. 27 | 28 | ### Additional Web Embedding API 29 | 30 | This section historically contained the description of WebAssembly's Web API. 31 | 32 | For the current description, see the [normative documentation](https://webassembly.github.io/spec/web-api/index.html). 33 | 34 | ## Modules 35 | 36 | WebAssembly's [modules](Modules.md) allow for natural [integration with 37 | the ES6 module system](https://github.com/WebAssembly/esm-integration). 38 | 39 | ## Security 40 | 41 | WebAssembly's [security](Security.md) model depend on the 42 | [same-origin policy], with [cross-origin resource sharing (CORS)] and 43 | [subresource integrity] to enable distribution through content 44 | distribution networks and to implement [dynamic linking](DynamicLinking.md). 45 | 46 | ## WebIDL 47 | 48 | There are various proposals in flight which may support future work toward 49 | WebIDL bindings for WebAssembly, including [JS String builtins], 50 | [source-phase imports], and the [component model]. 51 | 52 | There are also tools to provide this functionality today by generating 53 | JS wrapper code, for example [Emscripten's WebIDL Binder], 54 | [the wasm-webidl-bindings Rust crate], and 55 | [jco's experimental WebIDL Imports support]. 56 | 57 | [same-origin policy]: https://www.w3.org/Security/wiki/Same_Origin_Policy 58 | [cross-origin resource sharing (CORS)]: https://www.w3.org/TR/cors/ 59 | [subresource integrity]: https://www.w3.org/TR/SRI/ 60 | [JS String builtins]: https://github.com/WebAssembly/js-string-builtins/ 61 | [source-phase imports]: https://github.com/tc39/proposal-source-phase-imports 62 | [component model]: https://github.com/WebAssembly/component-model 63 | 64 | [Emscripten's WebIDL Binder]: https://emscripten.org/docs/porting/connecting_cpp_and_javascript/WebIDL-Binder.html 65 | [the wasm-webidl-bindings Rust crate]: https://github.com/rustwasm/wasm-webidl-bindings 66 | [jco's experimental WebIDL Imports support]: https://github.com/bytecodealliance/jco/blob/main/docs/src/transpiling.md#experimental-webidl-imports 67 | --------------------------------------------------------------------------------