Skip to content

Instantly share code, notes, and snippets.

@CyberShadow
Last active May 21, 2022 12:05
Show Gist options
  • Select an option

  • Save CyberShadow/511a497c5cd8a3e6a9679dd4b4b3b150 to your computer and use it in GitHub Desktop.

Select an option

Save CyberShadow/511a497c5cd8a3e6a9679dd4b4b3b150 to your computer and use it in GitHub Desktop.
hackbrary to measure realloc count and duration

Usage: LD_PRELOAD='/path/to/this/directory/$LIB/ralcount.so' ./Delta-V.x86_64

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <stdio.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <time.h>
#include <inttypes.h>
#include <gnu/lib-names.h>
// ****************************************************************************
#define NEXT(handle, path, func) ({ \
static typeof(&func) pfunc = NULL; \
if (!pfunc) \
pfunc = (typeof(&func))dlsym(RTLD_NEXT, #func); \
if (!pfunc) { \
if (!handle) { \
handle = dlopen(path, RTLD_LAZY); \
} \
if (!handle) { \
fprintf(stderr, "ralcount: Ack, dlopen of '%s' failed: %s\n", \
path, dlerror()); \
} \
pfunc = (typeof(&func))dlsym(handle, #func); \
} \
if (!pfunc) { \
fprintf(stderr, "ralcount: Ack, dlsym of '%s' (from '%s') failed: %s\n", \
#func, path, dlerror()); \
} \
pfunc; \
})
static void* libc = NULL;
static int second_counter = 0;
static int64_t second_ns = 0;
static time_t last_second = 0;
void* realloc(void* ptr, size_t size)
{
time_t curr_second = time(NULL);
if (curr_second != last_second) {
printf("%d reallocs - %" PRId64 " ns avg.\n",
second_counter,
second_counter ? second_ns / second_counter : -1
);
second_counter = 0;
second_ns = 0;
last_second = curr_second;
}
struct timespec start = {}, end = {};
clock_gettime(CLOCK_MONOTONIC, &start);
void* result = NEXT(libc, LIBC_SO, realloc)
(ptr, size);
clock_gettime(CLOCK_MONOTONIC, &end);
second_counter++;
second_ns += (int64_t)(end.tv_sec - start.tv_sec) * 1000000000 + (end.tv_nsec - start.tv_nsec);
return result;
}
PREFIX=/usr/local
LIB32=lib32
LIB64=lib64
all: lib
lib: lib32/ralcount.so lib64/ralcount.so
lib32:
mkdir lib32
lib64:
mkdir lib64
lib32/ralcount.so: lib32 lib.c Makefile
gcc -m32 -Wall -Wextra -g lib.c -o $@ -fPIC -shared -ldl -D_GNU_SOURCE
lib64/ralcount.so: lib64 lib.c Makefile
gcc -m64 -Wall -Wextra -g lib.c -o $@ -fPIC -shared -ldl -D_GNU_SOURCE
.PHONY: all lib
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment