From 89823f981e5bd510823f86ab9a4e1f64521d88a4 Mon Sep 17 00:00:00 2001 From: Honggyu Kim Date: Thu, 23 Feb 2023 23:49:24 +0900 Subject: [PATCH] libheaptrace: Fix segfaults when directly using LD_PRELOAD 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 Signed-off-by: Honggyu Kim --- heaptrace.cc | 1 + libheaptrace.cc | 13 ++++++++++--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/heaptrace.cc b/heaptrace.cc index 3158ef9..994c66e 100644 --- a/heaptrace.cc +++ b/heaptrace.cc @@ -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; diff --git a/libheaptrace.cc b/libheaptrace.cc index 0c064ca..11184d2 100644 --- a/libheaptrace.cc +++ b/libheaptrace.cc @@ -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"); @@ -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) {