Is there any reason to implement our malloc/free with exactly the same signature as library ones?

Skip to first unread message

Wei Chen

Apr 13, 2021, 5:55:50 AM4/13/21
to address-sanitizer
Hi all,

I'm recently learning Address Sanitizer code and learned that the runtime library is designed to replace the glibc malloc/free with our customized ones so that we can insert red zone before and after the allocated region.

From the code, I've learned that such a replacement is implemented by changing the runtime library load priority. By writing our malloc/free with exactly the same function signature as the library ones, and letting our runtime library being loaded before glibc, our malloc/free function will be invoked by the user program.

However, we are not able to invoke printf library functions anymore, cause printf depends on malloc, therefore, each time when printf is invoked when implementing asan runtime library, it will call our malloc instead of library malloc.

Why not just implement our malloc and free to another name, say asan_malloc and asan_free? In that case, we can replace the malloc invocation with asan_malloc invocation during compilation, and no need to write a totally new printf. Is there any reason to have the same name?

Dmitry Vyukov

Apr 13, 2021, 6:52:56 AM4/13/21
to address-sanitizer
Hi Wei,

One reason to define them with the same name is that it allows to
intercept malloc/free calls in code compiled without ASAN (e.g. libc's
getline). We won't check accesses to the buffer inside of libc, but we
will check them in the user code that uses the buffer.
Another reason is probably more important: in some cases memory is
allocated in one library and freed in another (again - getline). In
that case we may get a fatal crash/memory corruption is malloc/free
are not matching.

Wei Chen

Apr 15, 2021, 2:24:29 AM4/15/21
to address-sanitizer

Hi, May I ask how long it takes if I want to reimplement the runtime library for address sanitizer by one person? Saying that reimplementing the interfaces, interceptors and internal glibc functions.
Reply all
Reply to author
0 new messages