Debian Codegraph @

app/src/sys/unix/file.c

raw symbols SCIP
1 #include "util/file.h"
2
3 #include <limits.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <sys/stat.h>
8 #include <sys/types.h>
9 #include <unistd.h>
10 #ifdef __APPLE__
11 # include <mach-o/dyld.h> // for _NSGetExecutablePath()
12 #endif
13
14 #include "util/log.h"
15
16 bool
17 sc_file_executable_exists(const char *file) {
18 char *path = getenv("PATH");
19 if (!path)
20 return false;
21 path = strdup(path);
22 if (!path)
23 return false;
24
25 bool ret = false;
26 size_t file_len = strlen(file);
27 char *saveptr;
28 for (char *dir = strtok_r(path, ":", &saveptr); dir;
29 dir = strtok_r(NULL, ":", &saveptr)) {
30 size_t dir_len = strlen(dir);
31 char *fullpath = malloc(dir_len + file_len + 2);
32 if (!fullpath)
33 {
34 LOG_OOM();
35 continue;
36 }
37 memcpy(fullpath, dir, dir_len);
38 fullpath[dir_len] = '/';
39 memcpy(fullpath + dir_len + 1, file, file_len + 1);
40
41 struct stat sb;
42 bool fullpath_executable = stat(fullpath, &sb) == 0 &&
43 sb.st_mode & S_IXUSR;
44 free(fullpath);
45 if (fullpath_executable) {
46 ret = true;
47 break;
48 }
49 }
50
51 free(path);
52 return ret;
53 }
54
55 char *
56 sc_file_get_executable_path(void) {
57 // <https://stackoverflow.com/a/1024937/1987178>
58 #ifdef __linux__
59 char buf[PATH_MAX + 1]; // +1 for the null byte
60 ssize_t len = readlink("/proc/self/exe", buf, PATH_MAX);
61 if (len == -1) {
62 perror("readlink");
63 return NULL;
64 }
65 buf[len] = '\0';
66 return strdup(buf);
67 #elif defined(__APPLE__)
68 char buf[PATH_MAX];
69 uint32_t bufsize = PATH_MAX;
70 if (_NSGetExecutablePath(buf, &bufsize) != 0) {
71 LOGE("Executable path buffer too small; need %u bytes", bufsize);
72 return NULL;
73 }
74 return realpath(buf, NULL);
75 #else
76 // "_" is often used to store the full path of the command being executed
77 char *path = getenv("_");
78 if (!path) {
79 LOGE("Could not determine executable path");
80 return NULL;
81 }
82 return strdup(path);
83 #endif
84 }
85
86 bool
87 sc_file_is_regular(const char *path) {
88 struct stat path_stat;
89
90 if (stat(path, &path_stat)) {
91 perror("stat");
92 return false;
93 }
94 return S_ISREG(path_stat.st_mode);
95 }
96