Can a process query its (resident) memory size?

I was giving my SciTECO port another try since I thought, if dynamic linking won’t work with malloc() replacement, I’ll just link statically. Doing that I discovered that you can indeed replace malloc() in shared libraries as well. Here’s a simple test case:

// gcc -o malloc-replacement-test malloc-replacement-test.c `pkg-config --cflags --libs glib-2.0`
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>

#include <glib.h>

void * __attribute__((unused)) realloc(void *ptr, size_t size)
{
        printf("realloc(%p, %u) called\n", ptr, size);
        return NULL;
}

int main(int argc, char **argv)
{
        return 0;
}

This will abort on startup since libglib calls the overwritten version of realloc() during initialization. If you don’t link in glib, nothing happens. So how is that explained? I am on R1 Beta5 (hrev57937+129). Have things changed in Haiku since you wrote that comment and it’s now possible to overwrite malloc() for all shared libraries as well?

Does anything invoke realloc on startup/initialization if glib isn’t linked in? I wouldn’t be surprised if the answer is “no”, and so that’s why it “works” when glib isn’t linked.

My point was not that I am surprised that something calls realloc() when linking against glib - that is a fact, you can see the glib error message caused by returning NULL. I was surprised because it actually called my version of realloc() from glib (a shared library) while @SamuraiCrow said that shared libraries shouldn’t pick up these symbols.

Under these conditions, I can of course get my memory limiting to work via a custom version of malloc() just like I do on Linux, FreeBSD and NetBSD.

ELF has a single global namespace for public symbols. (PE as used on Windows does not.) So, there can only be one public malloc symbol throughout all loaded objects, and if there’s one in the main binary, this will override the one from the C library.

(There are exceptions to this. For example, if one builds and links a library with -Bsymbolic-functions or equivalent, then this will force all functions in that library that call other functions in that library to be bound to those functions and no other. But we don’t, and in fact for standards compliance can’t, link the C library with this option, so malloc and others can be overridden.)

1 Like