Debian Codegraph @

bypy/macos/util.c

raw
1 #include "util.h"
2 #include "../run-python.h"
3 #include <CoreFoundation/CoreFoundation.h>
4 #include <mach-o/dyld.h>
5
6 #define EXPORT __attribute__((visibility("default")))
7
8 #define EXE "@executable_path/.."
9
10 static const char *env_vars[] = {ENV_VARS};
11 static const char *env_var_vals[] = {ENV_VAR_VALS};
12
13 static void
14 set_env_vars(const char *contents_path) {
15 char buf[3 * PATH_MAX];
16 const char *env_var, *val;
17
18 for (size_t i = 0; i < arraysz(env_vars); i++) {
19 env_var = env_vars[i];
20 val = env_var_vals[i];
21 if (strcmp(env_var, "SSL_CERT_DIR") == 0 && getenv("CALIBRE_USE_SYSTEM_CERTIFICATES") && strcmp(getenv("CALIBRE_USE_SYSTEM_CERTIFICATES"), "1") == 0)
22 continue;
23 if (strstr(val, EXE) == val && strlen(val) >= sizeof(EXE)) {
24 snprintf(buf, sizeof(buf) - 1, "%s%s", contents_path, val + sizeof(EXE) - 1);
25 setenv(env_var, buf, 1);
26 } else setenv(env_var, val, 1);
27 }
28 return;
29 }
30
31 static void
32 get_paths(char *path) {
33 decode_char_buf(path, interpreter_data.exe_path);
34 for (unsigned i = 0; i < 3; i++) {
35 char *t = rindex(path, '/');
36 if (t == NULL) fatal("Failed to determine bundle path.");
37 *t = '\0';
38 }
39 if (strstr(path, "/calibre.app/Contents/") != NULL) {
40 // We are one of the duplicate executables created to workaround codesign's limitations
41 for (unsigned i = 0; i < 2; i++) {
42 char *t = rindex(path, '/');
43 if (t == NULL) fatal("Failed to resolve bundle path in dummy executable");
44 *t = '\0';
45 }
46 }
47 #define cat_literal(func, path, literal) func(path, literal, arraysz(literal) - 1)
48 cat_literal(strncat, path, "/Contents");
49 set_env_vars(path);
50 decode_char_buf(path, interpreter_data.bundle_resource_path);
51 #define set_path(which, fmt, ...) swprintf(interpreter_data.which, arraysz(interpreter_data.which), fmt, interpreter_data.bundle_resource_path, __VA_ARGS__)
52 set_path(python_home_path, L"%ls/Resources/Python", NULL);
53 set_path(frameworks_path, L"%ls/Frameworks", NULL);
54 set_path(python_lib_path, L"%ls/Resources/Python/lib/python%d.%d", PY_VERSION_MAJOR, PY_VERSION_MINOR);
55 set_path(extensions_path, L"%ls/Frameworks/plugins", NULL);
56 set_path(resources_path, L"%ls/Resources/resources", NULL);
57 set_path(executables_path, L"%ls/MacOS", NULL);
58 #undef set_path
59 cat_literal(wcsncat, interpreter_data.bundle_resource_path, L"/Resources");
60 #undef cat_literal
61 }
62
63 EXPORT
64 void
65 run(const wchar_t *program, const wchar_t *module, const wchar_t *function, bool gui_app, int argc, char *const *argv, char *exe_path) {
66 interpreter_data.argc = argc;
67 interpreter_data.argv = argv;
68 interpreter_data.basename = program;
69 interpreter_data.module = module;
70 interpreter_data.function = function;
71 pre_initialize_interpreter(gui_app);
72 get_paths(exe_path);
73 run_interpreter();
74 }