view dep/animia/src/fd/xnu.cc @ 166:54c5d80a737e

dep/animia: add libutil method I changed the "linux" method to be "proc", because it isn't exactly Linux specific this commit also has some changes to the x11 stuff: instead of enumerating over only top-level windows, we iterate over ALL of them this is because many X11 apps actually use multiple windows for some reason, I still can't get it to work with VLC, but it picks up Firefox...
author paper@DavesDouble.local
date Sun, 19 Nov 2023 04:21:56 -0500
parents 44c5e6dd9488
children e44b7c428d7c
line wrap: on
line source

/*
** fd/xnu.cc
**  - provides support for XNU (part of Darwin)
*/
#include "animia/fd/xnu.h"
#ifdef HAVE_COREFOUNDATION
#	include "animia/util/osx.h"
#endif
#include "animia.h"

#include <cassert>
#include <string>
#include <unordered_map>
#include <vector>
#include <memory>

#include <fcntl.h>
#include <libproc.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <sys/user.h>

namespace animia::internal::xnu {

bool XnuFdTools::EnumerateOpenProcesses(process_proc_t process_proc) {
	size_t pids_size = 512;
	std::unique_ptr<pid_t[]> pids;

	int returned_size = 0;
	do {
		pids.reset(new pid_t[pids_size]);
		returned_size = proc_listpids(PROC_ALL_PIDS, 0, pids.get(), pids_size * sizeof(pid_t));
		if (returned_size == -1)
			return false;
	} while ((pids_size * sizeof(size_t)) < returned_size);

	for (int i = 0; i < pids_size; i++) {
		std::string result;
		osx::util::GetProcessName(pids[i], result);
		if (!process_proc({pids[i], result}))
			return false;
	}

	return true;
}

bool XnuFdTools::EnumerateOpenFiles(const std::set<pid_t>& pids, open_file_proc_t open_file_proc) {
	if (!open_file_proc)
		return false;

	for (const auto& pid : pids) {
		int bufsz = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, NULL, 0);
		if (bufsz == -1)
			return false;

		struct proc_fdinfo* info = (struct proc_fdinfo*)malloc(bufsz);
		if (!info)
			return false;

		proc_pidinfo(pid, PROC_PIDLISTFDS, 0, info, bufsz);

		for (int i = 0; i < bufsz / sizeof(info[0]); i++) {
			if (info[i].proc_fdtype == PROX_FDTYPE_VNODE) {
				struct vnode_fdinfowithpath vnodeInfo;

				int sz = proc_pidfdinfo(pid, info[i].proc_fd, PROC_PIDFDVNODEPATHINFO, &vnodeInfo,
				                        PROC_PIDFDVNODEPATHINFO_SIZE);
				if (sz != PROC_PIDFDVNODEPATHINFO_SIZE)
					return false;

				/* this doesn't work!
				if (vnodeInfo.pfi.fi_openflags & O_WRONLY || vnodeInfo.pfi.fi_openflags & O_RDWR)
				    continue;
				*/

				if (!open_file_proc({pid, vnodeInfo.pvip.vip_path}))
					return false;
			}
		}
	}

	return true;
}

} // namespace animia::internal::xnu