References:
The memory model of WAMR can be basically described as below:
Note:
wasm_runtime_init or wasm_runtime_full_init. And for wasm_runtime_full_init, developer can specify the memory allocation mode with RuntimeInitArgs *init_args: allocate memory from a user defined byte buffer, from user defined allocation function, or from the platform's os_malloc function. Refer to wasm_export.h and Embedding WAMR guideline for more details. And developer can use wasm_runtime_malloc/wasm_runtime_free to allocate/free memory from/to the global heap.wasm_runtime_create_exec_env, then its size is specified by wasm_runtime_create_exec_env, otherwise if the exec_env is created by runtime internally, e.g. by wasm_application_execute_main or wasm_application_execute_func, then the size is specified by wasm_runtime_instantiate.-Wl,--initial-memory=n1,--max-memory=n2, for emsdk, the initial/max size can be specified with -s INITIAL_MEMORY=n1 -s MAXIMUM_MEMORY=n2 -s ALLOW_MEMORY_GROWTH=1 or -s TOTAL_MEMORY=n, and for asc, they can be specified with --initialMemory and --maximumMemory flags.
os_mmap from virtual address space instead of global heap.-z stack-size=n, for emsdk, the size can be specified with -s TOTAL_STACK=n.-Wl,--export=malloc -Wl,--export=free options, for asc, developer can use --exportRuntime option. For app heap, the size is specified by wasm_runtime_instantiate. It is recommended to export the malloc/free functions and disable app heap. However, if you are using the old pthread implementation, you might need some workaround to avoid the libc heap as mentioned in WAMR pthread library. And developer can use wasm_runtime_module_malloc/wasm_runtime_module_free to allocate/free memory from/to app heap (or libc heap if malloc/free functions are exported).__heap_base, so as to reduce the footprint, or at least one page (64KB) is required by linear memory.Normally there are some methods to tune the memory usage:
wasm_runtime_full_initwasm_runtime_create_exec_env or wasm_runtime_instantiatemalloc/free functions to use libc heap and disable app heapwasm_runtime_instantiatenostdlib mode, add -Wl,--strip-all: refer to How to reduce the footprint of building wasm app for more detailsclone_wasm_binary=false in LoadArgs and free the wasm binary buffer (with wasm_byte_vec_delete) after module loading; wasm_module_is_underlying_binary_freeable can be queried to check if the wasm binary buffer can be safely freed (see the example); after the buffer is freed, wasm_runtime_get_custom_section cannot be called anymorewasm_binary_freeable=true in LoadArgs and free the wasm binary buffer (with wasm_byte_vec_delete) after module loading; wasm_runtime_is_underlying_binary_freeable can be queried to check if the wasm binary buffer can be safely freed; after the buffer is freed, wasm_runtime_get_custom_section cannot be called anymore