Home
Support

Knowledge Base

BSPs and drivers
Community resources
Product documentation
Questions?
Contact us

Calloc preload example
 
________________________________________________________________________

Applicable Environment
________________________________________________________________________
  • Topic: Calloc preload example
  • SDP: 6.4.1, 6.5.0, 6.6.0, 7.0.0, 7.1.0
  • Target: Any supported target
________________________________________________________________________

Recommendation
________________________________________________________________________

An example on how to overload calloc():

1. Create calloclib.c:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

void* calloc(size_t n, size_t size) {
// To confirm you're using the right calloc() function
// uncomment the next line.
//fprintf(stderr, "Using calloc from libcalloc\n");
size_t new_size;
void * ptr;

new_size = n*size;
if ((n | size) & ~(((size_t)-1 >> (sizeof(size_t) << 2)))) {
if ((size != 0) && ((new_size / size) != n)) {
// this has caused a wrap around, fail request
errno = ENOMEM;
return(NULL);
}
}
ptr = malloc(new_size);
if (ptr) {
memset(ptr, 0, new_size);
}
return ptr;
}

2. Calloc test program:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int main(int argc, char *argv[]) {
void *ptr = calloc(65537, 65537);
// void *ptr = calloc(1, 10);
if (ptr == NULL) {
fprintf(stderr, "calloc error: errno=%d\n", errno);
} else {
fprintf(stderr, "calloc ptr @ 0x%p\n", ptr);
free(ptr);
}
return EXIT_SUCCESS;
}


3. Build the calloclib shared library
nto[ARCH]-gcc -shared -o libcalloc.so calloclib.c
e.g. ntox86-gcc -shared -o libcalloc.so calloclib.c

4. Build your application or calloctest
ntox86-gcc -o calloctest calloctest.c

5. Place both calloctest and libcalloc.so on your target. To use libcalloc start the test program (or any of your applications) by preloading it like this:

// void *ptr = calloc(65537, 65537);
# DL_DEBUG=libs LD_PRELOAD=/root/calloc/libcalloc.so /root/calloc/calloctest
load_object: attempt load of /root/calloc/libcalloc.so
load_elf32: found DT_TEXTREL, mapping a private copy of text sections!
load_elf32: loaded lib at addr b8200000(text) b8201518(data)
calloc error: errno=12
// overflow detected and error generated.

________________________________________________________________________
NOTE: This entry has been validated against the SDP version listed above. Use caution when considering this advice for any other SDP version. For supported releases, please reach out to QNX Technical Support if you have any questions/concerns.
________________________________________________________________________


Related Attachments
 None Found





Please contact us with your questions or concerns.