Skip to content

Commit 4aa8947

Browse files
committed
Export system malloc() and free() as dlmalloc() and dlfree() so that applications can have an easier mechanism to just hook in between to the existing malloc and free, but still keep calling the original dlmalloc and dlfree.
1 parent ec38205 commit 4aa8947

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

system/lib/dlmalloc.c

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6017,6 +6017,16 @@ int mspace_mallopt(int param_number, int value) {
60176017

60186018
#endif /* MSPACES */
60196019

6020+
// Export malloc and free as duplicate names dlmalloc and dlfree so that
6021+
// applications can replace malloc and free in their code, and make those
6022+
// replacements refer to the original dlmalloc and dlfree from this file.
6023+
// This allows an easy mechanism for hooking into memory allocation.
6024+
#if defined(__EMSCRIPTEN__) && !defined(USE_DL_PREFIX)
6025+
#undef dlmalloc
6026+
#undef dlfree
6027+
extern __typeof(malloc) dlmalloc __attribute__((weak, alias("malloc")));
6028+
extern __typeof(free) dlfree __attribute__((weak, alias("free")));
6029+
#endif
60206030

60216031
/* -------------------- Alternative MORECORE functions ------------------- */
60226032

tests/test_core.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7178,6 +7178,9 @@ def test_brk(self):
71787178
self.emcc_args += ['-DTEST_BRK=1']
71797179
self.do_run(open(path_from_root('tests', 'sbrk_brk.cpp')).read(), 'OK.')
71807180

7181+
def test_wrap_malloc(self):
7182+
self.do_run(open(path_from_root('tests', 'wrap_malloc.cpp')).read(), 'OK.')
7183+
71817184
# Generate tests for everything
71827185
def make_run(fullname, name=-1, compiler=-1, embetter=0, quantum_size=0,
71837186
typed_arrays=0, emcc_args=None, env=None):

tests/wrap_malloc.cpp

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
int totalAllocated = 0;
5+
int totalFreed = 0;
6+
7+
extern "C"
8+
{
9+
10+
extern void* dlmalloc(size_t bytes);
11+
extern void dlfree(void* mem);
12+
13+
void * __attribute__((noinline)) malloc(size_t size)
14+
{
15+
++totalAllocated;
16+
void *ptr = dlmalloc(size);
17+
printf("Allocated %u bytes, got %p. %d pointers allocated total.\n", size, ptr, totalAllocated);
18+
return ptr;
19+
}
20+
21+
void __attribute__((noinline)) free(void *ptr)
22+
{
23+
++totalFreed;
24+
dlfree(ptr);
25+
printf("Freed ptr %p, %d pointers freed total.\n", ptr, totalFreed);
26+
}
27+
28+
}
29+
30+
int main()
31+
{
32+
for(int i = 0; i < 20; ++i)
33+
{
34+
void *ptr = malloc(1024 * 1024);
35+
free(ptr);
36+
}
37+
printf("OK.\n");
38+
}

0 commit comments

Comments
 (0)