okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
01f8c3255
main
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 7readable by other processes while a lock is held (a lock that covered the data would make reads fail). It supports 8shared 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 10file is only a hint; the creation time is what tells the process that was recorded from a later one that reused 11the 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 : 24import ctypes 25import msvcrt 26from ctypes import wintypes 27 28_k32 = ctypes .WinDLL ("kernel32" ,use_last_error = True ) 29 30class _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 , 35ctypes .POINTER (_Overlapped )] 36_k32 .LockFileEx .restype = wintypes .BOOL 37_k32 .UnlockFileEx .argtypes = [wintypes .HANDLE ,wintypes .DWORD ,wintypes .DWORD ,wintypes .DWORD , 38ctypes .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 , 49ctypes .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 60def _overlapped ()-> _Overlapped : 61o = _Overlapped () 62o .Offset = LOCK_OFFSET & 0xFFFFFFFF 63o .OffsetHigh = LOCK_OFFSET >> 32 64return o 65 66def try_lock (fd :int ,* ,exclusive :bool )-> bool : 67"""Take the lock without waiting. False when another holder has it.""" 68handle = msvcrt .get_osfhandle (fd ) 69flags = _LOCKFILE_FAIL_IMMEDIATELY | (_LOCKFILE_EXCLUSIVE_LOCK if exclusive else 0 ) 70if _k32 .LockFileEx (handle ,flags ,0 ,1 ,0 ,ctypes .byref (_overlapped ())): 71return True 72code = ctypes .get_last_error () 73if code in (_ERROR_LOCK_VIOLATION ,_ERROR_IO_PENDING ): 74return False 75raise ctypes .WinError (code ,"LockFileEx" ) 76 77def unlock (fd :int )-> None : 78_k32 .UnlockFileEx (msvcrt .get_osfhandle (fd ),0 ,1 ,0 ,ctypes .byref (_overlapped ())) 79 80def 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 82process, it has exited, or its times cannot be read.""" 83if type (pid )is not int or pid <= 0 : 84return None 85handle = _k32 .OpenProcess (_PROCESS_QUERY_LIMITED_INFORMATION ,False ,pid ) 86if not handle : 87return None 88try : 89code = wintypes .DWORD () 90if not _k32 .GetExitCodeProcess (handle ,ctypes .byref (code ))or code .value != _STILL_ACTIVE : 91return None 92created ,exited ,kernel ,user = (wintypes .FILETIME ()for _ in range (4 )) 93if not _k32 .GetProcessTimes (handle ,ctypes .byref (created ),ctypes .byref (exited ), 94ctypes .byref (kernel ),ctypes .byref (user )): 95return None 96return (created .dwHighDateTime << 32 )| created .dwLowDateTime 97finally : 98_k32 .CloseHandle (handle ) 99 100def process_image (pid :int )-> str | None : 101"""The executable path of a running process, or None when it cannot be read.""" 102if type (pid )is not int or pid <= 0 : 103return None 104handle = _k32 .OpenProcess (_PROCESS_QUERY_LIMITED_INFORMATION ,False ,pid ) 105if not handle : 106return None 107try : 108size = wintypes .DWORD (32768 ) 109buffer = ctypes .create_unicode_buffer (size .value ) 110if not _k32 .QueryFullProcessImageNameW (handle ,0 ,buffer ,ctypes .byref (size )): 111return None 112return buffer .value 113finally : 114_k32 .CloseHandle (handle ) 115 116def 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.""" 118if type (pid )is not int or pid <= 0 : 119return False 120now = process_started (pid ) 121if now is None : 122# OpenProcess can be refused for a protected process that does exist; treat that as present. 123handle = _k32 .OpenProcess (_PROCESS_QUERY_LIMITED_INFORMATION ,False ,pid ) 124if handle : 125_k32 .CloseHandle (handle ) 126return False # opened, but exited or unreadable: not running 127return ctypes .get_last_error ()== _ERROR_ACCESS_DENIED 128return started is None or now == started 129else : 130def try_lock (fd :int ,* ,exclusive :bool )-> bool : 131raise OSError ("Windows only" ) 132 133def unlock (fd :int )-> None : 134raise OSError ("Windows only" ) 135 136def process_started (pid :int )-> int | None : 137return None 138 139def process_image (pid :int )-> str | None : 140return None 141 142def pid_alive (pid :int ,started :int | None = None )-> bool : 143raise OSError ("Windows only" )