Skip to content

Commit b2ead87

Browse files
committed
Platform (Unix): add exePath
1 parent 5e91668 commit b2ead87

File tree

1 file changed

+28
-20
lines changed

1 file changed

+28
-20
lines changed

src/util/platform/FFPlatform_unix.c

Lines changed: 28 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,27 @@
1414
#include <sys/sysctl.h>
1515
#endif
1616

17+
static void getExePath(FFPlatform* platform)
18+
{
19+
FFstrbuf* const exePath = &platform->exePath;
20+
ffStrbufEnsureFree(exePath, PATH_MAX);
21+
#ifdef __linux__
22+
ssize_t exePathLen = readlink("/proc/self/exe", exePath->chars, exePath->allocated);
23+
#elif defined(__APPLE__)
24+
int exePathLen = proc_pidpath((int) getpid(), exePath->chars, exePath->allocated);
25+
#elif defined(__FreeBSD__)
26+
size_t exePathLen = exePath->allocated;
27+
if(sysctl(
28+
(int[]){CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, (int) getpid()}, 4,
29+
exePath->chars, &exePathLen,
30+
NULL, 0
31+
))
32+
exePathLen = 0;
33+
#endif
34+
if (exePathLen > 0)
35+
exePath->length = (uint32_t) exePathLen;
36+
}
37+
1738
static void platformPathAddEnv(FFlist* dirs, const char* env)
1839
{
1940
const char* envValue = getenv(env);
@@ -90,27 +111,13 @@ static void getDataDirs(FFPlatform* platform)
90111
ffPlatformPathAddHome(&platform->dataDirs, platform, ".local/share/");
91112

92113
// Add ${currentExePath}/../share
93-
FF_STRBUF_AUTO_DESTROY exePath = ffStrbufCreateA(PATH_MAX);
94-
#ifdef __linux__
95-
ssize_t exePathLen = readlink("/proc/self/exe", exePath.chars, exePath.allocated);
96-
#elif defined(__APPLE__)
97-
int exePathLen = proc_pidpath((int) getpid(), exePath.chars, exePath.allocated);
98-
#elif defined(__FreeBSD__)
99-
size_t exePathLen = exePath.allocated;
100-
if(sysctl(
101-
(int[]){CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, (int) getpid()}, 4,
102-
exePath.chars, &exePathLen,
103-
NULL, 0
104-
))
105-
exePathLen = 0;
106-
#endif
107-
if (exePathLen > 0)
114+
if (platform->exePath.length > 0)
108115
{
109-
exePath.length = (uint32_t) exePathLen;
110-
ffStrbufSubstrBeforeLastC(&exePath, '/');
111-
ffStrbufSubstrBeforeLastC(&exePath, '/');
112-
ffStrbufAppendS(&exePath, "/share");
113-
ffPlatformPathAddAbsolute(&platform->dataDirs, exePath.chars);
116+
FF_STRBUF_AUTO_DESTROY path = ffStrbufCreateCopy(&platform->exePath);
117+
ffStrbufSubstrBeforeLastC(&path, '/');
118+
ffStrbufSubstrBeforeLastC(&path, '/');
119+
ffStrbufAppendS(&path, "/share");
120+
ffPlatformPathAddAbsolute(&platform->dataDirs, path.chars);
114121
}
115122

116123
#ifdef __APPLE__
@@ -183,6 +190,7 @@ void ffPlatformInitImpl(FFPlatform* platform)
183190
if(uname(&uts) != 0)
184191
memset(&uts, 0, sizeof(uts));
185192

193+
getExePath(platform);
186194
getHomeDir(platform, pwd);
187195
getCacheDir(platform);
188196
getConfigDirs(platform);

0 commit comments

Comments
 (0)