util: one whole-file reader for all tools

Three private ones had grown: fnread() in util.c, flen() behind
pid_cmdline()/pid_cgroup() in cgutil.c, and conf_read_template() in
conf.c.  Two of them were also wrong in ways the others were not.

fnread() formatted the path into a char[256] and stat()ed it before
opening, so a longer path was silently truncated and then read from
whichever file the truncation happened to name, and the size could
change between the look and the read.  flen() existed because neither
of those approaches works on procfs at all, where stat() reports zero
and the only way to learn the size is to read to EOF.

Add fslurp() to util.[ch], which every tool already links.  It opens
first and sizes the fd it holds, treats st_size as a hint, and reads
until EOF, so procfs and regular files take the same path.  Paths are
formatted by libite's vfopenf(), which allocates to fit.  Callers that
need the byte count, /proc/PID/cmdline embeds NUL, ask for it.

fnread() keeps its signature and becomes a bounded copy out of the
result, so its one caller is unaffected.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
This commit is contained in:
Joachim Wiberg committed 2026-07-30 15:21:27 +02:00
1 parent f1393ff8a1
commit 0721b0fec2
4 files changed
+115 -92

No files matched your search

+15 -54
View File
@@ -34,6 +34,7 @@
#include "cgutil.h"
#include "initctl.h"
#include "log.h"
#include "util.h"
#define CDIM plain ? "" : "\e[2m"
#define CRST plain ? "" : "\e[0m"
@@ -54,42 +55,18 @@ int cgroup_avail(void)
return fismnt(FINIT_CGPATH);
}
static size_t flen(FILE *fp)
{
size_t total = 0, sz;
char buf[512];
while ((sz = fread(buf, 1, sizeof(buf), fp)) > 0)
total += sz;
rewind(fp);
return total;
}
char *pid_cmdline(int pid)
{
size_t i, len;
char *buf;
FILE *fp;
fp = fopenf("r", "/proc/%d/cmdline", pid);
if (!fp)
buf = fslurp(&len, "/proc/%d/cmdline", pid);
if (!buf)
return strdup(""); /* regular process */
len = flen(fp);
if (len == 0) {
fail:
fclose(fp);
return NULL; /* kernel thread */
}
buf = calloc(len + 1, 1);
if (!buf)
goto fail;
if (fread(buf, 1, len, fp) < len) {
free(buf);
goto fail;
return NULL; /* kernel thread */
}
/* replace all NUL chars with space */
@@ -98,46 +75,30 @@ char *pid_cmdline(int pid)
buf[i] = ' ';
}
fclose(fp);
return buf;
}
char *pid_cgroup(int pid)
{
char *buf, *ptr = NULL;
size_t len;
FILE *fp;
char *buf, *ptr;
fp = fopenf("r", "/proc/%d/cgroup", pid);
if (!fp)
buf = fslurp(NULL, "/proc/%d/cgroup", pid);
if (!buf)
return NULL;
len = flen(fp);
if (len == 0) {
fclose(fp);
return NULL;
}
len++;
buf = calloc(1, len);
if (!buf) {
fclose(fp);
return NULL;
}
if (fgets(buf, len, fp))
ptr = chomp(buf);
fclose(fp);
ptr = strchr(buf, '\n'); /* first line only */
if (ptr)
*ptr = 0;
chomp(buf);
ptr = strchr(buf, '/');
if (ptr) {
ptr = strchr(ptr, '/');
if (ptr) {
memmove(buf, ptr, strlen(ptr) + 1);
return buf;
}
memmove(buf, ptr, strlen(ptr) + 1);
return buf;
}
free(buf);
return NULL;
}