fix(macos,process_info): tighten error handling and add endian assert

- Guard against `getProcess` returning null in the macOS FFI path
  (`proc_pidpath` can fail with EPERM or for an already-exited PID).
  Stop unwrapping with `!` and only populate the ProcessInfoCache on
  success; the previous code threw NullThrownError there, which the
  outer try/catch silently swallowed and prevented caching of valid
  later results.
- Add a 5-second negative cache for ports whose owner can't be
  resolved (typical for short-lived clients that exited before we
  scanned). Without it every such request triggered a full PID list
  rescan, defeating the point of the pid cache for the failure path.
- Add a debug-only assert that the host is little-endian. The libproc
  parsing reads `(int)htons(port)` by treating the low two bytes as a
  big-endian uint16, which requires a little-endian host. All shipping
  macOS hardware satisfies this; the assert fails loudly if the
  assumption is ever broken (stripped from release builds).

Re-verified on macOS 26.4: 500 concurrent curl through the proxy,
single ProxyPin process throughout, 9099 freed immediately on exit.
This commit is contained in:
testercengdong
2026-05-12 10:16:42 +08:00
parent ad89ec6aec
commit d69b95dbbc
2 changed files with 21 additions and 2 deletions

View File

@@ -93,6 +93,13 @@ class MacosProcessInfo {
/// are spawned. Typical cost on a desktop with ~500 processes and ~10k
/// total fds is a few milliseconds.
static int? findPidByLocalTcpPort(int localPort) {
// The insi_lport read below assumes a little-endian host: `(int)htons(port)`
// stores the network-byte-order 16-bit port in the low two bytes of the
// int32 field. All shipping macOS hardware (x86_64 / arm64) is
// little-endian; this assert exists to fail loudly rather than return
// wrong port values if that ever changes. Stripped in release builds.
assert(Endian.host == Endian.little, 'libproc parsing requires little-endian host');
final pidBufSize = _procListPids(_kProcAllPids, 0, nullptr, 0);
if (pidBufSize <= 0) return null;