blob: fd5ad0ab1a1d96d089a39d709deb4a8f733b32d3 [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 */
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
435static void
Steve Dowered93a882019-09-12 18:16:50 +0100436locate_pythons_for_key(HKEY root, REGSAM flags)
437{
438 _locate_pythons_for_key(root, CORE_PATH, flags, 0, FALSE);
439}
440
441static void
442locate_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
458static void
459locate_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
487static void
Brian Curtin07165f72012-06-20 15:36:14 -0500488locate_all_pythons()
489{
Steve Dowered93a882019-09-12 18:16:50 +0100490 /* venv Python is highest priority */
491 locate_venv_python();
Brian Curtin07165f72012-06-20 15:36:14 -0500492#if defined(_M_X64)
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100493 /* If we are a 64bit process, first hit the 32bit keys. */
Brian Curtin07165f72012-06-20 15:36:14 -0500494 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
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100498 /* If we are a 32bit process on a 64bit Windows, first hit the 64bit keys.*/
Brian Curtin07165f72012-06-20 15:36:14 -0500499 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 }
Serhiy Storchaka009b8112015-03-18 21:53:15 +0200505#endif
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100506 /* now hit the "native" key for this process bittedness. */
Brian Curtin07165f72012-06-20 15:36:14 -0500507 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);
Steve Dowered93a882019-09-12 18:16:50 +0100510 /* Store-installed Python is lowest priority */
511 locate_store_pythons();
Brian Curtin07165f72012-06-20 15:36:14 -0500512 qsort(installed_pythons, num_installed_pythons, sizeof(INSTALLED_PYTHON),
513 compare_pythons);
514}
515
516static INSTALLED_PYTHON *
517find_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
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100525 if (wcsstr(wanted_ver, L"-32")) {
Brian Curtin07165f72012-06-20 15:36:14 -0500526 bits = 32;
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100527 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 }
Brian Curtin07165f72012-06-20 15:36:14 -0500533 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
548static wchar_t appdata_ini_path[MAX_PATH];
549static 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 */
555static wchar_t *
556get_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. */
Steve Dower84bcfb32015-01-02 18:07:46 -0800569 _snwprintf_s(configured_value, MSGSIZE, _TRUNCATE, L"py_%ls", key);
Brian Curtin07165f72012-06-20 15:36:14 -0500570 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) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800592 debug(L"found configured value '%ls=%ls' in %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500593 key, result, found_in ? found_in : L"(unknown)");
594 } else {
Steve Dower84bcfb32015-01-02 18:07:46 -0800595 debug(L"found no configured value for '%ls'\n", key);
Brian Curtin07165f72012-06-20 15:36:14 -0500596 }
597 return result;
598}
599
600static INSTALLED_PYTHON *
Paul Moore835416c2016-05-22 12:28:41 +0100601locate_python(wchar_t * wanted_ver, BOOL from_shebang)
Brian Curtin07165f72012-06-20 15:36:14 -0500602{
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);
Steve Dower84bcfb32015-01-02 18:07:46 -0800621 debug(L"search for Python version '%ls' found ", wanted_ver);
Brian Curtin07165f72012-06-20 15:36:14 -0500622 if (result) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800623 debug(L"'%ls'\n", result->executable);
Brian Curtin07165f72012-06-20 15:36:14 -0500624 } else {
625 debug(L"no interpreter\n");
626 }
627 }
628 else {
629 *last_char = L'\0'; /* look for an overall default */
Steve Dowered93a882019-09-12 18:16:50 +0100630 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 }
Paul Moore835416c2016-05-22 12:28:41 +0100636 /* 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 */
Brian Curtin07165f72012-06-20 15:36:14 -0500643 if (result == NULL)
Paul Moore835416c2016-05-22 12:28:41 +0100644 result = find_python_by_version(from_shebang ? L"2" : L"3");
Brian Curtin07165f72012-06-20 15:36:14 -0500645 if (result == NULL)
Paul Moore835416c2016-05-22 12:28:41 +0100646 result = find_python_by_version(from_shebang ? L"3" : L"2");
Brian Curtin07165f72012-06-20 15:36:14 -0500647 debug(L"search for default Python found ");
648 if (result) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800649 debug(L"version %ls at '%ls'\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500650 result->version, result->executable);
651 } else {
652 debug(L"no interpreter\n");
653 }
654 }
655 return result;
656}
657
Vinay Sajipc985d082013-07-25 11:20:55 +0100658#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
669static 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 */
677static void
678locate_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) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800687 debug(L"GetModuleFileNameW returned value has no extension: %ls\n",
Vinay Sajipc985d082013-07-25 11:20:55 +0100688 wrapped_script_path);
Steve Dower84bcfb32015-01-02 18:07:46 -0800689 error(RC_NO_SCRIPT, L"Wrapper name '%ls' is not valid.", wrapped_script_path);
Vinay Sajipc985d082013-07-25 11:20:55 +0100690 }
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) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800695 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);
Vinay Sajipc985d082013-07-25 11:20:55 +0100697 }
698
Steve Dower84bcfb32015-01-02 18:07:46 -0800699 debug(L"Using wrapped script file '%ls'\n", wrapped_script_path);
Vinay Sajipc985d082013-07-25 11:20:55 +0100700}
701#endif
702
Brian Curtin07165f72012-06-20 15:36:14 -0500703/*
704 * Process creation code
705 */
706
707static BOOL
708safe_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
730static BOOL WINAPI
731ctrl_c_handler(DWORD code)
732{
733 return TRUE; /* We just ignore all control events. */
734}
735
736static void
737run_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
Vinay Sajip66fef9f2013-02-26 16:29:06 +0000746#if defined(_WINDOWS)
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100747 /*
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 */
Vinay Sajip66fef9f2013-02-26 16:29:06 +0000757 MSG msg;
758
759 PostMessage(0, 0, 0, 0);
760 GetMessage(&msg, 0, 0, 0);
761#endif
762
Steve Dower84bcfb32015-01-02 18:07:46 -0800763 debug(L"run_child: about to run '%ls'\n", cmdline);
Brian Curtin07165f72012-06-20 15:36:14 -0500764 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));
Shiva Saxenacb090472019-02-03 00:51:04 +0530776 GetStartupInfoW(&si);
Brian Curtin07165f72012-06-20 15:36:14 -0500777 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)
Steve Dower84bcfb32015-01-02 18:07:46 -0800795 error(RC_CREATE_PROCESS, L"Unable to create process using '%ls'", cmdline);
Brian Curtin07165f72012-06-20 15:36:14 -0500796 AssignProcessToJobObject(job, pi.hProcess);
797 CloseHandle(pi.hThread);
Martin v. Löwisb26a9b12013-01-25 14:25:48 +0100798 WaitForSingleObjectEx(pi.hProcess, INFINITE, FALSE);
Brian Curtin07165f72012-06-20 15:36:14 -0500799 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);
Vinay Sajipaab9f462015-12-26 12:35:47 +0000803 exit(rc);
Brian Curtin07165f72012-06-20 15:36:14 -0500804}
805
806static void
807invoke_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)
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +0200828 error(RC_CREATE_PROCESS, L"unable to allocate %zd bytes for child command.",
Brian Curtin07165f72012-06-20 15:36:14 -0500829 child_command_size);
830 if (no_suffix)
831 _snwprintf_s(child_command, child_command_size,
Steve Dower84bcfb32015-01-02 18:07:46 -0800832 child_command_size - 1, L"%ls %ls",
Brian Curtin07165f72012-06-20 15:36:14 -0500833 executable, cmdline);
834 else
835 _snwprintf_s(child_command, child_command_size,
Steve Dower84bcfb32015-01-02 18:07:46 -0800836 child_command_size - 1, L"%ls %ls %ls",
Brian Curtin07165f72012-06-20 15:36:14 -0500837 executable, suffix, cmdline);
838 run_child(child_command);
839 free(child_command);
840 }
841}
842
Vinay Sajip22c039b2013-06-07 15:37:28 +0100843typedef struct {
844 wchar_t *shebang;
845 BOOL search;
846} SHEBANG;
847
848static 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 },
Brian Curtin07165f72012-06-20 15:36:14 -0500854};
855
856/* For now, a static array of commands. */
857
858#define MAX_COMMANDS 100
859
860typedef struct {
861 wchar_t key[MAX_PATH];
862 wchar_t value[MSGSIZE];
863} COMMAND;
864
865static COMMAND commands[MAX_COMMANDS];
866static int num_commands = 0;
867
868#if defined(SKIP_PREFIX)
869
870static 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
881static 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
904static COMMAND path_command;
905
906static 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
945static 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
964static void
965update_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
971static void
972add_command(wchar_t * name, wchar_t * cmdline)
973{
974 if (num_commands >= MAX_COMMANDS) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800975 debug(L"can't add %ls = '%ls': no room\n", name, cmdline);
Brian Curtin07165f72012-06-20 15:36:14 -0500976 }
977 else {
978 COMMAND * cp = &commands[num_commands++];
979
980 update_command(cp, name, cmdline);
981 }
982}
983
984static void
985read_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) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800997 debug(L"read_commands: %ls: not enough space for names\n", config_path);
Brian Curtin07165f72012-06-20 15:36:14 -0500998 }
999 key = keynames;
1000 while (*key) {
1001 read = GetPrivateProfileStringW(L"commands", key, NULL, value, MSGSIZE,
1002 config_path);
1003 if (read == MSGSIZE - 1) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001004 debug(L"read_commands: %ls: not enough space for %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -05001005 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
1019static 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
1027static BOOL
1028parse_shebang(wchar_t * shebang_line, int nchars, wchar_t ** command,
Vinay Sajip22c039b2013-06-07 15:37:28 +01001029 wchar_t ** suffix, BOOL *search)
Brian Curtin07165f72012-06-20 15:36:14 -05001030{
1031 BOOL rc = FALSE;
Vinay Sajip22c039b2013-06-07 15:37:28 +01001032 SHEBANG * vpp;
Brian Curtin07165f72012-06-20 15:36:14 -05001033 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;
Vinay Sajip22c039b2013-06-07 15:37:28 +01001042 *search = FALSE;
Brian Curtin07165f72012-06-20 15:36:14 -05001043
1044 if ((*shebang_line++ == L'#') && (*shebang_line++ == L'!')) {
1045 shebang_line = skip_whitespace(shebang_line);
1046 if (*shebang_line) {
1047 *command = shebang_line;
Vinay Sajip22c039b2013-06-07 15:37:28 +01001048 for (vpp = builtin_virtual_paths; vpp->shebang; ++vpp) {
1049 plen = wcslen(vpp->shebang);
1050 if (wcsncmp(shebang_line, vpp->shebang, plen) == 0) {
Brian Curtin07165f72012-06-20 15:36:14 -05001051 rc = TRUE;
Vinay Sajip22c039b2013-06-07 15:37:28 +01001052 *search = vpp->search;
Brian Curtin07165f72012-06-20 15:36:14 -05001053 /* We can do this because all builtin commands contain
1054 * "python".
1055 */
1056 *command = wcsstr(shebang_line, L"python");
1057 break;
1058 }
1059 }
Vinay Sajip22c039b2013-06-07 15:37:28 +01001060 if (vpp->shebang == NULL) {
Brian Curtin07165f72012-06-20 15:36:14 -05001061 /*
Vinay Sajip9c10d6b2013-11-15 20:58:13 +00001062 * Not found in builtins - look in customized commands.
Brian Curtin07165f72012-06-20 15:36:14 -05001063 *
1064 * We can't permanently modify the shebang line in case
Vinay Sajip9c10d6b2013-11-15 20:58:13 +00001065 * it's not a customized command, but we can temporarily
Brian Curtin07165f72012-06-20 15:36:14 -05001066 * 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
1104typedef struct {
1105 int length;
1106 char sequence[4];
1107 UINT code_page;
1108} BOM;
1109
1110/*
Vinay Sajipc985d082013-07-25 11:20:55 +01001111 * Strictly, we don't need to handle UTF-16 and UTF-32, since Python itself
Brian Curtin07165f72012-06-20 15:36:14 -05001112 * doesn't. Never mind, one day it might - there's no harm leaving it in.
1113 */
1114static BOM BOMs[] = {
1115 { 3, { 0xEF, 0xBB, 0xBF }, CP_UTF8 }, /* UTF-8 - keep first */
Serhiy Storchaka29e2aa62015-12-18 10:23:09 +02001116 /* Test UTF-32LE before UTF-16LE since UTF-16LE BOM is a prefix
1117 * of UTF-32LE BOM. */
Brian Curtin07165f72012-06-20 15:36:14 -05001118 { 4, { 0xFF, 0xFE, 0x00, 0x00 }, CP_UTF32LE }, /* UTF-32LE */
1119 { 4, { 0x00, 0x00, 0xFE, 0xFF }, CP_UTF32BE }, /* UTF-32BE */
Serhiy Storchaka29e2aa62015-12-18 10:23:09 +02001120 { 2, { 0xFF, 0xFE }, CP_UTF16LE }, /* UTF-16LE */
1121 { 2, { 0xFE, 0xFF }, CP_UTF16BE }, /* UTF-16BE */
Brian Curtin07165f72012-06-20 15:36:14 -05001122 { 0 } /* sentinel */
1123};
1124
1125static BOM *
1126find_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
1144static char *
1145find_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
1178static BOOL
1179validate_version(wchar_t * p)
1180{
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +01001181 /*
Brendan Gerrity3876af42018-09-04 09:35:46 -07001182 Version information should start with the major version,
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +01001183 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. */
Brian Curtin07165f72012-06-20 15:36:14 -05001198
Brendan Gerrity3876af42018-09-04 09:35:46 -07001199 result = result && iswdigit(*p); /* Result = False if first string element is not a digit. */
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +01001200
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:
Brian Curtin07165f72012-06-20 15:36:14 -05001217 result = FALSE;
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +01001218 break;
Brian Curtin07165f72012-06-20 15:36:14 -05001219 }
1220 }
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +01001221 result = result && !*p; /* Must have reached EOS */
Brian Curtin07165f72012-06-20 15:36:14 -05001222 return result;
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +01001223
Brian Curtin07165f72012-06-20 15:36:14 -05001224}
1225
1226typedef struct {
1227 unsigned short min;
1228 unsigned short max;
1229 wchar_t version[MAX_VERSION_SIZE];
1230} PYC_MAGIC;
1231
1232static PYC_MAGIC magic_values[] = {
Steve Dower7ae61af2016-05-16 09:34:20 -07001233 { 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" },
Serhiy Storchaka3c317e72016-06-12 09:22:01 +03001246 { 3320, 3351, L"3.5" },
Nick Coghlan944368e2016-09-11 14:45:49 +10001247 { 3360, 3379, L"3.6" },
Yury Selivanovf2392132016-12-13 19:03:51 -05001248 { 3390, 3399, L"3.7" },
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001249 { 3400, 3419, L"3.8" },
Mark Shannon9af0e472020-01-14 10:12:45 +00001250 { 3420, 3429, L"3.9" },
Brian Curtin07165f72012-06-20 15:36:14 -05001251 { 0 }
1252};
1253
1254static INSTALLED_PYTHON *
1255find_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)) {
Paul Moore835416c2016-05-22 12:28:41 +01001262 result = locate_python(mp->version, FALSE);
Brian Curtin07165f72012-06-20 15:36:14 -05001263 if (result != NULL)
1264 break;
1265 }
1266 }
1267 return result;
1268}
1269
1270static void
1271maybe_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");
Serhiy Storchakaf8ed0042015-12-18 10:19:30 +02001282 char buffer[BUFSIZE];
Brian Curtin07165f72012-06-20 15:36:14 -05001283 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;
Vinay Sajip22c039b2013-06-07 15:37:28 +01001292 BOOL search;
Brian Curtin07165f72012-06-20 15:36:14 -05001293 wchar_t * command;
1294 wchar_t * suffix;
Vinay Sajip22c039b2013-06-07 15:37:28 +01001295 COMMAND *cmd = NULL;
Brian Curtin07165f72012-06-20 15:36:14 -05001296 INSTALLED_PYTHON * ip;
1297
1298 if (rc == 0) {
1299 read = fread(buffer, sizeof(char), BUFSIZE, fp);
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02001300 debug(L"maybe_handle_shebang: read %zd bytes\n", read);
Brian Curtin07165f72012-06-20 15:36:14 -05001301 fclose(fp);
1302
1303 if ((read >= 4) && (buffer[3] == '\n') && (buffer[2] == '\r')) {
Serhiy Storchakaf8ed0042015-12-18 10:19:30 +02001304 ip = find_by_magic((((unsigned char)buffer[1]) << 8 |
1305 (unsigned char)buffer[0]) & 0xFFFF);
Brian Curtin07165f72012-06-20 15:36:14 -05001306 if (ip != NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001307 debug(L"script file is compiled against Python %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -05001308 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 {
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02001320 debug(L"maybe_handle_shebang: BOM found, code page %u\n",
Brian Curtin07165f72012-06-20 15:36:14 -05001321 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 \
1351of 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,
Vinay Sajip22c039b2013-06-07 15:37:28 +01001408 &suffix, &search);
Brian Curtin07165f72012-06-20 15:36:14 -05001409 if (command != NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001410 debug(L"parse_shebang: found command: %ls\n", command);
Brian Curtin07165f72012-06-20 15:36:14 -05001411 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 \
Steve Dower84bcfb32015-01-02 18:07:46 -08001422path '%ls'", command);
Brian Curtin07165f72012-06-20 15:36:14 -05001423 command += 6; /* skip past "python" */
Vinay Sajip22c039b2013-06-07 15:37:28 +01001424 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");
Vinay Sajipa5892ab2015-12-26 13:10:51 +00001429 cmd = find_on_path(PYTHON_EXECUTABLE);
Steve Dower84bcfb32015-01-02 18:07:46 -08001430 debug(L"Python on path: %ls\n", cmd ? cmd->value : L"<not found>");
Vinay Sajip22c039b2013-06-07 15:37:28 +01001431 if (cmd) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001432 debug(L"located python on PATH: %ls\n", cmd->value);
Vinay Sajip22c039b2013-06-07 15:37:28 +01001433 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 }
Brian Curtin07165f72012-06-20 15:36:14 -05001441 if (*command && !validate_version(command))
1442 error(RC_BAD_VIRTUAL_PATH, L"Invalid version \
Steve Dower84bcfb32015-01-02 18:07:46 -08001443specification: '%ls'.\nIn the first line of the script, 'python' needs to be \
Brian Curtin07165f72012-06-20 15:36:14 -05001444followed by a valid version specifier.\nPlease check the documentation.",
1445 command);
1446 /* TODO could call validate_version(command) */
Paul Moore835416c2016-05-22 12:28:41 +01001447 ip = locate_python(command, TRUE);
Brian Curtin07165f72012-06-20 15:36:14 -05001448 if (ip == NULL) {
1449 error(RC_NO_PYTHON, L"Requested Python version \
Steve Dower84bcfb32015-01-02 18:07:46 -08001450(%ls) is not installed", command);
Brian Curtin07165f72012-06-20 15:36:14 -05001451 }
1452 else {
1453 invoke_child(ip->executable, suffix, cmdline);
1454 }
1455 }
1456 }
1457 }
1458 }
1459 }
1460}
1461
1462static wchar_t *
1463skip_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
1486static DWORD version_high = 0;
1487static DWORD version_low = 0;
1488
1489static void
1490get_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
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001506static void
1507show_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"\
1520Python Launcher for Windows Version %ls\n\n", version_text);
1521 fwprintf(stdout, L"\
1522usage:\n\
1523%ls [launcher-args] [python-args] script [script-args]\n\n", argv[0]);
1524 fputws(L"\
1525Launcher 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\nThe following help text is from Python:\n\n", stdout);
1540 fflush(stdout);
1541}
1542
1543static BOOL
1544show_python_list(wchar_t ** argv)
1545{
1546 /*
1547 * Display options -0
1548 */
1549 INSTALLED_PYTHON * result = NULL;
1550 INSTALLED_PYTHON * ip = installed_pythons; /* List of installed pythons */
1551 INSTALLED_PYTHON * defpy = locate_python(L"", FALSE);
1552 size_t i = 0;
1553 wchar_t *p = argv[1];
Steve Dowered93a882019-09-12 18:16:50 +01001554 wchar_t *ver_fmt = L"-%ls-%d";
1555 wchar_t *fmt = L"\n %ls";
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001556 wchar_t *defind = L" *"; /* Default indicator */
1557
1558 /*
1559 * Output informational messages to stderr to keep output
1560 * clean for use in pipes, etc.
1561 */
1562 fwprintf(stderr,
1563 L"Installed Pythons found by %s Launcher for Windows", argv[0]);
Steve Dowered93a882019-09-12 18:16:50 +01001564 if (!_wcsicmp(p, L"-0p") || !_wcsicmp(p, L"--list-paths"))
1565 fmt = L"\n %-15ls%ls"; /* include path */
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001566
1567 if (num_installed_pythons == 0) /* We have somehow got here without searching for pythons */
1568 locate_all_pythons(); /* Find them, Populates installed_pythons */
1569
1570 if (num_installed_pythons == 0) /* No pythons found */
1571 fwprintf(stderr, L"\nNo Installed Pythons Found!");
1572 else
1573 {
1574 for (i = 0; i < num_installed_pythons; i++, ip++) {
Steve Dowered93a882019-09-12 18:16:50 +01001575 wchar_t version[BUFSIZ];
1576 if (wcscmp(ip->version, L"venv") == 0) {
1577 wcscpy_s(version, BUFSIZ, L"(venv)");
1578 }
1579 else {
1580 swprintf_s(version, BUFSIZ, ver_fmt, ip->version, ip->bits);
1581 }
1582
1583 if (ip->exe_display[0]) {
1584 fwprintf(stdout, fmt, version, ip->exe_display);
1585 }
1586 else {
1587 fwprintf(stdout, fmt, version, ip->executable);
1588 }
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001589 /* If there is a default indicate it */
Steve Dowered93a882019-09-12 18:16:50 +01001590 if (defpy == ip)
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001591 fwprintf(stderr, defind);
1592 }
1593 }
1594
1595 if ((defpy == NULL) && (num_installed_pythons > 0))
1596 /* We have pythons but none is the default */
1597 fwprintf(stderr, L"\n\nCan't find a Default Python.\n\n");
1598 else
1599 fwprintf(stderr, L"\n\n"); /* End with a blank line */
Brendan Gerrityc8fe9cc2018-11-20 13:28:27 -08001600 return FALSE; /* If this has been called we cannot continue */
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001601}
1602
Steve Dower1c3de542018-12-10 08:11:21 -08001603#if defined(VENV_REDIRECT)
1604
1605static int
1606find_home_value(const char *buffer, const char **start, DWORD *length)
1607{
1608 for (const char *s = strstr(buffer, "home"); s; s = strstr(s + 1, "\nhome")) {
1609 if (*s == '\n') {
1610 ++s;
1611 }
1612 for (int i = 4; i > 0 && *s; --i, ++s);
1613
1614 while (*s && iswspace(*s)) {
1615 ++s;
1616 }
1617 if (*s != L'=') {
1618 continue;
1619 }
1620
1621 do {
1622 ++s;
1623 } while (*s && iswspace(*s));
1624
1625 *start = s;
1626 char *nl = strchr(s, '\n');
1627 if (nl) {
1628 *length = (DWORD)((ptrdiff_t)nl - (ptrdiff_t)s);
1629 } else {
1630 *length = (DWORD)strlen(s);
1631 }
1632 return 1;
1633 }
1634 return 0;
1635}
1636#endif
1637
1638static wchar_t *
1639wcsdup_pad(const wchar_t *s, int padding, int *newlen)
1640{
1641 size_t len = wcslen(s);
1642 len += 1 + padding;
1643 wchar_t *r = (wchar_t *)malloc(len * sizeof(wchar_t));
1644 if (!r) {
1645 return NULL;
1646 }
1647 if (wcscpy_s(r, len, s)) {
1648 free(r);
1649 return NULL;
1650 }
1651 *newlen = len < MAXINT ? (int)len : MAXINT;
1652 return r;
1653}
1654
1655static wchar_t *
1656get_process_name()
1657{
1658 DWORD bufferLen = MAX_PATH;
1659 DWORD len = bufferLen;
1660 wchar_t *r = NULL;
1661
1662 while (!r) {
1663 r = (wchar_t *)malloc(bufferLen * sizeof(wchar_t));
1664 if (!r) {
1665 error(RC_NO_MEMORY, L"out of memory");
1666 return NULL;
1667 }
1668 len = GetModuleFileNameW(NULL, r, bufferLen);
1669 if (len == 0) {
1670 free(r);
1671 error(0, L"Failed to get module name");
1672 return NULL;
1673 } else if (len == bufferLen &&
1674 GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
1675 free(r);
1676 r = NULL;
1677 bufferLen *= 2;
1678 }
1679 }
1680
1681 return r;
1682}
1683
Brian Curtin07165f72012-06-20 15:36:14 -05001684static int
1685process(int argc, wchar_t ** argv)
1686{
1687 wchar_t * wp;
1688 wchar_t * command;
Steve Dower76998fe2015-02-26 14:25:33 -08001689 wchar_t * executable;
Brian Curtin07165f72012-06-20 15:36:14 -05001690 wchar_t * p;
Steve Dower1c3de542018-12-10 08:11:21 -08001691 wchar_t * argv0;
Brian Curtin07165f72012-06-20 15:36:14 -05001692 int rc = 0;
Brian Curtin07165f72012-06-20 15:36:14 -05001693 INSTALLED_PYTHON * ip;
1694 BOOL valid;
1695 DWORD size, attrs;
Brian Curtin07165f72012-06-20 15:36:14 -05001696 wchar_t message[MSGSIZE];
Brian Curtin07165f72012-06-20 15:36:14 -05001697 void * version_data;
1698 VS_FIXEDFILEINFO * file_info;
1699 UINT block_size;
Steve Dower1c3de542018-12-10 08:11:21 -08001700#if defined(VENV_REDIRECT)
1701 wchar_t * venv_cfg_path;
Vinay Sajipc985d082013-07-25 11:20:55 +01001702 int newlen;
Steve Dower1c3de542018-12-10 08:11:21 -08001703#elif defined(SCRIPT_WRAPPER)
Vinay Sajipc985d082013-07-25 11:20:55 +01001704 wchar_t * newcommand;
1705 wchar_t * av[2];
Steve Dower1c3de542018-12-10 08:11:21 -08001706 int newlen;
1707 HRESULT hr;
1708 int index;
1709#else
1710 HRESULT hr;
1711 int index;
Vinay Sajipc985d082013-07-25 11:20:55 +01001712#endif
Brian Curtin07165f72012-06-20 15:36:14 -05001713
Vinay Sajipaab9f462015-12-26 12:35:47 +00001714 setvbuf(stderr, (char *)NULL, _IONBF, 0);
Brian Curtin07165f72012-06-20 15:36:14 -05001715 wp = get_env(L"PYLAUNCH_DEBUG");
1716 if ((wp != NULL) && (*wp != L'\0'))
1717 log_fp = stderr;
1718
1719#if defined(_M_X64)
1720 debug(L"launcher build: 64bit\n");
1721#else
1722 debug(L"launcher build: 32bit\n");
1723#endif
1724#if defined(_WINDOWS)
1725 debug(L"launcher executable: Windows\n");
1726#else
1727 debug(L"launcher executable: Console\n");
1728#endif
Steve Dower1c3de542018-12-10 08:11:21 -08001729#if !defined(VENV_REDIRECT)
Brian Curtin07165f72012-06-20 15:36:14 -05001730 /* Get the local appdata folder (non-roaming) */
1731 hr = SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA,
1732 NULL, 0, appdata_ini_path);
1733 if (hr != S_OK) {
1734 debug(L"SHGetFolderPath failed: %X\n", hr);
1735 appdata_ini_path[0] = L'\0';
1736 }
1737 else {
Steve Dower1c3de542018-12-10 08:11:21 -08001738 wcsncat_s(appdata_ini_path, MAX_PATH, L"\\py.ini", _TRUNCATE);
Brian Curtin07165f72012-06-20 15:36:14 -05001739 attrs = GetFileAttributesW(appdata_ini_path);
1740 if (attrs == INVALID_FILE_ATTRIBUTES) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001741 debug(L"File '%ls' non-existent\n", appdata_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001742 appdata_ini_path[0] = L'\0';
1743 } else {
Steve Dower84bcfb32015-01-02 18:07:46 -08001744 debug(L"Using local configuration file '%ls'\n", appdata_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001745 }
1746 }
Steve Dower1c3de542018-12-10 08:11:21 -08001747#endif
1748 argv0 = get_process_name();
1749 size = GetFileVersionInfoSizeW(argv0, &size);
Brian Curtin07165f72012-06-20 15:36:14 -05001750 if (size == 0) {
1751 winerror(GetLastError(), message, MSGSIZE);
Steve Dower84bcfb32015-01-02 18:07:46 -08001752 debug(L"GetFileVersionInfoSize failed: %ls\n", message);
Brian Curtin07165f72012-06-20 15:36:14 -05001753 }
1754 else {
1755 version_data = malloc(size);
1756 if (version_data) {
Steve Dower1c3de542018-12-10 08:11:21 -08001757 valid = GetFileVersionInfoW(argv0, 0, size,
Brian Curtin07165f72012-06-20 15:36:14 -05001758 version_data);
1759 if (!valid)
1760 debug(L"GetFileVersionInfo failed: %X\n", GetLastError());
1761 else {
Vinay Sajip404229b2013-01-29 22:52:57 +00001762 valid = VerQueryValueW(version_data, L"\\",
1763 (LPVOID *) &file_info, &block_size);
Brian Curtin07165f72012-06-20 15:36:14 -05001764 if (!valid)
1765 debug(L"VerQueryValue failed: %X\n", GetLastError());
1766 else {
1767 version_high = file_info->dwFileVersionMS;
1768 version_low = file_info->dwFileVersionLS;
1769 }
1770 }
1771 free(version_data);
1772 }
1773 }
Steve Dower1c3de542018-12-10 08:11:21 -08001774
1775#if defined(VENV_REDIRECT)
1776 /* Allocate some extra space for new filenames */
1777 venv_cfg_path = wcsdup_pad(argv0, 32, &newlen);
1778 if (!venv_cfg_path) {
1779 error(RC_NO_MEMORY, L"Failed to copy module name");
1780 }
1781 p = wcsrchr(venv_cfg_path, L'\\');
1782
1783 if (p == NULL) {
1784 error(RC_NO_VENV_CFG, L"No pyvenv.cfg file");
1785 }
1786 p[0] = L'\0';
1787 wcscat_s(venv_cfg_path, newlen, L"\\pyvenv.cfg");
1788 attrs = GetFileAttributesW(venv_cfg_path);
1789 if (attrs == INVALID_FILE_ATTRIBUTES) {
1790 debug(L"File '%ls' non-existent\n", venv_cfg_path);
1791 p[0] = '\0';
1792 p = wcsrchr(venv_cfg_path, L'\\');
1793 if (p != NULL) {
1794 p[0] = '\0';
1795 wcscat_s(venv_cfg_path, newlen, L"\\pyvenv.cfg");
1796 attrs = GetFileAttributesW(venv_cfg_path);
1797 if (attrs == INVALID_FILE_ATTRIBUTES) {
1798 debug(L"File '%ls' non-existent\n", venv_cfg_path);
1799 error(RC_NO_VENV_CFG, L"No pyvenv.cfg file");
1800 }
1801 }
1802 }
1803 debug(L"Using venv configuration file '%ls'\n", venv_cfg_path);
1804#else
1805 /* Allocate some extra space for new filenames */
1806 if (wcscpy_s(launcher_ini_path, MAX_PATH, argv0)) {
1807 error(RC_NO_MEMORY, L"Failed to copy module name");
1808 }
Brian Curtin07165f72012-06-20 15:36:14 -05001809 p = wcsrchr(launcher_ini_path, L'\\');
Steve Dower1c3de542018-12-10 08:11:21 -08001810
Brian Curtin07165f72012-06-20 15:36:14 -05001811 if (p == NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001812 debug(L"GetModuleFileNameW returned value has no backslash: %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -05001813 launcher_ini_path);
1814 launcher_ini_path[0] = L'\0';
1815 }
1816 else {
Steve Dower1c3de542018-12-10 08:11:21 -08001817 p[0] = L'\0';
1818 wcscat_s(launcher_ini_path, MAX_PATH, L"\\py.ini");
Brian Curtin07165f72012-06-20 15:36:14 -05001819 attrs = GetFileAttributesW(launcher_ini_path);
1820 if (attrs == INVALID_FILE_ATTRIBUTES) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001821 debug(L"File '%ls' non-existent\n", launcher_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001822 launcher_ini_path[0] = L'\0';
1823 } else {
Steve Dower84bcfb32015-01-02 18:07:46 -08001824 debug(L"Using global configuration file '%ls'\n", launcher_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001825 }
1826 }
Steve Dower1c3de542018-12-10 08:11:21 -08001827#endif
Brian Curtin07165f72012-06-20 15:36:14 -05001828
1829 command = skip_me(GetCommandLineW());
Steve Dower84bcfb32015-01-02 18:07:46 -08001830 debug(L"Called with command line: %ls\n", command);
Vinay Sajipc985d082013-07-25 11:20:55 +01001831
Steve Doweradad9e62019-01-25 14:59:58 -08001832#if !defined(VENV_REDIRECT)
1833 /* bpo-35811: The __PYVENV_LAUNCHER__ variable is used to
Mark Shannon9af0e472020-01-14 10:12:45 +00001834 * override sys.executable and locate the original prefix path.
Steve Doweradad9e62019-01-25 14:59:58 -08001835 * However, if it is silently inherited by a non-venv Python
1836 * process, that process will believe it is running in the venv
1837 * still. This is the only place where *we* can clear it (that is,
1838 * when py.exe is being used to launch Python), so we do.
1839 */
1840 SetEnvironmentVariableW(L"__PYVENV_LAUNCHER__", NULL);
1841#endif
1842
Vinay Sajipc985d082013-07-25 11:20:55 +01001843#if defined(SCRIPT_WRAPPER)
1844 /* The launcher is being used in "script wrapper" mode.
1845 * There should therefore be a Python script named <exename>-script.py in
1846 * the same directory as the launcher executable.
1847 * Put the script name into argv as the first (script name) argument.
1848 */
1849
1850 /* Get the wrapped script name - if the script is not present, this will
1851 * terminate the program with an error.
1852 */
1853 locate_wrapped_script();
1854
1855 /* Add the wrapped script to the start of command */
1856 newlen = wcslen(wrapped_script_path) + wcslen(command) + 2; /* ' ' + NUL */
1857 newcommand = malloc(sizeof(wchar_t) * newlen);
1858 if (!newcommand) {
1859 error(RC_NO_MEMORY, L"Could not allocate new command line");
1860 }
1861 else {
1862 wcscpy_s(newcommand, newlen, wrapped_script_path);
1863 wcscat_s(newcommand, newlen, L" ");
1864 wcscat_s(newcommand, newlen, command);
Steve Dower84bcfb32015-01-02 18:07:46 -08001865 debug(L"Running wrapped script with command line '%ls'\n", newcommand);
Vinay Sajipc985d082013-07-25 11:20:55 +01001866 read_commands();
1867 av[0] = wrapped_script_path;
1868 av[1] = NULL;
1869 maybe_handle_shebang(av, newcommand);
1870 /* Returns if no shebang line - pass to default processing */
1871 command = newcommand;
1872 valid = FALSE;
1873 }
Steve Dower1c3de542018-12-10 08:11:21 -08001874#elif defined(VENV_REDIRECT)
1875 {
1876 FILE *f;
1877 char buffer[4096]; /* 4KB should be enough for anybody */
1878 char *start;
1879 DWORD len, cch, cch_actual;
1880 size_t cb;
1881 if (_wfopen_s(&f, venv_cfg_path, L"r")) {
1882 error(RC_BAD_VENV_CFG, L"Cannot read '%ls'", venv_cfg_path);
1883 }
1884 cb = fread_s(buffer, sizeof(buffer), sizeof(buffer[0]),
1885 sizeof(buffer) / sizeof(buffer[0]), f);
1886 fclose(f);
1887
1888 if (!find_home_value(buffer, &start, &len)) {
1889 error(RC_BAD_VENV_CFG, L"Cannot find home in '%ls'",
1890 venv_cfg_path);
1891 }
1892
1893 cch = MultiByteToWideChar(CP_UTF8, 0, start, len, NULL, 0);
1894 if (!cch) {
1895 error(0, L"Cannot determine memory for home path");
1896 }
1897 cch += (DWORD)wcslen(PYTHON_EXECUTABLE) + 1 + 1; /* include sep and null */
1898 executable = (wchar_t *)malloc(cch * sizeof(wchar_t));
1899 if (executable == NULL) {
1900 error(RC_NO_MEMORY, L"A memory allocation failed");
1901 }
1902 cch_actual = MultiByteToWideChar(CP_UTF8, 0, start, len, executable, cch);
1903 if (!cch_actual) {
1904 error(RC_BAD_VENV_CFG, L"Cannot decode home path in '%ls'",
1905 venv_cfg_path);
1906 }
1907 if (executable[cch_actual - 1] != L'\\') {
1908 executable[cch_actual++] = L'\\';
1909 executable[cch_actual] = L'\0';
1910 }
1911 if (wcscat_s(executable, cch, PYTHON_EXECUTABLE)) {
1912 error(RC_BAD_VENV_CFG, L"Cannot create executable path from '%ls'",
1913 venv_cfg_path);
1914 }
1915 if (GetFileAttributesW(executable) == INVALID_FILE_ATTRIBUTES) {
1916 error(RC_NO_PYTHON, L"No Python at '%ls'", executable);
1917 }
1918 if (!SetEnvironmentVariableW(L"__PYVENV_LAUNCHER__", argv0)) {
1919 error(0, L"Failed to set launcher environment");
1920 }
1921 valid = 1;
1922 }
Vinay Sajipc985d082013-07-25 11:20:55 +01001923#else
Brian Curtin07165f72012-06-20 15:36:14 -05001924 if (argc <= 1) {
1925 valid = FALSE;
1926 p = NULL;
1927 }
1928 else {
1929 p = argv[1];
Brendan Gerrityc8fe9cc2018-11-20 13:28:27 -08001930 if ((argc == 2) && // list version args
1931 (!wcsncmp(p, L"-0", wcslen(L"-0")) ||
Brendan Gerrityaada63b2018-08-31 08:15:42 -07001932 !wcsncmp(p, L"--list", wcslen(L"--list"))))
1933 {
Brendan Gerrityc8fe9cc2018-11-20 13:28:27 -08001934 show_python_list(argv);
1935 return rc;
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001936 }
1937 valid = valid && (*p == L'-') && validate_version(&p[1]);
Brian Curtin07165f72012-06-20 15:36:14 -05001938 if (valid) {
Paul Moore835416c2016-05-22 12:28:41 +01001939 ip = locate_python(&p[1], FALSE);
Brian Curtin07165f72012-06-20 15:36:14 -05001940 if (ip == NULL)
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001941 {
1942 fwprintf(stdout, \
1943 L"Python %ls not found!\n", &p[1]);
1944 valid = show_python_list(argv);
Steve Dower84bcfb32015-01-02 18:07:46 -08001945 error(RC_NO_PYTHON, L"Requested Python version (%ls) not \
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001946installed, use -0 for available pythons", &p[1]);
1947 }
Steve Dower76998fe2015-02-26 14:25:33 -08001948 executable = ip->executable;
Brian Curtin07165f72012-06-20 15:36:14 -05001949 command += wcslen(p);
1950 command = skip_whitespace(command);
1951 }
Vinay Sajip2ae8c632013-01-29 22:29:25 +00001952 else {
1953 for (index = 1; index < argc; ++index) {
1954 if (*argv[index] != L'-')
1955 break;
1956 }
1957 if (index < argc) {
1958 read_commands();
1959 maybe_handle_shebang(&argv[index], command);
1960 }
1961 }
Brian Curtin07165f72012-06-20 15:36:14 -05001962 }
Vinay Sajipc985d082013-07-25 11:20:55 +01001963#endif
1964
Brian Curtin07165f72012-06-20 15:36:14 -05001965 if (!valid) {
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001966 if ((argc == 2) && (!_wcsicmp(p, L"-h") || !_wcsicmp(p, L"--help")))
1967 show_help_text(argv);
Brendan Gerrityaada63b2018-08-31 08:15:42 -07001968 if ((argc == 2) &&
1969 (!_wcsicmp(p, L"-0") || !_wcsicmp(p, L"--list") ||
1970 !_wcsicmp(p, L"-0p") || !_wcsicmp(p, L"--list-paths")))
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001971 {
Brendan Gerrityaada63b2018-08-31 08:15:42 -07001972 executable = NULL; /* Info call only */
1973 }
1974 else {
Steve Dowered93a882019-09-12 18:16:50 +01001975 /* look for the default Python */
1976 ip = locate_python(L"", FALSE);
1977 if (ip == NULL)
1978 error(RC_NO_PYTHON, L"Can't find a default Python.");
1979 executable = ip->executable;
Brian Curtin07165f72012-06-20 15:36:14 -05001980 }
1981 }
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001982 if (executable != NULL)
1983 invoke_child(executable, NULL, command);
1984 else
1985 rc = RC_NO_PYTHON;
Brian Curtin07165f72012-06-20 15:36:14 -05001986 return rc;
1987}
1988
1989#if defined(_WINDOWS)
1990
1991int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
1992 LPWSTR lpstrCmd, int nShow)
1993{
1994 return process(__argc, __wargv);
1995}
1996
1997#else
1998
1999int cdecl wmain(int argc, wchar_t ** argv)
2000{
2001 return process(argc, argv);
2002}
2003
Vinay Sajip2ae8c632013-01-29 22:29:25 +00002004#endif