-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmacos.h
More file actions
421 lines (359 loc) Β· 16.4 KB
/
macos.h
File metadata and controls
421 lines (359 loc) Β· 16.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
#include <limits.h> // for PATH_MAX
#include <spawn.h>
#include <stdio.h> // for snprintf
#include <stdlib.h> // for NULL, size_t, free
#include <string.h> // for strcmp, strerror, strlen
#include <unistd.h> // for usleep, exit
#include <CoreFoundation/CoreFoundation.h>
#include <objc/message.h>
#include <objc/objc.h>
#include <objc/runtime.h>
#include "logging.h"
#include "common.h"
#include "thread.h"
#define OS_NAME "macos"
// Declare needed AppKit function without including AppKit,
// to avoid difficulties with Objective-C versus pure C.
extern void NSApplicationLoad(void);
/*
* ===========================================================================
* MACOS LAUNCHER IMPLEMENTATION NOTES
* ===========================================================================
*
* This file implements macOS-specific runtime launching with careful handling
* of CoreFoundation runloop management for both GUI and non-GUI applications.
*
* RUNLOOP MODES SUPPORTED:
* - "main": Runtime runs on main thread (for -XstartOnFirstThread behavior)
* - "park": Runtime runs on pthread, main thread runs the event loop
* - "none": Runtime runs on main thread, no event loop management
* ===========================================================================
*/
extern char **environ;
static void dummy_call_back(void *info) { }
int handle_translocation(const int argc, const char *argv[]) {
// Note: This function was generated by Claude.ai. It works
// for now, but it uses internal security framework functions.
// Load Security framework
void *security_framework = lib_open("/System/Library/Frameworks/Security.framework/Security");
if (security_framework == NULL) {
LOG_DEBUG("MACOS", "Failed to load Security framework");
return 0; // Continue with normal execution
}
// Get function pointers
Boolean (*isTranslocatedFunc)(CFURLRef, Boolean *, CFErrorRef *) =
lib_sym(security_framework, "SecTranslocateIsTranslocatedURL");
CFURLRef (*getOriginalPathFunc)(CFURLRef, CFErrorRef *) =
lib_sym(security_framework, "SecTranslocateCreateOriginalPathForURL");
if (isTranslocatedFunc == NULL || getOriginalPathFunc == NULL) {
LOG_DEBUG("MACOS", "Failed to find translocation functions");
lib_close(security_framework);
return 0; // Continue with normal execution
}
// Get bundle path
CFBundleRef mainBundle = CFBundleGetMainBundle();
if (mainBundle == NULL) {
LOG_DEBUG("MACOS", "Failed to get main bundle");
lib_close(security_framework);
return 0;
}
CFURLRef bundleURL = CFBundleCopyBundleURL(mainBundle);
if (bundleURL == NULL) {
LOG_DEBUG("MACOS", "Failed to get bundle URL");
lib_close(security_framework);
return 0;
}
// Check if app is translocated
Boolean isTranslocated = FALSE;
isTranslocatedFunc(bundleURL, &isTranslocated, NULL);
if (!isTranslocated) {
LOG_DEBUG("MACOS", "Application is not translocated");
CFRelease(bundleURL);
lib_close(security_framework);
return 0; // Continue with normal execution
}
LOG_DEBUG("MACOS", "Application is translocated, finding original path");
// Get the original path
CFURLRef originalURL = getOriginalPathFunc(bundleURL, NULL);
if (originalURL == NULL) {
LOG_DEBUG("MACOS", "Failed to get original path");
CFRelease(bundleURL);
lib_close(security_framework);
return 0;
}
// Convert the URL to a filesystem path
char originalPath[PATH_MAX];
if (!CFURLGetFileSystemRepresentation(originalURL, TRUE, (UInt8*)originalPath, PATH_MAX)) {
LOG_DEBUG("MACOS", "Failed to convert URL to path");
CFRelease(originalURL);
CFRelease(bundleURL);
lib_close(security_framework);
return 0;
}
LOG_DEBUG("MACOS", "Original path: %s", originalPath);
// Get path to the executable within the bundle
CFURLRef executableURL = CFBundleCopyExecutableURL(mainBundle);
if (executableURL == NULL) {
LOG_DEBUG("MACOS", "Failed to get executable URL");
CFRelease(originalURL);
CFRelease(bundleURL);
lib_close(security_framework);
return 0;
}
char executablePath[PATH_MAX];
if (!CFURLGetFileSystemRepresentation(executableURL, TRUE, (UInt8*)executablePath, PATH_MAX)) {
LOG_DEBUG("MACOS", "Failed to convert executable URL to path");
CFRelease(executableURL);
CFRelease(originalURL);
CFRelease(bundleURL);
lib_close(security_framework);
return 0;
}
// Get relative path of executable within bundle
char bundlePath[PATH_MAX];
if (!CFURLGetFileSystemRepresentation(bundleURL, TRUE, (UInt8*)bundlePath, PATH_MAX)) {
LOG_DEBUG("MACOS", "Failed to convert bundle URL to path");
CFRelease(executableURL);
CFRelease(originalURL);
CFRelease(bundleURL);
lib_close(security_framework);
return 0;
}
char *relativeExecPath = executablePath + strlen(bundlePath);
// Construct path to original executable
char originalExecPath[PATH_MAX];
snprintf(originalExecPath, PATH_MAX, "%s%s", originalPath, relativeExecPath);
LOG_DEBUG("MACOS", "Original executable path: %s", originalExecPath);
// Remove quarantine attribute from the original bundle
char xattrCmd[PATH_MAX * 2];
snprintf(xattrCmd, PATH_MAX * 2, "xattr -dr com.apple.quarantine \"%s\"", originalPath);
LOG_DEBUG("MACOS", "Removing quarantine attribute: %s", xattrCmd);
system(xattrCmd);
// Prepare to relaunch from original location
char **args = (char **)malloc_or_die((argc + 1) * sizeof(char *), "untranslocated args");
args[0] = originalExecPath;
// Copy all arguments
for (int i = 1; i < argc; i++) {
args[i] = (char *)argv[i];
}
args[argc] = NULL;
// Clean up CF objects
CFRelease(executableURL);
CFRelease(originalURL);
CFRelease(bundleURL);
lib_close(security_framework);
// Execute the original application
LOG_DEBUG("MACOS", "Relaunching from original location");
pid_t pid;
int status = posix_spawn(&pid, originalExecPath, NULL, NULL, args, environ);
if (status == 0) {
LOG_DEBUG("MACOS", "Successfully relaunched, exiting translocated instance");
free(args);
exit(0); // Exit this translocated instance
} else {
LOG_DEBUG("MACOS", "Failed to relaunch: %s", strerror(status));
free(args);
return 0; // Continue with normal execution as fallback
}
}
// ===========================================================
// common.h FUNCTION IMPLEMENTATIONS
// ===========================================================
void setup(const int argc, const char *argv[]) {
// Thanks to https://objective-see.org/blog/blog_0x15.html.
// See doc/MACOS.md for why we have to do this.
handle_translocation(argc, argv);
}
void teardown() {}
void runloop_config(const char *directive) {
if (directive && strcmp(directive, "JVM") == 0) {
// JVM default: park main thread in event loop.
ctx_set_runloop_mode("park");
LOG_INFO("MACOS", "Setting runloop_mode to %s [auto]", "park");
}
}
void runloop_run(const char *mode) {
ctx_set_runloop_mode(mode);
LOG_INFO("MACOS", "Setting runloop_mode to %s", mode);
if (strcmp(mode, "park") == 0) {
LOG_INFO("MACOS", "Initializing runloop (park mode)");
// Signal early completion, transitioning to runloop state. This
// releases the directive thread while we block the main thread with
// this runloop.
LOG_DEBUG("MACOS", "Invoking ctx_signal_early_completion");
ctx_lock();
ctx_signal_early_completion(STATE_RUNLOOP);
ctx_unlock();
LOG_DEBUG("MACOS", "ctx_signal_early_completion invoked");
// Create a far-future timer to keep the runloop active.
// This timer is necessary to prevent the runloop from exiting immediately
// when there are no other sources/timers scheduled.
LOG_DEBUG("MACOS", "Creating far-future timer");
CFRunLoopTimerRef timer = CFRunLoopTimerCreate(kCFAllocatorDefault,
1.0e20, 0.0, 0, 0, (CFRunLoopTimerCallBack)dummy_call_back, NULL);
CFRunLoopAddTimer(CFRunLoopGetMain(), timer, kCFRunLoopDefaultMode);
CFRelease(timer);
LOG_DEBUG("MACOS", "Timer created");
// Run the main runloop.
LOG_DEBUG("MACOS", "Invoking CFRunLoopRun");
CFRunLoopRun();
LOG_DEBUG("MACOS", "CFRunLoopRun completed");
// Now that the runloop has exited, transition back to WAITING state.
ctx_lock();
if (ctx()->state == STATE_RUNLOOP) {
LOG_DEBUG("MACOS", "Transitioning from RUNLOOP to WAITING after CFRunLoopRun returned");
ctx_set_state(STATE_WAITING);
ctx_signal_main();
}
ctx_unlock();
} else {
LOG_INFO("MACOS", "Runloop mode '%s' - no event loop needed", mode);
// For non-park modes, just return normally - no early completion needed
}
}
void runloop_stop() {
// First, try to stop the runloop directly.
LOG_DEBUG("MACOS", "Invoking CFRunLoopStop");
CFRunLoopStop(CFRunLoopGetMain());
LOG_DEBUG("MACOS", "CFRunLoopStop completed");
// Note: On macOS, GUI frameworks like Java AWT/Swing fundamentally
// alter the CoreFoundation runloop state during initialization, making
// clean shutdown extremely difficult. When AWT initializes, it:
//
// 1. Adds 15+ runloop modes (vs. 1 for non-GUI apps):
// - AWTRunLoopMode
// - NSEventTrackingRunLoopMode
// - NSModalPanelRunLoopMode
// - NSGraphicsRunLoopMode
// - And 11+ others...
//
// 2. Installs event sources and timers that keep the runloop active.
//
// Once AWT has made these changes, the CFRunLoopStop function can no
// longer stop the runloop. Here are some things we tried to make it work:
//
// 1. Custom CFRunLoopSource with callbacks:
// - Created custom runloop source to signal shutdown
// - Added to default mode and signaled via CFRunLoopSourceSignal()
// - Callback never gets invoked when AWT modes dominate
//
// 2. Short polling intervals with volatile flags:
// - Used CFRunLoopRunInMode() with 0.1s timeouts
// - Checked volatile sig_atomic_t flag between iterations
// - But CFRunLoopRunInMode() NEVER RETURNS after AWT init
// - Pre-AWT: returns normally with kCFRunLoopRunTimedOut every 0.1s
// - Post-AWT: never returns, not even after minutes of waiting
// - AWT sources/timers/observers might keep runloop perpetually busy?
//
// 3. CFRunLoopWakeUp + CFRunLoopStop approach:
// - Attempted to wake up the runloop before stopping it
// - Still fails because CFRunLoopRunInMode never processes the signals
// - Main thread polling loop remains stuck in the never-returning call
//
// Therefore, as a fallback, we implement a timeout mechanism to detect
// when the runloop fails to shut down cleanly and force-exit if needed.
// Give the runloop a brief period to shut down gracefully.
const double timeout_seconds = 0.1;
const double start_time = CFAbsoluteTimeGetCurrent();
while (1) {
ctx_lock();
ThreadState current_state = ctx()->state;
int exit_code = ctx()->exit_code;
ctx_unlock();
if (current_state != STATE_RUNLOOP) break;
double elapsed = CFAbsoluteTimeGetCurrent() - start_time;
if (elapsed > timeout_seconds) {
LOG_INFO("MACOS", "CFRunLoop failed to terminate; forcing process exit", timeout_seconds);
exit(exit_code);
}
usleep(1000);
}
LOG_INFO("MACOS", "CFRunLoop has successfully terminated! ^_^");
}
int init_threads() { return SUCCESS; }
/*
* The macOS way of displaying a graphical error message.
*
* It uses Objective C calls to initialize the application,
* then create, configure, and display the alert.
*
* The reason the code is ugly and hard to read is because we
* are calling into Objective C from pure C, which goes against
* the grain of Apple's recommended technology choices.
* (If you are an expert macOS C developer reading this, please
* feel warmly invited to file an issue or PR improving this!)
*/
void show_alert(const char *title, const char *message) {
// Note: This function was generated by Claude.ai. It works, but
// we make no guarantees about its awesomeness or lack thereof. :-)
// Get necessary classes
Class NSAutoreleasePool = objc_getClass("NSAutoreleasePool");
Class NSApplication = objc_getClass("NSApplication");
Class NSString = objc_getClass("NSString");
Class NSAlert = objc_getClass("NSAlert");
// Create autorelease pool
id pool = ((id (*)(id, SEL))objc_msgSend)((id)NSAutoreleasePool, sel_registerName("alloc"));
pool = ((id (*)(id, SEL))objc_msgSend)(pool, sel_registerName("init"));
// Initialize application
((void(*)(void))NSApplicationLoad)(); // Cast the function pointer
id app = ((id (*)(id, SEL))objc_msgSend)((id)NSApplication, sel_registerName("sharedApplication"));
// Create strings
id nsTitle = ((id (*)(id, SEL, const char *))objc_msgSend)((id)NSString,
sel_registerName("stringWithUTF8String:"), title);
id nsMessage = ((id (*)(id, SEL, const char *))objc_msgSend)((id)NSString,
sel_registerName("stringWithUTF8String:"), message);
// Create and configure alert
id alert = ((id (*)(id, SEL))objc_msgSend)((id)NSAlert, sel_registerName("alloc"));
alert = ((id (*)(id, SEL))objc_msgSend)(alert, sel_registerName("init"));
((void (*)(id, SEL, id))objc_msgSend)(alert, sel_registerName("setMessageText:"), nsTitle);
((void (*)(id, SEL, id))objc_msgSend)(alert, sel_registerName("setInformativeText:"), nsMessage);
// Show alert
((void (*)(id, SEL))objc_msgSend)(alert, sel_registerName("runModal"));
// Release pool
((void (*)(id, SEL))objc_msgSend)(pool, sel_registerName("drain"));
}
/*
* The macOS way of launching a runtime.
*
* The behavior depends on the runloop mode:
* - "main": Launch on main thread with event loop (like Java's -XstartOnFirstThread flag)
* - "park": Launch on pthread, main thread runs the event loop (like OpenJDK's default behavior)
* - "none": Launch on main thread, no event loop (e.g. Python Qt apps)
*/
int launch(const LaunchFunc launch_runtime,
const size_t argc, const char **argv)
{
int runtime_result = SUCCESS;
// Note: For "park" mode, this function will be invoked from the already
// active thread, whereas for "main" and "none" modes, it will be invoked
// from the main thread. Therefore, we only need to differentiate between
// "main" and "none" here.
const char *runloop_mode = ctx_get_runloop_mode();
int main_mode = runloop_mode && strcmp(runloop_mode, "main") == 0;
if (main_mode) {
// GUI frameworks like SWT need the runtime to run on the main thread, but
// might expect the following setup to have been performed. Needs testing!
// Initialize NSApplication if needed (like OpenJDK does).
// This ensures AppKit is properly set up for GUI applications.
// It does *not* start the event loop, though; that will be the
// responsibility of the launched program within the runtime.
LOG_DEBUG("MACOS", "Invoking NSApplicationLoad (-XstartOnFirstThread style)");
NSApplicationLoad();
// Use NSAutoreleasePool for proper Objective-C memory management.
LOG_DEBUG("MACOS", "Configuring autorelease pool (-XstartOnFirstThread style)");
Class NSAutoreleasePool = objc_getClass("NSAutoreleasePool");
id pool = ((id (*)(id, SEL))objc_msgSend)((id)NSAutoreleasePool, sel_registerName("alloc"));
pool = ((id (*)(id, SEL))objc_msgSend)(pool, sel_registerName("init"));
LOG_INFO("MACOS", "Launching runtime (\"main\" mode)");
runtime_result = launch_runtime(argc, argv);
LOG_INFO("MACOS", "Runtime finished with code: %d", runtime_result);
LOG_DEBUG("MACOS", "Cleaning up autorelease pool (-XstartOnFirstThread style)");
((void (*)(id, SEL))objc_msgSend)(pool, sel_registerName("drain"));
} else {
// Either "none" or "park" mode, depending on the current thread.
LOG_INFO("MACOS", "Launching runtime");
runtime_result = launch_runtime(argc, argv);
LOG_INFO("MACOS", "Runtime finished with code: %d", runtime_result);
}
return runtime_result;
}