okami.mom/albedo
git clone https://git.nkp.pet/okami.mom/albedo
4359cba
main
1"""The kernel's memory cap: a sampled physical footprint, not an allocator limit. 2 3A cell that pushes the process past the cap is interrupted within an 4interval; a single allocation larger than the cap is not refused, so this is 5a guard against a runaway cell taking the namespace down, not a sandbox. 6""" 7 8from __future__import annotations 9 10import ctypes 11import os 12import struct 13import sys 14 15LIMIT = int (os .environ .get ("ALBEDO_KERNEL_MEMORY_BYTES" ,str (256 * 1024 * 1024 ))) 16INTERVAL = 0.1 # seconds between samples while a cell runs 17# A cell that starts with the kernel already past the cap (a large variable 18# left behind) may still grow this much, so `del big` and gc.collect() run. 19SLACK = 8 * 1024 * 1024 20PAGE = os .sysconf ("SC_PAGE_SIZE" )if hasattr (os ,"sysconf" )else 4096 21 22 23def footprint ()-> int | None : 24"""Bytes this process holds in physical memory: the resident set from 25/proc, or Darwin's physical footprint (what vmmap and Activity Monitor 26report). None where neither can tell.""" 27try : 28with open ("/proc/self/statm" ,"rb" )as statm : 29return int (statm .read ().split ()[1 ])* PAGE 30except (OSError ,IndexError ,ValueError ): 31return darwin_footprint (os .getpid ())if sys .platform == "darwin" else None 32 33 34def darwin_footprint (pid :int )-> int | None : 35"""ri_phys_footprint of a Darwin process's rusage_info_v0 (libproc's 36proc_pid_rusage), the 10th field after the 16-byte uuid.""" 37try : 38libproc = ctypes .CDLL ("/usr/lib/libproc.dylib" ) 39except OSError : 40return None 41buffer = ctypes .create_string_buffer (96 ) 42if libproc .proc_pid_rusage (pid ,0 ,buffer )!= 0 : 43return None 44return struct .unpack_from ("=Q" ,buffer .raw ,72 )[0 ] 45 46 47def threshold (start :int )-> int : 48"""The footprint past which a cell that started at `start` is interrupted.""" 49return max (LIMIT ,start + SLACK ) 50 51 52def mebibytes (size :int )-> str : 53return f" { size / ( 1024 * 1024 ):.0f } MiB"