blob: a260860f3c27a4d7c529b3adee4ce7401163a6bb [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)
144#if defined(_WINDOWS)
145
146#define PYTHON_EXECUTABLE L"pythonw_d.exe"
147
148#else
149
150#define PYTHON_EXECUTABLE L"python_d.exe"
151
152#endif
153#else
Brian Curtin07165f72012-06-20 15:36:14 -0500154#if defined(_WINDOWS)
155
156#define PYTHON_EXECUTABLE L"pythonw.exe"
157
158#else
159
160#define PYTHON_EXECUTABLE L"python.exe"
161
162#endif
Steve Dower1c3de542018-12-10 08:11:21 -0800163#endif
Brian Curtin07165f72012-06-20 15:36:14 -0500164
Miss Islington (bot)664d56a2019-09-12 10:36:14 -0700165#define MAX_VERSION_SIZE 8
Brian Curtin07165f72012-06-20 15:36:14 -0500166
167typedef struct {
168 wchar_t version[MAX_VERSION_SIZE]; /* m.n */
169 int bits; /* 32 or 64 */
170 wchar_t executable[MAX_PATH];
Miss Islington (bot)664d56a2019-09-12 10:36:14 -0700171 wchar_t exe_display[MAX_PATH];
Brian Curtin07165f72012-06-20 15:36:14 -0500172} INSTALLED_PYTHON;
173
174/*
175 * To avoid messing about with heap allocations, just assume we can allocate
176 * statically and never have to deal with more versions than this.
177 */
178#define MAX_INSTALLED_PYTHONS 100
179
180static INSTALLED_PYTHON installed_pythons[MAX_INSTALLED_PYTHONS];
181
182static size_t num_installed_pythons = 0;
183
Steve Dowerbb240872015-02-05 22:08:48 -0800184/*
185 * To hold SOFTWARE\Python\PythonCore\X.Y...\InstallPath
186 * The version name can be longer than MAX_VERSION_SIZE, but will be
187 * truncated to just X.Y for comparisons.
188 */
Miss Islington (bot)664d56a2019-09-12 10:36:14 -0700189#define IP_BASE_SIZE 80
Steve Dowerbb240872015-02-05 22:08:48 -0800190#define IP_VERSION_SIZE 8
191#define IP_SIZE (IP_BASE_SIZE + IP_VERSION_SIZE)
Brian Curtin07165f72012-06-20 15:36:14 -0500192#define CORE_PATH L"SOFTWARE\\Python\\PythonCore"
Miss Islington (bot)664d56a2019-09-12 10:36:14 -0700193/*
194 * Installations from the Microsoft Store will set the same registry keys,
195 * but because of a limitation in Windows they cannot be enumerated normally
196 * (unless you have no other Python installations... which is probably false
197 * because that's the most likely way to get this launcher!)
198 * This key is under HKEY_LOCAL_MACHINE
199 */
200#define LOOKASIDE_PATH L"SOFTWARE\\Microsoft\\AppModel\\Lookaside\\user\\Software\\Python\\PythonCore"
Brian Curtin07165f72012-06-20 15:36:14 -0500201
202static wchar_t * location_checks[] = {
203 L"\\",
Stefan Grönkef1502d02017-09-25 18:58:10 +0200204 L"\\PCbuild\\win32\\",
205 L"\\PCbuild\\amd64\\",
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100206 /* To support early 32bit versions of Python that stuck the build binaries
Stefan Grönkef1502d02017-09-25 18:58:10 +0200207 * directly in PCbuild... */
208 L"\\PCbuild\\",
Brian Curtin07165f72012-06-20 15:36:14 -0500209 NULL
210};
211
212static INSTALLED_PYTHON *
Miss Islington (bot)664d56a2019-09-12 10:36:14 -0700213find_existing_python(const wchar_t * path)
Brian Curtin07165f72012-06-20 15:36:14 -0500214{
215 INSTALLED_PYTHON * result = NULL;
216 size_t i;
217 INSTALLED_PYTHON * ip;
218
219 for (i = 0, ip = installed_pythons; i < num_installed_pythons; i++, ip++) {
220 if (_wcsicmp(path, ip->executable) == 0) {
221 result = ip;
222 break;
223 }
224 }
225 return result;
226}
227
Miss Islington (bot)664d56a2019-09-12 10:36:14 -0700228static INSTALLED_PYTHON *
229find_existing_python2(int bits, const wchar_t * version)
230{
231 INSTALLED_PYTHON * result = NULL;
232 size_t i;
233 INSTALLED_PYTHON * ip;
234
235 for (i = 0, ip = installed_pythons; i < num_installed_pythons; i++, ip++) {
236 if (bits == ip->bits && _wcsicmp(version, ip->version) == 0) {
237 result = ip;
238 break;
239 }
240 }
241 return result;
242}
243
Brian Curtin07165f72012-06-20 15:36:14 -0500244static void
Miss Islington (bot)664d56a2019-09-12 10:36:14 -0700245_locate_pythons_for_key(HKEY root, LPCWSTR subkey, REGSAM flags, int bits,
246 int display_name_only)
Brian Curtin07165f72012-06-20 15:36:14 -0500247{
248 HKEY core_root, ip_key;
Miss Islington (bot)664d56a2019-09-12 10:36:14 -0700249 LSTATUS status = RegOpenKeyExW(root, subkey, 0, flags, &core_root);
Brian Curtin07165f72012-06-20 15:36:14 -0500250 wchar_t message[MSGSIZE];
251 DWORD i;
252 size_t n;
Miss Islington (bot)664d56a2019-09-12 10:36:14 -0700253 BOOL ok, append_name;
Brian Curtin07165f72012-06-20 15:36:14 -0500254 DWORD type, data_size, attrs;
255 INSTALLED_PYTHON * ip, * pip;
Steve Dowerbb240872015-02-05 22:08:48 -0800256 wchar_t ip_version[IP_VERSION_SIZE];
Brian Curtin07165f72012-06-20 15:36:14 -0500257 wchar_t ip_path[IP_SIZE];
258 wchar_t * check;
259 wchar_t ** checkp;
260 wchar_t *key_name = (root == HKEY_LOCAL_MACHINE) ? L"HKLM" : L"HKCU";
261
262 if (status != ERROR_SUCCESS)
Steve Dower84bcfb32015-01-02 18:07:46 -0800263 debug(L"locate_pythons_for_key: unable to open PythonCore key in %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500264 key_name);
265 else {
266 ip = &installed_pythons[num_installed_pythons];
267 for (i = 0; num_installed_pythons < MAX_INSTALLED_PYTHONS; i++) {
Steve Dowerbb240872015-02-05 22:08:48 -0800268 status = RegEnumKeyW(core_root, i, ip_version, IP_VERSION_SIZE);
Brian Curtin07165f72012-06-20 15:36:14 -0500269 if (status != ERROR_SUCCESS) {
270 if (status != ERROR_NO_MORE_ITEMS) {
271 /* unexpected error */
272 winerror(status, message, MSGSIZE);
Steve Dower84bcfb32015-01-02 18:07:46 -0800273 debug(L"Can't enumerate registry key for version %ls: %ls\n",
Steve Dowerbb240872015-02-05 22:08:48 -0800274 ip_version, message);
Brian Curtin07165f72012-06-20 15:36:14 -0500275 }
276 break;
277 }
278 else {
Steve Dowerbb240872015-02-05 22:08:48 -0800279 wcsncpy_s(ip->version, MAX_VERSION_SIZE, ip_version,
280 MAX_VERSION_SIZE-1);
Miss Islington (bot)664d56a2019-09-12 10:36:14 -0700281 /* Still treating version as "x.y" rather than sys.winver
282 * When PEP 514 tags are properly used, we shouldn't need
283 * to strip this off here.
284 */
285 check = wcsrchr(ip->version, L'-');
286 if (check && !wcscmp(check, L"-32")) {
287 *check = L'\0';
288 }
Brian Curtin07165f72012-06-20 15:36:14 -0500289 _snwprintf_s(ip_path, IP_SIZE, _TRUNCATE,
Miss Islington (bot)664d56a2019-09-12 10:36:14 -0700290 L"%ls\\%ls\\InstallPath", subkey, ip_version);
Brian Curtin07165f72012-06-20 15:36:14 -0500291 status = RegOpenKeyExW(root, ip_path, 0, flags, &ip_key);
292 if (status != ERROR_SUCCESS) {
293 winerror(status, message, MSGSIZE);
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100294 /* Note: 'message' already has a trailing \n*/
Steve Dower84bcfb32015-01-02 18:07:46 -0800295 debug(L"%ls\\%ls: %ls", key_name, ip_path, message);
Brian Curtin07165f72012-06-20 15:36:14 -0500296 continue;
297 }
298 data_size = sizeof(ip->executable) - 1;
Miss Islington (bot)664d56a2019-09-12 10:36:14 -0700299 append_name = FALSE;
300 status = RegQueryValueExW(ip_key, L"ExecutablePath", NULL, &type,
Martin v. Löwisaf21ebb2012-06-21 18:15:54 +0200301 (LPBYTE)ip->executable, &data_size);
Miss Islington (bot)664d56a2019-09-12 10:36:14 -0700302 if (status != ERROR_SUCCESS || type != REG_SZ || !data_size) {
303 append_name = TRUE;
304 data_size = sizeof(ip->executable) - 1;
305 status = RegQueryValueExW(ip_key, NULL, NULL, &type,
306 (LPBYTE)ip->executable, &data_size);
307 if (status != ERROR_SUCCESS) {
308 winerror(status, message, MSGSIZE);
309 debug(L"%ls\\%ls: %ls\n", key_name, ip_path, message);
310 RegCloseKey(ip_key);
311 continue;
312 }
313 }
Brian Curtin07165f72012-06-20 15:36:14 -0500314 RegCloseKey(ip_key);
Miss Islington (bot)664d56a2019-09-12 10:36:14 -0700315 if (type != REG_SZ) {
Brian Curtin07165f72012-06-20 15:36:14 -0500316 continue;
317 }
Miss Islington (bot)664d56a2019-09-12 10:36:14 -0700318
319 data_size = data_size / sizeof(wchar_t) - 1; /* for NUL */
320 if (ip->executable[data_size - 1] == L'\\')
321 --data_size; /* reg value ended in a backslash */
322 /* ip->executable is data_size long */
323 for (checkp = location_checks; *checkp; ++checkp) {
324 check = *checkp;
325 if (append_name) {
Brian Curtin07165f72012-06-20 15:36:14 -0500326 _snwprintf_s(&ip->executable[data_size],
327 MAX_PATH - data_size,
328 MAX_PATH - data_size,
Steve Dower84bcfb32015-01-02 18:07:46 -0800329 L"%ls%ls", check, PYTHON_EXECUTABLE);
Miss Islington (bot)664d56a2019-09-12 10:36:14 -0700330 }
331 attrs = GetFileAttributesW(ip->executable);
332 if (attrs == INVALID_FILE_ATTRIBUTES) {
333 winerror(GetLastError(), message, MSGSIZE);
334 debug(L"locate_pythons_for_key: %ls: %ls",
335 ip->executable, message);
336 }
337 else if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
338 debug(L"locate_pythons_for_key: '%ls' is a directory\n",
339 ip->executable, attrs);
340 }
341 else if (find_existing_python(ip->executable)) {
342 debug(L"locate_pythons_for_key: %ls: already found\n",
343 ip->executable);
344 }
345 else {
346 /* check the executable type. */
347 if (bits) {
348 ip->bits = bits;
349 } else {
Brian Curtin07165f72012-06-20 15:36:14 -0500350 ok = GetBinaryTypeW(ip->executable, &attrs);
351 if (!ok) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800352 debug(L"Failure getting binary type: %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500353 ip->executable);
354 }
355 else {
356 if (attrs == SCS_64BIT_BINARY)
357 ip->bits = 64;
358 else if (attrs == SCS_32BIT_BINARY)
359 ip->bits = 32;
360 else
361 ip->bits = 0;
Miss Islington (bot)664d56a2019-09-12 10:36:14 -0700362 }
363 }
364 if (ip->bits == 0) {
365 debug(L"locate_pythons_for_key: %ls: \
Brian Curtin07165f72012-06-20 15:36:14 -0500366invalid binary type: %X\n",
Miss Islington (bot)664d56a2019-09-12 10:36:14 -0700367 ip->executable, attrs);
368 }
369 else {
370 if (display_name_only) {
371 /* display just the executable name. This is
372 * primarily for the Store installs */
373 const wchar_t *name = wcsrchr(ip->executable, L'\\');
374 if (name) {
375 wcscpy_s(ip->exe_display, MAX_PATH, name+1);
Brian Curtin07165f72012-06-20 15:36:14 -0500376 }
Miss Islington (bot)664d56a2019-09-12 10:36:14 -0700377 }
378 if (wcschr(ip->executable, L' ') != NULL) {
379 /* has spaces, so quote, and set original as
380 * the display name */
381 if (!ip->exe_display[0]) {
382 wcscpy_s(ip->exe_display, MAX_PATH, ip->executable);
383 }
384 n = wcslen(ip->executable);
385 memmove(&ip->executable[1],
386 ip->executable, n * sizeof(wchar_t));
387 ip->executable[0] = L'\"';
388 ip->executable[n + 1] = L'\"';
389 ip->executable[n + 2] = L'\0';
390 }
391 debug(L"locate_pythons_for_key: %ls \
Brian Curtin07165f72012-06-20 15:36:14 -0500392is a %dbit executable\n",
Miss Islington (bot)664d56a2019-09-12 10:36:14 -0700393 ip->executable, ip->bits);
394 if (find_existing_python2(ip->bits, ip->version)) {
395 debug(L"locate_pythons_for_key: %ls-%i: already \
396found\n", ip->version, ip->bits);
397 }
398 else {
399 ++num_installed_pythons;
400 pip = ip++;
401 if (num_installed_pythons >=
402 MAX_INSTALLED_PYTHONS)
403 break;
Brian Curtin07165f72012-06-20 15:36:14 -0500404 }
405 }
406 }
407 }
408 }
409 }
410 RegCloseKey(core_root);
411 }
412}
413
414static int
415compare_pythons(const void * p1, const void * p2)
416{
417 INSTALLED_PYTHON * ip1 = (INSTALLED_PYTHON *) p1;
418 INSTALLED_PYTHON * ip2 = (INSTALLED_PYTHON *) p2;
419 /* note reverse sorting on version */
420 int result = wcscmp(ip2->version, ip1->version);
421
422 if (result == 0)
423 result = ip2->bits - ip1->bits; /* 64 before 32 */
424 return result;
425}
426
427static void
Miss Islington (bot)664d56a2019-09-12 10:36:14 -0700428locate_pythons_for_key(HKEY root, REGSAM flags)
429{
430 _locate_pythons_for_key(root, CORE_PATH, flags, 0, FALSE);
431}
432
433static void
434locate_store_pythons()
435{
436#if defined(_M_X64)
437 /* 64bit process, so look in native registry */
438 _locate_pythons_for_key(HKEY_LOCAL_MACHINE, LOOKASIDE_PATH,
439 KEY_READ, 64, TRUE);
440#else
441 /* 32bit process, so check that we're on 64bit OS */
442 BOOL f64 = FALSE;
443 if (IsWow64Process(GetCurrentProcess(), &f64) && f64) {
444 _locate_pythons_for_key(HKEY_LOCAL_MACHINE, LOOKASIDE_PATH,
445 KEY_READ | KEY_WOW64_64KEY, 64, TRUE);
446 }
447#endif
448}
449
450static void
451locate_venv_python()
452{
453 static wchar_t venv_python[MAX_PATH];
454 INSTALLED_PYTHON * ip;
455 wchar_t *virtual_env = get_env(L"VIRTUAL_ENV");
456 DWORD attrs;
457
458 /* Check for VIRTUAL_ENV environment variable */
459 if (virtual_env == NULL || virtual_env[0] == L'\0') {
460 return;
461 }
462
463 /* Check for a python executable in the venv */
464 debug(L"Checking for Python executable in virtual env '%ls'\n", virtual_env);
465 _snwprintf_s(venv_python, MAX_PATH, _TRUNCATE,
466 L"%ls\\Scripts\\%ls", virtual_env, PYTHON_EXECUTABLE);
467 attrs = GetFileAttributesW(venv_python);
468 if (attrs == INVALID_FILE_ATTRIBUTES) {
469 debug(L"Python executable %ls missing from virtual env\n", venv_python);
470 return;
471 }
472
473 ip = &installed_pythons[num_installed_pythons++];
474 wcscpy_s(ip->executable, MAX_PATH, venv_python);
475 ip->bits = 0;
476 wcscpy_s(ip->version, MAX_VERSION_SIZE, L"venv");
477}
478
479static void
Brian Curtin07165f72012-06-20 15:36:14 -0500480locate_all_pythons()
481{
Miss Islington (bot)664d56a2019-09-12 10:36:14 -0700482 /* venv Python is highest priority */
483 locate_venv_python();
Brian Curtin07165f72012-06-20 15:36:14 -0500484#if defined(_M_X64)
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100485 /* If we are a 64bit process, first hit the 32bit keys. */
Brian Curtin07165f72012-06-20 15:36:14 -0500486 debug(L"locating Pythons in 32bit registry\n");
487 locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ | KEY_WOW64_32KEY);
488 locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ | KEY_WOW64_32KEY);
489#else
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100490 /* If we are a 32bit process on a 64bit Windows, first hit the 64bit keys.*/
Brian Curtin07165f72012-06-20 15:36:14 -0500491 BOOL f64 = FALSE;
492 if (IsWow64Process(GetCurrentProcess(), &f64) && f64) {
493 debug(L"locating Pythons in 64bit registry\n");
494 locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ | KEY_WOW64_64KEY);
495 locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ | KEY_WOW64_64KEY);
496 }
Serhiy Storchaka009b8112015-03-18 21:53:15 +0200497#endif
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100498 /* now hit the "native" key for this process bittedness. */
Brian Curtin07165f72012-06-20 15:36:14 -0500499 debug(L"locating Pythons in native registry\n");
500 locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ);
501 locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ);
Miss Islington (bot)664d56a2019-09-12 10:36:14 -0700502 /* Store-installed Python is lowest priority */
503 locate_store_pythons();
Brian Curtin07165f72012-06-20 15:36:14 -0500504 qsort(installed_pythons, num_installed_pythons, sizeof(INSTALLED_PYTHON),
505 compare_pythons);
506}
507
508static INSTALLED_PYTHON *
509find_python_by_version(wchar_t const * wanted_ver)
510{
511 INSTALLED_PYTHON * result = NULL;
512 INSTALLED_PYTHON * ip = installed_pythons;
513 size_t i, n;
514 size_t wlen = wcslen(wanted_ver);
515 int bits = 0;
516
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100517 if (wcsstr(wanted_ver, L"-32")) {
Brian Curtin07165f72012-06-20 15:36:14 -0500518 bits = 32;
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100519 wlen -= wcslen(L"-32");
520 }
521 else if (wcsstr(wanted_ver, L"-64")) { /* Added option to select 64 bit explicitly */
522 bits = 64;
523 wlen -= wcslen(L"-64");
524 }
Brian Curtin07165f72012-06-20 15:36:14 -0500525 for (i = 0; i < num_installed_pythons; i++, ip++) {
526 n = wcslen(ip->version);
527 if (n > wlen)
528 n = wlen;
529 if ((wcsncmp(ip->version, wanted_ver, n) == 0) &&
530 /* bits == 0 => don't care */
531 ((bits == 0) || (ip->bits == bits))) {
532 result = ip;
533 break;
534 }
535 }
536 return result;
537}
538
539
540static wchar_t appdata_ini_path[MAX_PATH];
541static wchar_t launcher_ini_path[MAX_PATH];
542
543/*
544 * Get a value either from the environment or a configuration file.
545 * The key passed in will either be "python", "python2" or "python3".
546 */
547static wchar_t *
548get_configured_value(wchar_t * key)
549{
550/*
551 * Note: this static value is used to return a configured value
552 * obtained either from the environment or configuration file.
553 * This should be OK since there wouldn't be any concurrent calls.
554 */
555 static wchar_t configured_value[MSGSIZE];
556 wchar_t * result = NULL;
557 wchar_t * found_in = L"environment";
558 DWORD size;
559
560 /* First, search the environment. */
Steve Dower84bcfb32015-01-02 18:07:46 -0800561 _snwprintf_s(configured_value, MSGSIZE, _TRUNCATE, L"py_%ls", key);
Brian Curtin07165f72012-06-20 15:36:14 -0500562 result = get_env(configured_value);
563 if (result == NULL && appdata_ini_path[0]) {
564 /* Not in environment: check local configuration. */
565 size = GetPrivateProfileStringW(L"defaults", key, NULL,
566 configured_value, MSGSIZE,
567 appdata_ini_path);
568 if (size > 0) {
569 result = configured_value;
570 found_in = appdata_ini_path;
571 }
572 }
573 if (result == NULL && launcher_ini_path[0]) {
574 /* Not in environment or local: check global configuration. */
575 size = GetPrivateProfileStringW(L"defaults", key, NULL,
576 configured_value, MSGSIZE,
577 launcher_ini_path);
578 if (size > 0) {
579 result = configured_value;
580 found_in = launcher_ini_path;
581 }
582 }
583 if (result) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800584 debug(L"found configured value '%ls=%ls' in %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500585 key, result, found_in ? found_in : L"(unknown)");
586 } else {
Steve Dower84bcfb32015-01-02 18:07:46 -0800587 debug(L"found no configured value for '%ls'\n", key);
Brian Curtin07165f72012-06-20 15:36:14 -0500588 }
589 return result;
590}
591
592static INSTALLED_PYTHON *
Paul Moore835416c2016-05-22 12:28:41 +0100593locate_python(wchar_t * wanted_ver, BOOL from_shebang)
Brian Curtin07165f72012-06-20 15:36:14 -0500594{
595 static wchar_t config_key [] = { L"pythonX" };
596 static wchar_t * last_char = &config_key[sizeof(config_key) /
597 sizeof(wchar_t) - 2];
598 INSTALLED_PYTHON * result = NULL;
599 size_t n = wcslen(wanted_ver);
600 wchar_t * configured_value;
601
602 if (num_installed_pythons == 0)
603 locate_all_pythons();
604
605 if (n == 1) { /* just major version specified */
606 *last_char = *wanted_ver;
607 configured_value = get_configured_value(config_key);
608 if (configured_value != NULL)
609 wanted_ver = configured_value;
610 }
611 if (*wanted_ver) {
612 result = find_python_by_version(wanted_ver);
Steve Dower84bcfb32015-01-02 18:07:46 -0800613 debug(L"search for Python version '%ls' found ", wanted_ver);
Brian Curtin07165f72012-06-20 15:36:14 -0500614 if (result) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800615 debug(L"'%ls'\n", result->executable);
Brian Curtin07165f72012-06-20 15:36:14 -0500616 } else {
617 debug(L"no interpreter\n");
618 }
619 }
620 else {
621 *last_char = L'\0'; /* look for an overall default */
Miss Islington (bot)664d56a2019-09-12 10:36:14 -0700622 result = find_python_by_version(L"venv");
623 if (result == NULL) {
624 configured_value = get_configured_value(config_key);
625 if (configured_value)
626 result = find_python_by_version(configured_value);
627 }
Paul Moore835416c2016-05-22 12:28:41 +0100628 /* Not found a value yet - try by major version.
629 * If we're looking for an interpreter specified in a shebang line,
630 * we want to try Python 2 first, then Python 3 (for Unix and backward
631 * compatibility). If we're being called interactively, assume the user
632 * wants the latest version available, so try Python 3 first, then
633 * Python 2.
634 */
Brian Curtin07165f72012-06-20 15:36:14 -0500635 if (result == NULL)
Paul Moore835416c2016-05-22 12:28:41 +0100636 result = find_python_by_version(from_shebang ? L"2" : L"3");
Brian Curtin07165f72012-06-20 15:36:14 -0500637 if (result == NULL)
Paul Moore835416c2016-05-22 12:28:41 +0100638 result = find_python_by_version(from_shebang ? L"3" : L"2");
Brian Curtin07165f72012-06-20 15:36:14 -0500639 debug(L"search for default Python found ");
640 if (result) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800641 debug(L"version %ls at '%ls'\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500642 result->version, result->executable);
643 } else {
644 debug(L"no interpreter\n");
645 }
646 }
647 return result;
648}
649
Vinay Sajipc985d082013-07-25 11:20:55 +0100650#if defined(SCRIPT_WRAPPER)
651/*
652 * Check for a script located alongside the executable
653 */
654
655#if defined(_WINDOWS)
656#define SCRIPT_SUFFIX L"-script.pyw"
657#else
658#define SCRIPT_SUFFIX L"-script.py"
659#endif
660
661static wchar_t wrapped_script_path[MAX_PATH];
662
663/* Locate the script being wrapped.
664 *
665 * This code should store the name of the wrapped script in
666 * wrapped_script_path, or terminate the program with an error if there is no
667 * valid wrapped script file.
668 */
669static void
670locate_wrapped_script()
671{
672 wchar_t * p;
673 size_t plen;
674 DWORD attrs;
675
676 plen = GetModuleFileNameW(NULL, wrapped_script_path, MAX_PATH);
677 p = wcsrchr(wrapped_script_path, L'.');
678 if (p == NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800679 debug(L"GetModuleFileNameW returned value has no extension: %ls\n",
Vinay Sajipc985d082013-07-25 11:20:55 +0100680 wrapped_script_path);
Steve Dower84bcfb32015-01-02 18:07:46 -0800681 error(RC_NO_SCRIPT, L"Wrapper name '%ls' is not valid.", wrapped_script_path);
Vinay Sajipc985d082013-07-25 11:20:55 +0100682 }
683
684 wcsncpy_s(p, MAX_PATH - (p - wrapped_script_path) + 1, SCRIPT_SUFFIX, _TRUNCATE);
685 attrs = GetFileAttributesW(wrapped_script_path);
686 if (attrs == INVALID_FILE_ATTRIBUTES) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800687 debug(L"File '%ls' non-existent\n", wrapped_script_path);
688 error(RC_NO_SCRIPT, L"Script file '%ls' is not present.", wrapped_script_path);
Vinay Sajipc985d082013-07-25 11:20:55 +0100689 }
690
Steve Dower84bcfb32015-01-02 18:07:46 -0800691 debug(L"Using wrapped script file '%ls'\n", wrapped_script_path);
Vinay Sajipc985d082013-07-25 11:20:55 +0100692}
693#endif
694
Brian Curtin07165f72012-06-20 15:36:14 -0500695/*
696 * Process creation code
697 */
698
699static BOOL
700safe_duplicate_handle(HANDLE in, HANDLE * pout)
701{
702 BOOL ok;
703 HANDLE process = GetCurrentProcess();
704 DWORD rc;
705
706 *pout = NULL;
707 ok = DuplicateHandle(process, in, process, pout, 0, TRUE,
708 DUPLICATE_SAME_ACCESS);
709 if (!ok) {
710 rc = GetLastError();
711 if (rc == ERROR_INVALID_HANDLE) {
712 debug(L"DuplicateHandle returned ERROR_INVALID_HANDLE\n");
713 ok = TRUE;
714 }
715 else {
716 debug(L"DuplicateHandle returned %d\n", rc);
717 }
718 }
719 return ok;
720}
721
722static BOOL WINAPI
723ctrl_c_handler(DWORD code)
724{
725 return TRUE; /* We just ignore all control events. */
726}
727
728static void
729run_child(wchar_t * cmdline)
730{
731 HANDLE job;
732 JOBOBJECT_EXTENDED_LIMIT_INFORMATION info;
733 DWORD rc;
734 BOOL ok;
735 STARTUPINFOW si;
736 PROCESS_INFORMATION pi;
737
Vinay Sajip66fef9f2013-02-26 16:29:06 +0000738#if defined(_WINDOWS)
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100739 /*
740 When explorer launches a Windows (GUI) application, it displays
741 the "app starting" (the "pointer + hourglass") cursor for a number
742 of seconds, or until the app does something UI-ish (eg, creating a
743 window, or fetching a message). As this launcher doesn't do this
744 directly, that cursor remains even after the child process does these
745 things. We avoid that by doing a simple post+get message.
746 See http://bugs.python.org/issue17290 and
747 https://bitbucket.org/vinay.sajip/pylauncher/issue/20/busy-cursor-for-a-long-time-when-running
748 */
Vinay Sajip66fef9f2013-02-26 16:29:06 +0000749 MSG msg;
750
751 PostMessage(0, 0, 0, 0);
752 GetMessage(&msg, 0, 0, 0);
753#endif
754
Steve Dower84bcfb32015-01-02 18:07:46 -0800755 debug(L"run_child: about to run '%ls'\n", cmdline);
Brian Curtin07165f72012-06-20 15:36:14 -0500756 job = CreateJobObject(NULL, NULL);
757 ok = QueryInformationJobObject(job, JobObjectExtendedLimitInformation,
758 &info, sizeof(info), &rc);
759 if (!ok || (rc != sizeof(info)) || !job)
760 error(RC_CREATE_PROCESS, L"Job information querying failed");
761 info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE |
762 JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK;
763 ok = SetInformationJobObject(job, JobObjectExtendedLimitInformation, &info,
764 sizeof(info));
765 if (!ok)
766 error(RC_CREATE_PROCESS, L"Job information setting failed");
767 memset(&si, 0, sizeof(si));
Shiva Saxenacb090472019-02-03 00:51:04 +0530768 GetStartupInfoW(&si);
Brian Curtin07165f72012-06-20 15:36:14 -0500769 ok = safe_duplicate_handle(GetStdHandle(STD_INPUT_HANDLE), &si.hStdInput);
770 if (!ok)
771 error(RC_NO_STD_HANDLES, L"stdin duplication failed");
772 ok = safe_duplicate_handle(GetStdHandle(STD_OUTPUT_HANDLE), &si.hStdOutput);
773 if (!ok)
774 error(RC_NO_STD_HANDLES, L"stdout duplication failed");
775 ok = safe_duplicate_handle(GetStdHandle(STD_ERROR_HANDLE), &si.hStdError);
776 if (!ok)
777 error(RC_NO_STD_HANDLES, L"stderr duplication failed");
778
779 ok = SetConsoleCtrlHandler(ctrl_c_handler, TRUE);
780 if (!ok)
781 error(RC_CREATE_PROCESS, L"control handler setting failed");
782
783 si.dwFlags = STARTF_USESTDHANDLES;
784 ok = CreateProcessW(NULL, cmdline, NULL, NULL, TRUE,
785 0, NULL, NULL, &si, &pi);
786 if (!ok)
Steve Dower84bcfb32015-01-02 18:07:46 -0800787 error(RC_CREATE_PROCESS, L"Unable to create process using '%ls'", cmdline);
Brian Curtin07165f72012-06-20 15:36:14 -0500788 AssignProcessToJobObject(job, pi.hProcess);
789 CloseHandle(pi.hThread);
Martin v. Löwisb26a9b12013-01-25 14:25:48 +0100790 WaitForSingleObjectEx(pi.hProcess, INFINITE, FALSE);
Brian Curtin07165f72012-06-20 15:36:14 -0500791 ok = GetExitCodeProcess(pi.hProcess, &rc);
792 if (!ok)
793 error(RC_CREATE_PROCESS, L"Failed to get exit code of process");
794 debug(L"child process exit code: %d\n", rc);
Vinay Sajipaab9f462015-12-26 12:35:47 +0000795 exit(rc);
Brian Curtin07165f72012-06-20 15:36:14 -0500796}
797
798static void
799invoke_child(wchar_t * executable, wchar_t * suffix, wchar_t * cmdline)
800{
801 wchar_t * child_command;
802 size_t child_command_size;
803 BOOL no_suffix = (suffix == NULL) || (*suffix == L'\0');
804 BOOL no_cmdline = (*cmdline == L'\0');
805
806 if (no_suffix && no_cmdline)
807 run_child(executable);
808 else {
809 if (no_suffix) {
810 /* add 2 for space separator + terminating NUL. */
811 child_command_size = wcslen(executable) + wcslen(cmdline) + 2;
812 }
813 else {
814 /* add 3 for 2 space separators + terminating NUL. */
815 child_command_size = wcslen(executable) + wcslen(suffix) +
816 wcslen(cmdline) + 3;
817 }
818 child_command = calloc(child_command_size, sizeof(wchar_t));
819 if (child_command == NULL)
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +0200820 error(RC_CREATE_PROCESS, L"unable to allocate %zd bytes for child command.",
Brian Curtin07165f72012-06-20 15:36:14 -0500821 child_command_size);
822 if (no_suffix)
823 _snwprintf_s(child_command, child_command_size,
Steve Dower84bcfb32015-01-02 18:07:46 -0800824 child_command_size - 1, L"%ls %ls",
Brian Curtin07165f72012-06-20 15:36:14 -0500825 executable, cmdline);
826 else
827 _snwprintf_s(child_command, child_command_size,
Steve Dower84bcfb32015-01-02 18:07:46 -0800828 child_command_size - 1, L"%ls %ls %ls",
Brian Curtin07165f72012-06-20 15:36:14 -0500829 executable, suffix, cmdline);
830 run_child(child_command);
831 free(child_command);
832 }
833}
834
Vinay Sajip22c039b2013-06-07 15:37:28 +0100835typedef struct {
836 wchar_t *shebang;
837 BOOL search;
838} SHEBANG;
839
840static SHEBANG builtin_virtual_paths [] = {
841 { L"/usr/bin/env python", TRUE },
842 { L"/usr/bin/python", FALSE },
843 { L"/usr/local/bin/python", FALSE },
844 { L"python", FALSE },
845 { NULL, FALSE },
Brian Curtin07165f72012-06-20 15:36:14 -0500846};
847
848/* For now, a static array of commands. */
849
850#define MAX_COMMANDS 100
851
852typedef struct {
853 wchar_t key[MAX_PATH];
854 wchar_t value[MSGSIZE];
855} COMMAND;
856
857static COMMAND commands[MAX_COMMANDS];
858static int num_commands = 0;
859
860#if defined(SKIP_PREFIX)
861
862static wchar_t * builtin_prefixes [] = {
863 /* These must be in an order that the longest matches should be found,
864 * i.e. if the prefix is "/usr/bin/env ", it should match that entry
865 * *before* matching "/usr/bin/".
866 */
867 L"/usr/bin/env ",
868 L"/usr/bin/",
869 L"/usr/local/bin/",
870 NULL
871};
872
873static wchar_t * skip_prefix(wchar_t * name)
874{
875 wchar_t ** pp = builtin_prefixes;
876 wchar_t * result = name;
877 wchar_t * p;
878 size_t n;
879
880 for (; p = *pp; pp++) {
881 n = wcslen(p);
882 if (_wcsnicmp(p, name, n) == 0) {
883 result += n; /* skip the prefix */
884 if (p[n - 1] == L' ') /* No empty strings in table, so n > 1 */
885 result = skip_whitespace(result);
886 break;
887 }
888 }
889 return result;
890}
891
892#endif
893
894#if defined(SEARCH_PATH)
895
896static COMMAND path_command;
897
898static COMMAND * find_on_path(wchar_t * name)
899{
900 wchar_t * pathext;
901 size_t varsize;
902 wchar_t * context = NULL;
903 wchar_t * extension;
904 COMMAND * result = NULL;
905 DWORD len;
906 errno_t rc;
907
908 wcscpy_s(path_command.key, MAX_PATH, name);
909 if (wcschr(name, L'.') != NULL) {
910 /* assume it has an extension. */
911 len = SearchPathW(NULL, name, NULL, MSGSIZE, path_command.value, NULL);
912 if (len) {
913 result = &path_command;
914 }
915 }
916 else {
917 /* No extension - search using registered extensions. */
918 rc = _wdupenv_s(&pathext, &varsize, L"PATHEXT");
919 if (rc == 0) {
920 extension = wcstok_s(pathext, L";", &context);
921 while (extension) {
922 len = SearchPathW(NULL, name, extension, MSGSIZE, path_command.value, NULL);
923 if (len) {
924 result = &path_command;
925 break;
926 }
927 extension = wcstok_s(NULL, L";", &context);
928 }
929 free(pathext);
930 }
931 }
932 return result;
933}
934
935#endif
936
937static COMMAND * find_command(wchar_t * name)
938{
939 COMMAND * result = NULL;
940 COMMAND * cp = commands;
941 int i;
942
943 for (i = 0; i < num_commands; i++, cp++) {
944 if (_wcsicmp(cp->key, name) == 0) {
945 result = cp;
946 break;
947 }
948 }
949#if defined(SEARCH_PATH)
950 if (result == NULL)
951 result = find_on_path(name);
952#endif
953 return result;
954}
955
956static void
957update_command(COMMAND * cp, wchar_t * name, wchar_t * cmdline)
958{
959 wcsncpy_s(cp->key, MAX_PATH, name, _TRUNCATE);
960 wcsncpy_s(cp->value, MSGSIZE, cmdline, _TRUNCATE);
961}
962
963static void
964add_command(wchar_t * name, wchar_t * cmdline)
965{
966 if (num_commands >= MAX_COMMANDS) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800967 debug(L"can't add %ls = '%ls': no room\n", name, cmdline);
Brian Curtin07165f72012-06-20 15:36:14 -0500968 }
969 else {
970 COMMAND * cp = &commands[num_commands++];
971
972 update_command(cp, name, cmdline);
973 }
974}
975
976static void
977read_config_file(wchar_t * config_path)
978{
979 wchar_t keynames[MSGSIZE];
980 wchar_t value[MSGSIZE];
981 DWORD read;
982 wchar_t * key;
983 COMMAND * cp;
984 wchar_t * cmdp;
985
986 read = GetPrivateProfileStringW(L"commands", NULL, NULL, keynames, MSGSIZE,
987 config_path);
988 if (read == MSGSIZE - 1) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800989 debug(L"read_commands: %ls: not enough space for names\n", config_path);
Brian Curtin07165f72012-06-20 15:36:14 -0500990 }
991 key = keynames;
992 while (*key) {
993 read = GetPrivateProfileStringW(L"commands", key, NULL, value, MSGSIZE,
994 config_path);
995 if (read == MSGSIZE - 1) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800996 debug(L"read_commands: %ls: not enough space for %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500997 config_path, key);
998 }
999 cmdp = skip_whitespace(value);
1000 if (*cmdp) {
1001 cp = find_command(key);
1002 if (cp == NULL)
1003 add_command(key, value);
1004 else
1005 update_command(cp, key, value);
1006 }
1007 key += wcslen(key) + 1;
1008 }
1009}
1010
1011static void read_commands()
1012{
1013 if (launcher_ini_path[0])
1014 read_config_file(launcher_ini_path);
1015 if (appdata_ini_path[0])
1016 read_config_file(appdata_ini_path);
1017}
1018
1019static BOOL
1020parse_shebang(wchar_t * shebang_line, int nchars, wchar_t ** command,
Vinay Sajip22c039b2013-06-07 15:37:28 +01001021 wchar_t ** suffix, BOOL *search)
Brian Curtin07165f72012-06-20 15:36:14 -05001022{
1023 BOOL rc = FALSE;
Vinay Sajip22c039b2013-06-07 15:37:28 +01001024 SHEBANG * vpp;
Brian Curtin07165f72012-06-20 15:36:14 -05001025 size_t plen;
1026 wchar_t * p;
1027 wchar_t zapped;
1028 wchar_t * endp = shebang_line + nchars - 1;
1029 COMMAND * cp;
1030 wchar_t * skipped;
1031
1032 *command = NULL; /* failure return */
1033 *suffix = NULL;
Vinay Sajip22c039b2013-06-07 15:37:28 +01001034 *search = FALSE;
Brian Curtin07165f72012-06-20 15:36:14 -05001035
1036 if ((*shebang_line++ == L'#') && (*shebang_line++ == L'!')) {
1037 shebang_line = skip_whitespace(shebang_line);
1038 if (*shebang_line) {
1039 *command = shebang_line;
Vinay Sajip22c039b2013-06-07 15:37:28 +01001040 for (vpp = builtin_virtual_paths; vpp->shebang; ++vpp) {
1041 plen = wcslen(vpp->shebang);
1042 if (wcsncmp(shebang_line, vpp->shebang, plen) == 0) {
Brian Curtin07165f72012-06-20 15:36:14 -05001043 rc = TRUE;
Vinay Sajip22c039b2013-06-07 15:37:28 +01001044 *search = vpp->search;
Brian Curtin07165f72012-06-20 15:36:14 -05001045 /* We can do this because all builtin commands contain
1046 * "python".
1047 */
1048 *command = wcsstr(shebang_line, L"python");
1049 break;
1050 }
1051 }
Vinay Sajip22c039b2013-06-07 15:37:28 +01001052 if (vpp->shebang == NULL) {
Brian Curtin07165f72012-06-20 15:36:14 -05001053 /*
Vinay Sajip9c10d6b2013-11-15 20:58:13 +00001054 * Not found in builtins - look in customized commands.
Brian Curtin07165f72012-06-20 15:36:14 -05001055 *
1056 * We can't permanently modify the shebang line in case
Vinay Sajip9c10d6b2013-11-15 20:58:13 +00001057 * it's not a customized command, but we can temporarily
Brian Curtin07165f72012-06-20 15:36:14 -05001058 * stick a NUL after the command while searching for it,
1059 * then put back the char we zapped.
1060 */
1061#if defined(SKIP_PREFIX)
1062 skipped = skip_prefix(shebang_line);
1063#else
1064 skipped = shebang_line;
1065#endif
1066 p = wcspbrk(skipped, L" \t\r\n");
1067 if (p != NULL) {
1068 zapped = *p;
1069 *p = L'\0';
1070 }
1071 cp = find_command(skipped);
1072 if (p != NULL)
1073 *p = zapped;
1074 if (cp != NULL) {
1075 *command = cp->value;
1076 if (p != NULL)
1077 *suffix = skip_whitespace(p);
1078 }
1079 }
1080 /* remove trailing whitespace */
1081 while ((endp > shebang_line) && isspace(*endp))
1082 --endp;
1083 if (endp > shebang_line)
1084 endp[1] = L'\0';
1085 }
1086 }
1087 return rc;
1088}
1089
1090/* #define CP_UTF8 65001 defined in winnls.h */
1091#define CP_UTF16LE 1200
1092#define CP_UTF16BE 1201
1093#define CP_UTF32LE 12000
1094#define CP_UTF32BE 12001
1095
1096typedef struct {
1097 int length;
1098 char sequence[4];
1099 UINT code_page;
1100} BOM;
1101
1102/*
Vinay Sajipc985d082013-07-25 11:20:55 +01001103 * Strictly, we don't need to handle UTF-16 and UTF-32, since Python itself
Brian Curtin07165f72012-06-20 15:36:14 -05001104 * doesn't. Never mind, one day it might - there's no harm leaving it in.
1105 */
1106static BOM BOMs[] = {
1107 { 3, { 0xEF, 0xBB, 0xBF }, CP_UTF8 }, /* UTF-8 - keep first */
Serhiy Storchaka29e2aa62015-12-18 10:23:09 +02001108 /* Test UTF-32LE before UTF-16LE since UTF-16LE BOM is a prefix
1109 * of UTF-32LE BOM. */
Brian Curtin07165f72012-06-20 15:36:14 -05001110 { 4, { 0xFF, 0xFE, 0x00, 0x00 }, CP_UTF32LE }, /* UTF-32LE */
1111 { 4, { 0x00, 0x00, 0xFE, 0xFF }, CP_UTF32BE }, /* UTF-32BE */
Serhiy Storchaka29e2aa62015-12-18 10:23:09 +02001112 { 2, { 0xFF, 0xFE }, CP_UTF16LE }, /* UTF-16LE */
1113 { 2, { 0xFE, 0xFF }, CP_UTF16BE }, /* UTF-16BE */
Brian Curtin07165f72012-06-20 15:36:14 -05001114 { 0 } /* sentinel */
1115};
1116
1117static BOM *
1118find_BOM(char * buffer)
1119{
1120/*
1121 * Look for a BOM in the input and return a pointer to the
1122 * corresponding structure, or NULL if not found.
1123 */
1124 BOM * result = NULL;
1125 BOM *bom;
1126
1127 for (bom = BOMs; bom->length; bom++) {
1128 if (strncmp(bom->sequence, buffer, bom->length) == 0) {
1129 result = bom;
1130 break;
1131 }
1132 }
1133 return result;
1134}
1135
1136static char *
1137find_terminator(char * buffer, int len, BOM *bom)
1138{
1139 char * result = NULL;
1140 char * end = buffer + len;
1141 char * p;
1142 char c;
1143 int cp;
1144
1145 for (p = buffer; p < end; p++) {
1146 c = *p;
1147 if (c == '\r') {
1148 result = p;
1149 break;
1150 }
1151 if (c == '\n') {
1152 result = p;
1153 break;
1154 }
1155 }
1156 if (result != NULL) {
1157 cp = bom->code_page;
1158
1159 /* adjustments to include all bytes of the char */
1160 /* no adjustment needed for UTF-8 or big endian */
1161 if (cp == CP_UTF16LE)
1162 ++result;
1163 else if (cp == CP_UTF32LE)
1164 result += 3;
1165 ++result; /* point just past terminator */
1166 }
1167 return result;
1168}
1169
1170static BOOL
1171validate_version(wchar_t * p)
1172{
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +01001173 /*
Brendan Gerrity3876af42018-09-04 09:35:46 -07001174 Version information should start with the major version,
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +01001175 Optionally followed by a period and a minor version,
1176 Optionally followed by a minus and one of 32 or 64.
1177 Valid examples:
1178 2
1179 3
1180 2.7
1181 3.6
1182 2.7-32
1183 The intent is to add to the valid patterns:
1184 3.10
1185 3-32
1186 3.6-64
1187 3-64
1188 */
1189 BOOL result = (p != NULL); /* Default to False if null pointer. */
Brian Curtin07165f72012-06-20 15:36:14 -05001190
Brendan Gerrity3876af42018-09-04 09:35:46 -07001191 result = result && iswdigit(*p); /* Result = False if first string element is not a digit. */
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +01001192
1193 while (result && iswdigit(*p)) /* Require a major version */
1194 ++p; /* Skip all leading digit(s) */
1195 if (result && (*p == L'.')) /* Allow . for major minor separator.*/
1196 {
1197 result = iswdigit(*++p); /* Must be at least one digit */
1198 while (result && iswdigit(*++p)) ; /* Skip any more Digits */
1199 }
1200 if (result && (*p == L'-')) { /* Allow - for Bits Separator */
1201 switch(*++p){
1202 case L'3': /* 3 is OK */
1203 result = (*++p == L'2') && !*++p; /* only if followed by 2 and ended.*/
1204 break;
1205 case L'6': /* 6 is OK */
1206 result = (*++p == L'4') && !*++p; /* only if followed by 4 and ended.*/
1207 break;
1208 default:
Brian Curtin07165f72012-06-20 15:36:14 -05001209 result = FALSE;
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +01001210 break;
Brian Curtin07165f72012-06-20 15:36:14 -05001211 }
1212 }
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +01001213 result = result && !*p; /* Must have reached EOS */
Brian Curtin07165f72012-06-20 15:36:14 -05001214 return result;
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +01001215
Brian Curtin07165f72012-06-20 15:36:14 -05001216}
1217
1218typedef struct {
1219 unsigned short min;
1220 unsigned short max;
1221 wchar_t version[MAX_VERSION_SIZE];
1222} PYC_MAGIC;
1223
1224static PYC_MAGIC magic_values[] = {
Steve Dower7ae61af2016-05-16 09:34:20 -07001225 { 50823, 50823, L"2.0" },
1226 { 60202, 60202, L"2.1" },
1227 { 60717, 60717, L"2.2" },
1228 { 62011, 62021, L"2.3" },
1229 { 62041, 62061, L"2.4" },
1230 { 62071, 62131, L"2.5" },
1231 { 62151, 62161, L"2.6" },
1232 { 62171, 62211, L"2.7" },
1233 { 3000, 3131, L"3.0" },
1234 { 3141, 3151, L"3.1" },
1235 { 3160, 3180, L"3.2" },
1236 { 3190, 3230, L"3.3" },
1237 { 3250, 3310, L"3.4" },
Serhiy Storchaka3c317e72016-06-12 09:22:01 +03001238 { 3320, 3351, L"3.5" },
Nick Coghlan944368e2016-09-11 14:45:49 +10001239 { 3360, 3379, L"3.6" },
Yury Selivanovf2392132016-12-13 19:03:51 -05001240 { 3390, 3399, L"3.7" },
Serhiy Storchakaed146b52019-08-24 13:41:53 +03001241 { 3400, 3419, L"3.8" },
Brian Curtin07165f72012-06-20 15:36:14 -05001242 { 0 }
1243};
1244
1245static INSTALLED_PYTHON *
1246find_by_magic(unsigned short magic)
1247{
1248 INSTALLED_PYTHON * result = NULL;
1249 PYC_MAGIC * mp;
1250
1251 for (mp = magic_values; mp->min; mp++) {
1252 if ((magic >= mp->min) && (magic <= mp->max)) {
Paul Moore835416c2016-05-22 12:28:41 +01001253 result = locate_python(mp->version, FALSE);
Brian Curtin07165f72012-06-20 15:36:14 -05001254 if (result != NULL)
1255 break;
1256 }
1257 }
1258 return result;
1259}
1260
1261static void
1262maybe_handle_shebang(wchar_t ** argv, wchar_t * cmdline)
1263{
1264/*
1265 * Look for a shebang line in the first argument. If found
1266 * and we spawn a child process, this never returns. If it
1267 * does return then we process the args "normally".
1268 *
1269 * argv[0] might be a filename with a shebang.
1270 */
1271 FILE * fp;
1272 errno_t rc = _wfopen_s(&fp, *argv, L"rb");
Serhiy Storchakaf8ed0042015-12-18 10:19:30 +02001273 char buffer[BUFSIZE];
Brian Curtin07165f72012-06-20 15:36:14 -05001274 wchar_t shebang_line[BUFSIZE + 1];
1275 size_t read;
1276 char *p;
1277 char * start;
1278 char * shebang_alias = (char *) shebang_line;
1279 BOM* bom;
1280 int i, j, nchars = 0;
1281 int header_len;
1282 BOOL is_virt;
Vinay Sajip22c039b2013-06-07 15:37:28 +01001283 BOOL search;
Brian Curtin07165f72012-06-20 15:36:14 -05001284 wchar_t * command;
1285 wchar_t * suffix;
Vinay Sajip22c039b2013-06-07 15:37:28 +01001286 COMMAND *cmd = NULL;
Brian Curtin07165f72012-06-20 15:36:14 -05001287 INSTALLED_PYTHON * ip;
1288
1289 if (rc == 0) {
1290 read = fread(buffer, sizeof(char), BUFSIZE, fp);
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02001291 debug(L"maybe_handle_shebang: read %zd bytes\n", read);
Brian Curtin07165f72012-06-20 15:36:14 -05001292 fclose(fp);
1293
1294 if ((read >= 4) && (buffer[3] == '\n') && (buffer[2] == '\r')) {
Serhiy Storchakaf8ed0042015-12-18 10:19:30 +02001295 ip = find_by_magic((((unsigned char)buffer[1]) << 8 |
1296 (unsigned char)buffer[0]) & 0xFFFF);
Brian Curtin07165f72012-06-20 15:36:14 -05001297 if (ip != NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001298 debug(L"script file is compiled against Python %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -05001299 ip->version);
1300 invoke_child(ip->executable, NULL, cmdline);
1301 }
1302 }
1303 /* Look for BOM */
1304 bom = find_BOM(buffer);
1305 if (bom == NULL) {
1306 start = buffer;
1307 debug(L"maybe_handle_shebang: BOM not found, using UTF-8\n");
1308 bom = BOMs; /* points to UTF-8 entry - the default */
1309 }
1310 else {
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02001311 debug(L"maybe_handle_shebang: BOM found, code page %u\n",
Brian Curtin07165f72012-06-20 15:36:14 -05001312 bom->code_page);
1313 start = &buffer[bom->length];
1314 }
1315 p = find_terminator(start, BUFSIZE, bom);
1316 /*
1317 * If no CR or LF was found in the heading,
1318 * we assume it's not a shebang file.
1319 */
1320 if (p == NULL) {
1321 debug(L"maybe_handle_shebang: No line terminator found\n");
1322 }
1323 else {
1324 /*
1325 * Found line terminator - parse the shebang.
1326 *
1327 * Strictly, we don't need to handle UTF-16 anf UTF-32,
1328 * since Python itself doesn't.
1329 * Never mind, one day it might.
1330 */
1331 header_len = (int) (p - start);
1332 switch(bom->code_page) {
1333 case CP_UTF8:
1334 nchars = MultiByteToWideChar(bom->code_page,
1335 0,
1336 start, header_len, shebang_line,
1337 BUFSIZE);
1338 break;
1339 case CP_UTF16BE:
1340 if (header_len % 2 != 0) {
1341 debug(L"maybe_handle_shebang: UTF-16BE, but an odd number \
1342of bytes: %d\n", header_len);
1343 /* nchars = 0; Not needed - initialised to 0. */
1344 }
1345 else {
1346 for (i = header_len; i > 0; i -= 2) {
1347 shebang_alias[i - 1] = start[i - 2];
1348 shebang_alias[i - 2] = start[i - 1];
1349 }
1350 nchars = header_len / sizeof(wchar_t);
1351 }
1352 break;
1353 case CP_UTF16LE:
1354 if ((header_len % 2) != 0) {
1355 debug(L"UTF-16LE, but an odd number of bytes: %d\n",
1356 header_len);
1357 /* nchars = 0; Not needed - initialised to 0. */
1358 }
1359 else {
1360 /* no actual conversion needed. */
1361 memcpy(shebang_line, start, header_len);
1362 nchars = header_len / sizeof(wchar_t);
1363 }
1364 break;
1365 case CP_UTF32BE:
1366 if (header_len % 4 != 0) {
1367 debug(L"UTF-32BE, but not divisible by 4: %d\n",
1368 header_len);
1369 /* nchars = 0; Not needed - initialised to 0. */
1370 }
1371 else {
1372 for (i = header_len, j = header_len / 2; i > 0; i -= 4,
1373 j -= 2) {
1374 shebang_alias[j - 1] = start[i - 2];
1375 shebang_alias[j - 2] = start[i - 1];
1376 }
1377 nchars = header_len / sizeof(wchar_t);
1378 }
1379 break;
1380 case CP_UTF32LE:
1381 if (header_len % 4 != 0) {
1382 debug(L"UTF-32LE, but not divisible by 4: %d\n",
1383 header_len);
1384 /* nchars = 0; Not needed - initialised to 0. */
1385 }
1386 else {
1387 for (i = header_len, j = header_len / 2; i > 0; i -= 4,
1388 j -= 2) {
1389 shebang_alias[j - 1] = start[i - 3];
1390 shebang_alias[j - 2] = start[i - 4];
1391 }
1392 nchars = header_len / sizeof(wchar_t);
1393 }
1394 break;
1395 }
1396 if (nchars > 0) {
1397 shebang_line[--nchars] = L'\0';
1398 is_virt = parse_shebang(shebang_line, nchars, &command,
Vinay Sajip22c039b2013-06-07 15:37:28 +01001399 &suffix, &search);
Brian Curtin07165f72012-06-20 15:36:14 -05001400 if (command != NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001401 debug(L"parse_shebang: found command: %ls\n", command);
Brian Curtin07165f72012-06-20 15:36:14 -05001402 if (!is_virt) {
1403 invoke_child(command, suffix, cmdline);
1404 }
1405 else {
1406 suffix = wcschr(command, L' ');
1407 if (suffix != NULL) {
1408 *suffix++ = L'\0';
1409 suffix = skip_whitespace(suffix);
1410 }
1411 if (wcsncmp(command, L"python", 6))
1412 error(RC_BAD_VIRTUAL_PATH, L"Unknown virtual \
Steve Dower84bcfb32015-01-02 18:07:46 -08001413path '%ls'", command);
Brian Curtin07165f72012-06-20 15:36:14 -05001414 command += 6; /* skip past "python" */
Vinay Sajip22c039b2013-06-07 15:37:28 +01001415 if (search && ((*command == L'\0') || isspace(*command))) {
1416 /* Command is eligible for path search, and there
1417 * is no version specification.
1418 */
1419 debug(L"searching PATH for python executable\n");
Vinay Sajipa5892ab2015-12-26 13:10:51 +00001420 cmd = find_on_path(PYTHON_EXECUTABLE);
Steve Dower84bcfb32015-01-02 18:07:46 -08001421 debug(L"Python on path: %ls\n", cmd ? cmd->value : L"<not found>");
Vinay Sajip22c039b2013-06-07 15:37:28 +01001422 if (cmd) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001423 debug(L"located python on PATH: %ls\n", cmd->value);
Vinay Sajip22c039b2013-06-07 15:37:28 +01001424 invoke_child(cmd->value, suffix, cmdline);
1425 /* Exit here, as we have found the command */
1426 return;
1427 }
1428 /* FALL THROUGH: No python found on PATH, so fall
1429 * back to locating the correct installed python.
1430 */
1431 }
Brian Curtin07165f72012-06-20 15:36:14 -05001432 if (*command && !validate_version(command))
1433 error(RC_BAD_VIRTUAL_PATH, L"Invalid version \
Steve Dower84bcfb32015-01-02 18:07:46 -08001434specification: '%ls'.\nIn the first line of the script, 'python' needs to be \
Brian Curtin07165f72012-06-20 15:36:14 -05001435followed by a valid version specifier.\nPlease check the documentation.",
1436 command);
1437 /* TODO could call validate_version(command) */
Paul Moore835416c2016-05-22 12:28:41 +01001438 ip = locate_python(command, TRUE);
Brian Curtin07165f72012-06-20 15:36:14 -05001439 if (ip == NULL) {
1440 error(RC_NO_PYTHON, L"Requested Python version \
Steve Dower84bcfb32015-01-02 18:07:46 -08001441(%ls) is not installed", command);
Brian Curtin07165f72012-06-20 15:36:14 -05001442 }
1443 else {
1444 invoke_child(ip->executable, suffix, cmdline);
1445 }
1446 }
1447 }
1448 }
1449 }
1450 }
1451}
1452
1453static wchar_t *
1454skip_me(wchar_t * cmdline)
1455{
1456 BOOL quoted;
1457 wchar_t c;
1458 wchar_t * result = cmdline;
1459
1460 quoted = cmdline[0] == L'\"';
1461 if (!quoted)
1462 c = L' ';
1463 else {
1464 c = L'\"';
1465 ++result;
1466 }
1467 result = wcschr(result, c);
1468 if (result == NULL) /* when, for example, just exe name on command line */
1469 result = L"";
1470 else {
1471 ++result; /* skip past space or closing quote */
1472 result = skip_whitespace(result);
1473 }
1474 return result;
1475}
1476
1477static DWORD version_high = 0;
1478static DWORD version_low = 0;
1479
1480static void
1481get_version_info(wchar_t * version_text, size_t size)
1482{
1483 WORD maj, min, rel, bld;
1484
1485 if (!version_high && !version_low)
1486 wcsncpy_s(version_text, size, L"0.1", _TRUNCATE); /* fallback */
1487 else {
1488 maj = HIWORD(version_high);
1489 min = LOWORD(version_high);
1490 rel = HIWORD(version_low);
1491 bld = LOWORD(version_low);
1492 _snwprintf_s(version_text, size, _TRUNCATE, L"%d.%d.%d.%d", maj,
1493 min, rel, bld);
1494 }
1495}
1496
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001497static void
1498show_help_text(wchar_t ** argv)
1499{
1500 wchar_t version_text [MAX_PATH];
1501#if defined(_M_X64)
1502 BOOL canDo64bit = TRUE;
1503#else
1504 /* If we are a 32bit process on a 64bit Windows, first hit the 64bit keys. */
1505 BOOL canDo64bit = FALSE;
1506 IsWow64Process(GetCurrentProcess(), &canDo64bit);
1507#endif
1508
1509 get_version_info(version_text, MAX_PATH);
1510 fwprintf(stdout, L"\
1511Python Launcher for Windows Version %ls\n\n", version_text);
1512 fwprintf(stdout, L"\
1513usage:\n\
1514%ls [launcher-args] [python-args] script [script-args]\n\n", argv[0]);
1515 fputws(L"\
1516Launcher arguments:\n\n\
1517-2 : Launch the latest Python 2.x version\n\
1518-3 : Launch the latest Python 3.x version\n\
1519-X.Y : Launch the specified Python version\n", stdout);
1520 if (canDo64bit) {
1521 fputws(L"\
1522 The above all default to 64 bit if a matching 64 bit python is present.\n\
1523-X.Y-32: Launch the specified 32bit Python version\n\
1524-X-32 : Launch the latest 32bit Python X version\n\
1525-X.Y-64: Launch the specified 64bit Python version\n\
1526-X-64 : Launch the latest 64bit Python X version", stdout);
1527 }
1528 fputws(L"\n-0 --list : List the available pythons", stdout);
1529 fputws(L"\n-0p --list-paths : List with paths", stdout);
1530 fputws(L"\n\nThe following help text is from Python:\n\n", stdout);
1531 fflush(stdout);
1532}
1533
1534static BOOL
1535show_python_list(wchar_t ** argv)
1536{
1537 /*
1538 * Display options -0
1539 */
1540 INSTALLED_PYTHON * result = NULL;
1541 INSTALLED_PYTHON * ip = installed_pythons; /* List of installed pythons */
1542 INSTALLED_PYTHON * defpy = locate_python(L"", FALSE);
1543 size_t i = 0;
1544 wchar_t *p = argv[1];
Miss Islington (bot)664d56a2019-09-12 10:36:14 -07001545 wchar_t *ver_fmt = L"-%ls-%d";
1546 wchar_t *fmt = L"\n %ls";
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001547 wchar_t *defind = L" *"; /* Default indicator */
1548
1549 /*
1550 * Output informational messages to stderr to keep output
1551 * clean for use in pipes, etc.
1552 */
1553 fwprintf(stderr,
1554 L"Installed Pythons found by %s Launcher for Windows", argv[0]);
Miss Islington (bot)664d56a2019-09-12 10:36:14 -07001555 if (!_wcsicmp(p, L"-0p") || !_wcsicmp(p, L"--list-paths"))
1556 fmt = L"\n %-15ls%ls"; /* include path */
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001557
1558 if (num_installed_pythons == 0) /* We have somehow got here without searching for pythons */
1559 locate_all_pythons(); /* Find them, Populates installed_pythons */
1560
1561 if (num_installed_pythons == 0) /* No pythons found */
1562 fwprintf(stderr, L"\nNo Installed Pythons Found!");
1563 else
1564 {
1565 for (i = 0; i < num_installed_pythons; i++, ip++) {
Miss Islington (bot)664d56a2019-09-12 10:36:14 -07001566 wchar_t version[BUFSIZ];
1567 if (wcscmp(ip->version, L"venv") == 0) {
1568 wcscpy_s(version, BUFSIZ, L"(venv)");
1569 }
1570 else {
1571 swprintf_s(version, BUFSIZ, ver_fmt, ip->version, ip->bits);
1572 }
1573
1574 if (ip->exe_display[0]) {
1575 fwprintf(stdout, fmt, version, ip->exe_display);
1576 }
1577 else {
1578 fwprintf(stdout, fmt, version, ip->executable);
1579 }
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001580 /* If there is a default indicate it */
Miss Islington (bot)664d56a2019-09-12 10:36:14 -07001581 if (defpy == ip)
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001582 fwprintf(stderr, defind);
1583 }
1584 }
1585
1586 if ((defpy == NULL) && (num_installed_pythons > 0))
1587 /* We have pythons but none is the default */
1588 fwprintf(stderr, L"\n\nCan't find a Default Python.\n\n");
1589 else
1590 fwprintf(stderr, L"\n\n"); /* End with a blank line */
Brendan Gerrityc8fe9cc2018-11-20 13:28:27 -08001591 return FALSE; /* If this has been called we cannot continue */
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001592}
1593
Steve Dower1c3de542018-12-10 08:11:21 -08001594#if defined(VENV_REDIRECT)
1595
1596static int
1597find_home_value(const char *buffer, const char **start, DWORD *length)
1598{
1599 for (const char *s = strstr(buffer, "home"); s; s = strstr(s + 1, "\nhome")) {
1600 if (*s == '\n') {
1601 ++s;
1602 }
1603 for (int i = 4; i > 0 && *s; --i, ++s);
1604
1605 while (*s && iswspace(*s)) {
1606 ++s;
1607 }
1608 if (*s != L'=') {
1609 continue;
1610 }
1611
1612 do {
1613 ++s;
1614 } while (*s && iswspace(*s));
1615
1616 *start = s;
1617 char *nl = strchr(s, '\n');
1618 if (nl) {
1619 *length = (DWORD)((ptrdiff_t)nl - (ptrdiff_t)s);
1620 } else {
1621 *length = (DWORD)strlen(s);
1622 }
1623 return 1;
1624 }
1625 return 0;
1626}
1627#endif
1628
1629static wchar_t *
1630wcsdup_pad(const wchar_t *s, int padding, int *newlen)
1631{
1632 size_t len = wcslen(s);
1633 len += 1 + padding;
1634 wchar_t *r = (wchar_t *)malloc(len * sizeof(wchar_t));
1635 if (!r) {
1636 return NULL;
1637 }
1638 if (wcscpy_s(r, len, s)) {
1639 free(r);
1640 return NULL;
1641 }
1642 *newlen = len < MAXINT ? (int)len : MAXINT;
1643 return r;
1644}
1645
1646static wchar_t *
1647get_process_name()
1648{
1649 DWORD bufferLen = MAX_PATH;
1650 DWORD len = bufferLen;
1651 wchar_t *r = NULL;
1652
1653 while (!r) {
1654 r = (wchar_t *)malloc(bufferLen * sizeof(wchar_t));
1655 if (!r) {
1656 error(RC_NO_MEMORY, L"out of memory");
1657 return NULL;
1658 }
1659 len = GetModuleFileNameW(NULL, r, bufferLen);
1660 if (len == 0) {
1661 free(r);
1662 error(0, L"Failed to get module name");
1663 return NULL;
1664 } else if (len == bufferLen &&
1665 GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
1666 free(r);
1667 r = NULL;
1668 bufferLen *= 2;
1669 }
1670 }
1671
1672 return r;
1673}
1674
Brian Curtin07165f72012-06-20 15:36:14 -05001675static int
1676process(int argc, wchar_t ** argv)
1677{
1678 wchar_t * wp;
1679 wchar_t * command;
Steve Dower76998fe2015-02-26 14:25:33 -08001680 wchar_t * executable;
Brian Curtin07165f72012-06-20 15:36:14 -05001681 wchar_t * p;
Steve Dower1c3de542018-12-10 08:11:21 -08001682 wchar_t * argv0;
Brian Curtin07165f72012-06-20 15:36:14 -05001683 int rc = 0;
Brian Curtin07165f72012-06-20 15:36:14 -05001684 INSTALLED_PYTHON * ip;
1685 BOOL valid;
1686 DWORD size, attrs;
Brian Curtin07165f72012-06-20 15:36:14 -05001687 wchar_t message[MSGSIZE];
Brian Curtin07165f72012-06-20 15:36:14 -05001688 void * version_data;
1689 VS_FIXEDFILEINFO * file_info;
1690 UINT block_size;
Steve Dower1c3de542018-12-10 08:11:21 -08001691#if defined(VENV_REDIRECT)
1692 wchar_t * venv_cfg_path;
Vinay Sajipc985d082013-07-25 11:20:55 +01001693 int newlen;
Steve Dower1c3de542018-12-10 08:11:21 -08001694#elif defined(SCRIPT_WRAPPER)
Vinay Sajipc985d082013-07-25 11:20:55 +01001695 wchar_t * newcommand;
1696 wchar_t * av[2];
Steve Dower1c3de542018-12-10 08:11:21 -08001697 int newlen;
1698 HRESULT hr;
1699 int index;
1700#else
1701 HRESULT hr;
1702 int index;
Vinay Sajipc985d082013-07-25 11:20:55 +01001703#endif
Brian Curtin07165f72012-06-20 15:36:14 -05001704
Vinay Sajipaab9f462015-12-26 12:35:47 +00001705 setvbuf(stderr, (char *)NULL, _IONBF, 0);
Brian Curtin07165f72012-06-20 15:36:14 -05001706 wp = get_env(L"PYLAUNCH_DEBUG");
1707 if ((wp != NULL) && (*wp != L'\0'))
1708 log_fp = stderr;
1709
1710#if defined(_M_X64)
1711 debug(L"launcher build: 64bit\n");
1712#else
1713 debug(L"launcher build: 32bit\n");
1714#endif
1715#if defined(_WINDOWS)
1716 debug(L"launcher executable: Windows\n");
1717#else
1718 debug(L"launcher executable: Console\n");
1719#endif
Steve Dower1c3de542018-12-10 08:11:21 -08001720#if !defined(VENV_REDIRECT)
Brian Curtin07165f72012-06-20 15:36:14 -05001721 /* Get the local appdata folder (non-roaming) */
1722 hr = SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA,
1723 NULL, 0, appdata_ini_path);
1724 if (hr != S_OK) {
1725 debug(L"SHGetFolderPath failed: %X\n", hr);
1726 appdata_ini_path[0] = L'\0';
1727 }
1728 else {
Steve Dower1c3de542018-12-10 08:11:21 -08001729 wcsncat_s(appdata_ini_path, MAX_PATH, L"\\py.ini", _TRUNCATE);
Brian Curtin07165f72012-06-20 15:36:14 -05001730 attrs = GetFileAttributesW(appdata_ini_path);
1731 if (attrs == INVALID_FILE_ATTRIBUTES) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001732 debug(L"File '%ls' non-existent\n", appdata_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001733 appdata_ini_path[0] = L'\0';
1734 } else {
Steve Dower84bcfb32015-01-02 18:07:46 -08001735 debug(L"Using local configuration file '%ls'\n", appdata_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001736 }
1737 }
Steve Dower1c3de542018-12-10 08:11:21 -08001738#endif
1739 argv0 = get_process_name();
1740 size = GetFileVersionInfoSizeW(argv0, &size);
Brian Curtin07165f72012-06-20 15:36:14 -05001741 if (size == 0) {
1742 winerror(GetLastError(), message, MSGSIZE);
Steve Dower84bcfb32015-01-02 18:07:46 -08001743 debug(L"GetFileVersionInfoSize failed: %ls\n", message);
Brian Curtin07165f72012-06-20 15:36:14 -05001744 }
1745 else {
1746 version_data = malloc(size);
1747 if (version_data) {
Steve Dower1c3de542018-12-10 08:11:21 -08001748 valid = GetFileVersionInfoW(argv0, 0, size,
Brian Curtin07165f72012-06-20 15:36:14 -05001749 version_data);
1750 if (!valid)
1751 debug(L"GetFileVersionInfo failed: %X\n", GetLastError());
1752 else {
Vinay Sajip404229b2013-01-29 22:52:57 +00001753 valid = VerQueryValueW(version_data, L"\\",
1754 (LPVOID *) &file_info, &block_size);
Brian Curtin07165f72012-06-20 15:36:14 -05001755 if (!valid)
1756 debug(L"VerQueryValue failed: %X\n", GetLastError());
1757 else {
1758 version_high = file_info->dwFileVersionMS;
1759 version_low = file_info->dwFileVersionLS;
1760 }
1761 }
1762 free(version_data);
1763 }
1764 }
Steve Dower1c3de542018-12-10 08:11:21 -08001765
1766#if defined(VENV_REDIRECT)
1767 /* Allocate some extra space for new filenames */
1768 venv_cfg_path = wcsdup_pad(argv0, 32, &newlen);
1769 if (!venv_cfg_path) {
1770 error(RC_NO_MEMORY, L"Failed to copy module name");
1771 }
1772 p = wcsrchr(venv_cfg_path, L'\\');
1773
1774 if (p == NULL) {
1775 error(RC_NO_VENV_CFG, L"No pyvenv.cfg file");
1776 }
1777 p[0] = L'\0';
1778 wcscat_s(venv_cfg_path, newlen, L"\\pyvenv.cfg");
1779 attrs = GetFileAttributesW(venv_cfg_path);
1780 if (attrs == INVALID_FILE_ATTRIBUTES) {
1781 debug(L"File '%ls' non-existent\n", venv_cfg_path);
1782 p[0] = '\0';
1783 p = wcsrchr(venv_cfg_path, L'\\');
1784 if (p != NULL) {
1785 p[0] = '\0';
1786 wcscat_s(venv_cfg_path, newlen, L"\\pyvenv.cfg");
1787 attrs = GetFileAttributesW(venv_cfg_path);
1788 if (attrs == INVALID_FILE_ATTRIBUTES) {
1789 debug(L"File '%ls' non-existent\n", venv_cfg_path);
1790 error(RC_NO_VENV_CFG, L"No pyvenv.cfg file");
1791 }
1792 }
1793 }
1794 debug(L"Using venv configuration file '%ls'\n", venv_cfg_path);
1795#else
1796 /* Allocate some extra space for new filenames */
1797 if (wcscpy_s(launcher_ini_path, MAX_PATH, argv0)) {
1798 error(RC_NO_MEMORY, L"Failed to copy module name");
1799 }
Brian Curtin07165f72012-06-20 15:36:14 -05001800 p = wcsrchr(launcher_ini_path, L'\\');
Steve Dower1c3de542018-12-10 08:11:21 -08001801
Brian Curtin07165f72012-06-20 15:36:14 -05001802 if (p == NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001803 debug(L"GetModuleFileNameW returned value has no backslash: %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -05001804 launcher_ini_path);
1805 launcher_ini_path[0] = L'\0';
1806 }
1807 else {
Steve Dower1c3de542018-12-10 08:11:21 -08001808 p[0] = L'\0';
1809 wcscat_s(launcher_ini_path, MAX_PATH, L"\\py.ini");
Brian Curtin07165f72012-06-20 15:36:14 -05001810 attrs = GetFileAttributesW(launcher_ini_path);
1811 if (attrs == INVALID_FILE_ATTRIBUTES) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001812 debug(L"File '%ls' non-existent\n", launcher_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001813 launcher_ini_path[0] = L'\0';
1814 } else {
Steve Dower84bcfb32015-01-02 18:07:46 -08001815 debug(L"Using global configuration file '%ls'\n", launcher_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001816 }
1817 }
Steve Dower1c3de542018-12-10 08:11:21 -08001818#endif
Brian Curtin07165f72012-06-20 15:36:14 -05001819
1820 command = skip_me(GetCommandLineW());
Steve Dower84bcfb32015-01-02 18:07:46 -08001821 debug(L"Called with command line: %ls\n", command);
Vinay Sajipc985d082013-07-25 11:20:55 +01001822
Steve Doweradad9e62019-01-25 14:59:58 -08001823#if !defined(VENV_REDIRECT)
1824 /* bpo-35811: The __PYVENV_LAUNCHER__ variable is used to
1825 * override sys.executable and locate the original prefix path.
1826 * However, if it is silently inherited by a non-venv Python
1827 * process, that process will believe it is running in the venv
1828 * still. This is the only place where *we* can clear it (that is,
1829 * when py.exe is being used to launch Python), so we do.
1830 */
1831 SetEnvironmentVariableW(L"__PYVENV_LAUNCHER__", NULL);
1832#endif
1833
Vinay Sajipc985d082013-07-25 11:20:55 +01001834#if defined(SCRIPT_WRAPPER)
1835 /* The launcher is being used in "script wrapper" mode.
1836 * There should therefore be a Python script named <exename>-script.py in
1837 * the same directory as the launcher executable.
1838 * Put the script name into argv as the first (script name) argument.
1839 */
1840
1841 /* Get the wrapped script name - if the script is not present, this will
1842 * terminate the program with an error.
1843 */
1844 locate_wrapped_script();
1845
1846 /* Add the wrapped script to the start of command */
1847 newlen = wcslen(wrapped_script_path) + wcslen(command) + 2; /* ' ' + NUL */
1848 newcommand = malloc(sizeof(wchar_t) * newlen);
1849 if (!newcommand) {
1850 error(RC_NO_MEMORY, L"Could not allocate new command line");
1851 }
1852 else {
1853 wcscpy_s(newcommand, newlen, wrapped_script_path);
1854 wcscat_s(newcommand, newlen, L" ");
1855 wcscat_s(newcommand, newlen, command);
Steve Dower84bcfb32015-01-02 18:07:46 -08001856 debug(L"Running wrapped script with command line '%ls'\n", newcommand);
Vinay Sajipc985d082013-07-25 11:20:55 +01001857 read_commands();
1858 av[0] = wrapped_script_path;
1859 av[1] = NULL;
1860 maybe_handle_shebang(av, newcommand);
1861 /* Returns if no shebang line - pass to default processing */
1862 command = newcommand;
1863 valid = FALSE;
1864 }
Steve Dower1c3de542018-12-10 08:11:21 -08001865#elif defined(VENV_REDIRECT)
1866 {
1867 FILE *f;
1868 char buffer[4096]; /* 4KB should be enough for anybody */
1869 char *start;
1870 DWORD len, cch, cch_actual;
1871 size_t cb;
1872 if (_wfopen_s(&f, venv_cfg_path, L"r")) {
1873 error(RC_BAD_VENV_CFG, L"Cannot read '%ls'", venv_cfg_path);
1874 }
1875 cb = fread_s(buffer, sizeof(buffer), sizeof(buffer[0]),
1876 sizeof(buffer) / sizeof(buffer[0]), f);
1877 fclose(f);
1878
1879 if (!find_home_value(buffer, &start, &len)) {
1880 error(RC_BAD_VENV_CFG, L"Cannot find home in '%ls'",
1881 venv_cfg_path);
1882 }
1883
1884 cch = MultiByteToWideChar(CP_UTF8, 0, start, len, NULL, 0);
1885 if (!cch) {
1886 error(0, L"Cannot determine memory for home path");
1887 }
1888 cch += (DWORD)wcslen(PYTHON_EXECUTABLE) + 1 + 1; /* include sep and null */
1889 executable = (wchar_t *)malloc(cch * sizeof(wchar_t));
1890 if (executable == NULL) {
1891 error(RC_NO_MEMORY, L"A memory allocation failed");
1892 }
1893 cch_actual = MultiByteToWideChar(CP_UTF8, 0, start, len, executable, cch);
1894 if (!cch_actual) {
1895 error(RC_BAD_VENV_CFG, L"Cannot decode home path in '%ls'",
1896 venv_cfg_path);
1897 }
1898 if (executable[cch_actual - 1] != L'\\') {
1899 executable[cch_actual++] = L'\\';
1900 executable[cch_actual] = L'\0';
1901 }
1902 if (wcscat_s(executable, cch, PYTHON_EXECUTABLE)) {
1903 error(RC_BAD_VENV_CFG, L"Cannot create executable path from '%ls'",
1904 venv_cfg_path);
1905 }
1906 if (GetFileAttributesW(executable) == INVALID_FILE_ATTRIBUTES) {
1907 error(RC_NO_PYTHON, L"No Python at '%ls'", executable);
1908 }
1909 if (!SetEnvironmentVariableW(L"__PYVENV_LAUNCHER__", argv0)) {
1910 error(0, L"Failed to set launcher environment");
1911 }
1912 valid = 1;
1913 }
Vinay Sajipc985d082013-07-25 11:20:55 +01001914#else
Brian Curtin07165f72012-06-20 15:36:14 -05001915 if (argc <= 1) {
1916 valid = FALSE;
1917 p = NULL;
1918 }
1919 else {
1920 p = argv[1];
Brendan Gerrityc8fe9cc2018-11-20 13:28:27 -08001921 if ((argc == 2) && // list version args
1922 (!wcsncmp(p, L"-0", wcslen(L"-0")) ||
Brendan Gerrityaada63b2018-08-31 08:15:42 -07001923 !wcsncmp(p, L"--list", wcslen(L"--list"))))
1924 {
Brendan Gerrityc8fe9cc2018-11-20 13:28:27 -08001925 show_python_list(argv);
1926 return rc;
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001927 }
1928 valid = valid && (*p == L'-') && validate_version(&p[1]);
Brian Curtin07165f72012-06-20 15:36:14 -05001929 if (valid) {
Paul Moore835416c2016-05-22 12:28:41 +01001930 ip = locate_python(&p[1], FALSE);
Brian Curtin07165f72012-06-20 15:36:14 -05001931 if (ip == NULL)
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001932 {
1933 fwprintf(stdout, \
1934 L"Python %ls not found!\n", &p[1]);
1935 valid = show_python_list(argv);
Steve Dower84bcfb32015-01-02 18:07:46 -08001936 error(RC_NO_PYTHON, L"Requested Python version (%ls) not \
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001937installed, use -0 for available pythons", &p[1]);
1938 }
Steve Dower76998fe2015-02-26 14:25:33 -08001939 executable = ip->executable;
Brian Curtin07165f72012-06-20 15:36:14 -05001940 command += wcslen(p);
1941 command = skip_whitespace(command);
1942 }
Vinay Sajip2ae8c632013-01-29 22:29:25 +00001943 else {
1944 for (index = 1; index < argc; ++index) {
1945 if (*argv[index] != L'-')
1946 break;
1947 }
1948 if (index < argc) {
1949 read_commands();
1950 maybe_handle_shebang(&argv[index], command);
1951 }
1952 }
Brian Curtin07165f72012-06-20 15:36:14 -05001953 }
Vinay Sajipc985d082013-07-25 11:20:55 +01001954#endif
1955
Brian Curtin07165f72012-06-20 15:36:14 -05001956 if (!valid) {
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001957 if ((argc == 2) && (!_wcsicmp(p, L"-h") || !_wcsicmp(p, L"--help")))
1958 show_help_text(argv);
Brendan Gerrityaada63b2018-08-31 08:15:42 -07001959 if ((argc == 2) &&
1960 (!_wcsicmp(p, L"-0") || !_wcsicmp(p, L"--list") ||
1961 !_wcsicmp(p, L"-0p") || !_wcsicmp(p, L"--list-paths")))
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001962 {
Brendan Gerrityaada63b2018-08-31 08:15:42 -07001963 executable = NULL; /* Info call only */
1964 }
1965 else {
Miss Islington (bot)664d56a2019-09-12 10:36:14 -07001966 /* look for the default Python */
1967 ip = locate_python(L"", FALSE);
1968 if (ip == NULL)
1969 error(RC_NO_PYTHON, L"Can't find a default Python.");
1970 executable = ip->executable;
Brian Curtin07165f72012-06-20 15:36:14 -05001971 }
1972 }
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001973 if (executable != NULL)
1974 invoke_child(executable, NULL, command);
1975 else
1976 rc = RC_NO_PYTHON;
Brian Curtin07165f72012-06-20 15:36:14 -05001977 return rc;
1978}
1979
1980#if defined(_WINDOWS)
1981
1982int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
1983 LPWSTR lpstrCmd, int nShow)
1984{
1985 return process(__argc, __wargv);
1986}
1987
1988#else
1989
1990int cdecl wmain(int argc, wchar_t ** argv)
1991{
1992 return process(argc, argv);
1993}
1994
Vinay Sajip2ae8c632013-01-29 22:29:25 +00001995#endif