Skip to content

Commit

Permalink
libheaptrace: Fix segfaults when directly using LD_PRELOAD
Browse files Browse the repository at this point in the history
The current usage of 'heaptrace' works fine as follows.

  $ heaptrace samples/sample.out
  [heaptrace] initialized for /proc/4084/maps (sample.out)
  [heaptrace]   finalized for /proc/4084/maps (sample.out)

It should be fine when running it with 'LD_PRELOAD' without using
'heaptrace' helper binary, but it gets crashed as follows.

  $ LD_PRELOAD=./libheaptrace.so samples/sample.out
  Segmentation falut (core dumped)

The problem is because 'getenv()' returns NULL in this case, but it
misses to check whether the returned values are NULL or not.

This patch fixes this problem and it makes LD_PRELOAD usage works fine.

  $ LD_PRELOAD=./libheaptrace.so samples/sample.out
  [heaptrace] initialized for /proc/4167/maps (sample.out)
  [heaptrace]   finalized for /proc/4167/maps (sample.out)

Fixed: #18

Reported-by: Bojun Seo <[email protected]>
Signed-off-by: Honggyu Kim <[email protected]>
  • Loading branch information
honggyukim committed Feb 23, 2023
1 parent d95b8c4 commit 89823f9
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
1 change: 1 addition & 0 deletions heaptrace.cc
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ static void init_options(int argc, char *argv[])
};

// set default option values
// TODO: create constexpr variables instead of default magic values.
opts.top = 10;
opts.sort_keys = "size";
opts.flamegraph = false;
Expand Down
13 changes: 10 additions & 3 deletions libheaptrace.cc
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ static void heaptrace_init()
int pid = getpid();
std::stringstream ss;
std::string comm = utils::get_comm_name();
char *env;

real_malloc = (MallocFunction)dlsym(RTLD_NEXT, "malloc");
real_free = (FreeFunction)dlsym(RTLD_NEXT, "free");
Expand All @@ -89,9 +90,15 @@ static void heaptrace_init()
sighandler_init();

// setup option values
opts.top = strtol(getenv("HEAPTRACE_NUM_TOP_BACKTRACE"), NULL, 0);
opts.sort_keys = getenv("HEAPTRACE_SORT_KEYS");
opts.flamegraph = strtol(getenv("HEAPTRACE_FLAME_GRAPH"), NULL, 0);
// TODO: create constexpr variables instead of default magic values.
env = getenv("HEAPTRACE_NUM_TOP_BACKTRACE");
opts.top = env ? strtol(env, NULL, 0) : 10;

env = getenv("HEAPTRACE_SORT_KEYS");
opts.sort_keys = env ? env : "size";

env = getenv("HEAPTRACE_FLAME_GRAPH");
opts.flamegraph = env ? strtol(env, NULL, 0) : false;

opts.outfile = getenv("HEAPTRACE_OUTFILE");
if (opts.outfile) {
Expand Down

0 comments on commit 89823f9

Please sign in to comment.