diff dep/animone/src/fd/freebsd.cc @ 338:f63dfa309380

dep/animone: separate *BSD into separate files they are wholly different operating systems with very different kernels on the inside
author Paper <paper@paper.us.eu.org>
date Wed, 19 Jun 2024 13:06:10 -0400
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/dep/animone/src/fd/freebsd.cc	Wed Jun 19 13:06:10 2024 -0400
@@ -0,0 +1,98 @@
+/*
+ * fd/freebsd.cc: support for FreeBSD
+ *
+ * somewhat tested...
+ */
+#include "animone/fd/bsd.h"
+#include "animone.h"
+#include "animone/fd.h"
+
+#include <sys/file.h>
+#include <sys/filedesc.h>
+#include <sys/param.h>
+#include <sys/queue.h>
+#include <sys/sysctl.h>
+#include <sys/types.h>
+#include <sys/user.h>
+#include <sys/vnode.h>
+
+#include <libutil.h>
+
+#include <string>
+
+namespace animone::internal::freebsd {
+
+static std::string Basename(const std::string& name) {
+	size_t s = name.find_last_of('/');
+
+	if (s == std::string::npos)
+		return name;
+
+	return name.substr(s, name.size());
+}
+
+bool GetProcessName(pid_t pid, std::string& name) {
+	static const int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};
+
+	struct kinfo_proc result;
+
+	size_t length = 1;
+	if (sysctl((int*)mib, (sizeof(mib) / sizeof(*mib)) - 1, &result, &length, NULL, 0) == -1)
+		return false;
+
+	name = Basename(result.ki_comm);
+
+	return true;
+}
+
+bool EnumerateOpenProcesses(process_proc_t process_proc) {
+	static const int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0};
+	size_t length = 0;
+
+	sysctl((int*)mib, (sizeof(mib) / sizeof(*mib)) - 1, NULL, &length, NULL, 0);
+
+	std::unique_ptr<struct kinfo_proc[]> result;
+	result.reset(new struct kinfo_proc[length]);
+
+	if (!result.get())
+		return false;
+
+	/* actually get our results */
+	if (sysctl((const int*)mib, (sizeof(mib) / sizeof(*mib)) - 1, result.get(), &length, NULL, 0) == ENOMEM)
+		return false;
+
+	if (length < sizeof(struct kinfo_proc))
+		return false;
+
+	for (int i = 0; i < length / sizeof(result[0]); i++)
+		if (!process_proc({.platform = ExecutablePlatform::Posix, .pid = result[i].ki_pid, .comm = result[i].ki_comm}))
+			return false;
+
+	return true;
+}
+
+bool EnumerateOpenFiles(const std::set<pid_t>& pids, open_file_proc_t open_file_proc) {
+	for (const auto& pid : pids) {
+		int cnt;
+		std::unique_ptr<struct kinfo_file[]> files(kinfo_getfile(pid, &cnt));
+		if (!files)
+			return false;
+
+		for (int i = 0; i < cnt; i++) {
+			const struct kinfo_file& current = files[i];
+			if (current.kf_vnode_type != KF_VTYPE_VREG || current.kf_vnode_type != KF_VTYPE_VLNK)
+				continue;
+
+			const int oflags = current.kf_flags & O_ACCMODE;
+			if (oflags == O_WRONLY || oflags == O_RDWR)
+				continue;
+
+			if (!open_file_proc({pid, current.kf_path}))
+				return false;
+		}
+	}
+
+	return true;
+}
+
+} // namespace animone::internal::freebsd