diff options
author | Andrea Claudi <aclaudi@redhat.com> | 2022-03-08 18:04:56 +0100 |
---|---|---|
committer | Stephen Hemminger <stephen@networkplumber.org> | 2022-03-11 19:10:48 -0800 |
commit | 1808f002dfdd33fc397151c30bcffcef25cb6ae9 (patch) | |
tree | 38811581107ceb841db3cd671ca182f37c054e6b /lib | |
parent | 62c0700c7b373ad71ef712e4c065610c80866440 (diff) | |
download | iproute2-1808f002dfdd33fc397151c30bcffcef25cb6ae9.tar.gz |
lib/fs: fix memory leak in get_task_name()
asprintf() allocates memory which is not freed on the error path of
get_task_name(), thus potentially leading to memory leaks.
%m specifier on fscanf allocates memory, too, which needs to be freed by
the caller.
This reworks get_task_name() to avoid memory allocation.
- Pass a buffer and its length to the function, similarly to what
get_command_name() does, thus avoiding to allocate memory for
the string to be returned;
- Use snprintf() instead of asprintf();
- Use fgets() instead of fscanf() to limit string length.
Fixes: 81bfd01a4c9e ("lib: move get_task_name() from rdma")
Signed-off-by: Andrea Claudi <aclaudi@redhat.com>
Signed-off-by: Stephen Hemminger <stephen@networkplumber.org>
Diffstat (limited to 'lib')
-rw-r--r-- | lib/fs.c | 23 |
1 files changed, 13 insertions, 10 deletions
@@ -342,25 +342,28 @@ int get_command_name(const char *pid, char *comm, size_t len) return 0; } -char *get_task_name(pid_t pid) +int get_task_name(pid_t pid, char *name, size_t len) { - char *comm; + char path[PATH_MAX]; FILE *f; if (!pid) - return NULL; + return -1; - if (asprintf(&comm, "/proc/%d/comm", pid) < 0) - return NULL; + if (snprintf(path, sizeof(path), "/proc/%d/comm", pid) >= sizeof(path)) + return -1; - f = fopen(comm, "r"); + f = fopen(path, "r"); if (!f) - return NULL; + return -1; - if (fscanf(f, "%ms\n", &comm) != 1) - comm = NULL; + if (!fgets(name, len, f)) + return -1; + + /* comm ends in \n, get rid of it */ + name[strcspn(name, "\n")] = '\0'; fclose(f); - return comm; + return 0; } |