1 /*
2  * Copyright (C) 2011-2013 Vinay Sajip.
3  * Licensed to PSF under a contributor agreement.
4  *
5  * Based on the work of:
6  *
7  * Mark Hammond (original author of Python version)
8  * Curt Hagenlocher (job management)
9  */
10 
11 #include <windows.h>
12 #include <shlobj.h>
13 #include <stdio.h>
14 #include <tchar.h>
15 
16 #define BUFSIZE 256
17 #define MSGSIZE 1024
18 
19 /* Build options. */
20 #define SKIP_PREFIX
21 #define SEARCH_PATH
22 
23 /* Error codes */
24 
25 #define RC_NO_STD_HANDLES   100
26 #define RC_CREATE_PROCESS   101
27 #define RC_BAD_VIRTUAL_PATH 102
28 #define RC_NO_PYTHON        103
29 #define RC_NO_MEMORY        104
30 /*
31  * SCRIPT_WRAPPER is used to choose one of the variants of an executable built
32  * from this source file. If not defined, the PEP 397 Python launcher is built;
33  * if defined, a script launcher of the type used by setuptools is built, which
34  * looks for a script name related to the executable name and runs that script
35  * with the appropriate Python interpreter.
36  *
37  * SCRIPT_WRAPPER should be undefined in the source, and defined in a VS project
38  * which builds the setuptools-style launcher.
39  */
40 #if defined(SCRIPT_WRAPPER)
41 #define RC_NO_SCRIPT        105
42 #endif
43 /*
44  * VENV_REDIRECT is used to choose the variant that looks for an adjacent or
45  * one-level-higher pyvenv.cfg, and uses its "home" property to locate and
46  * launch the original python.exe.
47  */
48 #if defined(VENV_REDIRECT)
49 #define RC_NO_VENV_CFG      106
50 #define RC_BAD_VENV_CFG     107
51 #endif
52 
53 /* Just for now - static definition */
54 
55 static FILE * log_fp = NULL;
56 
57 static wchar_t *
skip_whitespace(wchar_t * p)58 skip_whitespace(wchar_t * p)
59 {
60     while (*p && isspace(*p))
61         ++p;
62     return p;
63 }
64 
65 static void
debug(wchar_t * format,...)66 debug(wchar_t * format, ...)
67 {
68     va_list va;
69 
70     if (log_fp != NULL) {
71         va_start(va, format);
72         vfwprintf_s(log_fp, format, va);
73         va_end(va);
74     }
75 }
76 
77 static void
winerror(int rc,wchar_t * message,int size)78 winerror(int rc, wchar_t * message, int size)
79 {
80     FormatMessageW(
81         FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
82         NULL, rc, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
83         message, size, NULL);
84 }
85 
86 static void
error(int rc,wchar_t * format,...)87 error(int rc, wchar_t * format, ... )
88 {
89     va_list va;
90     wchar_t message[MSGSIZE];
91     wchar_t win_message[MSGSIZE];
92     int len;
93 
94     va_start(va, format);
95     len = _vsnwprintf_s(message, MSGSIZE, _TRUNCATE, format, va);
96     va_end(va);
97 
98     if (rc == 0) {  /* a Windows error */
99         winerror(GetLastError(), win_message, MSGSIZE);
100         if (len >= 0) {
101             _snwprintf_s(&message[len], MSGSIZE - len, _TRUNCATE, L": %ls",
102                          win_message);
103         }
104     }
105 
106 #if !defined(_WINDOWS)
107     fwprintf(stderr, L"%ls\n", message);
108 #else
109     MessageBoxW(NULL, message, L"Python Launcher is sorry to say ...",
110                MB_OK);
111 #endif
112     exit(rc);
113 }
114 
115 /*
116  * This function is here to simplify memory management
117  * and to treat blank values as if they are absent.
118  */
get_env(wchar_t * key)119 static wchar_t * get_env(wchar_t * key)
120 {
121     /* This is not thread-safe, just like getenv */
122     static wchar_t buf[BUFSIZE];
123     DWORD result = GetEnvironmentVariableW(key, buf, BUFSIZE);
124 
125     if (result >= BUFSIZE) {
126         /* Large environment variable. Accept some leakage */
127         wchar_t *buf2 = (wchar_t*)malloc(sizeof(wchar_t) * (result+1));
128         if (buf2 == NULL) {
129             error(RC_NO_MEMORY, L"Could not allocate environment buffer");
130         }
131         GetEnvironmentVariableW(key, buf2, result);
132         return buf2;
133     }
134 
135     if (result == 0)
136         /* Either some error, e.g. ERROR_ENVVAR_NOT_FOUND,
137            or an empty environment variable. */
138         return NULL;
139 
140     return buf;
141 }
142 
143 #if defined(_DEBUG)
144 /* Do not define EXECUTABLEPATH_VALUE in debug builds as it'll
145    never point to the debug build. */
146 #if defined(_WINDOWS)
147 
148 #define PYTHON_EXECUTABLE L"pythonw_d.exe"
149 
150 #else
151 
152 #define PYTHON_EXECUTABLE L"python_d.exe"
153 
154 #endif
155 #else
156 #if defined(_WINDOWS)
157 
158 #define PYTHON_EXECUTABLE L"pythonw.exe"
159 #define EXECUTABLEPATH_VALUE L"WindowedExecutablePath"
160 
161 #else
162 
163 #define PYTHON_EXECUTABLE L"python.exe"
164 #define EXECUTABLEPATH_VALUE L"ExecutablePath"
165 
166 #endif
167 #endif
168 
169 #define MAX_VERSION_SIZE    8
170 
171 typedef struct {
172     wchar_t version[MAX_VERSION_SIZE]; /* m.n */
173     int bits;   /* 32 or 64 */
174     wchar_t executable[MAX_PATH];
175     wchar_t exe_display[MAX_PATH];
176 } INSTALLED_PYTHON;
177 
178 /*
179  * To avoid messing about with heap allocations, just assume we can allocate
180  * statically and never have to deal with more versions than this.
181  */
182 #define MAX_INSTALLED_PYTHONS   100
183 
184 static INSTALLED_PYTHON installed_pythons[MAX_INSTALLED_PYTHONS];
185 
186 static size_t num_installed_pythons = 0;
187 
188 /*
189  * To hold SOFTWARE\Python\PythonCore\X.Y...\InstallPath
190  * The version name can be longer than MAX_VERSION_SIZE, but will be
191  * truncated to just X.Y for comparisons.
192  */
193 #define IP_BASE_SIZE 80
194 #define IP_VERSION_SIZE 8
195 #define IP_SIZE (IP_BASE_SIZE + IP_VERSION_SIZE)
196 #define CORE_PATH L"SOFTWARE\\Python\\PythonCore"
197 /*
198  * Installations from the Microsoft Store will set the same registry keys,
199  * but because of a limitation in Windows they cannot be enumerated normally
200  * (unless you have no other Python installations... which is probably false
201  * because that's the most likely way to get this launcher!)
202  * This key is under HKEY_LOCAL_MACHINE
203  */
204 #define LOOKASIDE_PATH L"SOFTWARE\\Microsoft\\AppModel\\Lookaside\\user\\Software\\Python\\PythonCore"
205 
206 static wchar_t * location_checks[] = {
207     L"\\",
208     L"\\PCbuild\\win32\\",
209     L"\\PCbuild\\amd64\\",
210     /* To support early 32bit versions of Python that stuck the build binaries
211     * directly in PCbuild... */
212     L"\\PCbuild\\",
213     NULL
214 };
215 
216 static INSTALLED_PYTHON *
find_existing_python(const wchar_t * path)217 find_existing_python(const wchar_t * path)
218 {
219     INSTALLED_PYTHON * result = NULL;
220     size_t i;
221     INSTALLED_PYTHON * ip;
222 
223     for (i = 0, ip = installed_pythons; i < num_installed_pythons; i++, ip++) {
224         if (_wcsicmp(path, ip->executable) == 0) {
225             result = ip;
226             break;
227         }
228     }
229     return result;
230 }
231 
232 static INSTALLED_PYTHON *
find_existing_python2(int bits,const wchar_t * version)233 find_existing_python2(int bits, const wchar_t * version)
234 {
235     INSTALLED_PYTHON * result = NULL;
236     size_t i;
237     INSTALLED_PYTHON * ip;
238 
239     for (i = 0, ip = installed_pythons; i < num_installed_pythons; i++, ip++) {
240         if (bits == ip->bits && _wcsicmp(version, ip->version) == 0) {
241             result = ip;
242             break;
243         }
244     }
245     return result;
246 }
247 
248 static void
_locate_pythons_for_key(HKEY root,LPCWSTR subkey,REGSAM flags,int bits,int display_name_only)249 _locate_pythons_for_key(HKEY root, LPCWSTR subkey, REGSAM flags, int bits,
250                         int display_name_only)
251 {
252     HKEY core_root, ip_key;
253     LSTATUS status = RegOpenKeyExW(root, subkey, 0, flags, &core_root);
254     wchar_t message[MSGSIZE];
255     DWORD i;
256     size_t n;
257     BOOL ok, append_name;
258     DWORD type, data_size, attrs;
259     INSTALLED_PYTHON * ip, * pip;
260     wchar_t ip_version[IP_VERSION_SIZE];
261     wchar_t ip_path[IP_SIZE];
262     wchar_t * check;
263     wchar_t ** checkp;
264     wchar_t *key_name = (root == HKEY_LOCAL_MACHINE) ? L"HKLM" : L"HKCU";
265 
266     if (status != ERROR_SUCCESS)
267         debug(L"locate_pythons_for_key: unable to open PythonCore key in %ls\n",
268               key_name);
269     else {
270         ip = &installed_pythons[num_installed_pythons];
271         for (i = 0; num_installed_pythons < MAX_INSTALLED_PYTHONS; i++) {
272             status = RegEnumKeyW(core_root, i, ip_version, IP_VERSION_SIZE);
273             if (status != ERROR_SUCCESS) {
274                 if (status != ERROR_NO_MORE_ITEMS) {
275                     /* unexpected error */
276                     winerror(status, message, MSGSIZE);
277                     debug(L"Can't enumerate registry key for version %ls: %ls\n",
278                           ip_version, message);
279                 }
280                 break;
281             }
282             else {
283                 wcsncpy_s(ip->version, MAX_VERSION_SIZE, ip_version,
284                           MAX_VERSION_SIZE-1);
285                 /* Still treating version as "x.y" rather than sys.winver
286                  * When PEP 514 tags are properly used, we shouldn't need
287                  * to strip this off here.
288                  */
289                 check = wcsrchr(ip->version, L'-');
290                 if (check && !wcscmp(check, L"-32")) {
291                     *check = L'\0';
292                 }
293                 _snwprintf_s(ip_path, IP_SIZE, _TRUNCATE,
294                              L"%ls\\%ls\\InstallPath", subkey, ip_version);
295                 status = RegOpenKeyExW(root, ip_path, 0, flags, &ip_key);
296                 if (status != ERROR_SUCCESS) {
297                     winerror(status, message, MSGSIZE);
298                     /* Note: 'message' already has a trailing \n*/
299                     debug(L"%ls\\%ls: %ls", key_name, ip_path, message);
300                     continue;
301                 }
302                 data_size = sizeof(ip->executable) - 1;
303                 append_name = FALSE;
304 #ifdef EXECUTABLEPATH_VALUE
305                 status = RegQueryValueExW(ip_key, EXECUTABLEPATH_VALUE, NULL, &type,
306                                           (LPBYTE)ip->executable, &data_size);
307 #else
308                 status = ERROR_FILE_NOT_FOUND; /* actual error doesn't matter */
309 #endif
310                 if (status != ERROR_SUCCESS || type != REG_SZ || !data_size) {
311                     append_name = TRUE;
312                     data_size = sizeof(ip->executable) - 1;
313                     status = RegQueryValueExW(ip_key, NULL, NULL, &type,
314                                               (LPBYTE)ip->executable, &data_size);
315                     if (status != ERROR_SUCCESS) {
316                         winerror(status, message, MSGSIZE);
317                         debug(L"%ls\\%ls: %ls\n", key_name, ip_path, message);
318                         RegCloseKey(ip_key);
319                         continue;
320                     }
321                 }
322                 RegCloseKey(ip_key);
323                 if (type != REG_SZ) {
324                     continue;
325                 }
326 
327                 data_size = data_size / sizeof(wchar_t) - 1;  /* for NUL */
328                 if (ip->executable[data_size - 1] == L'\\')
329                     --data_size; /* reg value ended in a backslash */
330                 /* ip->executable is data_size long */
331                 for (checkp = location_checks; *checkp; ++checkp) {
332                     check = *checkp;
333                     if (append_name) {
334                         _snwprintf_s(&ip->executable[data_size],
335                                      MAX_PATH - data_size,
336                                      MAX_PATH - data_size,
337                                      L"%ls%ls", check, PYTHON_EXECUTABLE);
338                     }
339                     attrs = GetFileAttributesW(ip->executable);
340                     if (attrs == INVALID_FILE_ATTRIBUTES) {
341                         winerror(GetLastError(), message, MSGSIZE);
342                         debug(L"locate_pythons_for_key: %ls: %ls",
343                               ip->executable, message);
344                     }
345                     else if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
346                         debug(L"locate_pythons_for_key: '%ls' is a directory\n",
347                               ip->executable, attrs);
348                     }
349                     else if (find_existing_python(ip->executable)) {
350                         debug(L"locate_pythons_for_key: %ls: already found\n",
351                               ip->executable);
352                     }
353                     else {
354                         /* check the executable type. */
355                         if (bits) {
356                             ip->bits = bits;
357                         } else {
358                             ok = GetBinaryTypeW(ip->executable, &attrs);
359                             if (!ok) {
360                                 debug(L"Failure getting binary type: %ls\n",
361                                       ip->executable);
362                             }
363                             else {
364                                 if (attrs == SCS_64BIT_BINARY)
365                                     ip->bits = 64;
366                                 else if (attrs == SCS_32BIT_BINARY)
367                                     ip->bits = 32;
368                                 else
369                                     ip->bits = 0;
370                             }
371                         }
372                         if (ip->bits == 0) {
373                             debug(L"locate_pythons_for_key: %ls: \
374 invalid binary type: %X\n",
375                                   ip->executable, attrs);
376                         }
377                         else {
378                             if (display_name_only) {
379                                 /* display just the executable name. This is
380                                  * primarily for the Store installs */
381                                 const wchar_t *name = wcsrchr(ip->executable, L'\\');
382                                 if (name) {
383                                     wcscpy_s(ip->exe_display, MAX_PATH, name+1);
384                                 }
385                             }
386                             if (wcschr(ip->executable, L' ') != NULL) {
387                                 /* has spaces, so quote, and set original as
388                                  * the display name */
389                                 if (!ip->exe_display[0]) {
390                                     wcscpy_s(ip->exe_display, MAX_PATH, ip->executable);
391                                 }
392                                 n = wcslen(ip->executable);
393                                 memmove(&ip->executable[1],
394                                         ip->executable, n * sizeof(wchar_t));
395                                 ip->executable[0] = L'\"';
396                                 ip->executable[n + 1] = L'\"';
397                                 ip->executable[n + 2] = L'\0';
398                             }
399                             debug(L"locate_pythons_for_key: %ls \
400 is a %dbit executable\n",
401                                 ip->executable, ip->bits);
402                             if (find_existing_python2(ip->bits, ip->version)) {
403                                 debug(L"locate_pythons_for_key: %ls-%i: already \
404 found\n", ip->version, ip->bits);
405                             }
406                             else {
407                                 ++num_installed_pythons;
408                                 pip = ip++;
409                                 if (num_installed_pythons >=
410                                     MAX_INSTALLED_PYTHONS)
411                                     break;
412                             }
413                         }
414                     }
415                 }
416             }
417         }
418         RegCloseKey(core_root);
419     }
420 }
421 
422 static int
compare_pythons(const void * p1,const void * p2)423 compare_pythons(const void * p1, const void * p2)
424 {
425     INSTALLED_PYTHON * ip1 = (INSTALLED_PYTHON *) p1;
426     INSTALLED_PYTHON * ip2 = (INSTALLED_PYTHON *) p2;
427     /* note reverse sorting on version */
428     int result = wcscmp(ip2->version, ip1->version);
429 
430     if (result == 0)
431         result = ip2->bits - ip1->bits; /* 64 before 32 */
432     return result;
433 }
434 
435 static void
locate_pythons_for_key(HKEY root,REGSAM flags)436 locate_pythons_for_key(HKEY root, REGSAM flags)
437 {
438     _locate_pythons_for_key(root, CORE_PATH, flags, 0, FALSE);
439 }
440 
441 static void
locate_store_pythons()442 locate_store_pythons()
443 {
444 #if defined(_M_X64)
445     /* 64bit process, so look in native registry */
446     _locate_pythons_for_key(HKEY_LOCAL_MACHINE, LOOKASIDE_PATH,
447                             KEY_READ, 64, TRUE);
448 #else
449     /* 32bit process, so check that we're on 64bit OS */
450     BOOL f64 = FALSE;
451     if (IsWow64Process(GetCurrentProcess(), &f64) && f64) {
452         _locate_pythons_for_key(HKEY_LOCAL_MACHINE, LOOKASIDE_PATH,
453                                 KEY_READ | KEY_WOW64_64KEY, 64, TRUE);
454     }
455 #endif
456 }
457 
458 static void
locate_venv_python()459 locate_venv_python()
460 {
461     static wchar_t venv_python[MAX_PATH];
462     INSTALLED_PYTHON * ip;
463     wchar_t *virtual_env = get_env(L"VIRTUAL_ENV");
464     DWORD attrs;
465 
466     /* Check for VIRTUAL_ENV environment variable */
467     if (virtual_env == NULL || virtual_env[0] == L'\0') {
468         return;
469     }
470 
471     /* Check for a python executable in the venv */
472     debug(L"Checking for Python executable in virtual env '%ls'\n", virtual_env);
473     _snwprintf_s(venv_python, MAX_PATH, _TRUNCATE,
474             L"%ls\\Scripts\\%ls", virtual_env, PYTHON_EXECUTABLE);
475     attrs = GetFileAttributesW(venv_python);
476     if (attrs == INVALID_FILE_ATTRIBUTES) {
477         debug(L"Python executable %ls missing from virtual env\n", venv_python);
478         return;
479     }
480 
481     ip = &installed_pythons[num_installed_pythons++];
482     wcscpy_s(ip->executable, MAX_PATH, venv_python);
483     ip->bits = 0;
484     wcscpy_s(ip->version, MAX_VERSION_SIZE, L"venv");
485 }
486 
487 static void
locate_all_pythons()488 locate_all_pythons()
489 {
490     /* venv Python is highest priority */
491     locate_venv_python();
492 #if defined(_M_X64)
493     /* If we are a 64bit process, first hit the 32bit keys. */
494     debug(L"locating Pythons in 32bit registry\n");
495     locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ | KEY_WOW64_32KEY);
496     locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ | KEY_WOW64_32KEY);
497 #else
498     /* If we are a 32bit process on a 64bit Windows, first hit the 64bit keys.*/
499     BOOL f64 = FALSE;
500     if (IsWow64Process(GetCurrentProcess(), &f64) && f64) {
501         debug(L"locating Pythons in 64bit registry\n");
502         locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ | KEY_WOW64_64KEY);
503         locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ | KEY_WOW64_64KEY);
504     }
505 #endif
506     /* now hit the "native" key for this process bittedness. */
507     debug(L"locating Pythons in native registry\n");
508     locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ);
509     locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ);
510     /* Store-installed Python is lowest priority */
511     locate_store_pythons();
512     qsort(installed_pythons, num_installed_pythons, sizeof(INSTALLED_PYTHON),
513           compare_pythons);
514 }
515 
516 static INSTALLED_PYTHON *
find_python_by_version(wchar_t const * wanted_ver)517 find_python_by_version(wchar_t const * wanted_ver)
518 {
519     INSTALLED_PYTHON * result = NULL;
520     INSTALLED_PYTHON * ip = installed_pythons;
521     size_t i, n;
522     size_t wlen = wcslen(wanted_ver);
523     int bits = 0;
524 
525     if (wcsstr(wanted_ver, L"-32")) {
526         bits = 32;
527         wlen -= wcslen(L"-32");
528     }
529     else if (wcsstr(wanted_ver, L"-64")) { /* Added option to select 64 bit explicitly */
530         bits = 64;
531         wlen -= wcslen(L"-64");
532     }
533     for (i = 0; i < num_installed_pythons; i++, ip++) {
534         n = wcslen(ip->version);
535         if (n > wlen)
536             n = wlen;
537         if ((wcsncmp(ip->version, wanted_ver, n) == 0) &&
538             /* bits == 0 => don't care */
539             ((bits == 0) || (ip->bits == bits))) {
540             result = ip;
541             break;
542         }
543     }
544     return result;
545 }
546 
547 
548 static wchar_t appdata_ini_path[MAX_PATH];
549 static wchar_t launcher_ini_path[MAX_PATH];
550 
551 /*
552  * Get a value either from the environment or a configuration file.
553  * The key passed in will either be "python", "python2" or "python3".
554  */
555 static wchar_t *
get_configured_value(wchar_t * key)556 get_configured_value(wchar_t * key)
557 {
558 /*
559  * Note: this static value is used to return a configured value
560  * obtained either from the environment or configuration file.
561  * This should be OK since there wouldn't be any concurrent calls.
562  */
563     static wchar_t configured_value[MSGSIZE];
564     wchar_t * result = NULL;
565     wchar_t * found_in = L"environment";
566     DWORD size;
567 
568     /* First, search the environment. */
569     _snwprintf_s(configured_value, MSGSIZE, _TRUNCATE, L"py_%ls", key);
570     result = get_env(configured_value);
571     if (result == NULL && appdata_ini_path[0]) {
572         /* Not in environment: check local configuration. */
573         size = GetPrivateProfileStringW(L"defaults", key, NULL,
574                                         configured_value, MSGSIZE,
575                                         appdata_ini_path);
576         if (size > 0) {
577             result = configured_value;
578             found_in = appdata_ini_path;
579         }
580     }
581     if (result == NULL && launcher_ini_path[0]) {
582         /* Not in environment or local: check global configuration. */
583         size = GetPrivateProfileStringW(L"defaults", key, NULL,
584                                         configured_value, MSGSIZE,
585                                         launcher_ini_path);
586         if (size > 0) {
587             result = configured_value;
588             found_in = launcher_ini_path;
589         }
590     }
591     if (result) {
592         debug(L"found configured value '%ls=%ls' in %ls\n",
593               key, result, found_in ? found_in : L"(unknown)");
594     } else {
595         debug(L"found no configured value for '%ls'\n", key);
596     }
597     return result;
598 }
599 
600 static INSTALLED_PYTHON *
locate_python(wchar_t * wanted_ver,BOOL from_shebang)601 locate_python(wchar_t * wanted_ver, BOOL from_shebang)
602 {
603     static wchar_t config_key [] = { L"pythonX" };
604     static wchar_t * last_char = &config_key[sizeof(config_key) /
605                                              sizeof(wchar_t) - 2];
606     INSTALLED_PYTHON * result = NULL;
607     size_t n = wcslen(wanted_ver);
608     wchar_t * configured_value;
609 
610     if (num_installed_pythons == 0)
611         locate_all_pythons();
612 
613     if (n == 1) {   /* just major version specified */
614         *last_char = *wanted_ver;
615         configured_value = get_configured_value(config_key);
616         if (configured_value != NULL)
617             wanted_ver = configured_value;
618     }
619     if (*wanted_ver) {
620         result = find_python_by_version(wanted_ver);
621         debug(L"search for Python version '%ls' found ", wanted_ver);
622         if (result) {
623             debug(L"'%ls'\n", result->executable);
624         } else {
625             debug(L"no interpreter\n");
626         }
627     }
628     else {
629         *last_char = L'\0'; /* look for an overall default */
630         result = find_python_by_version(L"venv");
631         if (result == NULL) {
632             configured_value = get_configured_value(config_key);
633             if (configured_value)
634                 result = find_python_by_version(configured_value);
635         }
636         /* Not found a value yet - try by major version.
637          * If we're looking for an interpreter specified in a shebang line,
638          * we want to try Python 2 first, then Python 3 (for Unix and backward
639          * compatibility). If we're being called interactively, assume the user
640          * wants the latest version available, so try Python 3 first, then
641          * Python 2.
642          */
643         if (result == NULL)
644             result = find_python_by_version(from_shebang ? L"2" : L"3");
645         if (result == NULL)
646             result = find_python_by_version(from_shebang ? L"3" : L"2");
647         debug(L"search for default Python found ");
648         if (result) {
649             debug(L"version %ls at '%ls'\n",
650                   result->version, result->executable);
651         } else {
652             debug(L"no interpreter\n");
653         }
654     }
655     return result;
656 }
657 
658 #if defined(SCRIPT_WRAPPER)
659 /*
660  * Check for a script located alongside the executable
661  */
662 
663 #if defined(_WINDOWS)
664 #define SCRIPT_SUFFIX L"-script.pyw"
665 #else
666 #define SCRIPT_SUFFIX L"-script.py"
667 #endif
668 
669 static wchar_t wrapped_script_path[MAX_PATH];
670 
671 /* Locate the script being wrapped.
672  *
673  * This code should store the name of the wrapped script in
674  * wrapped_script_path, or terminate the program with an error if there is no
675  * valid wrapped script file.
676  */
677 static void
locate_wrapped_script()678 locate_wrapped_script()
679 {
680     wchar_t * p;
681     size_t plen;
682     DWORD attrs;
683 
684     plen = GetModuleFileNameW(NULL, wrapped_script_path, MAX_PATH);
685     p = wcsrchr(wrapped_script_path, L'.');
686     if (p == NULL) {
687         debug(L"GetModuleFileNameW returned value has no extension: %ls\n",
688               wrapped_script_path);
689         error(RC_NO_SCRIPT, L"Wrapper name '%ls' is not valid.", wrapped_script_path);
690     }
691 
692     wcsncpy_s(p, MAX_PATH - (p - wrapped_script_path) + 1, SCRIPT_SUFFIX, _TRUNCATE);
693     attrs = GetFileAttributesW(wrapped_script_path);
694     if (attrs == INVALID_FILE_ATTRIBUTES) {
695         debug(L"File '%ls' non-existent\n", wrapped_script_path);
696         error(RC_NO_SCRIPT, L"Script file '%ls' is not present.", wrapped_script_path);
697     }
698 
699     debug(L"Using wrapped script file '%ls'\n", wrapped_script_path);
700 }
701 #endif
702 
703 /*
704  * Process creation code
705  */
706 
707 static BOOL
safe_duplicate_handle(HANDLE in,HANDLE * pout)708 safe_duplicate_handle(HANDLE in, HANDLE * pout)
709 {
710     BOOL ok;
711     HANDLE process = GetCurrentProcess();
712     DWORD rc;
713 
714     *pout = NULL;
715     ok = DuplicateHandle(process, in, process, pout, 0, TRUE,
716                          DUPLICATE_SAME_ACCESS);
717     if (!ok) {
718         rc = GetLastError();
719         if (rc == ERROR_INVALID_HANDLE) {
720             debug(L"DuplicateHandle returned ERROR_INVALID_HANDLE\n");
721             ok = TRUE;
722         }
723         else {
724             debug(L"DuplicateHandle returned %d\n", rc);
725         }
726     }
727     return ok;
728 }
729 
730 static BOOL WINAPI
ctrl_c_handler(DWORD code)731 ctrl_c_handler(DWORD code)
732 {
733     return TRUE;    /* We just ignore all control events. */
734 }
735 
736 static void
run_child(wchar_t * cmdline)737 run_child(wchar_t * cmdline)
738 {
739     HANDLE job;
740     JOBOBJECT_EXTENDED_LIMIT_INFORMATION info;
741     DWORD rc;
742     BOOL ok;
743     STARTUPINFOW si;
744     PROCESS_INFORMATION pi;
745 
746 #if defined(_WINDOWS)
747     /*
748     When explorer launches a Windows (GUI) application, it displays
749     the "app starting" (the "pointer + hourglass") cursor for a number
750     of seconds, or until the app does something UI-ish (eg, creating a
751     window, or fetching a message).  As this launcher doesn't do this
752     directly, that cursor remains even after the child process does these
753     things.  We avoid that by doing a simple post+get message.
754     See http://bugs.python.org/issue17290 and
755     https://bitbucket.org/vinay.sajip/pylauncher/issue/20/busy-cursor-for-a-long-time-when-running
756     */
757     MSG msg;
758 
759     PostMessage(0, 0, 0, 0);
760     GetMessage(&msg, 0, 0, 0);
761 #endif
762 
763     debug(L"run_child: about to run '%ls'\n", cmdline);
764     job = CreateJobObject(NULL, NULL);
765     ok = QueryInformationJobObject(job, JobObjectExtendedLimitInformation,
766                                   &info, sizeof(info), &rc);
767     if (!ok || (rc != sizeof(info)) || !job)
768         error(RC_CREATE_PROCESS, L"Job information querying failed");
769     info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE |
770                                              JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK;
771     ok = SetInformationJobObject(job, JobObjectExtendedLimitInformation, &info,
772                                  sizeof(info));
773     if (!ok)
774         error(RC_CREATE_PROCESS, L"Job information setting failed");
775     memset(&si, 0, sizeof(si));
776     GetStartupInfoW(&si);
777     ok = safe_duplicate_handle(GetStdHandle(STD_INPUT_HANDLE), &si.hStdInput);
778     if (!ok)
779         error(RC_NO_STD_HANDLES, L"stdin duplication failed");
780     ok = safe_duplicate_handle(GetStdHandle(STD_OUTPUT_HANDLE), &si.hStdOutput);
781     if (!ok)
782         error(RC_NO_STD_HANDLES, L"stdout duplication failed");
783     ok = safe_duplicate_handle(GetStdHandle(STD_ERROR_HANDLE), &si.hStdError);
784     if (!ok)
785         error(RC_NO_STD_HANDLES, L"stderr duplication failed");
786 
787     ok = SetConsoleCtrlHandler(ctrl_c_handler, TRUE);
788     if (!ok)
789         error(RC_CREATE_PROCESS, L"control handler setting failed");
790 
791     si.dwFlags = STARTF_USESTDHANDLES;
792     ok = CreateProcessW(NULL, cmdline, NULL, NULL, TRUE,
793                         0, NULL, NULL, &si, &pi);
794     if (!ok)
795         error(RC_CREATE_PROCESS, L"Unable to create process using '%ls'", cmdline);
796     AssignProcessToJobObject(job, pi.hProcess);
797     CloseHandle(pi.hThread);
798     WaitForSingleObjectEx(pi.hProcess, INFINITE, FALSE);
799     ok = GetExitCodeProcess(pi.hProcess, &rc);
800     if (!ok)
801         error(RC_CREATE_PROCESS, L"Failed to get exit code of process");
802     debug(L"child process exit code: %d\n", rc);
803     exit(rc);
804 }
805 
806 static void
invoke_child(wchar_t * executable,wchar_t * suffix,wchar_t * cmdline)807 invoke_child(wchar_t * executable, wchar_t * suffix, wchar_t * cmdline)
808 {
809     wchar_t * child_command;
810     size_t child_command_size;
811     BOOL no_suffix = (suffix == NULL) || (*suffix == L'\0');
812     BOOL no_cmdline = (*cmdline == L'\0');
813 
814     if (no_suffix && no_cmdline)
815         run_child(executable);
816     else {
817         if (no_suffix) {
818             /* add 2 for space separator + terminating NUL. */
819             child_command_size = wcslen(executable) + wcslen(cmdline) + 2;
820         }
821         else {
822             /* add 3 for 2 space separators + terminating NUL. */
823             child_command_size = wcslen(executable) + wcslen(suffix) +
824                                     wcslen(cmdline) + 3;
825         }
826         child_command = calloc(child_command_size, sizeof(wchar_t));
827         if (child_command == NULL)
828             error(RC_CREATE_PROCESS, L"unable to allocate %zd bytes for child command.",
829                   child_command_size);
830         if (no_suffix)
831             _snwprintf_s(child_command, child_command_size,
832                          child_command_size - 1, L"%ls %ls",
833                          executable, cmdline);
834         else
835             _snwprintf_s(child_command, child_command_size,
836                          child_command_size - 1, L"%ls %ls %ls",
837                          executable, suffix, cmdline);
838         run_child(child_command);
839         free(child_command);
840     }
841 }
842 
843 typedef struct {
844     wchar_t *shebang;
845     BOOL search;
846 } SHEBANG;
847 
848 static SHEBANG builtin_virtual_paths [] = {
849     { L"/usr/bin/env python", TRUE },
850     { L"/usr/bin/python", FALSE },
851     { L"/usr/local/bin/python", FALSE },
852     { L"python", FALSE },
853     { NULL, FALSE },
854 };
855 
856 /* For now, a static array of commands. */
857 
858 #define MAX_COMMANDS 100
859 
860 typedef struct {
861     wchar_t key[MAX_PATH];
862     wchar_t value[MSGSIZE];
863 } COMMAND;
864 
865 static COMMAND commands[MAX_COMMANDS];
866 static int num_commands = 0;
867 
868 #if defined(SKIP_PREFIX)
869 
870 static wchar_t * builtin_prefixes [] = {
871     /* These must be in an order that the longest matches should be found,
872      * i.e. if the prefix is "/usr/bin/env ", it should match that entry
873      * *before* matching "/usr/bin/".
874      */
875     L"/usr/bin/env ",
876     L"/usr/bin/",
877     L"/usr/local/bin/",
878     NULL
879 };
880 
skip_prefix(wchar_t * name)881 static wchar_t * skip_prefix(wchar_t * name)
882 {
883     wchar_t ** pp = builtin_prefixes;
884     wchar_t * result = name;
885     wchar_t * p;
886     size_t n;
887 
888     for (; p = *pp; pp++) {
889         n = wcslen(p);
890         if (_wcsnicmp(p, name, n) == 0) {
891             result += n;   /* skip the prefix */
892             if (p[n - 1] == L' ') /* No empty strings in table, so n > 1 */
893                 result = skip_whitespace(result);
894             break;
895         }
896     }
897     return result;
898 }
899 
900 #endif
901 
902 #if defined(SEARCH_PATH)
903 
904 static COMMAND path_command;
905 
find_on_path(wchar_t * name)906 static COMMAND * find_on_path(wchar_t * name)
907 {
908     wchar_t * pathext;
909     size_t    varsize;
910     wchar_t * context = NULL;
911     wchar_t * extension;
912     COMMAND * result = NULL;
913     DWORD     len;
914     errno_t   rc;
915 
916     wcscpy_s(path_command.key, MAX_PATH, name);
917     if (wcschr(name, L'.') != NULL) {
918         /* assume it has an extension. */
919         len = SearchPathW(NULL, name, NULL, MSGSIZE, path_command.value, NULL);
920         if (len) {
921             result = &path_command;
922         }
923     }
924     else {
925         /* No extension - search using registered extensions. */
926         rc = _wdupenv_s(&pathext, &varsize, L"PATHEXT");
927         if (rc == 0) {
928             extension = wcstok_s(pathext, L";", &context);
929             while (extension) {
930                 len = SearchPathW(NULL, name, extension, MSGSIZE, path_command.value, NULL);
931                 if (len) {
932                     result = &path_command;
933                     break;
934                 }
935                 extension = wcstok_s(NULL, L";", &context);
936             }
937             free(pathext);
938         }
939     }
940     return result;
941 }
942 
943 #endif
944 
find_command(wchar_t * name)945 static COMMAND * find_command(wchar_t * name)
946 {
947     COMMAND * result = NULL;
948     COMMAND * cp = commands;
949     int i;
950 
951     for (i = 0; i < num_commands; i++, cp++) {
952         if (_wcsicmp(cp->key, name) == 0) {
953             result = cp;
954             break;
955         }
956     }
957 #if defined(SEARCH_PATH)
958     if (result == NULL)
959         result = find_on_path(name);
960 #endif
961     return result;
962 }
963 
964 static void
update_command(COMMAND * cp,wchar_t * name,wchar_t * cmdline)965 update_command(COMMAND * cp, wchar_t * name, wchar_t * cmdline)
966 {
967     wcsncpy_s(cp->key, MAX_PATH, name, _TRUNCATE);
968     wcsncpy_s(cp->value, MSGSIZE, cmdline, _TRUNCATE);
969 }
970 
971 static void
add_command(wchar_t * name,wchar_t * cmdline)972 add_command(wchar_t * name, wchar_t * cmdline)
973 {
974     if (num_commands >= MAX_COMMANDS) {
975         debug(L"can't add %ls = '%ls': no room\n", name, cmdline);
976     }
977     else {
978         COMMAND * cp = &commands[num_commands++];
979 
980         update_command(cp, name, cmdline);
981     }
982 }
983 
984 static void
read_config_file(wchar_t * config_path)985 read_config_file(wchar_t * config_path)
986 {
987     wchar_t keynames[MSGSIZE];
988     wchar_t value[MSGSIZE];
989     DWORD read;
990     wchar_t * key;
991     COMMAND * cp;
992     wchar_t * cmdp;
993 
994     read = GetPrivateProfileStringW(L"commands", NULL, NULL, keynames, MSGSIZE,
995                                     config_path);
996     if (read == MSGSIZE - 1) {
997         debug(L"read_commands: %ls: not enough space for names\n", config_path);
998     }
999     key = keynames;
1000     while (*key) {
1001         read = GetPrivateProfileStringW(L"commands", key, NULL, value, MSGSIZE,
1002                                        config_path);
1003         if (read == MSGSIZE - 1) {
1004             debug(L"read_commands: %ls: not enough space for %ls\n",
1005                   config_path, key);
1006         }
1007         cmdp = skip_whitespace(value);
1008         if (*cmdp) {
1009             cp = find_command(key);
1010             if (cp == NULL)
1011                 add_command(key, value);
1012             else
1013                 update_command(cp, key, value);
1014         }
1015         key += wcslen(key) + 1;
1016     }
1017 }
1018 
read_commands()1019 static void read_commands()
1020 {
1021     if (launcher_ini_path[0])
1022         read_config_file(launcher_ini_path);
1023     if (appdata_ini_path[0])
1024         read_config_file(appdata_ini_path);
1025 }
1026 
1027 static BOOL
parse_shebang(wchar_t * shebang_line,int nchars,wchar_t ** command,wchar_t ** suffix,BOOL * search)1028 parse_shebang(wchar_t * shebang_line, int nchars, wchar_t ** command,
1029               wchar_t ** suffix, BOOL *search)
1030 {
1031     BOOL rc = FALSE;
1032     SHEBANG * vpp;
1033     size_t plen;
1034     wchar_t * p;
1035     wchar_t zapped;
1036     wchar_t * endp = shebang_line + nchars - 1;
1037     COMMAND * cp;
1038     wchar_t * skipped;
1039 
1040     *command = NULL;    /* failure return */
1041     *suffix = NULL;
1042     *search = FALSE;
1043 
1044     if ((*shebang_line++ == L'#') && (*shebang_line++ == L'!')) {
1045         shebang_line = skip_whitespace(shebang_line);
1046         if (*shebang_line) {
1047             *command = shebang_line;
1048             for (vpp = builtin_virtual_paths; vpp->shebang; ++vpp) {
1049                 plen = wcslen(vpp->shebang);
1050                 if (wcsncmp(shebang_line, vpp->shebang, plen) == 0) {
1051                     rc = TRUE;
1052                     *search = vpp->search;
1053                     /* We can do this because all builtin commands contain
1054                      * "python".
1055                      */
1056                     *command = wcsstr(shebang_line, L"python");
1057                     break;
1058                 }
1059             }
1060             if (vpp->shebang == NULL) {
1061                 /*
1062                  * Not found in builtins - look in customized commands.
1063                  *
1064                  * We can't permanently modify the shebang line in case
1065                  * it's not a customized command, but we can temporarily
1066                  * stick a NUL after the command while searching for it,
1067                  * then put back the char we zapped.
1068                  */
1069 #if defined(SKIP_PREFIX)
1070                 skipped = skip_prefix(shebang_line);
1071 #else
1072                 skipped = shebang_line;
1073 #endif
1074                 p = wcspbrk(skipped, L" \t\r\n");
1075                 if (p != NULL) {
1076                     zapped = *p;
1077                     *p = L'\0';
1078                 }
1079                 cp = find_command(skipped);
1080                 if (p != NULL)
1081                     *p = zapped;
1082                 if (cp != NULL) {
1083                     *command = cp->value;
1084                     if (p != NULL)
1085                         *suffix = skip_whitespace(p);
1086                 }
1087             }
1088             /* remove trailing whitespace */
1089             while ((endp > shebang_line) && isspace(*endp))
1090                 --endp;
1091             if (endp > shebang_line)
1092                 endp[1] = L'\0';
1093         }
1094     }
1095     return rc;
1096 }
1097 
1098 /* #define CP_UTF8             65001 defined in winnls.h */
1099 #define CP_UTF16LE          1200
1100 #define CP_UTF16BE          1201
1101 #define CP_UTF32LE          12000
1102 #define CP_UTF32BE          12001
1103 
1104 typedef struct {
1105     int length;
1106     char sequence[4];
1107     UINT code_page;
1108 } BOM;
1109 
1110 /*
1111  * Strictly, we don't need to handle UTF-16 and UTF-32, since Python itself
1112  * doesn't. Never mind, one day it might - there's no harm leaving it in.
1113  */
1114 static BOM BOMs[] = {
1115     { 3, { 0xEF, 0xBB, 0xBF }, CP_UTF8 },           /* UTF-8 - keep first */
1116     /* Test UTF-32LE before UTF-16LE since UTF-16LE BOM is a prefix
1117      * of UTF-32LE BOM. */
1118     { 4, { 0xFF, 0xFE, 0x00, 0x00 }, CP_UTF32LE },  /* UTF-32LE */
1119     { 4, { 0x00, 0x00, 0xFE, 0xFF }, CP_UTF32BE },  /* UTF-32BE */
1120     { 2, { 0xFF, 0xFE }, CP_UTF16LE },              /* UTF-16LE */
1121     { 2, { 0xFE, 0xFF }, CP_UTF16BE },              /* UTF-16BE */
1122     { 0 }                                           /* sentinel */
1123 };
1124 
1125 static BOM *
find_BOM(char * buffer)1126 find_BOM(char * buffer)
1127 {
1128 /*
1129  * Look for a BOM in the input and return a pointer to the
1130  * corresponding structure, or NULL if not found.
1131  */
1132     BOM * result = NULL;
1133     BOM *bom;
1134 
1135     for (bom = BOMs; bom->length; bom++) {
1136         if (strncmp(bom->sequence, buffer, bom->length) == 0) {
1137             result = bom;
1138             break;
1139         }
1140     }
1141     return result;
1142 }
1143 
1144 static char *
find_terminator(char * buffer,int len,BOM * bom)1145 find_terminator(char * buffer, int len, BOM *bom)
1146 {
1147     char * result = NULL;
1148     char * end = buffer + len;
1149     char  * p;
1150     char c;
1151     int cp;
1152 
1153     for (p = buffer; p < end; p++) {
1154         c = *p;
1155         if (c == '\r') {
1156             result = p;
1157             break;
1158         }
1159         if (c == '\n') {
1160             result = p;
1161             break;
1162         }
1163     }
1164     if (result != NULL) {
1165         cp = bom->code_page;
1166 
1167         /* adjustments to include all bytes of the char */
1168         /* no adjustment needed for UTF-8 or big endian */
1169         if (cp == CP_UTF16LE)
1170             ++result;
1171         else if (cp == CP_UTF32LE)
1172             result += 3;
1173         ++result; /* point just past terminator */
1174     }
1175     return result;
1176 }
1177 
1178 static BOOL
validate_version(wchar_t * p)1179 validate_version(wchar_t * p)
1180 {
1181     /*
1182     Version information should start with the major version,
1183     Optionally followed by a period and a minor version,
1184     Optionally followed by a minus and one of 32 or 64.
1185     Valid examples:
1186       2
1187       3
1188       2.7
1189       3.6
1190       2.7-32
1191       The intent is to add to the valid patterns:
1192       3.10
1193       3-32
1194       3.6-64
1195       3-64
1196     */
1197     BOOL result = (p != NULL); /* Default to False if null pointer. */
1198 
1199     result = result && iswdigit(*p);  /* Result = False if first string element is not a digit. */
1200 
1201     while (result && iswdigit(*p))   /* Require a major version */
1202         ++p;  /* Skip all leading digit(s) */
1203     if (result && (*p == L'.'))     /* Allow . for major minor separator.*/
1204     {
1205         result = iswdigit(*++p);     /* Must be at least one digit */
1206         while (result && iswdigit(*++p)) ; /* Skip any more Digits */
1207     }
1208     if (result && (*p == L'-')) {   /* Allow - for Bits Separator */
1209         switch(*++p){
1210         case L'3':                            /* 3 is OK */
1211             result = (*++p == L'2') && !*++p; /* only if followed by 2 and ended.*/
1212             break;
1213         case L'6':                            /* 6 is OK */
1214             result = (*++p == L'4') && !*++p; /* only if followed by 4 and ended.*/
1215             break;
1216         default:
1217             result = FALSE;
1218             break;
1219         }
1220     }
1221     result = result && !*p; /* Must have reached EOS */
1222     return result;
1223 
1224 }
1225 
1226 typedef struct {
1227     unsigned short min;
1228     unsigned short max;
1229     wchar_t version[MAX_VERSION_SIZE];
1230 } PYC_MAGIC;
1231 
1232 static PYC_MAGIC magic_values[] = {
1233     { 50823, 50823, L"2.0" },
1234     { 60202, 60202, L"2.1" },
1235     { 60717, 60717, L"2.2" },
1236     { 62011, 62021, L"2.3" },
1237     { 62041, 62061, L"2.4" },
1238     { 62071, 62131, L"2.5" },
1239     { 62151, 62161, L"2.6" },
1240     { 62171, 62211, L"2.7" },
1241     { 3000, 3131, L"3.0" },
1242     { 3141, 3151, L"3.1" },
1243     { 3160, 3180, L"3.2" },
1244     { 3190, 3230, L"3.3" },
1245     { 3250, 3310, L"3.4" },
1246     { 3320, 3351, L"3.5" },
1247     { 3360, 3379, L"3.6" },
1248     { 3390, 3399, L"3.7" },
1249     { 3400, 3419, L"3.8" },
1250     { 3420, 3429, L"3.9" },
1251     { 0 }
1252 };
1253 
1254 static INSTALLED_PYTHON *
find_by_magic(unsigned short magic)1255 find_by_magic(unsigned short magic)
1256 {
1257     INSTALLED_PYTHON * result = NULL;
1258     PYC_MAGIC * mp;
1259 
1260     for (mp = magic_values; mp->min; mp++) {
1261         if ((magic >= mp->min) && (magic <= mp->max)) {
1262             result = locate_python(mp->version, FALSE);
1263             if (result != NULL)
1264                 break;
1265         }
1266     }
1267     return result;
1268 }
1269 
1270 static void
maybe_handle_shebang(wchar_t ** argv,wchar_t * cmdline)1271 maybe_handle_shebang(wchar_t ** argv, wchar_t * cmdline)
1272 {
1273 /*
1274  * Look for a shebang line in the first argument.  If found
1275  * and we spawn a child process, this never returns.  If it
1276  * does return then we process the args "normally".
1277  *
1278  * argv[0] might be a filename with a shebang.
1279  */
1280     FILE * fp;
1281     errno_t rc = _wfopen_s(&fp, *argv, L"rb");
1282     char buffer[BUFSIZE];
1283     wchar_t shebang_line[BUFSIZE + 1];
1284     size_t read;
1285     char *p;
1286     char * start;
1287     char * shebang_alias = (char *) shebang_line;
1288     BOM* bom;
1289     int i, j, nchars = 0;
1290     int header_len;
1291     BOOL is_virt;
1292     BOOL search;
1293     wchar_t * command;
1294     wchar_t * suffix;
1295     COMMAND *cmd = NULL;
1296     INSTALLED_PYTHON * ip;
1297 
1298     if (rc == 0) {
1299         read = fread(buffer, sizeof(char), BUFSIZE, fp);
1300         debug(L"maybe_handle_shebang: read %zd bytes\n", read);
1301         fclose(fp);
1302 
1303         if ((read >= 4) && (buffer[3] == '\n') && (buffer[2] == '\r')) {
1304             ip = find_by_magic((((unsigned char)buffer[1]) << 8 |
1305                                 (unsigned char)buffer[0]) & 0xFFFF);
1306             if (ip != NULL) {
1307                 debug(L"script file is compiled against Python %ls\n",
1308                       ip->version);
1309                 invoke_child(ip->executable, NULL, cmdline);
1310             }
1311         }
1312         /* Look for BOM */
1313         bom = find_BOM(buffer);
1314         if (bom == NULL) {
1315             start = buffer;
1316             debug(L"maybe_handle_shebang: BOM not found, using UTF-8\n");
1317             bom = BOMs; /* points to UTF-8 entry - the default */
1318         }
1319         else {
1320             debug(L"maybe_handle_shebang: BOM found, code page %u\n",
1321                   bom->code_page);
1322             start = &buffer[bom->length];
1323         }
1324         p = find_terminator(start, BUFSIZE, bom);
1325         /*
1326          * If no CR or LF was found in the heading,
1327          * we assume it's not a shebang file.
1328          */
1329         if (p == NULL) {
1330             debug(L"maybe_handle_shebang: No line terminator found\n");
1331         }
1332         else {
1333             /*
1334              * Found line terminator - parse the shebang.
1335              *
1336              * Strictly, we don't need to handle UTF-16 anf UTF-32,
1337              * since Python itself doesn't.
1338              * Never mind, one day it might.
1339              */
1340             header_len = (int) (p - start);
1341             switch(bom->code_page) {
1342             case CP_UTF8:
1343                 nchars = MultiByteToWideChar(bom->code_page,
1344                                              0,
1345                                              start, header_len, shebang_line,
1346                                              BUFSIZE);
1347                 break;
1348             case CP_UTF16BE:
1349                 if (header_len % 2 != 0) {
1350                     debug(L"maybe_handle_shebang: UTF-16BE, but an odd number \
1351 of bytes: %d\n", header_len);
1352                     /* nchars = 0; Not needed - initialised to 0. */
1353                 }
1354                 else {
1355                     for (i = header_len; i > 0; i -= 2) {
1356                         shebang_alias[i - 1] = start[i - 2];
1357                         shebang_alias[i - 2] = start[i - 1];
1358                     }
1359                     nchars = header_len / sizeof(wchar_t);
1360                 }
1361                 break;
1362             case CP_UTF16LE:
1363                 if ((header_len % 2) != 0) {
1364                     debug(L"UTF-16LE, but an odd number of bytes: %d\n",
1365                           header_len);
1366                     /* nchars = 0; Not needed - initialised to 0. */
1367                 }
1368                 else {
1369                     /* no actual conversion needed. */
1370                     memcpy(shebang_line, start, header_len);
1371                     nchars = header_len / sizeof(wchar_t);
1372                 }
1373                 break;
1374             case CP_UTF32BE:
1375                 if (header_len % 4 != 0) {
1376                     debug(L"UTF-32BE, but not divisible by 4: %d\n",
1377                           header_len);
1378                     /* nchars = 0; Not needed - initialised to 0. */
1379                 }
1380                 else {
1381                     for (i = header_len, j = header_len / 2; i > 0; i -= 4,
1382                                                                     j -= 2) {
1383                         shebang_alias[j - 1] = start[i - 2];
1384                         shebang_alias[j - 2] = start[i - 1];
1385                     }
1386                     nchars = header_len / sizeof(wchar_t);
1387                 }
1388                 break;
1389             case CP_UTF32LE:
1390                 if (header_len % 4 != 0) {
1391                     debug(L"UTF-32LE, but not divisible by 4: %d\n",
1392                           header_len);
1393                     /* nchars = 0; Not needed - initialised to 0. */
1394                 }
1395                 else {
1396                     for (i = header_len, j = header_len / 2; i > 0; i -= 4,
1397                                                                     j -= 2) {
1398                         shebang_alias[j - 1] = start[i - 3];
1399                         shebang_alias[j - 2] = start[i - 4];
1400                     }
1401                     nchars = header_len / sizeof(wchar_t);
1402                 }
1403                 break;
1404             }
1405             if (nchars > 0) {
1406                 shebang_line[--nchars] = L'\0';
1407                 is_virt = parse_shebang(shebang_line, nchars, &command,
1408                                         &suffix, &search);
1409                 if (command != NULL) {
1410                     debug(L"parse_shebang: found command: %ls\n", command);
1411                     if (!is_virt) {
1412                         invoke_child(command, suffix, cmdline);
1413                     }
1414                     else {
1415                         suffix = wcschr(command, L' ');
1416                         if (suffix != NULL) {
1417                             *suffix++ = L'\0';
1418                             suffix = skip_whitespace(suffix);
1419                         }
1420                         if (wcsncmp(command, L"python", 6))
1421                             error(RC_BAD_VIRTUAL_PATH, L"Unknown virtual \
1422 path '%ls'", command);
1423                         command += 6;   /* skip past "python" */
1424                         if (search && ((*command == L'\0') || isspace(*command))) {
1425                             /* Command is eligible for path search, and there
1426                              * is no version specification.
1427                              */
1428                             debug(L"searching PATH for python executable\n");
1429                             cmd = find_on_path(PYTHON_EXECUTABLE);
1430                             debug(L"Python on path: %ls\n", cmd ? cmd->value : L"<not found>");
1431                             if (cmd) {
1432                                 debug(L"located python on PATH: %ls\n", cmd->value);
1433                                 invoke_child(cmd->value, suffix, cmdline);
1434                                 /* Exit here, as we have found the command */
1435                                 return;
1436                             }
1437                             /* FALL THROUGH: No python found on PATH, so fall
1438                              * back to locating the correct installed python.
1439                              */
1440                         }
1441                         if (*command && !validate_version(command))
1442                             error(RC_BAD_VIRTUAL_PATH, L"Invalid version \
1443 specification: '%ls'.\nIn the first line of the script, 'python' needs to be \
1444 followed by a valid version specifier.\nPlease check the documentation.",
1445                                   command);
1446                         /* TODO could call validate_version(command) */
1447                         ip = locate_python(command, TRUE);
1448                         if (ip == NULL) {
1449                             error(RC_NO_PYTHON, L"Requested Python version \
1450 (%ls) is not installed", command);
1451                         }
1452                         else {
1453                             invoke_child(ip->executable, suffix, cmdline);
1454                         }
1455                     }
1456                 }
1457             }
1458         }
1459     }
1460 }
1461 
1462 static wchar_t *
skip_me(wchar_t * cmdline)1463 skip_me(wchar_t * cmdline)
1464 {
1465     BOOL quoted;
1466     wchar_t c;
1467     wchar_t * result = cmdline;
1468 
1469     quoted = cmdline[0] == L'\"';
1470     if (!quoted)
1471         c = L' ';
1472     else {
1473         c = L'\"';
1474         ++result;
1475     }
1476     result = wcschr(result, c);
1477     if (result == NULL) /* when, for example, just exe name on command line */
1478         result = L"";
1479     else {
1480         ++result; /* skip past space or closing quote */
1481         result = skip_whitespace(result);
1482     }
1483     return result;
1484 }
1485 
1486 static DWORD version_high = 0;
1487 static DWORD version_low = 0;
1488 
1489 static void
get_version_info(wchar_t * version_text,size_t size)1490 get_version_info(wchar_t * version_text, size_t size)
1491 {
1492     WORD maj, min, rel, bld;
1493 
1494     if (!version_high && !version_low)
1495         wcsncpy_s(version_text, size, L"0.1", _TRUNCATE);   /* fallback */
1496     else {
1497         maj = HIWORD(version_high);
1498         min = LOWORD(version_high);
1499         rel = HIWORD(version_low);
1500         bld = LOWORD(version_low);
1501         _snwprintf_s(version_text, size, _TRUNCATE, L"%d.%d.%d.%d", maj,
1502                      min, rel, bld);
1503     }
1504 }
1505 
1506 static void
show_help_text(wchar_t ** argv)1507 show_help_text(wchar_t ** argv)
1508 {
1509     wchar_t version_text [MAX_PATH];
1510 #if defined(_M_X64)
1511     BOOL canDo64bit = TRUE;
1512 #else
1513     /* If we are a 32bit process on a 64bit Windows, first hit the 64bit keys. */
1514     BOOL canDo64bit = FALSE;
1515     IsWow64Process(GetCurrentProcess(), &canDo64bit);
1516 #endif
1517 
1518     get_version_info(version_text, MAX_PATH);
1519     fwprintf(stdout, L"\
1520 Python Launcher for Windows Version %ls\n\n", version_text);
1521     fwprintf(stdout, L"\
1522 usage:\n\
1523 %ls [launcher-args] [python-args] [script [script-args]]\n\n", argv[0]);
1524     fputws(L"\
1525 Launcher arguments:\n\n\
1526 -2     : Launch the latest Python 2.x version\n\
1527 -3     : Launch the latest Python 3.x version\n\
1528 -X.Y   : Launch the specified Python version\n", stdout);
1529     if (canDo64bit) {
1530         fputws(L"\
1531      The above all default to 64 bit if a matching 64 bit python is present.\n\
1532 -X.Y-32: Launch the specified 32bit Python version\n\
1533 -X-32  : Launch the latest 32bit Python X version\n\
1534 -X.Y-64: Launch the specified 64bit Python version\n\
1535 -X-64  : Launch the latest 64bit Python X version", stdout);
1536     }
1537     fputws(L"\n-0  --list       : List the available pythons", stdout);
1538     fputws(L"\n-0p --list-paths : List with paths", stdout);
1539     fputws(L"\n\n If no script is specified the specified interpreter is opened.", stdout);
1540     fputws(L"\nIf an exact version is not given, using the latest version can be overridden by", stdout);
1541     fputws(L"\nany of the following, (in priority order):", stdout);
1542     fputws(L"\n An active virtual environment", stdout);
1543     fputws(L"\n A shebang line in the script (if present)", stdout);
1544     fputws(L"\n With -2 or -3 flag a matching PY_PYTHON2 or PY_PYTHON3 Enviroment variable", stdout);
1545     fputws(L"\n A PY_PYTHON Enviroment variable", stdout);
1546     fputws(L"\n From [defaults] in py.ini in your %LOCALAPPDATA%\\py.ini", stdout);
1547     fputws(L"\n From [defaults] in py.ini beside py.exe (use `where py` to locate)", stdout);
1548     fputws(L"\n\nThe following help text is from Python:\n\n", stdout);
1549     fflush(stdout);
1550 }
1551 
1552 static BOOL
show_python_list(wchar_t ** argv)1553 show_python_list(wchar_t ** argv)
1554 {
1555     /*
1556      * Display options -0
1557      */
1558     INSTALLED_PYTHON * result = NULL;
1559     INSTALLED_PYTHON * ip = installed_pythons; /* List of installed pythons */
1560     INSTALLED_PYTHON * defpy = locate_python(L"", FALSE);
1561     size_t i = 0;
1562     wchar_t *p = argv[1];
1563     wchar_t *ver_fmt = L"-%ls-%d";
1564     wchar_t *fmt = L"\n %ls";
1565     wchar_t *defind = L" *"; /* Default indicator */
1566 
1567     /*
1568     * Output informational messages to stderr to keep output
1569     * clean for use in pipes, etc.
1570     */
1571     fwprintf(stderr,
1572              L"Installed Pythons found by %s Launcher for Windows", argv[0]);
1573     if (!_wcsicmp(p, L"-0p") || !_wcsicmp(p, L"--list-paths"))
1574         fmt = L"\n %-15ls%ls"; /* include path */
1575 
1576     if (num_installed_pythons == 0) /* We have somehow got here without searching for pythons */
1577         locate_all_pythons(); /* Find them, Populates installed_pythons */
1578 
1579     if (num_installed_pythons == 0) /* No pythons found */
1580         fwprintf(stderr, L"\nNo Installed Pythons Found!");
1581     else
1582     {
1583         for (i = 0; i < num_installed_pythons; i++, ip++) {
1584             wchar_t version[BUFSIZ];
1585             if (wcscmp(ip->version, L"venv") == 0) {
1586                 wcscpy_s(version, BUFSIZ, L"(venv)");
1587             }
1588             else {
1589                 swprintf_s(version, BUFSIZ, ver_fmt, ip->version, ip->bits);
1590             }
1591 
1592             if (ip->exe_display[0]) {
1593                 fwprintf(stdout, fmt, version, ip->exe_display);
1594             }
1595             else {
1596                 fwprintf(stdout, fmt, version, ip->executable);
1597             }
1598             /* If there is a default indicate it */
1599             if (defpy == ip)
1600                 fwprintf(stderr, defind);
1601         }
1602     }
1603 
1604     if ((defpy == NULL) && (num_installed_pythons > 0))
1605         /* We have pythons but none is the default */
1606         fwprintf(stderr, L"\n\nCan't find a Default Python.\n\n");
1607     else
1608         fwprintf(stderr, L"\n\n"); /* End with a blank line */
1609     return FALSE; /* If this has been called we cannot continue */
1610 }
1611 
1612 #if defined(VENV_REDIRECT)
1613 
1614 static int
find_home_value(const char * buffer,const char ** start,DWORD * length)1615 find_home_value(const char *buffer, const char **start, DWORD *length)
1616 {
1617     for (const char *s = strstr(buffer, "home"); s; s = strstr(s + 1, "\nhome")) {
1618         if (*s == '\n') {
1619             ++s;
1620         }
1621         for (int i = 4; i > 0 && *s; --i, ++s);
1622 
1623         while (*s && iswspace(*s)) {
1624             ++s;
1625         }
1626         if (*s != L'=') {
1627             continue;
1628         }
1629 
1630         do {
1631             ++s;
1632         } while (*s && iswspace(*s));
1633 
1634         *start = s;
1635         char *nl = strchr(s, '\n');
1636         if (nl) {
1637             *length = (DWORD)((ptrdiff_t)nl - (ptrdiff_t)s);
1638         } else {
1639             *length = (DWORD)strlen(s);
1640         }
1641         return 1;
1642     }
1643     return 0;
1644 }
1645 #endif
1646 
1647 static wchar_t *
wcsdup_pad(const wchar_t * s,int padding,int * newlen)1648 wcsdup_pad(const wchar_t *s, int padding, int *newlen)
1649 {
1650     size_t len = wcslen(s);
1651     len += 1 + padding;
1652     wchar_t *r = (wchar_t *)malloc(len * sizeof(wchar_t));
1653     if (!r) {
1654         return NULL;
1655     }
1656     if (wcscpy_s(r, len, s)) {
1657         free(r);
1658         return NULL;
1659     }
1660     *newlen = len < MAXINT ? (int)len : MAXINT;
1661     return r;
1662 }
1663 
1664 static wchar_t *
get_process_name()1665 get_process_name()
1666 {
1667     DWORD bufferLen = MAX_PATH;
1668     DWORD len = bufferLen;
1669     wchar_t *r = NULL;
1670 
1671     while (!r) {
1672         r = (wchar_t *)malloc(bufferLen * sizeof(wchar_t));
1673         if (!r) {
1674             error(RC_NO_MEMORY, L"out of memory");
1675             return NULL;
1676         }
1677         len = GetModuleFileNameW(NULL, r, bufferLen);
1678         if (len == 0) {
1679             free(r);
1680             error(0, L"Failed to get module name");
1681             return NULL;
1682         } else if (len == bufferLen &&
1683                    GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
1684             free(r);
1685             r = NULL;
1686             bufferLen *= 2;
1687         }
1688     }
1689 
1690     return r;
1691 }
1692 
1693 static int
process(int argc,wchar_t ** argv)1694 process(int argc, wchar_t ** argv)
1695 {
1696     wchar_t * wp;
1697     wchar_t * command;
1698     wchar_t * executable;
1699     wchar_t * p;
1700     wchar_t * argv0;
1701     int rc = 0;
1702     INSTALLED_PYTHON * ip;
1703     BOOL valid;
1704     DWORD size, attrs;
1705     wchar_t message[MSGSIZE];
1706     void * version_data;
1707     VS_FIXEDFILEINFO * file_info;
1708     UINT block_size;
1709 #if defined(VENV_REDIRECT)
1710     wchar_t * venv_cfg_path;
1711     int newlen;
1712 #elif defined(SCRIPT_WRAPPER)
1713     wchar_t * newcommand;
1714     wchar_t * av[2];
1715     int newlen;
1716     HRESULT hr;
1717     int index;
1718 #else
1719     HRESULT hr;
1720     int index;
1721 #endif
1722 
1723     setvbuf(stderr, (char *)NULL, _IONBF, 0);
1724     wp = get_env(L"PYLAUNCH_DEBUG");
1725     if ((wp != NULL) && (*wp != L'\0'))
1726         log_fp = stderr;
1727 
1728 #if defined(_M_X64)
1729     debug(L"launcher build: 64bit\n");
1730 #else
1731     debug(L"launcher build: 32bit\n");
1732 #endif
1733 #if defined(_WINDOWS)
1734     debug(L"launcher executable: Windows\n");
1735 #else
1736     debug(L"launcher executable: Console\n");
1737 #endif
1738 #if !defined(VENV_REDIRECT)
1739     /* Get the local appdata folder (non-roaming) */
1740     hr = SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA,
1741                           NULL, 0, appdata_ini_path);
1742     if (hr != S_OK) {
1743         debug(L"SHGetFolderPath failed: %X\n", hr);
1744         appdata_ini_path[0] = L'\0';
1745     }
1746     else {
1747         wcsncat_s(appdata_ini_path, MAX_PATH, L"\\py.ini", _TRUNCATE);
1748         attrs = GetFileAttributesW(appdata_ini_path);
1749         if (attrs == INVALID_FILE_ATTRIBUTES) {
1750             debug(L"File '%ls' non-existent\n", appdata_ini_path);
1751             appdata_ini_path[0] = L'\0';
1752         } else {
1753             debug(L"Using local configuration file '%ls'\n", appdata_ini_path);
1754         }
1755     }
1756 #endif
1757     argv0 = get_process_name();
1758     size = GetFileVersionInfoSizeW(argv0, &size);
1759     if (size == 0) {
1760         winerror(GetLastError(), message, MSGSIZE);
1761         debug(L"GetFileVersionInfoSize failed: %ls\n", message);
1762     }
1763     else {
1764         version_data = malloc(size);
1765         if (version_data) {
1766             valid = GetFileVersionInfoW(argv0, 0, size,
1767                                         version_data);
1768             if (!valid)
1769                 debug(L"GetFileVersionInfo failed: %X\n", GetLastError());
1770             else {
1771                 valid = VerQueryValueW(version_data, L"\\",
1772                                        (LPVOID *) &file_info, &block_size);
1773                 if (!valid)
1774                     debug(L"VerQueryValue failed: %X\n", GetLastError());
1775                 else {
1776                     version_high = file_info->dwFileVersionMS;
1777                     version_low = file_info->dwFileVersionLS;
1778                 }
1779             }
1780             free(version_data);
1781         }
1782     }
1783 
1784 #if defined(VENV_REDIRECT)
1785     /* Allocate some extra space for new filenames */
1786     venv_cfg_path = wcsdup_pad(argv0, 32, &newlen);
1787     if (!venv_cfg_path) {
1788         error(RC_NO_MEMORY, L"Failed to copy module name");
1789     }
1790     p = wcsrchr(venv_cfg_path, L'\\');
1791 
1792     if (p == NULL) {
1793         error(RC_NO_VENV_CFG, L"No pyvenv.cfg file");
1794     }
1795     p[0] = L'\0';
1796     wcscat_s(venv_cfg_path, newlen, L"\\pyvenv.cfg");
1797     attrs = GetFileAttributesW(venv_cfg_path);
1798     if (attrs == INVALID_FILE_ATTRIBUTES) {
1799         debug(L"File '%ls' non-existent\n", venv_cfg_path);
1800         p[0] = '\0';
1801         p = wcsrchr(venv_cfg_path, L'\\');
1802         if (p != NULL) {
1803             p[0] = '\0';
1804             wcscat_s(venv_cfg_path, newlen, L"\\pyvenv.cfg");
1805             attrs = GetFileAttributesW(venv_cfg_path);
1806             if (attrs == INVALID_FILE_ATTRIBUTES) {
1807                 debug(L"File '%ls' non-existent\n", venv_cfg_path);
1808                 error(RC_NO_VENV_CFG, L"No pyvenv.cfg file");
1809             }
1810         }
1811     }
1812     debug(L"Using venv configuration file '%ls'\n", venv_cfg_path);
1813 #else
1814     /* Allocate some extra space for new filenames */
1815     if (wcscpy_s(launcher_ini_path, MAX_PATH, argv0)) {
1816         error(RC_NO_MEMORY, L"Failed to copy module name");
1817     }
1818     p = wcsrchr(launcher_ini_path, L'\\');
1819 
1820     if (p == NULL) {
1821         debug(L"GetModuleFileNameW returned value has no backslash: %ls\n",
1822               launcher_ini_path);
1823         launcher_ini_path[0] = L'\0';
1824     }
1825     else {
1826         p[0] = L'\0';
1827         wcscat_s(launcher_ini_path, MAX_PATH, L"\\py.ini");
1828         attrs = GetFileAttributesW(launcher_ini_path);
1829         if (attrs == INVALID_FILE_ATTRIBUTES) {
1830             debug(L"File '%ls' non-existent\n", launcher_ini_path);
1831             launcher_ini_path[0] = L'\0';
1832         } else {
1833             debug(L"Using global configuration file '%ls'\n", launcher_ini_path);
1834         }
1835     }
1836 #endif
1837 
1838     command = skip_me(GetCommandLineW());
1839     debug(L"Called with command line: %ls\n", command);
1840 
1841 #if !defined(VENV_REDIRECT)
1842     /* bpo-35811: The __PYVENV_LAUNCHER__ variable is used to
1843      * override sys.executable and locate the original prefix path.
1844      * However, if it is silently inherited by a non-venv Python
1845      * process, that process will believe it is running in the venv
1846      * still. This is the only place where *we* can clear it (that is,
1847      * when py.exe is being used to launch Python), so we do.
1848      */
1849     SetEnvironmentVariableW(L"__PYVENV_LAUNCHER__", NULL);
1850 #endif
1851 
1852 #if defined(SCRIPT_WRAPPER)
1853     /* The launcher is being used in "script wrapper" mode.
1854      * There should therefore be a Python script named <exename>-script.py in
1855      * the same directory as the launcher executable.
1856      * Put the script name into argv as the first (script name) argument.
1857      */
1858 
1859     /* Get the wrapped script name - if the script is not present, this will
1860      * terminate the program with an error.
1861      */
1862     locate_wrapped_script();
1863 
1864     /* Add the wrapped script to the start of command */
1865     newlen = wcslen(wrapped_script_path) + wcslen(command) + 2; /* ' ' + NUL */
1866     newcommand = malloc(sizeof(wchar_t) * newlen);
1867     if (!newcommand) {
1868         error(RC_NO_MEMORY, L"Could not allocate new command line");
1869     }
1870     else {
1871         wcscpy_s(newcommand, newlen, wrapped_script_path);
1872         wcscat_s(newcommand, newlen, L" ");
1873         wcscat_s(newcommand, newlen, command);
1874         debug(L"Running wrapped script with command line '%ls'\n", newcommand);
1875         read_commands();
1876         av[0] = wrapped_script_path;
1877         av[1] = NULL;
1878         maybe_handle_shebang(av, newcommand);
1879         /* Returns if no shebang line - pass to default processing */
1880         command = newcommand;
1881         valid = FALSE;
1882     }
1883 #elif defined(VENV_REDIRECT)
1884     {
1885         FILE *f;
1886         char buffer[4096]; /* 4KB should be enough for anybody */
1887         char *start;
1888         DWORD len, cch, cch_actual;
1889         size_t cb;
1890         if (_wfopen_s(&f, venv_cfg_path, L"r")) {
1891             error(RC_BAD_VENV_CFG, L"Cannot read '%ls'", venv_cfg_path);
1892         }
1893         cb = fread_s(buffer, sizeof(buffer), sizeof(buffer[0]),
1894                      sizeof(buffer) / sizeof(buffer[0]), f);
1895         fclose(f);
1896 
1897         if (!find_home_value(buffer, &start, &len)) {
1898             error(RC_BAD_VENV_CFG, L"Cannot find home in '%ls'",
1899                   venv_cfg_path);
1900         }
1901 
1902         cch = MultiByteToWideChar(CP_UTF8, 0, start, len, NULL, 0);
1903         if (!cch) {
1904             error(0, L"Cannot determine memory for home path");
1905         }
1906         cch += (DWORD)wcslen(PYTHON_EXECUTABLE) + 1 + 1; /* include sep and null */
1907         executable = (wchar_t *)malloc(cch * sizeof(wchar_t));
1908         if (executable == NULL) {
1909             error(RC_NO_MEMORY, L"A memory allocation failed");
1910         }
1911         cch_actual = MultiByteToWideChar(CP_UTF8, 0, start, len, executable, cch);
1912         if (!cch_actual) {
1913             error(RC_BAD_VENV_CFG, L"Cannot decode home path in '%ls'",
1914                   venv_cfg_path);
1915         }
1916         if (executable[cch_actual - 1] != L'\\') {
1917             executable[cch_actual++] = L'\\';
1918             executable[cch_actual] = L'\0';
1919         }
1920         if (wcscat_s(executable, cch, PYTHON_EXECUTABLE)) {
1921             error(RC_BAD_VENV_CFG, L"Cannot create executable path from '%ls'",
1922                   venv_cfg_path);
1923         }
1924         if (GetFileAttributesW(executable) == INVALID_FILE_ATTRIBUTES) {
1925             error(RC_NO_PYTHON, L"No Python at '%ls'", executable);
1926         }
1927         if (!SetEnvironmentVariableW(L"__PYVENV_LAUNCHER__", argv0)) {
1928             error(0, L"Failed to set launcher environment");
1929         }
1930         valid = 1;
1931     }
1932 #else
1933     if (argc <= 1) {
1934         valid = FALSE;
1935         p = NULL;
1936     }
1937     else {
1938         p = argv[1];
1939         if ((argc == 2) && // list version args
1940             (!wcsncmp(p, L"-0", wcslen(L"-0")) ||
1941             !wcsncmp(p, L"--list", wcslen(L"--list"))))
1942         {
1943             show_python_list(argv);
1944             return rc;
1945         }
1946         valid = valid && (*p == L'-') && validate_version(&p[1]);
1947         if (valid) {
1948             ip = locate_python(&p[1], FALSE);
1949             if (ip == NULL)
1950             {
1951                 fwprintf(stdout, \
1952                          L"Python %ls not found!\n", &p[1]);
1953                 valid = show_python_list(argv);
1954                 error(RC_NO_PYTHON, L"Requested Python version (%ls) not \
1955 installed, use -0 for available pythons", &p[1]);
1956             }
1957             executable = ip->executable;
1958             command += wcslen(p);
1959             command = skip_whitespace(command);
1960         }
1961         else {
1962             for (index = 1; index < argc; ++index) {
1963                 if (*argv[index] != L'-')
1964                     break;
1965             }
1966             if (index < argc) {
1967                 read_commands();
1968                 maybe_handle_shebang(&argv[index], command);
1969             }
1970         }
1971     }
1972 #endif
1973 
1974     if (!valid) {
1975         if ((argc == 2) && (!_wcsicmp(p, L"-h") || !_wcsicmp(p, L"--help")))
1976             show_help_text(argv);
1977         if ((argc == 2) &&
1978             (!_wcsicmp(p, L"-0") || !_wcsicmp(p, L"--list") ||
1979             !_wcsicmp(p, L"-0p") || !_wcsicmp(p, L"--list-paths")))
1980         {
1981             executable = NULL; /* Info call only */
1982         }
1983         else {
1984             /* look for the default Python */
1985             ip = locate_python(L"", FALSE);
1986             if (ip == NULL)
1987                 error(RC_NO_PYTHON, L"Can't find a default Python.");
1988             executable = ip->executable;
1989         }
1990     }
1991     if (executable != NULL)
1992         invoke_child(executable, NULL, command);
1993     else
1994         rc = RC_NO_PYTHON;
1995     return rc;
1996 }
1997 
1998 #if defined(_WINDOWS)
1999 
wWinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPWSTR lpstrCmd,int nShow)2000 int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
2001                    LPWSTR lpstrCmd, int nShow)
2002 {
2003     return process(__argc, __wargv);
2004 }
2005 
2006 #else
2007 
wmain(int argc,wchar_t ** argv)2008 int cdecl wmain(int argc, wchar_t ** argv)
2009 {
2010     return process(argc, argv);
2011 }
2012 
2013 #endif
2014