benchcount.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Round 190of: LD_PRELOAD helper for LYNX --pluginbench (Linux, glibc). Counts the malloc-family calls and the
  2. // pthread mutex locks a thread makes while it has counting on; LYNX finds lynxbench_counts with dlsym. Build:
  3. // cc -O2 -shared -fPIC -o libbenchcount.so benchcount.c -ldl
  4. #define _GNU_SOURCE
  5. #include <dlfcn.h>
  6. #include <pthread.h>
  7. #include <stddef.h>
  8. extern void* __libc_malloc (size_t);
  9. extern void* __libc_calloc (size_t, size_t);
  10. extern void* __libc_realloc (void*, size_t);
  11. extern void* __libc_memalign (size_t, size_t);
  12. extern void __libc_free (void*);
  13. static __thread int counting;
  14. static __thread unsigned long allocations, locks;
  15. void lynxbench_counts (int on, unsigned long* a, unsigned long* l)
  16. {
  17. if (on)
  18. {
  19. allocations = locks = 0;
  20. counting = 1;
  21. return;
  22. }
  23. counting = 0;
  24. if (a) *a = allocations;
  25. if (l) *l = locks;
  26. }
  27. void* malloc (size_t n) { if (counting) ++allocations; return __libc_malloc (n); }
  28. void* calloc (size_t a, size_t b) { if (counting) ++allocations; return __libc_calloc (a, b); }
  29. void* realloc (void* p, size_t n) { if (counting) ++allocations; return __libc_realloc (p, n); }
  30. void free (void* p) { if (counting && p) ++allocations; __libc_free (p); }
  31. int posix_memalign (void** out, size_t align, size_t n)
  32. {
  33. if (counting) ++allocations;
  34. void* p = __libc_memalign (align, n);
  35. if (! p) return 12;
  36. *out = p;
  37. return 0;
  38. }
  39. void* aligned_alloc (size_t align, size_t n) { if (counting) ++allocations; return __libc_memalign (align, n); }
  40. void* memalign (size_t align, size_t n) { if (counting) ++allocations; return __libc_memalign (align, n); }
  41. typedef int (*lockfn) (pthread_mutex_t*);
  42. int pthread_mutex_lock (pthread_mutex_t* m)
  43. {
  44. static lockfn real;
  45. if (! real)
  46. real = (lockfn) dlsym (RTLD_NEXT, "pthread_mutex_lock");
  47. if (counting) ++locks;
  48. return real (m);
  49. }