blob: e6288451546d956bc58e23d63c93366472722cd9 [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/*
31 * SCRIPT_WRAPPER is used to choose between two variants of an executable built
32 * from this source file. If not defined, the PEP 397 Python launcher is built;
33 * if defined, a script launcher of the type used by setuptools is built, which
34 * looks for a script name related to the executable name and runs that script
35 * with the appropriate Python interpreter.
36 *
37 * SCRIPT_WRAPPER should be undefined in the source, and defined in a VS project
38 * which builds the setuptools-style launcher.
39 */
40#if defined(SCRIPT_WRAPPER)
41#define RC_NO_SCRIPT 105
42#endif
43
Brian Curtin07165f72012-06-20 15:36:14 -050044/* Just for now - static definition */
45
46static FILE * log_fp = NULL;
47
48static wchar_t *
49skip_whitespace(wchar_t * p)
50{
51 while (*p && isspace(*p))
52 ++p;
53 return p;
54}
55
Brian Curtin07165f72012-06-20 15:36:14 -050056static void
57debug(wchar_t * format, ...)
58{
59 va_list va;
60
61 if (log_fp != NULL) {
62 va_start(va, format);
63 vfwprintf_s(log_fp, format, va);
64 }
65}
66
67static void
68winerror(int rc, wchar_t * message, int size)
69{
70 FormatMessageW(
71 FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
72 NULL, rc, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
73 message, size, NULL);
74}
75
76static void
77error(int rc, wchar_t * format, ... )
78{
79 va_list va;
80 wchar_t message[MSGSIZE];
81 wchar_t win_message[MSGSIZE];
82 int len;
83
84 va_start(va, format);
85 len = _vsnwprintf_s(message, MSGSIZE, _TRUNCATE, format, va);
86
87 if (rc == 0) { /* a Windows error */
88 winerror(GetLastError(), win_message, MSGSIZE);
89 if (len >= 0) {
Steve Dower84bcfb32015-01-02 18:07:46 -080090 _snwprintf_s(&message[len], MSGSIZE - len, _TRUNCATE, L": %ls",
Brian Curtin07165f72012-06-20 15:36:14 -050091 win_message);
92 }
93 }
94
95#if !defined(_WINDOWS)
Steve Dower84bcfb32015-01-02 18:07:46 -080096 fwprintf(stderr, L"%ls\n", message);
Brian Curtin07165f72012-06-20 15:36:14 -050097#else
Vinay Sajipc985d082013-07-25 11:20:55 +010098 MessageBox(NULL, message, TEXT("Python Launcher is sorry to say ..."),
Serhiy Storchaka009b8112015-03-18 21:53:15 +020099 MB_OK);
Brian Curtin07165f72012-06-20 15:36:14 -0500100#endif
Vinay Sajipaab9f462015-12-26 12:35:47 +0000101 exit(rc);
Brian Curtin07165f72012-06-20 15:36:14 -0500102}
103
Vinay Sajipc985d082013-07-25 11:20:55 +0100104/*
105 * This function is here to simplify memory management
106 * and to treat blank values as if they are absent.
107 */
108static wchar_t * get_env(wchar_t * key)
109{
110 /* This is not thread-safe, just like getenv */
111 static wchar_t buf[BUFSIZE];
112 DWORD result = GetEnvironmentVariableW(key, buf, BUFSIZE);
113
114 if (result >= BUFSIZE) {
115 /* Large environment variable. Accept some leakage */
116 wchar_t *buf2 = (wchar_t*)malloc(sizeof(wchar_t) * (result+1));
Vinay Sajipabeb6472015-12-13 09:41:29 +0000117 if (buf2 == NULL) {
Vinay Sajipc985d082013-07-25 11:20:55 +0100118 error(RC_NO_MEMORY, L"Could not allocate environment buffer");
119 }
120 GetEnvironmentVariableW(key, buf2, result);
121 return buf2;
122 }
123
124 if (result == 0)
125 /* Either some error, e.g. ERROR_ENVVAR_NOT_FOUND,
126 or an empty environment variable. */
127 return NULL;
128
129 return buf;
130}
131
Brian Curtin07165f72012-06-20 15:36:14 -0500132#if defined(_WINDOWS)
133
134#define PYTHON_EXECUTABLE L"pythonw.exe"
135
136#else
137
138#define PYTHON_EXECUTABLE L"python.exe"
139
140#endif
141
Brian Curtin07165f72012-06-20 15:36:14 -0500142#define MAX_VERSION_SIZE 4
143
144typedef struct {
145 wchar_t version[MAX_VERSION_SIZE]; /* m.n */
146 int bits; /* 32 or 64 */
147 wchar_t executable[MAX_PATH];
148} INSTALLED_PYTHON;
149
150/*
151 * To avoid messing about with heap allocations, just assume we can allocate
152 * statically and never have to deal with more versions than this.
153 */
154#define MAX_INSTALLED_PYTHONS 100
155
156static INSTALLED_PYTHON installed_pythons[MAX_INSTALLED_PYTHONS];
157
158static size_t num_installed_pythons = 0;
159
Steve Dowerbb240872015-02-05 22:08:48 -0800160/*
161 * To hold SOFTWARE\Python\PythonCore\X.Y...\InstallPath
162 * The version name can be longer than MAX_VERSION_SIZE, but will be
163 * truncated to just X.Y for comparisons.
164 */
Brian Curtin07165f72012-06-20 15:36:14 -0500165#define IP_BASE_SIZE 40
Steve Dowerbb240872015-02-05 22:08:48 -0800166#define IP_VERSION_SIZE 8
167#define IP_SIZE (IP_BASE_SIZE + IP_VERSION_SIZE)
Brian Curtin07165f72012-06-20 15:36:14 -0500168#define CORE_PATH L"SOFTWARE\\Python\\PythonCore"
169
170static wchar_t * location_checks[] = {
171 L"\\",
Steve Dowerbb240872015-02-05 22:08:48 -0800172 L"\\PCBuild\\win32\\",
Brian Curtin07165f72012-06-20 15:36:14 -0500173 L"\\PCBuild\\amd64\\",
Mark Hammond32d1e562016-01-11 14:53:01 +1100174 // To support early 32bit versions of Python that stuck the build binaries
175 // directly in PCBuild...
176 L"\\PCBuild\\",
Brian Curtin07165f72012-06-20 15:36:14 -0500177 NULL
178};
179
180static INSTALLED_PYTHON *
181find_existing_python(wchar_t * path)
182{
183 INSTALLED_PYTHON * result = NULL;
184 size_t i;
185 INSTALLED_PYTHON * ip;
186
187 for (i = 0, ip = installed_pythons; i < num_installed_pythons; i++, ip++) {
188 if (_wcsicmp(path, ip->executable) == 0) {
189 result = ip;
190 break;
191 }
192 }
193 return result;
194}
195
196static void
197locate_pythons_for_key(HKEY root, REGSAM flags)
198{
199 HKEY core_root, ip_key;
200 LSTATUS status = RegOpenKeyExW(root, CORE_PATH, 0, flags, &core_root);
201 wchar_t message[MSGSIZE];
202 DWORD i;
203 size_t n;
204 BOOL ok;
205 DWORD type, data_size, attrs;
206 INSTALLED_PYTHON * ip, * pip;
Steve Dowerbb240872015-02-05 22:08:48 -0800207 wchar_t ip_version[IP_VERSION_SIZE];
Brian Curtin07165f72012-06-20 15:36:14 -0500208 wchar_t ip_path[IP_SIZE];
209 wchar_t * check;
210 wchar_t ** checkp;
211 wchar_t *key_name = (root == HKEY_LOCAL_MACHINE) ? L"HKLM" : L"HKCU";
212
213 if (status != ERROR_SUCCESS)
Steve Dower84bcfb32015-01-02 18:07:46 -0800214 debug(L"locate_pythons_for_key: unable to open PythonCore key in %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500215 key_name);
216 else {
217 ip = &installed_pythons[num_installed_pythons];
218 for (i = 0; num_installed_pythons < MAX_INSTALLED_PYTHONS; i++) {
Steve Dowerbb240872015-02-05 22:08:48 -0800219 status = RegEnumKeyW(core_root, i, ip_version, IP_VERSION_SIZE);
Brian Curtin07165f72012-06-20 15:36:14 -0500220 if (status != ERROR_SUCCESS) {
221 if (status != ERROR_NO_MORE_ITEMS) {
222 /* unexpected error */
223 winerror(status, message, MSGSIZE);
Steve Dower84bcfb32015-01-02 18:07:46 -0800224 debug(L"Can't enumerate registry key for version %ls: %ls\n",
Steve Dowerbb240872015-02-05 22:08:48 -0800225 ip_version, message);
Brian Curtin07165f72012-06-20 15:36:14 -0500226 }
227 break;
228 }
229 else {
Steve Dowerbb240872015-02-05 22:08:48 -0800230 wcsncpy_s(ip->version, MAX_VERSION_SIZE, ip_version,
231 MAX_VERSION_SIZE-1);
Brian Curtin07165f72012-06-20 15:36:14 -0500232 _snwprintf_s(ip_path, IP_SIZE, _TRUNCATE,
Steve Dowerbb240872015-02-05 22:08:48 -0800233 L"%ls\\%ls\\InstallPath", CORE_PATH, ip_version);
Brian Curtin07165f72012-06-20 15:36:14 -0500234 status = RegOpenKeyExW(root, ip_path, 0, flags, &ip_key);
235 if (status != ERROR_SUCCESS) {
236 winerror(status, message, MSGSIZE);
237 // Note: 'message' already has a trailing \n
Steve Dower84bcfb32015-01-02 18:07:46 -0800238 debug(L"%ls\\%ls: %ls", key_name, ip_path, message);
Brian Curtin07165f72012-06-20 15:36:14 -0500239 continue;
240 }
241 data_size = sizeof(ip->executable) - 1;
Martin v. Löwisaf21ebb2012-06-21 18:15:54 +0200242 status = RegQueryValueExW(ip_key, NULL, NULL, &type,
243 (LPBYTE)ip->executable, &data_size);
Brian Curtin07165f72012-06-20 15:36:14 -0500244 RegCloseKey(ip_key);
245 if (status != ERROR_SUCCESS) {
246 winerror(status, message, MSGSIZE);
Steve Dower84bcfb32015-01-02 18:07:46 -0800247 debug(L"%ls\\%ls: %ls\n", key_name, ip_path, message);
Brian Curtin07165f72012-06-20 15:36:14 -0500248 continue;
249 }
250 if (type == REG_SZ) {
251 data_size = data_size / sizeof(wchar_t) - 1; /* for NUL */
252 if (ip->executable[data_size - 1] == L'\\')
253 --data_size; /* reg value ended in a backslash */
254 /* ip->executable is data_size long */
255 for (checkp = location_checks; *checkp; ++checkp) {
256 check = *checkp;
257 _snwprintf_s(&ip->executable[data_size],
258 MAX_PATH - data_size,
259 MAX_PATH - data_size,
Steve Dower84bcfb32015-01-02 18:07:46 -0800260 L"%ls%ls", check, PYTHON_EXECUTABLE);
Brian Curtin07165f72012-06-20 15:36:14 -0500261 attrs = GetFileAttributesW(ip->executable);
262 if (attrs == INVALID_FILE_ATTRIBUTES) {
263 winerror(GetLastError(), message, MSGSIZE);
Steve Dower84bcfb32015-01-02 18:07:46 -0800264 debug(L"locate_pythons_for_key: %ls: %ls",
Brian Curtin07165f72012-06-20 15:36:14 -0500265 ip->executable, message);
266 }
267 else if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800268 debug(L"locate_pythons_for_key: '%ls' is a \
Brian Curtin07165f72012-06-20 15:36:14 -0500269directory\n",
270 ip->executable, attrs);
271 }
272 else if (find_existing_python(ip->executable)) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800273 debug(L"locate_pythons_for_key: %ls: already \
Steve Dower13be8c22015-03-10 19:38:25 -0700274found\n", ip->executable);
Brian Curtin07165f72012-06-20 15:36:14 -0500275 }
276 else {
277 /* check the executable type. */
278 ok = GetBinaryTypeW(ip->executable, &attrs);
279 if (!ok) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800280 debug(L"Failure getting binary type: %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500281 ip->executable);
282 }
283 else {
284 if (attrs == SCS_64BIT_BINARY)
285 ip->bits = 64;
286 else if (attrs == SCS_32BIT_BINARY)
287 ip->bits = 32;
288 else
289 ip->bits = 0;
290 if (ip->bits == 0) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800291 debug(L"locate_pythons_for_key: %ls: \
Brian Curtin07165f72012-06-20 15:36:14 -0500292invalid binary type: %X\n",
293 ip->executable, attrs);
294 }
295 else {
296 if (wcschr(ip->executable, L' ') != NULL) {
297 /* has spaces, so quote */
298 n = wcslen(ip->executable);
299 memmove(&ip->executable[1],
300 ip->executable, n * sizeof(wchar_t));
301 ip->executable[0] = L'\"';
302 ip->executable[n + 1] = L'\"';
303 ip->executable[n + 2] = L'\0';
304 }
Steve Dower84bcfb32015-01-02 18:07:46 -0800305 debug(L"locate_pythons_for_key: %ls \
Brian Curtin07165f72012-06-20 15:36:14 -0500306is a %dbit executable\n",
307 ip->executable, ip->bits);
308 ++num_installed_pythons;
309 pip = ip++;
310 if (num_installed_pythons >=
311 MAX_INSTALLED_PYTHONS)
312 break;
313 /* Copy over the attributes for the next */
314 *ip = *pip;
315 }
316 }
317 }
318 }
319 }
320 }
321 }
322 RegCloseKey(core_root);
323 }
324}
325
326static int
327compare_pythons(const void * p1, const void * p2)
328{
329 INSTALLED_PYTHON * ip1 = (INSTALLED_PYTHON *) p1;
330 INSTALLED_PYTHON * ip2 = (INSTALLED_PYTHON *) p2;
331 /* note reverse sorting on version */
332 int result = wcscmp(ip2->version, ip1->version);
333
334 if (result == 0)
335 result = ip2->bits - ip1->bits; /* 64 before 32 */
336 return result;
337}
338
339static void
340locate_all_pythons()
341{
342#if defined(_M_X64)
343 // If we are a 64bit process, first hit the 32bit keys.
344 debug(L"locating Pythons in 32bit registry\n");
345 locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ | KEY_WOW64_32KEY);
346 locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ | KEY_WOW64_32KEY);
347#else
348 // If we are a 32bit process on a 64bit Windows, first hit the 64bit keys.
349 BOOL f64 = FALSE;
350 if (IsWow64Process(GetCurrentProcess(), &f64) && f64) {
351 debug(L"locating Pythons in 64bit registry\n");
352 locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ | KEY_WOW64_64KEY);
353 locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ | KEY_WOW64_64KEY);
354 }
Serhiy Storchaka009b8112015-03-18 21:53:15 +0200355#endif
Brian Curtin07165f72012-06-20 15:36:14 -0500356 // now hit the "native" key for this process bittedness.
357 debug(L"locating Pythons in native registry\n");
358 locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ);
359 locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ);
360 qsort(installed_pythons, num_installed_pythons, sizeof(INSTALLED_PYTHON),
361 compare_pythons);
362}
363
364static INSTALLED_PYTHON *
365find_python_by_version(wchar_t const * wanted_ver)
366{
367 INSTALLED_PYTHON * result = NULL;
368 INSTALLED_PYTHON * ip = installed_pythons;
369 size_t i, n;
370 size_t wlen = wcslen(wanted_ver);
371 int bits = 0;
372
373 if (wcsstr(wanted_ver, L"-32"))
374 bits = 32;
375 for (i = 0; i < num_installed_pythons; i++, ip++) {
376 n = wcslen(ip->version);
377 if (n > wlen)
378 n = wlen;
379 if ((wcsncmp(ip->version, wanted_ver, n) == 0) &&
380 /* bits == 0 => don't care */
381 ((bits == 0) || (ip->bits == bits))) {
382 result = ip;
383 break;
384 }
385 }
386 return result;
387}
388
389
Steve Dower76998fe2015-02-26 14:25:33 -0800390static wchar_t *
391find_python_by_venv()
392{
393 static wchar_t venv_python[MAX_PATH];
394 wchar_t *virtual_env = get_env(L"VIRTUAL_ENV");
395 DWORD attrs;
396
397 /* Check for VIRTUAL_ENV environment variable */
398 if (virtual_env == NULL || virtual_env[0] == L'\0') {
399 return NULL;
400 }
401
402 /* Check for a python executable in the venv */
403 debug(L"Checking for Python executable in virtual env '%ls'\n", virtual_env);
404 _snwprintf_s(venv_python, MAX_PATH, _TRUNCATE,
405 L"%ls\\Scripts\\%ls", virtual_env, PYTHON_EXECUTABLE);
406 attrs = GetFileAttributesW(venv_python);
407 if (attrs == INVALID_FILE_ATTRIBUTES) {
408 debug(L"Python executable %ls missing from virtual env\n", venv_python);
409 return NULL;
410 }
411
412 return venv_python;
413}
414
Brian Curtin07165f72012-06-20 15:36:14 -0500415static wchar_t appdata_ini_path[MAX_PATH];
416static wchar_t launcher_ini_path[MAX_PATH];
417
418/*
419 * Get a value either from the environment or a configuration file.
420 * The key passed in will either be "python", "python2" or "python3".
421 */
422static wchar_t *
423get_configured_value(wchar_t * key)
424{
425/*
426 * Note: this static value is used to return a configured value
427 * obtained either from the environment or configuration file.
428 * This should be OK since there wouldn't be any concurrent calls.
429 */
430 static wchar_t configured_value[MSGSIZE];
431 wchar_t * result = NULL;
432 wchar_t * found_in = L"environment";
433 DWORD size;
434
435 /* First, search the environment. */
Steve Dower84bcfb32015-01-02 18:07:46 -0800436 _snwprintf_s(configured_value, MSGSIZE, _TRUNCATE, L"py_%ls", key);
Brian Curtin07165f72012-06-20 15:36:14 -0500437 result = get_env(configured_value);
438 if (result == NULL && appdata_ini_path[0]) {
439 /* Not in environment: check local configuration. */
440 size = GetPrivateProfileStringW(L"defaults", key, NULL,
441 configured_value, MSGSIZE,
442 appdata_ini_path);
443 if (size > 0) {
444 result = configured_value;
445 found_in = appdata_ini_path;
446 }
447 }
448 if (result == NULL && launcher_ini_path[0]) {
449 /* Not in environment or local: check global configuration. */
450 size = GetPrivateProfileStringW(L"defaults", key, NULL,
451 configured_value, MSGSIZE,
452 launcher_ini_path);
453 if (size > 0) {
454 result = configured_value;
455 found_in = launcher_ini_path;
456 }
457 }
458 if (result) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800459 debug(L"found configured value '%ls=%ls' in %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500460 key, result, found_in ? found_in : L"(unknown)");
461 } else {
Steve Dower84bcfb32015-01-02 18:07:46 -0800462 debug(L"found no configured value for '%ls'\n", key);
Brian Curtin07165f72012-06-20 15:36:14 -0500463 }
464 return result;
465}
466
467static INSTALLED_PYTHON *
Paul Moore835416c2016-05-22 12:28:41 +0100468locate_python(wchar_t * wanted_ver, BOOL from_shebang)
Brian Curtin07165f72012-06-20 15:36:14 -0500469{
470 static wchar_t config_key [] = { L"pythonX" };
471 static wchar_t * last_char = &config_key[sizeof(config_key) /
472 sizeof(wchar_t) - 2];
473 INSTALLED_PYTHON * result = NULL;
474 size_t n = wcslen(wanted_ver);
475 wchar_t * configured_value;
476
477 if (num_installed_pythons == 0)
478 locate_all_pythons();
479
480 if (n == 1) { /* just major version specified */
481 *last_char = *wanted_ver;
482 configured_value = get_configured_value(config_key);
483 if (configured_value != NULL)
484 wanted_ver = configured_value;
485 }
486 if (*wanted_ver) {
487 result = find_python_by_version(wanted_ver);
Steve Dower84bcfb32015-01-02 18:07:46 -0800488 debug(L"search for Python version '%ls' found ", wanted_ver);
Brian Curtin07165f72012-06-20 15:36:14 -0500489 if (result) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800490 debug(L"'%ls'\n", result->executable);
Brian Curtin07165f72012-06-20 15:36:14 -0500491 } else {
492 debug(L"no interpreter\n");
493 }
494 }
495 else {
496 *last_char = L'\0'; /* look for an overall default */
497 configured_value = get_configured_value(config_key);
498 if (configured_value)
499 result = find_python_by_version(configured_value);
Paul Moore835416c2016-05-22 12:28:41 +0100500 /* Not found a value yet - try by major version.
501 * If we're looking for an interpreter specified in a shebang line,
502 * we want to try Python 2 first, then Python 3 (for Unix and backward
503 * compatibility). If we're being called interactively, assume the user
504 * wants the latest version available, so try Python 3 first, then
505 * Python 2.
506 */
Brian Curtin07165f72012-06-20 15:36:14 -0500507 if (result == NULL)
Paul Moore835416c2016-05-22 12:28:41 +0100508 result = find_python_by_version(from_shebang ? L"2" : L"3");
Brian Curtin07165f72012-06-20 15:36:14 -0500509 if (result == NULL)
Paul Moore835416c2016-05-22 12:28:41 +0100510 result = find_python_by_version(from_shebang ? L"3" : L"2");
Brian Curtin07165f72012-06-20 15:36:14 -0500511 debug(L"search for default Python found ");
512 if (result) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800513 debug(L"version %ls at '%ls'\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500514 result->version, result->executable);
515 } else {
516 debug(L"no interpreter\n");
517 }
518 }
519 return result;
520}
521
Vinay Sajipc985d082013-07-25 11:20:55 +0100522#if defined(SCRIPT_WRAPPER)
523/*
524 * Check for a script located alongside the executable
525 */
526
527#if defined(_WINDOWS)
528#define SCRIPT_SUFFIX L"-script.pyw"
529#else
530#define SCRIPT_SUFFIX L"-script.py"
531#endif
532
533static wchar_t wrapped_script_path[MAX_PATH];
534
535/* Locate the script being wrapped.
536 *
537 * This code should store the name of the wrapped script in
538 * wrapped_script_path, or terminate the program with an error if there is no
539 * valid wrapped script file.
540 */
541static void
542locate_wrapped_script()
543{
544 wchar_t * p;
545 size_t plen;
546 DWORD attrs;
547
548 plen = GetModuleFileNameW(NULL, wrapped_script_path, MAX_PATH);
549 p = wcsrchr(wrapped_script_path, L'.');
550 if (p == NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800551 debug(L"GetModuleFileNameW returned value has no extension: %ls\n",
Vinay Sajipc985d082013-07-25 11:20:55 +0100552 wrapped_script_path);
Steve Dower84bcfb32015-01-02 18:07:46 -0800553 error(RC_NO_SCRIPT, L"Wrapper name '%ls' is not valid.", wrapped_script_path);
Vinay Sajipc985d082013-07-25 11:20:55 +0100554 }
555
556 wcsncpy_s(p, MAX_PATH - (p - wrapped_script_path) + 1, SCRIPT_SUFFIX, _TRUNCATE);
557 attrs = GetFileAttributesW(wrapped_script_path);
558 if (attrs == INVALID_FILE_ATTRIBUTES) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800559 debug(L"File '%ls' non-existent\n", wrapped_script_path);
560 error(RC_NO_SCRIPT, L"Script file '%ls' is not present.", wrapped_script_path);
Vinay Sajipc985d082013-07-25 11:20:55 +0100561 }
562
Steve Dower84bcfb32015-01-02 18:07:46 -0800563 debug(L"Using wrapped script file '%ls'\n", wrapped_script_path);
Vinay Sajipc985d082013-07-25 11:20:55 +0100564}
565#endif
566
Brian Curtin07165f72012-06-20 15:36:14 -0500567/*
568 * Process creation code
569 */
570
571static BOOL
572safe_duplicate_handle(HANDLE in, HANDLE * pout)
573{
574 BOOL ok;
575 HANDLE process = GetCurrentProcess();
576 DWORD rc;
577
578 *pout = NULL;
579 ok = DuplicateHandle(process, in, process, pout, 0, TRUE,
580 DUPLICATE_SAME_ACCESS);
581 if (!ok) {
582 rc = GetLastError();
583 if (rc == ERROR_INVALID_HANDLE) {
584 debug(L"DuplicateHandle returned ERROR_INVALID_HANDLE\n");
585 ok = TRUE;
586 }
587 else {
588 debug(L"DuplicateHandle returned %d\n", rc);
589 }
590 }
591 return ok;
592}
593
594static BOOL WINAPI
595ctrl_c_handler(DWORD code)
596{
597 return TRUE; /* We just ignore all control events. */
598}
599
600static void
601run_child(wchar_t * cmdline)
602{
603 HANDLE job;
604 JOBOBJECT_EXTENDED_LIMIT_INFORMATION info;
605 DWORD rc;
606 BOOL ok;
607 STARTUPINFOW si;
608 PROCESS_INFORMATION pi;
609
Vinay Sajip66fef9f2013-02-26 16:29:06 +0000610#if defined(_WINDOWS)
611 // When explorer launches a Windows (GUI) application, it displays
612 // the "app starting" (the "pointer + hourglass") cursor for a number
613 // of seconds, or until the app does something UI-ish (eg, creating a
614 // window, or fetching a message). As this launcher doesn't do this
615 // directly, that cursor remains even after the child process does these
616 // things. We avoid that by doing a simple post+get message.
Serhiy Storchaka009b8112015-03-18 21:53:15 +0200617 // See http://bugs.python.org/issue17290 and
Vinay Sajip66fef9f2013-02-26 16:29:06 +0000618 // https://bitbucket.org/vinay.sajip/pylauncher/issue/20/busy-cursor-for-a-long-time-when-running
619 MSG msg;
620
621 PostMessage(0, 0, 0, 0);
622 GetMessage(&msg, 0, 0, 0);
623#endif
624
Steve Dower84bcfb32015-01-02 18:07:46 -0800625 debug(L"run_child: about to run '%ls'\n", cmdline);
Brian Curtin07165f72012-06-20 15:36:14 -0500626 job = CreateJobObject(NULL, NULL);
627 ok = QueryInformationJobObject(job, JobObjectExtendedLimitInformation,
628 &info, sizeof(info), &rc);
629 if (!ok || (rc != sizeof(info)) || !job)
630 error(RC_CREATE_PROCESS, L"Job information querying failed");
631 info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE |
632 JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK;
633 ok = SetInformationJobObject(job, JobObjectExtendedLimitInformation, &info,
634 sizeof(info));
635 if (!ok)
636 error(RC_CREATE_PROCESS, L"Job information setting failed");
637 memset(&si, 0, sizeof(si));
638 si.cb = sizeof(si);
639 ok = safe_duplicate_handle(GetStdHandle(STD_INPUT_HANDLE), &si.hStdInput);
640 if (!ok)
641 error(RC_NO_STD_HANDLES, L"stdin duplication failed");
642 ok = safe_duplicate_handle(GetStdHandle(STD_OUTPUT_HANDLE), &si.hStdOutput);
643 if (!ok)
644 error(RC_NO_STD_HANDLES, L"stdout duplication failed");
645 ok = safe_duplicate_handle(GetStdHandle(STD_ERROR_HANDLE), &si.hStdError);
646 if (!ok)
647 error(RC_NO_STD_HANDLES, L"stderr duplication failed");
648
649 ok = SetConsoleCtrlHandler(ctrl_c_handler, TRUE);
650 if (!ok)
651 error(RC_CREATE_PROCESS, L"control handler setting failed");
652
653 si.dwFlags = STARTF_USESTDHANDLES;
654 ok = CreateProcessW(NULL, cmdline, NULL, NULL, TRUE,
655 0, NULL, NULL, &si, &pi);
656 if (!ok)
Steve Dower84bcfb32015-01-02 18:07:46 -0800657 error(RC_CREATE_PROCESS, L"Unable to create process using '%ls'", cmdline);
Brian Curtin07165f72012-06-20 15:36:14 -0500658 AssignProcessToJobObject(job, pi.hProcess);
659 CloseHandle(pi.hThread);
Martin v. Löwisb26a9b12013-01-25 14:25:48 +0100660 WaitForSingleObjectEx(pi.hProcess, INFINITE, FALSE);
Brian Curtin07165f72012-06-20 15:36:14 -0500661 ok = GetExitCodeProcess(pi.hProcess, &rc);
662 if (!ok)
663 error(RC_CREATE_PROCESS, L"Failed to get exit code of process");
664 debug(L"child process exit code: %d\n", rc);
Vinay Sajipaab9f462015-12-26 12:35:47 +0000665 exit(rc);
Brian Curtin07165f72012-06-20 15:36:14 -0500666}
667
668static void
669invoke_child(wchar_t * executable, wchar_t * suffix, wchar_t * cmdline)
670{
671 wchar_t * child_command;
672 size_t child_command_size;
673 BOOL no_suffix = (suffix == NULL) || (*suffix == L'\0');
674 BOOL no_cmdline = (*cmdline == L'\0');
675
676 if (no_suffix && no_cmdline)
677 run_child(executable);
678 else {
679 if (no_suffix) {
680 /* add 2 for space separator + terminating NUL. */
681 child_command_size = wcslen(executable) + wcslen(cmdline) + 2;
682 }
683 else {
684 /* add 3 for 2 space separators + terminating NUL. */
685 child_command_size = wcslen(executable) + wcslen(suffix) +
686 wcslen(cmdline) + 3;
687 }
688 child_command = calloc(child_command_size, sizeof(wchar_t));
689 if (child_command == NULL)
690 error(RC_CREATE_PROCESS, L"unable to allocate %d bytes for child command.",
691 child_command_size);
692 if (no_suffix)
693 _snwprintf_s(child_command, child_command_size,
Steve Dower84bcfb32015-01-02 18:07:46 -0800694 child_command_size - 1, L"%ls %ls",
Brian Curtin07165f72012-06-20 15:36:14 -0500695 executable, cmdline);
696 else
697 _snwprintf_s(child_command, child_command_size,
Steve Dower84bcfb32015-01-02 18:07:46 -0800698 child_command_size - 1, L"%ls %ls %ls",
Brian Curtin07165f72012-06-20 15:36:14 -0500699 executable, suffix, cmdline);
700 run_child(child_command);
701 free(child_command);
702 }
703}
704
Vinay Sajip22c039b2013-06-07 15:37:28 +0100705typedef struct {
706 wchar_t *shebang;
707 BOOL search;
708} SHEBANG;
709
710static SHEBANG builtin_virtual_paths [] = {
711 { L"/usr/bin/env python", TRUE },
712 { L"/usr/bin/python", FALSE },
713 { L"/usr/local/bin/python", FALSE },
714 { L"python", FALSE },
715 { NULL, FALSE },
Brian Curtin07165f72012-06-20 15:36:14 -0500716};
717
718/* For now, a static array of commands. */
719
720#define MAX_COMMANDS 100
721
722typedef struct {
723 wchar_t key[MAX_PATH];
724 wchar_t value[MSGSIZE];
725} COMMAND;
726
727static COMMAND commands[MAX_COMMANDS];
728static int num_commands = 0;
729
730#if defined(SKIP_PREFIX)
731
732static wchar_t * builtin_prefixes [] = {
733 /* These must be in an order that the longest matches should be found,
734 * i.e. if the prefix is "/usr/bin/env ", it should match that entry
735 * *before* matching "/usr/bin/".
736 */
737 L"/usr/bin/env ",
738 L"/usr/bin/",
739 L"/usr/local/bin/",
740 NULL
741};
742
743static wchar_t * skip_prefix(wchar_t * name)
744{
745 wchar_t ** pp = builtin_prefixes;
746 wchar_t * result = name;
747 wchar_t * p;
748 size_t n;
749
750 for (; p = *pp; pp++) {
751 n = wcslen(p);
752 if (_wcsnicmp(p, name, n) == 0) {
753 result += n; /* skip the prefix */
754 if (p[n - 1] == L' ') /* No empty strings in table, so n > 1 */
755 result = skip_whitespace(result);
756 break;
757 }
758 }
759 return result;
760}
761
762#endif
763
764#if defined(SEARCH_PATH)
765
766static COMMAND path_command;
767
768static COMMAND * find_on_path(wchar_t * name)
769{
770 wchar_t * pathext;
771 size_t varsize;
772 wchar_t * context = NULL;
773 wchar_t * extension;
774 COMMAND * result = NULL;
775 DWORD len;
776 errno_t rc;
777
778 wcscpy_s(path_command.key, MAX_PATH, name);
779 if (wcschr(name, L'.') != NULL) {
780 /* assume it has an extension. */
781 len = SearchPathW(NULL, name, NULL, MSGSIZE, path_command.value, NULL);
782 if (len) {
783 result = &path_command;
784 }
785 }
786 else {
787 /* No extension - search using registered extensions. */
788 rc = _wdupenv_s(&pathext, &varsize, L"PATHEXT");
789 if (rc == 0) {
790 extension = wcstok_s(pathext, L";", &context);
791 while (extension) {
792 len = SearchPathW(NULL, name, extension, MSGSIZE, path_command.value, NULL);
793 if (len) {
794 result = &path_command;
795 break;
796 }
797 extension = wcstok_s(NULL, L";", &context);
798 }
799 free(pathext);
800 }
801 }
802 return result;
803}
804
805#endif
806
807static COMMAND * find_command(wchar_t * name)
808{
809 COMMAND * result = NULL;
810 COMMAND * cp = commands;
811 int i;
812
813 for (i = 0; i < num_commands; i++, cp++) {
814 if (_wcsicmp(cp->key, name) == 0) {
815 result = cp;
816 break;
817 }
818 }
819#if defined(SEARCH_PATH)
820 if (result == NULL)
821 result = find_on_path(name);
822#endif
823 return result;
824}
825
826static void
827update_command(COMMAND * cp, wchar_t * name, wchar_t * cmdline)
828{
829 wcsncpy_s(cp->key, MAX_PATH, name, _TRUNCATE);
830 wcsncpy_s(cp->value, MSGSIZE, cmdline, _TRUNCATE);
831}
832
833static void
834add_command(wchar_t * name, wchar_t * cmdline)
835{
836 if (num_commands >= MAX_COMMANDS) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800837 debug(L"can't add %ls = '%ls': no room\n", name, cmdline);
Brian Curtin07165f72012-06-20 15:36:14 -0500838 }
839 else {
840 COMMAND * cp = &commands[num_commands++];
841
842 update_command(cp, name, cmdline);
843 }
844}
845
846static void
847read_config_file(wchar_t * config_path)
848{
849 wchar_t keynames[MSGSIZE];
850 wchar_t value[MSGSIZE];
851 DWORD read;
852 wchar_t * key;
853 COMMAND * cp;
854 wchar_t * cmdp;
855
856 read = GetPrivateProfileStringW(L"commands", NULL, NULL, keynames, MSGSIZE,
857 config_path);
858 if (read == MSGSIZE - 1) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800859 debug(L"read_commands: %ls: not enough space for names\n", config_path);
Brian Curtin07165f72012-06-20 15:36:14 -0500860 }
861 key = keynames;
862 while (*key) {
863 read = GetPrivateProfileStringW(L"commands", key, NULL, value, MSGSIZE,
864 config_path);
865 if (read == MSGSIZE - 1) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800866 debug(L"read_commands: %ls: not enough space for %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500867 config_path, key);
868 }
869 cmdp = skip_whitespace(value);
870 if (*cmdp) {
871 cp = find_command(key);
872 if (cp == NULL)
873 add_command(key, value);
874 else
875 update_command(cp, key, value);
876 }
877 key += wcslen(key) + 1;
878 }
879}
880
881static void read_commands()
882{
883 if (launcher_ini_path[0])
884 read_config_file(launcher_ini_path);
885 if (appdata_ini_path[0])
886 read_config_file(appdata_ini_path);
887}
888
889static BOOL
890parse_shebang(wchar_t * shebang_line, int nchars, wchar_t ** command,
Vinay Sajip22c039b2013-06-07 15:37:28 +0100891 wchar_t ** suffix, BOOL *search)
Brian Curtin07165f72012-06-20 15:36:14 -0500892{
893 BOOL rc = FALSE;
Vinay Sajip22c039b2013-06-07 15:37:28 +0100894 SHEBANG * vpp;
Brian Curtin07165f72012-06-20 15:36:14 -0500895 size_t plen;
896 wchar_t * p;
897 wchar_t zapped;
898 wchar_t * endp = shebang_line + nchars - 1;
899 COMMAND * cp;
900 wchar_t * skipped;
901
902 *command = NULL; /* failure return */
903 *suffix = NULL;
Vinay Sajip22c039b2013-06-07 15:37:28 +0100904 *search = FALSE;
Brian Curtin07165f72012-06-20 15:36:14 -0500905
906 if ((*shebang_line++ == L'#') && (*shebang_line++ == L'!')) {
907 shebang_line = skip_whitespace(shebang_line);
908 if (*shebang_line) {
909 *command = shebang_line;
Vinay Sajip22c039b2013-06-07 15:37:28 +0100910 for (vpp = builtin_virtual_paths; vpp->shebang; ++vpp) {
911 plen = wcslen(vpp->shebang);
912 if (wcsncmp(shebang_line, vpp->shebang, plen) == 0) {
Brian Curtin07165f72012-06-20 15:36:14 -0500913 rc = TRUE;
Vinay Sajip22c039b2013-06-07 15:37:28 +0100914 *search = vpp->search;
Brian Curtin07165f72012-06-20 15:36:14 -0500915 /* We can do this because all builtin commands contain
916 * "python".
917 */
918 *command = wcsstr(shebang_line, L"python");
919 break;
920 }
921 }
Vinay Sajip22c039b2013-06-07 15:37:28 +0100922 if (vpp->shebang == NULL) {
Brian Curtin07165f72012-06-20 15:36:14 -0500923 /*
Vinay Sajip9c10d6b2013-11-15 20:58:13 +0000924 * Not found in builtins - look in customized commands.
Brian Curtin07165f72012-06-20 15:36:14 -0500925 *
926 * We can't permanently modify the shebang line in case
Vinay Sajip9c10d6b2013-11-15 20:58:13 +0000927 * it's not a customized command, but we can temporarily
Brian Curtin07165f72012-06-20 15:36:14 -0500928 * stick a NUL after the command while searching for it,
929 * then put back the char we zapped.
930 */
931#if defined(SKIP_PREFIX)
932 skipped = skip_prefix(shebang_line);
933#else
934 skipped = shebang_line;
935#endif
936 p = wcspbrk(skipped, L" \t\r\n");
937 if (p != NULL) {
938 zapped = *p;
939 *p = L'\0';
940 }
941 cp = find_command(skipped);
942 if (p != NULL)
943 *p = zapped;
944 if (cp != NULL) {
945 *command = cp->value;
946 if (p != NULL)
947 *suffix = skip_whitespace(p);
948 }
949 }
950 /* remove trailing whitespace */
951 while ((endp > shebang_line) && isspace(*endp))
952 --endp;
953 if (endp > shebang_line)
954 endp[1] = L'\0';
955 }
956 }
957 return rc;
958}
959
960/* #define CP_UTF8 65001 defined in winnls.h */
961#define CP_UTF16LE 1200
962#define CP_UTF16BE 1201
963#define CP_UTF32LE 12000
964#define CP_UTF32BE 12001
965
966typedef struct {
967 int length;
968 char sequence[4];
969 UINT code_page;
970} BOM;
971
972/*
Vinay Sajipc985d082013-07-25 11:20:55 +0100973 * Strictly, we don't need to handle UTF-16 and UTF-32, since Python itself
Brian Curtin07165f72012-06-20 15:36:14 -0500974 * doesn't. Never mind, one day it might - there's no harm leaving it in.
975 */
976static BOM BOMs[] = {
977 { 3, { 0xEF, 0xBB, 0xBF }, CP_UTF8 }, /* UTF-8 - keep first */
Serhiy Storchaka29e2aa62015-12-18 10:23:09 +0200978 /* Test UTF-32LE before UTF-16LE since UTF-16LE BOM is a prefix
979 * of UTF-32LE BOM. */
Brian Curtin07165f72012-06-20 15:36:14 -0500980 { 4, { 0xFF, 0xFE, 0x00, 0x00 }, CP_UTF32LE }, /* UTF-32LE */
981 { 4, { 0x00, 0x00, 0xFE, 0xFF }, CP_UTF32BE }, /* UTF-32BE */
Serhiy Storchaka29e2aa62015-12-18 10:23:09 +0200982 { 2, { 0xFF, 0xFE }, CP_UTF16LE }, /* UTF-16LE */
983 { 2, { 0xFE, 0xFF }, CP_UTF16BE }, /* UTF-16BE */
Brian Curtin07165f72012-06-20 15:36:14 -0500984 { 0 } /* sentinel */
985};
986
987static BOM *
988find_BOM(char * buffer)
989{
990/*
991 * Look for a BOM in the input and return a pointer to the
992 * corresponding structure, or NULL if not found.
993 */
994 BOM * result = NULL;
995 BOM *bom;
996
997 for (bom = BOMs; bom->length; bom++) {
998 if (strncmp(bom->sequence, buffer, bom->length) == 0) {
999 result = bom;
1000 break;
1001 }
1002 }
1003 return result;
1004}
1005
1006static char *
1007find_terminator(char * buffer, int len, BOM *bom)
1008{
1009 char * result = NULL;
1010 char * end = buffer + len;
1011 char * p;
1012 char c;
1013 int cp;
1014
1015 for (p = buffer; p < end; p++) {
1016 c = *p;
1017 if (c == '\r') {
1018 result = p;
1019 break;
1020 }
1021 if (c == '\n') {
1022 result = p;
1023 break;
1024 }
1025 }
1026 if (result != NULL) {
1027 cp = bom->code_page;
1028
1029 /* adjustments to include all bytes of the char */
1030 /* no adjustment needed for UTF-8 or big endian */
1031 if (cp == CP_UTF16LE)
1032 ++result;
1033 else if (cp == CP_UTF32LE)
1034 result += 3;
1035 ++result; /* point just past terminator */
1036 }
1037 return result;
1038}
1039
1040static BOOL
1041validate_version(wchar_t * p)
1042{
1043 BOOL result = TRUE;
1044
1045 if (!isdigit(*p)) /* expect major version */
1046 result = FALSE;
1047 else if (*++p) { /* more to do */
1048 if (*p != L'.') /* major/minor separator */
1049 result = FALSE;
1050 else {
1051 ++p;
1052 if (!isdigit(*p)) /* expect minor version */
1053 result = FALSE;
1054 else {
1055 ++p;
1056 if (*p) { /* more to do */
1057 if (*p != L'-')
1058 result = FALSE;
1059 else {
1060 ++p;
1061 if ((*p != '3') && (*++p != '2') && !*++p)
1062 result = FALSE;
1063 }
1064 }
1065 }
1066 }
1067 }
1068 return result;
1069}
1070
1071typedef struct {
1072 unsigned short min;
1073 unsigned short max;
1074 wchar_t version[MAX_VERSION_SIZE];
1075} PYC_MAGIC;
1076
1077static PYC_MAGIC magic_values[] = {
Steve Dower7ae61af2016-05-16 09:34:20 -07001078 { 50823, 50823, L"2.0" },
1079 { 60202, 60202, L"2.1" },
1080 { 60717, 60717, L"2.2" },
1081 { 62011, 62021, L"2.3" },
1082 { 62041, 62061, L"2.4" },
1083 { 62071, 62131, L"2.5" },
1084 { 62151, 62161, L"2.6" },
1085 { 62171, 62211, L"2.7" },
1086 { 3000, 3131, L"3.0" },
1087 { 3141, 3151, L"3.1" },
1088 { 3160, 3180, L"3.2" },
1089 { 3190, 3230, L"3.3" },
1090 { 3250, 3310, L"3.4" },
Serhiy Storchaka3c317e72016-06-12 09:22:01 +03001091 { 3320, 3351, L"3.5" },
Nick Coghlan944368e2016-09-11 14:45:49 +10001092 { 3360, 3379, L"3.6" },
Yury Selivanovf2392132016-12-13 19:03:51 -05001093 { 3390, 3399, L"3.7" },
Brian Curtin07165f72012-06-20 15:36:14 -05001094 { 0 }
1095};
1096
1097static INSTALLED_PYTHON *
1098find_by_magic(unsigned short magic)
1099{
1100 INSTALLED_PYTHON * result = NULL;
1101 PYC_MAGIC * mp;
1102
1103 for (mp = magic_values; mp->min; mp++) {
1104 if ((magic >= mp->min) && (magic <= mp->max)) {
Paul Moore835416c2016-05-22 12:28:41 +01001105 result = locate_python(mp->version, FALSE);
Brian Curtin07165f72012-06-20 15:36:14 -05001106 if (result != NULL)
1107 break;
1108 }
1109 }
1110 return result;
1111}
1112
1113static void
1114maybe_handle_shebang(wchar_t ** argv, wchar_t * cmdline)
1115{
1116/*
1117 * Look for a shebang line in the first argument. If found
1118 * and we spawn a child process, this never returns. If it
1119 * does return then we process the args "normally".
1120 *
1121 * argv[0] might be a filename with a shebang.
1122 */
1123 FILE * fp;
1124 errno_t rc = _wfopen_s(&fp, *argv, L"rb");
Serhiy Storchakaf8ed0042015-12-18 10:19:30 +02001125 char buffer[BUFSIZE];
Brian Curtin07165f72012-06-20 15:36:14 -05001126 wchar_t shebang_line[BUFSIZE + 1];
1127 size_t read;
1128 char *p;
1129 char * start;
1130 char * shebang_alias = (char *) shebang_line;
1131 BOM* bom;
1132 int i, j, nchars = 0;
1133 int header_len;
1134 BOOL is_virt;
Vinay Sajip22c039b2013-06-07 15:37:28 +01001135 BOOL search;
Brian Curtin07165f72012-06-20 15:36:14 -05001136 wchar_t * command;
1137 wchar_t * suffix;
Vinay Sajip22c039b2013-06-07 15:37:28 +01001138 COMMAND *cmd = NULL;
Brian Curtin07165f72012-06-20 15:36:14 -05001139 INSTALLED_PYTHON * ip;
1140
1141 if (rc == 0) {
1142 read = fread(buffer, sizeof(char), BUFSIZE, fp);
1143 debug(L"maybe_handle_shebang: read %d bytes\n", read);
1144 fclose(fp);
1145
1146 if ((read >= 4) && (buffer[3] == '\n') && (buffer[2] == '\r')) {
Serhiy Storchakaf8ed0042015-12-18 10:19:30 +02001147 ip = find_by_magic((((unsigned char)buffer[1]) << 8 |
1148 (unsigned char)buffer[0]) & 0xFFFF);
Brian Curtin07165f72012-06-20 15:36:14 -05001149 if (ip != NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001150 debug(L"script file is compiled against Python %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -05001151 ip->version);
1152 invoke_child(ip->executable, NULL, cmdline);
1153 }
1154 }
1155 /* Look for BOM */
1156 bom = find_BOM(buffer);
1157 if (bom == NULL) {
1158 start = buffer;
1159 debug(L"maybe_handle_shebang: BOM not found, using UTF-8\n");
1160 bom = BOMs; /* points to UTF-8 entry - the default */
1161 }
1162 else {
1163 debug(L"maybe_handle_shebang: BOM found, code page %d\n",
1164 bom->code_page);
1165 start = &buffer[bom->length];
1166 }
1167 p = find_terminator(start, BUFSIZE, bom);
1168 /*
1169 * If no CR or LF was found in the heading,
1170 * we assume it's not a shebang file.
1171 */
1172 if (p == NULL) {
1173 debug(L"maybe_handle_shebang: No line terminator found\n");
1174 }
1175 else {
1176 /*
1177 * Found line terminator - parse the shebang.
1178 *
1179 * Strictly, we don't need to handle UTF-16 anf UTF-32,
1180 * since Python itself doesn't.
1181 * Never mind, one day it might.
1182 */
1183 header_len = (int) (p - start);
1184 switch(bom->code_page) {
1185 case CP_UTF8:
1186 nchars = MultiByteToWideChar(bom->code_page,
1187 0,
1188 start, header_len, shebang_line,
1189 BUFSIZE);
1190 break;
1191 case CP_UTF16BE:
1192 if (header_len % 2 != 0) {
1193 debug(L"maybe_handle_shebang: UTF-16BE, but an odd number \
1194of bytes: %d\n", header_len);
1195 /* nchars = 0; Not needed - initialised to 0. */
1196 }
1197 else {
1198 for (i = header_len; i > 0; i -= 2) {
1199 shebang_alias[i - 1] = start[i - 2];
1200 shebang_alias[i - 2] = start[i - 1];
1201 }
1202 nchars = header_len / sizeof(wchar_t);
1203 }
1204 break;
1205 case CP_UTF16LE:
1206 if ((header_len % 2) != 0) {
1207 debug(L"UTF-16LE, but an odd number of bytes: %d\n",
1208 header_len);
1209 /* nchars = 0; Not needed - initialised to 0. */
1210 }
1211 else {
1212 /* no actual conversion needed. */
1213 memcpy(shebang_line, start, header_len);
1214 nchars = header_len / sizeof(wchar_t);
1215 }
1216 break;
1217 case CP_UTF32BE:
1218 if (header_len % 4 != 0) {
1219 debug(L"UTF-32BE, but not divisible by 4: %d\n",
1220 header_len);
1221 /* nchars = 0; Not needed - initialised to 0. */
1222 }
1223 else {
1224 for (i = header_len, j = header_len / 2; i > 0; i -= 4,
1225 j -= 2) {
1226 shebang_alias[j - 1] = start[i - 2];
1227 shebang_alias[j - 2] = start[i - 1];
1228 }
1229 nchars = header_len / sizeof(wchar_t);
1230 }
1231 break;
1232 case CP_UTF32LE:
1233 if (header_len % 4 != 0) {
1234 debug(L"UTF-32LE, but not divisible by 4: %d\n",
1235 header_len);
1236 /* nchars = 0; Not needed - initialised to 0. */
1237 }
1238 else {
1239 for (i = header_len, j = header_len / 2; i > 0; i -= 4,
1240 j -= 2) {
1241 shebang_alias[j - 1] = start[i - 3];
1242 shebang_alias[j - 2] = start[i - 4];
1243 }
1244 nchars = header_len / sizeof(wchar_t);
1245 }
1246 break;
1247 }
1248 if (nchars > 0) {
1249 shebang_line[--nchars] = L'\0';
1250 is_virt = parse_shebang(shebang_line, nchars, &command,
Vinay Sajip22c039b2013-06-07 15:37:28 +01001251 &suffix, &search);
Brian Curtin07165f72012-06-20 15:36:14 -05001252 if (command != NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001253 debug(L"parse_shebang: found command: %ls\n", command);
Brian Curtin07165f72012-06-20 15:36:14 -05001254 if (!is_virt) {
1255 invoke_child(command, suffix, cmdline);
1256 }
1257 else {
1258 suffix = wcschr(command, L' ');
1259 if (suffix != NULL) {
1260 *suffix++ = L'\0';
1261 suffix = skip_whitespace(suffix);
1262 }
1263 if (wcsncmp(command, L"python", 6))
1264 error(RC_BAD_VIRTUAL_PATH, L"Unknown virtual \
Steve Dower84bcfb32015-01-02 18:07:46 -08001265path '%ls'", command);
Brian Curtin07165f72012-06-20 15:36:14 -05001266 command += 6; /* skip past "python" */
Vinay Sajip22c039b2013-06-07 15:37:28 +01001267 if (search && ((*command == L'\0') || isspace(*command))) {
1268 /* Command is eligible for path search, and there
1269 * is no version specification.
1270 */
1271 debug(L"searching PATH for python executable\n");
Vinay Sajipa5892ab2015-12-26 13:10:51 +00001272 cmd = find_on_path(PYTHON_EXECUTABLE);
Steve Dower84bcfb32015-01-02 18:07:46 -08001273 debug(L"Python on path: %ls\n", cmd ? cmd->value : L"<not found>");
Vinay Sajip22c039b2013-06-07 15:37:28 +01001274 if (cmd) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001275 debug(L"located python on PATH: %ls\n", cmd->value);
Vinay Sajip22c039b2013-06-07 15:37:28 +01001276 invoke_child(cmd->value, suffix, cmdline);
1277 /* Exit here, as we have found the command */
1278 return;
1279 }
1280 /* FALL THROUGH: No python found on PATH, so fall
1281 * back to locating the correct installed python.
1282 */
1283 }
Brian Curtin07165f72012-06-20 15:36:14 -05001284 if (*command && !validate_version(command))
1285 error(RC_BAD_VIRTUAL_PATH, L"Invalid version \
Steve Dower84bcfb32015-01-02 18:07:46 -08001286specification: '%ls'.\nIn the first line of the script, 'python' needs to be \
Brian Curtin07165f72012-06-20 15:36:14 -05001287followed by a valid version specifier.\nPlease check the documentation.",
1288 command);
1289 /* TODO could call validate_version(command) */
Paul Moore835416c2016-05-22 12:28:41 +01001290 ip = locate_python(command, TRUE);
Brian Curtin07165f72012-06-20 15:36:14 -05001291 if (ip == NULL) {
1292 error(RC_NO_PYTHON, L"Requested Python version \
Steve Dower84bcfb32015-01-02 18:07:46 -08001293(%ls) is not installed", command);
Brian Curtin07165f72012-06-20 15:36:14 -05001294 }
1295 else {
1296 invoke_child(ip->executable, suffix, cmdline);
1297 }
1298 }
1299 }
1300 }
1301 }
1302 }
1303}
1304
1305static wchar_t *
1306skip_me(wchar_t * cmdline)
1307{
1308 BOOL quoted;
1309 wchar_t c;
1310 wchar_t * result = cmdline;
1311
1312 quoted = cmdline[0] == L'\"';
1313 if (!quoted)
1314 c = L' ';
1315 else {
1316 c = L'\"';
1317 ++result;
1318 }
1319 result = wcschr(result, c);
1320 if (result == NULL) /* when, for example, just exe name on command line */
1321 result = L"";
1322 else {
1323 ++result; /* skip past space or closing quote */
1324 result = skip_whitespace(result);
1325 }
1326 return result;
1327}
1328
1329static DWORD version_high = 0;
1330static DWORD version_low = 0;
1331
1332static void
1333get_version_info(wchar_t * version_text, size_t size)
1334{
1335 WORD maj, min, rel, bld;
1336
1337 if (!version_high && !version_low)
1338 wcsncpy_s(version_text, size, L"0.1", _TRUNCATE); /* fallback */
1339 else {
1340 maj = HIWORD(version_high);
1341 min = LOWORD(version_high);
1342 rel = HIWORD(version_low);
1343 bld = LOWORD(version_low);
1344 _snwprintf_s(version_text, size, _TRUNCATE, L"%d.%d.%d.%d", maj,
1345 min, rel, bld);
1346 }
1347}
1348
1349static int
1350process(int argc, wchar_t ** argv)
1351{
1352 wchar_t * wp;
1353 wchar_t * command;
Steve Dower76998fe2015-02-26 14:25:33 -08001354 wchar_t * executable;
Brian Curtin07165f72012-06-20 15:36:14 -05001355 wchar_t * p;
1356 int rc = 0;
1357 size_t plen;
1358 INSTALLED_PYTHON * ip;
1359 BOOL valid;
1360 DWORD size, attrs;
1361 HRESULT hr;
1362 wchar_t message[MSGSIZE];
1363 wchar_t version_text [MAX_PATH];
1364 void * version_data;
1365 VS_FIXEDFILEINFO * file_info;
1366 UINT block_size;
Vinay Sajip2ae8c632013-01-29 22:29:25 +00001367 int index;
Vinay Sajipc985d082013-07-25 11:20:55 +01001368#if defined(SCRIPT_WRAPPER)
1369 int newlen;
1370 wchar_t * newcommand;
1371 wchar_t * av[2];
1372#endif
Brian Curtin07165f72012-06-20 15:36:14 -05001373
Vinay Sajipaab9f462015-12-26 12:35:47 +00001374 setvbuf(stderr, (char *)NULL, _IONBF, 0);
Brian Curtin07165f72012-06-20 15:36:14 -05001375 wp = get_env(L"PYLAUNCH_DEBUG");
1376 if ((wp != NULL) && (*wp != L'\0'))
1377 log_fp = stderr;
1378
1379#if defined(_M_X64)
1380 debug(L"launcher build: 64bit\n");
1381#else
1382 debug(L"launcher build: 32bit\n");
1383#endif
1384#if defined(_WINDOWS)
1385 debug(L"launcher executable: Windows\n");
1386#else
1387 debug(L"launcher executable: Console\n");
1388#endif
1389 /* Get the local appdata folder (non-roaming) */
1390 hr = SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA,
1391 NULL, 0, appdata_ini_path);
1392 if (hr != S_OK) {
1393 debug(L"SHGetFolderPath failed: %X\n", hr);
1394 appdata_ini_path[0] = L'\0';
1395 }
1396 else {
1397 plen = wcslen(appdata_ini_path);
1398 p = &appdata_ini_path[plen];
1399 wcsncpy_s(p, MAX_PATH - plen, L"\\py.ini", _TRUNCATE);
1400 attrs = GetFileAttributesW(appdata_ini_path);
1401 if (attrs == INVALID_FILE_ATTRIBUTES) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001402 debug(L"File '%ls' non-existent\n", appdata_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001403 appdata_ini_path[0] = L'\0';
1404 } else {
Steve Dower84bcfb32015-01-02 18:07:46 -08001405 debug(L"Using local configuration file '%ls'\n", appdata_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001406 }
1407 }
1408 plen = GetModuleFileNameW(NULL, launcher_ini_path, MAX_PATH);
1409 size = GetFileVersionInfoSizeW(launcher_ini_path, &size);
1410 if (size == 0) {
1411 winerror(GetLastError(), message, MSGSIZE);
Steve Dower84bcfb32015-01-02 18:07:46 -08001412 debug(L"GetFileVersionInfoSize failed: %ls\n", message);
Brian Curtin07165f72012-06-20 15:36:14 -05001413 }
1414 else {
1415 version_data = malloc(size);
1416 if (version_data) {
1417 valid = GetFileVersionInfoW(launcher_ini_path, 0, size,
1418 version_data);
1419 if (!valid)
1420 debug(L"GetFileVersionInfo failed: %X\n", GetLastError());
1421 else {
Vinay Sajip404229b2013-01-29 22:52:57 +00001422 valid = VerQueryValueW(version_data, L"\\",
1423 (LPVOID *) &file_info, &block_size);
Brian Curtin07165f72012-06-20 15:36:14 -05001424 if (!valid)
1425 debug(L"VerQueryValue failed: %X\n", GetLastError());
1426 else {
1427 version_high = file_info->dwFileVersionMS;
1428 version_low = file_info->dwFileVersionLS;
1429 }
1430 }
1431 free(version_data);
1432 }
1433 }
1434 p = wcsrchr(launcher_ini_path, L'\\');
1435 if (p == NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001436 debug(L"GetModuleFileNameW returned value has no backslash: %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -05001437 launcher_ini_path);
1438 launcher_ini_path[0] = L'\0';
1439 }
1440 else {
1441 wcsncpy_s(p, MAX_PATH - (p - launcher_ini_path), L"\\py.ini",
1442 _TRUNCATE);
1443 attrs = GetFileAttributesW(launcher_ini_path);
1444 if (attrs == INVALID_FILE_ATTRIBUTES) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001445 debug(L"File '%ls' non-existent\n", launcher_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001446 launcher_ini_path[0] = L'\0';
1447 } else {
Steve Dower84bcfb32015-01-02 18:07:46 -08001448 debug(L"Using global configuration file '%ls'\n", launcher_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001449 }
1450 }
1451
1452 command = skip_me(GetCommandLineW());
Steve Dower84bcfb32015-01-02 18:07:46 -08001453 debug(L"Called with command line: %ls\n", command);
Vinay Sajipc985d082013-07-25 11:20:55 +01001454
1455#if defined(SCRIPT_WRAPPER)
1456 /* The launcher is being used in "script wrapper" mode.
1457 * There should therefore be a Python script named <exename>-script.py in
1458 * the same directory as the launcher executable.
1459 * Put the script name into argv as the first (script name) argument.
1460 */
1461
1462 /* Get the wrapped script name - if the script is not present, this will
1463 * terminate the program with an error.
1464 */
1465 locate_wrapped_script();
1466
1467 /* Add the wrapped script to the start of command */
1468 newlen = wcslen(wrapped_script_path) + wcslen(command) + 2; /* ' ' + NUL */
1469 newcommand = malloc(sizeof(wchar_t) * newlen);
1470 if (!newcommand) {
1471 error(RC_NO_MEMORY, L"Could not allocate new command line");
1472 }
1473 else {
1474 wcscpy_s(newcommand, newlen, wrapped_script_path);
1475 wcscat_s(newcommand, newlen, L" ");
1476 wcscat_s(newcommand, newlen, command);
Steve Dower84bcfb32015-01-02 18:07:46 -08001477 debug(L"Running wrapped script with command line '%ls'\n", newcommand);
Vinay Sajipc985d082013-07-25 11:20:55 +01001478 read_commands();
1479 av[0] = wrapped_script_path;
1480 av[1] = NULL;
1481 maybe_handle_shebang(av, newcommand);
1482 /* Returns if no shebang line - pass to default processing */
1483 command = newcommand;
1484 valid = FALSE;
1485 }
1486#else
Brian Curtin07165f72012-06-20 15:36:14 -05001487 if (argc <= 1) {
1488 valid = FALSE;
1489 p = NULL;
1490 }
1491 else {
1492 p = argv[1];
1493 plen = wcslen(p);
Brian Curtin07165f72012-06-20 15:36:14 -05001494 valid = (*p == L'-') && validate_version(&p[1]);
1495 if (valid) {
Paul Moore835416c2016-05-22 12:28:41 +01001496 ip = locate_python(&p[1], FALSE);
Brian Curtin07165f72012-06-20 15:36:14 -05001497 if (ip == NULL)
Steve Dower84bcfb32015-01-02 18:07:46 -08001498 error(RC_NO_PYTHON, L"Requested Python version (%ls) not \
Brian Curtin07165f72012-06-20 15:36:14 -05001499installed", &p[1]);
Steve Dower76998fe2015-02-26 14:25:33 -08001500 executable = ip->executable;
Brian Curtin07165f72012-06-20 15:36:14 -05001501 command += wcslen(p);
1502 command = skip_whitespace(command);
1503 }
Vinay Sajip2ae8c632013-01-29 22:29:25 +00001504 else {
1505 for (index = 1; index < argc; ++index) {
1506 if (*argv[index] != L'-')
1507 break;
1508 }
1509 if (index < argc) {
1510 read_commands();
1511 maybe_handle_shebang(&argv[index], command);
1512 }
1513 }
Brian Curtin07165f72012-06-20 15:36:14 -05001514 }
Vinay Sajipc985d082013-07-25 11:20:55 +01001515#endif
1516
Brian Curtin07165f72012-06-20 15:36:14 -05001517 if (!valid) {
Steve Dower76998fe2015-02-26 14:25:33 -08001518 /* Look for an active virtualenv */
1519 executable = find_python_by_venv();
1520
1521 /* If we didn't find one, look for the default Python */
1522 if (executable == NULL) {
Paul Moore835416c2016-05-22 12:28:41 +01001523 ip = locate_python(L"", FALSE);
Steve Dower76998fe2015-02-26 14:25:33 -08001524 if (ip == NULL)
1525 error(RC_NO_PYTHON, L"Can't find a default Python.");
1526 executable = ip->executable;
1527 }
Brian Curtin07165f72012-06-20 15:36:14 -05001528 if ((argc == 2) && (!_wcsicmp(p, L"-h") || !_wcsicmp(p, L"--help"))) {
1529#if defined(_M_X64)
1530 BOOL canDo64bit = TRUE;
1531#else
1532 // If we are a 32bit process on a 64bit Windows, first hit the 64bit keys.
1533 BOOL canDo64bit = FALSE;
1534 IsWow64Process(GetCurrentProcess(), &canDo64bit);
1535#endif
1536
1537 get_version_info(version_text, MAX_PATH);
1538 fwprintf(stdout, L"\
Steve Dower84bcfb32015-01-02 18:07:46 -08001539Python Launcher for Windows Version %ls\n\n", version_text);
Brian Curtin07165f72012-06-20 15:36:14 -05001540 fwprintf(stdout, L"\
Steve Dower84bcfb32015-01-02 18:07:46 -08001541usage: %ls [ launcher-arguments ] [ python-arguments ] script [ script-arguments ]\n\n", argv[0]);
Brian Curtin07165f72012-06-20 15:36:14 -05001542 fputws(L"\
1543Launcher arguments:\n\n\
1544-2 : Launch the latest Python 2.x version\n\
1545-3 : Launch the latest Python 3.x version\n\
1546-X.Y : Launch the specified Python version\n", stdout);
1547 if (canDo64bit) {
1548 fputws(L"\
1549-X.Y-32: Launch the specified 32bit Python version", stdout);
1550 }
1551 fputws(L"\n\nThe following help text is from Python:\n\n", stdout);
1552 fflush(stdout);
1553 }
1554 }
Steve Dower76998fe2015-02-26 14:25:33 -08001555 invoke_child(executable, NULL, command);
Brian Curtin07165f72012-06-20 15:36:14 -05001556 return rc;
1557}
1558
1559#if defined(_WINDOWS)
1560
1561int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
1562 LPWSTR lpstrCmd, int nShow)
1563{
1564 return process(__argc, __wargv);
1565}
1566
1567#else
1568
1569int cdecl wmain(int argc, wchar_t ** argv)
1570{
1571 return process(argc, argv);
1572}
1573
Vinay Sajip2ae8c632013-01-29 22:29:25 +00001574#endif