### Install a Tool or SDK Source: https://emscripten.org/docs/tools_reference/emsdk.html Downloads and installs a specified tool or SDK. Replace with the target name. ```bash ./emsdk install ``` -------------------------------- ### Install SDK Target with Specific Tools Source: https://emscripten.org/docs/tools_reference/emsdk.html Install an SDK target by explicitly listing all required tools. This provides more granular control over the installed components. ```bash ./emsdk install git-1.8.3 clang-upstream-main-64bit node-0.10.17-64bit python-2.7.5.3-64bit java-7.45-64bit llvm-git-main-64bit emscripten-main-64bit ``` -------------------------------- ### Quick Toolchain Profiling Example Source: https://emscripten.org/docs/optimizing/Profiling-Toolchain.html Run this sequence to get a basic HTML profile of the toolchain's compilation process. Ensure you are in the Emscripten directory and set the EMPROFILE environment variable. ```bash cd path/to/emscripten export EMPROFILE=1 emcc test/hello_world.c -O3 -o a.html emprofile ``` -------------------------------- ### Install an SDK Target Source: https://emscripten.org/docs/tools_reference/emsdk.html Install a predefined SDK target, which bundles a specific release of Emscripten and its associated tools. This is a convenient way to get a complete Emscripten environment. ```bash ./emsdk install sdk-upstream-main-64bit ``` -------------------------------- ### Install a Specific Tool or SDK Version Source: https://emscripten.org/docs/tools_reference/emsdk.html Downloads and installs a new tool or SDK version by its name. ```bash ./emsdk install ``` ```bash ./emsdk install sdk-1.38.21-64bit ``` -------------------------------- ### Check Installed Tools Source: https://emscripten.org/docs/building_from_source/toolchain_what_is_needed.html These commands verify the presence and versions of essential tools like Python, Node.js, Git, Java, GCC/G++, and CMake. This helps in confirming your environment setup. ```bash # Check for Python python --version # Check for Node.js node --version # Check for Git git --version # Check for Java java -version # Check for gcc / g++ gcc --version g++ # Check for cmake cmake ``` -------------------------------- ### Windows .emscripten Configuration Example Source: https://emscripten.org/docs/tools_reference/emsdk.html An example of the .emscripten configuration file on Windows, showing paths to LLVM and Node.js. ```python # .emscripten file from Windows SDK import os LLVM_ROOT='C:/Program Files/Emscripten/clang/e1.21.0_64bit' NODE_JS='C:/Program Files/Emscripten/node/0.10.17_64bit/node.exe' ``` -------------------------------- ### Install Latest Emscripten SDK Source: https://emscripten.org/docs/tools_reference/emsdk.html Fetches the latest tool registry, downloads and installs the most recent SDK, and activates it for use. ```bash # Fetch the latest registry of available tools. ./emsdk update # Download and install the latest SDK tools. ./emsdk install latest # Set up the compiler configuration to point to the "latest" SDK. ./emsdk activate latest ``` -------------------------------- ### Install and Activate Emscripten SDK Source: https://emscripten.org/docs/contributing/developers_guide.html Installs the latest tip-of-tree binaries for Emscripten and activates them. These are needed for contributing to core Emscripten code. ```bash emsdk install tot emsdk activate tot ``` -------------------------------- ### Install and Activate SDK from Main Branch Source: https://emscripten.org/docs/tools_reference/emsdk.html Build and activate the Emscripten SDK from the main branch by installing git, cloning the latest emscripten-core/emscripten/main, and setting it as the active version. ```bash # Install git (Skip if the system already has it). ./emsdk install git-1.8.3 # Clone+pull the latest emscripten-core/emscripten/main. ./emsdk install sdk-main-64bit # Set this as the active version. ./emsdk activate sdk-main-64bit ``` -------------------------------- ### Linux .emscripten Configuration Example Source: https://emscripten.org/docs/tools_reference/emsdk.html An example of the .emscripten configuration file on Linux, specifying Node.js and LLVM root paths. ```python # .emscripten file from Linux SDK import os NODE_JS = 'node' LLVM_ROOT='/home/ubuntu/emsdk/upstream/bin' ``` -------------------------------- ### Emscripten Fetch Progress and Management Example Source: https://emscripten.org/docs/api_reference/fetch.html This example demonstrates how to track download progress using the onprogress callback and manage fetch requests with attributes like request method, load destination, and error/success handlers. It also shows how to initiate a fetch request. ```c void downloadProgress(emscripten_fetch_t *fetch) { if (fetch->totalBytes) { printf("Downloading %s.. %.2f%% complete.\n", fetch->url, fetch->dataOffset * 100.0 / fetch->totalBytes); } else { printf("Downloading %s.. %lld bytes complete.\n", fetch->url, fetch->dataOffset + fetch->numBytes); } } int main() { emscripten_fetch_attr_t attr; emscripten_fetch_attr_init(&attr); strcpy(attr.requestMethod, "GET"); attr.attributes = EMSCRIPTEN_FETCH_LOAD_TO_MEMORY; attr.onsuccess = downloadSucceeded; attr.onprogress = downloadProgress; attr.onerror = downloadFailed; emscripten_fetch(&attr, "myfile.dat"); } ``` -------------------------------- ### Install Latest Emscripten SDK Source: https://emscripten.org/docs/getting_started/downloads.html Download and install the latest SDK tools. ```bash ./emsdk install latest ``` -------------------------------- ### Set Binaryen Root Directory Source: https://emscripten.org/docs/building_from_source/configuring_emscripten_settings.html Example of how to specify the BINARYEN_ROOT variable within the .emscripten configuration file. Ensure the path points to your Binaryen installation. ```python BINARYEN_ROOT = 'C:\\tools\\binaryen\\' ``` -------------------------------- ### File Content Example Source: https://emscripten.org/docs/getting_started/Tutorial.html This is the expected content of the 'test/hello_world_file.txt' file that the C++ code will read. ```text == This data has been read from a file. The file is readable as if it were at the same location in the filesystem, including directories, as in the local filesystem where you compiled the source. == ``` -------------------------------- ### Install Sphinx Dependencies Source: https://emscripten.org/docs/site/about.html Ensures the correct version of Sphinx is installed for building the site. Run this command in your development environment. ```bash pip install -r requirements-dev.txt ``` -------------------------------- ### Compilation Command for Async Fetch Example Source: https://emscripten.org/docs/porting/asyncify.html Command to compile the C code for the async fetch example. Requires Asyncify or JSPI and outputting to an HTML file. ```bash emcc example.c -O3 -o a.html -s ``` -------------------------------- ### Install Individual Tools or Groups Source: https://emscripten.org/docs/tools_reference/emsdk.html Install specific tools or a collection of tools by their identifiers. This can be done for single tools or multiple tools at once. ```bash ./emsdk install node-0.10.17-64bit ``` ```bash ./emsdk install node-0.10.17-64bit java-7.45-64bit ``` -------------------------------- ### Install Emscripten SDK Component Source: https://emscripten.org/docs/building_from_source/verify_emscripten_environment.html Install a specific component from the Emscripten SDK repository. Replace 'java-7.45-64bit' with the actual name of the component you need to install. ```bash ./emsdk install java-7.45-64bit ``` -------------------------------- ### Create Web Audio Context and Start Wasm Audio Worklet Thread Source: https://emscripten.org/docs/api_reference/wasm_audio_worklets.html Initializes a Web Audio context and starts an Emscripten Wasm Audio Worklet thread. This is the first step in setting up audio processing with Wasm. ```c #include uint8_t audioThreadStack[4096]; int main() { EMSCRIPTEN_WEBAUDIO_T context = emscripten_create_audio_context(0); emscripten_start_wasm_audio_worklet_thread_async(context, audioThreadStack, sizeof(audioThreadStack), &AudioThreadInitialized, 0); } ``` -------------------------------- ### Install MinGW Compiler Toolchain (Windows) Source: https://emscripten.org/docs/building_from_source/toolchain_what_is_needed.html For SDK users on Windows, this installs and activates the MinGW compiler toolchain. This is an alternative to Visual Studio for building projects. ```bash emsdk install mingw-4.6.2-32bit emsdk activate mingw-4.6.2-32bit ``` -------------------------------- ### Install and Activate Old Emscripten SDK Version Source: https://emscripten.org/docs/tools_reference/emsdk.html Installs and activates a specific archived tool or SDK version. ```bash # Install the required version. ./emsdk install # Activate required version. ./emsdk activate ``` -------------------------------- ### Install Git on Linux Source: https://emscripten.org/docs/getting_started/downloads.html Install Git on Linux using the system package manager. Git is only required if you intend to use tools from a development branch. ```bash # Install git sudo apt-get install git ``` -------------------------------- ### Install a Specific Emscripten SDK Version Source: https://emscripten.org/docs/getting_started/downloads.html Install a specific tagged release of the Emscripten SDK by providing the version number. ```bash ./emsdk install 1.38.45 ``` -------------------------------- ### Install and Activate Latest Changes with emsdk Source: https://emscripten.org/docs/tools_reference/emsdk.html Use 'tot' to install and activate the latest continuously built version of the Emscripten SDK, which includes recent Emscripten and LLVM changes. ```bash ./emsdk install tot ./emsdk activate tot ``` -------------------------------- ### Installing Emscripten and Make in GitLab CI Source: https://emscripten.org/docs/compiling/GitLab.html This section of the .gitlab-ci.yml file details the installation of Emscripten and the 'make' utility from the Alpine Linux testing repository within the 'before_script' stage. ```yaml before_script: - apk add emscripten make --repository=http://dl-cdn.alpinelinux.org/alpine/edge/testing ``` -------------------------------- ### Example C++ Classes Source: https://emscripten.org/docs/porting/connecting_cpp_and_javascript/WebIDL-Binder.html Defines sample C++ classes 'Foo' and 'Bar' with methods and a constructor. These serve as the basis for WebIDL binding. ```cpp class Foo { public: int getVal(); void setVal(int v); }; class Bar { public: Bar(long val); void doSomething(); }; ``` -------------------------------- ### Get Help for emsdk Source: https://emscripten.org/docs/tools_reference/emsdk.html Displays a list of all supported commands for the emsdk tool. ```bash ./emsdk help ``` -------------------------------- ### Install Tip-of-Tree Emscripten Build Source: https://emscripten.org/docs/getting_started/downloads.html Install the latest tip-of-tree build, which represents the most recent code that has passed integration tests. This may be less stable than tagged releases but is useful for testing new features or reporting regressions. ```bash ./emsdk install tot ``` -------------------------------- ### Verify Emscripten Installation Source: https://emscripten.org/docs/getting_started/Tutorial.html Run this command to verify your Emscripten installation. If you encounter warnings, refer to the debugging guide. ```bash ./emcc -v ``` -------------------------------- ### FS.init Source: https://emscripten.org/docs/api_reference/Filesystem-API.html Sets up standard I/O devices for stdin, stdout, and stderr. ```APIDOC ## FS.init(_input_, _output_, _error_) ### Description Sets up standard I/O devices for `stdin`, `stdout`, and `stderr`. The devices are set up using the following (optional) callbacks. If any of the callbacks throw an exception, it will be caught and handled as if the device malfunctioned. ### Parameters #### Path Parameters - **input** (function) - Optional - Input callback. This will be called with no parameters whenever the program attempts to read from `stdin`. It should return an ASCII character code when data is available, or `null` when it isn’t. - **output** (function) - Optional - Output callback. This will be called with an ASCII character code whenever the program writes to `stdout`. It may also be called with `null` to flush the output. - **error** (function) - Optional - Error callback. This is similar to `output`, except it is called when data is written to `stderr`. ``` -------------------------------- ### Mount PROXYFS Example Source: https://emscripten.org/docs/api_reference/Filesystem-API.html Demonstrates how Module 2 can access and modify Module 1's filesystem using PROXYFS. Ensure Module 1's FS is available. ```javascript module2.FS.mkdir("/fs1"); module2.FS.mount(module2.PROXYFS, { root: "/", fs: module1.FS }, "/fs1"); ``` -------------------------------- ### Get Compiler Setting Example Source: https://emscripten.org/docs/api_reference/emscripten.h.html Retrieves the value of a specific compiler setting, such as INITIAL_MEMORY. Ensure the code is built with -sRETAIN_COMPILER_SETTINGS. ```c emscripten_get_compiler_setting("INITIAL_MEMORY") ``` -------------------------------- ### Get Call Stack Example Source: https://emscripten.org/docs/api_reference/emscripten.h.html Programmatically obtains the current call stack. Pass 0 for out and maxbytes to query the required buffer size. ```c int stackSize = emscripten_get_callstack(EM_LOG_JS_STACK, NULL, 0); char* stack = (char*)malloc(stackSize); emscripten_get_callstack(EM_LOG_JS_STACK, stack, stackSize); // Use stack... ``` -------------------------------- ### List Available SDKs and Tools Source: https://emscripten.org/docs/tools_reference/emsdk.html Lists all currently installed SDKs and tools, along with their status. Use the --old flag to include historical versions. ```bash ./emsdk list ``` ```bash ./emsdk list --old ``` -------------------------------- ### Emscripten Check Warning Example Source: https://emscripten.org/docs/building_from_source/verify_emscripten_environment.html This output indicates a potential issue where the detected LLVM version for clang does not match the expected version. This may require installing or activating the correct LLVM component. ```text emcc (Emscripten GCC-like replacement + linker emulating GNU ld) 1.21.0 shared:INFO: (Emscripten: Running sanity checks) emcc: warning: LLVM version for clang executable "/usr/bin/clang" appears incorrect (seeing "16.0", expected "18") [-Wversion-check] ``` -------------------------------- ### Synchronous Fetch Example Source: https://emscripten.org/docs/api_reference/fetch.html Demonstrates a synchronous GET request to download a file. The emscripten_fetch function blocks until the operation completes. Success and failure callbacks, if provided, are called synchronously before emscripten_fetch returns. ```c int main() { emscripten_fetch_attr_t attr; emscripten_fetch_attr_init(&attr); strcpy(attr.requestMethod, "GET"); attr.attributes = EMSCRIPTEN_FETCH_LOAD_TO_MEMORY | EMSCRIPTEN_FETCH_SYNCHRONOUS; emscripten_fetch_t *fetch = emscripten_fetch(&attr, "file.dat"); // Blocks here until the operation is complete. if (fetch->status == 200) { printf("Finished downloading %llu bytes from URL %s.\n", fetch->numBytes, fetch->url); // The data is now available at fetch->data[0] through fetch->data[fetch->numBytes-1]; } else { printf("Downloading %s failed, HTTP failure status code: %d.\n", fetch->url, fetch->status); } emscripten_fetch_close(fetch); } ``` -------------------------------- ### Define JavaScript Library with Function Postset Source: https://emscripten.org/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.html This example shows an alternative way to define a JavaScript library using a `__postset` property that directly contains a function call. This is suitable for simpler setup logic compared to the array-based approach. ```javascript addToLibrary({ $method_support__postset: 'method_support();', $method_support: function() { var SomeLib = function() { this.callCount = 0; }; SomeLib.prototype.getCallCount = function() { return this.callCount; }; SomeLib.prototype.process = function() { ++this.callCount; }; SomeLib.prototype.reset = function() { this.callCount = 0; }; var inst = new SomeLib(); _method_01 = inst.getCallCount.bind(inst); _method_02 = inst.process.bind(inst); _method_03 = inst.reset.bind(inst); }, method_01: function() {}, method_01__deps: ['$method_support'], method_02: function() {}, method_01__deps: ['$method_support'], method_03: function() {}, method_01__deps: ['$method_support'], }); ``` -------------------------------- ### List Available SDKs and Tools Source: https://emscripten.org/docs/tools_reference/emsdk.html Use the 'list' command to see all available Emscripten SDKs and individual tools. ```bash ./emsdk list ``` -------------------------------- ### Setup Cross-Origin Storage Extension Source: https://emscripten.org/docs/compiling/CrossOriginStorage.html This command downloads and unpacks the Cross-Origin Storage polyfill extension. It is a prerequisite for automated browser testing with the extension. ```bash python3 test/setup_cos_extension.py ``` -------------------------------- ### SDL Hello World C Code with Emscripten Integration Source: https://emscripten.org/docs/getting_started/Tutorial.html This C code demonstrates a basic SDL application that initializes video, draws a colored square, and prints output. It includes Emscripten-specific includes and macros for potential browser integration. ```c // Copyright 2011 The Emscripten Authors. All rights reserved. // Emscripten is available under two separate licenses, the MIT license and the // University of Illinois/NCSA Open Source License. Both these licenses can be // found in the LICENSE file. #include #include #ifdef __EMSCRIPTEN__ #include #endif int main(int argc, char** argv) { printf("Hello, world!\n"); SDL_Init(SDL_INIT_VIDEO); SDL_Surface *screen = SDL_SetVideoMode(256, 256, 32, SDL_SWSURFACE); #ifdef TEST_SDL_LOCK_OPTS EM_ASM("SDL.defaults.copyOnLock = false; SDL.defaults.discardOnLock = true; SDL.defaults.opaqueFrontBuffer = false;"); #endif if (SDL_MUSTLOCK(screen)) SDL_LockSurface(screen); for (int i = 0; i < 256; i++) { for (int j = 0; j < 256; j++) { #ifdef TEST_SDL_LOCK_OPTS // Alpha behaves like in the browser, so write proper opaque pixels. int alpha = 255; #else // To emulate native behavior with blitting to screen, alpha component is ignored. Test that it is so by outputting // data (and testing that it does get discarded) int alpha = (i+j) % 255; #endif *((Uint32*)screen->pixels + i * 256 + j) = SDL_MapRGBA(screen->format, i, j, 255-i, alpha); } } if (SDL_MUSTLOCK(screen)) SDL_UnlockSurface(screen); SDL_Flip(screen); printf("you should see a smoothly-colored square - no sharp lines but the square borders!\n"); printf("and here is some text that should be HTML-friendly: amp: |&| double-quote: |\"| quote: |'| less-than, greater-than, html-like tags: ||\nanother line.\n"); SDL_Quit(); return 0; } ``` -------------------------------- ### Full Embind Example with Vector, Map, and Optional Source: https://emscripten.org/docs/porting/connecting_cpp_and_javascript/embind.html Demonstrates registering and using std::vector, std::map, and std::optional with Embind, including C++ function bindings and JavaScript interaction. ```cpp #include #include #include #include using namespace emscripten; std::vector returnVectorData () { std::vector v(10, 1); return v; } std::map returnMapData () { std::map m; m.insert(std::pair(10, "This is a string.")); return m; } std::optional returnOptionalData() { return "hello"; } EMSCRIPTEN_BINDINGS(module) { function("returnVectorData", &returnVectorData); function("returnMapData", &returnMapData); function("returnOptionalData", &returnOptionalData); // register bindings for std::vector, std::map, // and std::optional. register_vector("vector"); register_map("map"); register_optional(); } ``` -------------------------------- ### Create and Run a Wasm Worker Source: https://emscripten.org/docs/api_reference/wasm_workers.html This example demonstrates creating a Wasm Worker and posting a function to execute within it. Ensure to build with the `-sWASM_WORKERS` flag. ```c #include #include void run_in_worker() { printf("Hello from Wasm Worker!\n"); } int main() { emscripten_wasm_worker_t worker = emscripten_malloc_wasm_worker(/*stackSize: */4096); emscripten_wasm_worker_post_function_v(worker, run_in_worker); } ``` -------------------------------- ### Install Emscripten SDK Asserts Version Source: https://emscripten.org/docs/tools_reference/emsdk.html Installs and activates a specific 'asserts' version of the Emscripten SDK, which includes more runtime checks. ```bash ./emsdk install 4.0.7-asserts ./emsdk activate 4.0.7-asserts ``` -------------------------------- ### Build Basic C++ Example with Emscripten Source: https://emscripten.org/docs/building_from_source/verify_emscripten_environment.html Compile a simple C++ file using Emscripten to verify the build process. This command should complete without warnings, producing an output JavaScript file. ```bash cd emscripten/ ./emcc test/hello_world.cpp ``` -------------------------------- ### Install GCC and CMake (Linux) Source: https://emscripten.org/docs/building_from_source/toolchain_what_is_needed.html Installs the GCC compiler and CMake build system on Linux. These are essential for building Emscripten from source on this platform. ```bash #Install gcc sudo apt-get install build-essential # Install cmake sudo apt-get install cmake ``` -------------------------------- ### Build with Emscripten using Make Source: https://emscripten.org/docs/compiling/Building-Projects.html Use emconfigure and emmake to replace GCC with Emcc for building projects with Make. The final step compiles the output to JavaScript and WebAssembly. ```bash # Run emconfigure with the normal configure command as an argument. emconfigure ./configure # Run emmake with the normal make to generate Wasm object files. emmake make # Compile the linked code generated by make to JavaScript + WebAssembly. # 'project.o' should be replaced with the make output for your project, and # you may need to rename it if it isn't something emcc recognizes # (for example, it might have a different suffix like 'project.so' or # 'project.so.1', or no suffix like just 'project' for an executable). # If the project output is a library, you may need to add your 'main.c' file # here as well. # [-Ox] represents build optimisations (discussed in the next section). emcc [-Ox] project.o -o project.js ``` -------------------------------- ### emscripten_set_touchstart_callback Source: https://emscripten.org/docs/api_reference/html5.h.html Registers a callback function to handle the touch start event. The callback is invoked when a touch start event occurs on the specified target. ```APIDOC ## EMSCRIPTEN_RESULT emscripten_set_touchstart_callback(const char *target, void *userData, bool useCapture, em_touch_callback_func callback) ### Description Registers a callback function for receiving touch start events. ### Method `emscripten_set_touchstart_callback` ### Parameters #### Target - **target** (const char*) - The HTML element ID to attach the callback to. - **userData** (void*) - User-defined data to be passed to the callback. - **useCapture** (bool) - Set to `true` to use event capturing. - **callback** (em_touch_callback_func) - The callback function to be executed when a touch start event occurs. ### Returns - `EMSCRIPTEN_RESULT` - Returns `EMSCRIPTEN_RESULT_SUCCESS` on success, or an error code otherwise. ``` -------------------------------- ### Build Site HTML Source: https://emscripten.org/docs/site/about.html Cleans previous builds and generates the HTML for the website. Navigate to the '/emscripten/site' directory before running. ```bash make clean make html ``` -------------------------------- ### Class Binding Constructor with Callable Example Source: https://emscripten.org/docs/api_reference/bind.h.html Demonstrates various ways to bind constructors using factory functions, std::function, and std::bind. ```cpp using namespace std::placeholders; myClass1.constructor(&my_factory); myClass2.constructor(std::function(&class2_factory)); myClass3.constructor(std::bind(Class3Functor(), _1)); ``` -------------------------------- ### Standard Build Commands Source: https://emscripten.org/docs/compiling/Building-Projects.html These are the typical commands used to configure and build a project without Emscripten. ```bash ./configure make ``` -------------------------------- ### Emscripten Initialization and Shutdown Source: https://emscripten.org/docs/api_reference/advanced-apis.html Advanced Emscripten API functions for static initialization and application shutdown. `staticInit()` is for early setup, and `quit()` for graceful termination. ```c FS.staticInit() ``` ```c FS.quit() ``` -------------------------------- ### LeakSanitizer Output Example Source: https://emscripten.org/docs/debugging/Sanitizers.html Example output from LeakSanitizer showing detected memory leaks, including the size and location of the leaked objects and allocation call stacks. ```text ================================================================= ==42==ERROR: LeakSanitizer: detected memory leaks Direct leak of 40 byte(s) in 1 object(s) allocated from: #0 0x5ce5 in operator new[](unsigned long)+0x5ce5 (a.out.wasm+0x5ce5) #1 0xb24 in __original_main leak.cpp:2:3 #2 0xb3a in main+0xb3a (a.out.wasm+0xb3a) #3 0x800019b8 in Object.Module._main a.out.js:6584:32 #4 0x80001ae1 in Object.callMain a.out.js:6881:30 #5 0x80001b1b in doRun a.out.js:6939:60 #6 0x80001b29 in run a.out.js:6953:5 #7 0x80001acc in runCaller a.out.js:6860:29 SUMMARY: AddressSanitizer: 40 byte(s) leaked in 1 allocation(s). ``` -------------------------------- ### Use-After-Return Error Output Example Source: https://emscripten.org/docs/debugging/Sanitizers.html Example output from AddressSanitizer indicating a stack-use-after-return error, detailing the memory address, program counter, and call stack where the error occurred. ```text ================================================================= ==42==ERROR: AddressSanitizer: stack-use-after-return on address 0x02a95010 at pc 0x00000d90 bp 0x02965f70 sp 0x02965f7c WRITE of size 4 at 0x02a95010 thread T0 #0 0xd90 in __original_main use_after_return.c:13:10 #1 0xe0a in main+0xe0a (a.out.wasm+0xe0a) Address 0x02a95010 is located in stack of thread T0 at offset 16 in frame #0 0x11 (a.out.wasm+0x11) This frame has 1 object(s): [16, 56) 'buf' (line 8) <== Memory access at offset 16 is inside this variable HINT: this may be a false positive if your program uses some custom stack unwind mechanism, swapcontext or vfork (longjmp and C++ exceptions *are* supported) SUMMARY: AddressSanitizer: stack-use-after-return (a.out.wasm+0xd8f) ``` -------------------------------- ### Build and Link External Library with Emscripten Source: https://emscripten.org/docs/compiling/Building-Projects.html This sequence demonstrates how to build an external library (libstuff.a) and then link it with your main project (project.o) to create a final executable. It involves using emconfigure and emmake for the library and project builds, followed by emcc for linking. ```bash # Compile libstuff to libstuff.a emconfigure ./configure emmake make # Compile project to project.o emconfigure ./configure emmake make # Link the library and code together. emcc project.o libstuff.a -o final.html ``` -------------------------------- ### Install Emscripten Build Source: https://emscripten.org/docs/contributing/developers_guide.html Installs an arbitrary build of Emscripten from a specific commit hash. This is useful for bisecting regressions across different Emscripten versions without manual compilation. ```bash emsdk install [HASH] ``` -------------------------------- ### EVAL_CTORS Logging Example (Partial Success) Source: https://emscripten.org/docs/optimizing/Optimizing-Code.html Example output when EVAL_CTORS partially succeeds but stops due to an import call (e.g., reading from environment). This indicates areas where optimization was limited. ```text trying to eval __wasm_call_ctors ...partial evalling successful, but stopping since could not eval: call import: wasi_snapshot_preview1.environ_sizes_get recommendation: consider --ignore-external-input ...stopping ``` -------------------------------- ### Example of INCOMING_MODULE_JS_API Configuration Source: https://emscripten.org/docs/tools_reference/settings_reference.html This snippet demonstrates how to configure the INCOMING_MODULE_JS_API setting. It shows a JavaScript object 'Module' with 'print' and 'preRun' properties, which should be reflected in the INCOMING_MODULE_JS_API list to ensure the compiler generates code to handle these values. ```javascript var Module = { print: (x) => console.log('print: ' + x), preRun: [() => console.log('pre run')] }; ``` -------------------------------- ### Differentiated Optimization: Size vs. Speed Source: https://emscripten.org/docs/compiling/Building-Projects.html This example shows how to apply different optimization levels to specific files, optimizing one for size (-Oz) and others for speed (-O2). Ensure these flags are correctly passed during the linking stage. ```bash # Optimize the first file for size, and the rest using `-O2`. emcc -Oz a.cpp -c -o a.o emcc -O2 b.cpp -c -o b.o emcc -O2 a.o b.o -o project.js ``` -------------------------------- ### Install Python and CMake on Linux Source: https://emscripten.org/docs/getting_started/downloads.html Install Python and CMake using the system package manager on Linux. Python is required by emsdk, and CMake is optional but needed for tests and building certain components. ```bash sudo apt-get install python3 # Install CMake (optional, only needed for tests and building Binaryen or LLVM) sudo apt-get install cmake ``` -------------------------------- ### Fast Iteration Builds with Emscripten Source: https://emscripten.org/docs/getting_started/FAQ.html Use the -O0 optimization level during the link step for significantly faster build times during development. This is recommended for rapid iteration. ```bash emcc ... -O0 ... ``` -------------------------------- ### EVAL_CTORS Logging Example (Success with main() Stop) Source: https://emscripten.org/docs/optimizing/Optimizing-Code.html Example output when EVAL_CTORS successfully evaluates global constructors but stops during main() evaluation due to an import call (e.g., writing to file descriptor). ```text trying to eval __wasm_call_ctors ...success on __wasm_call_ctors. trying to eval main ...stopping (in block) since could not eval: call import: wasi_snapshot_preview1.fd_write ...stopping ``` -------------------------------- ### Activate Latest Emscripten SDK Source: https://emscripten.org/docs/getting_started/downloads.html Set up the compiler configuration to point to the 'latest' SDK. ```bash ./emsdk activate latest ``` -------------------------------- ### Module.preRun Source: https://emscripten.org/docs/api_reference/module.html A function or array of functions to be called right before the main() function is invoked, after the environment setup is complete. Useful for tasks like setting up the file system. ```APIDOC ## Module.preRun ### Description A function (or array of functions) to call right before calling `main()`, but after defining and setting up the environment, including global initializers. This is useful, for example, to set up directories and files using the File System API — as this needs to happen after the FileSystem API has been loaded, but before the program starts to run. Note: If code needs to affect global initializers, it should instead be run using `preInit`. ``` -------------------------------- ### FS.cwd() Source: https://emscripten.org/docs/api_reference/Filesystem-API.html Gets the current working directory of the filesystem. ```APIDOC ## FS.cwd() ### Description Gets the current working directory. ### Returns - **string**: The current working directory. ``` -------------------------------- ### Compile C and C++ with WebAssembly EH and setjmp-longjmp Source: https://emscripten.org/docs/porting/setjmp-longjmp.html Example of compiling C and C++ files separately, ensuring consistent WebAssembly EH and setjmp-longjmp support, before linking them together. ```bash emcc -c -sSUPPORT_LONGJMP=wasm a.c -o a.o em++ -c -fwasm-exceptions b.cpp -o b.o em++ -fwasm-exceptions a.o b.o -o test.js ``` -------------------------------- ### FS.mkdev Source: https://emscripten.org/docs/api_reference/Filesystem-API.html Creates a new device node in the file system. ```APIDOC ## FS.mkdev ### Description Creates a new device node in the file system referencing the registered device driver (`FS.registerDevice()`) for `dev`. ### Method FS.mkdev ### Parameters #### Path Parameters - **path** (string) - Required - The path name for the new device node. - **mode** (int) - Optional - File permissions for the new node. Defaults to 0777 (octal). - **dev** (int) - Required - The registered device driver. ### Request Example ```javascript var id = FS.makedev(64, 0); FS.registerDevice(id, {}); FS.mkdev('/dummy', id); ``` ### Response (No specific response details provided in the source for this method.) ``` -------------------------------- ### emscripten_trace_record_frame_start Source: https://emscripten.org/docs/api_reference/trace.h.html Records the start of a new frame or event loop iteration. ```APIDOC ## emscripten_trace_record_frame_start ### Description Records the beginning of a new frame or an iteration of the application's main event loop. This is useful for analyzing frame-based performance. ``` -------------------------------- ### emscripten_get_element_css_size Source: https://emscripten.org/docs/api_reference/html5.h.html Gets the current CSS width and height of a specified HTML element. ```APIDOC ## emscripten_get_element_css_size ### Description Gets the current CSS width and height of the element specified by `target`. ### Function Signature `EMSCRIPTEN_RESULT emscripten_get_element_css_size(const char *target, double *width, double *height)` ### Parameters #### Path Parameters - **target** (const char*) - Required - Element to get size of. - **width** (double*) - Required - Pointer to store the width of the element. - **height** (double*) - Required - Pointer to store the height of the element. ### Returns `EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. ### Return Type `EMSCRIPTEN_RESULT` ``` -------------------------------- ### Include Headers and Glue Code Source: https://emscripten.org/docs/porting/connecting_cpp_and_javascript/WebIDL-Binder.html Example C++ wrapper file that includes necessary headers for bound classes and the generated glue code. ```cpp #include <...> // Where "..." represents the headers for the classes we are binding. #include ```