Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FreeBSD] lookup process path via sysctl #5189

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions Sources/CoreFoundation/CFPlatform.c
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,10 @@ static inline void _CFSetProgramNameFromPath(const char *path) {
#include <sys/exec.h>
#endif

#if TARGET_OS_BSD && defined(__FreeBSD__)
#include <sys/sysctl.h>
#endif

const char *_CFProcessPath(void) {
if (__CFProcessPath) return __CFProcessPath;

Expand Down Expand Up @@ -230,6 +234,29 @@ const char *_CFProcessPath(void) {
char *res = realpath(ps->ps_argvstr[0], NULL);
argv0 = res? res: strdup(ps->ps_argvstr[0]);
}
#elif defined(__FreeBSD__)
// see sysctl(3), pid == -1 means current process
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
int sysctl_ret = 0;
size_t len = PATH_MAX + 1;
argv0 = calloc(len, 1);

sysctl_ret = sysctl(mib, 4, argv0, &len, NULL, 0);

// in case for whatever reason the path is > PATH_MAX
if (sysctl_ret == -1 && errno == ENOMEM) {
// get size needed
sysctl_ret = sysctl(mib, 4, NULL, &len, NULL, 0);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any reason to not do this unconditionally to compute the required length?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since we should almost never the case when exec path is > PATH_MAX, so we can save an extra syscall in most cases. (In fact, I'm not sure if it's even possible on generic FreeBSD, but there are many FreeBSD variants floating around...)

if (sysctl_ret != -1) {
argv0 = realloc(argv0, len);
sysctl_ret = sysctl(mib, 4, argv0, &len, NULL, 0);
}
}

if (sysctl_ret == -1) {
free(argv0);
argv0 = NULL;
}
#endif

if (!__CFProcessIsRestricted() && argv0 && argv0[0] == '/') {
Expand Down Expand Up @@ -908,6 +935,9 @@ static void __CFTSDFinalize(void *arg) {

if (!arg || arg == CF_TSD_BAD_PTR) {
// We've already been destroyed. The call above set the bad pointer again. Now we just return.
#if defined(__FreeBSD__)
__CFTSDSetSpecific(NULL);
#endif
return;
}

Expand Down