From 0b964b71318e36c0f4396cd8edff7211a4a848c8 Mon Sep 17 00:00:00 2001 From: Jeremy Maitin-Shepard Date: Fri, 24 May 2024 11:05:31 -0700 Subject: [PATCH] wasm32-unknown-unknown: Fix undefined malloc/free/calloc symbols (#275) As discussed in https://github.com/gyscos/zstd-rs/issues/250, in some cases the definitions of `malloc`, `free`, and `calloc` are used but don't get linked in, leading to undefined symbols (i.e. reference to the symbol in "env"). I was not able to determine exactly why this is happening, but it seems to be related to `malloc`, `calloc`, and `free` being defined as inline functions. When building in debug mode there are undefined symbols; when building in release mode there are not, presumably because the functions are inlined. Switching to macros avoids issues of inlining and fixes this issue for me. --- zstd-safe/zstd-sys/wasm-shim/stdlib.h | 36 ++++++++++----------------- 1 file changed, 13 insertions(+), 23 deletions(-) diff --git a/zstd-safe/zstd-sys/wasm-shim/stdlib.h b/zstd-safe/zstd-sys/wasm-shim/stdlib.h index 0f701f5c..506b8199 100644 --- a/zstd-safe/zstd-sys/wasm-shim/stdlib.h +++ b/zstd-safe/zstd-sys/wasm-shim/stdlib.h @@ -1,28 +1,18 @@ #include -#ifndef _STDLIB_H -#define _STDLIB_H 1 +#ifndef _STDLIB_H +#define _STDLIB_H 1 -void *rust_zstd_wasm_shim_malloc(size_t size); -void *rust_zstd_wasm_shim_calloc(size_t nmemb, size_t size); -void rust_zstd_wasm_shim_free(void *ptr); -void rust_zstd_wasm_shim_qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*)); +void* rust_zstd_wasm_shim_malloc(size_t size); +void* rust_zstd_wasm_shim_calloc(size_t nmemb, size_t size); +void rust_zstd_wasm_shim_free(void* ptr); +void rust_zstd_wasm_shim_qsort(void* base, size_t nitems, size_t size, + int (*compar)(const void*, const void*)); -inline void *malloc(size_t size) { - return rust_zstd_wasm_shim_malloc(size); -} +#define malloc(size) rust_zstd_wasm_shim_malloc(size) +#define calloc(nmemb, size) rust_zstd_wasm_shim_calloc(nmemb, size) +#define free(ptr) rust_zstd_wasm_shim_free(ptr) +#define qsort(base, nitems, size, compar) \ + rust_zstd_wasm_shim_qsort(base, nitems, size, compar) -inline void *calloc(size_t nmemb, size_t size) { - return rust_zstd_wasm_shim_calloc(nmemb, size); -} - -inline void free(void *ptr) { - rust_zstd_wasm_shim_free(ptr); -} - -inline void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*)) -{ - return rust_zstd_wasm_shim_qsort(base, nitems, size, compar); -} - -#endif // _STDLIB_H +#endif // _STDLIB_H