-
-
Notifications
You must be signed in to change notification settings - Fork 30.8k
/
launcher.c
2045 lines (1880 loc) · 65.6 KB
/
launcher.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
/*
* Copyright (C) 2011-2013 Vinay Sajip.
* Licensed to PSF under a contributor agreement.
*
* Based on the work of:
*
* Mark Hammond (original author of Python version)
* Curt Hagenlocher (job management)
*/
#include <windows.h>
#include <shlobj.h>
#include <stdio.h>
#include <tchar.h>
#define BUFSIZE 256
#define MSGSIZE 1024
/* Build options. */
#define SKIP_PREFIX
#define SEARCH_PATH
/* Error codes */
#define RC_NO_STD_HANDLES 100
#define RC_CREATE_PROCESS 101
#define RC_BAD_VIRTUAL_PATH 102
#define RC_NO_PYTHON 103
#define RC_NO_MEMORY 104
/*
* SCRIPT_WRAPPER is used to choose one of the variants of an executable built
* from this source file. If not defined, the PEP 397 Python launcher is built;
* if defined, a script launcher of the type used by setuptools is built, which
* looks for a script name related to the executable name and runs that script
* with the appropriate Python interpreter.
*
* SCRIPT_WRAPPER should be undefined in the source, and defined in a VS project
* which builds the setuptools-style launcher.
*/
#if defined(SCRIPT_WRAPPER)
#define RC_NO_SCRIPT 105
#endif
/*
* VENV_REDIRECT is used to choose the variant that looks for an adjacent or
* one-level-higher pyvenv.cfg, and uses its "home" property to locate and
* launch the original python.exe.
*/
#if defined(VENV_REDIRECT)
#define RC_NO_VENV_CFG 106
#define RC_BAD_VENV_CFG 107
#endif
/* Just for now - static definition */
static FILE * log_fp = NULL;
static wchar_t *
skip_whitespace(wchar_t * p)
{
while (*p && isspace(*p))
++p;
return p;
}
static void
debug(wchar_t * format, ...)
{
va_list va;
if (log_fp != NULL) {
va_start(va, format);
vfwprintf_s(log_fp, format, va);
va_end(va);
}
}
static void
winerror(int rc, wchar_t * message, int size)
{
FormatMessageW(
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, rc, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
message, size, NULL);
}
static void
error(int rc, wchar_t * format, ... )
{
va_list va;
wchar_t message[MSGSIZE];
wchar_t win_message[MSGSIZE];
int len;
va_start(va, format);
len = _vsnwprintf_s(message, MSGSIZE, _TRUNCATE, format, va);
va_end(va);
if (rc == 0) { /* a Windows error */
winerror(GetLastError(), win_message, MSGSIZE);
if (len >= 0) {
_snwprintf_s(&message[len], MSGSIZE - len, _TRUNCATE, L": %ls",
win_message);
}
}
#if !defined(_WINDOWS)
fwprintf(stderr, L"%ls\n", message);
#else
MessageBoxW(NULL, message, L"Python Launcher is sorry to say ...",
MB_OK);
#endif
exit(rc);
}
/*
* This function is here to simplify memory management
* and to treat blank values as if they are absent.
*/
static wchar_t * get_env(wchar_t * key)
{
/* This is not thread-safe, just like getenv */
static wchar_t buf[BUFSIZE];
DWORD result = GetEnvironmentVariableW(key, buf, BUFSIZE);
if (result >= BUFSIZE) {
/* Large environment variable. Accept some leakage */
wchar_t *buf2 = (wchar_t*)malloc(sizeof(wchar_t) * (result+1));
if (buf2 == NULL) {
error(RC_NO_MEMORY, L"Could not allocate environment buffer");
}
GetEnvironmentVariableW(key, buf2, result);
return buf2;
}
if (result == 0)
/* Either some error, e.g. ERROR_ENVVAR_NOT_FOUND,
or an empty environment variable. */
return NULL;
return buf;
}
#if defined(_DEBUG)
/* Do not define EXECUTABLEPATH_VALUE in debug builds as it'll
never point to the debug build. */
#if defined(_WINDOWS)
#define PYTHON_EXECUTABLE L"pythonw_d.exe"
#else
#define PYTHON_EXECUTABLE L"python_d.exe"
#endif
#else
#if defined(_WINDOWS)
#define PYTHON_EXECUTABLE L"pythonw.exe"
#define EXECUTABLEPATH_VALUE L"WindowedExecutablePath"
#else
#define PYTHON_EXECUTABLE L"python.exe"
#define EXECUTABLEPATH_VALUE L"ExecutablePath"
#endif
#endif
#define MAX_VERSION_SIZE 8
typedef struct {
wchar_t version[MAX_VERSION_SIZE]; /* m.n */
int bits; /* 32 or 64 */
wchar_t executable[MAX_PATH];
wchar_t exe_display[MAX_PATH];
} INSTALLED_PYTHON;
/*
* To avoid messing about with heap allocations, just assume we can allocate
* statically and never have to deal with more versions than this.
*/
#define MAX_INSTALLED_PYTHONS 100
static INSTALLED_PYTHON installed_pythons[MAX_INSTALLED_PYTHONS];
static size_t num_installed_pythons = 0;
/*
* To hold SOFTWARE\Python\PythonCore\X.Y...\InstallPath
* The version name can be longer than MAX_VERSION_SIZE, but will be
* truncated to just X.Y for comparisons.
*/
#define IP_BASE_SIZE 80
#define IP_VERSION_SIZE 8
#define IP_SIZE (IP_BASE_SIZE + IP_VERSION_SIZE)
#define CORE_PATH L"SOFTWARE\\Python\\PythonCore"
/*
* Installations from the Microsoft Store will set the same registry keys,
* but because of a limitation in Windows they cannot be enumerated normally
* (unless you have no other Python installations... which is probably false
* because that's the most likely way to get this launcher!)
* This key is under HKEY_LOCAL_MACHINE
*/
#define LOOKASIDE_PATH L"SOFTWARE\\Microsoft\\AppModel\\Lookaside\\user\\Software\\Python\\PythonCore"
static wchar_t * location_checks[] = {
L"\\",
L"\\PCbuild\\win32\\",
L"\\PCbuild\\amd64\\",
/* To support early 32bit versions of Python that stuck the build binaries
* directly in PCbuild... */
L"\\PCbuild\\",
NULL
};
static INSTALLED_PYTHON *
find_existing_python(const wchar_t * path)
{
INSTALLED_PYTHON * result = NULL;
size_t i;
INSTALLED_PYTHON * ip;
for (i = 0, ip = installed_pythons; i < num_installed_pythons; i++, ip++) {
if (_wcsicmp(path, ip->executable) == 0) {
result = ip;
break;
}
}
return result;
}
static INSTALLED_PYTHON *
find_existing_python2(int bits, const wchar_t * version)
{
INSTALLED_PYTHON * result = NULL;
size_t i;
INSTALLED_PYTHON * ip;
for (i = 0, ip = installed_pythons; i < num_installed_pythons; i++, ip++) {
if (bits == ip->bits && _wcsicmp(version, ip->version) == 0) {
result = ip;
break;
}
}
return result;
}
static void
_locate_pythons_for_key(HKEY root, LPCWSTR subkey, REGSAM flags, int bits,
int display_name_only)
{
HKEY core_root, ip_key;
LSTATUS status = RegOpenKeyExW(root, subkey, 0, flags, &core_root);
wchar_t message[MSGSIZE];
DWORD i;
size_t n;
BOOL ok, append_name;
DWORD type, data_size, attrs;
INSTALLED_PYTHON * ip, * pip;
wchar_t ip_version[IP_VERSION_SIZE];
wchar_t ip_path[IP_SIZE];
wchar_t * check;
wchar_t ** checkp;
wchar_t *key_name = (root == HKEY_LOCAL_MACHINE) ? L"HKLM" : L"HKCU";
if (status != ERROR_SUCCESS)
debug(L"locate_pythons_for_key: unable to open PythonCore key in %ls\n",
key_name);
else {
ip = &installed_pythons[num_installed_pythons];
for (i = 0; num_installed_pythons < MAX_INSTALLED_PYTHONS; i++) {
status = RegEnumKeyW(core_root, i, ip_version, IP_VERSION_SIZE);
if (status != ERROR_SUCCESS) {
if (status != ERROR_NO_MORE_ITEMS) {
/* unexpected error */
winerror(status, message, MSGSIZE);
debug(L"Can't enumerate registry key for version %ls: %ls\n",
ip_version, message);
}
break;
}
else {
wcsncpy_s(ip->version, MAX_VERSION_SIZE, ip_version,
MAX_VERSION_SIZE-1);
/* Still treating version as "x.y" rather than sys.winver
* When PEP 514 tags are properly used, we shouldn't need
* to strip this off here.
*/
check = wcsrchr(ip->version, L'-');
if (check && !wcscmp(check, L"-32")) {
*check = L'\0';
}
_snwprintf_s(ip_path, IP_SIZE, _TRUNCATE,
L"%ls\\%ls\\InstallPath", subkey, ip_version);
status = RegOpenKeyExW(root, ip_path, 0, flags, &ip_key);
if (status != ERROR_SUCCESS) {
winerror(status, message, MSGSIZE);
/* Note: 'message' already has a trailing \n*/
debug(L"%ls\\%ls: %ls", key_name, ip_path, message);
continue;
}
data_size = sizeof(ip->executable) - 1;
append_name = FALSE;
#ifdef EXECUTABLEPATH_VALUE
status = RegQueryValueExW(ip_key, EXECUTABLEPATH_VALUE, NULL, &type,
(LPBYTE)ip->executable, &data_size);
#else
status = ERROR_FILE_NOT_FOUND; /* actual error doesn't matter */
#endif
if (status != ERROR_SUCCESS || type != REG_SZ || !data_size) {
append_name = TRUE;
data_size = sizeof(ip->executable) - 1;
status = RegQueryValueExW(ip_key, NULL, NULL, &type,
(LPBYTE)ip->executable, &data_size);
if (status != ERROR_SUCCESS) {
winerror(status, message, MSGSIZE);
debug(L"%ls\\%ls: %ls\n", key_name, ip_path, message);
RegCloseKey(ip_key);
continue;
}
}
RegCloseKey(ip_key);
if (type != REG_SZ) {
continue;
}
data_size = data_size / sizeof(wchar_t) - 1; /* for NUL */
if (ip->executable[data_size - 1] == L'\\')
--data_size; /* reg value ended in a backslash */
/* ip->executable is data_size long */
for (checkp = location_checks; *checkp; ++checkp) {
check = *checkp;
if (append_name) {
_snwprintf_s(&ip->executable[data_size],
MAX_PATH - data_size,
MAX_PATH - data_size,
L"%ls%ls", check, PYTHON_EXECUTABLE);
}
attrs = GetFileAttributesW(ip->executable);
if (attrs == INVALID_FILE_ATTRIBUTES) {
winerror(GetLastError(), message, MSGSIZE);
debug(L"locate_pythons_for_key: %ls: %ls",
ip->executable, message);
}
else if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
debug(L"locate_pythons_for_key: '%ls' is a directory\n",
ip->executable);
}
else if (find_existing_python(ip->executable)) {
debug(L"locate_pythons_for_key: %ls: already found\n",
ip->executable);
}
else {
/* check the executable type. */
if (bits) {
ip->bits = bits;
} else {
ok = GetBinaryTypeW(ip->executable, &attrs);
if (!ok) {
debug(L"Failure getting binary type: %ls\n",
ip->executable);
}
else {
if (attrs == SCS_64BIT_BINARY)
ip->bits = 64;
else if (attrs == SCS_32BIT_BINARY)
ip->bits = 32;
else
ip->bits = 0;
}
}
if (ip->bits == 0) {
debug(L"locate_pythons_for_key: %ls: \
invalid binary type: %X\n",
ip->executable, attrs);
}
else {
if (display_name_only) {
/* display just the executable name. This is
* primarily for the Store installs */
const wchar_t *name = wcsrchr(ip->executable, L'\\');
if (name) {
wcscpy_s(ip->exe_display, MAX_PATH, name+1);
}
}
if (wcschr(ip->executable, L' ') != NULL) {
/* has spaces, so quote, and set original as
* the display name */
if (!ip->exe_display[0]) {
wcscpy_s(ip->exe_display, MAX_PATH, ip->executable);
}
n = wcslen(ip->executable);
memmove(&ip->executable[1],
ip->executable, n * sizeof(wchar_t));
ip->executable[0] = L'\"';
ip->executable[n + 1] = L'\"';
ip->executable[n + 2] = L'\0';
}
debug(L"locate_pythons_for_key: %ls \
is a %dbit executable\n",
ip->executable, ip->bits);
if (find_existing_python2(ip->bits, ip->version)) {
debug(L"locate_pythons_for_key: %ls-%i: already \
found\n", ip->version, ip->bits);
}
else {
++num_installed_pythons;
pip = ip++;
if (num_installed_pythons >=
MAX_INSTALLED_PYTHONS)
break;
}
}
}
}
}
}
RegCloseKey(core_root);
}
}
static int
compare_pythons(const void * p1, const void * p2)
{
INSTALLED_PYTHON * ip1 = (INSTALLED_PYTHON *) p1;
INSTALLED_PYTHON * ip2 = (INSTALLED_PYTHON *) p2;
/* note reverse sorting on version */
int result = CompareStringW(LOCALE_INVARIANT, SORT_DIGITSASNUMBERS,
ip2->version, -1, ip1->version, -1);
switch (result) {
case 0:
error(0, L"CompareStringW failed");
return 0;
case CSTR_LESS_THAN:
return -1;
case CSTR_EQUAL:
return ip2->bits - ip1->bits; /* 64 before 32 */
case CSTR_GREATER_THAN:
return 1;
default:
return 0; // This should never be reached.
}
}
static void
locate_pythons_for_key(HKEY root, REGSAM flags)
{
_locate_pythons_for_key(root, CORE_PATH, flags, 0, FALSE);
}
static void
locate_store_pythons(void)
{
#if defined(_M_X64)
/* 64bit process, so look in native registry */
_locate_pythons_for_key(HKEY_LOCAL_MACHINE, LOOKASIDE_PATH,
KEY_READ, 64, TRUE);
#else
/* 32bit process, so check that we're on 64bit OS */
BOOL f64 = FALSE;
if (IsWow64Process(GetCurrentProcess(), &f64) && f64) {
_locate_pythons_for_key(HKEY_LOCAL_MACHINE, LOOKASIDE_PATH,
KEY_READ | KEY_WOW64_64KEY, 64, TRUE);
}
#endif
}
static void
locate_venv_python(void)
{
static wchar_t venv_python[MAX_PATH];
INSTALLED_PYTHON * ip;
wchar_t *virtual_env = get_env(L"VIRTUAL_ENV");
DWORD attrs;
/* Check for VIRTUAL_ENV environment variable */
if (virtual_env == NULL || virtual_env[0] == L'\0') {
return;
}
/* Check for a python executable in the venv */
debug(L"Checking for Python executable in virtual env '%ls'\n", virtual_env);
_snwprintf_s(venv_python, MAX_PATH, _TRUNCATE,
L"%ls\\Scripts\\%ls", virtual_env, PYTHON_EXECUTABLE);
attrs = GetFileAttributesW(venv_python);
if (attrs == INVALID_FILE_ATTRIBUTES) {
debug(L"Python executable %ls missing from virtual env\n", venv_python);
return;
}
ip = &installed_pythons[num_installed_pythons++];
wcscpy_s(ip->executable, MAX_PATH, venv_python);
ip->bits = 0;
wcscpy_s(ip->version, MAX_VERSION_SIZE, L"venv");
}
static void
locate_all_pythons(void)
{
/* venv Python is highest priority */
locate_venv_python();
#if defined(_M_X64)
/* If we are a 64bit process, first hit the 32bit keys. */
debug(L"locating Pythons in 32bit registry\n");
locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ | KEY_WOW64_32KEY);
locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ | KEY_WOW64_32KEY);
#else
/* If we are a 32bit process on a 64bit Windows, first hit the 64bit keys.*/
BOOL f64 = FALSE;
if (IsWow64Process(GetCurrentProcess(), &f64) && f64) {
debug(L"locating Pythons in 64bit registry\n");
locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ | KEY_WOW64_64KEY);
locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ | KEY_WOW64_64KEY);
}
#endif
/* now hit the "native" key for this process bittedness. */
debug(L"locating Pythons in native registry\n");
locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ);
locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ);
/* Store-installed Python is lowest priority */
locate_store_pythons();
qsort(installed_pythons, num_installed_pythons, sizeof(INSTALLED_PYTHON),
compare_pythons);
}
static INSTALLED_PYTHON *
find_python_by_version(wchar_t const * wanted_ver)
{
INSTALLED_PYTHON * result = NULL;
INSTALLED_PYTHON * ip = installed_pythons;
size_t i, n;
size_t wlen = wcslen(wanted_ver);
int bits = 0;
if (wcsstr(wanted_ver, L"-32")) {
bits = 32;
wlen -= wcslen(L"-32");
}
else if (wcsstr(wanted_ver, L"-64")) { /* Added option to select 64 bit explicitly */
bits = 64;
wlen -= wcslen(L"-64");
}
for (i = 0; i < num_installed_pythons; i++, ip++) {
n = wcslen(ip->version);
/*
* If wlen is greater than 1, we're probably trying to find a specific
* version and thus want an exact match: 3.1 != 3.10. Otherwise, we
* just want a prefix match.
*/
if ((wlen > 1) && (n != wlen)) {
continue;
}
if (n > wlen) {
n = wlen;
}
if ((wcsncmp(ip->version, wanted_ver, n) == 0) &&
/* bits == 0 => don't care */
((bits == 0) || (ip->bits == bits))) {
result = ip;
break;
}
}
return result;
}
static wchar_t appdata_ini_path[MAX_PATH];
static wchar_t launcher_ini_path[MAX_PATH];
/*
* Get a value either from the environment or a configuration file.
* The key passed in will either be "python", "python2" or "python3".
*/
static wchar_t *
get_configured_value(wchar_t * key)
{
/*
* Note: this static value is used to return a configured value
* obtained either from the environment or configuration file.
* This should be OK since there wouldn't be any concurrent calls.
*/
static wchar_t configured_value[MSGSIZE];
wchar_t * result = NULL;
wchar_t * found_in = L"environment";
DWORD size;
/* First, search the environment. */
_snwprintf_s(configured_value, MSGSIZE, _TRUNCATE, L"py_%ls", key);
result = get_env(configured_value);
if (result == NULL && appdata_ini_path[0]) {
/* Not in environment: check local configuration. */
size = GetPrivateProfileStringW(L"defaults", key, NULL,
configured_value, MSGSIZE,
appdata_ini_path);
if (size > 0) {
result = configured_value;
found_in = appdata_ini_path;
}
}
if (result == NULL && launcher_ini_path[0]) {
/* Not in environment or local: check global configuration. */
size = GetPrivateProfileStringW(L"defaults", key, NULL,
configured_value, MSGSIZE,
launcher_ini_path);
if (size > 0) {
result = configured_value;
found_in = launcher_ini_path;
}
}
if (result) {
debug(L"found configured value '%ls=%ls' in %ls\n",
key, result, found_in ? found_in : L"(unknown)");
} else {
debug(L"found no configured value for '%ls'\n", key);
}
return result;
}
static INSTALLED_PYTHON *
locate_python(wchar_t * wanted_ver, BOOL from_shebang)
{
static wchar_t config_key [] = { L"pythonX" };
static wchar_t * last_char = &config_key[sizeof(config_key) /
sizeof(wchar_t) - 2];
INSTALLED_PYTHON * result = NULL;
size_t n = wcslen(wanted_ver);
wchar_t * configured_value;
if (num_installed_pythons == 0)
locate_all_pythons();
if (n == 1) { /* just major version specified */
*last_char = *wanted_ver;
configured_value = get_configured_value(config_key);
if (configured_value != NULL)
wanted_ver = configured_value;
}
if (*wanted_ver) {
result = find_python_by_version(wanted_ver);
debug(L"search for Python version '%ls' found ", wanted_ver);
if (result) {
debug(L"'%ls'\n", result->executable);
} else {
debug(L"no interpreter\n");
}
}
else {
*last_char = L'\0'; /* look for an overall default */
result = find_python_by_version(L"venv");
if (result == NULL) {
configured_value = get_configured_value(config_key);
if (configured_value)
result = find_python_by_version(configured_value);
}
/* Not found a value yet - try by major version.
* If we're looking for an interpreter specified in a shebang line,
* we want to try Python 2 first, then Python 3 (for Unix and backward
* compatibility). If we're being called interactively, assume the user
* wants the latest version available, so try Python 3 first, then
* Python 2.
*/
if (result == NULL)
result = find_python_by_version(from_shebang ? L"2" : L"3");
if (result == NULL)
result = find_python_by_version(from_shebang ? L"3" : L"2");
debug(L"search for default Python found ");
if (result) {
debug(L"version %ls at '%ls'\n",
result->version, result->executable);
} else {
debug(L"no interpreter\n");
}
}
return result;
}
#if defined(SCRIPT_WRAPPER)
/*
* Check for a script located alongside the executable
*/
#if defined(_WINDOWS)
#define SCRIPT_SUFFIX L"-script.pyw"
#else
#define SCRIPT_SUFFIX L"-script.py"
#endif
static wchar_t wrapped_script_path[MAX_PATH];
/* Locate the script being wrapped.
*
* This code should store the name of the wrapped script in
* wrapped_script_path, or terminate the program with an error if there is no
* valid wrapped script file.
*/
static void
locate_wrapped_script(void)
{
wchar_t * p;
size_t plen;
DWORD attrs;
plen = GetModuleFileNameW(NULL, wrapped_script_path, MAX_PATH);
p = wcsrchr(wrapped_script_path, L'.');
if (p == NULL) {
debug(L"GetModuleFileNameW returned value has no extension: %ls\n",
wrapped_script_path);
error(RC_NO_SCRIPT, L"Wrapper name '%ls' is not valid.", wrapped_script_path);
}
wcsncpy_s(p, MAX_PATH - (p - wrapped_script_path) + 1, SCRIPT_SUFFIX, _TRUNCATE);
attrs = GetFileAttributesW(wrapped_script_path);
if (attrs == INVALID_FILE_ATTRIBUTES) {
debug(L"File '%ls' non-existent\n", wrapped_script_path);
error(RC_NO_SCRIPT, L"Script file '%ls' is not present.", wrapped_script_path);
}
debug(L"Using wrapped script file '%ls'\n", wrapped_script_path);
}
#endif
/*
* Process creation code
*/
static BOOL
safe_duplicate_handle(HANDLE in, HANDLE * pout)
{
BOOL ok;
HANDLE process = GetCurrentProcess();
DWORD rc;
*pout = NULL;
ok = DuplicateHandle(process, in, process, pout, 0, TRUE,
DUPLICATE_SAME_ACCESS);
if (!ok) {
rc = GetLastError();
if (rc == ERROR_INVALID_HANDLE) {
debug(L"DuplicateHandle returned ERROR_INVALID_HANDLE\n");
ok = TRUE;
}
else {
debug(L"DuplicateHandle returned %d\n", rc);
}
}
return ok;
}
static BOOL WINAPI
ctrl_c_handler(DWORD code)
{
return TRUE; /* We just ignore all control events. */
}
static void
run_child(wchar_t * cmdline)
{
HANDLE job;
JOBOBJECT_EXTENDED_LIMIT_INFORMATION info;
DWORD rc;
BOOL ok;
STARTUPINFOW si;
PROCESS_INFORMATION pi;
#if defined(_WINDOWS)
/*
When explorer launches a Windows (GUI) application, it displays
the "app starting" (the "pointer + hourglass") cursor for a number
of seconds, or until the app does something UI-ish (eg, creating a
window, or fetching a message). As this launcher doesn't do this
directly, that cursor remains even after the child process does these
things. We avoid that by doing a simple post+get message.
See http://bugs.python.org/issue17290
*/
MSG msg;
PostMessage(0, 0, 0, 0);
GetMessage(&msg, 0, 0, 0);
#endif
debug(L"run_child: about to run '%ls'\n", cmdline);
job = CreateJobObject(NULL, NULL);
ok = QueryInformationJobObject(job, JobObjectExtendedLimitInformation,
&info, sizeof(info), &rc);
if (!ok || (rc != sizeof(info)) || !job)
error(RC_CREATE_PROCESS, L"Job information querying failed");
info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE |
JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK;
ok = SetInformationJobObject(job, JobObjectExtendedLimitInformation, &info,
sizeof(info));
if (!ok)
error(RC_CREATE_PROCESS, L"Job information setting failed");
memset(&si, 0, sizeof(si));
GetStartupInfoW(&si);
ok = safe_duplicate_handle(GetStdHandle(STD_INPUT_HANDLE), &si.hStdInput);
if (!ok)
error(RC_NO_STD_HANDLES, L"stdin duplication failed");
ok = safe_duplicate_handle(GetStdHandle(STD_OUTPUT_HANDLE), &si.hStdOutput);
if (!ok)
error(RC_NO_STD_HANDLES, L"stdout duplication failed");
ok = safe_duplicate_handle(GetStdHandle(STD_ERROR_HANDLE), &si.hStdError);
if (!ok)
error(RC_NO_STD_HANDLES, L"stderr duplication failed");
ok = SetConsoleCtrlHandler(ctrl_c_handler, TRUE);
if (!ok)
error(RC_CREATE_PROCESS, L"control handler setting failed");
si.dwFlags = STARTF_USESTDHANDLES;
ok = CreateProcessW(NULL, cmdline, NULL, NULL, TRUE,
0, NULL, NULL, &si, &pi);
if (!ok)
error(RC_CREATE_PROCESS, L"Unable to create process using '%ls'", cmdline);
AssignProcessToJobObject(job, pi.hProcess);
CloseHandle(pi.hThread);
WaitForSingleObjectEx(pi.hProcess, INFINITE, FALSE);
ok = GetExitCodeProcess(pi.hProcess, &rc);
if (!ok)
error(RC_CREATE_PROCESS, L"Failed to get exit code of process");
debug(L"child process exit code: %d\n", rc);
exit(rc);
}
static void
invoke_child(wchar_t * executable, wchar_t * suffix, wchar_t * cmdline)
{
wchar_t * child_command;
size_t child_command_size;
BOOL no_suffix = (suffix == NULL) || (*suffix == L'\0');
BOOL no_cmdline = (*cmdline == L'\0');
if (no_suffix && no_cmdline)
run_child(executable);
else {
if (no_suffix) {
/* add 2 for space separator + terminating NUL. */
child_command_size = wcslen(executable) + wcslen(cmdline) + 2;
}
else {
/* add 3 for 2 space separators + terminating NUL. */
child_command_size = wcslen(executable) + wcslen(suffix) +
wcslen(cmdline) + 3;
}
child_command = calloc(child_command_size, sizeof(wchar_t));
if (child_command == NULL)
error(RC_CREATE_PROCESS, L"unable to allocate %zd bytes for child command.",
child_command_size);
if (no_suffix)
_snwprintf_s(child_command, child_command_size,
child_command_size - 1, L"%ls %ls",
executable, cmdline);
else
_snwprintf_s(child_command, child_command_size,
child_command_size - 1, L"%ls %ls %ls",
executable, suffix, cmdline);
run_child(child_command);
free(child_command);
}
}
typedef struct {
wchar_t *shebang;
BOOL search;
} SHEBANG;
static SHEBANG builtin_virtual_paths [] = {
{ L"/usr/bin/env python", TRUE },
{ L"/usr/bin/python", FALSE },
{ L"/usr/local/bin/python", FALSE },
{ L"python", FALSE },
{ NULL, FALSE },
};
/* For now, a static array of commands. */
#define MAX_COMMANDS 100
typedef struct {
wchar_t key[MAX_PATH];
wchar_t value[MSGSIZE];
} COMMAND;
static COMMAND commands[MAX_COMMANDS];
static int num_commands = 0;
#if defined(SKIP_PREFIX)
static wchar_t * builtin_prefixes [] = {
/* These must be in an order that the longest matches should be found,
* i.e. if the prefix is "/usr/bin/env ", it should match that entry
* *before* matching "/usr/bin/".
*/
L"/usr/bin/env ",
L"/usr/bin/",
L"/usr/local/bin/",
NULL
};
static wchar_t * skip_prefix(wchar_t * name)
{
wchar_t ** pp = builtin_prefixes;
wchar_t * result = name;
wchar_t * p;
size_t n;
for (; p = *pp; pp++) {
n = wcslen(p);
if (_wcsnicmp(p, name, n) == 0) {
result += n; /* skip the prefix */
if (p[n - 1] == L' ') /* No empty strings in table, so n > 1 */
result = skip_whitespace(result);
break;
}
}
return result;
}
#endif
#if defined(SEARCH_PATH)
static COMMAND path_command;
static COMMAND * find_on_path(wchar_t * name)
{
wchar_t * pathext;
size_t varsize;
wchar_t * context = NULL;
wchar_t * extension;
COMMAND * result = NULL;
DWORD len;
errno_t rc;
wcscpy_s(path_command.key, MAX_PATH, name);
if (wcschr(name, L'.') != NULL) {
/* assume it has an extension. */
len = SearchPathW(NULL, name, NULL, MSGSIZE, path_command.value, NULL);
if (len) {
result = &path_command;
}
}
else {
/* No extension - search using registered extensions. */
rc = _wdupenv_s(&pathext, &varsize, L"PATHEXT");
if (rc == 0) {
extension = wcstok_s(pathext, L";", &context);
while (extension) {
len = SearchPathW(NULL, name, extension, MSGSIZE, path_command.value, NULL);
if (len) {
result = &path_command;
break;
}
extension = wcstok_s(NULL, L";", &context);
}
free(pathext);
}
}
return result;
}
#endif
static COMMAND * find_command(wchar_t * name)
{
COMMAND * result = NULL;
COMMAND * cp = commands;
int i;
for (i = 0; i < num_commands; i++, cp++) {
if (_wcsicmp(cp->key, name) == 0) {
result = cp;
break;
}
}
#if defined(SEARCH_PATH)
if (result == NULL)
result = find_on_path(name);
#endif
return result;
}
static void
update_command(COMMAND * cp, wchar_t * name, wchar_t * cmdline)
{
wcsncpy_s(cp->key, MAX_PATH, name, _TRUNCATE);
wcsncpy_s(cp->value, MSGSIZE, cmdline, _TRUNCATE);
}
static void
add_command(wchar_t * name, wchar_t * cmdline)
{
if (num_commands >= MAX_COMMANDS) {
debug(L"can't add %ls = '%ls': no room\n", name, cmdline);
}
else {
COMMAND * cp = &commands[num_commands++];
update_command(cp, name, cmdline);
}
}