[
  {
    "path": ".gitignore",
    "content": "*~\n*#\n.#*\n.*.swp\nout\n"
  },
  {
    "path": "BinaryEncoding.md",
    "content": "# Binary Encoding\n\nThis file historically contained the description of WebAssembly's binary encoding.\n\nFor the current description, see the [normative documentation](http://webassembly.github.io/spec/core/binary/index.html).\n"
  },
  {
    "path": "CAndC++.md",
    "content": "# Guide for C/C++ developers\n\nWebAssembly is being designed to support C and C++ code well, right from\nthe start in [the MVP](MVP.md). The following explains the outlook for\nC and C++ developers.\n\n## Porting C and C++ code to WebAssembly\n\n### Platform features\n\nWebAssembly has a pretty conventional ISA: 8-bit bytes, two's complement\nintegers, little-endian, and a lot of other normal properties. Reasonably\nportable C/C++ code should port to WebAssembly without difficultly.\n\nWebAssembly has 32-bit and 64-bit architecture variants, called wasm32 and\nwasm64. wasm32 has an ILP32 data model, meaning that `int`, `long`, and\npointer types are all 32-bit, while the `long long` type is 64-bit. wasm64\nhas an LP64 data model, meaning that `long` and pointer types will be\n64-bit, while `int` is 32-bit.\n\n[The MVP](MVP.md) will support only wasm32; support for wasm64 will be\nadded in the future to support\n[64-bit address spaces :unicorn:][future 64-bit].\n\n`float` and `double` are the IEEE 754-2019 single- and double-precision types,\nwhich are native in WebAssembly. `long double` is the IEEE 754-2019\nquad-precision type, which is a software-emulated type. WebAssembly does\nnot have a builtin quad-precision type or associated operators. The long\ndouble type here is software-emulated in library code linked into WebAssembly\napplications that need it.\n\nFor performance and compatibility with other platforms, `float` and\n`double` are recommended for most uses.\n\n### Language Support\n\nC and C++ language conformance is largely determined by individual compiler\nsupport, but WebAssembly includes all the functionality that popular C and C++\ncompilers need to support high-quality implementations.\n\nWhile [the MVP](MVP.md) will be fully functional, additional features enabling\ngreater performance will be added soon after, including:\n\n * Support for [multi-threaded execution with shared memory][future threads].\n\n * [Zero-cost C++ exception handling][future exceptions].\n   C++ exceptions can be implemented without this, but this feature will\n   enable them to have lower runtime overhead.\n\n * Support for [128-bit SIMD][future simd]. SIMD will be\n   exposed to C/C++ though explicit APIs such as [LLVM's vector extensions]\n   and [GCC's vector extensions], auto-vectorization, and emulated APIs from\n   other platforms such as `<xmmintrin.h>`.\n\n  [LLVM's vector extensions]: https://clang.llvm.org/docs/LanguageExtensions.html#vectors-and-extended-vectors\n  [GCC's vector extensions]: https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html\n\n### APIs\n\nWebAssembly applications can use high-level C/C++ APIs such as the C\nand C++ standard libraries, OpenGL, SDL, pthreads, and others, just as\nin normal C/C++ development. Under the covers, these libraries\nimplement their functionality by using low-level facilities provided by\nWebAssembly implementations. On [the Web](Web.md), they utilize\nWeb APIs (for example, OpenGL is executed on WebGL, libc date and\ntime methods use the browser's Date functionality, etc.).\n[In other contexts](NonWeb.md), other low-level mechanisms may be used.\n\n### ABIs\n\nIn [the MVP](MVP.md), WebAssembly does not yet have a stable ABI for\nlibraries. Developers will need to ensure that all code linked into an\napplication are compiled with the same compiler and options.\n\nIn the future, when WebAssembly is extended to support\n[dynamic linking](DynamicLinking.md), stable ABIs are\nexpected to be defined in accompaniment.\n\n### Undefined and Implementation-defined Behavior\n\n#### Undefined Behavior\n\nWebAssembly doesn't change the C or C++ languages. Things which cause\nundefined behavior in C or C++ are still bugs when compiling for WebAssembly\n[even when the corresponding behavior in WebAssembly itself is defined](Nondeterminism.md#note-for-users-of-c-c-and-similar-languages).\nC and C++ optimizers still assume that undefined behavior won't occur,\nso such bugs can still lead to surprising behavior.\n\nFor example, while unaligned memory access is\n[fully defined](Semantics.md#alignment) in WebAssembly, C and C++ compilers\nmake no guarantee that a (non-packed) unaligned memory access at the source\nlevel is harmlessly translated into an unaligned memory access in WebAssembly.\nAnd in practice, popular C and C++ compilers do optimize on the assumption that\nalignment rules are followed, meaning that they don't always preserve program\nbehavior otherwise.\n\nOn WebAssembly, the primary [nondeterminism](Nondeterminism.md) and\n[security](Security.md) invariants are always maintained. Demons can't actually\nfly out your nose, as that would constitute an escape from the sandbox. And,\ncallstacks can't become corrupted.\n\nOther than that, programs which invoke undefined behavior at the source language\nlevel may be compiled into WebAssembly programs which do anything else,\nincluding corrupting the contents of the application's linear memory, calling APIs with\narbitrary parameters, hanging, trapping, or consuming arbitrary amounts of\nresources (within the limits).\n\n[Tools are being developed and ported](Tooling.md) to help developers find\nand fix such bugs in their code.\n\n#### Implementation-Defined Behavior\n\nMost implementation-defined behavior in C and C++ is dependent on the compiler\nrather than on the underlying platform. For those details that are dependent\non the platform, on WebAssembly they follow naturally from having 8-bit bytes,\n32-bit and 64-bit two's complement integers, and\n[32-bit and 64-bit IEEE-754-2019-style floating point support](https://webassembly.github.io/spec/core/exec/numerics.html#floating-point).\n\n## Portability of compiled code\n\nWebAssembly can be efficiently implemented on a wide variety of platforms,\nprovided they can satisfy certain\n[basic expectations](Portability.md#assumptions-for-efficient-execution).\n\nWebAssembly has very limited [nondeterminism](Nondeterminism.md), so it is\nexpected that compiled WebAssembly programs will behave very consistently\nacross different implementations, and across different versions of the same\nimplementation.\n\n[future 64-bit]: https://github.com/WebAssembly/memory64\n[future threads]: https://github.com/WebAssembly/design/issues/1073\n[future simd]: https://github.com/WebAssembly/design/issues/1075\n[future exceptions]: https://github.com/WebAssembly/design/issues/1078\n\n"
  },
  {
    "path": "CodeOfConduct.md",
    "content": "The code of conduct has moved to https://github.com/WebAssembly/meetings/blob/main/CODE_OF_CONDUCT.md.\n"
  },
  {
    "path": "Contributing.md",
    "content": "# Contributing to WebAssembly\n\nInterested in contributing to WebAssembly? We suggest you start by:\n\n* Acquainting yourself with the\n   [Code of Ethics and Professional Conduct](CodeOfConduct.md).\n\n* Joining the\n[W3C Community Group]. Please do this before starting new proposals,\nattending meetings, or making significant contributions. It provides the legal\nframework that protects participants and supports standardization. And make\nsure you're registered as affiliated with your company or organization in the\nCommunity Group, if any.\n\n* Then, you may wish to:\n  - [ask questions],\n  - discuss existing [phase-0 proposals] and [phase-1+ proposals],\n  - attend [meetings],\n  - discuss [tooling conventions],\n  - or make [new proposals]!\n \nIf your issue or PR has not received comments, you can ping the relevant spec\neditor or [champion]. It is polite to ping no more than once a week.\n\nHappy assembly!\n\n[W3C Community Group]: https://www.w3.org/community/webassembly/\n[Code of Ethics and Professional Conduct]: https://github.com/WebAssembly/meetings/blob/main/CODE_OF_CONDUCT.md\n[meetings]: https://github.com/WebAssembly/meetings\n[phase-1+ proposals]: https://github.com/WebAssembly/proposals\n[phase-0 proposals]: https://github.com/WebAssembly/design/issues\n[ask questions]: https://github.com/WebAssembly/design/discussions\n[new proposals]: https://github.com/WebAssembly/meetings/blob/main/process/proposal.md\n[tooling conventions]: https://github.com/WebAssembly/tool-conventions\n[champion]: https://github.com/WebAssembly/proposals\n"
  },
  {
    "path": "DynamicLinking.md",
    "content": "# Dynamic linking\n\nWebAssembly enables load-time and run-time (`dlopen`) dynamic linking in the\nMVP by having multiple [instantiated modules](Modules.md)\nshare functions, [linear memories](Semantics.md#linear-memory),\n[tables](Semantics.md#table) and [constants](Semantics.md#constants)\nusing module [imports](Modules.md#imports) and [exports](Modules.md#exports). In\nparticular, since all (non-local) state that a module can access can be imported\nand exported and thus shared between separate modules' instances, toolchains\nhave the building blocks to implement dynamic loaders.\n\nSince the manner in which modules are loaded and instantiated is defined by the\nhost environment (e.g., the [JavaScript API](JS.md)), dynamic linking requires\nuse of host-specific functionality to link two modules. At a minimum, the host\nenvironment must provide a way to dynamically instantiate modules while\nconnecting exports to imports.\n\nThe simplest load-time dynamic linking scheme between modules A and B can be \nachieved by having module A export functions, tables and memories that are\nimported by B. A C++ toolchain can expose this functionality by using the\nsame function attributes currently used to export/import symbols from\nnative DSOs/DLLs:\n\n```\n#ifdef _WIN32\n#  define EXPORT __declspec(dllexport)\n#  define IMPORT __declspec(dllimport)\n#else\n#  define EXPORT __attribute__ ((visibility (\"default\")))\n#  define IMPORT __attribute__ ((visibility (\"default\")))\n#endif\n\ntypedef void (**PF)();\n\nIMPORT PF imp();\nEXPORT void exp() { (*imp())(); }\n```\n\nThis code would, at a minimum, generate a WebAssembly module with imports for:\n\n* the function `imp`\n* the heap used to perfom the load, when dereferencing the return value of `imp`\n* the table used to perform the pointer-to-function call\n\nand exports for:\n\n* the function `exp`\n\nA more realistic module using libc would have more imports including:\n\n* an immutable `i32` global import for the offset in linear memory to place\n  global [data segments](Modules.md#data-section) and later use as a constant\n  base address when loading and storing from globals\n* an immutable `i32` global import for the offset into the indirect function\n  table at which to place the modules' indirectly called functions and later\n  compute their indices for address-of\n\nOne extra detail is what to use as the [module name](Modules.md#imports) for\nimports (since WebAssembly has a two-level namespace). One option is to have a\nsingle default module name for all C/C++ imports/exports (which then allows the\ntoolchain to put implementation-internal names in a separate namespace, avoiding\nthe need for `__`-prefix conventions).\n\nTo implement run-time dynamic linking (e.g., `dlopen` and `dlsym`):\n\n* `dlopen` would compile and instantiate a new module, storing the compiled\n  instance in a host-environment table, returning the index to the caller.\n* `dlsym` would be given this index, pull the instance out of the table,\n  search the instances's exports, append the found function to the function\n  table (using host-defined functionality in the MVP, but directly from\n  WebAssembly code in the\n  [future :unicorn:][future types]) and return the\n  table index of the appended element to the caller.\n\nNote that the representation of a C function-pointer in WebAssembly is an index\ninto a function table, so the above scheme lines up perfectly with the\nfunction-pointer return value of `dlsym`.\n\nMore complicated dynamic linking functionality (e.g., interposition, weak\nsymbols, etc) can be simulated efficiently by assigning a function table\nindex to each weak/mutable symbol, calling the symbol via `call_indirect` on that\nindex, and mutating the underlying element as needed.\n\nAfter the MVP, we would like to standardize a single [ABI][] per source\nlanguage, allowing for WebAssembly libraries to interface with each other\nregardless of compiler. Specifying an ABI requires that all ABI-related \nfuture features (like SIMD, multiple return values and exception handling)\nhave been implemented. While it is highly recommended for compilers targeting\nWebAssembly to adhere to the specified ABI for interoperability, WebAssembly\nruntimes will be ABI agnostic, so it will be possible to use a non-standard ABI\nfor specialized purposes.\n\n  [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface\n\n[future types]: https://github.com/WebAssembly/reference-types/blob/master/proposals/reference-types/Overview.md#language-extensions\n"
  },
  {
    "path": "Events.md",
    "content": "## Past Events\n\n| Date | Title | Slides | Video | Presenter(s) |\n|-----:|-------|:------:|:-----:|--------------|\n| 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 |\n| November  10th 2015 | BlinkOn 5: WebAssembly     | | [video](https://youtu.be/iCSAUHpPbiU) | Nick Bray |\n| December   9th 2015 | Emscripten and WebAssembly | [slides](https://kripken.github.io/talks/wasm.html) | | Alon Zakai |\n| January   31st 2016 | FOSDEM LLVM room           | [slides](https://fosdem.org/2016/schedule/event/llvm_webassembly) | | JF Bastien and Dan Gohman |\n| June      13th 2016 | NYLUG Presents: WebAssembly: A New Compiler Target For The Web | | [video](https://www.youtube.com/watch?v=RByPdCN1RQ4) | Luke Wagner |\n| 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 |\n| September 14th 2016 | WebAssembly: birth of a virtual ISA | | [video](https://www.youtube.com/watch?v=vmzz17JGPHI) | Ben Smith |\n| September 21st 2016 | C++ on the Web: Let's have some serious fun | | [video](https://www.youtube.com/watch?v=jXMtQ2fTl4c) | Dan Gohman |\n| September 22nd 2016 | WebAssembly: high speed at low cost for everyone | [paper](http://www.mlworkshop.org/2016-1.pdf) | | Andreas Rossberg |\n| October   31st 2016 | VMIL16: WebAssembly from wire to machine code: a view inside V8's implementation | | | Ben L. Titzer |\n| November   7th 2016 | Empire Node: How Webassembly Will Change the Way You Write Javascript | | [video](https://www.youtube.com/watch?v=kq2HBddiyh0) | Seth Samuel |\n| November  12th 2016 | Chrome Dev Summit Advanced JS performance with V8 and WebAssembly | | [video](https://www.youtube.com/watch?v=PvZdTZ1Nl5o) | Seth Thompson |\n| 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\n| 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\n| October      5th 2017 | Node.js Interactive: What's a Wasm? | | [video](https://www.youtube.com/watch?v=gk9ERa7UYPM) | Paul Milham\n\n\n## Upcoming\n\n| Date | Title | Slides | Video | Presenter(s) |\n|-----:|-------|:------:|:-----:|--------------|\n"
  },
  {
    "path": "FAQ.md",
    "content": "# FAQ\n\n## Why create a new standard when there is already asm.js?\n\n... especially since pthreads ([Mozilla pthreads][], [Chromium pthreads][]) and\nSIMD ([simd.js][], [Chromium SIMD][], [simd.js in asm.js][]) are coming to\nJavaScript.\n\n  [Mozilla pthreads]: https://blog.mozilla.org/javascript/2015/02/26/the-path-to-parallel-javascript/\n  [Chromium pthreads]: https://groups.google.com/a/chromium.org/forum/#!topic/blink-dev/d-0ibJwCS24\n  [simd.js]: https://hacks.mozilla.org/2014/10/introducing-simd-js/\n  [Chromium SIMD]: https://groups.google.com/a/chromium.org/forum/#!topic/blink-dev/2PIOEJG_aYY\n  [simd.js in asm.js]: http://discourse.specifiction.org/t/request-for-comments-simd-js-in-asm-js/676\n\nThere are two main benefits WebAssembly provides:\n\n1. The kind of binary format being considered for WebAssembly can be natively\n   decoded much faster than JavaScript can be parsed ([experiments][] show more\n   than 20× faster).  On mobile, large compiled codes can easily take 20–40\n   seconds *just to parse*, so native decoding (especially when combined with\n   other techniques like [streaming][] for better-than-gzip compression) is\n   critical to providing a good cold-load user experience.\n\n2. By avoiding the simultaneous asm.js constraints of [AOT][]-[compilability][]\n   and good performance even on engines without\n   [specific asm.js optimizations][], a new standard makes it *much easier* to\n   add the [features :unicorn:][future general] required to reach native\n   levels of performance.\n\n  [experiments]: BinaryEncoding.md#why-a-binary-encoding-instead-of-a-text-only-representation\n  [streaming]: https://www.w3.org/TR/streams-api/\n  [AOT]: http://asmjs.org/spec/latest/#ahead-of-time-compilation\n  [compilability]: https://blog.mozilla.org/luke/2014/01/14/asm-js-aot-compilation-and-startup-performance/\n  [specific asm.js optimizations]: https://blog.mozilla.org/luke/2015/02/18/microsoft-announces-asm-js-optimizations/#asmjs-opts\n\nOf course, every new standard introduces new costs (maintenance, attack surface,\ncode size) that must be offset by the benefits. WebAssembly minimizes costs by\nhaving a design that allows (though not requires) a browser to implement\nWebAssembly inside its *existing* JavaScript engine (thereby reusing the\nJavaScript engine's existing compiler backend, ES6 module loading frontend,\nsecurity sandboxing mechanisms and other supporting VM components). Thus, in\ncost, WebAssembly should be comparable to a big new JavaScript feature, not a\nfundamental extension to the browser model.\n\nComparing the two, even for engines which already optimize asm.js, the benefits\noutweigh the costs.\n\n\n## What are WebAssembly's use cases?\n\nWebAssembly was designed with [a variety of use cases in mind](UseCases.md).\n\n\n## Can WebAssembly be polyfilled?\n\nWe think so. There was an early\n[prototype](https://github.com/WebAssembly/polyfill-prototype-1) with demos \n[[1](https://lukewagner.github.io/AngryBotsPacked), \n[2](https://lukewagner.github.io/PlatformerGamePacked)], which showed\nthat decoding a binary WebAssembly-like format into asm.js can be efficient.\nAnd as the WebAssembly design has changed there have been\n[more](https://github.com/WebAssembly/polyfill-prototype-2)\n[experiments](https://github.com/WebAssembly/binaryen/blob/master/src/wasm2asm.h)\nwith polyfilling.\n\nOverall, optimism has been increasing for quick adoption of WebAssembly in\nbrowsers, which is great, but it has decreased the motivation to work on a\npolyfill.\n\nIt is also the case that polyfilling WebAssembly to asm.js is less urgent\nbecause of the existence of alternatives, for example, a reverse polyfill -\ncompiling\n[asm.js to WebAssembly](https://github.com/WebAssembly/binaryen/blob/master/src/asm2wasm.h) -\nexists, and it allows shipping a single build that can run as either\nasm.js or WebAssembly. It is also possible to build a project into\ntwo parallel asm.js and WebAssembly builds by just\n[flipping a switch](https://github.com/kripken/emscripten/wiki/WebAssembly)\nin emscripten, which avoids polyfill time on the client entirely. A third\noption, for non-performant code, is to use a compiled WebAssembly interpreter\nsuch as\n[binaryen.js](https://github.com/WebAssembly/binaryen/blob/master/test/binaryen.js/test.js).\n\nHowever, a WebAssembly polyfill is still an interesting idea and should in\nprinciple be possible.\n\n\n## Is WebAssembly only for C/C++ programmers?\n\nAs explained in the [high-level goals](HighLevelGoals.md), to achieve a Minimum\nViable Product, the initial focus is on [C/C++](CAndC++.md).\n\nHowever, by [integrating with JavaScript at the ES6 Module interface](Modules.md#integration-with-es6-modules),\nweb developers don't need to write C++ to take advantage of libraries that others have written; \nreusing 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).\n\nBeyond the MVP, another [high-level goal](HighLevelGoals.md)\nis to improve support for languages other than C/C++.  This includes [allowing WebAssembly code to\nallocate and access garbage-collected (JavaScript, DOM, Web API) objects\n:unicorn:][future garbage collection].\nEven before GC support is added to WebAssembly, it is possible to compile a language's VM \nto WebAssembly (assuming it's written in portable C/C++) and this has already been demonstrated \n([1](https://ruby.dj), [2](https://kripken.github.io/lua.vm.js/lua.vm.js.html),\n[3](https://syntensity.blogspot.com/2010/12/python-demo.html)).  However, \"compile the VM\" strategies \nincrease the size of distributed code, lose browser devtools integration, can have cross-language\ncycle-collection problems and miss optimizations that require integration with the browser.\n\n\n## Which compilers can I use to build WebAssembly programs?\n\nWebAssembly initially focuses on [C/C++](CAndC++.md), and a new, clean\nWebAssembly backend is being developed in upstream clang/LLVM, which can then be\nused by LLVM-based projects like [Emscripten][] and [PNaCl][].\n\nAs WebAssembly evolves it will support more languages than C/C++, and we hope\nthat other compilers will support it as well, even for the C/C++ language, for\nexample [GCC][]. The WebAssembly working group found it easier to start with\nLLVM support because they had more experience with that toolchain from their\n[Emscripten][] and [PNaCl][] work.\n\n  [Emscripten]: http://emscripten.org\n  [PNaCl]: https://developer.chrome.com/docs/native-client/\n  [GCC]: https://gcc.gnu.org\n\nWe hope that proprietary compilers also gain WebAssembly support, but we'll let\nvendors speak about their own platforms.\n\nThe [WebAssembly Community Group][] would be delighted to collaborate with more\ncompiler vendors, take their input into consideration in WebAssembly itself, and\nwork with them on ABI matters.\n\n  [WebAssembly Community Group]: https://www.w3.org/community/webassembly/\n\n\n## Will WebAssembly support View Source on the Web?\n\nYes! WebAssembly defines a [text format](TextFormat.md) to be rendered when\ndevelopers view the source of a WebAssembly module in any developer tool. Also,\na specific goal of the text format is to allow developers to write WebAssembly\nmodules by hand for testing, experimenting, optimizing, learning and teaching\npurposes. In fact, by dropping all the\n[coercions required by asm.js validation](http://asmjs.org/spec/latest/#introduction),\nthe WebAssembly text format should be much more natural to read and write than\nasm.js. Outside the browser, command-line and online tools that convert between\ntext and binary will also be made readily available.  Lastly, a scalable form of\nsource maps is also being considered as part of the WebAssembly\n[tooling story](Tooling.md).\n\n\n## What's the story for Emscripten users?\n\nExisting Emscripten users will get the option to build their projects to\nWebAssembly, by flipping a flag. Initially, Emscripten's asm.js output would be\nconverted to WebAssembly, but eventually Emscripten would use WebAssembly\nthroughout the pipeline. This painless transition is enabled by the\n[high-level goal](HighLevelGoals.md) that WebAssembly integrate well with the\nWeb platform (including allowing synchronous calls into and out of JavaScript)\nwhich makes WebAssembly compatible with Emscripten's current asm.js compilation\nmodel.\n\n\n## Is WebAssembly trying to replace JavaScript?\n\nNo! WebAssembly is designed to be a complement to, not replacement of,\nJavaScript. While WebAssembly will, over time, allow many languages to be\ncompiled to the Web, JavaScript has an incredible amount of momentum and will\nremain the single, privileged (as described\n[above](FAQ.md#is-webassembly-only-for-cc-programmers)) dynamic language of the\nWeb. Furthermore, it is expected that JavaScript and WebAssembly will be used\ntogether in a number of configurations:\n\n* Whole, compiled C++ apps that leverage JavaScript to glue things together.\n* HTML/CSS/JavaScript UI around a main WebAssembly-controlled center canvas,\n  allowing developers to leverage the power of web frameworks to build\n  accessible, web-native-feeling experiences.\n* Mostly HTML/CSS/JavaScript app with a few high-performance WebAssembly modules\n  (e.g., graphing, simulation, image/sound/video processing, visualization,\n  animation, compression, etc., examples which we can already see in asm.js\n  today) allowing developers to reuse popular WebAssembly libraries just like\n  JavaScript libraries today.\n* When WebAssembly\n  [gains the ability to access garbage-collected objects :unicorn:][future garbage collection],\n  those objects will be shared with JavaScript, and not live in a walled-off\n  world of their own.\n\n\n## Why not just use LLVM bitcode as a binary format?\n\nThe [LLVM](https://llvm.org/) compiler infrastructure has a lot of attractive \nqualities: it has an existing intermediate representation (LLVM IR) and binary\nencoding format (bitcode). It has code generation backends targeting many \narchitectures and is actively developed and maintained by a large community. In\nfact PNaCl already uses LLVM as a basis for its binary\nformat. However, the goals and requirements that LLVM was designed to meet are\nsubtly mismatched with those of WebAssembly.\n\nWebAssembly has several requirements and goals for its Instruction Set\nArchitecture (ISA) and binary encoding:\n\n* Portability: The ISA must be the same for every machine architecture.\n* Stability: The ISA and binary encoding must not change over time (or change\n  only in ways that can be kept backward-compatible).\n* Small encoding: The representation of a program should be as small as possible\n  for transmission over the Internet.\n* Fast decoding: The binary format should be fast to decompress and decode for\n  fast startup of programs.\n* Fast compiling: The ISA should be fast to compile (and suitable for either\n  AOT- or JIT-compilation) for fast startup of programs.\n* Minimal [nondeterminism](Nondeterminism.md): The behavior of programs should\n  be as predictable and deterministic as possible (and should be the same on\n  every architecture, a stronger form of the portability requirement stated\n  above).\n\nLLVM IR is meant to make compiler optimizations easy to implement, and to\nrepresent the constructs and semantics required by C, C++, and other languages\non a large variety of operating systems and architectures. This means that by\ndefault the IR is not portable (the same program has different representations\nfor different architectures) or stable (it changes over time as optimization and\nlanguage requirements change). It has representations for a huge variety of\ninformation that is useful for implementing mid-level compiler optimizations but\nis not useful for code generation (but which represents a large surface area for\ncodegen implementers to deal with).  It also has undefined behavior (largely\nsimilar to that of C and C++) which makes some classes of optimization feasible\nor more powerful, but can lead to unpredictable behavior at runtime. LLVM's\nbinary format (bitcode) was designed for temporary on-disk serialization\nof the IR for link-time optimization, and not for stability or compressibility\n(although it does have some features for both of those).\n\nNone of these problems are insurmountable. For example PNaCl defines a small\nportable\n[subset](https://developer.chrome.com/native-client/reference/pnacl-bitcode-abi)\nof the IR with reduced undefined behavior, and a stable version of the bitcode\nencoding. It also employs several techniques to improve startup\nperformance. However, each customization, workaround, and special solution means\nless benefit from the common infrastructure. We believe that by taking our\nexperience with LLVM and designing an IR and binary encoding for our goals and\nrequirements, we can do much better than adapting a system designed for other\npurposes.\n\nNote that this discussion applies to use of LLVM IR as a standardized\nformat. LLVM's clang frontend and midlevel optimizers can still be used to\ngenerate WebAssembly code from C and C++, and will use LLVM IR in their\nimplementation similarly to how PNaCl and Emscripten do today.\n\n\n## Why is there no fast-math mode with relaxed floating point semantics?\n\nOptimizing compilers commonly have fast-math flags which permit the compiler to\nrelax the rules around floating point in order to optimize more\naggressively. This can include assuming that NaNs or infinities don't occur,\nignoring the difference between negative zero and positive zero, making\nalgebraic manipulations which change how rounding is performed or when overflow\nmight occur, or replacing operators with approximations that are cheaper to\ncompute.\n\nThese optimizations effectively introduce nondeterminism; it isn't possible to\ndetermine how the code will behave without knowing the specific choices made by\nthe optimizer. This often isn't a serious problem in native code scenarios,\nbecause all the nondeterminism is resolved by the time native code is\nproduced. Since most hardware doesn't have floating point nondeterminism,\ndevelopers have an opportunity to test the generated code, and then count on it\nbehaving consistently for all users thereafter.\n\nWebAssembly implementations run on the user side, so there is no opportunity for\ndevelopers to test the final behavior of the code. Nondeterminism at this level\ncould cause distributed WebAssembly programs to behave differently in different\nimplementations, or change over time. WebAssembly does have\n[some nondeterminism](Nondeterminism.md) in cases where the tradeoffs warrant\nit, but fast-math flags are not believed to be important enough:\n\n * Many of the important fast-math optimizations happen in the mid-level\n   optimizer of a compiler, before WebAssembly code is emitted. For example,\n   loop vectorization that depends on floating point reassociation can still be\n   done at this level if the user applies the appropriate fast-math flags, so\n   WebAssembly programs can still enjoy these benefits. As another example,\n   compilers can replace floating point division with floating point\n   multiplication by a reciprocal in WebAssembly programs just as they do for\n   other platforms.\n * Mid-level compiler optimizations may also be augmented by implementing them\n   in a [JIT library](JITLibrary.md) in WebAssembly. This would allow them to\n   perform optimizations that benefit from having\n   [information about the target](FeatureTest.md) and information about the\n   source program semantics such as fast-math flags at the same time. For\n   example, if SIMD types wider than 128-bit are added, it's expected that there\n   would be feature tests allowing WebAssembly code to determine which SIMD\n   types to use on a given platform.\n * When WebAssembly\n   [adds an FMA operator :unicorn:][future floating point],\n   folding multiply and add sequences into FMA operators will be possible.\n * WebAssembly doesn't include its own math functions like `sin`, `cos`, `exp`,\n   `pow`, and so on. WebAssembly's strategy for such functions is to allow them\n   to be implemented as library routines in WebAssembly itself (note that x86's\n   `sin` and `cos` instructions are slow and imprecise and are generally avoided\n   these days anyway). Users wishing to use faster and less precise math\n   functions on WebAssembly can simply select a math library implementation\n   which does so.\n * Most of the individual floating point operators that WebAssembly does have\n   already map to individual fast instructions in hardware. Telling `add`,\n   `sub`, or `mul` they don't have to worry about NaN for example doesn't make\n   them any faster, because NaN is handled quickly and transparently in hardware\n   on all modern platforms.\n * WebAssembly has no floating point traps, status register, dynamic rounding\n   modes, or signalling NaNs, so optimizations that depend on the absence of\n   these features are all safe.\n\n\n## What about `mmap`?\n\nThe [`mmap`](https://pubs.opengroup.org/onlinepubs/009695399/functions/mmap.html)\nsyscall has many useful features. While these are all packed into one overloaded\nsyscall in POSIX, WebAssembly unpacks this functionality into multiple\noperators:\n\n* the MVP starts with the ability to grow linear memory via a\n  [`memory.grow`] operator;\n* proposed\n  [future features :unicorn:][future memory control] would\n  allow the application to change the protection and mappings for pages in the\n  contiguous range `0` to `memory.size`.\n\nA significant feature of `mmap` that is missing from the above list is the\nability to allocate disjoint virtual address ranges. The reasoning for this\nomission is:\n\n* The above functionality is sufficient to allow a user-level libc to implement\n  full, compatible `mmap` with what appears to be noncontiguous memory\n  allocation (but, under the hood is just coordinated use of `memory_resize` and\n  `mprotect`/`map_file`/`map_shmem`/`madvise`).\n* The benefit of allowing noncontiguous virtual address allocation would be if\n  it allowed the engine to interleave a WebAssembly module's linear memory with\n  other memory allocations in the same process (in order to mitigate virtual\n  address space fragmentation). There are two problems with this:\n\n  - This interleaving with unrelated allocations does not currently admit\n    efficient security checks to prevent one module from corrupting data outside\n    its heap (see discussion in\n    [#285](https://github.com/WebAssembly/design/pull/285)).\n  - This interleaving would require making allocation nondeterministic and\n    nondeterminism is something that WebAssembly generally\n    [tries to avoid](Nondeterminism.md).\n\n\n## Why have wasm32 and wasm64, instead of just an abstract `size_t`?\n\nThe amount of linear memory needed to hold an abstract `size_t` would then also\nneed to be determined by an abstraction, and then partitioning the linear memory\naddress space into segments for different purposes would be more complex. The\nsize of each segment would depend on how many `size_t`-sized objects are stored\nin it. This is theoretically doable, but it would add complexity and there would\nbe more work to do at application startup time.\n\nAlso, allowing applications to statically know the pointer size can allow them\nto be optimized more aggressively. Optimizers can better fold and simplify\ninteger expressions when they have full knowledge of the bitwidth. And, knowing\nmemory sizes and layouts for various types allows one to know how many trailing\nzeros there are in various pointer types.\n\nAlso, C and C++ deeply conflict with the concept of an abstract `size_t`.\nConstructs like `sizeof` are required to be fully evaluated in the front-end\nof the compiler because they can participate in type checking. And even before\nthat, it's common to have predefined macros which indicate pointer sizes,\nallowing code to be specialized for pointer sizes at the very earliest stages of\ncompilation. Once specializations are made, information is lost, scuttling\nattempts to introduce abstractions.\n\nAnd finally, it's still possible to add an abstract `size_t` in the future if\nthe need arises and practicalities permit it.\n\n\n## Why have wasm32 and wasm64, instead of just using 8 bytes for storing pointers?\n\nA great number of applications don't ever need as much as 4 GiB of memory.\nForcing all these applications to use 8 bytes for every pointer they store would\nsignificantly increase the amount of memory they require, and decrease their\neffective utilization of important hardware resources such as cache and memory\nbandwidth.\n\nThe motivations and performance effects here should be essentially the same as\nthose that motivated the development of the\n[x32 ABI](https://en.wikipedia.org/wiki/X32_ABI) for Linux.\n\nEven Knuth found it worthwhile to give us his opinion on this issue at some point,\n[a flame about 64-bit pointers](https://www-cs-faculty.stanford.edu/~uno/news08.html).\n\n## Will I be able to access proprietary platform APIs (e.g. Android / iOS)?\n\nYes but it will depend on the _WebAssembly embedder_. Inside a browser you'll \nget access to the same HTML5 and other browser-specific APIs which are also \naccessible through regular JavaScript. However, if a wasm VM is provided as an \n[“app execution platform”](NonWeb.md) by a specific vendor, it might provide \naccess to [proprietary platform-specific APIs](Portability.md#api) of e.g. \nAndroid / iOS. \n\n[future general]: FutureFeatures.md\n[future garbage collection]: https://github.com/WebAssembly/proposals/issues/16\n[future floating point]: https://github.com/WebAssembly/design/issues/1391\n[future memory control]: https://github.com/WebAssembly/memory-control\n[`memory.grow`]: https://webassembly.github.io/spec/core/syntax/instructions.html#syntax-instr-memory\n"
  },
  {
    "path": "FeatureTest.md",
    "content": "See [rationale](Rationale.md#feature-testing---motivating-scenarios) for motivating scenarios.\n\n# Feature Test\n\n[Post-MVP :unicorn:][future general], applications will be able to query which features are\nsupported via\n[`has_feature` or a similar API :unicorn:][future feature testing]. This\naccounts for the pragmatic reality that features are shipped in different orders\nat different times by different engines.\n\nWhat follows is a sketch of what such a feature testing capability could look\nlike.\n\nSince some WebAssembly features add operators and all WebAssembly code in a\nmodule is validated ahead-of-time, the usual JavaScript feature detection\npattern:\n\n```\nif (foo)\n    foo();\nelse\n    alternativeToFoo();\n```\n\nwon't work in WebAssembly (if `foo` isn't supported, `foo()` will fail to\nvalidate).\n\nInstead, applications may use one of the following strategies:\n\n1. Compile several versions of a module, each assuming different feature support\n   and use `has_feature` tests to determine which version to load.\n\n2. During the [\"specific\" layer decoding](BinaryEncoding.md), which will happen\n   in user code in the MVP *anyway*, use `has_feature` to determine which features\n   are supported and then translate unsupported feature use into either a polyfill\n   or a trap.\n\nBoth of these options could be automatically provided by the toolchain and\ncontrolled by compiler flags. Since `has_feature` is a constant expression,\nit can be constant-folded by WebAssembly engines.\n\nTo illustrate, consider 4 examples:\n\n* [`i32.bitrev` :unicorn:][future integer] - Strategy 2\n  could be used to translate `(i32.bitrev lhs rhs)` into an equivalent expression\n  that stores `lhs` and `rhs` in locals then uses `i32.lt_s` and `select`.\n* [Threads :unicorn:][future threads] - If an application uses `#ifdef` extensively\n  to produce thread-enabled/disabled builds, Strategy 1 would be appropriate.\n  However, if the application was able to abstract use of threading to a few\n  primitives, Strategy 2 could be used to patch in the right primitive \n  implementation.\n* [`mprotect` :unicorn:][future memory control] - If engines\n  aren't able to use OS signal handling to implement `mprotect` efficiently,\n  `mprotect` may become a permanently optional feature. For uses of `mprotect`\n  that are not necessary for correctness (but rather just catching bugs),\n  `mprotect` could be replaced with `nop`. If `mprotect` was necessary for\n  correctness but an alternative strategy existed that did not rely on\n  `mprotect`, `mprotect` could be replaced with an `abort()` call, relying on\n  the application to test `(has_feature \"mprotect\")` to avoid calling the\n  `abort()`. The `has_feature` query could be exposed to C++ code via\n  the existing `__builtin_cpu_supports`.\n* [SIMD][future simd] - When SIMD operators have a good-enough\n  polyfill, e.g., `f32x4.fma` via `f32x4.mul`/`add`, Strategy 2 could be used \n  (similar to the `i32.bitrev` example above). However, when a SIMD feature has no\n  efficient polyfill (e.g., `f64x2`, which introduces both operators *and*\n  types), alternative algorithms need to be provided and selected at load time.\n\nAs a hypothetical (not implemented) example polyfilling the SIMD `f64x2`\nfeature, the C++ compiler could provide a new function attribute that indicated\nthat one function was an optimized, but feature-dependent, version of another\nfunction (similar to the\n[`ifunc` attribute](https://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/Function-Attributes.html#index-g_t_0040code_007bifunc_007d-attribute-2529),\nbut without the callback):\n\n```\n#include <xmmintrin.h>\nvoid foo(...) {\n  __m128 x, y;           // -> f32x4 locals\n  ...\n  x = _mm_add_ps(x, y);  // -> f32x4.add\n  ...\n}\nvoid foo_f64x2(...) __attribute__((optimizes(\"foo\",\"f64x2\"))) {\n  __m256 x, y;           // -> f64x2 locals\n  ...\n  x = _m_add_pd(x, y);   // -> f64x2.add\n  ...\n}\n...\nfoo(...);                 // calls either foo or foo_f64x2\n```\n\nIn this example, the toolchain could emit both `foo` and `foo_f64x2` as\nfunction definitions in the \"specific layer\" binary format. The load-time\npolyfill would then replace `foo` with `foo_f64x2` if\n`(has_feature \"f64x2\")`. Many other strategies are possible to allow finer or\ncoarser granularity substitution. Since this is all in userspace, the strategy\ncan evolve over time.\n\nSee also the [better feature testing support :unicorn:][future feature testing]\nfuture feature.\n\n[future general]: FutureFeatures.md\n[future feature testing]: https://github.com/WebAssembly/design/issues/1280\n[future integer]: https://github.com/WebAssembly/design/issues/1382\n[future threads]: https://github.com/WebAssembly/design/issues/1073\n[future simd]: https://github.com/WebAssembly/design/issues/1075\n[future memory control]: https://github.com/WebAssembly/memory-control\n"
  },
  {
    "path": "FutureFeatures.md",
    "content": "# Future Features for WebAssembly\n\nFor a list of standard and standard-track features and their implementation\nstatus in major WebAssembly implementations, see\n[the WebAssembly features page].\n\nFor a list of all currently active proposals and their champions, see\n[the proposals page].\n\nFor a list of discussions about possible future features, see\n[the design repo's issue tracker].\n\n[the WebAssembly features page]: https://webassembly.org/features/\n[the proposals page]: https://github.com/WebAssembly/proposals/\n[the design repo's issue tracker]: https://github.com/WebAssembly/design/issues\n"
  },
  {
    "path": "HighLevelGoals.md",
    "content": "# WebAssembly High-Level Goals\n\n1. Define a [portable](Portability.md), size- and load-time-efficient\n   [binary format](MVP.md#binary-format) to serve as a compilation target which\n   can be compiled to execute at native speed by taking advantage of common\n   hardware capabilities available on a wide range of platforms, including\n   [mobile](https://en.wikipedia.org/wiki/Mobile_device) and\n   [IoT](https://en.wikipedia.org/wiki/Internet_of_Things).\n2. Specify and implement incrementally:\n    * develop new features as independent [proposals];\n    * maintain [layering], with a core spec focused on pure sandboxed\n      computation, with host interactions factored out into higher\n      specification layers;\n    * preserve backwards compatibility;\n    * prioritize new features according to feedback and experience; and\n    * avoid biasing towards any one programming language family.\n3. Design to execute within and integrate well with the *existing*\n   [Web platform](Web.md):\n    * maintain the versionless, [feature-tested](FeatureTest.md) and backwards-compatible evolution story of the Web;\n    * execute in the same semantic universe as JavaScript;\n    * allow synchronous calls to and from JavaScript;\n    * enforce the same-origin and permissions security policies;\n    * access browser functionality through the same Web APIs that are accessible\n      to JavaScript; and\n    * define a human-editable text format that is convertible to and from the\n      binary format, supporting View Source functionality.\n4. Design to support [non-browser embeddings](NonWeb.md) as well.\n5. Make a great platform:\n    * promote [compilers and tools targeting WebAssembly];\n    * enable other useful [tooling](Tooling.md);\n    * maintain a high level of [determinism]; and\n    * specify using [formal semantics].\n\n[compilers and tools targeting WebAssembly]: https://webassembly.org/getting-started/developers-guide/\n[proposals]: https://github.com/WebAssembly/proposals/\n[layering]: https://webassembly.org/specs/\n[determinism]: Nondeterminism.md\n[formal semantics]: https://github.com/WebAssembly/spec\n"
  },
  {
    "path": "JITLibrary.md",
    "content": "# JIT and Optimization Library\n\nWebAssembly's Just-in-Time compilation (JIT)\ninterface will likely be fairly low-level, exposing general-purpose primitives\nrather than higher-level functionality. Still, there is a need for higher-level\nfunctionality, and for greater flexibility than the WebAssembly spec can provide.\nThere is also a need for experimentation, particularly in the area of\napplications wishing to dynamically generate new code, to determine which features\nand interfaces are most appropriate. JIT and Optimization libraries that would run\ninside WebAssembly and provide support and higher-level features would fit this\nneed very well.\n\nSuch libraries wouldn't be part of the WebAssembly spec itself, but the concept\nis relevant to discuss here because features that we can expect to address in\nlibraries are features that we may not need to add to the spec. This strategy\ncan help keep the spec itself simple and reduce the surface area of features\nrequired of every spec implementation.\n\nAnd, libraries will facilitate light-weight experimentation with new features\nthat we may eventually want to add to WebAssembly itself. In a library layer,\nwe can quickly iterate, experiment, and gain real-world insight, before adding\nfeatures to the spec itself and freezing all the details. And as new features\nare standardized, libraries will become the polyfills which will help those\nfeatures gain adoption.\n\nThis raises the question of how we should decide which features belong in the\nspec, and which belong in a library. Some of the fundamental advantages of\nputting functionality in a library rather than in the spec and in implementations\nthemselves include:\n\n * A library can freely choose to offer greater degrees of undefined behavior,\n   implementation-defined behavior, unspecified behavior, and so on. This means\n   it can perform much more aggressive optimizations, including many that are\n   extremely common in optimizing compilers and might otherwise seem missing in\n   the WebAssembly spec itself:\n    * Constant folding, strength reduction, and code motion of math functions\n      such as `sin`, `cos`, `exp`, `log`, `pow`, and `atan2`.\n    * Performing aggressive expression simplifications that depend on assuming\n      that integer arithmetic doesn't overflow.\n    * Performing GVN with redundant load elimination, and other optimizations\n      based on aliasing rules that incur undefined behavior if they are violated.\n    * Vectorization that utilizes both floating point reassociation and\n      awareness of the underlying platform through\n      [feature testing](FeatureTest.md).\n\n * A library can support higher-level features, and features that are tailored\n   to certain applications, whereas the WebAssembly spec itself is limited to\n   general-purpose primitives. Possible examples of this are:\n    * A richer type system, which could include things like complex, rational,\n      arbitrary bitwidth integers, non-power-of-2 SIMD types, interval\n      arithmetic, etc.\n    * A higher-level type system, which could include basic polymorphism of\n      various kinds (either with true dynamism or with monomorphisation).\n    * Richer control flow constructs.\n    * A broader set of operators, such as string-handling operators,\n      data type serialization, testing facilities, and linear algebra\n      operators, all of which can benefit from being integrated at the\n      language level.\n   Since every feature required in the spec itself will need to be implemented\n   by all implementations, domain-specific features run the risk of making\n   people \"pay for what they don't use\". With features libraries, people need\n   only pay for the features they choose to use.\n\n * A library can evolve over time to meet the changing needs of higher-level\n   languages. In practice, compiler IRs such as LLVM IR evolve to add new\n   features, change existing features, and sometimes remove features, and these\n   kinds of changes are much harder to do in a spec.\n\nThe library approach also means that applications using a particular version\nof a library can get consistent behavior and performance, because of the\ndeterminism of the underlying WebAssembly platform.\n\nA significant range of approaches are possible:\n\n  * \"Customized WebAssembly\". This might involve a library whose input format\n    is conceptually WebAssembly but with some additional features. The library\n    could optimize and then lower those features leaving standard WebAssembly\n    to present to the underlying implementation.\n\n  * \"Bring Your Own Compiler\" There's nothing stopping one from bundling\n    full-fledged AOT-style compilers that compile an independent source language\n    or IR into WebAssembly right there in WebAssembly itself. Obviously this\n    will involve tradeoffs in terms of download size and startup time, but it\n    would allow a unique degree of flexibility.\n\n  * And many things in between.\n"
  },
  {
    "path": "JS.md",
    "content": "# JavaScript API\n\nThis file historically contained the description of WebAssembly's JavaScript API.\n\nFor the current description, see the [normative documentation](http://webassembly.github.io/spec/js-api/index.html).\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"{}\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright {yyyy} {name of copyright owner}\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\n"
  },
  {
    "path": "MVP.md",
    "content": "# Minimum Viable Product\n\nWebAssembly initially launched with a \"minimum viable product\" version (the \"MVP\"),\nwhich was complete enough for some use cases, however many important features were\ndeferred. WebAssembly has added many [features] since then.\n\n[features]: https://webassembly.org/features/\n"
  },
  {
    "path": "Modules.md",
    "content": "# Modules\n\nThis file historically contained the description of WebAssembly's module structure.\n\nFor the current description, see the [normative documentation](https://webassembly.github.io/spec/core/syntax/modules.html).\n"
  },
  {
    "path": "NonWeb.md",
    "content": "# Non-Web Embeddings\n\nWhile WebAssembly is designed to run [on the Web](Web.md), it is\nalso desirable for it to be able to execute well in other environments,\nincluding everything from minimal shells for testing to full-blown\napplication environments e.g. on servers in datacenters, on IoT devices,\nor mobile/desktop apps. It may even be desirable to execute WebAssembly\nembedded within larger programs.\n\nNon-Web environments may provide different APIs than Web\nenvironments.\n\nNon-Web environments include JavaScript VMs (e.g. [node.js]), however\nWebAssembly is also capable of being executed without a JavaScript VM present.\nThe table in the [features page] of the website lists several such\nimplementations.\n\n[node.js]: https://nodejs.org\n[features page]: https://webassembly.org/features/\n\n[WASI] is a set of standards-track APIs being developed by the [WASI Subgroup]\nintended for use in many environments, including in non-browser and non-JS\nengines.\n\n[WASI]: https://wasi.dev\n[WASI Subgroup]: https://github.com/WebAssembly/wasi\n\nThe WebAssembly spec itself will not try to define any large portable libc-like\nlibrary. However, certain features that are core to WebAssembly semantics that\nare similar to functions found in native libc *would* be part of the core\nWebAssembly spec as primitive operators (e.g., the `memory.grow` operator, which\nis similar to the `sbrk` function on many systems, and in the future, perhaps\noperators supporting `dlopen` functionality).\n\nWhere there is overlap between the Web and popular non-Web environments,\nshared specs could be proposed, but these would be separate from the WebAssembly\nspec. A symmetric example in JavaScript would be the in-progress \n[Loader](https://whatwg.github.io/loader) spec, which is proposed for both\nWeb and node.js environments and is distinct from the JavaScript spec.\n\nHowever, for most cases it is expected that, to achieve portability at the\nsource code level, communities would build libraries that mapped from a \nsource-level interface such as POSIX or SDL to the host environment's builtin\ncapabilities, either at build time or runtime, possibly making use of\n[feature testing](FeatureTest.md), [dynamic linking](DynamicLinking.md),\nstatic linking, or polyfilling.\n\nIn general, by preserving spec layering, and the core WebAssembly spec\nindependent of the host environment and linking specs, WebAssembly can be\nused as a portable binary format on many platforms, in many environments, for\nmany use cases, bringing great benefits in portability, tooling and\nlanguage-agnosticity.\n\n[shared-everything linking]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/examples/SharedEverythingDynamicLinking.md\n"
  },
  {
    "path": "Nondeterminism.md",
    "content": "# Nondeterminism in WebAssembly\n\nWebAssembly is a [portable](Portability.md) [sandboxed](Security.md) platform\nwith limited, local, nondeterminism.\n\n  * *Limited*: nondeterministic execution can only occur in a small number of\n    well-defined cases (described below) and, in those cases, the implementation\n    may select from a limited set of possible behaviors.\n  * *Local*: when nondeterministic execution occurs, the effect is local,\n    there is no \"spooky action at a distance\".\n\nThe [rationale](Rationale.md) document details why WebAssembly is designed as\ndetailed in this document.\n\nThe following is a list of the places where the WebAssembly specification\ncurrently admits nondeterminism:\n\n * New features will be added to WebAssembly, which means different implementations\n   will have different support for each feature.\n * The sequence of calls of exported functions, and the values of the incoming\n   arguments and return values from the outside environment, are not\n   determined by the Wasm spec.\n * With `shared` memory that can be accessed by multiple threads, the results of\n   load, read-modify-write, wait, and awake operators are nondeterministic.\n * Except when otherwise specified, when an arithmetic operator returns NaN,\n   there is nondeterminism in determining the specific bits of the NaN. However,\n   wasm does still provide the guarantee that NaN values returned from an operation\n   will not have 1 bits in their fraction field that aren't set in any NaN values\n   in the input operands, except for the most significant bit of the fraction field\n   (which most operators set to 1).\n * Except when otherwise specified, when an arithmetic operator with a floating\n   point result type receives no NaN input values and produces a NaN result\n   value, the sign bit of the NaN result value is nondeterministic.\n * The [relaxed SIMD] instructions have nondeterministic results.\n * Environment-dependent resource limits may be exhausted. A few examples:\n   - Memory allocation may fail.\n   - The runtime can fail to allocate a physical page when a memory location is first\n     accessed (e.g. through a load or store), even if that memory was virtually reserved\n     by the maximum size property of the [memory section](Modules.md#linear-memory-section).\n   - Program stack may get exhausted (e.g., because function call depth is too big,\n     or functions have too many locals, or infinite recursion). Note that this stack\n     isn't located in the program-accessible linear memory.\n   - Resources such as handles may get exhausted.\n   - Any other resource could get exhausted at any time. Caveat emptor.\n\nThe following proposals would add additional nondeterminism:\n\n * [Flexible-vectors], adding nondeterminism in the length of the vectors.\n\nUsers of C, C++, and similar languages should be aware that operators which\nhave defined or constrained behavior in WebAssembly itself may nonetheless still\nhave undefined behavior\n[at the source code level](CAndC++.md#undefined-behavior).\n\n[relaxed SIMD]: https://github.com/WebAssembly/relaxed-simd\n[Flexible-vectors]: https://github.com/WebAssembly/flexible-vectors\n"
  },
  {
    "path": "Portability.md",
    "content": "# Portability\n\nWebAssembly's [binary format](BinaryEncoding.md) is designed to be executable\nefficiently on a variety of operating systems and instruction set architectures,\n[on the Web](Web.md) and [off the Web](NonWeb.md).\n\n## Assumptions for Efficient Execution\n\nExecution environments which, despite\n[limited, local, nondeterminism](Nondeterminism.md), don't offer\nthe following characteristics may be able to execute WebAssembly modules\nnonetheless. In some cases they may have to emulate behavior that the host\nhardware or operating system don't offer so that WebAssembly modules execute\n*as-if* the behavior were supported. This sometimes will lead to poor\nperformance.\n\nAs WebAssembly's standardization goes forward we expect to formalize these\nrequirements, and how WebAssembly will adapt to new platforms that didn't\nnecessarily exist when WebAssembly was first designed.\n\nWebAssembly portability assumes that execution environments offer the following\ncharacteristics:\n\n* 8-bit bytes.\n* Addressable at a byte memory granularity.\n* Support unaligned memory accesses or reliable trapping that allows software\n  emulation thereof.\n* Two's complement signed integers in 32 bits and optionally 64 bits.\n* IEEE 754-2019 32-bit and 64-bit floating point, except for\n  [a few exceptions][floating-point operations].\n* Little-endian byte ordering.\n* Memory regions which can be efficiently addressed with 32-bit\n  pointers or indices.\n* wasm64 additionally supports linear memory bigger than\n  [4 GiB with 64-bit pointers or indices][future 64-bit].\n* Enforce secure isolation between WebAssembly modules and other modules or\n  processes executing on the same machine.\n* An execution environment which offers forward progress guarantees to all\n  threads of execution (even when executing in a non-parallel manner).\n* Availability of lock-free atomic memory operators, when naturally aligned, for\n  8- 16- and 32-bit accesses. At a minimum this must include an atomic\n  compare-and-exchange operator (or equivalent load-linked/store-conditional).\n* wasm64 additionally requires lock-free atomic memory operators, when naturally\n  aligned, for 64-bit accesses.\n\n## API\n\nWebAssembly does not specify any APIs or syscalls, only an \n[import mechanism](Modules.md) where the set of available imports is defined\nby the host environment. In a [Web](Web.md) environment, functionality is\naccessed through the Web APIs defined by the\n[Web Platform](https://en.wikipedia.org/wiki/Open_Web_Platform).\n[Non-Web](NonWeb.md) environments can choose to implement standard Web APIs,\nstandard non-Web APIs (e.g. POSIX), or invent their own.\n\n## Source-level\n\nPortability at the C/C++ level can be achieved by programming to\na standard API (e.g., POSIX) and relying on the compiler and/or libraries to map\nthe standard interface to the host environment's available imports either at\ncompile-time (via `#ifdef`) or run-time (via [feature detection]\nand dynamic [loading](Modules.md)/[linking](DynamicLinking.md)).\n\n[future 64-bit]: https://github.com/WebAssembly/memory64/blob/main/proposals/memory64/Overview.md\n[floating-point operations]: https://webassembly.github.io/spec/core/exec/numerics.html#floating-point-operations\n[feature detection]: https://github.com/WebAssembly/design/issues/1280\n"
  },
  {
    "path": "README.md",
    "content": "# WebAssembly Design\n\nThis repository is part of the [WebAssembly Community Group] and hosts the\n[issue tracker] for [phase 0 proposals], a [discussion forum] for questions\nand general discussion, and a collection of high-level non-normative\n[design documents].\n\nFor more information about WebAssembly itself, see [the website]! For\ninformation about Contributing to WebAssembly see [the Contributing document].\n\nPlease follow our [Code of Ethics and Professional Conduct].\n\n## Design documents\n\nSome of the design documents in this repository are out of date. We're\ngradually working updating these documents. The following are some documents\nwhich are fairly up to date:\n\n - [WebAssembly High-Level Goals](HighLevelGoals.md)\n - [What does Portability mean in Wasm?](Portability.md)\n - [Design Rationale](Rationale.md)\n - [WebAssembly's Security model](Security.md)\n - [Nondeterminism in WebAssembly](Nondeterminism.md)\n\n[issue tracker]: https://github.com/WebAssembly/design/issues\n[phase 0 proposals]: https://github.com/WebAssembly/meetings/blob/main/process/phases.md#0-pre-proposal-individual-contributor\n[discussion forum]: https://github.com/WebAssembly/design/discussions\n[the Contributing document]: Contributing.md\n[the website]: https://webassembly.org\n[Code of Ethics and Professional Conduct]: https://github.com/WebAssembly/meetings/blob/main/CODE_OF_CONDUCT.md\n[design documents]: #design-documents\n[WebAssembly Community Group]: https://www.w3.org/community/webassembly/\n"
  },
  {
    "path": "Rationale.md",
    "content": "# Design Rationale\n\nThis document describes rationales for WebAssembly's design decisions, acting as\nfootnotes to the main design text, keeping the main specification easier to\nread, and making it easier to revisit decisions later without having to plow\nthrough all the issues and pull requests. This rationale document tries to list\nhow decisions were made, and where tradeoffs were made for the sake of language\nergonomics, portability, performance, security, and Getting Things Done.\n\nWebAssembly was designed incrementally, with multiple implementations being\npursued concurrently. As the MVP stabilizes and we get experience from real-world\ncodebases, we'll revisit the alternatives listed below, reevaluate the tradeoffs\nand update the [design](Semantics.md) before the MVP is finalized.\n\n\n## Why a stack machine?\n\nWhy not an AST, or a register- or SSA-based bytecode?\n\n* We started with an AST and generalized to a [structured stack machine](Semantics.md). ASTs allow a \n  dense encoding and efficient decoding, compilation, and interpretation.\n  The structured stack machine of WebAssembly is a generalization of ASTs allowed in previous versions while allowing\n  efficiency gains in interpretation and baseline compilation, as well as a straightforward \n  design for multi-return functions.\n* The stack machine allows smaller binary encoding than registers or SSA [JSZap][], [Slim Binaries][],\n  and structured control flow allows simpler and more efficient verification, including decoding directly\n  to a compiler's internal SSA form.\n* [Polyfill prototype][] shows simple and efficient translation to asm.js.\n\n  [JSZap]: https://research.microsoft.com/en-us/projects/jszap/\n  [Slim Binaries]: https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.108.1711\n  [Polyfill prototype]: https://github.com/WebAssembly/polyfill-prototype-1\n\n\n## Why not a fully-general stack machine?\n\nThe WebAssembly stack machine is restricted to structured control flow and structured\nuse of the stack. This greatly simplifies one-pass verification, avoiding a fixpoint computation\nlike 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)).\nThis also simplifies compilation and manipulation of WebAssembly code by other tools.\nFurther generalization of the WebAssembly stack machine is planned post-MVP, such as the\naddition of multiple return values from control flow constructs and function calls.\n\n## Basic Types Only\n\nWebAssembly only represents [a few types](Semantics.md#Types).\n\n* More complex types can be formed from these basic types. It's up to the source\n  language compiler to express its own types in terms of the basic machine\n  types. This allows WebAssembly to present itself as a virtual ISA, and lets\n  compilers target it as they would any other ISA.\n* These types are directly representable on all modern CPU architectures.\n* Smaller types (such as `i8` and `i16`) are usually no more efficient and in\n  languages like C/C++ are only semantically meaningful for memory accesses\n  since arithmetic get widened to `i32` or `i64`. Avoiding them at least for MVP\n  makes it easier to implement a WebAssembly VM.\n* Other types (such as `f16`, `i128`) aren't widely supported by existing\n  hardware and can be supported by runtime libraries if developers wish to use\n  them. Hardware support is sometimes uneven, e.g. some support load/store of\n  `f16` only whereas other hardware also supports scalar arithmetic on `f16`,\n  and yet other hardware only supports SIMD arithmetic on `f16`. They can be\n  added to WebAssembly later without compromising MVP.\n* More complex object types aren't semantically useful for MVP: WebAssembly\n  seeks to provide the primitive building blocks upon which higher-level\n  constructs can be built. They may become useful to support other languages,\n  especially when considering [garbage collection][future garbage collection].\n\n\n## Load/Store Addressing\n\nLoad/store instructions include an immediate offset used for\n[addressing](Semantics.md#Addressing). This is intended to simplify folding\nof offsets into complex address modes in hardware, and to simplify bounds\nchecking optimizations. It offloads some of the optimization work to the\ncompiler that targets WebAssembly, executing on the developer's machine, instead\nof performing that work in the WebAssembly compiler on the user's machine.\n\n\n## Alignment Hints\n\nLoad/store instructions contain\n[alignment hints](Semantics.md#Alignment). This makes it easier to generate\nefficient code on certain hardware architectures.\n\nEither tooling or an explicit opt-in \"debug mode\" in the spec could allow\nexecution of a module in a mode that threw exceptions on misaligned access.\nThis mode would incur some runtime cost for branching on most platforms which is\nwhy it isn't the specified default.\n\n\n## Out of Bounds\n\nThe ideal semantics is for\n[out-of-bounds accesses](Semantics.md#Out-of-Bounds) to trap, but the\nimplications are not yet fully clear.\n\nThere are several possible variations on this design being discussed and\nexperimented with. More measurement is required to understand the associated\ntradeoffs.\n\n  * After an out-of-bounds access, the instance can no longer execute code and\n    any outstanding JavaScript [ArrayBuffer][] aliasing the linear memory are\n    detached.\n    * This would primarily allow hoisting bounds checks above effectful\n      operators.\n    * This can be viewed as a mild security measure under the assumption that\n      while the sandbox is still ensuring safety, the instance's internal state\n      is incoherent and further execution could lead to Bad Things (e.g., XSS\n      attacks).\n  * To allow for potentially more-efficient memory sandboxing, the semantics\n    could allow for a nondeterministic choice between one of the following when\n    an out-of-bounds access occurred.\n    * The ideal trap semantics.\n    * Loads return an unspecified value.\n    * Stores are either ignored or store to an unspecified location in the\n      linear memory.\n    * Either tooling or an explicit opt-in \"debug mode\" in the spec should allow\n      execution of a module in a mode that threw exceptions on out-of-bounds\n      access.\n\n  [ArrayBuffer]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer\n\n\n## Linear Memory Resizing\n\nTo allow efficient engines to employ virtual-memory based techniques for bounds\nchecking, memory sizes are required to be page-aligned.\nFor portability across a range of CPU architectures and operating systems,\nWebAssembly defines a fixed page size.\nPrograms can depend on this fixed page size and still remain portable across all\nWebAssembly engines.\n64KiB represents the least common multiple of many platforms and CPUs.\nIn the future, WebAssembly may offer the ability to use larger page sizes on\nsome platforms for increased TLB efficiency.\n\nThe `memory.grow` operator returns the old memory size. This is desirable for\nusing `memory.grow` independently on multiple threads, so that each thread can\nknow where the region it allocated starts. The obvious alternative would be for\nsuch threads to communicate manually, however WebAssembly implementations will likely\nalready be communicating between threads in order to properly allocate the sum\nof the allocation requests, so it's expected that they can provide the needed\ninformation without significant extra effort.\n\nThe [optional maximum size](Modules.md#linear-memory-section) is designed to\naddress a number of competing constraints:\n\n1. Allow WebAssembly modules to grab large regions of contiguous memory in a\n   32-bit address space early in an application's startup before the virtual\n   address space becomes fragmented by execution of the application.\n2. Allow many small WebAssembly instances to execute in a single 32-bit process.\n   (For example, it is common for a single web application to use dozens of\n   libraries, each of which may, over time, include WebAssembly modules as\n   implementation details.)\n3. Avoid *forcing* every developer using WebAssembly to understand their precise\n   maximum heap usage.\n4. When [threading and shared memory][future threads] are added to WebAssembly\n   post-MVP, the design should not require memory growth\n   to `realloc` since this implies significant implementation complexity,\n   security hazards, and optimization challenges.\n\nThe optional maximum addresses these constraints:\n\n* (1) is addressed by specifying a large maximum memory size. Simply setting a\n  large *initial* memory size has problems due to (3) and the fact that a\n  failure to allocate initial is a fatal error which makes the choice of \"how\n  big?\" difficult.\n* (2) and (3) are addressed by making the maximum optional combined with the\n  implied implementation that, on 32-bit, engines will not allocate\n  significantly more than the current memory size, *and* the compiler sets the\n  initial size to just enough to hold static data.\n* (4) is addressed assuming that, when threading is added, a new, optional\n  \"shared\" flag is added to the memory section that must be set to enable shared\n  memory and the shared flag forces the maximum to be specified. In this case,\n  shared memory never moves; the only thing that changes is that the bounds\n  grows which does not have all the abovementioned hazards. In particular, any\n  extant `SharedArrayBuffer`s that alias linear memory stay valid without\n  any updates.\n\n## Linear memory disabled if no linear memory section\n\nSee [#107](https://github.com/WebAssembly/spec/pull/107).\n\n\n## Control Flow\n\nStructured control flow provides simple and size-efficient binary encoding and\ncompilation. Any control flow--even irreducible--can be transformed into structured\ncontrol flow with the\n[Relooper](https://github.com/kripken/emscripten/raw/master/docs/paper.pdf)\n[algorithm](https://dl.acm.org/citation.cfm?id=2048224&CFID=670868333&CFTOKEN=46181900),\nwith guaranteed low code size overhead, and typically minimal throughput\noverhead (except for pathological cases of irreducible control\nflow). Alternative approaches can generate reducible control flow via node\nsplitting, which can reduce throughput overhead, at the cost of increasing\ncode size (potentially very significantly in pathological cases).\nAlso,\n[more expressive control flow constructs :unicorn:][future flow control]\nmay be added in the future.\n\n## Nop\n\nThe nop operator does not produce a value or cause side effects.\nIt 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.\n\n\n## Locals\n\nC/C++ makes it possible to take the address of a function's local values and\npass this pointer to callees or to other threads. Since WebAssembly's local\nvariables are outside the address space, C/C++ compilers implement address-taken\nvariables by creating a separate stack data structure within linear memory. This\nstack is sometimes called the \"aliased\" stack, since it is used for variables\nwhich may be pointed to by pointers.\n\nSince the aliased stack appears to the WebAssembly engine as normal memory,\nWebAssembly optimizations that would target the aliased stack need to be more\ngeneral, and thus more complicated. We observe that common compiler\noptimizations done before the WebAssembly code is produced, such as LLVM's\nglobal value numbering, effectively split address-taken variables into many\nsmall ranges that can often be allocated as local variables. Thus our\nexpectation that any loss of optimization potential here is minimal.\n\nConversely, non-address taken values which are usually on the stack are instead\nrepresented as locals inside functions. This effectively means that WebAssembly\nhas an infinite set of registers, and can choose to spill values as it sees fit\nin a manner unobservable to the hosted code. This implies that there's a\nseparate stack, unaddressable from hosted code, which is also used to spill\nreturn values. This allows strong security properties to be enforced, but does\nmean that two stacks are maintained (one by the VM, the other by the compiler\nwhich targets WebAssembly) which can lead to some inefficiencies.\n\nLocal variables are not in Static Single Assignment (SSA) form, meaning that\nmultiple incoming SSA values which have separate liveness can \"share\" the\nstorage represented by a local through the `set_local` operator. From an SSA\nperspective, this means that multiple independent values can share a local\nvariable in WebAssembly, which is effectively a kind of pre-coloring that clever\nproducers can use to pre-color variables and give hints to a WebAssembly VM's\nregister allocation algorithms, offloading some of the optimization work from\nthe WebAssembly VM.\n\n\n## Variable-Length Argument Lists (\"varargs\")\n\nC and C++ compilers are expected to implement variable-length argument lists by\nstoring arguments in a buffer in linear memory and passing a pointer to the\nbuffer. This greatly simplifies WebAssembly VM implementations by punting this\nABI consideration to the front-end compiler. It does negatively impact\nperformance, but variable-length calls are already somewhat slow.\n\n\n## Multiple Return Values\n\nWebAssembly's MVP does not support multiple return values from functions because\nthey aren't strictly necessary for the earliest anticipated use cases (and it's\na *minimum* viable product), and they would introduce some complexity for some\nimplementations. However, multiple return values are a very useful feature, and\nare relevant to ABIs, so it's likely to be added soon after the MVP.\n\n\n## Indirect Calls\n\nThe table-based scheme for indirect function calls was motivated by the need\nto represent function pointers as integer values that can be stored into the\nlinear memory, as well as to enforce basic safety properties such as\ncalling a function with the wrong signature does not destroy the safety\nguarantees of WebAssembly. In particular, an exact signature match implies\nan internal machine-level ABI match, which some engines require to ensure safety.\nAn indirection also avoids a possible information leak through raw code addresses.\n\nLanguages like C and C++ that compile to WebAssembly also imposed\nrequirements, such as the uniqueness of function pointers and the ability\nto compare function pointers to data pointers, or treat data as function\npointers.\n\nSeveral alternatives to direct indices with a heterogeneous indirect function table\nwere considered, from alternatives with multiple tables to statically typed function\npointers that can be mapped back and forth to integers. With the added complication\nof dynamic linking and dynamic code generation, none of these alternatives perfectly\nfit the requirements.\n\nThe current design requires two dynamic checks when invoking a function pointer:\na bounds check against the size of the indirect function table and a signature check\nfor the function at that index against an expected signature. Some dynamic optimization\ntechniques (e.g. inline caches, or a one-element cache), can reduce the number of\nchecks in common cases. Other techniques such as trading a bounds check for a mask or\nsegregating the table per signature to require only a bounds check could be considered\nin the future. Also, if tables are small enough, an engine can internally use per-signature\ntables filled with failure handlers to avoid one check.\n\n## Control Flow Instructions with Values\n\nControl flow instructions such as `br`, `br_if`, `br_table`, `if` and `if-else` can \ntransfer stack values in WebAssembly. These primitives are useful building blocks for \nWebAssembly producers, e.g. in compiling expression languages. It offers significant \nsize reduction by avoiding the need for `set_local`/`get_local` pairs in the common case \nof an expression with only one immediate use. Control flow instructions can then model\nexpressions with result values, thus allowing even more opportunities to further reduce\n`set_local`/`get_local` usage (which constitute 30-40% of total bytes in the\n[polyfill prototype](https://github.com/WebAssembly/polyfill-prototype-1)).\n`br`-with-value and `if` constructs that return values can also model `phis` which\nappear in SSA representations of programs.\n\n\n## Limited Local Nondeterminism\n\nThere are a few obvious cases where nondeterminism is essential to the API, such\nas random number generators, date/time functions or input events. The\nWebAssembly specification is strict when it comes to other sources of\n[limited local nondeterminism](Nondeterminism.md) of operators: it specifies\nall possible corner cases, and specifies a single outcome when this can be done\nreasonably.\n\nIdeally, WebAssembly would be fully deterministic because a fully deterministic\nplatform is easier to:\n\n* Reason about.\n* Implement.\n* Test portably.\n\nNondeterminism is only specified as a compromise when there is no other\npractical way to:\n\n* Achieve [portable](Portability.md) native performance.\n* Lower resource usage.\n* Reduce implementation complexity (both of WebAssembly VMs as well as compilers\n  generating WebAssembly binaries).\n* Allow usage of new hardware features.\n* Allows implementations to [security-harden](Security.md) certain usecases.\n\nWhen nondeterminism is allowed into WebAssembly it is always done in a limited\nand local manner. This prevents the entire program from being invalid, as would\nbe the case with C++ undefined behavior.\n\nAs WebAssembly gets implemented and tested with multiple languages on multiple\narchitectures we may revisit some of the design decisions:\n\n* When all relevant hardware implements an operation the same way, there's no\n  need for nondeterminism in WebAssembly semantics. One such\n  example is floating-point: at a high-level most operators follow\n  IEEE-754 semantics, it is therefore not necessary to specify WebAssembly's\n  floating-point operators differently from IEEE-754.\n* When different languages have different expectations then it's unfortunate if\n  WebAssembly measurably penalizes one's performance by enforcing determinism\n  which that language doesn't care about, but which another language may want.\n\n\n## NaN bit-pattern nondeterminism.\n\nNaNs produced by floating-point instructions in WebAssembly have\nnondeterministic bit patterns in most circumstances. The bit pattern of a NaN\nis not usually significant, however there are a few ways that it can be\nobserved:\n - a `reinterpret` conversion to an integer type\n - a `store` to linear memory followed by a load with a different type or index\n - a NaN stored to an imported or exported global variable or linear memory may\n   be observed by the outside environment\n - a NaN passed to a `call` or `call_indirect` to an imported function may\n   be observed by the outside environment\n - a return value of an exported function may be observed by the outside\n   environment\n - `copysign` can be used to copy the sign bit onto a non-NaN value, where\n   it then be observed\n\nThe motivation for nondeterminism in NaN bit patterns is that popular platforms\nhave differing behavior. IEEE 754-2019 makes some recommendations, but has few\nhard requirements in this area, and in practice there is significant divergence,\nfor example:\n - When an instruction with no NaN inputs produces a NaN output, x86 produces\n   a NaN with the sign bit set, while ARM and others produce a NaN with it\n   unset.\n - When an instruction has multiple NaN inputs, x86 always returns the first\n   NaN (converted to a quiet NaN if needed), while ARMv8 returns the first\n   signaling NaN (converted to a quiet NaN) if one is present, and otherwise\n   returns the first quiet NaN.\n - Some hardware architectures have found that returning one of the input NaNs\n   has a cost, and prefer to return a NaN with a fixed bit pattern instead.\n - LLVM (used in some WebAssembly implementations) doesn't guarantee that it\n   won't commute `fadd`, `fmul` and other instructions, so it's not possible\n   to rely on the \"first\" NaN being preserved as such.\n - IEEE 754-2019 itself recommends architectures use NaN bits to provide\n   architecture-specific debugging facilities.\n\nIEEE 754-2019 6.2 says that instructions returning a NaN *should* return one of\ntheir input NaNs. In WebAssembly, implementations may do this, however they are\nnot required to. Since IEEE 754-2019 states this as a \"should\" (as opposed to a\n\"shall\"), it isn't a requirement for IEEE 754-2019 conformance.\n\nAn alternative design would be to require engines to always \"canonicalize\"\nNaNs whenever their bits could be observed. This would eliminate the\nnondeterminism and provide slightly better portability, since it would hide\nhardware-specific NaN propagation behavior. However, it is theorized that this\nwould add an unacceptable amount of overhead, and that the benefit is marginal\nsince most programs are unaffected by this issue.\n\n\n## Support for NaN-boxing.\n\nIn general, WebAssembly's floating point instructions provide the guarantee that\nif all NaNs passed to an instruction are \"canonical\", the result is \"canonical\",\nwhere canonical means the most significant bit of the fraction field is 1, and\nthe trailing bits are all 0.\n\nThis is intended to support interpreters running on WebAssembly that use\nNaN-boxing, because they don't have to canonicalize the output of an arithmetic\ninstruction if they know the inputs are canonical.\n\nWhen one or more of the inputs of an instruction are non-canonical NaNs, the\nresulting NaN bit pattern is nondeterministic. This is intended to accommodate\nthe diversity in NaN behavior among popular hardware architectures.\n\nNote that the sign bit is still nondeterministic in a canonical NaN. This is\nalso to accommodate popular hardware architectures; for example, x86 generates\nNaNs with the sign bit set to 1 while other architectures generate NaNs with it\nset to 0. And as above, the cost of canonicalizing NaNs is believed to be\ngreater than the benefit.\n\nNaNs generated by JS or other entities in the external environment are not\nrequired to be canonical, so exported function arguments, imported function\nreturn values, and values stored in exported variables or memory may be\nnon-canonical.\n\n\n## Integer operations\n\nWebAssembly's signed integer divide rounds its result toward zero. This is not\nbecause of a lack of sympathy for\n[better alternatives](https://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html),\nbut out of practicality. Because all popular hardware today implements\nrounding toward zero, and because C and many other languages now specify\nrounding to zero, having WebAssembly in the middle doing something different\nwould mean divisions would have to be doubly complicated.\n\nSimilarly, WebAssembly's shift operators mask their shift counts to the number\nof bits in the shifted value. Confusingly, this means that shifting a 32-bit\nvalue by 32 bits is an identity operation, and that a left shift is not\nequivalent to a multiplication by a power of 2 because the overflow behavior\nis different. Nevertheless, because several popular hardware architectures\ntoday implement this masking behavior, and those that don't can typically\nemulate it with a single extra mask instruction, and because several popular\nsource languages, including JavaScript and C#, have come to specify this\nbehavior too, we reluctantly adopt this behavior as well.\n\nWebAssembly has three classes of integer operations: signed, unsigned, and\nsign-agnostic. The signed and unsigned instructions have the property that\nwhenever they can't return their mathematically expected value (such as when\nan overflow occurs, or when their operand is outside their domain), they\ntrap, in order to avoid silently returning an incorrect value.\n\nNote that the `add`, `sub`, and `mul` operators are categorized as\nsign-agnostic. Because of the magic of two's complement representation, they\nmay be used for both signed and unsigned purposes. Note that this (very\nconveniently!) means that engines don't need to add extra overflow-checking\ncode for these most common of arithmetic operators on the most popular\nhardware platforms.\n\n\n## Motivating Scenarios for Feature Testing\n\n1. [Post-MVP :unicorn:][future general],\n[`i32.bitrev` :unicorn:][future bitrev] is introduced. A\nWebAssembly developer updates their toolkit so that the compiler may leverage\n`i32.bitrev`. The developer's WebAssembly module works correctly both on\nexecution environments at MVP, as well as those supporting `i32.bitrev`.\n\n  * A variant of this, where a few more new opcodes are available, the compiler\nis updated to be able to leverage all of them, but not all execution targets\nsupport all of them. The developer wants to reach as many of their customers as\npossible, while at the same time providing them with the best experience\npossible. The developer has to balance the cost of the test matrix resulting\nfrom the combinations of possible feature configurations.\n\n2. [Post-MVP :unicorn:][future general], module authors may now use\n[Threading][future threads]\nAPIs in the browser. A developer wants to leverage multithreading in their\nmodule.\n\n  * In one variant of the scenario, our developer does not want to pay the\nengineering cost of developing and supporting a threaded and non-threaded\nversion of their code. They opt not to support MVP targets, and only support\npost-MVP targets. End-users (browser users) get some message indicating they\nneed MVP support.\n\n  * In another variant, our developer explicitly authors both MVP-only and post-\nMVP (with threads) code.\n\n3. [SIMD][future simd] support is not universally\nequivalent on all targets. While polyfill variants of SIMD APIs are available,\na developer prefers writing dedicated SIMD and non-SIMD versions of their\ncompression algorithm, because the non-SIMD version performs better in\nenvironments without SIMD support, when compared to the SIMD polyfill. They\npackage their compression code for reuse by third parties.\n\n4. An application author is assembling together an application by reusing\nmodules such as those developed in the scenarios above. The application author's\ndevelopment environment is able to quickly and correctly identify the platform\ndependencies (e.g. threading, SIMD) and communicate back to the application\nauthor the implications these dependencies have on the end-application. Some\nAPIs exposed from the threading-aware module are only pertinent to environments\nsupporting threading. As a consequence, the application author needs to write\nspecialized code when threads are/are not supported. (Note: we should understand\nthis scenario for both forms of WebAssembly reuse currently imagined: dynamic\nlinking and static imports.)\n\n5. The compression algorithm described in scenario 3 is deployed on a\nrestrictive execution environment, as part of an application. In this\nenvironment, a process may not change memory page access protection flags (e.g.\ncertain gaming consoles, to investigate server side deployment scenarios). The\ncompression module is compiled by the WebAssembly environment, enabling the\nconfiguration most specific to the target (i.e. with/without Threads, SIMD,\netc).\n\n  * A variant of this scenario where the environment is additionally separating\nstorage into system-visible and application-visible, the latter not being able\nto contain machine-executable code (certain phones, to investigate if gaming\nconsoles or server side have a similar sandboxing mechanism).\n\n\n## Why a binary encoding?\n\nGiven that text is so compressible and it is well known that it is hard to beat\ngzipped source, is there any win from having a binary format over a text format?\nYes:\n\n* Large reductions in payload size can still significantly decrease the\n  compressed file size.\n  * Experimental results from a\n    [polyfill prototype](https://github.com/WebAssembly/polyfill-prototype-1) show the\n    gzipped binary format to be about 20-30% smaller than the corresponding\n    gzipped asm.js.\n* A binary format that represents the names of variables and functions with raw\n  indices instead of strings is much faster to decode: array indexing\n  vs. dictionary lookup.\n  * Experimental results from a\n    [polyfill prototype](https://github.com/WebAssembly/polyfill-prototype-1) show that\n    decoding the binary format is about 23× faster than parsing the\n    corresponding asm.js source (using\n    [this demo](https://github.com/lukewagner/AngryBotsPacked), comparing\n    *just* parsing in SpiderMonkey (no validation, IR generation) to *just*\n    decoding in the polyfill (no asm.js code generation).\n* A binary format allows many optimizations for code size and decoding speed that would\n  not be possible on a source form.\n\n\n## Why a layered binary encoding?\n* We can do better than generic compression because we are aware of the code\n  structure and other details:\n  * For example, macro compression that\n    [deduplicates AST trees](https://github.com/WebAssembly/design/issues/58#issuecomment-101863032)\n    can focus on ASTs + their children, thus having `O(nodes)` entities\n    to worry about, compared to generic compression which in principle would\n    need to look at `O(bytes*bytes)` entities.  Such macros would allow the\n    logical equivalent of `#define ADD1(x) (x+1)`, i.e., to be\n    parameterized. Simpler macros (`#define ADDX1 (x+1)`) can implement useful\n    features like constant pools.\n  * Another example is reordering of functions and some internal nodes, which\n    we know does not change semantics, but\n    [can improve general compression](https://www.rfk.id.au/blog/entry/cromulate-improve-compressibility/).\n* JITs and simple developer tooling do not benefit from compression, so layering allows\n  the related development and maintenance burden to be offloaded to reusable tools/libraries.\n* Each of the layers works to find compression opportunities to the best of\n  its abilities, without encroaching upon the subsequent layer's compression\n  opportunities.\n* [Existing web standards](https://www.w3.org/TR/PNG/) demonstrate many of\n  the advantages of a layered encoding strategy.\n\n\n## Why \"polymorphic\" stack typing after control transfer?\n\nFor 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.\nAt the same time, type checking should be fast, so be expressible by a linear traversal.\n\nThere 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.\nConsequently, no constraint has to be imposed between the two regarding the stack.\nIn a linear type checking algorithm this can be expressed by allowing to assume any type of stack.\nIn type system terms, the instruction can thus be said to be _polymorphic_ in its stack type.\n\nThis 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:\n\n* It is composable: if instruction sequences A and B are valid, then block(A,B) is valid (e.g. at empty stack type).\n* It is decomposable: if block(A,B) is valid, then both A and B are valid.\n* It generalises an expression language: every expression is directly expressible, even if it contains control transfer.\n* 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).\n* It maintains basic transformations: for example, (i32.const 1) (br_if $l) can always be replaced with (br $l).\n\nSome of these properties are relevant to support certain compilation techniques without artificial complication for producers.\nAs a small but representative example, consider a textbook one-pass compiler, which would often use something like the following scheme for compiling expressions:\n```\ncompile(A + B) = compile(A); compile(B); emit(i32.add)\ncompile(A / B) = compile(A); compile(B); emit(dup i32.eqz (br_if $div_zero) drop i32.div)\ncompile(A / 0) = compile(A); emit(br $div_zero)\n```\nThe third case is a specialisation of the second, a simple optimisation.\nWithout 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.\nSimilar situations arise in production compilers, for example, in the asm.js-to-wasm compilers that some of the WebAssembly VMs/tools are implementing.\n\nOther solutions that have been discussed would lose most of the above properties. For example:\n\n* Disallowing certain forms of unreachable code (whether by rules or by construction) would break all but decomposability.\n* 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).\n* Requiring the stack to be empty after a jump remains agnostic to reachability and maintains decomposability, but still breaks all other properties.\n\nIt is worth noting that this kind of type checking, in general, is not unusual.\nFor 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).\nMoreover, programming languages that allow control transfer _expressions_ usually type them polymorphically as well (e.g., `throw`/`raise`, which is an expression in some languages).\n\n\n[future general]: FutureFeatures.md\n[future flow control]: https://github.com/WebAssembly/design/issues/796\n[future bitrev]: https://github.com/WebAssembly/design/issues/1382\n[future threads]: https://github.com/WebAssembly/design/issues/1073\n[future simd]: https://github.com/WebAssembly/design/issues/1075\n[future garbage collection]: https://github.com/WebAssembly/proposals/issues/16\n"
  },
  {
    "path": "Security.md",
    "content": "# Security\n\nThe security model of WebAssembly has two important goals: (1) protect *users*\nfrom buggy or malicious modules, and (2) provide *developers* with useful\nprimitives and mitigations for developing safe applications, within the\nconstraints of (1).\n\n## Users\n\nEach WebAssembly module executes within a sandboxed environment separated from\nthe host runtime using fault isolation techniques. This implies:\n\n  * Applications execute independently, and can't escape the sandbox without\n  going through appropriate APIs.\n  * Applications generally execute deterministically\n  [with limited exceptions](Nondeterminism.md).\n\nAdditionally, each module is subject to the security policies of its embedding.\nWithin a [web browser](Web.md), this includes restrictions on information flow\nthrough [same-origin policy][]. On a [non-web](NonWeb.md) platform, this could\ninclude the POSIX security model.\n\n## Developers\n\nThe design of WebAssembly promotes safe programs by eliminating dangerous\nfeatures from its execution semantics, while maintaining compatibility with\nprograms written for [C/C++](CAndC%2B%2B.md).\n\nModules must declare all accessible functions and their associated types\nat load time, even when [dynamic linking](DynamicLinking.md) is used. This\nallows implicit enforcement of [control-flow integrity][] (CFI) through\nstructured control-flow. Since compiled code is immutable and not observable at\nruntime, WebAssembly programs are protected from control flow hijacking attacks.\n\n  * [Function calls](Semantics.md#calls) must specify the index of a target\n  that corresponds to a valid entry in the\n  [function index space](Modules.md#function-index-space) or\n  [table index space](Modules.md#table-index-space).\n  * [Indirect function calls](Rationale.md#indirect-calls) are subject to a type\n  signature check at runtime; the type signature of the selected indirect\n  function must match the type signature specified at the call site.\n  * A protected call stack that is invulnerable to buffer overflows in the\n  module heap ensures safe function returns.\n  * [Branches](Semantics.md#branches-and-nesting) must point to valid\n  destinations within the enclosing function.\n\nVariables in C/C++ can be lowered to two different primitives in WebAssembly,\ndepending on their scope. [Local variables](Semantics.md#local-variables)\nwith fixed scope and [global variables](Semantics.md#global-variables) are\nrepresented as fixed-type values stored by index. The former are initialized\nto zero by default and are stored in the protected call stack, whereas\nthe latter are located in the [global index space](Modules.md#global-index-space)\nand can be imported from external modules. Local variables with\n[unclear static scope](Rationale.md#locals) (e.g. are used by the address-of\noperator, or are of type `struct` and returned by value) are stored in a separate\nuser-addressable stack in [linear memory](Semantics.md#linear-memory) at\ncompile time. This is an isolated memory region with fixed maximum size that is\nzero initialized by default. References to this memory are computed with\ninfinite precision to avoid wrapping and simplify bounds checking. WebAssembly\nmodules may also have [multiple linear memory sections], which are independent\nof each other. In the future,\n[finer-grained memory operations][future memory control]\n(e.g. shared memory, page protection, large pages, etc.) may be implemented.\n\n[Traps](Semantics.md#traps) are used to immediately terminate execution and\nsignal abnormal behavior to the execution environment. In a browser, this is\nrepresented as a JavaScript exception. Support for\nmodule-defined trap handlers\nmay be implemented in the future. Operations that can trap include:\n\n  * specifying an invalid index in any index space,\n  * performing an indirect function call with a mismatched signature,\n  * exceeding the maximum size of the protected call stack,\n  * accessing [out-of-bounds](#Rationale.md#out-of-bounds) addresses in linear\n  memory,\n  * executing an illegal arithmetic operations (e.g. division or remainder by\n  zero, signed division overflow, etc).\n\n### Memory Safety\nCompared to traditional C/C++ programs, these semantics obviate certain classes\nof memory safety bugs in WebAssembly. Buffer overflows, which occur when data\nexceeds the boundaries of an object and accesses adjacent memory regions, cannot\naffect local or global variables stored in index space, they are fixed-size and\naddressed by index. Data stored in linear memory can overwrite adjacent objects,\nsince bounds checking is performed at linear memory region granularity and is\nnot context-sensitive. However, the presence of control-flow integrity and\nprotected call stacks prevents direct code injection attacks. Thus,\ncommon mitigations such as [data execution prevention][] (DEP) and\n[stack smashing protection][] (SSP) are not needed by WebAssembly programs.\n\nAnother common class of memory safety errors involves unsafe pointer usage and\n[undefined behavior](CAndC%2B%2B.md#undefined-behavior). This includes\ndereferencing pointers to unallocated memory (e.g. `NULL`), or freed memory\nallocations. In WebAssembly, the semantics of pointers have been eliminated for\nfunction calls and variables with fixed static scope, allowing references to\ninvalid indexes in any index space to trigger a validation error at load time,\nor at worst a trap at runtime. Accesses to linear memory are bounds-checked at\nthe region level, potentially resulting in a trap at runtime. These memory\nregion(s) are isolated from the internal memory of the runtime, and are set to\nzero by default unless otherwise initialized.\n\nNevertheless, other classes of bugs are not obviated by the semantics of\nWebAssembly. Although attackers cannot perform direct code injection attacks,\nit is possible to hijack the control flow of a module using code reuse attacks\nagainst indirect calls. However, conventional [return-oriented programming][]\n(ROP) attacks using short sequences of instructions (\"gadgets\") are not possible\nin WebAssembly, because control-flow integrity ensures that call targets are\nvalid functions declared at load time. Likewise, race conditions, such as\n[time of check to time of use][] (TOCTOU) vulnerabilities, are possible in\nWebAssembly, since no execution or scheduling guarantees are provided beyond\nin-order execution and [atomic memory primitives][threads].\nSimilarly, [side channel attacks][] can occur, such as timing attacks against\nmodules. In the future, additional protections may be provided by runtimes or\nthe toolchain, such as code diversification or memory randomization (similar to\n[address space layout randomization][] (ASLR)), or [bounded pointers][] (\"fat\"\npointers).\n\n### Control-Flow Integrity\nThe effectiveness of control-flow integrity can be measured based on its\ncompleteness. Generally, there are three types of external control-flow\ntransitions that need to be protected, because the callee may not be trusted:\n  1. Direct function calls,\n  2. Indirect function calls,\n  3. Returns.\n\nTogether, (1) and (2) are commonly referred to as \"forward-edge\", since they\ncorrespond to forward edges in a directed control-flow graph. Likewise (3) is\ncommonly referred to as \"back-edge\", since it corresponds to back edges in a\ndirected control-flow graph. More specialized function calls, such as tail\ncalls, can be viewed as a combination of (1) and (3).\n\nTypically, this is implemented using runtime instrumentation. During\ncompilation, the compiler generates an expected control flow graph of program\nexecution, and inserts runtime instrumentation at each call site to verify that\nthe transition is safe. Sets of expected call targets are constructed from the\nset of all possible call targets in the program, unique identifiers are assigned\nto each set, and the instrumentation checks whether the current call target is\na member of the expected call target set. If this check succeeds, then the\noriginal call is allowed to proceed, otherwise a failure handler is executed,\nwhich typically terminates the program.\n\nIn WebAssembly, the execution semantics implicitly guarantee the safety of (1)\nthrough usage of explicit function section indexes, and (3) through a protected\ncall stack. Additionally, the type signature of indirect function calls is\nalready checked at runtime, effectively implementing coarse-grained type-based\ncontrol-flow integrity for (2). All of this is achieved without explicit runtime\ninstrumentation in the module. However, as discussed\n[previously](#memory-safety), this protection does not prevent code reuse\nattacks with function-level granularity against indirect calls.\n\n#### Clang/LLVM CFI\nThe Clang/LLVM compiler infrastructure includes a [built-in implementation] of\nfine-grained control flow integrity, which has been extended to support the\nWebAssembly target. It is available in Clang/LLVM with the\n[WebAssembly backend].\n\nEnabling fine-grained control-flow integrity (by passing `-fsanitize=cfi` to\nemscripten) has a number of advantages over the default WebAssembly\nconfiguration. Not only does this better defend against code reuse attacks that\nleverage indirect function calls (2), but it also enhances the built-in function\nsignature checks by operating at the C/C++ type level, which is semantically\nricher that the WebAssembly [type level](Semantics.md#types), which consists\nof only four value types. Currently, enabling this feature has a small\nperformance cost for each indirect call, because an integer range check is\nused to verify that the target index is trusted, but this may be eliminated in\nthe future by leveraging built-in support for\n[multiple indirect tables] with homogeneous type\nin WebAssembly.\n\n  [address space layout randomization]: https://en.wikipedia.org/wiki/Address_space_layout_randomization\n  [bounded pointers]: https://en.wikipedia.org/wiki/Bounded_pointer\n  [built-in implementation]: https://clang.llvm.org/docs/ControlFlowIntegrity.html\n  [control-flow integrity]: https://research.microsoft.com/apps/pubs/default.aspx?id=64250\n  [data execution prevention]: https://en.wikipedia.org/wiki/Executable_space_protection\n  [forward-edge control-flow integrity]: https://www.usenix.org/node/184460\n  [new WebAssembly backend]: https://github.com/WebAssembly/binaryen#cc-source--webassembly-llvm-backend--s2wasm--webassembly\n  [return-oriented programming]: https://en.wikipedia.org/wiki/Return-oriented_programming\n  [same-origin policy]: https://www.w3.org/Security/wiki/Same_Origin_Policy\n  [side channel attacks]: https://en.wikipedia.org/wiki/Side-channel_attack\n  [stack smashing protection]: https://en.wikipedia.org/wiki/Buffer_overflow_protection#Random_canaries\n  [time of check to time of use]: https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use\n\n[multiple linear memory sections]: https://github.com/WebAssembly/multi-memory/blob/main/proposals/multi-memory/Overview.md\n[multiple indirect tables]: https://github.com/WebAssembly/reference-types/blob/master/proposals/reference-types/Overview.md\n[threads]: https://github.com/WebAssembly/threads/blob/main/proposals/threads/Overview.md\n[future memory control]: https://github.com/WebAssembly/memory-control\n"
  },
  {
    "path": "Semantics.md",
    "content": "# Semantics\n\nThis file historically contained the description of WebAssembly's instruction set.\n\nFor the current description, see the [normative documentation](http://webassembly.github.io/spec/core/exec/index.html).\n"
  },
  {
    "path": "TextFormat.md",
    "content": "# Text Format\n\nThis file historically contained the description of WebAssembly's text format.\n\nFor the current description, see the [normative documentation](http://webassembly.github.io/spec/core/text/index.html).\n"
  },
  {
    "path": "Tooling.md",
    "content": "# Tooling support\n\nTooling for in-browser execution is often of uneven quality. WebAssembly aims at\nmaking it possible to support truly great tooling by exposing\n[low-level capabilities][] instead of prescribing which tooling should be\nbuilt. This enables:\n\n* Porting of existing and familiar tooling to WebAssembly;\n* Building new tooling that's particularly well suited to WebAssembly.\n\n  [low-level capabilities]: https://extensiblewebmanifesto.org\n\nWebAssembly development should be self-hosting, and not just as a cute hack but\nas enjoyable platform that developers actively seek out because the tools they\nwant and need *just work*. Developers have high expectations, and meeting these\nexpectations on tooling means WebAssembly has the features required to build\nrich applications for non-developers.\n\nThe tooling we expect to support includes:\n\n* Editors:\n  - Editors such as vim and emacs should *just work*.\n* Compilers and language virtual machines:\n  - Compilers for languages which can target WebAssembly (C/C++, Rust, Go, C#)\n    should be able to run in WebAssembly themselves, emit a WebAssembly module\n    that can then be executed.\n  - Virtual machines for languages such as bash, Python, Ruby should work.\n  - Virtual machines which use a just-in-time compiler (JavaScript VMs, luajit,\n    pypy) should be able to support a new just-in-time backend for WebAssembly.\n* Debuggers:\n  - Basic browser integration can be done through source map support.\n  - Full integration for languages like C++ require more standardization effort\n    on debugging information format as well as permissions for interrupting\n    programs, inspecting their state, modifying their state.\n  - Debug information is better delivered on-demand instead of built-in to a\n    WebAssembly module.\n* Sanitizers for [non-memory-safe](Security.md#memory-safety) languages: asan,\n  tsan, msan, ubsan. Efficient support of sanitizers may require improving:\n  - Trapping support;\n  - Shadow stack techniques (often implemented through `mmap`'s `MAP_FIXED`).\n* Opt-in [security](Security.md) enhancements for developers' own code:\n  developers targeting WebAssembly may want their own code to be sandboxed\n  further than what WebAssembly implementations require to protect users.\n* Profilers:\n  - Sample-based;\n  - Instrumentation-based.\n* Process dump: local variables, call stack, heap, global variables, list of\n  threads.\n* JavaScript+WebAssembly size optimization tool: huge WebAssembly+JavaScript\n  mixed applications, WebAssembly calling to JavaScript libraries which\n  communicate with the rest of the Web platform, need tooling to perform\n  dead code stripping and global optimization across the API boundary.\n\nIn many cases, the tooling will be pure WebAssembly without any tool-specific\nsupport from WebAssembly. This won't be possible for debugging, but should be\nentirely possible for sanitizers.\n"
  },
  {
    "path": "UseCases.md",
    "content": "# Use Cases\n\nWebAssembly's [high-level goals](HighLevelGoals.md) define *what* WebAssembly\naims to achieve, and in *which order*. *How* WebAssembly achieves its goals is\ndocumented for [Web](Web.md) and [non-Web](NonWeb.md) platforms. The following\nis an unordered and incomplete list of applications/domains/computations that\nwould benefit from WebAssembly and are being considered as use cases during the\ndesign of WebAssembly.\n\n## Inside the browser\n\n* Better execution for languages and toolkits that are currently cross-compiled\n  to the Web (C/C++, GWT, …).\n* Image / video editing.\n* Games:\n  - Casual games that need to start quickly.\n  - AAA games that have heavy assets.\n  - Game portals (mixed-party/origin content).\n* Peer-to-peer applications (games, collaborative editing, decentralized and\n  centralized).\n* Music applications (streaming, caching).\n* Image recognition.\n* Live video augmentation (e.g. putting hats on people's heads).\n* VR and augmented reality (very low latency).\n* CAD applications.\n* Scientific visualization and simulation.\n* Interactive educational software, and news articles.\n* Platform simulation / emulation (ARC, DOSBox, QEMU, MAME, …).\n* Language interpreters and virtual machines.\n* POSIX user-space environment, allowing porting of existing POSIX applications.\n* Developer tooling (editors, compilers, debuggers, …).\n* Remote desktop.\n* VPN.\n* Encryption.\n* Local web server.\n* Common NPAPI users, within the web's security model and APIs.\n* Fat client for enterprise applications (e.g. databases).\n\n## Outside the browser\n\n* Game distribution service (portable and secure).\n* Server-side compute of untrusted code.\n* Server-side application.\n* Hybrid native apps on mobile devices.\n* Symmetric computations across multiple nodes\n\n## How WebAssembly can be used\n\n* Entire code base in WebAssembly.\n* Main frame in WebAssembly, but the UI is in JavaScript / HTML.\n* Re-use existing code by targeting WebAssembly, embedded in a larger\n  JavaScript / HTML application. This could be anything from simple helper\n  libraries, to compute-oriented task offload.\n"
  },
  {
    "path": "Web.md",
    "content": "# Web Embedding\n\nUnsurprisingly, one of WebAssembly's primary purposes is to run on the Web,\nfor example embedded in Web browsers (though this is\n[not its only purpose](NonWeb.md)).\n\nThis means integrating with the Web ecosystem, leveraging Web APIs, supporting\nthe Web's security model, preserving the Web's portability, and designing in\nroom for evolutionary development. Many of these goals are clearly\nreflected in WebAssembly's [high-level goals](HighLevelGoals.md). In\nparticular, WebAssembly MVP will be no looser from a security point of view\nthan if the module was JavaScript.\n\nMore concretely, the following is a list of points of contact between WebAssembly\nand the rest of the Web platform that have been considered:\n\n## JavaScript API\n\nA [JavaScript API](JS.md) is provided which allows JavaScript to compile\nWebAssembly modules, perform limited reflection on compiled modules, store\nand retrieve compiled modules from offline storage, instantiate compiled modules\nwith JavaScript imports, call the exported functions of instantiated modules,\nalias the exported memory of instantiated modules, etc.\n\nThe Web embedding includes additional methods useful in that context.\nIn non-web embeddings, these APIs may not be present.\n\n### Additional Web Embedding API\n\nThis section historically contained the description of WebAssembly's Web API.\n\nFor the current description, see the [normative documentation](https://webassembly.github.io/spec/web-api/index.html).\n\n## Modules\n\nWebAssembly's [modules](Modules.md) allow for natural [integration with\nthe ES6 module system](https://github.com/WebAssembly/esm-integration).\n\n## Security\n\nWebAssembly's [security](Security.md) model depend on the\n[same-origin policy], with [cross-origin resource sharing (CORS)] and\n[subresource integrity] to enable distribution through content\ndistribution networks and to implement [dynamic linking](DynamicLinking.md).\n\n## WebIDL\n\nThere are various proposals in flight which may support future work toward\nWebIDL bindings for WebAssembly, including [JS String builtins],\n[source-phase imports], and the [component model].\n\nThere are also tools to provide this functionality today by generating\nJS wrapper code, for example [Emscripten's WebIDL Binder],\n[the wasm-webidl-bindings Rust crate], and\n[jco's experimental WebIDL Imports support].\n\n[same-origin policy]: https://www.w3.org/Security/wiki/Same_Origin_Policy\n[cross-origin resource sharing (CORS)]: https://www.w3.org/TR/cors/\n[subresource integrity]: https://www.w3.org/TR/SRI/\n[JS String builtins]: https://github.com/WebAssembly/js-string-builtins/\n[source-phase imports]: https://github.com/tc39/proposal-source-phase-imports\n[component model]: https://github.com/WebAssembly/component-model\n\n[Emscripten's WebIDL Binder]: https://emscripten.org/docs/porting/connecting_cpp_and_javascript/WebIDL-Binder.html\n[the wasm-webidl-bindings Rust crate]: https://github.com/rustwasm/wasm-webidl-bindings\n[jco's experimental WebIDL Imports support]: https://github.com/bytecodealliance/jco/blob/main/docs/src/transpiling.md#experimental-webidl-imports\n"
  }
]