X-Git-Url: http://git.lttng.org./?a=blobdiff_plain;f=src%2Fcommon%2Futils.c;h=bc4f6112f9db4907e18dd9758f2a39105ca0a138;hb=f03ea3f43450abb1a1ea704044e1e8c78cfc0b4c;hp=5aedb0889896eb41e60dfdefc3e44ba896a9ac9a;hpb=395004a13b038fde13364a662d735d16937ea2d1;p=lttng-tools.git diff --git a/src/common/utils.c b/src/common/utils.c index 5aedb0889..bc4f6112f 100644 --- a/src/common/utils.c +++ b/src/common/utils.c @@ -7,6 +7,7 @@ */ #include "common/macros.h" +#include #define _LGPL_SOURCE #include #include @@ -223,30 +224,43 @@ end: LTTNG_HIDDEN int utils_create_pid_file(pid_t pid, const char *filepath) { - int ret; - FILE *fp; + int ret, fd = -1; + FILE *fp = NULL; assert(filepath); - fp = fopen(filepath, "w"); + fd = open(filepath, O_CREAT | O_WRONLY, S_IRUSR |S_IWUSR | S_IRGRP | S_IROTH); + if (fd < 0) { + PERROR("open file %s", filepath); + ret = -1; + goto error; + } + + fp = fdopen(fd, "w"); if (fp == NULL) { - PERROR("open pid file %s", filepath); + PERROR("fdopen file %s", filepath); ret = -1; + if (close(fd)) { + PERROR("Failed to close `%s` file descriptor while handling fdopen error", filepath); + } + goto error; } ret = fprintf(fp, "%d\n", (int) pid); if (ret < 0) { - PERROR("fprintf pid file"); + PERROR("fprintf file %s", filepath); + ret = -1; goto error; } - if (fclose(fp)) { - PERROR("fclose"); - } - DBG("Pid %d written in file %s", (int) pid, filepath); + DBG("'%d' written in file %s", (int) pid, filepath); ret = 0; + error: + if (fp && fclose(fp)) { + PERROR("fclose file %s", filepath); + } return ret; } @@ -1062,7 +1076,7 @@ end: } static -int read_proc_meminfo_field(const char *field, size_t *value) +int read_proc_meminfo_field(const char *field, uint64_t *value) { int ret; FILE *proc_meminfo; @@ -1080,10 +1094,10 @@ int read_proc_meminfo_field(const char *field, size_t *value) * field. */ while (!feof(proc_meminfo)) { - unsigned long value_kb; + uint64_t value_kb; ret = fscanf(proc_meminfo, - "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API "s %lu kB\n", + "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API "s %" SCNu64 " kB\n", name, &value_kb); if (ret == EOF) { /* @@ -1100,7 +1114,12 @@ int read_proc_meminfo_field(const char *field, size_t *value) * This number is displayed in kilo-bytes. Return the * number of bytes. */ - *value = ((size_t) value_kb) * 1024; + if (value_kb > UINT64_MAX / 1024) { + ERR("Overflow on kb to bytes conversion"); + break; + } + + *value = value_kb * 1024; ret = 0; goto found; } @@ -1120,7 +1139,7 @@ fopen_error: * a best guess. */ LTTNG_HIDDEN -int utils_get_memory_available(size_t *value) +int utils_get_memory_available(uint64_t *value) { return read_proc_meminfo_field(PROC_MEMINFO_MEMAVAILABLE_LINE, value); } @@ -1130,7 +1149,7 @@ int utils_get_memory_available(size_t *value) * the information in `/proc/meminfo`. */ LTTNG_HIDDEN -int utils_get_memory_total(size_t *value) +int utils_get_memory_total(uint64_t *value) { return read_proc_meminfo_field(PROC_MEMINFO_MEMTOTAL_LINE, value); }