From e8828c152dfe20305e2c16bf85f42b8cba65d164 Mon Sep 17 00:00:00 2001 From: Carlo Cabrera Date: Wed, 13 Aug 2025 13:55:33 +0800 Subject: [PATCH] Apply review suggestions for `pid_path.rb` Co-authored-by: MikeMcQuaid <125011+MikeMcQuaid@users.noreply.github.com> --- Library/Homebrew/utils/pid_path.rb | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/Library/Homebrew/utils/pid_path.rb b/Library/Homebrew/utils/pid_path.rb index 1ae07a78fe..73f7505b68 100755 --- a/Library/Homebrew/utils/pid_path.rb +++ b/Library/Homebrew/utils/pid_path.rb @@ -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?