"""Identify processes that execute code from a test daemon snapshot.""" from collections.abc import Sequence import ctypes import os from pathlib import Path import struct import sys def darwin_argv(pid: int) -> list[bytes]: # KERN_PROCARGS2 returns argc, the executable path, NUL padding, argv, # then the environment. Stop at argc even when an argument is empty. mib = (ctypes.c_int * 3)(1, 49, pid) # CTL_KERN, KERN_PROCARGS2, pid buffer = ctypes.create_string_buffer(os.sysconf("SC_ARG_MAX")) size = ctypes.c_size_t(len(buffer)) libc = ctypes.CDLL(None) if libc.sysctl(mib, 3, buffer, ctypes.byref(size), None, 0) != 0: return [] return unpack_darwin_argv(buffer.raw[: size.value]) def unpack_darwin_argv(data: bytes) -> list[bytes]: if len(data) < struct.calcsize("i"): return [] (argc,) = struct.unpack_from("i", data) if argc <= 0: return [] _, _, arguments = data[struct.calcsize("i") :].partition(b"\0") entries = arguments.lstrip(b"\0").split(b"\0", argc) return entries[:argc] if len(entries) > argc else [] def process_argv(pid: int) -> list[bytes]: if sys.platform == "darwin": return darwin_argv(pid) try: return ( Path(f"/proc/{pid}/cmdline").read_bytes().removesuffix(b"\0").split(b"\0") ) except (FileNotFoundError, ProcessLookupError, PermissionError): # Processes can exit after pgrep, or belong to a different user. return [] def uses_snapshot(argv: Sequence[bytes], roots: tuple[bytes, ...]) -> bool: def from_snapshot(path: bytes) -> bool: return path.startswith(b"/") and os.path.normpath(path).startswith(roots) if not argv: return False command, *arguments = argv if from_snapshot(command): return True executable = os.path.basename(command) if executable == b"beam.smp": # The snapshot launcher supplies the package ebin directories to -pa. for index, argument in enumerate(arguments[:-1]): if argument == b"-extra": break if argument == b"-pa" and from_snapshot(arguments[index + 1]): return True return False if executable in (b"sh", b"bash", b"dash", b"zsh"): return bool(arguments and from_snapshot(arguments[0])) if executable.lower().startswith(b"python") or executable.startswith(b"albedo-"): # Named Python interpreters use an albedo- symlink. The script # immediately follows -u, or is the first argument. if arguments and arguments[0] == b"-u": arguments = arguments[1:] return bool(arguments and from_snapshot(arguments[0])) return False def main() -> None: root = os.path.abspath(sys.argv[1]) roots = tuple( os.fsencode(path.rstrip("/") + "/") for path in (root, os.path.realpath(root)) ) for value in sys.argv[2:]: pid = int(value) if uses_snapshot(process_argv(pid), roots): print(pid) if __name__ == "__main__": main()