Skip to content

Commit

Permalink
wasm32-unknown-unknown: Fix undefined malloc/free/calloc symbols (#275)
Browse files Browse the repository at this point in the history
As discussed in #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.
  • Loading branch information
jbms committed May 24, 2024
1 parent a2125e3 commit fb6b490
Showing 1 changed file with 13 additions and 23 deletions.
36 changes: 13 additions & 23 deletions zstd-safe/zstd-sys/wasm-shim/stdlib.h
Original file line number Diff line number Diff line change
@@ -1,28 +1,18 @@
#include <stddef.h>

#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

0 comments on commit fb6b490

Please sign in to comment.