okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-022-int into f-022-gyrocuda: Pascal path kept for cc 6.0, 8-lane trellis rows for every other CUDA card01f8c3255

main
6.4 KiB143 linesraw
1"""Windows file-lock and process-identity primitives for the managed runtime (ctypes; no pywin32).
2
3POSIX gets these from ``fcntl.flock`` and ``os.kill(pid, 0)``. Neither exists on Windows, and ``os.kill`` there is
4``TerminateProcess``: calling it with signal 0 would END the process, so a liveness check must never be written that way.
5
6* ``try_lock`` / ``unlock``: a byte-range lock (``LockFileEx``) on one byte far beyond the data, so the file stays
7  readable by other processes while a lock is held (a lock that covered the data would make reads fail). It supports
8  shared locks, which ``msvcrt.locking`` does not, and is released by the OS when the process ends, however it ends.
9* ``process_started`` / ``pid_alive``: whether a process exists and when it was created. A PID recorded in a state
10  file is only a hint; the creation time is what tells the process that was recorded from a later one that reused
11  the number.
12"""
13
14from __future__ import annotations
15
16import os
17
18WINDOWS = os.name == "nt"
19
20#: the locked byte. Beyond any data file the runtime writes (they are all far smaller).
21LOCK_OFFSET = 1 << 16
22
23if WINDOWS:
24    import ctypes
25    import msvcrt
26    from ctypes import wintypes
27
28    _k32 = ctypes.WinDLL("kernel32", use_last_error=True)
29
30    class _Overlapped(ctypes.Structure):
31        _fields_ = [("Internal", ctypes.c_void_p), ("InternalHigh", ctypes.c_void_p),
32                    ("Offset", wintypes.DWORD), ("OffsetHigh", wintypes.DWORD), ("hEvent", wintypes.HANDLE)]
33
34    _k32.LockFileEx.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.DWORD, wintypes.DWORD, wintypes.DWORD,
35                                ctypes.POINTER(_Overlapped)]
36    _k32.LockFileEx.restype = wintypes.BOOL
37    _k32.UnlockFileEx.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.DWORD, wintypes.DWORD,
38                                  ctypes.POINTER(_Overlapped)]
39    _k32.UnlockFileEx.restype = wintypes.BOOL
40    _k32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
41    _k32.OpenProcess.restype = wintypes.HANDLE
42    _k32.CloseHandle.argtypes = [wintypes.HANDLE]
43    _k32.GetExitCodeProcess.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)]
44    _k32.GetExitCodeProcess.restype = wintypes.BOOL
45    _k32.GetProcessTimes.argtypes = [wintypes.HANDLE] + [ctypes.POINTER(wintypes.FILETIME)] * 4
46    _k32.GetProcessTimes.restype = wintypes.BOOL
47
48    _k32.QueryFullProcessImageNameW.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.LPWSTR,
49                                                ctypes.POINTER(wintypes.DWORD)]
50    _k32.QueryFullProcessImageNameW.restype = wintypes.BOOL
51
52    _LOCKFILE_FAIL_IMMEDIATELY = 0x1
53    _LOCKFILE_EXCLUSIVE_LOCK = 0x2
54    _ERROR_LOCK_VIOLATION = 33
55    _ERROR_IO_PENDING = 997
56    _PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
57    _STILL_ACTIVE = 259
58    _ERROR_ACCESS_DENIED = 5
59
60    def _overlapped() -> _Overlapped:
61        o = _Overlapped()
62        o.Offset = LOCK_OFFSET & 0xFFFFFFFF
63        o.OffsetHigh = LOCK_OFFSET >> 32
64        return o
65
66    def try_lock(fd: int, *, exclusive: bool) -> bool:
67        """Take the lock without waiting. False when another holder has it."""
68        handle = msvcrt.get_osfhandle(fd)
69        flags = _LOCKFILE_FAIL_IMMEDIATELY | (_LOCKFILE_EXCLUSIVE_LOCK if exclusive else 0)
70        if _k32.LockFileEx(handle, flags, 0, 1, 0, ctypes.byref(_overlapped())):
71            return True
72        code = ctypes.get_last_error()
73        if code in (_ERROR_LOCK_VIOLATION, _ERROR_IO_PENDING):
74            return False
75        raise ctypes.WinError(code, "LockFileEx")
76
77    def unlock(fd: int) -> None:
78        _k32.UnlockFileEx(msvcrt.get_osfhandle(fd), 0, 1, 0, ctypes.byref(_overlapped()))
79
80    def process_started(pid: int) -> int | None:
81        """The creation time (100 ns ticks since 1601) of a running process, or None when there is no such
82        process, it has exited, or its times cannot be read."""
83        if type(pid) is not int or pid <= 0:
84            return None
85        handle = _k32.OpenProcess(_PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
86        if not handle:
87            return None
88        try:
89            code = wintypes.DWORD()
90            if not _k32.GetExitCodeProcess(handle, ctypes.byref(code)) or code.value != _STILL_ACTIVE:
91                return None
92            created, exited, kernel, user = (wintypes.FILETIME() for _ in range(4))
93            if not _k32.GetProcessTimes(handle, ctypes.byref(created), ctypes.byref(exited),
94                                        ctypes.byref(kernel), ctypes.byref(user)):
95                return None
96            return (created.dwHighDateTime << 32) | created.dwLowDateTime
97        finally:
98            _k32.CloseHandle(handle)
99
100    def process_image(pid: int) -> str | None:
101        """The executable path of a running process, or None when it cannot be read."""
102        if type(pid) is not int or pid <= 0:
103            return None
104        handle = _k32.OpenProcess(_PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
105        if not handle:
106            return None
107        try:
108            size = wintypes.DWORD(32768)
109            buffer = ctypes.create_unicode_buffer(size.value)
110            if not _k32.QueryFullProcessImageNameW(handle, 0, buffer, ctypes.byref(size)):
111                return None
112            return buffer.value
113        finally:
114            _k32.CloseHandle(handle)
115
116    def pid_alive(pid: int, started: int | None = None) -> bool:
117        """Whether `pid` is a running process, and, when `started` is given, the one created at that time."""
118        if type(pid) is not int or pid <= 0:
119            return False
120        now = process_started(pid)
121        if now is None:
122            # OpenProcess can be refused for a protected process that does exist; treat that as present.
123            handle = _k32.OpenProcess(_PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
124            if handle:
125                _k32.CloseHandle(handle)
126                return False                          # opened, but exited or unreadable: not running
127            return ctypes.get_last_error() == _ERROR_ACCESS_DENIED
128        return started is None or now == started
129else:
130    def try_lock(fd: int, *, exclusive: bool) -> bool:
131        raise OSError("Windows only")
132
133    def unlock(fd: int) -> None:
134        raise OSError("Windows only")
135
136    def process_started(pid: int) -> int | None:
137        return None
138
139    def process_image(pid: int) -> str | None:
140        return None
141
142    def pid_alive(pid: int, started: int | None = None) -> bool:
143        raise OSError("Windows only")