blob: f3a7ddc5439c9e83b1496f2318ea791b9a12f779 [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 Dowerb264c602018-12-10 08:11:34 -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 Dowerb264c602018-12-10 08:11:34 -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);
Miss Islington (bot)ba7970f2018-06-15 16:00:24 -070073 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);
Miss Islington (bot)ba7970f2018-06-15 16:00:24 -070096 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 Dowerb264c602018-12-10 08:11:34 -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 Dowerb264c602018-12-10 08:11:34 -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 Dowerb264c602018-12-10 08:11:34 -0800163#endif
Brian Curtin07165f72012-06-20 15:36:14 -0500164
Brian Curtin07165f72012-06-20 15:36:14 -0500165#define MAX_VERSION_SIZE 4
166
167typedef struct {
168 wchar_t version[MAX_VERSION_SIZE]; /* m.n */
169 int bits; /* 32 or 64 */
170 wchar_t executable[MAX_PATH];
171} INSTALLED_PYTHON;
172
173/*
174 * To avoid messing about with heap allocations, just assume we can allocate
175 * statically and never have to deal with more versions than this.
176 */
177#define MAX_INSTALLED_PYTHONS 100
178
179static INSTALLED_PYTHON installed_pythons[MAX_INSTALLED_PYTHONS];
180
181static size_t num_installed_pythons = 0;
182
Steve Dowerbb240872015-02-05 22:08:48 -0800183/*
184 * To hold SOFTWARE\Python\PythonCore\X.Y...\InstallPath
185 * The version name can be longer than MAX_VERSION_SIZE, but will be
186 * truncated to just X.Y for comparisons.
187 */
Brian Curtin07165f72012-06-20 15:36:14 -0500188#define IP_BASE_SIZE 40
Steve Dowerbb240872015-02-05 22:08:48 -0800189#define IP_VERSION_SIZE 8
190#define IP_SIZE (IP_BASE_SIZE + IP_VERSION_SIZE)
Brian Curtin07165f72012-06-20 15:36:14 -0500191#define CORE_PATH L"SOFTWARE\\Python\\PythonCore"
192
193static wchar_t * location_checks[] = {
194 L"\\",
Stefan Grönkef1502d02017-09-25 18:58:10 +0200195 L"\\PCbuild\\win32\\",
196 L"\\PCbuild\\amd64\\",
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100197 /* To support early 32bit versions of Python that stuck the build binaries
Stefan Grönkef1502d02017-09-25 18:58:10 +0200198 * directly in PCbuild... */
199 L"\\PCbuild\\",
Brian Curtin07165f72012-06-20 15:36:14 -0500200 NULL
201};
202
203static INSTALLED_PYTHON *
204find_existing_python(wchar_t * path)
205{
206 INSTALLED_PYTHON * result = NULL;
207 size_t i;
208 INSTALLED_PYTHON * ip;
209
210 for (i = 0, ip = installed_pythons; i < num_installed_pythons; i++, ip++) {
211 if (_wcsicmp(path, ip->executable) == 0) {
212 result = ip;
213 break;
214 }
215 }
216 return result;
217}
218
219static void
220locate_pythons_for_key(HKEY root, REGSAM flags)
221{
222 HKEY core_root, ip_key;
223 LSTATUS status = RegOpenKeyExW(root, CORE_PATH, 0, flags, &core_root);
224 wchar_t message[MSGSIZE];
225 DWORD i;
226 size_t n;
227 BOOL ok;
228 DWORD type, data_size, attrs;
229 INSTALLED_PYTHON * ip, * pip;
Steve Dowerbb240872015-02-05 22:08:48 -0800230 wchar_t ip_version[IP_VERSION_SIZE];
Brian Curtin07165f72012-06-20 15:36:14 -0500231 wchar_t ip_path[IP_SIZE];
232 wchar_t * check;
233 wchar_t ** checkp;
234 wchar_t *key_name = (root == HKEY_LOCAL_MACHINE) ? L"HKLM" : L"HKCU";
235
236 if (status != ERROR_SUCCESS)
Steve Dower84bcfb32015-01-02 18:07:46 -0800237 debug(L"locate_pythons_for_key: unable to open PythonCore key in %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500238 key_name);
239 else {
240 ip = &installed_pythons[num_installed_pythons];
241 for (i = 0; num_installed_pythons < MAX_INSTALLED_PYTHONS; i++) {
Steve Dowerbb240872015-02-05 22:08:48 -0800242 status = RegEnumKeyW(core_root, i, ip_version, IP_VERSION_SIZE);
Brian Curtin07165f72012-06-20 15:36:14 -0500243 if (status != ERROR_SUCCESS) {
244 if (status != ERROR_NO_MORE_ITEMS) {
245 /* unexpected error */
246 winerror(status, message, MSGSIZE);
Steve Dower84bcfb32015-01-02 18:07:46 -0800247 debug(L"Can't enumerate registry key for version %ls: %ls\n",
Steve Dowerbb240872015-02-05 22:08:48 -0800248 ip_version, message);
Brian Curtin07165f72012-06-20 15:36:14 -0500249 }
250 break;
251 }
252 else {
Steve Dowerbb240872015-02-05 22:08:48 -0800253 wcsncpy_s(ip->version, MAX_VERSION_SIZE, ip_version,
254 MAX_VERSION_SIZE-1);
Brian Curtin07165f72012-06-20 15:36:14 -0500255 _snwprintf_s(ip_path, IP_SIZE, _TRUNCATE,
Steve Dowerbb240872015-02-05 22:08:48 -0800256 L"%ls\\%ls\\InstallPath", CORE_PATH, ip_version);
Brian Curtin07165f72012-06-20 15:36:14 -0500257 status = RegOpenKeyExW(root, ip_path, 0, flags, &ip_key);
258 if (status != ERROR_SUCCESS) {
259 winerror(status, message, MSGSIZE);
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100260 /* Note: 'message' already has a trailing \n*/
Steve Dower84bcfb32015-01-02 18:07:46 -0800261 debug(L"%ls\\%ls: %ls", key_name, ip_path, message);
Brian Curtin07165f72012-06-20 15:36:14 -0500262 continue;
263 }
264 data_size = sizeof(ip->executable) - 1;
Martin v. Löwisaf21ebb2012-06-21 18:15:54 +0200265 status = RegQueryValueExW(ip_key, NULL, NULL, &type,
266 (LPBYTE)ip->executable, &data_size);
Brian Curtin07165f72012-06-20 15:36:14 -0500267 RegCloseKey(ip_key);
268 if (status != ERROR_SUCCESS) {
269 winerror(status, message, MSGSIZE);
Steve Dower84bcfb32015-01-02 18:07:46 -0800270 debug(L"%ls\\%ls: %ls\n", key_name, ip_path, message);
Brian Curtin07165f72012-06-20 15:36:14 -0500271 continue;
272 }
273 if (type == REG_SZ) {
274 data_size = data_size / sizeof(wchar_t) - 1; /* for NUL */
275 if (ip->executable[data_size - 1] == L'\\')
276 --data_size; /* reg value ended in a backslash */
277 /* ip->executable is data_size long */
278 for (checkp = location_checks; *checkp; ++checkp) {
279 check = *checkp;
280 _snwprintf_s(&ip->executable[data_size],
281 MAX_PATH - data_size,
282 MAX_PATH - data_size,
Steve Dower84bcfb32015-01-02 18:07:46 -0800283 L"%ls%ls", check, PYTHON_EXECUTABLE);
Brian Curtin07165f72012-06-20 15:36:14 -0500284 attrs = GetFileAttributesW(ip->executable);
285 if (attrs == INVALID_FILE_ATTRIBUTES) {
286 winerror(GetLastError(), message, MSGSIZE);
Steve Dower84bcfb32015-01-02 18:07:46 -0800287 debug(L"locate_pythons_for_key: %ls: %ls",
Brian Curtin07165f72012-06-20 15:36:14 -0500288 ip->executable, message);
289 }
290 else if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800291 debug(L"locate_pythons_for_key: '%ls' is a \
Brian Curtin07165f72012-06-20 15:36:14 -0500292directory\n",
293 ip->executable, attrs);
294 }
295 else if (find_existing_python(ip->executable)) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800296 debug(L"locate_pythons_for_key: %ls: already \
Steve Dower13be8c22015-03-10 19:38:25 -0700297found\n", ip->executable);
Brian Curtin07165f72012-06-20 15:36:14 -0500298 }
299 else {
300 /* check the executable type. */
301 ok = GetBinaryTypeW(ip->executable, &attrs);
302 if (!ok) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800303 debug(L"Failure getting binary type: %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500304 ip->executable);
305 }
306 else {
307 if (attrs == SCS_64BIT_BINARY)
308 ip->bits = 64;
309 else if (attrs == SCS_32BIT_BINARY)
310 ip->bits = 32;
311 else
312 ip->bits = 0;
313 if (ip->bits == 0) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800314 debug(L"locate_pythons_for_key: %ls: \
Brian Curtin07165f72012-06-20 15:36:14 -0500315invalid binary type: %X\n",
316 ip->executable, attrs);
317 }
318 else {
319 if (wcschr(ip->executable, L' ') != NULL) {
320 /* has spaces, so quote */
321 n = wcslen(ip->executable);
322 memmove(&ip->executable[1],
323 ip->executable, n * sizeof(wchar_t));
324 ip->executable[0] = L'\"';
325 ip->executable[n + 1] = L'\"';
326 ip->executable[n + 2] = L'\0';
327 }
Steve Dower84bcfb32015-01-02 18:07:46 -0800328 debug(L"locate_pythons_for_key: %ls \
Brian Curtin07165f72012-06-20 15:36:14 -0500329is a %dbit executable\n",
330 ip->executable, ip->bits);
331 ++num_installed_pythons;
332 pip = ip++;
333 if (num_installed_pythons >=
334 MAX_INSTALLED_PYTHONS)
335 break;
336 /* Copy over the attributes for the next */
337 *ip = *pip;
338 }
339 }
340 }
341 }
342 }
343 }
344 }
345 RegCloseKey(core_root);
346 }
347}
348
349static int
350compare_pythons(const void * p1, const void * p2)
351{
352 INSTALLED_PYTHON * ip1 = (INSTALLED_PYTHON *) p1;
353 INSTALLED_PYTHON * ip2 = (INSTALLED_PYTHON *) p2;
354 /* note reverse sorting on version */
355 int result = wcscmp(ip2->version, ip1->version);
356
357 if (result == 0)
358 result = ip2->bits - ip1->bits; /* 64 before 32 */
359 return result;
360}
361
362static void
363locate_all_pythons()
364{
365#if defined(_M_X64)
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100366 /* If we are a 64bit process, first hit the 32bit keys. */
Brian Curtin07165f72012-06-20 15:36:14 -0500367 debug(L"locating Pythons in 32bit registry\n");
368 locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ | KEY_WOW64_32KEY);
369 locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ | KEY_WOW64_32KEY);
370#else
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100371 /* If we are a 32bit process on a 64bit Windows, first hit the 64bit keys.*/
Brian Curtin07165f72012-06-20 15:36:14 -0500372 BOOL f64 = FALSE;
373 if (IsWow64Process(GetCurrentProcess(), &f64) && f64) {
374 debug(L"locating Pythons in 64bit registry\n");
375 locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ | KEY_WOW64_64KEY);
376 locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ | KEY_WOW64_64KEY);
377 }
Serhiy Storchaka009b8112015-03-18 21:53:15 +0200378#endif
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100379 /* now hit the "native" key for this process bittedness. */
Brian Curtin07165f72012-06-20 15:36:14 -0500380 debug(L"locating Pythons in native registry\n");
381 locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ);
382 locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ);
383 qsort(installed_pythons, num_installed_pythons, sizeof(INSTALLED_PYTHON),
384 compare_pythons);
385}
386
387static INSTALLED_PYTHON *
388find_python_by_version(wchar_t const * wanted_ver)
389{
390 INSTALLED_PYTHON * result = NULL;
391 INSTALLED_PYTHON * ip = installed_pythons;
392 size_t i, n;
393 size_t wlen = wcslen(wanted_ver);
394 int bits = 0;
395
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100396 if (wcsstr(wanted_ver, L"-32")) {
Brian Curtin07165f72012-06-20 15:36:14 -0500397 bits = 32;
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100398 wlen -= wcslen(L"-32");
399 }
400 else if (wcsstr(wanted_ver, L"-64")) { /* Added option to select 64 bit explicitly */
401 bits = 64;
402 wlen -= wcslen(L"-64");
403 }
Brian Curtin07165f72012-06-20 15:36:14 -0500404 for (i = 0; i < num_installed_pythons; i++, ip++) {
405 n = wcslen(ip->version);
406 if (n > wlen)
407 n = wlen;
408 if ((wcsncmp(ip->version, wanted_ver, n) == 0) &&
409 /* bits == 0 => don't care */
410 ((bits == 0) || (ip->bits == bits))) {
411 result = ip;
412 break;
413 }
414 }
415 return result;
416}
417
418
Steve Dower76998fe2015-02-26 14:25:33 -0800419static wchar_t *
420find_python_by_venv()
421{
422 static wchar_t venv_python[MAX_PATH];
423 wchar_t *virtual_env = get_env(L"VIRTUAL_ENV");
424 DWORD attrs;
425
426 /* Check for VIRTUAL_ENV environment variable */
427 if (virtual_env == NULL || virtual_env[0] == L'\0') {
428 return NULL;
429 }
430
431 /* Check for a python executable in the venv */
432 debug(L"Checking for Python executable in virtual env '%ls'\n", virtual_env);
433 _snwprintf_s(venv_python, MAX_PATH, _TRUNCATE,
434 L"%ls\\Scripts\\%ls", virtual_env, PYTHON_EXECUTABLE);
435 attrs = GetFileAttributesW(venv_python);
436 if (attrs == INVALID_FILE_ATTRIBUTES) {
437 debug(L"Python executable %ls missing from virtual env\n", venv_python);
438 return NULL;
439 }
440
441 return venv_python;
442}
443
Brian Curtin07165f72012-06-20 15:36:14 -0500444static wchar_t appdata_ini_path[MAX_PATH];
445static wchar_t launcher_ini_path[MAX_PATH];
446
447/*
448 * Get a value either from the environment or a configuration file.
449 * The key passed in will either be "python", "python2" or "python3".
450 */
451static wchar_t *
452get_configured_value(wchar_t * key)
453{
454/*
455 * Note: this static value is used to return a configured value
456 * obtained either from the environment or configuration file.
457 * This should be OK since there wouldn't be any concurrent calls.
458 */
459 static wchar_t configured_value[MSGSIZE];
460 wchar_t * result = NULL;
461 wchar_t * found_in = L"environment";
462 DWORD size;
463
464 /* First, search the environment. */
Steve Dower84bcfb32015-01-02 18:07:46 -0800465 _snwprintf_s(configured_value, MSGSIZE, _TRUNCATE, L"py_%ls", key);
Brian Curtin07165f72012-06-20 15:36:14 -0500466 result = get_env(configured_value);
467 if (result == NULL && appdata_ini_path[0]) {
468 /* Not in environment: check local configuration. */
469 size = GetPrivateProfileStringW(L"defaults", key, NULL,
470 configured_value, MSGSIZE,
471 appdata_ini_path);
472 if (size > 0) {
473 result = configured_value;
474 found_in = appdata_ini_path;
475 }
476 }
477 if (result == NULL && launcher_ini_path[0]) {
478 /* Not in environment or local: check global configuration. */
479 size = GetPrivateProfileStringW(L"defaults", key, NULL,
480 configured_value, MSGSIZE,
481 launcher_ini_path);
482 if (size > 0) {
483 result = configured_value;
484 found_in = launcher_ini_path;
485 }
486 }
487 if (result) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800488 debug(L"found configured value '%ls=%ls' in %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500489 key, result, found_in ? found_in : L"(unknown)");
490 } else {
Steve Dower84bcfb32015-01-02 18:07:46 -0800491 debug(L"found no configured value for '%ls'\n", key);
Brian Curtin07165f72012-06-20 15:36:14 -0500492 }
493 return result;
494}
495
496static INSTALLED_PYTHON *
Paul Moore835416c2016-05-22 12:28:41 +0100497locate_python(wchar_t * wanted_ver, BOOL from_shebang)
Brian Curtin07165f72012-06-20 15:36:14 -0500498{
499 static wchar_t config_key [] = { L"pythonX" };
500 static wchar_t * last_char = &config_key[sizeof(config_key) /
501 sizeof(wchar_t) - 2];
502 INSTALLED_PYTHON * result = NULL;
503 size_t n = wcslen(wanted_ver);
504 wchar_t * configured_value;
505
506 if (num_installed_pythons == 0)
507 locate_all_pythons();
508
509 if (n == 1) { /* just major version specified */
510 *last_char = *wanted_ver;
511 configured_value = get_configured_value(config_key);
512 if (configured_value != NULL)
513 wanted_ver = configured_value;
514 }
515 if (*wanted_ver) {
516 result = find_python_by_version(wanted_ver);
Steve Dower84bcfb32015-01-02 18:07:46 -0800517 debug(L"search for Python version '%ls' found ", wanted_ver);
Brian Curtin07165f72012-06-20 15:36:14 -0500518 if (result) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800519 debug(L"'%ls'\n", result->executable);
Brian Curtin07165f72012-06-20 15:36:14 -0500520 } else {
521 debug(L"no interpreter\n");
522 }
523 }
524 else {
525 *last_char = L'\0'; /* look for an overall default */
526 configured_value = get_configured_value(config_key);
527 if (configured_value)
528 result = find_python_by_version(configured_value);
Paul Moore835416c2016-05-22 12:28:41 +0100529 /* Not found a value yet - try by major version.
530 * If we're looking for an interpreter specified in a shebang line,
531 * we want to try Python 2 first, then Python 3 (for Unix and backward
532 * compatibility). If we're being called interactively, assume the user
533 * wants the latest version available, so try Python 3 first, then
534 * Python 2.
535 */
Brian Curtin07165f72012-06-20 15:36:14 -0500536 if (result == NULL)
Paul Moore835416c2016-05-22 12:28:41 +0100537 result = find_python_by_version(from_shebang ? L"2" : L"3");
Brian Curtin07165f72012-06-20 15:36:14 -0500538 if (result == NULL)
Paul Moore835416c2016-05-22 12:28:41 +0100539 result = find_python_by_version(from_shebang ? L"3" : L"2");
Brian Curtin07165f72012-06-20 15:36:14 -0500540 debug(L"search for default Python found ");
541 if (result) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800542 debug(L"version %ls at '%ls'\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500543 result->version, result->executable);
544 } else {
545 debug(L"no interpreter\n");
546 }
547 }
548 return result;
549}
550
Vinay Sajipc985d082013-07-25 11:20:55 +0100551#if defined(SCRIPT_WRAPPER)
552/*
553 * Check for a script located alongside the executable
554 */
555
556#if defined(_WINDOWS)
557#define SCRIPT_SUFFIX L"-script.pyw"
558#else
559#define SCRIPT_SUFFIX L"-script.py"
560#endif
561
562static wchar_t wrapped_script_path[MAX_PATH];
563
564/* Locate the script being wrapped.
565 *
566 * This code should store the name of the wrapped script in
567 * wrapped_script_path, or terminate the program with an error if there is no
568 * valid wrapped script file.
569 */
570static void
571locate_wrapped_script()
572{
573 wchar_t * p;
574 size_t plen;
575 DWORD attrs;
576
577 plen = GetModuleFileNameW(NULL, wrapped_script_path, MAX_PATH);
578 p = wcsrchr(wrapped_script_path, L'.');
579 if (p == NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800580 debug(L"GetModuleFileNameW returned value has no extension: %ls\n",
Vinay Sajipc985d082013-07-25 11:20:55 +0100581 wrapped_script_path);
Steve Dower84bcfb32015-01-02 18:07:46 -0800582 error(RC_NO_SCRIPT, L"Wrapper name '%ls' is not valid.", wrapped_script_path);
Vinay Sajipc985d082013-07-25 11:20:55 +0100583 }
584
585 wcsncpy_s(p, MAX_PATH - (p - wrapped_script_path) + 1, SCRIPT_SUFFIX, _TRUNCATE);
586 attrs = GetFileAttributesW(wrapped_script_path);
587 if (attrs == INVALID_FILE_ATTRIBUTES) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800588 debug(L"File '%ls' non-existent\n", wrapped_script_path);
589 error(RC_NO_SCRIPT, L"Script file '%ls' is not present.", wrapped_script_path);
Vinay Sajipc985d082013-07-25 11:20:55 +0100590 }
591
Steve Dower84bcfb32015-01-02 18:07:46 -0800592 debug(L"Using wrapped script file '%ls'\n", wrapped_script_path);
Vinay Sajipc985d082013-07-25 11:20:55 +0100593}
594#endif
595
Brian Curtin07165f72012-06-20 15:36:14 -0500596/*
597 * Process creation code
598 */
599
600static BOOL
601safe_duplicate_handle(HANDLE in, HANDLE * pout)
602{
603 BOOL ok;
604 HANDLE process = GetCurrentProcess();
605 DWORD rc;
606
607 *pout = NULL;
608 ok = DuplicateHandle(process, in, process, pout, 0, TRUE,
609 DUPLICATE_SAME_ACCESS);
610 if (!ok) {
611 rc = GetLastError();
612 if (rc == ERROR_INVALID_HANDLE) {
613 debug(L"DuplicateHandle returned ERROR_INVALID_HANDLE\n");
614 ok = TRUE;
615 }
616 else {
617 debug(L"DuplicateHandle returned %d\n", rc);
618 }
619 }
620 return ok;
621}
622
623static BOOL WINAPI
624ctrl_c_handler(DWORD code)
625{
626 return TRUE; /* We just ignore all control events. */
627}
628
629static void
630run_child(wchar_t * cmdline)
631{
632 HANDLE job;
633 JOBOBJECT_EXTENDED_LIMIT_INFORMATION info;
634 DWORD rc;
635 BOOL ok;
636 STARTUPINFOW si;
637 PROCESS_INFORMATION pi;
638
Vinay Sajip66fef9f2013-02-26 16:29:06 +0000639#if defined(_WINDOWS)
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +0100640 /*
641 When explorer launches a Windows (GUI) application, it displays
642 the "app starting" (the "pointer + hourglass") cursor for a number
643 of seconds, or until the app does something UI-ish (eg, creating a
644 window, or fetching a message). As this launcher doesn't do this
645 directly, that cursor remains even after the child process does these
646 things. We avoid that by doing a simple post+get message.
647 See http://bugs.python.org/issue17290 and
648 https://bitbucket.org/vinay.sajip/pylauncher/issue/20/busy-cursor-for-a-long-time-when-running
649 */
Vinay Sajip66fef9f2013-02-26 16:29:06 +0000650 MSG msg;
651
652 PostMessage(0, 0, 0, 0);
653 GetMessage(&msg, 0, 0, 0);
654#endif
655
Steve Dower84bcfb32015-01-02 18:07:46 -0800656 debug(L"run_child: about to run '%ls'\n", cmdline);
Brian Curtin07165f72012-06-20 15:36:14 -0500657 job = CreateJobObject(NULL, NULL);
658 ok = QueryInformationJobObject(job, JobObjectExtendedLimitInformation,
659 &info, sizeof(info), &rc);
660 if (!ok || (rc != sizeof(info)) || !job)
661 error(RC_CREATE_PROCESS, L"Job information querying failed");
662 info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE |
663 JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK;
664 ok = SetInformationJobObject(job, JobObjectExtendedLimitInformation, &info,
665 sizeof(info));
666 if (!ok)
667 error(RC_CREATE_PROCESS, L"Job information setting failed");
668 memset(&si, 0, sizeof(si));
669 si.cb = sizeof(si);
670 ok = safe_duplicate_handle(GetStdHandle(STD_INPUT_HANDLE), &si.hStdInput);
671 if (!ok)
672 error(RC_NO_STD_HANDLES, L"stdin duplication failed");
673 ok = safe_duplicate_handle(GetStdHandle(STD_OUTPUT_HANDLE), &si.hStdOutput);
674 if (!ok)
675 error(RC_NO_STD_HANDLES, L"stdout duplication failed");
676 ok = safe_duplicate_handle(GetStdHandle(STD_ERROR_HANDLE), &si.hStdError);
677 if (!ok)
678 error(RC_NO_STD_HANDLES, L"stderr duplication failed");
679
680 ok = SetConsoleCtrlHandler(ctrl_c_handler, TRUE);
681 if (!ok)
682 error(RC_CREATE_PROCESS, L"control handler setting failed");
683
684 si.dwFlags = STARTF_USESTDHANDLES;
685 ok = CreateProcessW(NULL, cmdline, NULL, NULL, TRUE,
686 0, NULL, NULL, &si, &pi);
687 if (!ok)
Steve Dower84bcfb32015-01-02 18:07:46 -0800688 error(RC_CREATE_PROCESS, L"Unable to create process using '%ls'", cmdline);
Brian Curtin07165f72012-06-20 15:36:14 -0500689 AssignProcessToJobObject(job, pi.hProcess);
690 CloseHandle(pi.hThread);
Martin v. Löwisb26a9b12013-01-25 14:25:48 +0100691 WaitForSingleObjectEx(pi.hProcess, INFINITE, FALSE);
Brian Curtin07165f72012-06-20 15:36:14 -0500692 ok = GetExitCodeProcess(pi.hProcess, &rc);
693 if (!ok)
694 error(RC_CREATE_PROCESS, L"Failed to get exit code of process");
695 debug(L"child process exit code: %d\n", rc);
Vinay Sajipaab9f462015-12-26 12:35:47 +0000696 exit(rc);
Brian Curtin07165f72012-06-20 15:36:14 -0500697}
698
699static void
700invoke_child(wchar_t * executable, wchar_t * suffix, wchar_t * cmdline)
701{
702 wchar_t * child_command;
703 size_t child_command_size;
704 BOOL no_suffix = (suffix == NULL) || (*suffix == L'\0');
705 BOOL no_cmdline = (*cmdline == L'\0');
706
707 if (no_suffix && no_cmdline)
708 run_child(executable);
709 else {
710 if (no_suffix) {
711 /* add 2 for space separator + terminating NUL. */
712 child_command_size = wcslen(executable) + wcslen(cmdline) + 2;
713 }
714 else {
715 /* add 3 for 2 space separators + terminating NUL. */
716 child_command_size = wcslen(executable) + wcslen(suffix) +
717 wcslen(cmdline) + 3;
718 }
719 child_command = calloc(child_command_size, sizeof(wchar_t));
720 if (child_command == NULL)
721 error(RC_CREATE_PROCESS, L"unable to allocate %d bytes for child command.",
722 child_command_size);
723 if (no_suffix)
724 _snwprintf_s(child_command, child_command_size,
Steve Dower84bcfb32015-01-02 18:07:46 -0800725 child_command_size - 1, L"%ls %ls",
Brian Curtin07165f72012-06-20 15:36:14 -0500726 executable, cmdline);
727 else
728 _snwprintf_s(child_command, child_command_size,
Steve Dower84bcfb32015-01-02 18:07:46 -0800729 child_command_size - 1, L"%ls %ls %ls",
Brian Curtin07165f72012-06-20 15:36:14 -0500730 executable, suffix, cmdline);
731 run_child(child_command);
732 free(child_command);
733 }
734}
735
Vinay Sajip22c039b2013-06-07 15:37:28 +0100736typedef struct {
737 wchar_t *shebang;
738 BOOL search;
739} SHEBANG;
740
741static SHEBANG builtin_virtual_paths [] = {
742 { L"/usr/bin/env python", TRUE },
743 { L"/usr/bin/python", FALSE },
744 { L"/usr/local/bin/python", FALSE },
745 { L"python", FALSE },
746 { NULL, FALSE },
Brian Curtin07165f72012-06-20 15:36:14 -0500747};
748
749/* For now, a static array of commands. */
750
751#define MAX_COMMANDS 100
752
753typedef struct {
754 wchar_t key[MAX_PATH];
755 wchar_t value[MSGSIZE];
756} COMMAND;
757
758static COMMAND commands[MAX_COMMANDS];
759static int num_commands = 0;
760
761#if defined(SKIP_PREFIX)
762
763static wchar_t * builtin_prefixes [] = {
764 /* These must be in an order that the longest matches should be found,
765 * i.e. if the prefix is "/usr/bin/env ", it should match that entry
766 * *before* matching "/usr/bin/".
767 */
768 L"/usr/bin/env ",
769 L"/usr/bin/",
770 L"/usr/local/bin/",
771 NULL
772};
773
774static wchar_t * skip_prefix(wchar_t * name)
775{
776 wchar_t ** pp = builtin_prefixes;
777 wchar_t * result = name;
778 wchar_t * p;
779 size_t n;
780
781 for (; p = *pp; pp++) {
782 n = wcslen(p);
783 if (_wcsnicmp(p, name, n) == 0) {
784 result += n; /* skip the prefix */
785 if (p[n - 1] == L' ') /* No empty strings in table, so n > 1 */
786 result = skip_whitespace(result);
787 break;
788 }
789 }
790 return result;
791}
792
793#endif
794
795#if defined(SEARCH_PATH)
796
797static COMMAND path_command;
798
799static COMMAND * find_on_path(wchar_t * name)
800{
801 wchar_t * pathext;
802 size_t varsize;
803 wchar_t * context = NULL;
804 wchar_t * extension;
805 COMMAND * result = NULL;
806 DWORD len;
807 errno_t rc;
808
809 wcscpy_s(path_command.key, MAX_PATH, name);
810 if (wcschr(name, L'.') != NULL) {
811 /* assume it has an extension. */
812 len = SearchPathW(NULL, name, NULL, MSGSIZE, path_command.value, NULL);
813 if (len) {
814 result = &path_command;
815 }
816 }
817 else {
818 /* No extension - search using registered extensions. */
819 rc = _wdupenv_s(&pathext, &varsize, L"PATHEXT");
820 if (rc == 0) {
821 extension = wcstok_s(pathext, L";", &context);
822 while (extension) {
823 len = SearchPathW(NULL, name, extension, MSGSIZE, path_command.value, NULL);
824 if (len) {
825 result = &path_command;
826 break;
827 }
828 extension = wcstok_s(NULL, L";", &context);
829 }
830 free(pathext);
831 }
832 }
833 return result;
834}
835
836#endif
837
838static COMMAND * find_command(wchar_t * name)
839{
840 COMMAND * result = NULL;
841 COMMAND * cp = commands;
842 int i;
843
844 for (i = 0; i < num_commands; i++, cp++) {
845 if (_wcsicmp(cp->key, name) == 0) {
846 result = cp;
847 break;
848 }
849 }
850#if defined(SEARCH_PATH)
851 if (result == NULL)
852 result = find_on_path(name);
853#endif
854 return result;
855}
856
857static void
858update_command(COMMAND * cp, wchar_t * name, wchar_t * cmdline)
859{
860 wcsncpy_s(cp->key, MAX_PATH, name, _TRUNCATE);
861 wcsncpy_s(cp->value, MSGSIZE, cmdline, _TRUNCATE);
862}
863
864static void
865add_command(wchar_t * name, wchar_t * cmdline)
866{
867 if (num_commands >= MAX_COMMANDS) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800868 debug(L"can't add %ls = '%ls': no room\n", name, cmdline);
Brian Curtin07165f72012-06-20 15:36:14 -0500869 }
870 else {
871 COMMAND * cp = &commands[num_commands++];
872
873 update_command(cp, name, cmdline);
874 }
875}
876
877static void
878read_config_file(wchar_t * config_path)
879{
880 wchar_t keynames[MSGSIZE];
881 wchar_t value[MSGSIZE];
882 DWORD read;
883 wchar_t * key;
884 COMMAND * cp;
885 wchar_t * cmdp;
886
887 read = GetPrivateProfileStringW(L"commands", NULL, NULL, keynames, MSGSIZE,
888 config_path);
889 if (read == MSGSIZE - 1) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800890 debug(L"read_commands: %ls: not enough space for names\n", config_path);
Brian Curtin07165f72012-06-20 15:36:14 -0500891 }
892 key = keynames;
893 while (*key) {
894 read = GetPrivateProfileStringW(L"commands", key, NULL, value, MSGSIZE,
895 config_path);
896 if (read == MSGSIZE - 1) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800897 debug(L"read_commands: %ls: not enough space for %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500898 config_path, key);
899 }
900 cmdp = skip_whitespace(value);
901 if (*cmdp) {
902 cp = find_command(key);
903 if (cp == NULL)
904 add_command(key, value);
905 else
906 update_command(cp, key, value);
907 }
908 key += wcslen(key) + 1;
909 }
910}
911
912static void read_commands()
913{
914 if (launcher_ini_path[0])
915 read_config_file(launcher_ini_path);
916 if (appdata_ini_path[0])
917 read_config_file(appdata_ini_path);
918}
919
920static BOOL
921parse_shebang(wchar_t * shebang_line, int nchars, wchar_t ** command,
Vinay Sajip22c039b2013-06-07 15:37:28 +0100922 wchar_t ** suffix, BOOL *search)
Brian Curtin07165f72012-06-20 15:36:14 -0500923{
924 BOOL rc = FALSE;
Vinay Sajip22c039b2013-06-07 15:37:28 +0100925 SHEBANG * vpp;
Brian Curtin07165f72012-06-20 15:36:14 -0500926 size_t plen;
927 wchar_t * p;
928 wchar_t zapped;
929 wchar_t * endp = shebang_line + nchars - 1;
930 COMMAND * cp;
931 wchar_t * skipped;
932
933 *command = NULL; /* failure return */
934 *suffix = NULL;
Vinay Sajip22c039b2013-06-07 15:37:28 +0100935 *search = FALSE;
Brian Curtin07165f72012-06-20 15:36:14 -0500936
937 if ((*shebang_line++ == L'#') && (*shebang_line++ == L'!')) {
938 shebang_line = skip_whitespace(shebang_line);
939 if (*shebang_line) {
940 *command = shebang_line;
Vinay Sajip22c039b2013-06-07 15:37:28 +0100941 for (vpp = builtin_virtual_paths; vpp->shebang; ++vpp) {
942 plen = wcslen(vpp->shebang);
943 if (wcsncmp(shebang_line, vpp->shebang, plen) == 0) {
Brian Curtin07165f72012-06-20 15:36:14 -0500944 rc = TRUE;
Vinay Sajip22c039b2013-06-07 15:37:28 +0100945 *search = vpp->search;
Brian Curtin07165f72012-06-20 15:36:14 -0500946 /* We can do this because all builtin commands contain
947 * "python".
948 */
949 *command = wcsstr(shebang_line, L"python");
950 break;
951 }
952 }
Vinay Sajip22c039b2013-06-07 15:37:28 +0100953 if (vpp->shebang == NULL) {
Brian Curtin07165f72012-06-20 15:36:14 -0500954 /*
Vinay Sajip9c10d6b2013-11-15 20:58:13 +0000955 * Not found in builtins - look in customized commands.
Brian Curtin07165f72012-06-20 15:36:14 -0500956 *
957 * We can't permanently modify the shebang line in case
Vinay Sajip9c10d6b2013-11-15 20:58:13 +0000958 * it's not a customized command, but we can temporarily
Brian Curtin07165f72012-06-20 15:36:14 -0500959 * stick a NUL after the command while searching for it,
960 * then put back the char we zapped.
961 */
962#if defined(SKIP_PREFIX)
963 skipped = skip_prefix(shebang_line);
964#else
965 skipped = shebang_line;
966#endif
967 p = wcspbrk(skipped, L" \t\r\n");
968 if (p != NULL) {
969 zapped = *p;
970 *p = L'\0';
971 }
972 cp = find_command(skipped);
973 if (p != NULL)
974 *p = zapped;
975 if (cp != NULL) {
976 *command = cp->value;
977 if (p != NULL)
978 *suffix = skip_whitespace(p);
979 }
980 }
981 /* remove trailing whitespace */
982 while ((endp > shebang_line) && isspace(*endp))
983 --endp;
984 if (endp > shebang_line)
985 endp[1] = L'\0';
986 }
987 }
988 return rc;
989}
990
991/* #define CP_UTF8 65001 defined in winnls.h */
992#define CP_UTF16LE 1200
993#define CP_UTF16BE 1201
994#define CP_UTF32LE 12000
995#define CP_UTF32BE 12001
996
997typedef struct {
998 int length;
999 char sequence[4];
1000 UINT code_page;
1001} BOM;
1002
1003/*
Vinay Sajipc985d082013-07-25 11:20:55 +01001004 * Strictly, we don't need to handle UTF-16 and UTF-32, since Python itself
Brian Curtin07165f72012-06-20 15:36:14 -05001005 * doesn't. Never mind, one day it might - there's no harm leaving it in.
1006 */
1007static BOM BOMs[] = {
1008 { 3, { 0xEF, 0xBB, 0xBF }, CP_UTF8 }, /* UTF-8 - keep first */
Serhiy Storchaka29e2aa62015-12-18 10:23:09 +02001009 /* Test UTF-32LE before UTF-16LE since UTF-16LE BOM is a prefix
1010 * of UTF-32LE BOM. */
Brian Curtin07165f72012-06-20 15:36:14 -05001011 { 4, { 0xFF, 0xFE, 0x00, 0x00 }, CP_UTF32LE }, /* UTF-32LE */
1012 { 4, { 0x00, 0x00, 0xFE, 0xFF }, CP_UTF32BE }, /* UTF-32BE */
Serhiy Storchaka29e2aa62015-12-18 10:23:09 +02001013 { 2, { 0xFF, 0xFE }, CP_UTF16LE }, /* UTF-16LE */
1014 { 2, { 0xFE, 0xFF }, CP_UTF16BE }, /* UTF-16BE */
Brian Curtin07165f72012-06-20 15:36:14 -05001015 { 0 } /* sentinel */
1016};
1017
1018static BOM *
1019find_BOM(char * buffer)
1020{
1021/*
1022 * Look for a BOM in the input and return a pointer to the
1023 * corresponding structure, or NULL if not found.
1024 */
1025 BOM * result = NULL;
1026 BOM *bom;
1027
1028 for (bom = BOMs; bom->length; bom++) {
1029 if (strncmp(bom->sequence, buffer, bom->length) == 0) {
1030 result = bom;
1031 break;
1032 }
1033 }
1034 return result;
1035}
1036
1037static char *
1038find_terminator(char * buffer, int len, BOM *bom)
1039{
1040 char * result = NULL;
1041 char * end = buffer + len;
1042 char * p;
1043 char c;
1044 int cp;
1045
1046 for (p = buffer; p < end; p++) {
1047 c = *p;
1048 if (c == '\r') {
1049 result = p;
1050 break;
1051 }
1052 if (c == '\n') {
1053 result = p;
1054 break;
1055 }
1056 }
1057 if (result != NULL) {
1058 cp = bom->code_page;
1059
1060 /* adjustments to include all bytes of the char */
1061 /* no adjustment needed for UTF-8 or big endian */
1062 if (cp == CP_UTF16LE)
1063 ++result;
1064 else if (cp == CP_UTF32LE)
1065 result += 3;
1066 ++result; /* point just past terminator */
1067 }
1068 return result;
1069}
1070
1071static BOOL
1072validate_version(wchar_t * p)
1073{
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +01001074 /*
Miss Islington (bot)28dd7372018-10-05 19:18:41 -07001075 Version information should start with the major version,
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +01001076 Optionally followed by a period and a minor version,
1077 Optionally followed by a minus and one of 32 or 64.
1078 Valid examples:
1079 2
1080 3
1081 2.7
1082 3.6
1083 2.7-32
1084 The intent is to add to the valid patterns:
1085 3.10
1086 3-32
1087 3.6-64
1088 3-64
1089 */
1090 BOOL result = (p != NULL); /* Default to False if null pointer. */
Brian Curtin07165f72012-06-20 15:36:14 -05001091
Miss Islington (bot)28dd7372018-10-05 19:18:41 -07001092 result = result && iswdigit(*p); /* Result = False if first string element is not a digit. */
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +01001093
1094 while (result && iswdigit(*p)) /* Require a major version */
1095 ++p; /* Skip all leading digit(s) */
1096 if (result && (*p == L'.')) /* Allow . for major minor separator.*/
1097 {
1098 result = iswdigit(*++p); /* Must be at least one digit */
1099 while (result && iswdigit(*++p)) ; /* Skip any more Digits */
1100 }
1101 if (result && (*p == L'-')) { /* Allow - for Bits Separator */
1102 switch(*++p){
1103 case L'3': /* 3 is OK */
1104 result = (*++p == L'2') && !*++p; /* only if followed by 2 and ended.*/
1105 break;
1106 case L'6': /* 6 is OK */
1107 result = (*++p == L'4') && !*++p; /* only if followed by 4 and ended.*/
1108 break;
1109 default:
Brian Curtin07165f72012-06-20 15:36:14 -05001110 result = FALSE;
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +01001111 break;
Brian Curtin07165f72012-06-20 15:36:14 -05001112 }
1113 }
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +01001114 result = result && !*p; /* Must have reached EOS */
Brian Curtin07165f72012-06-20 15:36:14 -05001115 return result;
Steve (Gadget) Barnes870f6a12017-05-13 00:21:26 +01001116
Brian Curtin07165f72012-06-20 15:36:14 -05001117}
1118
1119typedef struct {
1120 unsigned short min;
1121 unsigned short max;
1122 wchar_t version[MAX_VERSION_SIZE];
1123} PYC_MAGIC;
1124
1125static PYC_MAGIC magic_values[] = {
Steve Dower7ae61af2016-05-16 09:34:20 -07001126 { 50823, 50823, L"2.0" },
1127 { 60202, 60202, L"2.1" },
1128 { 60717, 60717, L"2.2" },
1129 { 62011, 62021, L"2.3" },
1130 { 62041, 62061, L"2.4" },
1131 { 62071, 62131, L"2.5" },
1132 { 62151, 62161, L"2.6" },
1133 { 62171, 62211, L"2.7" },
1134 { 3000, 3131, L"3.0" },
1135 { 3141, 3151, L"3.1" },
1136 { 3160, 3180, L"3.2" },
1137 { 3190, 3230, L"3.3" },
1138 { 3250, 3310, L"3.4" },
Serhiy Storchaka3c317e72016-06-12 09:22:01 +03001139 { 3320, 3351, L"3.5" },
Nick Coghlan944368e2016-09-11 14:45:49 +10001140 { 3360, 3379, L"3.6" },
Yury Selivanovf2392132016-12-13 19:03:51 -05001141 { 3390, 3399, L"3.7" },
Brian Curtin07165f72012-06-20 15:36:14 -05001142 { 0 }
1143};
1144
1145static INSTALLED_PYTHON *
1146find_by_magic(unsigned short magic)
1147{
1148 INSTALLED_PYTHON * result = NULL;
1149 PYC_MAGIC * mp;
1150
1151 for (mp = magic_values; mp->min; mp++) {
1152 if ((magic >= mp->min) && (magic <= mp->max)) {
Paul Moore835416c2016-05-22 12:28:41 +01001153 result = locate_python(mp->version, FALSE);
Brian Curtin07165f72012-06-20 15:36:14 -05001154 if (result != NULL)
1155 break;
1156 }
1157 }
1158 return result;
1159}
1160
1161static void
1162maybe_handle_shebang(wchar_t ** argv, wchar_t * cmdline)
1163{
1164/*
1165 * Look for a shebang line in the first argument. If found
1166 * and we spawn a child process, this never returns. If it
1167 * does return then we process the args "normally".
1168 *
1169 * argv[0] might be a filename with a shebang.
1170 */
1171 FILE * fp;
1172 errno_t rc = _wfopen_s(&fp, *argv, L"rb");
Serhiy Storchakaf8ed0042015-12-18 10:19:30 +02001173 char buffer[BUFSIZE];
Brian Curtin07165f72012-06-20 15:36:14 -05001174 wchar_t shebang_line[BUFSIZE + 1];
1175 size_t read;
1176 char *p;
1177 char * start;
1178 char * shebang_alias = (char *) shebang_line;
1179 BOM* bom;
1180 int i, j, nchars = 0;
1181 int header_len;
1182 BOOL is_virt;
Vinay Sajip22c039b2013-06-07 15:37:28 +01001183 BOOL search;
Brian Curtin07165f72012-06-20 15:36:14 -05001184 wchar_t * command;
1185 wchar_t * suffix;
Vinay Sajip22c039b2013-06-07 15:37:28 +01001186 COMMAND *cmd = NULL;
Brian Curtin07165f72012-06-20 15:36:14 -05001187 INSTALLED_PYTHON * ip;
1188
1189 if (rc == 0) {
1190 read = fread(buffer, sizeof(char), BUFSIZE, fp);
1191 debug(L"maybe_handle_shebang: read %d bytes\n", read);
1192 fclose(fp);
1193
1194 if ((read >= 4) && (buffer[3] == '\n') && (buffer[2] == '\r')) {
Serhiy Storchakaf8ed0042015-12-18 10:19:30 +02001195 ip = find_by_magic((((unsigned char)buffer[1]) << 8 |
1196 (unsigned char)buffer[0]) & 0xFFFF);
Brian Curtin07165f72012-06-20 15:36:14 -05001197 if (ip != NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001198 debug(L"script file is compiled against Python %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -05001199 ip->version);
1200 invoke_child(ip->executable, NULL, cmdline);
1201 }
1202 }
1203 /* Look for BOM */
1204 bom = find_BOM(buffer);
1205 if (bom == NULL) {
1206 start = buffer;
1207 debug(L"maybe_handle_shebang: BOM not found, using UTF-8\n");
1208 bom = BOMs; /* points to UTF-8 entry - the default */
1209 }
1210 else {
1211 debug(L"maybe_handle_shebang: BOM found, code page %d\n",
1212 bom->code_page);
1213 start = &buffer[bom->length];
1214 }
1215 p = find_terminator(start, BUFSIZE, bom);
1216 /*
1217 * If no CR or LF was found in the heading,
1218 * we assume it's not a shebang file.
1219 */
1220 if (p == NULL) {
1221 debug(L"maybe_handle_shebang: No line terminator found\n");
1222 }
1223 else {
1224 /*
1225 * Found line terminator - parse the shebang.
1226 *
1227 * Strictly, we don't need to handle UTF-16 anf UTF-32,
1228 * since Python itself doesn't.
1229 * Never mind, one day it might.
1230 */
1231 header_len = (int) (p - start);
1232 switch(bom->code_page) {
1233 case CP_UTF8:
1234 nchars = MultiByteToWideChar(bom->code_page,
1235 0,
1236 start, header_len, shebang_line,
1237 BUFSIZE);
1238 break;
1239 case CP_UTF16BE:
1240 if (header_len % 2 != 0) {
1241 debug(L"maybe_handle_shebang: UTF-16BE, but an odd number \
1242of bytes: %d\n", header_len);
1243 /* nchars = 0; Not needed - initialised to 0. */
1244 }
1245 else {
1246 for (i = header_len; i > 0; i -= 2) {
1247 shebang_alias[i - 1] = start[i - 2];
1248 shebang_alias[i - 2] = start[i - 1];
1249 }
1250 nchars = header_len / sizeof(wchar_t);
1251 }
1252 break;
1253 case CP_UTF16LE:
1254 if ((header_len % 2) != 0) {
1255 debug(L"UTF-16LE, but an odd number of bytes: %d\n",
1256 header_len);
1257 /* nchars = 0; Not needed - initialised to 0. */
1258 }
1259 else {
1260 /* no actual conversion needed. */
1261 memcpy(shebang_line, start, header_len);
1262 nchars = header_len / sizeof(wchar_t);
1263 }
1264 break;
1265 case CP_UTF32BE:
1266 if (header_len % 4 != 0) {
1267 debug(L"UTF-32BE, but not divisible by 4: %d\n",
1268 header_len);
1269 /* nchars = 0; Not needed - initialised to 0. */
1270 }
1271 else {
1272 for (i = header_len, j = header_len / 2; i > 0; i -= 4,
1273 j -= 2) {
1274 shebang_alias[j - 1] = start[i - 2];
1275 shebang_alias[j - 2] = start[i - 1];
1276 }
1277 nchars = header_len / sizeof(wchar_t);
1278 }
1279 break;
1280 case CP_UTF32LE:
1281 if (header_len % 4 != 0) {
1282 debug(L"UTF-32LE, but not divisible by 4: %d\n",
1283 header_len);
1284 /* nchars = 0; Not needed - initialised to 0. */
1285 }
1286 else {
1287 for (i = header_len, j = header_len / 2; i > 0; i -= 4,
1288 j -= 2) {
1289 shebang_alias[j - 1] = start[i - 3];
1290 shebang_alias[j - 2] = start[i - 4];
1291 }
1292 nchars = header_len / sizeof(wchar_t);
1293 }
1294 break;
1295 }
1296 if (nchars > 0) {
1297 shebang_line[--nchars] = L'\0';
1298 is_virt = parse_shebang(shebang_line, nchars, &command,
Vinay Sajip22c039b2013-06-07 15:37:28 +01001299 &suffix, &search);
Brian Curtin07165f72012-06-20 15:36:14 -05001300 if (command != NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001301 debug(L"parse_shebang: found command: %ls\n", command);
Brian Curtin07165f72012-06-20 15:36:14 -05001302 if (!is_virt) {
1303 invoke_child(command, suffix, cmdline);
1304 }
1305 else {
1306 suffix = wcschr(command, L' ');
1307 if (suffix != NULL) {
1308 *suffix++ = L'\0';
1309 suffix = skip_whitespace(suffix);
1310 }
1311 if (wcsncmp(command, L"python", 6))
1312 error(RC_BAD_VIRTUAL_PATH, L"Unknown virtual \
Steve Dower84bcfb32015-01-02 18:07:46 -08001313path '%ls'", command);
Brian Curtin07165f72012-06-20 15:36:14 -05001314 command += 6; /* skip past "python" */
Vinay Sajip22c039b2013-06-07 15:37:28 +01001315 if (search && ((*command == L'\0') || isspace(*command))) {
1316 /* Command is eligible for path search, and there
1317 * is no version specification.
1318 */
1319 debug(L"searching PATH for python executable\n");
Vinay Sajipa5892ab2015-12-26 13:10:51 +00001320 cmd = find_on_path(PYTHON_EXECUTABLE);
Steve Dower84bcfb32015-01-02 18:07:46 -08001321 debug(L"Python on path: %ls\n", cmd ? cmd->value : L"<not found>");
Vinay Sajip22c039b2013-06-07 15:37:28 +01001322 if (cmd) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001323 debug(L"located python on PATH: %ls\n", cmd->value);
Vinay Sajip22c039b2013-06-07 15:37:28 +01001324 invoke_child(cmd->value, suffix, cmdline);
1325 /* Exit here, as we have found the command */
1326 return;
1327 }
1328 /* FALL THROUGH: No python found on PATH, so fall
1329 * back to locating the correct installed python.
1330 */
1331 }
Brian Curtin07165f72012-06-20 15:36:14 -05001332 if (*command && !validate_version(command))
1333 error(RC_BAD_VIRTUAL_PATH, L"Invalid version \
Steve Dower84bcfb32015-01-02 18:07:46 -08001334specification: '%ls'.\nIn the first line of the script, 'python' needs to be \
Brian Curtin07165f72012-06-20 15:36:14 -05001335followed by a valid version specifier.\nPlease check the documentation.",
1336 command);
1337 /* TODO could call validate_version(command) */
Paul Moore835416c2016-05-22 12:28:41 +01001338 ip = locate_python(command, TRUE);
Brian Curtin07165f72012-06-20 15:36:14 -05001339 if (ip == NULL) {
1340 error(RC_NO_PYTHON, L"Requested Python version \
Steve Dower84bcfb32015-01-02 18:07:46 -08001341(%ls) is not installed", command);
Brian Curtin07165f72012-06-20 15:36:14 -05001342 }
1343 else {
1344 invoke_child(ip->executable, suffix, cmdline);
1345 }
1346 }
1347 }
1348 }
1349 }
1350 }
1351}
1352
1353static wchar_t *
1354skip_me(wchar_t * cmdline)
1355{
1356 BOOL quoted;
1357 wchar_t c;
1358 wchar_t * result = cmdline;
1359
1360 quoted = cmdline[0] == L'\"';
1361 if (!quoted)
1362 c = L' ';
1363 else {
1364 c = L'\"';
1365 ++result;
1366 }
1367 result = wcschr(result, c);
1368 if (result == NULL) /* when, for example, just exe name on command line */
1369 result = L"";
1370 else {
1371 ++result; /* skip past space or closing quote */
1372 result = skip_whitespace(result);
1373 }
1374 return result;
1375}
1376
1377static DWORD version_high = 0;
1378static DWORD version_low = 0;
1379
1380static void
1381get_version_info(wchar_t * version_text, size_t size)
1382{
1383 WORD maj, min, rel, bld;
1384
1385 if (!version_high && !version_low)
1386 wcsncpy_s(version_text, size, L"0.1", _TRUNCATE); /* fallback */
1387 else {
1388 maj = HIWORD(version_high);
1389 min = LOWORD(version_high);
1390 rel = HIWORD(version_low);
1391 bld = LOWORD(version_low);
1392 _snwprintf_s(version_text, size, _TRUNCATE, L"%d.%d.%d.%d", maj,
1393 min, rel, bld);
1394 }
1395}
1396
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001397static void
1398show_help_text(wchar_t ** argv)
1399{
1400 wchar_t version_text [MAX_PATH];
1401#if defined(_M_X64)
1402 BOOL canDo64bit = TRUE;
1403#else
1404 /* If we are a 32bit process on a 64bit Windows, first hit the 64bit keys. */
1405 BOOL canDo64bit = FALSE;
1406 IsWow64Process(GetCurrentProcess(), &canDo64bit);
1407#endif
1408
1409 get_version_info(version_text, MAX_PATH);
1410 fwprintf(stdout, L"\
1411Python Launcher for Windows Version %ls\n\n", version_text);
1412 fwprintf(stdout, L"\
1413usage:\n\
1414%ls [launcher-args] [python-args] script [script-args]\n\n", argv[0]);
1415 fputws(L"\
1416Launcher arguments:\n\n\
1417-2 : Launch the latest Python 2.x version\n\
1418-3 : Launch the latest Python 3.x version\n\
1419-X.Y : Launch the specified Python version\n", stdout);
1420 if (canDo64bit) {
1421 fputws(L"\
1422 The above all default to 64 bit if a matching 64 bit python is present.\n\
1423-X.Y-32: Launch the specified 32bit Python version\n\
1424-X-32 : Launch the latest 32bit Python X version\n\
1425-X.Y-64: Launch the specified 64bit Python version\n\
1426-X-64 : Launch the latest 64bit Python X version", stdout);
1427 }
1428 fputws(L"\n-0 --list : List the available pythons", stdout);
1429 fputws(L"\n-0p --list-paths : List with paths", stdout);
1430 fputws(L"\n\nThe following help text is from Python:\n\n", stdout);
1431 fflush(stdout);
1432}
1433
1434static BOOL
1435show_python_list(wchar_t ** argv)
1436{
1437 /*
1438 * Display options -0
1439 */
1440 INSTALLED_PYTHON * result = NULL;
1441 INSTALLED_PYTHON * ip = installed_pythons; /* List of installed pythons */
1442 INSTALLED_PYTHON * defpy = locate_python(L"", FALSE);
1443 size_t i = 0;
1444 wchar_t *p = argv[1];
1445 wchar_t *fmt = L"\n -%ls-%d"; /* print VER-BITS */
1446 wchar_t *defind = L" *"; /* Default indicator */
1447
1448 /*
1449 * Output informational messages to stderr to keep output
1450 * clean for use in pipes, etc.
1451 */
1452 fwprintf(stderr,
1453 L"Installed Pythons found by %s Launcher for Windows", argv[0]);
1454 if (!_wcsicmp(p, L"-0p") || !_wcsicmp(p, L"--list-paths")) /* Show path? */
1455 fmt = L"\n -%ls-%d\t%ls"; /* print VER-BITS path */
1456
1457 if (num_installed_pythons == 0) /* We have somehow got here without searching for pythons */
1458 locate_all_pythons(); /* Find them, Populates installed_pythons */
1459
1460 if (num_installed_pythons == 0) /* No pythons found */
1461 fwprintf(stderr, L"\nNo Installed Pythons Found!");
1462 else
1463 {
1464 for (i = 0; i < num_installed_pythons; i++, ip++) {
1465 fwprintf(stdout, fmt, ip->version, ip->bits, ip->executable);
1466 /* If there is a default indicate it */
1467 if ((defpy != NULL) && !_wcsicmp(ip->executable, defpy->executable))
1468 fwprintf(stderr, defind);
1469 }
1470 }
1471
1472 if ((defpy == NULL) && (num_installed_pythons > 0))
1473 /* We have pythons but none is the default */
1474 fwprintf(stderr, L"\n\nCan't find a Default Python.\n\n");
1475 else
1476 fwprintf(stderr, L"\n\n"); /* End with a blank line */
Miss Islington (bot)129642a2018-11-20 13:48:34 -08001477 return FALSE; /* If this has been called we cannot continue */
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001478}
1479
Steve Dowerb264c602018-12-10 08:11:34 -08001480#if defined(VENV_REDIRECT)
1481
1482static int
1483find_home_value(const char *buffer, const char **start, DWORD *length)
1484{
1485 for (const char *s = strstr(buffer, "home"); s; s = strstr(s + 1, "\nhome")) {
1486 if (*s == '\n') {
1487 ++s;
1488 }
1489 for (int i = 4; i > 0 && *s; --i, ++s);
1490
1491 while (*s && iswspace(*s)) {
1492 ++s;
1493 }
1494 if (*s != L'=') {
1495 continue;
1496 }
1497
1498 do {
1499 ++s;
1500 } while (*s && iswspace(*s));
1501
1502 *start = s;
1503 char *nl = strchr(s, '\n');
1504 if (nl) {
1505 *length = (DWORD)((ptrdiff_t)nl - (ptrdiff_t)s);
1506 } else {
1507 *length = (DWORD)strlen(s);
1508 }
1509 return 1;
1510 }
1511 return 0;
1512}
1513#endif
1514
1515static wchar_t *
1516wcsdup_pad(const wchar_t *s, int padding, int *newlen)
1517{
1518 size_t len = wcslen(s);
1519 len += 1 + padding;
1520 wchar_t *r = (wchar_t *)malloc(len * sizeof(wchar_t));
1521 if (!r) {
1522 return NULL;
1523 }
1524 if (wcscpy_s(r, len, s)) {
1525 free(r);
1526 return NULL;
1527 }
1528 *newlen = len < MAXINT ? (int)len : MAXINT;
1529 return r;
1530}
1531
1532static wchar_t *
1533get_process_name()
1534{
1535 DWORD bufferLen = MAX_PATH;
1536 DWORD len = bufferLen;
1537 wchar_t *r = NULL;
1538
1539 while (!r) {
1540 r = (wchar_t *)malloc(bufferLen * sizeof(wchar_t));
1541 if (!r) {
1542 error(RC_NO_MEMORY, L"out of memory");
1543 return NULL;
1544 }
1545 len = GetModuleFileNameW(NULL, r, bufferLen);
1546 if (len == 0) {
1547 free(r);
1548 error(0, L"Failed to get module name");
1549 return NULL;
1550 } else if (len == bufferLen &&
1551 GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
1552 free(r);
1553 r = NULL;
1554 bufferLen *= 2;
1555 }
1556 }
1557
1558 return r;
1559}
1560
Brian Curtin07165f72012-06-20 15:36:14 -05001561static int
1562process(int argc, wchar_t ** argv)
1563{
1564 wchar_t * wp;
1565 wchar_t * command;
Steve Dower76998fe2015-02-26 14:25:33 -08001566 wchar_t * executable;
Brian Curtin07165f72012-06-20 15:36:14 -05001567 wchar_t * p;
Steve Dowerb264c602018-12-10 08:11:34 -08001568 wchar_t * argv0;
Brian Curtin07165f72012-06-20 15:36:14 -05001569 int rc = 0;
Brian Curtin07165f72012-06-20 15:36:14 -05001570 INSTALLED_PYTHON * ip;
1571 BOOL valid;
1572 DWORD size, attrs;
Brian Curtin07165f72012-06-20 15:36:14 -05001573 wchar_t message[MSGSIZE];
Brian Curtin07165f72012-06-20 15:36:14 -05001574 void * version_data;
1575 VS_FIXEDFILEINFO * file_info;
1576 UINT block_size;
Steve Dowerb264c602018-12-10 08:11:34 -08001577#if defined(VENV_REDIRECT)
1578 wchar_t * venv_cfg_path;
Vinay Sajipc985d082013-07-25 11:20:55 +01001579 int newlen;
Steve Dowerb264c602018-12-10 08:11:34 -08001580#elif defined(SCRIPT_WRAPPER)
Vinay Sajipc985d082013-07-25 11:20:55 +01001581 wchar_t * newcommand;
1582 wchar_t * av[2];
Steve Dowerb264c602018-12-10 08:11:34 -08001583 int newlen;
1584 HRESULT hr;
1585 int index;
1586#else
1587 HRESULT hr;
1588 int index;
Vinay Sajipc985d082013-07-25 11:20:55 +01001589#endif
Brian Curtin07165f72012-06-20 15:36:14 -05001590
Vinay Sajipaab9f462015-12-26 12:35:47 +00001591 setvbuf(stderr, (char *)NULL, _IONBF, 0);
Brian Curtin07165f72012-06-20 15:36:14 -05001592 wp = get_env(L"PYLAUNCH_DEBUG");
1593 if ((wp != NULL) && (*wp != L'\0'))
1594 log_fp = stderr;
1595
1596#if defined(_M_X64)
1597 debug(L"launcher build: 64bit\n");
1598#else
1599 debug(L"launcher build: 32bit\n");
1600#endif
1601#if defined(_WINDOWS)
1602 debug(L"launcher executable: Windows\n");
1603#else
1604 debug(L"launcher executable: Console\n");
1605#endif
Steve Dowerb264c602018-12-10 08:11:34 -08001606#if !defined(VENV_REDIRECT)
Brian Curtin07165f72012-06-20 15:36:14 -05001607 /* Get the local appdata folder (non-roaming) */
1608 hr = SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA,
1609 NULL, 0, appdata_ini_path);
1610 if (hr != S_OK) {
1611 debug(L"SHGetFolderPath failed: %X\n", hr);
1612 appdata_ini_path[0] = L'\0';
1613 }
1614 else {
Steve Dowerb264c602018-12-10 08:11:34 -08001615 wcsncat_s(appdata_ini_path, MAX_PATH, L"\\py.ini", _TRUNCATE);
Brian Curtin07165f72012-06-20 15:36:14 -05001616 attrs = GetFileAttributesW(appdata_ini_path);
1617 if (attrs == INVALID_FILE_ATTRIBUTES) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001618 debug(L"File '%ls' non-existent\n", appdata_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001619 appdata_ini_path[0] = L'\0';
1620 } else {
Steve Dower84bcfb32015-01-02 18:07:46 -08001621 debug(L"Using local configuration file '%ls'\n", appdata_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001622 }
1623 }
Steve Dowerb264c602018-12-10 08:11:34 -08001624#endif
1625 argv0 = get_process_name();
1626 size = GetFileVersionInfoSizeW(argv0, &size);
Brian Curtin07165f72012-06-20 15:36:14 -05001627 if (size == 0) {
1628 winerror(GetLastError(), message, MSGSIZE);
Steve Dower84bcfb32015-01-02 18:07:46 -08001629 debug(L"GetFileVersionInfoSize failed: %ls\n", message);
Brian Curtin07165f72012-06-20 15:36:14 -05001630 }
1631 else {
1632 version_data = malloc(size);
1633 if (version_data) {
Steve Dowerb264c602018-12-10 08:11:34 -08001634 valid = GetFileVersionInfoW(argv0, 0, size,
Brian Curtin07165f72012-06-20 15:36:14 -05001635 version_data);
1636 if (!valid)
1637 debug(L"GetFileVersionInfo failed: %X\n", GetLastError());
1638 else {
Vinay Sajip404229b2013-01-29 22:52:57 +00001639 valid = VerQueryValueW(version_data, L"\\",
1640 (LPVOID *) &file_info, &block_size);
Brian Curtin07165f72012-06-20 15:36:14 -05001641 if (!valid)
1642 debug(L"VerQueryValue failed: %X\n", GetLastError());
1643 else {
1644 version_high = file_info->dwFileVersionMS;
1645 version_low = file_info->dwFileVersionLS;
1646 }
1647 }
1648 free(version_data);
1649 }
1650 }
Steve Dowerb264c602018-12-10 08:11:34 -08001651
1652#if defined(VENV_REDIRECT)
1653 /* Allocate some extra space for new filenames */
1654 venv_cfg_path = wcsdup_pad(argv0, 32, &newlen);
1655 if (!venv_cfg_path) {
1656 error(RC_NO_MEMORY, L"Failed to copy module name");
1657 }
1658 p = wcsrchr(venv_cfg_path, L'\\');
1659
1660 if (p == NULL) {
1661 error(RC_NO_VENV_CFG, L"No pyvenv.cfg file");
1662 }
1663 p[0] = L'\0';
1664 wcscat_s(venv_cfg_path, newlen, L"\\pyvenv.cfg");
1665 attrs = GetFileAttributesW(venv_cfg_path);
1666 if (attrs == INVALID_FILE_ATTRIBUTES) {
1667 debug(L"File '%ls' non-existent\n", venv_cfg_path);
1668 p[0] = '\0';
1669 p = wcsrchr(venv_cfg_path, L'\\');
1670 if (p != NULL) {
1671 p[0] = '\0';
1672 wcscat_s(venv_cfg_path, newlen, L"\\pyvenv.cfg");
1673 attrs = GetFileAttributesW(venv_cfg_path);
1674 if (attrs == INVALID_FILE_ATTRIBUTES) {
1675 debug(L"File '%ls' non-existent\n", venv_cfg_path);
1676 error(RC_NO_VENV_CFG, L"No pyvenv.cfg file");
1677 }
1678 }
1679 }
1680 debug(L"Using venv configuration file '%ls'\n", venv_cfg_path);
1681#else
1682 /* Allocate some extra space for new filenames */
1683 if (wcscpy_s(launcher_ini_path, MAX_PATH, argv0)) {
1684 error(RC_NO_MEMORY, L"Failed to copy module name");
1685 }
Brian Curtin07165f72012-06-20 15:36:14 -05001686 p = wcsrchr(launcher_ini_path, L'\\');
Steve Dowerb264c602018-12-10 08:11:34 -08001687
Brian Curtin07165f72012-06-20 15:36:14 -05001688 if (p == NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001689 debug(L"GetModuleFileNameW returned value has no backslash: %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -05001690 launcher_ini_path);
1691 launcher_ini_path[0] = L'\0';
1692 }
1693 else {
Steve Dowerb264c602018-12-10 08:11:34 -08001694 p[0] = L'\0';
1695 wcscat_s(launcher_ini_path, MAX_PATH, L"\\py.ini");
Brian Curtin07165f72012-06-20 15:36:14 -05001696 attrs = GetFileAttributesW(launcher_ini_path);
1697 if (attrs == INVALID_FILE_ATTRIBUTES) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001698 debug(L"File '%ls' non-existent\n", launcher_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001699 launcher_ini_path[0] = L'\0';
1700 } else {
Steve Dower84bcfb32015-01-02 18:07:46 -08001701 debug(L"Using global configuration file '%ls'\n", launcher_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001702 }
1703 }
Steve Dowerb264c602018-12-10 08:11:34 -08001704#endif
Brian Curtin07165f72012-06-20 15:36:14 -05001705
1706 command = skip_me(GetCommandLineW());
Steve Dower84bcfb32015-01-02 18:07:46 -08001707 debug(L"Called with command line: %ls\n", command);
Vinay Sajipc985d082013-07-25 11:20:55 +01001708
1709#if defined(SCRIPT_WRAPPER)
1710 /* The launcher is being used in "script wrapper" mode.
1711 * There should therefore be a Python script named <exename>-script.py in
1712 * the same directory as the launcher executable.
1713 * Put the script name into argv as the first (script name) argument.
1714 */
1715
1716 /* Get the wrapped script name - if the script is not present, this will
1717 * terminate the program with an error.
1718 */
1719 locate_wrapped_script();
1720
1721 /* Add the wrapped script to the start of command */
1722 newlen = wcslen(wrapped_script_path) + wcslen(command) + 2; /* ' ' + NUL */
1723 newcommand = malloc(sizeof(wchar_t) * newlen);
1724 if (!newcommand) {
1725 error(RC_NO_MEMORY, L"Could not allocate new command line");
1726 }
1727 else {
1728 wcscpy_s(newcommand, newlen, wrapped_script_path);
1729 wcscat_s(newcommand, newlen, L" ");
1730 wcscat_s(newcommand, newlen, command);
Steve Dower84bcfb32015-01-02 18:07:46 -08001731 debug(L"Running wrapped script with command line '%ls'\n", newcommand);
Vinay Sajipc985d082013-07-25 11:20:55 +01001732 read_commands();
1733 av[0] = wrapped_script_path;
1734 av[1] = NULL;
1735 maybe_handle_shebang(av, newcommand);
1736 /* Returns if no shebang line - pass to default processing */
1737 command = newcommand;
1738 valid = FALSE;
1739 }
Steve Dowerb264c602018-12-10 08:11:34 -08001740#elif defined(VENV_REDIRECT)
1741 {
1742 FILE *f;
1743 char buffer[4096]; /* 4KB should be enough for anybody */
1744 char *start;
1745 DWORD len, cch, cch_actual;
1746 size_t cb;
1747 if (_wfopen_s(&f, venv_cfg_path, L"r")) {
1748 error(RC_BAD_VENV_CFG, L"Cannot read '%ls'", venv_cfg_path);
1749 }
1750 cb = fread_s(buffer, sizeof(buffer), sizeof(buffer[0]),
1751 sizeof(buffer) / sizeof(buffer[0]), f);
1752 fclose(f);
1753
1754 if (!find_home_value(buffer, &start, &len)) {
1755 error(RC_BAD_VENV_CFG, L"Cannot find home in '%ls'",
1756 venv_cfg_path);
1757 }
1758
1759 cch = MultiByteToWideChar(CP_UTF8, 0, start, len, NULL, 0);
1760 if (!cch) {
1761 error(0, L"Cannot determine memory for home path");
1762 }
1763 cch += (DWORD)wcslen(PYTHON_EXECUTABLE) + 1 + 1; /* include sep and null */
1764 executable = (wchar_t *)malloc(cch * sizeof(wchar_t));
1765 if (executable == NULL) {
1766 error(RC_NO_MEMORY, L"A memory allocation failed");
1767 }
1768 cch_actual = MultiByteToWideChar(CP_UTF8, 0, start, len, executable, cch);
1769 if (!cch_actual) {
1770 error(RC_BAD_VENV_CFG, L"Cannot decode home path in '%ls'",
1771 venv_cfg_path);
1772 }
1773 if (executable[cch_actual - 1] != L'\\') {
1774 executable[cch_actual++] = L'\\';
1775 executable[cch_actual] = L'\0';
1776 }
1777 if (wcscat_s(executable, cch, PYTHON_EXECUTABLE)) {
1778 error(RC_BAD_VENV_CFG, L"Cannot create executable path from '%ls'",
1779 venv_cfg_path);
1780 }
1781 if (GetFileAttributesW(executable) == INVALID_FILE_ATTRIBUTES) {
1782 error(RC_NO_PYTHON, L"No Python at '%ls'", executable);
1783 }
1784 if (!SetEnvironmentVariableW(L"__PYVENV_LAUNCHER__", argv0)) {
1785 error(0, L"Failed to set launcher environment");
1786 }
1787 valid = 1;
1788 }
Vinay Sajipc985d082013-07-25 11:20:55 +01001789#else
Brian Curtin07165f72012-06-20 15:36:14 -05001790 if (argc <= 1) {
1791 valid = FALSE;
1792 p = NULL;
1793 }
1794 else {
1795 p = argv[1];
Miss Islington (bot)129642a2018-11-20 13:48:34 -08001796 if ((argc == 2) && // list version args
1797 (!wcsncmp(p, L"-0", wcslen(L"-0")) ||
Miss Islington (bot)5df36582018-08-31 11:32:22 -04001798 !wcsncmp(p, L"--list", wcslen(L"--list"))))
1799 {
Miss Islington (bot)129642a2018-11-20 13:48:34 -08001800 show_python_list(argv);
1801 return rc;
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001802 }
1803 valid = valid && (*p == L'-') && validate_version(&p[1]);
Brian Curtin07165f72012-06-20 15:36:14 -05001804 if (valid) {
Paul Moore835416c2016-05-22 12:28:41 +01001805 ip = locate_python(&p[1], FALSE);
Brian Curtin07165f72012-06-20 15:36:14 -05001806 if (ip == NULL)
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001807 {
1808 fwprintf(stdout, \
1809 L"Python %ls not found!\n", &p[1]);
1810 valid = show_python_list(argv);
Steve Dower84bcfb32015-01-02 18:07:46 -08001811 error(RC_NO_PYTHON, L"Requested Python version (%ls) not \
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001812installed, use -0 for available pythons", &p[1]);
1813 }
Steve Dower76998fe2015-02-26 14:25:33 -08001814 executable = ip->executable;
Brian Curtin07165f72012-06-20 15:36:14 -05001815 command += wcslen(p);
1816 command = skip_whitespace(command);
1817 }
Vinay Sajip2ae8c632013-01-29 22:29:25 +00001818 else {
1819 for (index = 1; index < argc; ++index) {
1820 if (*argv[index] != L'-')
1821 break;
1822 }
1823 if (index < argc) {
1824 read_commands();
1825 maybe_handle_shebang(&argv[index], command);
1826 }
1827 }
Brian Curtin07165f72012-06-20 15:36:14 -05001828 }
Vinay Sajipc985d082013-07-25 11:20:55 +01001829#endif
1830
Brian Curtin07165f72012-06-20 15:36:14 -05001831 if (!valid) {
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001832 if ((argc == 2) && (!_wcsicmp(p, L"-h") || !_wcsicmp(p, L"--help")))
1833 show_help_text(argv);
Miss Islington (bot)5df36582018-08-31 11:32:22 -04001834 if ((argc == 2) &&
1835 (!_wcsicmp(p, L"-0") || !_wcsicmp(p, L"--list") ||
1836 !_wcsicmp(p, L"-0p") || !_wcsicmp(p, L"--list-paths")))
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001837 {
Miss Islington (bot)5df36582018-08-31 11:32:22 -04001838 executable = NULL; /* Info call only */
1839 }
1840 else {
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001841 /* Look for an active virtualenv */
1842 executable = find_python_by_venv();
Steve Dower76998fe2015-02-26 14:25:33 -08001843
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001844 /* If we didn't find one, look for the default Python */
1845 if (executable == NULL) {
1846 ip = locate_python(L"", FALSE);
1847 if (ip == NULL)
1848 error(RC_NO_PYTHON, L"Can't find a default Python.");
1849 executable = ip->executable;
Brian Curtin07165f72012-06-20 15:36:14 -05001850 }
Brian Curtin07165f72012-06-20 15:36:14 -05001851 }
1852 }
Steve (Gadget) Barnes5b8f9722017-06-28 20:14:52 +01001853 if (executable != NULL)
1854 invoke_child(executable, NULL, command);
1855 else
1856 rc = RC_NO_PYTHON;
Brian Curtin07165f72012-06-20 15:36:14 -05001857 return rc;
1858}
1859
1860#if defined(_WINDOWS)
1861
1862int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
1863 LPWSTR lpstrCmd, int nShow)
1864{
1865 return process(__argc, __wargv);
1866}
1867
1868#else
1869
1870int cdecl wmain(int argc, wchar_t ** argv)
1871{
1872 return process(argc, argv);
1873}
1874
Vinay Sajip2ae8c632013-01-29 22:29:25 +00001875#endif