* Copyright (C) 2012 David Goulet <dgoulet@efficios.com>
* Copyright (C) 2013 Jérémie Galarneau <jeremie.galarneau@efficios.com>
*
- * SPDX-License-Identifier: GPL-2.0-only
+ * SPDX-License-Identifier: LGPL-2.1-only
*
*/
#include "common/macros.h"
+#include <stdint.h>
#define _LGPL_SOURCE
#include <assert.h>
#include <ctype.h>
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;
}
}
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;
* 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) {
/*
* 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;
}
* 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);
}
* 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);
}