blob: cc2d35b2c4cb7cca44ce0fd79fea2bfd294fc1f4 [file] [log] [blame]
Brian Curtin07165f72012-06-20 15:36:14 -05001/*
Vinay Sajip22c039b2013-06-07 15:37:28 +01002 * Copyright (C) 2011-2013 Vinay Sajip.
Martin v. Löwis6a8ca3e2012-06-21 19:29:37 +02003 * Licensed to PSF under a contributor agreement.
Brian Curtin07165f72012-06-20 15:36:14 -05004 *
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
Vinay Sajip22c039b2013-06-07 15:37:28 +010021#define SEARCH_PATH
Brian Curtin07165f72012-06-20 15:36:14 -050022
Vinay Sajipc985d082013-07-25 11:20:55 +010023/* 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/*
Steve Dower1c3de542018-12-10 08:11:21 -080031 * SCRIPT_WRAPPER is used to choose one of the variants of an executable built
Vinay Sajipc985d082013-07-25 11:20:55 +010032 * 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
Steve Dower1c3de542018-12-10 08:11:21 -080043/*
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
Vinay Sajipc985d082013-07-25 11:20:55 +010052
Brian Curtin07165f72012-06-20 15:36:14 -050053/* Just for now - static definition */
54
55static FILE * log_fp = NULL;
56
57static wchar_t *
58skip_whitespace(wchar_t * p)
59{
60 while (*p && isspace(*p))
61 ++p;
62 return p;
63}
64
Brian Curtin07165f72012-06-20 15:36:14 -050065static void
66debug(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);
Zackery Spytz3a6d7522018-06-15 16:39:04 -060073 va_end(va);
Brian Curtin07165f72012-06-20 15:36:14 -050074 }
75}
76
77static void
78winerror(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
86static void
87error(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);
Zackery Spytz3a6d7522018-06-15 16:39:04 -060096 va_end(va);
Brian Curtin07165f72012-06-20 15:36:14 -050097
98 if (rc == 0) { /* a Windows error */
99 winerror(GetLastError(), win_message, MSGSIZE);
100 if (len >= 0) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800101 _snwprintf_s(&message[len], MSGSIZE - len, _TRUNCATE, L": %ls",
Brian Curtin07165f72012-06-20 15:36:14 -0500102 win_message);
103 }
104 }
105
106#if !defined(_WINDOWS)
Steve Dower84bcfb32015-01-02 18:07:46 -0800107 fwprintf(stderr, L"%ls\n", message);
Brian Curtin07165f72012-06-20 15:36:14 -0500108#else
Steve Dower1c3de542018-12-10 08:11:21 -0800109 MessageBoxW(NULL, message, L"Python Launcher is sorry to say ...",
Serhiy Storchaka009b8112015-03-18 21:53:15 +0200110 MB_OK);
Brian Curtin07165f72012-06-20 15:36:14 -0500111#endif
Vinay Sajipaab9f462015-12-26 12:35:47 +0000112 exit(rc);
Brian Curtin07165f72012-06-20 15:36:14 -0500113}
114
Vinay Sajipc985d082013-07-25 11:20:55 +0100115/*
116 * This function is here to simplify memory management
117 * and to treat blank values as if they are absent.
118 */
119static 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));
Vinay Sajipabeb6472015-12-13 09:41:29 +0000128 if (buf2 == NULL) {
Vinay Sajipc985d082013-07-25 11:20:55 +0100129 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
Steve Dower1c3de542018-12-10 08:11:21 -0800143#if defined(_DEBUG)
Steve Dower353fb1e2019-10-03 08:31:21 -0700144/* Do not define EXECUTABLEPATH_VALUE in debug builds as it'll
145 never point to the debug build. */
Steve Dower1c3de542018-12-10 08:11:21 -0800146#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
Brian Curtin07165f72012-06-20 15:36:14 -0500156#if defined(_WINDOWS)
157
158#define PYTHON_EXECUTABLE L"pythonw.exe"
Steve Dower353fb1e2019-10-03 08:31:21 -0700159#define EXECUTABLEPATH_VALUE L"WindowedExecutablePath"
Brian Curtin07165f72012-06-20 15:36:14 -0500160
161#else
162
163#define PYTHON_EXECUTABLE L"python.exe"
Steve Dower353fb1e2019-10-03 08:31:21 -0700164#define EXECUTABLEPATH_VALUE L"ExecutablePath"
Brian Curtin07165f72012-06-20 15:36:14 -0500165
166#endif
Steve Dower1c3de542018-12-10 08:11:21 -0800167#endif
Brian Curtin07165f72012-06-20 15:36:14 -0500168
Steve Dowered93a882019-09-12 18:16:50 +0100169#define MAX_VERSION_SIZE 8
Brian Curtin07165f72012-06-20 15:36:14 -0500170
171typedef struct {
172 wchar_t version[MAX_VERSION_SIZE]; /* m.n */
173 int bits; /* 32 or 64 */
174 wchar_t executable[MAX_PATH];
Steve Dowered93a882019-09-12 18:16:50 +0100175 wchar_t exe_display[MAX_PATH];
Brian Curtin07165f72012-06-20 15:36:14 -0500176} 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
184static INSTALLED_PYTHON installed_pythons[MAX_INSTALLED_PYTHONS];
185
186static size_t num_installed_pythons = 0;
187
Steve Dowerbb240872015-02-05 22:08:48 -0800188/*
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 */
Steve Dowered93a882019-09-12 18:16:50 +0100193#define IP_BASE_SIZE 80
Steve Dowerbb240872015-02-05 22:08:48 -0800194#define IP_VERSION_SIZE 8
195#define IP_SIZE (IP_BASE_SIZE + IP_VERSION_SIZE)
Brian Curtin07165f72012-06-20 15:36:14 -0500196#define CORE_PATH L"SOFTWARE\\Python\\PythonCore"
Steve Dowered93a882019-09-12 18:16:50 +0100197/*
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"
Brian Curtin07165f72012-06-20 15:36:14 -0500205
206static wchar_t * location_checks[] = {
207 L"\\",
Stefan Grönkef1502d02017-09-25 18:58:10 +0200208 L"\\PCbuild\\win32\\",
209 L"\\PCbuild\\amd64\\",
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100210 /* To support early 32bit versions of Python that stuck the build binaries
Stefan Grönkef1502d02017-09-25 18:58:10 +0200211 * directly in PCbuild... */
212 L"\\PCbuild\\",
Brian Curtin07165f72012-06-20 15:36:14 -0500213 NULL
214};
215
216static INSTALLED_PYTHON *
Steve Dowered93a882019-09-12 18:16:50 +0100217find_existing_python(const wchar_t * path)
Brian Curtin07165f72012-06-20 15:36:14 -0500218{
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
Steve Dowered93a882019-09-12 18:16:50 +0100232static INSTALLED_PYTHON *
233find_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
Brian Curtin07165f72012-06-20 15:36:14 -0500248static void
Steve Dowered93a882019-09-12 18:16:50 +0100249_locate_pythons_for_key(HKEY root, LPCWSTR subkey, REGSAM flags, int bits,
250 int display_name_only)
Brian Curtin07165f72012-06-20 15:36:14 -0500251{
252 HKEY core_root, ip_key;
Steve Dowered93a882019-09-12 18:16:50 +0100253 LSTATUS status = RegOpenKeyExW(root, subkey, 0, flags, &core_root);
Brian Curtin07165f72012-06-20 15:36:14 -0500254 wchar_t message[MSGSIZE];
255 DWORD i;
256 size_t n;
Steve Dowered93a882019-09-12 18:16:50 +0100257 BOOL ok, append_name;
Brian Curtin07165f72012-06-20 15:36:14 -0500258 DWORD type, data_size, attrs;
259 INSTALLED_PYTHON * ip, * pip;
Steve Dowerbb240872015-02-05 22:08:48 -0800260 wchar_t ip_version[IP_VERSION_SIZE];
Brian Curtin07165f72012-06-20 15:36:14 -0500261 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)
Steve Dower84bcfb32015-01-02 18:07:46 -0800267 debug(L"locate_pythons_for_key: unable to open PythonCore key in %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500268 key_name);
269 else {
270 ip = &installed_pythons[num_installed_pythons];
271 for (i = 0; num_installed_pythons < MAX_INSTALLED_PYTHONS; i++) {
Steve Dowerbb240872015-02-05 22:08:48 -0800272 status = RegEnumKeyW(core_root, i, ip_version, IP_VERSION_SIZE);
Brian Curtin07165f72012-06-20 15:36:14 -0500273 if (status != ERROR_SUCCESS) {
274 if (status != ERROR_NO_MORE_ITEMS) {
275 /* unexpected error */
276 winerror(status, message, MSGSIZE);
Steve Dower84bcfb32015-01-02 18:07:46 -0800277 debug(L"Can't enumerate registry key for version %ls: %ls\n",
Steve Dowerbb240872015-02-05 22:08:48 -0800278 ip_version, message);
Brian Curtin07165f72012-06-20 15:36:14 -0500279 }
280 break;
281 }
282 else {
Steve Dowerbb240872015-02-05 22:08:48 -0800283 wcsncpy_s(ip->version, MAX_VERSION_SIZE, ip_version,
284 MAX_VERSION_SIZE-1);
Steve Dowered93a882019-09-12 18:16:50 +0100285 /* 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 }
Brian Curtin07165f72012-06-20 15:36:14 -0500293 _snwprintf_s(ip_path, IP_SIZE, _TRUNCATE,
Steve Dowered93a882019-09-12 18:16:50 +0100294 L"%ls\\%ls\\InstallPath", subkey, ip_version);
Brian Curtin07165f72012-06-20 15:36:14 -0500295 status = RegOpenKeyExW(root, ip_path, 0, flags, &ip_key);
296 if (status != ERROR_SUCCESS) {
297 winerror(status, message, MSGSIZE);
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100298 /* Note: 'message' already has a trailing \n*/
Steve Dower84bcfb32015-01-02 18:07:46 -0800299 debug(L"%ls\\%ls: %ls", key_name, ip_path, message);
Brian Curtin07165f72012-06-20 15:36:14 -0500300 continue;
301 }
302 data_size = sizeof(ip->executable) - 1;
Steve Dowered93a882019-09-12 18:16:50 +0100303 append_name = FALSE;
Steve Dower353fb1e2019-10-03 08:31:21 -0700304#ifdef EXECUTABLEPATH_VALUE
305 status = RegQueryValueExW(ip_key, EXECUTABLEPATH_VALUE, NULL, &type,
Martin v. Löwisaf21ebb2012-06-21 18:15:54 +0200306 (LPBYTE)ip->executable, &data_size);
Steve Dower353fb1e2019-10-03 08:31:21 -0700307#else
308 status = ERROR_FILE_NOT_FOUND; /* actual error doesn't matter */
309#endif
Steve Dowered93a882019-09-12 18:16:50 +0100310 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 }
Brian Curtin07165f72012-06-20 15:36:14 -0500322 RegCloseKey(ip_key);
Steve Dowered93a882019-09-12 18:16:50 +0100323 if (type != REG_SZ) {
Brian Curtin07165f72012-06-20 15:36:14 -0500324 continue;
325 }
Steve Dowered93a882019-09-12 18:16:50 +0100326
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) {
Brian Curtin07165f72012-06-20 15:36:14 -0500334 _snwprintf_s(&ip->executable[data_size],
335 MAX_PATH - data_size,
336 MAX_PATH - data_size,
Steve Dower84bcfb32015-01-02 18:07:46 -0800337 L"%ls%ls", check, PYTHON_EXECUTABLE);
Steve Dowered93a882019-09-12 18:16:50 +0100338 }
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 {
Brian Curtin07165f72012-06-20 15:36:14 -0500358 ok = GetBinaryTypeW(ip->executable, &attrs);
359 if (!ok) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800360 debug(L"Failure getting binary type: %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500361 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;
Steve Dowered93a882019-09-12 18:16:50 +0100370 }
371 }
372 if (ip->bits == 0) {
373 debug(L"locate_pythons_for_key: %ls: \
Brian Curtin07165f72012-06-20 15:36:14 -0500374invalid binary type: %X\n",
Steve Dowered93a882019-09-12 18:16:50 +0100375 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);
Brian Curtin07165f72012-06-20 15:36:14 -0500384 }
Steve Dowered93a882019-09-12 18:16:50 +0100385 }
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 \
Brian Curtin07165f72012-06-20 15:36:14 -0500400is a %dbit executable\n",
Steve Dowered93a882019-09-12 18:16:50 +0100401 ip->executable, ip->bits);
402 if (find_existing_python2(ip->bits, ip->version)) {
403 debug(L"locate_pythons_for_key: %ls-%i: already \
404found\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;
Brian Curtin07165f72012-06-20 15:36:14 -0500412 }
413 }
414 }
415 }
416 }
417 }
418 RegCloseKey(core_root);
419 }
420}
421
422static int
423compare_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 */
Zackery Spytzf62dad12020-11-16 14:32:35 -0700428 int result = CompareStringW(LOCALE_INVARIANT, SORT_DIGITSASNUMBERS,
429 ip2->version, -1, ip1->version, -1);
430 switch (result) {
431 case 0:
432 error(0, L"CompareStringW failed");
433 return 0;
434 case CSTR_LESS_THAN:
435 return -1;
436 case CSTR_EQUAL:
437 return ip2->bits - ip1->bits; /* 64 before 32 */
438 case CSTR_GREATER_THAN:
439 return 1;
440 default:
441 return 0; // This should never be reached.
442 }
Brian Curtin07165f72012-06-20 15:36:14 -0500443}
444
445static void
Steve Dowered93a882019-09-12 18:16:50 +0100446locate_pythons_for_key(HKEY root, REGSAM flags)
447{
448 _locate_pythons_for_key(root, CORE_PATH, flags, 0, FALSE);
449}
450
451static void
452locate_store_pythons()
453{
454#if defined(_M_X64)
455 /* 64bit process, so look in native registry */
456 _locate_pythons_for_key(HKEY_LOCAL_MACHINE, LOOKASIDE_PATH,
457 KEY_READ, 64, TRUE);
458#else
459 /* 32bit process, so check that we're on 64bit OS */
460 BOOL f64 = FALSE;
461 if (IsWow64Process(GetCurrentProcess(), &f64) && f64) {
462 _locate_pythons_for_key(HKEY_LOCAL_MACHINE, LOOKASIDE_PATH,
463 KEY_READ | KEY_WOW64_64KEY, 64, TRUE);
464 }
465#endif
466}
467
468static void
469locate_venv_python()
470{
471 static wchar_t venv_python[MAX_PATH];
472 INSTALLED_PYTHON * ip;
473 wchar_t *virtual_env = get_env(L"VIRTUAL_ENV");
474 DWORD attrs;
475
476 /* Check for VIRTUAL_ENV environment variable */
477 if (virtual_env == NULL || virtual_env[0] == L'\0') {
478 return;
479 }
480
481 /* Check for a python executable in the venv */
482 debug(L"Checking for Python executable in virtual env '%ls'\n", virtual_env);
483 _snwprintf_s(venv_python, MAX_PATH, _TRUNCATE,
484 L"%ls\\Scripts\\%ls", virtual_env, PYTHON_EXECUTABLE);
485 attrs = GetFileAttributesW(venv_python);
486 if (attrs == INVALID_FILE_ATTRIBUTES) {
487 debug(L"Python executable %ls missing from virtual env\n", venv_python);
488 return;
489 }
490
491 ip = &installed_pythons[num_installed_pythons++];
492 wcscpy_s(ip->executable, MAX_PATH, venv_python);
493 ip->bits = 0;
494 wcscpy_s(ip->version, MAX_VERSION_SIZE, L"venv");
495}
496
497static void
Brian Curtin07165f72012-06-20 15:36:14 -0500498locate_all_pythons()
499{
Steve Dowered93a882019-09-12 18:16:50 +0100500 /* venv Python is highest priority */
501 locate_venv_python();
Brian Curtin07165f72012-06-20 15:36:14 -0500502#if defined(_M_X64)
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100503 /* If we are a 64bit process, first hit the 32bit keys. */
Brian Curtin07165f72012-06-20 15:36:14 -0500504 debug(L"locating Pythons in 32bit registry\n");
505 locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ | KEY_WOW64_32KEY);
506 locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ | KEY_WOW64_32KEY);
507#else
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100508 /* If we are a 32bit process on a 64bit Windows, first hit the 64bit keys.*/
Brian Curtin07165f72012-06-20 15:36:14 -0500509 BOOL f64 = FALSE;
510 if (IsWow64Process(GetCurrentProcess(), &f64) && f64) {
511 debug(L"locating Pythons in 64bit registry\n");
512 locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ | KEY_WOW64_64KEY);
513 locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ | KEY_WOW64_64KEY);
514 }
Serhiy Storchaka009b8112015-03-18 21:53:15 +0200515#endif
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100516 /* now hit the "native" key for this process bittedness. */
Brian Curtin07165f72012-06-20 15:36:14 -0500517 debug(L"locating Pythons in native registry\n");
518 locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ);
519 locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ);
Steve Dowered93a882019-09-12 18:16:50 +0100520 /* Store-installed Python is lowest priority */
521 locate_store_pythons();
Brian Curtin07165f72012-06-20 15:36:14 -0500522 qsort(installed_pythons, num_installed_pythons, sizeof(INSTALLED_PYTHON),
523 compare_pythons);
524}
525
526static INSTALLED_PYTHON *
527find_python_by_version(wchar_t const * wanted_ver)
528{
529 INSTALLED_PYTHON * result = NULL;
530 INSTALLED_PYTHON * ip = installed_pythons;
531 size_t i, n;
532 size_t wlen = wcslen(wanted_ver);
533 int bits = 0;
534
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100535 if (wcsstr(wanted_ver, L"-32")) {
Brian Curtin07165f72012-06-20 15:36:14 -0500536 bits = 32;
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100537 wlen -= wcslen(L"-32");
538 }
539 else if (wcsstr(wanted_ver, L"-64")) { /* Added option to select 64 bit explicitly */
540 bits = 64;
541 wlen -= wcslen(L"-64");
542 }
Brian Curtin07165f72012-06-20 15:36:14 -0500543 for (i = 0; i < num_installed_pythons; i++, ip++) {
544 n = wcslen(ip->version);
545 if (n > wlen)
546 n = wlen;
547 if ((wcsncmp(ip->version, wanted_ver, n) == 0) &&
548 /* bits == 0 => don't care */
549 ((bits == 0) || (ip->bits == bits))) {
550 result = ip;
551 break;
552 }
553 }
554 return result;
555}
556
557
558static wchar_t appdata_ini_path[MAX_PATH];
559static wchar_t launcher_ini_path[MAX_PATH];
560
561/*
562 * Get a value either from the environment or a configuration file.
563 * The key passed in will either be "python", "python2" or "python3".
564 */
565static wchar_t *
566get_configured_value(wchar_t * key)
567{
568/*
569 * Note: this static value is used to return a configured value
570 * obtained either from the environment or configuration file.
571 * This should be OK since there wouldn't be any concurrent calls.
572 */
573 static wchar_t configured_value[MSGSIZE];
574 wchar_t * result = NULL;
575 wchar_t * found_in = L"environment";
576 DWORD size;
577
578 /* First, search the environment. */
Steve Dower84bcfb32015-01-02 18:07:46 -0800579 _snwprintf_s(configured_value, MSGSIZE, _TRUNCATE, L"py_%ls", key);
Brian Curtin07165f72012-06-20 15:36:14 -0500580 result = get_env(configured_value);
581 if (result == NULL && appdata_ini_path[0]) {
582 /* Not in environment: check local configuration. */
583 size = GetPrivateProfileStringW(L"defaults", key, NULL,
584 configured_value, MSGSIZE,
585 appdata_ini_path);
586 if (size > 0) {
587 result = configured_value;
588 found_in = appdata_ini_path;
589 }
590 }
591 if (result == NULL && launcher_ini_path[0]) {
592 /* Not in environment or local: check global configuration. */
593 size = GetPrivateProfileStringW(L"defaults", key, NULL,
594 configured_value, MSGSIZE,
595 launcher_ini_path);
596 if (size > 0) {
597 result = configured_value;
598 found_in = launcher_ini_path;
599 }
600 }
601 if (result) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800602 debug(L"found configured value '%ls=%ls' in %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500603 key, result, found_in ? found_in : L"(unknown)");
604 } else {
Steve Dower84bcfb32015-01-02 18:07:46 -0800605 debug(L"found no configured value for '%ls'\n", key);
Brian Curtin07165f72012-06-20 15:36:14 -0500606 }
607 return result;
608}
609
610static INSTALLED_PYTHON *
Paul Moore835416c2016-05-22 12:28:41 +0100611locate_python(wchar_t * wanted_ver, BOOL from_shebang)
Brian Curtin07165f72012-06-20 15:36:14 -0500612{
613 static wchar_t config_key [] = { L"pythonX" };
614 static wchar_t * last_char = &config_key[sizeof(config_key) /
615 sizeof(wchar_t) - 2];
616 INSTALLED_PYTHON * result = NULL;
617 size_t n = wcslen(wanted_ver);
618 wchar_t * configured_value;
619
620 if (num_installed_pythons == 0)
621 locate_all_pythons();
622
623 if (n == 1) { /* just major version specified */
624 *last_char = *wanted_ver;
625 configured_value = get_configured_value(config_key);
626 if (configured_value != NULL)
627 wanted_ver = configured_value;
628 }
629 if (*wanted_ver) {
630 result = find_python_by_version(wanted_ver);
Steve Dower84bcfb32015-01-02 18:07:46 -0800631 debug(L"search for Python version '%ls' found ", wanted_ver);
Brian Curtin07165f72012-06-20 15:36:14 -0500632 if (result) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800633 debug(L"'%ls'\n", result->executable);
Brian Curtin07165f72012-06-20 15:36:14 -0500634 } else {
635 debug(L"no interpreter\n");
636 }
637 }
638 else {
639 *last_char = L'\0'; /* look for an overall default */
Steve Dowered93a882019-09-12 18:16:50 +0100640 result = find_python_by_version(L"venv");
641 if (result == NULL) {
642 configured_value = get_configured_value(config_key);
643 if (configured_value)
644 result = find_python_by_version(configured_value);
645 }
Paul Moore835416c2016-05-22 12:28:41 +0100646 /* Not found a value yet - try by major version.
647 * If we're looking for an interpreter specified in a shebang line,
648 * we want to try Python 2 first, then Python 3 (for Unix and backward
649 * compatibility). If we're being called interactively, assume the user
650 * wants the latest version available, so try Python 3 first, then
651 * Python 2.
652 */
Brian Curtin07165f72012-06-20 15:36:14 -0500653 if (result == NULL)
Paul Moore835416c2016-05-22 12:28:41 +0100654 result = find_python_by_version(from_shebang ? L"2" : L"3");
Brian Curtin07165f72012-06-20 15:36:14 -0500655 if (result == NULL)
Paul Moore835416c2016-05-22 12:28:41 +0100656 result = find_python_by_version(from_shebang ? L"3" : L"2");
Brian Curtin07165f72012-06-20 15:36:14 -0500657 debug(L"search for default Python found ");
658 if (result) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800659 debug(L"version %ls at '%ls'\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500660 result->version, result->executable);
661 } else {
662 debug(L"no interpreter\n");
663 }
664 }
665 return result;
666}
667
Vinay Sajipc985d082013-07-25 11:20:55 +0100668#if defined(SCRIPT_WRAPPER)
669/*
670 * Check for a script located alongside the executable
671 */
672
673#if defined(_WINDOWS)
674#define SCRIPT_SUFFIX L"-script.pyw"
675#else
676#define SCRIPT_SUFFIX L"-script.py"
677#endif
678
679static wchar_t wrapped_script_path[MAX_PATH];
680
681/* Locate the script being wrapped.
682 *
683 * This code should store the name of the wrapped script in
684 * wrapped_script_path, or terminate the program with an error if there is no
685 * valid wrapped script file.
686 */
687static void
688locate_wrapped_script()
689{
690 wchar_t * p;
691 size_t plen;
692 DWORD attrs;
693
694 plen = GetModuleFileNameW(NULL, wrapped_script_path, MAX_PATH);
695 p = wcsrchr(wrapped_script_path, L'.');
696 if (p == NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800697 debug(L"GetModuleFileNameW returned value has no extension: %ls\n",
Vinay Sajipc985d082013-07-25 11:20:55 +0100698 wrapped_script_path);
Steve Dower84bcfb32015-01-02 18:07:46 -0800699 error(RC_NO_SCRIPT, L"Wrapper name '%ls' is not valid.", wrapped_script_path);
Vinay Sajipc985d082013-07-25 11:20:55 +0100700 }
701
702 wcsncpy_s(p, MAX_PATH - (p - wrapped_script_path) + 1, SCRIPT_SUFFIX, _TRUNCATE);
703 attrs = GetFileAttributesW(wrapped_script_path);
704 if (attrs == INVALID_FILE_ATTRIBUTES) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800705 debug(L"File '%ls' non-existent\n", wrapped_script_path);
706 error(RC_NO_SCRIPT, L"Script file '%ls' is not present.", wrapped_script_path);
Vinay Sajipc985d082013-07-25 11:20:55 +0100707 }
708
Steve Dower84bcfb32015-01-02 18:07:46 -0800709 debug(L"Using wrapped script file '%ls'\n", wrapped_script_path);
Vinay Sajipc985d082013-07-25 11:20:55 +0100710}
711#endif
712
Brian Curtin07165f72012-06-20 15:36:14 -0500713/*
714 * Process creation code
715 */
716
717static BOOL
718safe_duplicate_handle(HANDLE in, HANDLE * pout)
719{
720 BOOL ok;
721 HANDLE process = GetCurrentProcess();
722 DWORD rc;
723
724 *pout = NULL;
725 ok = DuplicateHandle(process, in, process, pout, 0, TRUE,
726 DUPLICATE_SAME_ACCESS);
727 if (!ok) {
728 rc = GetLastError();
729 if (rc == ERROR_INVALID_HANDLE) {
730 debug(L"DuplicateHandle returned ERROR_INVALID_HANDLE\n");
731 ok = TRUE;
732 }
733 else {
734 debug(L"DuplicateHandle returned %d\n", rc);
735 }
736 }
737 return ok;
738}
739
740static BOOL WINAPI
741ctrl_c_handler(DWORD code)
742{
743 return TRUE; /* We just ignore all control events. */
744}
745
746static void
747run_child(wchar_t * cmdline)
748{
749 HANDLE job;
750 JOBOBJECT_EXTENDED_LIMIT_INFORMATION info;
751 DWORD rc;
752 BOOL ok;
753 STARTUPINFOW si;
754 PROCESS_INFORMATION pi;
755
Vinay Sajip66fef9f2013-02-26 16:29:06 +0000756#if defined(_WINDOWS)
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100757 /*
758 When explorer launches a Windows (GUI) application, it displays
759 the "app starting" (the "pointer + hourglass") cursor for a number
760 of seconds, or until the app does something UI-ish (eg, creating a
761 window, or fetching a message). As this launcher doesn't do this
762 directly, that cursor remains even after the child process does these
763 things. We avoid that by doing a simple post+get message.
764 See http://bugs.python.org/issue17290 and
765 https://bitbucket.org/vinay.sajip/pylauncher/issue/20/busy-cursor-for-a-long-time-when-running
766 */
Vinay Sajip66fef9f2013-02-26 16:29:06 +0000767 MSG msg;
768
769 PostMessage(0, 0, 0, 0);
770 GetMessage(&msg, 0, 0, 0);
771#endif
772
Steve Dower84bcfb32015-01-02 18:07:46 -0800773 debug(L"run_child: about to run '%ls'\n", cmdline);
Brian Curtin07165f72012-06-20 15:36:14 -0500774 job = CreateJobObject(NULL, NULL);
775 ok = QueryInformationJobObject(job, JobObjectExtendedLimitInformation,
776 &info, sizeof(info), &rc);
777 if (!ok || (rc != sizeof(info)) || !job)
778 error(RC_CREATE_PROCESS, L"Job information querying failed");
779 info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE |
780 JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK;
781 ok = SetInformationJobObject(job, JobObjectExtendedLimitInformation, &info,
782 sizeof(info));
783 if (!ok)
784 error(RC_CREATE_PROCESS, L"Job information setting failed");
785 memset(&si, 0, sizeof(si));
Shiva Saxenacb090472019-02-03 00:51:04 +0530786 GetStartupInfoW(&si);
Brian Curtin07165f72012-06-20 15:36:14 -0500787 ok = safe_duplicate_handle(GetStdHandle(STD_INPUT_HANDLE), &si.hStdInput);
788 if (!ok)
789 error(RC_NO_STD_HANDLES, L"stdin duplication failed");
790 ok = safe_duplicate_handle(GetStdHandle(STD_OUTPUT_HANDLE), &si.hStdOutput);
791 if (!ok)
792 error(RC_NO_STD_HANDLES, L"stdout duplication failed");
793 ok = safe_duplicate_handle(GetStdHandle(STD_ERROR_HANDLE), &si.hStdError);
794 if (!ok)
795 error(RC_NO_STD_HANDLES, L"stderr duplication failed");
796
797 ok = SetConsoleCtrlHandler(ctrl_c_handler, TRUE);
798 if (!ok)
799 error(RC_CREATE_PROCESS, L"control handler setting failed");
800
801 si.dwFlags = STARTF_USESTDHANDLES;
802 ok = CreateProcessW(NULL, cmdline, NULL, NULL, TRUE,
803 0, NULL, NULL, &si, &pi);
804 if (!ok)
Steve Dower84bcfb32015-01-02 18:07:46 -0800805 error(RC_CREATE_PROCESS, L"Unable to create process using '%ls'", cmdline);
Brian Curtin07165f72012-06-20 15:36:14 -0500806 AssignProcessToJobObject(job, pi.hProcess);
807 CloseHandle(pi.hThread);
Martin v. Löwisb26a9b12013-01-25 14:25:48 +0100808 WaitForSingleObjectEx(pi.hProcess, INFINITE, FALSE);
Brian Curtin07165f72012-06-20 15:36:14 -0500809 ok = GetExitCodeProcess(pi.hProcess, &rc);
810 if (!ok)
811 error(RC_CREATE_PROCESS, L"Failed to get exit code of process");
812 debug(L"child process exit code: %d\n", rc);
Vinay Sajipaab9f462015-12-26 12:35:47 +0000813 exit(rc);
Brian Curtin07165f72012-06-20 15:36:14 -0500814}
815
816static void
817invoke_child(wchar_t * executable, wchar_t * suffix, wchar_t * cmdline)
818{
819 wchar_t * child_command;
820 size_t child_command_size;
821 BOOL no_suffix = (suffix == NULL) || (*suffix == L'\0');
822 BOOL no_cmdline = (*cmdline == L'\0');
823
824 if (no_suffix && no_cmdline)
825 run_child(executable);
826 else {
827 if (no_suffix) {
828 /* add 2 for space separator + terminating NUL. */
829 child_command_size = wcslen(executable) + wcslen(cmdline) + 2;
830 }
831 else {
832 /* add 3 for 2 space separators + terminating NUL. */
833 child_command_size = wcslen(executable) + wcslen(suffix) +
834 wcslen(cmdline) + 3;
835 }
836 child_command = calloc(child_command_size, sizeof(wchar_t));
837 if (child_command == NULL)
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +0200838 error(RC_CREATE_PROCESS, L"unable to allocate %zd bytes for child command.",
Brian Curtin07165f72012-06-20 15:36:14 -0500839 child_command_size);
840 if (no_suffix)
841 _snwprintf_s(child_command, child_command_size,
Steve Dower84bcfb32015-01-02 18:07:46 -0800842 child_command_size - 1, L"%ls %ls",
Brian Curtin07165f72012-06-20 15:36:14 -0500843 executable, cmdline);
844 else
845 _snwprintf_s(child_command, child_command_size,
Steve Dower84bcfb32015-01-02 18:07:46 -0800846 child_command_size - 1, L"%ls %ls %ls",
Brian Curtin07165f72012-06-20 15:36:14 -0500847 executable, suffix, cmdline);
848 run_child(child_command);
849 free(child_command);
850 }
851}
852
Vinay Sajip22c039b2013-06-07 15:37:28 +0100853typedef struct {
854 wchar_t *shebang;
855 BOOL search;
856} SHEBANG;
857
858static SHEBANG builtin_virtual_paths [] = {
859 { L"/usr/bin/env python", TRUE },
860 { L"/usr/bin/python", FALSE },
861 { L"/usr/local/bin/python", FALSE },
862 { L"python", FALSE },
863 { NULL, FALSE },
Brian Curtin07165f72012-06-20 15:36:14 -0500864};
865
866/* For now, a static array of commands. */
867
868#define MAX_COMMANDS 100
869
870typedef struct {
871 wchar_t key[MAX_PATH];
872 wchar_t value[MSGSIZE];
873} COMMAND;
874
875static COMMAND commands[MAX_COMMANDS];
876static int num_commands = 0;
877
878#if defined(SKIP_PREFIX)
879
880static wchar_t * builtin_prefixes [] = {
881 /* These must be in an order that the longest matches should be found,
882 * i.e. if the prefix is "/usr/bin/env ", it should match that entry
883 * *before* matching "/usr/bin/".
884 */
885 L"/usr/bin/env ",
886 L"/usr/bin/",
887 L"/usr/local/bin/",
888 NULL
889};
890
891static wchar_t * skip_prefix(wchar_t * name)
892{
893 wchar_t ** pp = builtin_prefixes;
894 wchar_t * result = name;
895 wchar_t * p;
896 size_t n;
897
898 for (; p = *pp; pp++) {
899 n = wcslen(p);
900 if (_wcsnicmp(p, name, n) == 0) {
901 result += n; /* skip the prefix */
902 if (p[n - 1] == L' ') /* No empty strings in table, so n > 1 */
903 result = skip_whitespace(result);
904 break;
905 }
906 }
907 return result;
908}
909
910#endif
911
912#if defined(SEARCH_PATH)
913
914static COMMAND path_command;
915
916static COMMAND * find_on_path(wchar_t * name)
917{
918 wchar_t * pathext;
919 size_t varsize;
920 wchar_t * context = NULL;
921 wchar_t * extension;
922 COMMAND * result = NULL;
923 DWORD len;
924 errno_t rc;
925
926 wcscpy_s(path_command.key, MAX_PATH, name);
927 if (wcschr(name, L'.') != NULL) {
928 /* assume it has an extension. */
929 len = SearchPathW(NULL, name, NULL, MSGSIZE, path_command.value, NULL);
930 if (len) {
931 result = &path_command;
932 }
933 }
934 else {
935 /* No extension - search using registered extensions. */
936 rc = _wdupenv_s(&pathext, &varsize, L"PATHEXT");
937 if (rc == 0) {
938 extension = wcstok_s(pathext, L";", &context);
939 while (extension) {
940 len = SearchPathW(NULL, name, extension, MSGSIZE, path_command.value, NULL);
941 if (len) {
942 result = &path_command;
943 break;
944 }
945 extension = wcstok_s(NULL, L";", &context);
946 }
947 free(pathext);
948 }
949 }
950 return result;
951}
952
953#endif
954
955static COMMAND * find_command(wchar_t * name)
956{
957 COMMAND * result = NULL;
958 COMMAND * cp = commands;
959 int i;
960
961 for (i = 0; i < num_commands; i++, cp++) {
962 if (_wcsicmp(cp->key, name) == 0) {
963 result = cp;
964 break;
965 }
966 }
967#if defined(SEARCH_PATH)
968 if (result == NULL)
969 result = find_on_path(name);
970#endif
971 return result;
972}
973
974static void
975update_command(COMMAND * cp, wchar_t * name, wchar_t * cmdline)
976{
977 wcsncpy_s(cp->key, MAX_PATH, name, _TRUNCATE);
978 wcsncpy_s(cp->value, MSGSIZE, cmdline, _TRUNCATE);
979}
980
981static void
982add_command(wchar_t * name, wchar_t * cmdline)
983{
984 if (num_commands >= MAX_COMMANDS) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800985 debug(L"can't add %ls = '%ls': no room\n", name, cmdline);
Brian Curtin07165f72012-06-20 15:36:14 -0500986 }
987 else {
988 COMMAND * cp = &commands[num_commands++];
989
990 update_command(cp, name, cmdline);
991 }
992}
993
994static void
995read_config_file(wchar_t * config_path)
996{
997 wchar_t keynames[MSGSIZE];
998 wchar_t value[MSGSIZE];
999 DWORD read;
1000 wchar_t * key;
1001 COMMAND * cp;
1002 wchar_t * cmdp;
1003
1004 read = GetPrivateProfileStringW(L"commands", NULL, NULL, keynames, MSGSIZE,
1005 config_path);
1006 if (read == MSGSIZE - 1) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001007 debug(L"read_commands: %ls: not enough space for names\n", config_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001008 }
1009 key = keynames;
1010 while (*key) {
1011 read = GetPrivateProfileStringW(L"commands", key, NULL, value, MSGSIZE,
1012 config_path);
1013 if (read == MSGSIZE - 1) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001014 debug(L"read_commands: %ls: not enough space for %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -05001015 config_path, key);
1016 }
1017 cmdp = skip_whitespace(value);
1018 if (*cmdp) {
1019 cp = find_command(key);
1020 if (cp == NULL)
1021 add_command(key, value);
1022 else
1023 update_command(cp, key, value);
1024 }
1025 key += wcslen(key) + 1;
1026 }
1027}
1028
1029static void read_commands()
1030{
1031 if (launcher_ini_path[0])
1032 read_config_file(launcher_ini_path);
1033 if (appdata_ini_path[0])
1034 read_config_file(appdata_ini_path);
1035}
1036
1037static BOOL
1038parse_shebang(wchar_t * shebang_line, int nchars, wchar_t ** command,
Vinay Sajip22c039b2013-06-07 15:37:28 +01001039 wchar_t ** suffix, BOOL *search)
Brian Curtin07165f72012-06-20 15:36:14 -05001040{
1041 BOOL rc = FALSE;
Vinay Sajip22c039b2013-06-07 15:37:28 +01001042 SHEBANG * vpp;
Brian Curtin07165f72012-06-20 15:36:14 -05001043 size_t plen;
1044 wchar_t * p;
1045 wchar_t zapped;
1046 wchar_t * endp = shebang_line + nchars - 1;
1047 COMMAND * cp;
1048 wchar_t * skipped;
1049
1050 *command = NULL; /* failure return */
1051 *suffix = NULL;
Vinay Sajip22c039b2013-06-07 15:37:28 +01001052 *search = FALSE;
Brian Curtin07165f72012-06-20 15:36:14 -05001053
1054 if ((*shebang_line++ == L'#') && (*shebang_line++ == L'!')) {
1055 shebang_line = skip_whitespace(shebang_line);
1056 if (*shebang_line) {
1057 *command = shebang_line;
Vinay Sajip22c039b2013-06-07 15:37:28 +01001058 for (vpp = builtin_virtual_paths; vpp->shebang; ++vpp) {
1059 plen = wcslen(vpp->shebang);
1060 if (wcsncmp(shebang_line, vpp->shebang, plen) == 0) {
Brian Curtin07165f72012-06-20 15:36:14 -05001061 rc = TRUE;
Vinay Sajip22c039b2013-06-07 15:37:28 +01001062 *search = vpp->search;
Brian Curtin07165f72012-06-20 15:36:14 -05001063 /* We can do this because all builtin commands contain
1064 * "python".
1065 */
1066 *command = wcsstr(shebang_line, L"python");
1067 break;
1068 }
1069 }
Vinay Sajip22c039b2013-06-07 15:37:28 +01001070 if (vpp->shebang == NULL) {
Brian Curtin07165f72012-06-20 15:36:14 -05001071 /*
Vinay Sajip9c10d6b2013-11-15 20:58:13 +00001072 * Not found in builtins - look in customized commands.
Brian Curtin07165f72012-06-20 15:36:14 -05001073 *
1074 * We can't permanently modify the shebang line in case
Vinay Sajip9c10d6b2013-11-15 20:58:13 +00001075 * it's not a customized command, but we can temporarily
Brian Curtin07165f72012-06-20 15:36:14 -05001076 * stick a NUL after the command while searching for it,
1077 * then put back the char we zapped.
1078 */
1079#if defined(SKIP_PREFIX)
1080 skipped = skip_prefix(shebang_line);
1081#else
1082 skipped = shebang_line;
1083#endif
1084 p = wcspbrk(skipped, L" \t\r\n");
1085 if (p != NULL) {
1086 zapped = *p;
1087 *p = L'\0';
1088 }
1089 cp = find_command(skipped);
1090 if (p != NULL)
1091 *p = zapped;
1092 if (cp != NULL) {
1093 *command = cp->value;
1094 if (p != NULL)
1095 *suffix = skip_whitespace(p);
1096 }
1097 }
1098 /* remove trailing whitespace */
1099 while ((endp > shebang_line) && isspace(*endp))
1100 --endp;
1101 if (endp > shebang_line)
1102 endp[1] = L'\0';
1103 }
1104 }
1105 return rc;
1106}
1107
1108/* #define CP_UTF8 65001 defined in winnls.h */
1109#define CP_UTF16LE 1200
1110#define CP_UTF16BE 1201
1111#define CP_UTF32LE 12000
1112#define CP_UTF32BE 12001
1113
1114typedef struct {
1115 int length;
1116 char sequence[4];
1117 UINT code_page;
1118} BOM;
1119
1120/*
Vinay Sajipc985d082013-07-25 11:20:55 +01001121 * Strictly, we don't need to handle UTF-16 and UTF-32, since Python itself
Brian Curtin07165f72012-06-20 15:36:14 -05001122 * doesn't. Never mind, one day it might - there's no harm leaving it in.
1123 */
1124static BOM BOMs[] = {
1125 { 3, { 0xEF, 0xBB, 0xBF }, CP_UTF8 }, /* UTF-8 - keep first */
Serhiy Storchaka29e2aa62015-12-18 10:23:09 +02001126 /* Test UTF-32LE before UTF-16LE since UTF-16LE BOM is a prefix
1127 * of UTF-32LE BOM. */
Brian Curtin07165f72012-06-20 15:36:14 -05001128 { 4, { 0xFF, 0xFE, 0x00, 0x00 }, CP_UTF32LE }, /* UTF-32LE */
1129 { 4, { 0x00, 0x00, 0xFE, 0xFF }, CP_UTF32BE }, /* UTF-32BE */
Serhiy Storchaka29e2aa62015-12-18 10:23:09 +02001130 { 2, { 0xFF, 0xFE }, CP_UTF16LE }, /* UTF-16LE */
1131 { 2, { 0xFE, 0xFF }, CP_UTF16BE }, /* UTF-16BE */
Brian Curtin07165f72012-06-20 15:36:14 -05001132 { 0 } /* sentinel */
1133};
1134
1135static BOM *
1136find_BOM(char * buffer)
1137{
1138/*
1139 * Look for a BOM in the input and return a pointer to the
1140 * corresponding structure, or NULL if not found.
1141 */
1142 BOM * result = NULL;
1143 BOM *bom;
1144
1145 for (bom = BOMs; bom->length; bom++) {
1146 if (strncmp(bom->sequence, buffer, bom->length) == 0) {
1147 result = bom;
1148 break;
1149 }
1150 }
1151 return result;
1152}
1153
1154static char *
1155find_terminator(char * buffer, int len, BOM *bom)
1156{
1157 char * result = NULL;
1158 char * end = buffer + len;
1159 char * p;
1160 char c;
1161 int cp;
1162
1163 for (p = buffer; p < end; p++) {
1164 c = *p;
1165 if (c == '\r') {
1166 result = p;
1167 break;
1168 }
1169 if (c == '\n') {
1170 result = p;
1171 break;
1172 }
1173 }
1174 if (result != NULL) {
1175 cp = bom->code_page;
1176
1177 /* adjustments to include all bytes of the char */
1178 /* no adjustment needed for UTF-8 or big endian */
1179 if (cp == CP_UTF16LE)
1180 ++result;
1181 else if (cp == CP_UTF32LE)
1182 result += 3;
1183 ++result; /* point just past terminator */
1184 }
1185 return result;
1186}
1187
1188static BOOL
1189validate_version(wchar_t * p)
1190{
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +01001191 /*
Brendan Gerrity3876af42018-09-04 09:35:46 -07001192 Version information should start with the major version,
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +01001193 Optionally followed by a period and a minor version,
1194 Optionally followed by a minus and one of 32 or 64.
1195 Valid examples:
1196 2
1197 3
1198 2.7
1199 3.6
1200 2.7-32
1201 The intent is to add to the valid patterns:
1202 3.10
1203 3-32
1204 3.6-64
1205 3-64
1206 */
1207 BOOL result = (p != NULL); /* Default to False if null pointer. */
Brian Curtin07165f72012-06-20 15:36:14 -05001208
Brendan Gerrity3876af42018-09-04 09:35:46 -07001209 result = result && iswdigit(*p); /* Result = False if first string element is not a digit. */
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +01001210
1211 while (result && iswdigit(*p)) /* Require a major version */
1212 ++p; /* Skip all leading digit(s) */
1213 if (result && (*p == L'.')) /* Allow . for major minor separator.*/
1214 {
1215 result = iswdigit(*++p); /* Must be at least one digit */
1216 while (result && iswdigit(*++p)) ; /* Skip any more Digits */
1217 }
1218 if (result && (*p == L'-')) { /* Allow - for Bits Separator */
1219 switch(*++p){
1220 case L'3': /* 3 is OK */
1221 result = (*++p == L'2') && !*++p; /* only if followed by 2 and ended.*/
1222 break;
1223 case L'6': /* 6 is OK */
1224 result = (*++p == L'4') && !*++p; /* only if followed by 4 and ended.*/
1225 break;
1226 default:
Brian Curtin07165f72012-06-20 15:36:14 -05001227 result = FALSE;
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +01001228 break;
Brian Curtin07165f72012-06-20 15:36:14 -05001229 }
1230 }
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +01001231 result = result && !*p; /* Must have reached EOS */
Brian Curtin07165f72012-06-20 15:36:14 -05001232 return result;
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +01001233
Brian Curtin07165f72012-06-20 15:36:14 -05001234}
1235
1236typedef struct {
1237 unsigned short min;
1238 unsigned short max;
1239 wchar_t version[MAX_VERSION_SIZE];
1240} PYC_MAGIC;
1241
1242static PYC_MAGIC magic_values[] = {
Steve Dower7ae61af2016-05-16 09:34:20 -07001243 { 50823, 50823, L"2.0" },
1244 { 60202, 60202, L"2.1" },
1245 { 60717, 60717, L"2.2" },
1246 { 62011, 62021, L"2.3" },
1247 { 62041, 62061, L"2.4" },
1248 { 62071, 62131, L"2.5" },
1249 { 62151, 62161, L"2.6" },
1250 { 62171, 62211, L"2.7" },
1251 { 3000, 3131, L"3.0" },
1252 { 3141, 3151, L"3.1" },
1253 { 3160, 3180, L"3.2" },
1254 { 3190, 3230, L"3.3" },
1255 { 3250, 3310, L"3.4" },
Serhiy Storchaka3c317e72016-06-12 09:22:01 +03001256 { 3320, 3351, L"3.5" },
Nick Coghlan944368e2016-09-11 14:45:49 +10001257 { 3360, 3379, L"3.6" },
Yury Selivanovf2392132016-12-13 19:03:51 -05001258 { 3390, 3399, L"3.7" },
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001259 { 3400, 3419, L"3.8" },
Mark Shannon9af0e472020-01-14 10:12:45 +00001260 { 3420, 3429, L"3.9" },
Mark Shannonc6409152020-11-12 10:42:44 +00001261 { 3430, 3439, L"3.10" },
Brian Curtin07165f72012-06-20 15:36:14 -05001262 { 0 }
1263};
1264
1265static INSTALLED_PYTHON *
1266find_by_magic(unsigned short magic)
1267{
1268 INSTALLED_PYTHON * result = NULL;
1269 PYC_MAGIC * mp;
1270
1271 for (mp = magic_values; mp->min; mp++) {
1272 if ((magic >= mp->min) && (magic <= mp->max)) {
Paul Moore835416c2016-05-22 12:28:41 +01001273 result = locate_python(mp->version, FALSE);
Brian Curtin07165f72012-06-20 15:36:14 -05001274 if (result != NULL)
1275 break;
1276 }
1277 }
1278 return result;
1279}
1280
1281static void
1282maybe_handle_shebang(wchar_t ** argv, wchar_t * cmdline)
1283{
1284/*
1285 * Look for a shebang line in the first argument. If found
1286 * and we spawn a child process, this never returns. If it
1287 * does return then we process the args "normally".
1288 *
1289 * argv[0] might be a filename with a shebang.
1290 */
1291 FILE * fp;
1292 errno_t rc = _wfopen_s(&fp, *argv, L"rb");
Serhiy Storchakaf8ed0042015-12-18 10:19:30 +02001293 char buffer[BUFSIZE];
Brian Curtin07165f72012-06-20 15:36:14 -05001294 wchar_t shebang_line[BUFSIZE + 1];
1295 size_t read;
1296 char *p;
1297 char * start;
1298 char * shebang_alias = (char *) shebang_line;
1299 BOM* bom;
1300 int i, j, nchars = 0;
1301 int header_len;
1302 BOOL is_virt;
Vinay Sajip22c039b2013-06-07 15:37:28 +01001303 BOOL search;
Brian Curtin07165f72012-06-20 15:36:14 -05001304 wchar_t * command;
1305 wchar_t * suffix;
Vinay Sajip22c039b2013-06-07 15:37:28 +01001306 COMMAND *cmd = NULL;
Brian Curtin07165f72012-06-20 15:36:14 -05001307 INSTALLED_PYTHON * ip;
1308
1309 if (rc == 0) {
1310 read = fread(buffer, sizeof(char), BUFSIZE, fp);
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02001311 debug(L"maybe_handle_shebang: read %zd bytes\n", read);
Brian Curtin07165f72012-06-20 15:36:14 -05001312 fclose(fp);
1313
1314 if ((read >= 4) && (buffer[3] == '\n') && (buffer[2] == '\r')) {
Serhiy Storchakaf8ed0042015-12-18 10:19:30 +02001315 ip = find_by_magic((((unsigned char)buffer[1]) << 8 |
1316 (unsigned char)buffer[0]) & 0xFFFF);
Brian Curtin07165f72012-06-20 15:36:14 -05001317 if (ip != NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001318 debug(L"script file is compiled against Python %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -05001319 ip->version);
1320 invoke_child(ip->executable, NULL, cmdline);
1321 }
1322 }
1323 /* Look for BOM */
1324 bom = find_BOM(buffer);
1325 if (bom == NULL) {
1326 start = buffer;
1327 debug(L"maybe_handle_shebang: BOM not found, using UTF-8\n");
1328 bom = BOMs; /* points to UTF-8 entry - the default */
1329 }
1330 else {
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02001331 debug(L"maybe_handle_shebang: BOM found, code page %u\n",
Brian Curtin07165f72012-06-20 15:36:14 -05001332 bom->code_page);
1333 start = &buffer[bom->length];
1334 }
1335 p = find_terminator(start, BUFSIZE, bom);
1336 /*
1337 * If no CR or LF was found in the heading,
1338 * we assume it's not a shebang file.
1339 */
1340 if (p == NULL) {
1341 debug(L"maybe_handle_shebang: No line terminator found\n");
1342 }
1343 else {
1344 /*
1345 * Found line terminator - parse the shebang.
1346 *
1347 * Strictly, we don't need to handle UTF-16 anf UTF-32,
1348 * since Python itself doesn't.
1349 * Never mind, one day it might.
1350 */
1351 header_len = (int) (p - start);
1352 switch(bom->code_page) {
1353 case CP_UTF8:
1354 nchars = MultiByteToWideChar(bom->code_page,
1355 0,
1356 start, header_len, shebang_line,
1357 BUFSIZE);
1358 break;
1359 case CP_UTF16BE:
1360 if (header_len % 2 != 0) {
1361 debug(L"maybe_handle_shebang: UTF-16BE, but an odd number \
1362of bytes: %d\n", header_len);
1363 /* nchars = 0; Not needed - initialised to 0. */
1364 }
1365 else {
1366 for (i = header_len; i > 0; i -= 2) {
1367 shebang_alias[i - 1] = start[i - 2];
1368 shebang_alias[i - 2] = start[i - 1];
1369 }
1370 nchars = header_len / sizeof(wchar_t);
1371 }
1372 break;
1373 case CP_UTF16LE:
1374 if ((header_len % 2) != 0) {
1375 debug(L"UTF-16LE, but an odd number of bytes: %d\n",
1376 header_len);
1377 /* nchars = 0; Not needed - initialised to 0. */
1378 }
1379 else {
1380 /* no actual conversion needed. */
1381 memcpy(shebang_line, start, header_len);
1382 nchars = header_len / sizeof(wchar_t);
1383 }
1384 break;
1385 case CP_UTF32BE:
1386 if (header_len % 4 != 0) {
1387 debug(L"UTF-32BE, but not divisible by 4: %d\n",
1388 header_len);
1389 /* nchars = 0; Not needed - initialised to 0. */
1390 }
1391 else {
1392 for (i = header_len, j = header_len / 2; i > 0; i -= 4,
1393 j -= 2) {
1394 shebang_alias[j - 1] = start[i - 2];
1395 shebang_alias[j - 2] = start[i - 1];
1396 }
1397 nchars = header_len / sizeof(wchar_t);
1398 }
1399 break;
1400 case CP_UTF32LE:
1401 if (header_len % 4 != 0) {
1402 debug(L"UTF-32LE, but not divisible by 4: %d\n",
1403 header_len);
1404 /* nchars = 0; Not needed - initialised to 0. */
1405 }
1406 else {
1407 for (i = header_len, j = header_len / 2; i > 0; i -= 4,
1408 j -= 2) {
1409 shebang_alias[j - 1] = start[i - 3];
1410 shebang_alias[j - 2] = start[i - 4];
1411 }
1412 nchars = header_len / sizeof(wchar_t);
1413 }
1414 break;
1415 }
1416 if (nchars > 0) {
1417 shebang_line[--nchars] = L'\0';
1418 is_virt = parse_shebang(shebang_line, nchars, &command,
Vinay Sajip22c039b2013-06-07 15:37:28 +01001419 &suffix, &search);
Brian Curtin07165f72012-06-20 15:36:14 -05001420 if (command != NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001421 debug(L"parse_shebang: found command: %ls\n", command);
Brian Curtin07165f72012-06-20 15:36:14 -05001422 if (!is_virt) {
1423 invoke_child(command, suffix, cmdline);
1424 }
1425 else {
1426 suffix = wcschr(command, L' ');
1427 if (suffix != NULL) {
1428 *suffix++ = L'\0';
1429 suffix = skip_whitespace(suffix);
1430 }
1431 if (wcsncmp(command, L"python", 6))
1432 error(RC_BAD_VIRTUAL_PATH, L"Unknown virtual \
Steve Dower84bcfb32015-01-02 18:07:46 -08001433path '%ls'", command);
Brian Curtin07165f72012-06-20 15:36:14 -05001434 command += 6; /* skip past "python" */
Vinay Sajip22c039b2013-06-07 15:37:28 +01001435 if (search && ((*command == L'\0') || isspace(*command))) {
1436 /* Command is eligible for path search, and there
1437 * is no version specification.
1438 */
1439 debug(L"searching PATH for python executable\n");
Vinay Sajipa5892ab2015-12-26 13:10:51 +00001440 cmd = find_on_path(PYTHON_EXECUTABLE);
Steve Dower84bcfb32015-01-02 18:07:46 -08001441 debug(L"Python on path: %ls\n", cmd ? cmd->value : L"<not found>");
Vinay Sajip22c039b2013-06-07 15:37:28 +01001442 if (cmd) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001443 debug(L"located python on PATH: %ls\n", cmd->value);
Vinay Sajip22c039b2013-06-07 15:37:28 +01001444 invoke_child(cmd->value, suffix, cmdline);
1445 /* Exit here, as we have found the command */
1446 return;
1447 }
1448 /* FALL THROUGH: No python found on PATH, so fall
1449 * back to locating the correct installed python.
1450 */
1451 }
Brian Curtin07165f72012-06-20 15:36:14 -05001452 if (*command && !validate_version(command))
1453 error(RC_BAD_VIRTUAL_PATH, L"Invalid version \
Steve Dower84bcfb32015-01-02 18:07:46 -08001454specification: '%ls'.\nIn the first line of the script, 'python' needs to be \
Brian Curtin07165f72012-06-20 15:36:14 -05001455followed by a valid version specifier.\nPlease check the documentation.",
1456 command);
1457 /* TODO could call validate_version(command) */
Paul Moore835416c2016-05-22 12:28:41 +01001458 ip = locate_python(command, TRUE);
Brian Curtin07165f72012-06-20 15:36:14 -05001459 if (ip == NULL) {
1460 error(RC_NO_PYTHON, L"Requested Python version \
Steve Dower84bcfb32015-01-02 18:07:46 -08001461(%ls) is not installed", command);
Brian Curtin07165f72012-06-20 15:36:14 -05001462 }
1463 else {
1464 invoke_child(ip->executable, suffix, cmdline);
1465 }
1466 }
1467 }
1468 }
1469 }
1470 }
1471}
1472
1473static wchar_t *
1474skip_me(wchar_t * cmdline)
1475{
1476 BOOL quoted;
1477 wchar_t c;
1478 wchar_t * result = cmdline;
1479
1480 quoted = cmdline[0] == L'\"';
1481 if (!quoted)
1482 c = L' ';
1483 else {
1484 c = L'\"';
1485 ++result;
1486 }
1487 result = wcschr(result, c);
1488 if (result == NULL) /* when, for example, just exe name on command line */
1489 result = L"";
1490 else {
1491 ++result; /* skip past space or closing quote */
1492 result = skip_whitespace(result);
1493 }
1494 return result;
1495}
1496
1497static DWORD version_high = 0;
1498static DWORD version_low = 0;
1499
1500static void
1501get_version_info(wchar_t * version_text, size_t size)
1502{
1503 WORD maj, min, rel, bld;
1504
1505 if (!version_high && !version_low)
1506 wcsncpy_s(version_text, size, L"0.1", _TRUNCATE); /* fallback */
1507 else {
1508 maj = HIWORD(version_high);
1509 min = LOWORD(version_high);
1510 rel = HIWORD(version_low);
1511 bld = LOWORD(version_low);
1512 _snwprintf_s(version_text, size, _TRUNCATE, L"%d.%d.%d.%d", maj,
1513 min, rel, bld);
1514 }
1515}
1516
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001517static void
1518show_help_text(wchar_t ** argv)
1519{
1520 wchar_t version_text [MAX_PATH];
1521#if defined(_M_X64)
1522 BOOL canDo64bit = TRUE;
1523#else
1524 /* If we are a 32bit process on a 64bit Windows, first hit the 64bit keys. */
1525 BOOL canDo64bit = FALSE;
1526 IsWow64Process(GetCurrentProcess(), &canDo64bit);
1527#endif
1528
1529 get_version_info(version_text, MAX_PATH);
1530 fwprintf(stdout, L"\
1531Python Launcher for Windows Version %ls\n\n", version_text);
1532 fwprintf(stdout, L"\
1533usage:\n\
Steve (Gadget) Barnesb3e67832020-06-13 00:19:34 +01001534%ls [launcher-args] [python-args] [script [script-args]]\n\n", argv[0]);
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001535 fputws(L"\
1536Launcher arguments:\n\n\
1537-2 : Launch the latest Python 2.x version\n\
1538-3 : Launch the latest Python 3.x version\n\
1539-X.Y : Launch the specified Python version\n", stdout);
1540 if (canDo64bit) {
1541 fputws(L"\
1542 The above all default to 64 bit if a matching 64 bit python is present.\n\
1543-X.Y-32: Launch the specified 32bit Python version\n\
1544-X-32 : Launch the latest 32bit Python X version\n\
1545-X.Y-64: Launch the specified 64bit Python version\n\
1546-X-64 : Launch the latest 64bit Python X version", stdout);
1547 }
1548 fputws(L"\n-0 --list : List the available pythons", stdout);
1549 fputws(L"\n-0p --list-paths : List with paths", stdout);
Steve (Gadget) Barnesb3e67832020-06-13 00:19:34 +01001550 fputws(L"\n\n If no script is specified the specified interpreter is opened.", stdout);
1551 fputws(L"\nIf an exact version is not given, using the latest version can be overridden by", stdout);
1552 fputws(L"\nany of the following, (in priority order):", stdout);
1553 fputws(L"\n An active virtual environment", stdout);
1554 fputws(L"\n A shebang line in the script (if present)", stdout);
1555 fputws(L"\n With -2 or -3 flag a matching PY_PYTHON2 or PY_PYTHON3 Enviroment variable", stdout);
1556 fputws(L"\n A PY_PYTHON Enviroment variable", stdout);
1557 fputws(L"\n From [defaults] in py.ini in your %LOCALAPPDATA%\\py.ini", stdout);
1558 fputws(L"\n From [defaults] in py.ini beside py.exe (use `where py` to locate)", stdout);
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001559 fputws(L"\n\nThe following help text is from Python:\n\n", stdout);
1560 fflush(stdout);
1561}
1562
1563static BOOL
1564show_python_list(wchar_t ** argv)
1565{
1566 /*
1567 * Display options -0
1568 */
1569 INSTALLED_PYTHON * result = NULL;
1570 INSTALLED_PYTHON * ip = installed_pythons; /* List of installed pythons */
1571 INSTALLED_PYTHON * defpy = locate_python(L"", FALSE);
1572 size_t i = 0;
1573 wchar_t *p = argv[1];
Steve Dowered93a882019-09-12 18:16:50 +01001574 wchar_t *ver_fmt = L"-%ls-%d";
1575 wchar_t *fmt = L"\n %ls";
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001576 wchar_t *defind = L" *"; /* Default indicator */
1577
1578 /*
1579 * Output informational messages to stderr to keep output
1580 * clean for use in pipes, etc.
1581 */
1582 fwprintf(stderr,
1583 L"Installed Pythons found by %s Launcher for Windows", argv[0]);
Steve Dowered93a882019-09-12 18:16:50 +01001584 if (!_wcsicmp(p, L"-0p") || !_wcsicmp(p, L"--list-paths"))
1585 fmt = L"\n %-15ls%ls"; /* include path */
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001586
1587 if (num_installed_pythons == 0) /* We have somehow got here without searching for pythons */
1588 locate_all_pythons(); /* Find them, Populates installed_pythons */
1589
1590 if (num_installed_pythons == 0) /* No pythons found */
1591 fwprintf(stderr, L"\nNo Installed Pythons Found!");
1592 else
1593 {
1594 for (i = 0; i < num_installed_pythons; i++, ip++) {
Steve Dowered93a882019-09-12 18:16:50 +01001595 wchar_t version[BUFSIZ];
1596 if (wcscmp(ip->version, L"venv") == 0) {
1597 wcscpy_s(version, BUFSIZ, L"(venv)");
1598 }
1599 else {
1600 swprintf_s(version, BUFSIZ, ver_fmt, ip->version, ip->bits);
1601 }
1602
1603 if (ip->exe_display[0]) {
1604 fwprintf(stdout, fmt, version, ip->exe_display);
1605 }
1606 else {
1607 fwprintf(stdout, fmt, version, ip->executable);
1608 }
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001609 /* If there is a default indicate it */
Steve Dowered93a882019-09-12 18:16:50 +01001610 if (defpy == ip)
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001611 fwprintf(stderr, defind);
1612 }
1613 }
1614
1615 if ((defpy == NULL) && (num_installed_pythons > 0))
1616 /* We have pythons but none is the default */
1617 fwprintf(stderr, L"\n\nCan't find a Default Python.\n\n");
1618 else
1619 fwprintf(stderr, L"\n\n"); /* End with a blank line */
Brendan Gerrityc8fe9cc2018-11-20 13:28:27 -08001620 return FALSE; /* If this has been called we cannot continue */
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001621}
1622
Steve Dower1c3de542018-12-10 08:11:21 -08001623#if defined(VENV_REDIRECT)
1624
1625static int
1626find_home_value(const char *buffer, const char **start, DWORD *length)
1627{
1628 for (const char *s = strstr(buffer, "home"); s; s = strstr(s + 1, "\nhome")) {
1629 if (*s == '\n') {
1630 ++s;
1631 }
1632 for (int i = 4; i > 0 && *s; --i, ++s);
1633
1634 while (*s && iswspace(*s)) {
1635 ++s;
1636 }
1637 if (*s != L'=') {
1638 continue;
1639 }
1640
1641 do {
1642 ++s;
1643 } while (*s && iswspace(*s));
1644
1645 *start = s;
1646 char *nl = strchr(s, '\n');
1647 if (nl) {
1648 *length = (DWORD)((ptrdiff_t)nl - (ptrdiff_t)s);
1649 } else {
1650 *length = (DWORD)strlen(s);
1651 }
1652 return 1;
1653 }
1654 return 0;
1655}
1656#endif
1657
1658static wchar_t *
1659wcsdup_pad(const wchar_t *s, int padding, int *newlen)
1660{
1661 size_t len = wcslen(s);
1662 len += 1 + padding;
1663 wchar_t *r = (wchar_t *)malloc(len * sizeof(wchar_t));
1664 if (!r) {
1665 return NULL;
1666 }
1667 if (wcscpy_s(r, len, s)) {
1668 free(r);
1669 return NULL;
1670 }
1671 *newlen = len < MAXINT ? (int)len : MAXINT;
1672 return r;
1673}
1674
1675static wchar_t *
1676get_process_name()
1677{
1678 DWORD bufferLen = MAX_PATH;
1679 DWORD len = bufferLen;
1680 wchar_t *r = NULL;
1681
1682 while (!r) {
1683 r = (wchar_t *)malloc(bufferLen * sizeof(wchar_t));
1684 if (!r) {
1685 error(RC_NO_MEMORY, L"out of memory");
1686 return NULL;
1687 }
1688 len = GetModuleFileNameW(NULL, r, bufferLen);
1689 if (len == 0) {
1690 free(r);
1691 error(0, L"Failed to get module name");
1692 return NULL;
1693 } else if (len == bufferLen &&
1694 GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
1695 free(r);
1696 r = NULL;
1697 bufferLen *= 2;
1698 }
1699 }
1700
1701 return r;
1702}
1703
Brian Curtin07165f72012-06-20 15:36:14 -05001704static int
1705process(int argc, wchar_t ** argv)
1706{
1707 wchar_t * wp;
1708 wchar_t * command;
Steve Dower76998fe2015-02-26 14:25:33 -08001709 wchar_t * executable;
Brian Curtin07165f72012-06-20 15:36:14 -05001710 wchar_t * p;
Steve Dower1c3de542018-12-10 08:11:21 -08001711 wchar_t * argv0;
Brian Curtin07165f72012-06-20 15:36:14 -05001712 int rc = 0;
Brian Curtin07165f72012-06-20 15:36:14 -05001713 INSTALLED_PYTHON * ip;
1714 BOOL valid;
1715 DWORD size, attrs;
Brian Curtin07165f72012-06-20 15:36:14 -05001716 wchar_t message[MSGSIZE];
Brian Curtin07165f72012-06-20 15:36:14 -05001717 void * version_data;
1718 VS_FIXEDFILEINFO * file_info;
1719 UINT block_size;
Steve Dower1c3de542018-12-10 08:11:21 -08001720#if defined(VENV_REDIRECT)
1721 wchar_t * venv_cfg_path;
Vinay Sajipc985d082013-07-25 11:20:55 +01001722 int newlen;
Steve Dower1c3de542018-12-10 08:11:21 -08001723#elif defined(SCRIPT_WRAPPER)
Vinay Sajipc985d082013-07-25 11:20:55 +01001724 wchar_t * newcommand;
1725 wchar_t * av[2];
Steve Dower1c3de542018-12-10 08:11:21 -08001726 int newlen;
1727 HRESULT hr;
1728 int index;
1729#else
1730 HRESULT hr;
1731 int index;
Vinay Sajipc985d082013-07-25 11:20:55 +01001732#endif
Brian Curtin07165f72012-06-20 15:36:14 -05001733
Vinay Sajipaab9f462015-12-26 12:35:47 +00001734 setvbuf(stderr, (char *)NULL, _IONBF, 0);
Brian Curtin07165f72012-06-20 15:36:14 -05001735 wp = get_env(L"PYLAUNCH_DEBUG");
1736 if ((wp != NULL) && (*wp != L'\0'))
1737 log_fp = stderr;
1738
1739#if defined(_M_X64)
1740 debug(L"launcher build: 64bit\n");
1741#else
1742 debug(L"launcher build: 32bit\n");
1743#endif
1744#if defined(_WINDOWS)
1745 debug(L"launcher executable: Windows\n");
1746#else
1747 debug(L"launcher executable: Console\n");
1748#endif
Steve Dower1c3de542018-12-10 08:11:21 -08001749#if !defined(VENV_REDIRECT)
Brian Curtin07165f72012-06-20 15:36:14 -05001750 /* Get the local appdata folder (non-roaming) */
1751 hr = SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA,
1752 NULL, 0, appdata_ini_path);
1753 if (hr != S_OK) {
1754 debug(L"SHGetFolderPath failed: %X\n", hr);
1755 appdata_ini_path[0] = L'\0';
1756 }
1757 else {
Steve Dower1c3de542018-12-10 08:11:21 -08001758 wcsncat_s(appdata_ini_path, MAX_PATH, L"\\py.ini", _TRUNCATE);
Brian Curtin07165f72012-06-20 15:36:14 -05001759 attrs = GetFileAttributesW(appdata_ini_path);
1760 if (attrs == INVALID_FILE_ATTRIBUTES) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001761 debug(L"File '%ls' non-existent\n", appdata_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001762 appdata_ini_path[0] = L'\0';
1763 } else {
Steve Dower84bcfb32015-01-02 18:07:46 -08001764 debug(L"Using local configuration file '%ls'\n", appdata_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001765 }
1766 }
Steve Dower1c3de542018-12-10 08:11:21 -08001767#endif
1768 argv0 = get_process_name();
1769 size = GetFileVersionInfoSizeW(argv0, &size);
Brian Curtin07165f72012-06-20 15:36:14 -05001770 if (size == 0) {
1771 winerror(GetLastError(), message, MSGSIZE);
Steve Dower84bcfb32015-01-02 18:07:46 -08001772 debug(L"GetFileVersionInfoSize failed: %ls\n", message);
Brian Curtin07165f72012-06-20 15:36:14 -05001773 }
1774 else {
1775 version_data = malloc(size);
1776 if (version_data) {
Steve Dower1c3de542018-12-10 08:11:21 -08001777 valid = GetFileVersionInfoW(argv0, 0, size,
Brian Curtin07165f72012-06-20 15:36:14 -05001778 version_data);
1779 if (!valid)
1780 debug(L"GetFileVersionInfo failed: %X\n", GetLastError());
1781 else {
Vinay Sajip404229b2013-01-29 22:52:57 +00001782 valid = VerQueryValueW(version_data, L"\\",
1783 (LPVOID *) &file_info, &block_size);
Brian Curtin07165f72012-06-20 15:36:14 -05001784 if (!valid)
1785 debug(L"VerQueryValue failed: %X\n", GetLastError());
1786 else {
1787 version_high = file_info->dwFileVersionMS;
1788 version_low = file_info->dwFileVersionLS;
1789 }
1790 }
1791 free(version_data);
1792 }
1793 }
Steve Dower1c3de542018-12-10 08:11:21 -08001794
1795#if defined(VENV_REDIRECT)
1796 /* Allocate some extra space for new filenames */
1797 venv_cfg_path = wcsdup_pad(argv0, 32, &newlen);
1798 if (!venv_cfg_path) {
1799 error(RC_NO_MEMORY, L"Failed to copy module name");
1800 }
1801 p = wcsrchr(venv_cfg_path, L'\\');
1802
1803 if (p == NULL) {
1804 error(RC_NO_VENV_CFG, L"No pyvenv.cfg file");
1805 }
1806 p[0] = L'\0';
1807 wcscat_s(venv_cfg_path, newlen, L"\\pyvenv.cfg");
1808 attrs = GetFileAttributesW(venv_cfg_path);
1809 if (attrs == INVALID_FILE_ATTRIBUTES) {
1810 debug(L"File '%ls' non-existent\n", venv_cfg_path);
1811 p[0] = '\0';
1812 p = wcsrchr(venv_cfg_path, L'\\');
1813 if (p != NULL) {
1814 p[0] = '\0';
1815 wcscat_s(venv_cfg_path, newlen, L"\\pyvenv.cfg");
1816 attrs = GetFileAttributesW(venv_cfg_path);
1817 if (attrs == INVALID_FILE_ATTRIBUTES) {
1818 debug(L"File '%ls' non-existent\n", venv_cfg_path);
1819 error(RC_NO_VENV_CFG, L"No pyvenv.cfg file");
1820 }
1821 }
1822 }
1823 debug(L"Using venv configuration file '%ls'\n", venv_cfg_path);
1824#else
1825 /* Allocate some extra space for new filenames */
1826 if (wcscpy_s(launcher_ini_path, MAX_PATH, argv0)) {
1827 error(RC_NO_MEMORY, L"Failed to copy module name");
1828 }
Brian Curtin07165f72012-06-20 15:36:14 -05001829 p = wcsrchr(launcher_ini_path, L'\\');
Steve Dower1c3de542018-12-10 08:11:21 -08001830
Brian Curtin07165f72012-06-20 15:36:14 -05001831 if (p == NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001832 debug(L"GetModuleFileNameW returned value has no backslash: %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -05001833 launcher_ini_path);
1834 launcher_ini_path[0] = L'\0';
1835 }
1836 else {
Steve Dower1c3de542018-12-10 08:11:21 -08001837 p[0] = L'\0';
1838 wcscat_s(launcher_ini_path, MAX_PATH, L"\\py.ini");
Brian Curtin07165f72012-06-20 15:36:14 -05001839 attrs = GetFileAttributesW(launcher_ini_path);
1840 if (attrs == INVALID_FILE_ATTRIBUTES) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001841 debug(L"File '%ls' non-existent\n", launcher_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001842 launcher_ini_path[0] = L'\0';
1843 } else {
Steve Dower84bcfb32015-01-02 18:07:46 -08001844 debug(L"Using global configuration file '%ls'\n", launcher_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001845 }
1846 }
Steve Dower1c3de542018-12-10 08:11:21 -08001847#endif
Brian Curtin07165f72012-06-20 15:36:14 -05001848
1849 command = skip_me(GetCommandLineW());
Steve Dower84bcfb32015-01-02 18:07:46 -08001850 debug(L"Called with command line: %ls\n", command);
Vinay Sajipc985d082013-07-25 11:20:55 +01001851
Steve Doweradad9e62019-01-25 14:59:58 -08001852#if !defined(VENV_REDIRECT)
1853 /* bpo-35811: The __PYVENV_LAUNCHER__ variable is used to
Mark Shannon9af0e472020-01-14 10:12:45 +00001854 * override sys.executable and locate the original prefix path.
Steve Doweradad9e62019-01-25 14:59:58 -08001855 * However, if it is silently inherited by a non-venv Python
1856 * process, that process will believe it is running in the venv
1857 * still. This is the only place where *we* can clear it (that is,
1858 * when py.exe is being used to launch Python), so we do.
1859 */
1860 SetEnvironmentVariableW(L"__PYVENV_LAUNCHER__", NULL);
1861#endif
1862
Vinay Sajipc985d082013-07-25 11:20:55 +01001863#if defined(SCRIPT_WRAPPER)
1864 /* The launcher is being used in "script wrapper" mode.
1865 * There should therefore be a Python script named <exename>-script.py in
1866 * the same directory as the launcher executable.
1867 * Put the script name into argv as the first (script name) argument.
1868 */
1869
1870 /* Get the wrapped script name - if the script is not present, this will
1871 * terminate the program with an error.
1872 */
1873 locate_wrapped_script();
1874
1875 /* Add the wrapped script to the start of command */
1876 newlen = wcslen(wrapped_script_path) + wcslen(command) + 2; /* ' ' + NUL */
1877 newcommand = malloc(sizeof(wchar_t) * newlen);
1878 if (!newcommand) {
1879 error(RC_NO_MEMORY, L"Could not allocate new command line");
1880 }
1881 else {
1882 wcscpy_s(newcommand, newlen, wrapped_script_path);
1883 wcscat_s(newcommand, newlen, L" ");
1884 wcscat_s(newcommand, newlen, command);
Steve Dower84bcfb32015-01-02 18:07:46 -08001885 debug(L"Running wrapped script with command line '%ls'\n", newcommand);
Vinay Sajipc985d082013-07-25 11:20:55 +01001886 read_commands();
1887 av[0] = wrapped_script_path;
1888 av[1] = NULL;
1889 maybe_handle_shebang(av, newcommand);
1890 /* Returns if no shebang line - pass to default processing */
1891 command = newcommand;
1892 valid = FALSE;
1893 }
Steve Dower1c3de542018-12-10 08:11:21 -08001894#elif defined(VENV_REDIRECT)
1895 {
1896 FILE *f;
1897 char buffer[4096]; /* 4KB should be enough for anybody */
1898 char *start;
1899 DWORD len, cch, cch_actual;
1900 size_t cb;
1901 if (_wfopen_s(&f, venv_cfg_path, L"r")) {
1902 error(RC_BAD_VENV_CFG, L"Cannot read '%ls'", venv_cfg_path);
1903 }
1904 cb = fread_s(buffer, sizeof(buffer), sizeof(buffer[0]),
1905 sizeof(buffer) / sizeof(buffer[0]), f);
1906 fclose(f);
1907
1908 if (!find_home_value(buffer, &start, &len)) {
1909 error(RC_BAD_VENV_CFG, L"Cannot find home in '%ls'",
1910 venv_cfg_path);
1911 }
1912
1913 cch = MultiByteToWideChar(CP_UTF8, 0, start, len, NULL, 0);
1914 if (!cch) {
1915 error(0, L"Cannot determine memory for home path");
1916 }
1917 cch += (DWORD)wcslen(PYTHON_EXECUTABLE) + 1 + 1; /* include sep and null */
1918 executable = (wchar_t *)malloc(cch * sizeof(wchar_t));
1919 if (executable == NULL) {
1920 error(RC_NO_MEMORY, L"A memory allocation failed");
1921 }
1922 cch_actual = MultiByteToWideChar(CP_UTF8, 0, start, len, executable, cch);
1923 if (!cch_actual) {
1924 error(RC_BAD_VENV_CFG, L"Cannot decode home path in '%ls'",
1925 venv_cfg_path);
1926 }
1927 if (executable[cch_actual - 1] != L'\\') {
1928 executable[cch_actual++] = L'\\';
1929 executable[cch_actual] = L'\0';
1930 }
1931 if (wcscat_s(executable, cch, PYTHON_EXECUTABLE)) {
1932 error(RC_BAD_VENV_CFG, L"Cannot create executable path from '%ls'",
1933 venv_cfg_path);
1934 }
1935 if (GetFileAttributesW(executable) == INVALID_FILE_ATTRIBUTES) {
1936 error(RC_NO_PYTHON, L"No Python at '%ls'", executable);
1937 }
1938 if (!SetEnvironmentVariableW(L"__PYVENV_LAUNCHER__", argv0)) {
1939 error(0, L"Failed to set launcher environment");
1940 }
1941 valid = 1;
1942 }
Vinay Sajipc985d082013-07-25 11:20:55 +01001943#else
Brian Curtin07165f72012-06-20 15:36:14 -05001944 if (argc <= 1) {
1945 valid = FALSE;
1946 p = NULL;
1947 }
1948 else {
1949 p = argv[1];
Brendan Gerrityc8fe9cc2018-11-20 13:28:27 -08001950 if ((argc == 2) && // list version args
1951 (!wcsncmp(p, L"-0", wcslen(L"-0")) ||
Brendan Gerrityaada63b2018-08-31 08:15:42 -07001952 !wcsncmp(p, L"--list", wcslen(L"--list"))))
1953 {
Brendan Gerrityc8fe9cc2018-11-20 13:28:27 -08001954 show_python_list(argv);
1955 return rc;
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001956 }
1957 valid = valid && (*p == L'-') && validate_version(&p[1]);
Brian Curtin07165f72012-06-20 15:36:14 -05001958 if (valid) {
Paul Moore835416c2016-05-22 12:28:41 +01001959 ip = locate_python(&p[1], FALSE);
Brian Curtin07165f72012-06-20 15:36:14 -05001960 if (ip == NULL)
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001961 {
1962 fwprintf(stdout, \
1963 L"Python %ls not found!\n", &p[1]);
1964 valid = show_python_list(argv);
Steve Dower84bcfb32015-01-02 18:07:46 -08001965 error(RC_NO_PYTHON, L"Requested Python version (%ls) not \
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001966installed, use -0 for available pythons", &p[1]);
1967 }
Steve Dower76998fe2015-02-26 14:25:33 -08001968 executable = ip->executable;
Brian Curtin07165f72012-06-20 15:36:14 -05001969 command += wcslen(p);
1970 command = skip_whitespace(command);
1971 }
Vinay Sajip2ae8c632013-01-29 22:29:25 +00001972 else {
1973 for (index = 1; index < argc; ++index) {
1974 if (*argv[index] != L'-')
1975 break;
1976 }
1977 if (index < argc) {
1978 read_commands();
1979 maybe_handle_shebang(&argv[index], command);
1980 }
1981 }
Brian Curtin07165f72012-06-20 15:36:14 -05001982 }
Vinay Sajipc985d082013-07-25 11:20:55 +01001983#endif
1984
Brian Curtin07165f72012-06-20 15:36:14 -05001985 if (!valid) {
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001986 if ((argc == 2) && (!_wcsicmp(p, L"-h") || !_wcsicmp(p, L"--help")))
1987 show_help_text(argv);
Brendan Gerrityaada63b2018-08-31 08:15:42 -07001988 if ((argc == 2) &&
1989 (!_wcsicmp(p, L"-0") || !_wcsicmp(p, L"--list") ||
1990 !_wcsicmp(p, L"-0p") || !_wcsicmp(p, L"--list-paths")))
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001991 {
Brendan Gerrityaada63b2018-08-31 08:15:42 -07001992 executable = NULL; /* Info call only */
1993 }
1994 else {
Steve Dowered93a882019-09-12 18:16:50 +01001995 /* look for the default Python */
1996 ip = locate_python(L"", FALSE);
1997 if (ip == NULL)
1998 error(RC_NO_PYTHON, L"Can't find a default Python.");
1999 executable = ip->executable;
Brian Curtin07165f72012-06-20 15:36:14 -05002000 }
2001 }
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01002002 if (executable != NULL)
2003 invoke_child(executable, NULL, command);
2004 else
2005 rc = RC_NO_PYTHON;
Brian Curtin07165f72012-06-20 15:36:14 -05002006 return rc;
2007}
2008
2009#if defined(_WINDOWS)
2010
2011int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
2012 LPWSTR lpstrCmd, int nShow)
2013{
2014 return process(__argc, __wargv);
2015}
2016
2017#else
2018
2019int cdecl wmain(int argc, wchar_t ** argv)
2020{
2021 return process(argc, argv);
2022}
2023
Vinay Sajip2ae8c632013-01-29 22:29:25 +00002024#endif