xref: /wasmtime-44.0.1/docs/wmemcheck.md (revision acbcc21d)
1# Wasm memcheck (wmemcheck)
2
3wmemcheck provides the ability to check for invalid mallocs, reads, and writes
4inside a Wasm module, as long as Wasmtime is able to make certain assumptions
5(`malloc` and `free` functions are visible and your program uses only the
6default allocator). This is analogous to the Valgrind tool's memory checker
7(memcheck) tool for native programs.
8
9How to use:
10
111. When building Wasmtime, add the CLI flag "--features wmemcheck" to compile with wmemcheck configured.
12    > cargo build --features wmemcheck
132. When running your wasm module, add the CLI flag "-W wmemcheck".
14    > wasmtime run -W wmemcheck test.wasm
15
16If your program executes an invalid operation (load or store to non-allocated
17address, double-free, or an internal error in malloc that allocates the same
18memory twice) you will see an error that looks like a Wasm trap. For example, given the program
19
20```c
21#include <stdlib.h>
22
23int main() {
24    char* p = malloc(1024);
25    *p = 0;
26    free(p);
27    *p = 0;
28}
29```
30
31compiled with WASI-SDK via
32
33```plain
34$ /opt/wasi-sdk/bin/clang -o test.wasm test.c
35```
36
37you can observe the memory checker working like so:
38
39```plain
40$ wasmtime run -W wmemcheck ./test.wasm
41Error: failed to run main module `./test.wasm`
42
43Caused by:
44    0: failed to invoke command default
45    1: error while executing at wasm backtrace:
46           0:  0x103 - <unknown>!__original_main
47           1:   0x87 - <unknown>!_start
48           2: 0x2449 - <unknown>!_start.command_export
49    2: Invalid store at addr 0x10610 of size 1
50```
51