Skip to content

Instantly share code, notes, and snippets.

@gyulkkajo
Created April 21, 2020 06:46
Show Gist options
  • Save gyulkkajo/6e255d8ccad77128f35cf4b81759903d to your computer and use it in GitHub Desktop.
Save gyulkkajo/6e255d8ccad77128f35cf4b81759903d to your computer and use it in GitHub Desktop.
mtrace helper : Start/Stop mtrace to debug memory leak or to check memory usage by signal
#include <stdio.h>
#include <signal.h>
#include <mcheck.h>
#include <stdlib.h>
/*
* mtrace Helper
*
* Usage : Compile with this binary
*
* At runtime, start with env vars
*
* - MALLOC_TRACE : output file from mtrace
* - MALLOC_TRACE_SIGNUM : (Optional) Signal number to start/stop tracing
* Start at launch without it
*
* $ MALLOC_TRACE_SIGNUM=11 MALLOC_TRACE=`pwd`/out ./a.out
* or
* $ MALLOC_TRACE=`pwd`/out ./a.out
*
*
* NOTE: Turn off ASLR to debug symbol
*
* $ echo 0 > /proc/sys/kernel/randomize_va_space
*/
static int sig_num = SIGUSR1;
static int is_installed = 0;
static void sighandler_stop(int sig)
{
struct sigaction sa;
sa.sa_handler = SIG_DFL;
if (sigaction(sig_num, &sa, NULL) == -1) {
printf(">> mtrace: Failed to add signal handler\n");
return;
}
printf(">> mtrace: stop tracing\n");
muntrace();
}
static void sighandler_start(int sig) {
struct sigaction sa;
printf(">> mtrace: start tracing\n");
sa.sa_handler = sighandler_stop;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
if (sigaction(sig_num, &sa, NULL) == -1) {
printf(">> mtrace: Failed to add signal handler\n");
return;
}
mtrace();
}
void __attribute__((constructor)) initialize_signal(void)
{
struct sigaction sa;
char *p_usr_signum;
p_usr_signum = getenv("MALLOC_TRACE_SIGNUM");
if (p_usr_signum != NULL) {
sig_num = atoi(p_usr_signum);
sa.sa_handler = sighandler_start;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
if (sigaction(sig_num, &sa, NULL) == -1) {
printf(">> mtrace: Failed to add signal handler\n");
return;
}
} else {
sighandler_start(sig_num);
}
printf(">> mtrace: Initialized tracing hook\n");
}
@gyulkkajo
Copy link
Author

Simple version of mtrace helper.

TODO: is there anyway to avoid re-compile? like using LD_PRELOAD?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment