util: avoid /proc on BSDs (but keep for tests)

/proc is removed on OpenBSD, deprecated on FreeBSD or may not contain
Linux-style nodes.

Not mounted:

  test_cmdline_as_str                  [ ERROR ]
  Error: src/util-strings.c:483: assertion failed: fd >= 0 (-1 >= 0)

Mounted but only has /proc/curproc instead of /proc/self:

  test_cmdline_as_str                  [ ERROR ]
  Error: child killed by signal 11
This commit is contained in:
Jan Beich 2023-05-17 13:12:07 +00:00
parent c7517b2737
commit cc046f1f67

View file

@ -45,6 +45,12 @@
#include <xlocale.h>
#endif
#if defined(__DragonFly__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
#include <sys/types.h>
#include <sys/sysctl.h>
#include <unistd.h>
#endif
#include "util-macros.h"
#include "util-mem.h"
@ -397,6 +403,29 @@ strstartswith(const char *str, const char *prefix)
static inline char *
cmdline_as_str(void)
{
#ifdef KERN_PROC_ARGS
int mib[] = {
CTL_KERN,
#if defined(__NetBSD__) || defined(__OpenBSD__)
KERN_PROC_ARGS,
getpid(),
KERN_PROC_ARGV,
#else
KERN_PROC,
KERN_PROC_ARGS,
getpid(),
#endif
};
size_t len;
if (sysctl(mib, ARRAY_LENGTH(mib), NULL, &len, NULL, 0))
return NULL;
char *const procargs = malloc(len);
if (sysctl(mib, ARRAY_LENGTH(mib), procargs, &len, NULL, 0))
return NULL;
return procargs;
#else
int fd = open("/proc/self/cmdline", O_RDONLY);
if (fd > 0) {
char buffer[1024] = {0};
@ -404,5 +433,6 @@ cmdline_as_str(void)
close(fd);
return len > 0 ? xstrdup(buffer) : NULL;
}
#endif
return NULL;
}