Apply review suggestions for pid_path.rb

Co-authored-by: MikeMcQuaid <125011+MikeMcQuaid@users.noreply.github.com>
This commit is contained in:
Carlo Cabrera 2025-08-13 13:55:33 +08:00 committed by Carlo Cabrera
parent a7c124c2d0
commit e8828c152d
No known key found for this signature in database
GPG Key ID: C74D447FC549A1D0

View File

@ -2,22 +2,31 @@
# typed: strict
# frozen_string_literal: true
pid = ARGV[0]&.to_i
exit 1 unless pid
require "fiddle"
libproc = Fiddle.dlopen("/usr/lib/libproc.dylib")
proc_pidpath = Fiddle::Function.new(
libproc_proc_pidpath_function = Fiddle::Function.new(
libproc["proc_pidpath"],
[Fiddle::TYPE_INT, Fiddle::TYPE_VOIDP, Fiddle::TYPE_UINT32_T],
Fiddle::TYPE_INT,
)
pid = ARGV[0]&.to_i
exit 1 unless pid
# We have to allocate a (char) buffer of exactly `PROC_PIDPATHINFO_MAXSIZE` to use `proc_pidpath`
# From `include/sys/proc_info.h`, PROC_PIDPATHINFO_MAXSIZE = 4 * MAXPATHLEN
# From `include/sys/param.h`, MAXPATHLEN = PATH_MAX
# From `include/sys/syslimits.h`, PATH_MAX = 1024
# https://github.com/apple-oss-distributions/xnu/blob/e3723e1f17661b24996789d8afc084c0c3303b26/libsyscall/wrappers/libproc/libproc.c#L268-L275
buffer_size = 4 * 1024 # PROC_PIDPATHINFO_MAXSIZE = 4 * MAXPATHLEN
buffer = "\0" * buffer_size
pointer_to_buffer = Fiddle::Pointer.to_ptr(buffer)
bufsize = 4 * 1024 # PROC_PIDPATHINFO_MAXSIZE = 4 * MAXPATHLEN
buf = "\0" * bufsize
ptr = Fiddle::Pointer.to_ptr(buf)
ret = proc_pidpath.call(pid, ptr, bufsize)
puts ptr.to_s.strip if ret.positive?
# `proc_pidpath` returns a positive value on success. See:
# https://stackoverflow.com/a/8149198
# https://github.com/chromium/chromium/blob/86df41504a235f9369f6f53887da12a718a19db4/base/process/process_handle_mac.cc#L37-L44
# https://github.com/apple-oss-distributions/xnu/blob/e3723e1f17661b24996789d8afc084c0c3303b26/libsyscall/wrappers/libproc/libproc.c#L263-L283
return_value = libproc_proc_pidpath_function.call(pid, pointer_to_buffer, buffer_size)
puts pointer_to_buffer.to_s.strip if return_value.positive?