From b2ead8735bd97e187188a3a91105df7fd6366b39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E9=80=9A=E6=B4=B2?= Date: Thu, 24 Aug 2023 14:20:48 +0800 Subject: [PATCH] Platform (Unix): add `exePath` --- src/util/platform/FFPlatform_unix.c | 48 +++++++++++++++++------------ 1 file changed, 28 insertions(+), 20 deletions(-) diff --git a/src/util/platform/FFPlatform_unix.c b/src/util/platform/FFPlatform_unix.c index 2fa403ca6..3f7aada12 100644 --- a/src/util/platform/FFPlatform_unix.c +++ b/src/util/platform/FFPlatform_unix.c @@ -14,6 +14,27 @@ #include #endif +static void getExePath(FFPlatform* platform) +{ + FFstrbuf* const exePath = &platform->exePath; + ffStrbufEnsureFree(exePath, PATH_MAX); + #ifdef __linux__ + ssize_t exePathLen = readlink("/proc/self/exe", exePath->chars, exePath->allocated); + #elif defined(__APPLE__) + int exePathLen = proc_pidpath((int) getpid(), exePath->chars, exePath->allocated); + #elif defined(__FreeBSD__) + size_t exePathLen = exePath->allocated; + if(sysctl( + (int[]){CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, (int) getpid()}, 4, + exePath->chars, &exePathLen, + NULL, 0 + )) + exePathLen = 0; + #endif + if (exePathLen > 0) + exePath->length = (uint32_t) exePathLen; +} + static void platformPathAddEnv(FFlist* dirs, const char* env) { const char* envValue = getenv(env); @@ -90,27 +111,13 @@ static void getDataDirs(FFPlatform* platform) ffPlatformPathAddHome(&platform->dataDirs, platform, ".local/share/"); // Add ${currentExePath}/../share - FF_STRBUF_AUTO_DESTROY exePath = ffStrbufCreateA(PATH_MAX); - #ifdef __linux__ - ssize_t exePathLen = readlink("/proc/self/exe", exePath.chars, exePath.allocated); - #elif defined(__APPLE__) - int exePathLen = proc_pidpath((int) getpid(), exePath.chars, exePath.allocated); - #elif defined(__FreeBSD__) - size_t exePathLen = exePath.allocated; - if(sysctl( - (int[]){CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, (int) getpid()}, 4, - exePath.chars, &exePathLen, - NULL, 0 - )) - exePathLen = 0; - #endif - if (exePathLen > 0) + if (platform->exePath.length > 0) { - exePath.length = (uint32_t) exePathLen; - ffStrbufSubstrBeforeLastC(&exePath, '/'); - ffStrbufSubstrBeforeLastC(&exePath, '/'); - ffStrbufAppendS(&exePath, "/share"); - ffPlatformPathAddAbsolute(&platform->dataDirs, exePath.chars); + FF_STRBUF_AUTO_DESTROY path = ffStrbufCreateCopy(&platform->exePath); + ffStrbufSubstrBeforeLastC(&path, '/'); + ffStrbufSubstrBeforeLastC(&path, '/'); + ffStrbufAppendS(&path, "/share"); + ffPlatformPathAddAbsolute(&platform->dataDirs, path.chars); } #ifdef __APPLE__ @@ -183,6 +190,7 @@ void ffPlatformInitImpl(FFPlatform* platform) if(uname(&uts) != 0) memset(&uts, 0, sizeof(uts)); + getExePath(platform); getHomeDir(platform, pwd); getCacheDir(platform); getConfigDirs(platform);