This repository has been archived by the owner on Aug 23, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
1122 lines (1001 loc) · 37.3 KB
/
main.c
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libgen.h>
#include <sys/stat.h>
#include <pwd.h>
#include <dlfcn.h>
#include <mach-o/dyld.h>
#include <CoreFoundation/CoreFoundation.h>
#include <ApplicationServices/ApplicationServices.h>
#include <locale.h>
/*
Typedefs
*/
typedef int PyObject;
typedef PyObject* (*Py_BuildValuePtr)(const char*, ...);
#if 0
typedef void (*Py_SetPathPtr)(const wchar_t*);
#endif
typedef int (*PySys_SetObjectPtr)(const char*, PyObject*);
typedef void (*Py_SetProgramNamePtr)(const char *);
typedef void (*Py_InitializePtr)(void);
typedef int (*PyRun_SimpleFilePtr)(FILE *, const char *);
typedef void (*Py_FinalizePtr)(void);
typedef PyObject *(*PySys_GetObjectPtr)(const char *);
typedef int *(*PySys_SetArgvPtr)(int argc, char **argv);
typedef PyObject *(*PyObject_GetAttrStringPtr)(PyObject *, const char *);
typedef wchar_t* (*_Py_DecodeUTF8_surrogateescapePtr)(const char *s, ssize_t size);
typedef CFTypeRef id;
typedef const char * SEL;
typedef signed char BOOL;
#define NSAlertAlternateReturn 0
/*
Forward declarations
*/
static int report_error(const char *);
static CFTypeRef py2app_getKey(const char *key);
/*
Strings
*/
static const char *ERR_REALLYBADTITLE = "The application could not be launched.";
static const char *ERR_TITLEFORMAT = "%@ has encountered a fatal error, and will now terminate.";
static const char *ERR_NONAME = "The Info.plist file must have values for the CFBundleName or CFBundleExecutable strings.";
static const char *ERR_PYRUNTIMELOCATIONS = "The Info.plist file must have a PyRuntimeLocations array containing string values for preferred Python runtime locations. These strings should be \"otool -L\" style mach ids; \"@executable_stub\" and \"~\" prefixes will be translated accordingly.";
static const char *ERR_NOPYTHONRUNTIME = "A Python runtime not could be located. You may need to install a framework build of Python, or edit the PyRuntimeLocations array in this application's Info.plist file.";
static const char *ERR_NOPYTHONSCRIPT = "A main script could not be located in the Resources folder.;";
static const char *ERR_LINKERRFMT = "An internal error occurred while attempting to link with:\r\r%s\r\rSee the Console for a detailed dyld error message";
static const char *ERR_PYTHONEXCEPTION = "An uncaught exception was raised during execution of the main script.\r\rThis may mean that an unexpected error has occurred, or that you do not have all of the dependencies for this application.\r\rSee the Console for a detailed traceback.";
static const char *ERR_COLONPATH = "Python applications can not currently run from paths containing a '/' (or ':' from the Terminal).";
static const char *ERR_DEFAULTURLTITLE = "Visit Website";
static const char *ERR_CONSOLEAPP = "Console.app";
static const char *ERR_CONSOLEAPPTITLE = "Open Console";
static const char *ERR_TERMINATE = "Terminate";
/*
Globals
*/
static CFMutableArrayRef py2app_pool;
static CFBundleRef py2app_main_bundle;
#define USES(NAME) static __typeof__(&NAME) py2app_ ## NAME
/* ApplicationServices */
USES(LSOpenFSRef);
USES(LSFindApplicationForInfo);
USES(GetCurrentProcess);
USES(SetFrontProcess);
/* CoreFoundation */
USES(CFArrayRemoveValueAtIndex);
USES(CFStringCreateFromExternalRepresentation);
USES(CFStringAppendCString);
USES(CFStringCreateMutable);
USES(kCFTypeArrayCallBacks);
USES(CFArrayCreateMutable);
USES(CFRetain);
USES(CFRelease);
USES(CFBundleCreate);
USES(CFBundleGetValueForInfoDictionaryKey);
USES(CFArrayGetCount);
USES(CFStringCreateWithCString);
USES(CFArrayGetValueAtIndex);
USES(CFArrayAppendValue);
USES(CFStringFind);
USES(CFBundleCopyPrivateFrameworksURL);
USES(CFURLCreateWithFileSystemPathRelativeToBase);
USES(CFStringCreateWithSubstring);
USES(CFStringGetLength);
USES(CFURLGetFileSystemRepresentation);
USES(CFURLCreateWithFileSystemPath);
USES(CFShow);
USES(CFBundleCopyResourcesDirectoryURL);
USES(CFURLCreateFromFileSystemRepresentation);
USES(CFURLCreateFromFileSystemRepresentationRelativeToBase);
USES(CFStringGetCharacterAtIndex);
USES(CFURLCreateWithString);
USES(CFStringGetCString);
USES(CFStringCreateByCombiningStrings);
USES(CFDictionaryGetValue);
USES(CFBooleanGetValue);
USES(CFNumberGetValue);
USES(CFStringCreateArrayBySeparatingStrings);
USES(CFArrayAppendArray);
USES(CFStringCreateByCombiningStrings);
USES(CFStringCreateWithFormat);
USES(CFBundleCopyResourceURL);
USES(CFBundleCopyAuxiliaryExecutableURL);
USES(CFURLCreateCopyDeletingLastPathComponent);
USES(CFURLCreateCopyAppendingPathComponent);
USES(CFURLCopyLastPathComponent);
USES(CFStringGetMaximumSizeForEncoding);
#undef USES
/*
objc
*/
static id (*py2app_objc_getClass)(const char *name);
static SEL (*py2app_sel_getUid)(const char *str);
static id (*py2app_objc_msgSend)(id self, SEL op, ...);
/*
Cocoa
*/
static void (*py2app_NSLog)(CFStringRef format, ...);
static BOOL (*py2app_NSApplicationLoad)(void);
static int (*py2app_NSRunAlertPanel)(CFStringRef title, CFStringRef msg, CFStringRef defaultButton, CFStringRef alternateButton, CFStringRef otherButton, ...);
/*
Functions
*/
static int bind_objc_Cocoa_ApplicationServices(void) {
static Boolean bound = false;
if (bound) return 0;
bound = true;
void* cf_dylib;
cf_dylib = dlopen("/usr/lib/libobjc.dylib", RTLD_LAZY);
if (!cf_dylib) return -1;
#define LOOKUP(NAME) do { \
py2app_ ## NAME = (__typeof__(py2app_ ## NAME))dlsym( \
cf_dylib, #NAME); \
if (!py2app_ ## NAME) return -1; \
} while (0)
LOOKUP(objc_getClass);
LOOKUP(sel_getUid);
LOOKUP(objc_msgSend);
cf_dylib = dlopen(
"/System/Library/Frameworks/Cocoa.framework/Cocoa",
RTLD_LAZY);
if (!cf_dylib) return -1;
LOOKUP(NSLog);
LOOKUP(NSApplicationLoad);
LOOKUP(NSRunAlertPanel);
cf_dylib = dlopen(
"/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices",
RTLD_LAZY);
if (!cf_dylib) return -1;
LOOKUP(GetCurrentProcess);
LOOKUP(SetFrontProcess);
LOOKUP(LSOpenFSRef);
LOOKUP(LSFindApplicationForInfo);
#undef LOOKUP
return 0;
}
static int bind_CoreFoundation(void) {
static Boolean bound = false;
void *cf_dylib;
if (bound) return 0;
bound = true;
cf_dylib = dlopen(
"/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation",
RTLD_LAZY);
if (!cf_dylib) return -1;
#define LOOKUP(NAME) do { \
py2app_ ## NAME = (__typeof__(py2app_ ## NAME))dlsym( \
cf_dylib, #NAME); \
if (!py2app_ ## NAME) return -1; \
} while (0)
LOOKUP(CFArrayRemoveValueAtIndex);
LOOKUP(CFStringCreateFromExternalRepresentation);
LOOKUP(CFStringAppendCString);
LOOKUP(CFStringCreateMutable);
LOOKUP(kCFTypeArrayCallBacks);
LOOKUP(CFArrayCreateMutable);
LOOKUP(CFRetain);
LOOKUP(CFRelease);
LOOKUP(CFBundleCreate);
LOOKUP(CFBundleGetValueForInfoDictionaryKey);
LOOKUP(CFArrayGetCount);
LOOKUP(CFStringCreateWithCString);
LOOKUP(CFArrayGetValueAtIndex);
LOOKUP(CFArrayAppendValue);
LOOKUP(CFStringFind);
LOOKUP(CFBundleCopyPrivateFrameworksURL);
LOOKUP(CFURLCreateWithFileSystemPathRelativeToBase);
LOOKUP(CFStringCreateWithSubstring);
LOOKUP(CFStringGetLength);
LOOKUP(CFURLGetFileSystemRepresentation);
LOOKUP(CFURLCreateWithFileSystemPath);
LOOKUP(CFShow);
LOOKUP(CFBundleCopyResourcesDirectoryURL);
LOOKUP(CFURLCreateFromFileSystemRepresentation);
LOOKUP(CFURLCreateFromFileSystemRepresentationRelativeToBase);
LOOKUP(CFStringGetCharacterAtIndex);
LOOKUP(CFURLCreateWithString);
LOOKUP(CFStringGetCString);
LOOKUP(CFStringCreateByCombiningStrings);
LOOKUP(CFDictionaryGetValue);
LOOKUP(CFBooleanGetValue);
LOOKUP(CFNumberGetValue);
LOOKUP(CFStringCreateArrayBySeparatingStrings);
LOOKUP(CFArrayAppendArray);
LOOKUP(CFStringCreateByCombiningStrings);
LOOKUP(CFStringCreateWithFormat);
LOOKUP(CFBundleCopyResourceURL);
LOOKUP(CFBundleCopyAuxiliaryExecutableURL);
LOOKUP(CFURLCreateCopyDeletingLastPathComponent);
LOOKUP(CFURLCreateCopyAppendingPathComponent);
LOOKUP(CFURLCopyLastPathComponent);
LOOKUP(CFStringGetMaximumSizeForEncoding);
#undef LOOKUP
return 0;
}
#define AUTORELEASE(obj) ((obj == NULL) ? NULL : ( \
py2app_CFArrayAppendValue(py2app_pool, (const void *)obj), \
py2app_CFRelease(obj), \
obj))
#define py2app_CFSTR(s) AUTORELEASE( \
py2app_CFStringCreateWithCString(NULL, s, kCFStringEncodingUTF8))
static int py2app_openConsole(void) {
OSStatus err;
FSRef consoleRef;
err = py2app_LSFindApplicationForInfo(
kLSUnknownCreator,
NULL,
py2app_CFSTR(ERR_CONSOLEAPP),
&consoleRef,
NULL);
if (err != noErr) return err;
return py2app_LSOpenFSRef((const FSRef *)&consoleRef, NULL);
}
static CFTypeRef py2app_getKey(const char *key) {
CFTypeRef rval;
CFStringRef cfKey = py2app_CFStringCreateWithCString(NULL,
key, kCFStringEncodingUTF8);
if (!cfKey) return NULL;
rval = py2app_CFBundleGetValueForInfoDictionaryKey(
py2app_main_bundle,
cfKey);
py2app_CFRelease(cfKey);
return rval;
}
static CFStringRef py2app_getApplicationName(void) {
static CFStringRef name = NULL;
if (name) return name;
name = (CFStringRef)py2app_getKey("CFBundleName");
if (!name) name = (CFStringRef)py2app_getKey("CFBundleExecutable");
if (!name) name = py2app_CFSTR("py2app stub executable");
return AUTORELEASE(name);
}
static CFStringRef py2app_getErrorTitle(CFStringRef applicationName) {
CFStringRef res;
if (!applicationName) return py2app_CFSTR(ERR_REALLYBADTITLE);
res = py2app_CFStringCreateWithFormat(
NULL, NULL, py2app_CFSTR(ERR_TITLEFORMAT), applicationName);
(void)AUTORELEASE(res);
return res;
}
static void ensureGUI(void) {
ProcessSerialNumber psn;
id app = ((id(*)(id, SEL))py2app_objc_msgSend)(py2app_objc_getClass("NSApplication"), py2app_sel_getUid("sharedApplication"));
py2app_NSApplicationLoad();
((void(*)(id, SEL, BOOL))py2app_objc_msgSend)(app, py2app_sel_getUid("activateIgnoringOtherApps:"), 1);
if (py2app_GetCurrentProcess(&psn) == noErr) {
py2app_SetFrontProcess(&psn);
}
}
static int report_error(const char *error) {
int choice;
id releasePool;
if (bind_objc_Cocoa_ApplicationServices()) {
fprintf(stderr, "%s\n", error);
return -1;
}
releasePool = ((id(*)(id, SEL))py2app_objc_msgSend)(
((id(*)(id, SEL))py2app_objc_msgSend)(
py2app_objc_getClass("NSAutoreleasePool"),
py2app_sel_getUid("alloc")),
py2app_sel_getUid("init"));
py2app_NSLog(py2app_CFSTR("%@"), py2app_CFSTR(error));
if (!py2app_NSApplicationLoad()) {
py2app_NSLog(py2app_CFSTR("NSApplicationLoad() failed"));
} else {
ensureGUI();
choice = py2app_NSRunAlertPanel(
py2app_getErrorTitle(py2app_getApplicationName()),
py2app_CFSTR("%@"),
py2app_CFSTR(ERR_TERMINATE),
py2app_CFSTR(ERR_CONSOLEAPPTITLE),
NULL,
py2app_CFSTR(error));
if (choice == NSAlertAlternateReturn) py2app_openConsole();
}
((void(*)(id, SEL))py2app_objc_msgSend)(releasePool, py2app_sel_getUid("release"));
return -1;
}
static CFStringRef pathFromURL(CFURLRef anURL) {
UInt8 buf[PATH_MAX];
py2app_CFURLGetFileSystemRepresentation(anURL, true, buf, sizeof(buf));
return py2app_CFStringCreateWithCString(NULL, (char *)buf, kCFStringEncodingUTF8);
}
static CFStringRef pyStandardizePath(CFStringRef pyLocation) {
CFRange foundRange;
CFURLRef fmwkURL;
CFURLRef locURL;
CFStringRef subpath;
static CFStringRef prefix = NULL;
if (!prefix) prefix = py2app_CFSTR("@executable_path/");
foundRange = py2app_CFStringFind(pyLocation, prefix, 0);
if (foundRange.location == kCFNotFound || foundRange.length == 0) {
return NULL;
}
fmwkURL = py2app_CFBundleCopyPrivateFrameworksURL(py2app_main_bundle);
foundRange.location = foundRange.length;
foundRange.length = py2app_CFStringGetLength(pyLocation) - foundRange.length;
subpath = py2app_CFStringCreateWithSubstring(NULL, pyLocation, foundRange);
locURL = py2app_CFURLCreateWithFileSystemPathRelativeToBase(
NULL,
subpath,
kCFURLPOSIXPathStyle,
false,
fmwkURL);
py2app_CFRelease(subpath);
py2app_CFRelease(fmwkURL);
subpath = pathFromURL(locURL);
py2app_CFRelease(locURL);
return subpath;
}
static Boolean doesPathExist(CFStringRef path) {
struct stat st;
CFURLRef locURL;
UInt8 buf[PATH_MAX];
locURL = py2app_CFURLCreateWithFileSystemPath(
NULL, path, kCFURLPOSIXPathStyle, false);
py2app_CFURLGetFileSystemRepresentation(locURL, true, buf, sizeof(buf));
py2app_CFRelease(locURL);
return (stat((const char *)buf, &st) == -1 ? false : true);
}
static CFStringRef py2app_findPyLocation(CFArrayRef pyLocations) {
CFIndex i;
CFIndex cnt = py2app_CFArrayGetCount(pyLocations);
for (i = 0; i < cnt; i++) {
CFStringRef newLoc;
CFStringRef pyLocation = py2app_CFArrayGetValueAtIndex(pyLocations, i);
newLoc = pyStandardizePath(pyLocation);
if (!newLoc) {
newLoc = pyLocation;
py2app_CFRetain(newLoc);
}
if (doesPathExist(newLoc)) {
return newLoc;
}
if (newLoc) py2app_CFRelease(newLoc);
}
return NULL;
}
static CFStringRef tildeExpand(CFStringRef path) {
CFURLRef pathURL;
char buf[PATH_MAX];
CFURLRef fullPathURL;
struct passwd *pwnam;
char tmp;
char *dir = NULL;
py2app_CFStringGetCString(path, buf, sizeof(buf), kCFStringEncodingUTF8);
int i;
if (buf[0] != '~') {
return py2app_CFStringCreateWithCString(
NULL, buf, kCFStringEncodingUTF8);
}
/* user in path */
i = 1;
while (buf[i] != '\0' && buf[i] != '/') {
i++;
}
if (i == 1) {
dir = getenv("HOME");
} else {
tmp = buf[i];
buf[i] = '\0';
pwnam = getpwnam((const char *)&buf[1]);
if (pwnam) dir = pwnam->pw_dir;
buf[i] = tmp;
}
if (!dir) {
return py2app_CFStringCreateWithCString(NULL, buf, kCFStringEncodingUTF8);
}
pathURL = py2app_CFURLCreateFromFileSystemRepresentation(
NULL, (const UInt8*)dir, strlen(dir), false);
fullPathURL = py2app_CFURLCreateFromFileSystemRepresentationRelativeToBase(
NULL, (const UInt8*)&buf[i + 1], strlen(&buf[i + 1]), false, pathURL);
py2app_CFRelease(pathURL);
path = pathFromURL(fullPathURL);
py2app_CFRelease(fullPathURL);
return path;
}
static void setcfenv(char *name, CFStringRef value) {
char buf[PATH_MAX];
py2app_CFStringGetCString(value, buf, sizeof(buf), kCFStringEncodingUTF8);
setenv(name, buf, 1);
}
static void py2app_setPythonPath(void) {
CFMutableArrayRef paths;
CFURLRef resDir;
CFStringRef resPath;
CFArrayRef resPackages;
CFDictionaryRef options;
paths = py2app_CFArrayCreateMutable(NULL, 0, py2app_kCFTypeArrayCallBacks);
resDir = py2app_CFBundleCopyResourcesDirectoryURL(py2app_main_bundle);
resPath = pathFromURL(resDir);
py2app_CFArrayAppendValue(paths, resPath);
py2app_CFRelease(resPath);
resPackages = py2app_getKey("PyResourcePackages");
if (resPackages) {
int i;
int cnt = py2app_CFArrayGetCount(resPackages);
for (i = 0; i < cnt; i++) {
resPath = tildeExpand(py2app_CFArrayGetValueAtIndex(resPackages, i));
if (py2app_CFStringGetLength(resPath)) {
if (py2app_CFStringGetCharacterAtIndex(resPath, 0) != '/') {
CFURLRef absURL = py2app_CFURLCreateWithString(
NULL, resPath, resDir);
py2app_CFRelease(resPath);
resPath = pathFromURL(absURL);
py2app_CFRelease(absURL);
}
py2app_CFArrayAppendValue(paths, resPath);
}
py2app_CFRelease(resPath);
}
}
py2app_CFRelease(resDir);
options = py2app_getKey("PyOptions");
if (options) {
CFBooleanRef use_pythonpath;
CFNumberRef optimize;
use_pythonpath = py2app_CFDictionaryGetValue(
options, py2app_CFSTR("use_pythonpath"));
if (use_pythonpath && py2app_CFBooleanGetValue(use_pythonpath)) {
char *ppath = getenv("PYTHONPATH");
if (ppath) {
CFArrayRef oldPath;
oldPath = py2app_CFStringCreateArrayBySeparatingStrings(
NULL, py2app_CFSTR(ppath), py2app_CFSTR(":"));
if (oldPath) {
CFRange rng;
rng.location = 0;
rng.length = py2app_CFArrayGetCount(oldPath);
py2app_CFArrayAppendArray(paths, oldPath, rng);
py2app_CFRelease(oldPath);
}
}
}
optimize = py2app_CFDictionaryGetValue(
options, py2app_CFSTR("optimize"));
if (optimize) {
int v = 0;
char buf[32];
py2app_CFNumberGetValue(optimize, kCFNumberIntType, &v);
snprintf(buf, 31, "%d", v);
setenv("PYTHONOPTIMIZE", buf, 1);
}
}
if (py2app_CFArrayGetCount(paths)) {
resPath = py2app_CFStringCreateByCombiningStrings(NULL, paths, py2app_CFSTR(":"));
setcfenv("PYTHONPATH", resPath);
py2app_CFRelease(resPath);
} else {
if (getenv("PYTHONPATH") != NULL) {
unsetenv("PYTHONPATH");
}
}
py2app_CFRelease(paths);
}
static void setResourcePath(void) {
CFURLRef resDir;
CFStringRef resPath;
resDir = py2app_CFBundleCopyResourcesDirectoryURL(py2app_main_bundle);
resPath = pathFromURL(resDir);
py2app_CFRelease(resDir);
setcfenv("RESOURCEPATH", resPath);
py2app_CFRelease(resPath);
}
static void setExecutablePath(void) {
char executable_path[PATH_MAX+1];
uint32_t bufsize = PATH_MAX;
memset(executable_path, '\0', PATH_MAX+1);
if (_NSGetExecutablePath(executable_path, &bufsize) == 0) {
setenv("EXECUTABLEPATH", executable_path, 1);
}
}
static CFStringRef getMainScript(void) {
CFMutableArrayRef possibleMains;
CFBundleRef bndl;
CFStringRef e_py, e_pyc, e_pyo, path;
int i, cnt;
possibleMains = py2app_CFArrayCreateMutable(NULL, 0, py2app_kCFTypeArrayCallBacks);
CFArrayRef firstMains = py2app_getKey("PyMainFileNames");
if (firstMains) {
CFRange rng;
rng.location = 0;
rng.length = py2app_CFArrayGetCount(firstMains);
py2app_CFArrayAppendArray(possibleMains, firstMains, rng);
}
py2app_CFArrayAppendValue(possibleMains, py2app_CFSTR("__main__"));
py2app_CFArrayAppendValue(possibleMains, py2app_CFSTR("__realmain__"));
py2app_CFArrayAppendValue(possibleMains, py2app_CFSTR("Main"));
e_py = py2app_CFSTR("py");
e_pyc = py2app_CFSTR("pyc");
e_pyo = py2app_CFSTR("pyo");
cnt = py2app_CFArrayGetCount(possibleMains);
bndl = py2app_main_bundle;
path = NULL;
for (i = 0; i < cnt; i++) {
CFStringRef base;
CFURLRef resURL;
base = py2app_CFArrayGetValueAtIndex(possibleMains, i);
resURL = py2app_CFBundleCopyResourceURL(bndl, base, e_py, NULL);
if (resURL == NULL) {
resURL = py2app_CFBundleCopyResourceURL(bndl, base, e_pyc, NULL);
}
if (resURL == NULL) {
resURL = py2app_CFBundleCopyResourceURL(bndl, base, e_pyo, NULL);
}
if (resURL != NULL) {
path = pathFromURL(resURL);
py2app_CFRelease(resURL);
break;
}
}
py2app_CFRelease(possibleMains);
return path;
}
static int report_linkEdit_error(void) {
CFStringRef errString;
const char *errorString;
char* buf;
errorString = dlerror();
fputs(errorString, stderr);
errString = py2app_CFStringCreateWithFormat(
NULL, NULL, py2app_CFSTR(ERR_LINKERRFMT), errorString);
buf = alloca(py2app_CFStringGetMaximumSizeForEncoding(
py2app_CFStringGetLength(errString), kCFStringEncodingUTF8));
py2app_CFStringGetCString(errString, buf, sizeof(buf), kCFStringEncodingUTF8);
py2app_CFRelease(errString);
return report_error(buf);
}
static CFStringRef getPythonInterpreter(CFStringRef pyLocation) {
CFBundleRef bndl;
CFStringRef auxName;
CFURLRef auxURL;
CFStringRef path;
auxName = py2app_getKey("PyExecutableName");
if (!auxName) auxName = py2app_CFSTR("python");
bndl = py2app_main_bundle;
auxURL = py2app_CFBundleCopyAuxiliaryExecutableURL(bndl, auxName);
if (auxURL) {
path = pathFromURL(auxURL);
py2app_CFRelease(auxURL);
return path;
}
return NULL;
}
static CFStringRef getErrorScript(void) {
CFMutableArrayRef errorScripts;
CFBundleRef bndl;
CFStringRef path;
int i, cnt;
errorScripts = py2app_CFArrayCreateMutable(NULL, 0, py2app_kCFTypeArrayCallBacks);
CFArrayRef firstErrorScripts = py2app_getKey("PyErrorScripts");
if (firstErrorScripts) {
CFRange rng;
rng.location = 0;
rng.length = py2app_CFArrayGetCount(firstErrorScripts);
py2app_CFArrayAppendArray(errorScripts, firstErrorScripts, rng);
}
py2app_CFArrayAppendValue(errorScripts, py2app_CFSTR("__error__"));
py2app_CFArrayAppendValue(errorScripts, py2app_CFSTR("__error__.py"));
py2app_CFArrayAppendValue(errorScripts, py2app_CFSTR("__error__.pyc"));
py2app_CFArrayAppendValue(errorScripts, py2app_CFSTR("__error__.pyo"));
py2app_CFArrayAppendValue(errorScripts, py2app_CFSTR("__error__.sh"));
cnt = py2app_CFArrayGetCount(errorScripts);
bndl = py2app_main_bundle;
path = NULL;
for (i = 0; i < cnt; i++) {
CFStringRef base;
CFURLRef resURL;
base = py2app_CFArrayGetValueAtIndex(errorScripts, i);
resURL = py2app_CFBundleCopyResourceURL(bndl, base, NULL, NULL);
if (resURL) {
path = pathFromURL(resURL);
py2app_CFRelease(resURL);
break;
}
}
py2app_CFRelease(errorScripts);
return path;
}
static CFMutableArrayRef get_trimmed_lines(CFStringRef output) {
CFMutableArrayRef lines;
CFArrayRef tmp;
CFRange rng;
lines = py2app_CFArrayCreateMutable(NULL, 0, py2app_kCFTypeArrayCallBacks);
tmp = py2app_CFStringCreateArrayBySeparatingStrings(
NULL, output, py2app_CFSTR("\n"));
rng.location = 0;
rng.length = py2app_CFArrayGetCount(tmp);
py2app_CFArrayAppendArray(lines, tmp, rng);
while (true) {
CFIndex cnt = py2app_CFArrayGetCount(lines);
CFStringRef last;
/* Nothing on stdout means pass silently */
if (cnt <= 0) {
py2app_CFRelease(lines);
return NULL;
}
last = py2app_CFArrayGetValueAtIndex(lines, cnt - 1);
if (py2app_CFStringGetLength(last) > 0) break;
py2app_CFArrayRemoveValueAtIndex(lines, cnt - 1);
}
return lines;
}
static int report_script_error(const char *msg) {
CFStringRef errorScript;
CFMutableArrayRef lines;
CFRange foundRange;
CFStringRef lastLine;
CFStringRef output = NULL;
CFIndex lineCount;
CFURLRef buttonURL = NULL;
CFStringRef buttonString = NULL;
CFStringRef title = NULL;
CFStringRef errmsg = NULL;
id releasePool;
int errBinding;
int status = 0;
errorScript = getErrorScript();
if (!errorScript) return report_error(msg);
errBinding = bind_objc_Cocoa_ApplicationServices();
if (!errBinding) {
id task, stdoutPipe, taskData;
CFMutableArrayRef argv;
releasePool = ((id(*)(id, SEL))py2app_objc_msgSend)(
((id(*)(id, SEL))py2app_objc_msgSend)(
py2app_objc_getClass("NSAutoreleasePool"),
py2app_sel_getUid("alloc")),
py2app_sel_getUid("init"));
task = ((id(*)(id, SEL))py2app_objc_msgSend)(
((id(*)(id, SEL))py2app_objc_msgSend)(
py2app_objc_getClass("NSTask"),
py2app_sel_getUid("alloc")),
py2app_sel_getUid("init"));
stdoutPipe = ((id(*)(id, SEL))py2app_objc_msgSend)(py2app_objc_getClass("NSPipe"), py2app_sel_getUid("pipe"));
((void(*)(id, SEL, id))py2app_objc_msgSend)(task, py2app_sel_getUid("setLaunchPath:"), py2app_CFSTR("/bin/sh"));
((void(*)(id, SEL, id))py2app_objc_msgSend)(task, py2app_sel_getUid("setStandardOutput:"), stdoutPipe);
argv = py2app_CFArrayCreateMutable(NULL, 0, py2app_kCFTypeArrayCallBacks);
py2app_CFArrayAppendValue(argv, errorScript);
py2app_CFArrayAppendValue(argv, py2app_getApplicationName());
((void(*)(id, SEL, id))py2app_objc_msgSend)(task, py2app_sel_getUid("setArguments:"), argv);
/* This could throw, in theory, but /bin/sh should prevent that */
((void(*)(id, SEL))py2app_objc_msgSend)(task, py2app_sel_getUid("launch"));
((void(*)(id, SEL))py2app_objc_msgSend)(task, py2app_sel_getUid("waitUntilExit"));
taskData = ((id(*)(id, SEL))py2app_objc_msgSend)(
((id(*)(id, SEL))py2app_objc_msgSend)(stdoutPipe, py2app_sel_getUid("fileHandleForReading")),
py2app_sel_getUid("readDataToEndOfFile"));
py2app_CFRelease(argv);
status = ((int(*)(id, SEL))py2app_objc_msgSend)(task, py2app_sel_getUid("terminationStatus"));
py2app_CFRelease(task);
if (!status && taskData) {
output = py2app_CFStringCreateFromExternalRepresentation(
NULL, taskData, kCFStringEncodingUTF8);
}
((void(*)(id, SEL))py2app_objc_msgSend)(releasePool, py2app_sel_getUid("release"));
}
py2app_CFRelease(errorScript);
if (status || !output) return report_error(msg);
lines = get_trimmed_lines(output);
py2app_CFRelease(output);
/* Nothing on stdout means pass silently */
if (!lines) return -1;
lineCount = py2app_CFArrayGetCount(lines);
lastLine = py2app_CFArrayGetValueAtIndex(lines, lineCount - 1);
foundRange = py2app_CFStringFind(lastLine, py2app_CFSTR("ERRORURL: "), 0);
if (foundRange.location != kCFNotFound && foundRange.length != 0) {
CFMutableArrayRef buttonArr;
CFArrayRef tmp;
CFRange rng;
buttonArr = py2app_CFArrayCreateMutable(NULL, 0, py2app_kCFTypeArrayCallBacks);
tmp = py2app_CFStringCreateArrayBySeparatingStrings(
NULL, lastLine, py2app_CFSTR(" "));
lineCount -= 1;
py2app_CFArrayRemoveValueAtIndex(lines, lineCount);
rng.location = 1;
rng.length = py2app_CFArrayGetCount(tmp) - 1;
py2app_CFArrayAppendArray(buttonArr, tmp, rng);
py2app_CFRelease(tmp);
while (true) {
CFStringRef tmpstr;
if (py2app_CFArrayGetCount(buttonArr) <= 0) break;
tmpstr = py2app_CFArrayGetValueAtIndex(buttonArr, 0);
if (py2app_CFStringGetLength(tmpstr) == 0) {
py2app_CFArrayRemoveValueAtIndex(buttonArr, 0);
} else {
break;
}
}
buttonURL = py2app_CFURLCreateWithString(
NULL, py2app_CFArrayGetValueAtIndex(buttonArr, 0), NULL);
if (buttonURL) {
py2app_CFArrayRemoveValueAtIndex(buttonArr, 0);
while (true) {
CFStringRef tmpstr;
if (py2app_CFArrayGetCount(buttonArr) <= 0) break;
tmpstr = py2app_CFArrayGetValueAtIndex(buttonArr, 0);
if (py2app_CFStringGetLength(tmpstr) == 0) {
py2app_CFArrayRemoveValueAtIndex(buttonArr, 0);
} else {
break;
}
}
if (py2app_CFArrayGetCount(buttonArr) > 0) {
buttonString = py2app_CFStringCreateByCombiningStrings(
NULL, buttonArr, py2app_CFSTR(" "));
}
if (!buttonString) buttonString = py2app_CFSTR(ERR_DEFAULTURLTITLE);
}
py2app_CFRelease(buttonArr);
}
if (lineCount <= 0 || errBinding) {
py2app_CFRelease(lines);
return report_error(msg);
}
releasePool = ((id(*)(id, SEL))py2app_objc_msgSend)(
((id(*)(id, SEL))py2app_objc_msgSend)(
py2app_objc_getClass("NSAutoreleasePool"),
py2app_sel_getUid("alloc")),
py2app_sel_getUid("init"));
title = py2app_CFArrayGetValueAtIndex(lines, 0);
py2app_CFRetain(title);
(void)AUTORELEASE(title);
lineCount -= 1;
py2app_CFArrayRemoveValueAtIndex(lines, lineCount);
py2app_NSLog(py2app_CFSTR("%@"), title);
if (lineCount > 0) {
CFStringRef showerr;
errmsg = py2app_CFStringCreateByCombiningStrings(
NULL, lines, py2app_CFSTR("\r"));
(void)AUTORELEASE(errmsg);
showerr = ((id(*)(id, SEL, id))py2app_objc_msgSend)(
((id(*)(id, SEL, id))py2app_objc_msgSend)(errmsg, py2app_sel_getUid("componentsSeparatedByString:"), py2app_CFSTR("\r")),
py2app_sel_getUid("componentsJoinedByString:"), py2app_CFSTR("\n"));
py2app_NSLog(py2app_CFSTR("%@"), showerr);
} else {
errmsg = py2app_CFSTR("");
}
ensureGUI();
if (!buttonURL) {
int choice = py2app_NSRunAlertPanel(
title, py2app_CFSTR("%@"), py2app_CFSTR(ERR_TERMINATE),
py2app_CFSTR(ERR_CONSOLEAPPTITLE), NULL, errmsg);
if (choice == NSAlertAlternateReturn) py2app_openConsole();
} else {
int choice = py2app_NSRunAlertPanel(
title, py2app_CFSTR("%@"), py2app_CFSTR(ERR_TERMINATE),
buttonString, NULL, errmsg);
if (choice == NSAlertAlternateReturn) {
id ws = ((id(*)(id, SEL))py2app_objc_msgSend)(py2app_objc_getClass("NSWorkspace"), py2app_sel_getUid("sharedWorkspace"));
((void(*)(id, SEL, id))py2app_objc_msgSend)(ws, py2app_sel_getUid("openURL:"), buttonURL);
}
}
((void(*)(id, SEL))py2app_objc_msgSend)(releasePool, py2app_sel_getUid("release"));
py2app_CFRelease(lines);
return -1;
}
static int py2app_main(int argc, char * const *argv, char * const *envp) {
CFArrayRef pyLocations;
CFStringRef pyLocation;
CFStringRef mainScript;
CFStringRef pythonInterpreter;
char *resource_path;
char buf[PATH_MAX];
char c_pythonInterpreter[PATH_MAX];
char c_mainScript[PATH_MAX];
char **argv_new;
struct stat sb;
void *py_dylib;
int rval;
FILE *mainScriptFile;
char* curenv = NULL;
char* curlocale = NULL;
char exec_path[PATH_MAX+1];
uint32_t exec_path_size = sizeof(exec_path);
if (getenv("PYTHONOPTIMIZE") != NULL) {
unsetenv("PYTHONOPTIMIZE");
}
if (getenv("PYTHONDEBUG") != NULL) {
unsetenv("PYTHONDEBUG");
}
if (getenv("PYTHONDONTWRITEBYTECODE") != NULL) {
unsetenv("PYTHONDONTWRITEBYTECODE");
}
if (getenv("PYTHONIOENCODING") != NULL) {
unsetenv("PYTHONIOENCODING");
}
if (getenv("PYTHONDUMPREFS") != NULL) {
unsetenv("PYTHONDUMPREFS");
}
if (getenv("PYTHONMALLOCSTATS") != NULL) {
unsetenv("PYTHONMALLOCSTATS");
}
if (!py2app_getApplicationName()) return report_error(ERR_NONAME);
pyLocations = (CFArrayRef)py2app_getKey("PyRuntimeLocations");
if (!pyLocations) return report_error(ERR_PYRUNTIMELOCATIONS);
pyLocation = py2app_findPyLocation(pyLocations);
if (!pyLocation) return report_error(ERR_NOPYTHONRUNTIME);
setExecutablePath();
setResourcePath();
/* check for ':' in path, not compatible with Python due to Py_GetPath */
/* XXX: Could work-around by creating something in /tmp I guess */
resource_path = getenv("RESOURCEPATH");
if ((resource_path == NULL) || (strchr(resource_path, ':') != NULL)) {
return report_error(ERR_COLONPATH);
}
py2app_setPythonPath();
if (_NSGetExecutablePath(exec_path, &exec_path_size) != 0) {
fprintf(stderr, "_NSGetExecutablePath failed to find current executable\n");
return -1;
}
exec_path[exec_path_size] = '\0';
setenv("ARGVZERO", realpath(exec_path, NULL), 1);
/* Clear unwanted environment variable that could be set
* by a PyObjC bundle in a parent process. Not clearing causes
* problems in PyObjC.
*/
if (getenv("PYOBJC_BUNDLE_ADDRESS") != NULL) {
unsetenv("PYOBJC_BUNDLE_ADDRESS");
}
snprintf(buf, sizeof(buf)-1, "PYOBJC_BUNDLE_ADDRESS%ld", (long)getpid());
if (getenv(buf) != NULL) {
unsetenv(buf);
}
mainScript = getMainScript();
if (!mainScript) return report_error(ERR_NOPYTHONSCRIPT);
pythonInterpreter = getPythonInterpreter(pyLocation);
py2app_CFStringGetCString(
pythonInterpreter, c_pythonInterpreter,
sizeof(c_pythonInterpreter), kCFStringEncodingUTF8);
py2app_CFRelease(pythonInterpreter);
if (lstat(c_pythonInterpreter, &sb) == 0) {
if (!((sb.st_mode & S_IFLNK) == S_IFLNK)) {
setenv("PYTHONHOME", resource_path, 1);
}
}
py2app_CFStringGetCString(pyLocation, buf, sizeof(buf), kCFStringEncodingUTF8);
py_dylib = dlopen(buf, RTLD_LAZY);
if (!py_dylib) return report_linkEdit_error();
#define LOOKUP(NAME) \
NAME ## Ptr py2app_ ## NAME = (NAME ## Ptr)dlsym(py_dylib, #NAME); \
if (!py2app_ ## NAME) { \
return report_linkEdit_error(); \
}
#define OPT_LOOKUP(NAME) \
NAME ## Ptr py2app_ ## NAME = (NAME ## Ptr)dlsym(py_dylib, #NAME);
LOOKUP(Py_SetProgramName);
LOOKUP(Py_Initialize);
LOOKUP(PyRun_SimpleFile);
LOOKUP(Py_Finalize);
LOOKUP(PySys_GetObject);
LOOKUP(PySys_SetArgv);
LOOKUP(PyObject_GetAttrString);
LOOKUP(Py_BuildValue);
#if 0
OPT_LOOKUP(Py_SetPath);
#endif
OPT_LOOKUP(_Py_DecodeUTF8_surrogateescape);
LOOKUP(PySys_SetObject);
int isPy3K = dlsym(py_dylib, "PyBytes_FromString") != NULL;
#undef OPT_LOOKUP
#undef LOOKUP
/*
* When apps are started from the Finder (or anywhere
* except from the terminal), the LANG and LC_* variables
* aren't set in the environment. This confuses Py_Initialize
* when it tries to import the codec for UTF-8,
* therefore explicitly set the locale.
*
* Also set the LC_CTYPE environment variable because Py_Initialize
* resets the locale information using the environment :-(
*/
curlocale = setlocale(LC_ALL, NULL);
if (curlocale != NULL) {
curlocale = strdup(curlocale);
if (curlocale == NULL) {
(void)report_error("cannot save locale information");
return -1;
}
}
setlocale(LC_ALL, "en_US.UTF-8");
curenv = getenv("LC_CTYPE");
if (curenv) {
curenv = strdup(curenv);