blob: 40d4cb5474d9afb566ee63f8bd7aeb6dc7457668 [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
101 ExitProcess(rc);
102}
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 Hammondce543fd2016-01-11 14:50:22 +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 *
468locate_python(wchar_t * wanted_ver)
469{
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);
500 if (result == NULL)
501 result = find_python_by_version(L"2");
502 if (result == NULL)
503 result = find_python_by_version(L"3");
504 debug(L"search for default Python found ");
505 if (result) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800506 debug(L"version %ls at '%ls'\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500507 result->version, result->executable);
508 } else {
509 debug(L"no interpreter\n");
510 }
511 }
512 return result;
513}
514
Vinay Sajipc985d082013-07-25 11:20:55 +0100515#if defined(SCRIPT_WRAPPER)
516/*
517 * Check for a script located alongside the executable
518 */
519
520#if defined(_WINDOWS)
521#define SCRIPT_SUFFIX L"-script.pyw"
522#else
523#define SCRIPT_SUFFIX L"-script.py"
524#endif
525
526static wchar_t wrapped_script_path[MAX_PATH];
527
528/* Locate the script being wrapped.
529 *
530 * This code should store the name of the wrapped script in
531 * wrapped_script_path, or terminate the program with an error if there is no
532 * valid wrapped script file.
533 */
534static void
535locate_wrapped_script()
536{
537 wchar_t * p;
538 size_t plen;
539 DWORD attrs;
540
541 plen = GetModuleFileNameW(NULL, wrapped_script_path, MAX_PATH);
542 p = wcsrchr(wrapped_script_path, L'.');
543 if (p == NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800544 debug(L"GetModuleFileNameW returned value has no extension: %ls\n",
Vinay Sajipc985d082013-07-25 11:20:55 +0100545 wrapped_script_path);
Steve Dower84bcfb32015-01-02 18:07:46 -0800546 error(RC_NO_SCRIPT, L"Wrapper name '%ls' is not valid.", wrapped_script_path);
Vinay Sajipc985d082013-07-25 11:20:55 +0100547 }
548
549 wcsncpy_s(p, MAX_PATH - (p - wrapped_script_path) + 1, SCRIPT_SUFFIX, _TRUNCATE);
550 attrs = GetFileAttributesW(wrapped_script_path);
551 if (attrs == INVALID_FILE_ATTRIBUTES) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800552 debug(L"File '%ls' non-existent\n", wrapped_script_path);
553 error(RC_NO_SCRIPT, L"Script file '%ls' is not present.", wrapped_script_path);
Vinay Sajipc985d082013-07-25 11:20:55 +0100554 }
555
Steve Dower84bcfb32015-01-02 18:07:46 -0800556 debug(L"Using wrapped script file '%ls'\n", wrapped_script_path);
Vinay Sajipc985d082013-07-25 11:20:55 +0100557}
558#endif
559
Brian Curtin07165f72012-06-20 15:36:14 -0500560/*
561 * Process creation code
562 */
563
564static BOOL
565safe_duplicate_handle(HANDLE in, HANDLE * pout)
566{
567 BOOL ok;
568 HANDLE process = GetCurrentProcess();
569 DWORD rc;
570
571 *pout = NULL;
572 ok = DuplicateHandle(process, in, process, pout, 0, TRUE,
573 DUPLICATE_SAME_ACCESS);
574 if (!ok) {
575 rc = GetLastError();
576 if (rc == ERROR_INVALID_HANDLE) {
577 debug(L"DuplicateHandle returned ERROR_INVALID_HANDLE\n");
578 ok = TRUE;
579 }
580 else {
581 debug(L"DuplicateHandle returned %d\n", rc);
582 }
583 }
584 return ok;
585}
586
587static BOOL WINAPI
588ctrl_c_handler(DWORD code)
589{
590 return TRUE; /* We just ignore all control events. */
591}
592
593static void
594run_child(wchar_t * cmdline)
595{
596 HANDLE job;
597 JOBOBJECT_EXTENDED_LIMIT_INFORMATION info;
598 DWORD rc;
599 BOOL ok;
600 STARTUPINFOW si;
601 PROCESS_INFORMATION pi;
602
Vinay Sajip66fef9f2013-02-26 16:29:06 +0000603#if defined(_WINDOWS)
604 // When explorer launches a Windows (GUI) application, it displays
605 // the "app starting" (the "pointer + hourglass") cursor for a number
606 // of seconds, or until the app does something UI-ish (eg, creating a
607 // window, or fetching a message). As this launcher doesn't do this
608 // directly, that cursor remains even after the child process does these
609 // things. We avoid that by doing a simple post+get message.
Serhiy Storchaka009b8112015-03-18 21:53:15 +0200610 // See http://bugs.python.org/issue17290 and
Vinay Sajip66fef9f2013-02-26 16:29:06 +0000611 // https://bitbucket.org/vinay.sajip/pylauncher/issue/20/busy-cursor-for-a-long-time-when-running
612 MSG msg;
613
614 PostMessage(0, 0, 0, 0);
615 GetMessage(&msg, 0, 0, 0);
616#endif
617
Steve Dower84bcfb32015-01-02 18:07:46 -0800618 debug(L"run_child: about to run '%ls'\n", cmdline);
Brian Curtin07165f72012-06-20 15:36:14 -0500619 job = CreateJobObject(NULL, NULL);
620 ok = QueryInformationJobObject(job, JobObjectExtendedLimitInformation,
621 &info, sizeof(info), &rc);
622 if (!ok || (rc != sizeof(info)) || !job)
623 error(RC_CREATE_PROCESS, L"Job information querying failed");
624 info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE |
625 JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK;
626 ok = SetInformationJobObject(job, JobObjectExtendedLimitInformation, &info,
627 sizeof(info));
628 if (!ok)
629 error(RC_CREATE_PROCESS, L"Job information setting failed");
630 memset(&si, 0, sizeof(si));
631 si.cb = sizeof(si);
632 ok = safe_duplicate_handle(GetStdHandle(STD_INPUT_HANDLE), &si.hStdInput);
633 if (!ok)
634 error(RC_NO_STD_HANDLES, L"stdin duplication failed");
635 ok = safe_duplicate_handle(GetStdHandle(STD_OUTPUT_HANDLE), &si.hStdOutput);
636 if (!ok)
637 error(RC_NO_STD_HANDLES, L"stdout duplication failed");
638 ok = safe_duplicate_handle(GetStdHandle(STD_ERROR_HANDLE), &si.hStdError);
639 if (!ok)
640 error(RC_NO_STD_HANDLES, L"stderr duplication failed");
641
642 ok = SetConsoleCtrlHandler(ctrl_c_handler, TRUE);
643 if (!ok)
644 error(RC_CREATE_PROCESS, L"control handler setting failed");
645
646 si.dwFlags = STARTF_USESTDHANDLES;
647 ok = CreateProcessW(NULL, cmdline, NULL, NULL, TRUE,
648 0, NULL, NULL, &si, &pi);
649 if (!ok)
Steve Dower84bcfb32015-01-02 18:07:46 -0800650 error(RC_CREATE_PROCESS, L"Unable to create process using '%ls'", cmdline);
Brian Curtin07165f72012-06-20 15:36:14 -0500651 AssignProcessToJobObject(job, pi.hProcess);
652 CloseHandle(pi.hThread);
Martin v. Löwisb26a9b12013-01-25 14:25:48 +0100653 WaitForSingleObjectEx(pi.hProcess, INFINITE, FALSE);
Brian Curtin07165f72012-06-20 15:36:14 -0500654 ok = GetExitCodeProcess(pi.hProcess, &rc);
655 if (!ok)
656 error(RC_CREATE_PROCESS, L"Failed to get exit code of process");
657 debug(L"child process exit code: %d\n", rc);
658 ExitProcess(rc);
659}
660
661static void
662invoke_child(wchar_t * executable, wchar_t * suffix, wchar_t * cmdline)
663{
664 wchar_t * child_command;
665 size_t child_command_size;
666 BOOL no_suffix = (suffix == NULL) || (*suffix == L'\0');
667 BOOL no_cmdline = (*cmdline == L'\0');
668
669 if (no_suffix && no_cmdline)
670 run_child(executable);
671 else {
672 if (no_suffix) {
673 /* add 2 for space separator + terminating NUL. */
674 child_command_size = wcslen(executable) + wcslen(cmdline) + 2;
675 }
676 else {
677 /* add 3 for 2 space separators + terminating NUL. */
678 child_command_size = wcslen(executable) + wcslen(suffix) +
679 wcslen(cmdline) + 3;
680 }
681 child_command = calloc(child_command_size, sizeof(wchar_t));
682 if (child_command == NULL)
683 error(RC_CREATE_PROCESS, L"unable to allocate %d bytes for child command.",
684 child_command_size);
685 if (no_suffix)
686 _snwprintf_s(child_command, child_command_size,
Steve Dower84bcfb32015-01-02 18:07:46 -0800687 child_command_size - 1, L"%ls %ls",
Brian Curtin07165f72012-06-20 15:36:14 -0500688 executable, cmdline);
689 else
690 _snwprintf_s(child_command, child_command_size,
Steve Dower84bcfb32015-01-02 18:07:46 -0800691 child_command_size - 1, L"%ls %ls %ls",
Brian Curtin07165f72012-06-20 15:36:14 -0500692 executable, suffix, cmdline);
693 run_child(child_command);
694 free(child_command);
695 }
696}
697
Vinay Sajip22c039b2013-06-07 15:37:28 +0100698typedef struct {
699 wchar_t *shebang;
700 BOOL search;
701} SHEBANG;
702
703static SHEBANG builtin_virtual_paths [] = {
704 { L"/usr/bin/env python", TRUE },
705 { L"/usr/bin/python", FALSE },
706 { L"/usr/local/bin/python", FALSE },
707 { L"python", FALSE },
708 { NULL, FALSE },
Brian Curtin07165f72012-06-20 15:36:14 -0500709};
710
711/* For now, a static array of commands. */
712
713#define MAX_COMMANDS 100
714
715typedef struct {
716 wchar_t key[MAX_PATH];
717 wchar_t value[MSGSIZE];
718} COMMAND;
719
720static COMMAND commands[MAX_COMMANDS];
721static int num_commands = 0;
722
723#if defined(SKIP_PREFIX)
724
725static wchar_t * builtin_prefixes [] = {
726 /* These must be in an order that the longest matches should be found,
727 * i.e. if the prefix is "/usr/bin/env ", it should match that entry
728 * *before* matching "/usr/bin/".
729 */
730 L"/usr/bin/env ",
731 L"/usr/bin/",
732 L"/usr/local/bin/",
733 NULL
734};
735
736static wchar_t * skip_prefix(wchar_t * name)
737{
738 wchar_t ** pp = builtin_prefixes;
739 wchar_t * result = name;
740 wchar_t * p;
741 size_t n;
742
743 for (; p = *pp; pp++) {
744 n = wcslen(p);
745 if (_wcsnicmp(p, name, n) == 0) {
746 result += n; /* skip the prefix */
747 if (p[n - 1] == L' ') /* No empty strings in table, so n > 1 */
748 result = skip_whitespace(result);
749 break;
750 }
751 }
752 return result;
753}
754
755#endif
756
757#if defined(SEARCH_PATH)
758
759static COMMAND path_command;
760
761static COMMAND * find_on_path(wchar_t * name)
762{
763 wchar_t * pathext;
764 size_t varsize;
765 wchar_t * context = NULL;
766 wchar_t * extension;
767 COMMAND * result = NULL;
768 DWORD len;
769 errno_t rc;
770
771 wcscpy_s(path_command.key, MAX_PATH, name);
772 if (wcschr(name, L'.') != NULL) {
773 /* assume it has an extension. */
774 len = SearchPathW(NULL, name, NULL, MSGSIZE, path_command.value, NULL);
775 if (len) {
776 result = &path_command;
777 }
778 }
779 else {
780 /* No extension - search using registered extensions. */
781 rc = _wdupenv_s(&pathext, &varsize, L"PATHEXT");
782 if (rc == 0) {
783 extension = wcstok_s(pathext, L";", &context);
784 while (extension) {
785 len = SearchPathW(NULL, name, extension, MSGSIZE, path_command.value, NULL);
786 if (len) {
787 result = &path_command;
788 break;
789 }
790 extension = wcstok_s(NULL, L";", &context);
791 }
792 free(pathext);
793 }
794 }
795 return result;
796}
797
798#endif
799
800static COMMAND * find_command(wchar_t * name)
801{
802 COMMAND * result = NULL;
803 COMMAND * cp = commands;
804 int i;
805
806 for (i = 0; i < num_commands; i++, cp++) {
807 if (_wcsicmp(cp->key, name) == 0) {
808 result = cp;
809 break;
810 }
811 }
812#if defined(SEARCH_PATH)
813 if (result == NULL)
814 result = find_on_path(name);
815#endif
816 return result;
817}
818
819static void
820update_command(COMMAND * cp, wchar_t * name, wchar_t * cmdline)
821{
822 wcsncpy_s(cp->key, MAX_PATH, name, _TRUNCATE);
823 wcsncpy_s(cp->value, MSGSIZE, cmdline, _TRUNCATE);
824}
825
826static void
827add_command(wchar_t * name, wchar_t * cmdline)
828{
829 if (num_commands >= MAX_COMMANDS) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800830 debug(L"can't add %ls = '%ls': no room\n", name, cmdline);
Brian Curtin07165f72012-06-20 15:36:14 -0500831 }
832 else {
833 COMMAND * cp = &commands[num_commands++];
834
835 update_command(cp, name, cmdline);
836 }
837}
838
839static void
840read_config_file(wchar_t * config_path)
841{
842 wchar_t keynames[MSGSIZE];
843 wchar_t value[MSGSIZE];
844 DWORD read;
845 wchar_t * key;
846 COMMAND * cp;
847 wchar_t * cmdp;
848
849 read = GetPrivateProfileStringW(L"commands", NULL, NULL, keynames, MSGSIZE,
850 config_path);
851 if (read == MSGSIZE - 1) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800852 debug(L"read_commands: %ls: not enough space for names\n", config_path);
Brian Curtin07165f72012-06-20 15:36:14 -0500853 }
854 key = keynames;
855 while (*key) {
856 read = GetPrivateProfileStringW(L"commands", key, NULL, value, 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 %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500860 config_path, key);
861 }
862 cmdp = skip_whitespace(value);
863 if (*cmdp) {
864 cp = find_command(key);
865 if (cp == NULL)
866 add_command(key, value);
867 else
868 update_command(cp, key, value);
869 }
870 key += wcslen(key) + 1;
871 }
872}
873
874static void read_commands()
875{
876 if (launcher_ini_path[0])
877 read_config_file(launcher_ini_path);
878 if (appdata_ini_path[0])
879 read_config_file(appdata_ini_path);
880}
881
882static BOOL
883parse_shebang(wchar_t * shebang_line, int nchars, wchar_t ** command,
Vinay Sajip22c039b2013-06-07 15:37:28 +0100884 wchar_t ** suffix, BOOL *search)
Brian Curtin07165f72012-06-20 15:36:14 -0500885{
886 BOOL rc = FALSE;
Vinay Sajip22c039b2013-06-07 15:37:28 +0100887 SHEBANG * vpp;
Brian Curtin07165f72012-06-20 15:36:14 -0500888 size_t plen;
889 wchar_t * p;
890 wchar_t zapped;
891 wchar_t * endp = shebang_line + nchars - 1;
892 COMMAND * cp;
893 wchar_t * skipped;
894
895 *command = NULL; /* failure return */
896 *suffix = NULL;
Vinay Sajip22c039b2013-06-07 15:37:28 +0100897 *search = FALSE;
Brian Curtin07165f72012-06-20 15:36:14 -0500898
899 if ((*shebang_line++ == L'#') && (*shebang_line++ == L'!')) {
900 shebang_line = skip_whitespace(shebang_line);
901 if (*shebang_line) {
902 *command = shebang_line;
Vinay Sajip22c039b2013-06-07 15:37:28 +0100903 for (vpp = builtin_virtual_paths; vpp->shebang; ++vpp) {
904 plen = wcslen(vpp->shebang);
905 if (wcsncmp(shebang_line, vpp->shebang, plen) == 0) {
Brian Curtin07165f72012-06-20 15:36:14 -0500906 rc = TRUE;
Vinay Sajip22c039b2013-06-07 15:37:28 +0100907 *search = vpp->search;
Brian Curtin07165f72012-06-20 15:36:14 -0500908 /* We can do this because all builtin commands contain
909 * "python".
910 */
911 *command = wcsstr(shebang_line, L"python");
912 break;
913 }
914 }
Vinay Sajip22c039b2013-06-07 15:37:28 +0100915 if (vpp->shebang == NULL) {
Brian Curtin07165f72012-06-20 15:36:14 -0500916 /*
Vinay Sajip9c10d6b2013-11-15 20:58:13 +0000917 * Not found in builtins - look in customized commands.
Brian Curtin07165f72012-06-20 15:36:14 -0500918 *
919 * We can't permanently modify the shebang line in case
Vinay Sajip9c10d6b2013-11-15 20:58:13 +0000920 * it's not a customized command, but we can temporarily
Brian Curtin07165f72012-06-20 15:36:14 -0500921 * stick a NUL after the command while searching for it,
922 * then put back the char we zapped.
923 */
924#if defined(SKIP_PREFIX)
925 skipped = skip_prefix(shebang_line);
926#else
927 skipped = shebang_line;
928#endif
929 p = wcspbrk(skipped, L" \t\r\n");
930 if (p != NULL) {
931 zapped = *p;
932 *p = L'\0';
933 }
934 cp = find_command(skipped);
935 if (p != NULL)
936 *p = zapped;
937 if (cp != NULL) {
938 *command = cp->value;
939 if (p != NULL)
940 *suffix = skip_whitespace(p);
941 }
942 }
943 /* remove trailing whitespace */
944 while ((endp > shebang_line) && isspace(*endp))
945 --endp;
946 if (endp > shebang_line)
947 endp[1] = L'\0';
948 }
949 }
950 return rc;
951}
952
953/* #define CP_UTF8 65001 defined in winnls.h */
954#define CP_UTF16LE 1200
955#define CP_UTF16BE 1201
956#define CP_UTF32LE 12000
957#define CP_UTF32BE 12001
958
959typedef struct {
960 int length;
961 char sequence[4];
962 UINT code_page;
963} BOM;
964
965/*
Vinay Sajipc985d082013-07-25 11:20:55 +0100966 * Strictly, we don't need to handle UTF-16 and UTF-32, since Python itself
Brian Curtin07165f72012-06-20 15:36:14 -0500967 * doesn't. Never mind, one day it might - there's no harm leaving it in.
968 */
969static BOM BOMs[] = {
970 { 3, { 0xEF, 0xBB, 0xBF }, CP_UTF8 }, /* UTF-8 - keep first */
Serhiy Storchaka29e2aa62015-12-18 10:23:09 +0200971 /* Test UTF-32LE before UTF-16LE since UTF-16LE BOM is a prefix
972 * of UTF-32LE BOM. */
Brian Curtin07165f72012-06-20 15:36:14 -0500973 { 4, { 0xFF, 0xFE, 0x00, 0x00 }, CP_UTF32LE }, /* UTF-32LE */
974 { 4, { 0x00, 0x00, 0xFE, 0xFF }, CP_UTF32BE }, /* UTF-32BE */
Serhiy Storchaka29e2aa62015-12-18 10:23:09 +0200975 { 2, { 0xFF, 0xFE }, CP_UTF16LE }, /* UTF-16LE */
976 { 2, { 0xFE, 0xFF }, CP_UTF16BE }, /* UTF-16BE */
Brian Curtin07165f72012-06-20 15:36:14 -0500977 { 0 } /* sentinel */
978};
979
980static BOM *
981find_BOM(char * buffer)
982{
983/*
984 * Look for a BOM in the input and return a pointer to the
985 * corresponding structure, or NULL if not found.
986 */
987 BOM * result = NULL;
988 BOM *bom;
989
990 for (bom = BOMs; bom->length; bom++) {
991 if (strncmp(bom->sequence, buffer, bom->length) == 0) {
992 result = bom;
993 break;
994 }
995 }
996 return result;
997}
998
999static char *
1000find_terminator(char * buffer, int len, BOM *bom)
1001{
1002 char * result = NULL;
1003 char * end = buffer + len;
1004 char * p;
1005 char c;
1006 int cp;
1007
1008 for (p = buffer; p < end; p++) {
1009 c = *p;
1010 if (c == '\r') {
1011 result = p;
1012 break;
1013 }
1014 if (c == '\n') {
1015 result = p;
1016 break;
1017 }
1018 }
1019 if (result != NULL) {
1020 cp = bom->code_page;
1021
1022 /* adjustments to include all bytes of the char */
1023 /* no adjustment needed for UTF-8 or big endian */
1024 if (cp == CP_UTF16LE)
1025 ++result;
1026 else if (cp == CP_UTF32LE)
1027 result += 3;
1028 ++result; /* point just past terminator */
1029 }
1030 return result;
1031}
1032
1033static BOOL
1034validate_version(wchar_t * p)
1035{
1036 BOOL result = TRUE;
1037
1038 if (!isdigit(*p)) /* expect major version */
1039 result = FALSE;
1040 else if (*++p) { /* more to do */
1041 if (*p != L'.') /* major/minor separator */
1042 result = FALSE;
1043 else {
1044 ++p;
1045 if (!isdigit(*p)) /* expect minor version */
1046 result = FALSE;
1047 else {
1048 ++p;
1049 if (*p) { /* more to do */
1050 if (*p != L'-')
1051 result = FALSE;
1052 else {
1053 ++p;
1054 if ((*p != '3') && (*++p != '2') && !*++p)
1055 result = FALSE;
1056 }
1057 }
1058 }
1059 }
1060 }
1061 return result;
1062}
1063
1064typedef struct {
1065 unsigned short min;
1066 unsigned short max;
1067 wchar_t version[MAX_VERSION_SIZE];
1068} PYC_MAGIC;
1069
1070static PYC_MAGIC magic_values[] = {
Steve Dower7ae61af2016-05-16 09:34:20 -07001071 { 50823, 50823, L"2.0" },
1072 { 60202, 60202, L"2.1" },
1073 { 60717, 60717, L"2.2" },
1074 { 62011, 62021, L"2.3" },
1075 { 62041, 62061, L"2.4" },
1076 { 62071, 62131, L"2.5" },
1077 { 62151, 62161, L"2.6" },
1078 { 62171, 62211, L"2.7" },
1079 { 3000, 3131, L"3.0" },
1080 { 3141, 3151, L"3.1" },
1081 { 3160, 3180, L"3.2" },
1082 { 3190, 3230, L"3.3" },
1083 { 3250, 3310, L"3.4" },
Serhiy Storchaka3c317e72016-06-12 09:22:01 +03001084 { 3320, 3351, L"3.5" },
Steve Dowerdc953a52016-05-16 11:04:44 -07001085 { 3360, 3361, L"3.6" },
Brian Curtin07165f72012-06-20 15:36:14 -05001086 { 0 }
1087};
1088
1089static INSTALLED_PYTHON *
1090find_by_magic(unsigned short magic)
1091{
1092 INSTALLED_PYTHON * result = NULL;
1093 PYC_MAGIC * mp;
1094
1095 for (mp = magic_values; mp->min; mp++) {
1096 if ((magic >= mp->min) && (magic <= mp->max)) {
1097 result = locate_python(mp->version);
1098 if (result != NULL)
1099 break;
1100 }
1101 }
1102 return result;
1103}
1104
1105static void
1106maybe_handle_shebang(wchar_t ** argv, wchar_t * cmdline)
1107{
1108/*
1109 * Look for a shebang line in the first argument. If found
1110 * and we spawn a child process, this never returns. If it
1111 * does return then we process the args "normally".
1112 *
1113 * argv[0] might be a filename with a shebang.
1114 */
1115 FILE * fp;
1116 errno_t rc = _wfopen_s(&fp, *argv, L"rb");
1117 unsigned char buffer[BUFSIZE];
1118 wchar_t shebang_line[BUFSIZE + 1];
1119 size_t read;
1120 char *p;
1121 char * start;
1122 char * shebang_alias = (char *) shebang_line;
1123 BOM* bom;
1124 int i, j, nchars = 0;
1125 int header_len;
1126 BOOL is_virt;
Vinay Sajip22c039b2013-06-07 15:37:28 +01001127 BOOL search;
Brian Curtin07165f72012-06-20 15:36:14 -05001128 wchar_t * command;
1129 wchar_t * suffix;
Vinay Sajip22c039b2013-06-07 15:37:28 +01001130 COMMAND *cmd = NULL;
Brian Curtin07165f72012-06-20 15:36:14 -05001131 INSTALLED_PYTHON * ip;
1132
1133 if (rc == 0) {
1134 read = fread(buffer, sizeof(char), BUFSIZE, fp);
1135 debug(L"maybe_handle_shebang: read %d bytes\n", read);
1136 fclose(fp);
1137
1138 if ((read >= 4) && (buffer[3] == '\n') && (buffer[2] == '\r')) {
1139 ip = find_by_magic((buffer[1] << 8 | buffer[0]) & 0xFFFF);
1140 if (ip != NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001141 debug(L"script file is compiled against Python %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -05001142 ip->version);
1143 invoke_child(ip->executable, NULL, cmdline);
1144 }
1145 }
1146 /* Look for BOM */
1147 bom = find_BOM(buffer);
1148 if (bom == NULL) {
1149 start = buffer;
1150 debug(L"maybe_handle_shebang: BOM not found, using UTF-8\n");
1151 bom = BOMs; /* points to UTF-8 entry - the default */
1152 }
1153 else {
1154 debug(L"maybe_handle_shebang: BOM found, code page %d\n",
1155 bom->code_page);
1156 start = &buffer[bom->length];
1157 }
1158 p = find_terminator(start, BUFSIZE, bom);
1159 /*
1160 * If no CR or LF was found in the heading,
1161 * we assume it's not a shebang file.
1162 */
1163 if (p == NULL) {
1164 debug(L"maybe_handle_shebang: No line terminator found\n");
1165 }
1166 else {
1167 /*
1168 * Found line terminator - parse the shebang.
1169 *
1170 * Strictly, we don't need to handle UTF-16 anf UTF-32,
1171 * since Python itself doesn't.
1172 * Never mind, one day it might.
1173 */
1174 header_len = (int) (p - start);
1175 switch(bom->code_page) {
1176 case CP_UTF8:
1177 nchars = MultiByteToWideChar(bom->code_page,
1178 0,
1179 start, header_len, shebang_line,
1180 BUFSIZE);
1181 break;
1182 case CP_UTF16BE:
1183 if (header_len % 2 != 0) {
1184 debug(L"maybe_handle_shebang: UTF-16BE, but an odd number \
1185of bytes: %d\n", header_len);
1186 /* nchars = 0; Not needed - initialised to 0. */
1187 }
1188 else {
1189 for (i = header_len; i > 0; i -= 2) {
1190 shebang_alias[i - 1] = start[i - 2];
1191 shebang_alias[i - 2] = start[i - 1];
1192 }
1193 nchars = header_len / sizeof(wchar_t);
1194 }
1195 break;
1196 case CP_UTF16LE:
1197 if ((header_len % 2) != 0) {
1198 debug(L"UTF-16LE, but an odd number of bytes: %d\n",
1199 header_len);
1200 /* nchars = 0; Not needed - initialised to 0. */
1201 }
1202 else {
1203 /* no actual conversion needed. */
1204 memcpy(shebang_line, start, header_len);
1205 nchars = header_len / sizeof(wchar_t);
1206 }
1207 break;
1208 case CP_UTF32BE:
1209 if (header_len % 4 != 0) {
1210 debug(L"UTF-32BE, but not divisible by 4: %d\n",
1211 header_len);
1212 /* nchars = 0; Not needed - initialised to 0. */
1213 }
1214 else {
1215 for (i = header_len, j = header_len / 2; i > 0; i -= 4,
1216 j -= 2) {
1217 shebang_alias[j - 1] = start[i - 2];
1218 shebang_alias[j - 2] = start[i - 1];
1219 }
1220 nchars = header_len / sizeof(wchar_t);
1221 }
1222 break;
1223 case CP_UTF32LE:
1224 if (header_len % 4 != 0) {
1225 debug(L"UTF-32LE, but not divisible by 4: %d\n",
1226 header_len);
1227 /* nchars = 0; Not needed - initialised to 0. */
1228 }
1229 else {
1230 for (i = header_len, j = header_len / 2; i > 0; i -= 4,
1231 j -= 2) {
1232 shebang_alias[j - 1] = start[i - 3];
1233 shebang_alias[j - 2] = start[i - 4];
1234 }
1235 nchars = header_len / sizeof(wchar_t);
1236 }
1237 break;
1238 }
1239 if (nchars > 0) {
1240 shebang_line[--nchars] = L'\0';
1241 is_virt = parse_shebang(shebang_line, nchars, &command,
Vinay Sajip22c039b2013-06-07 15:37:28 +01001242 &suffix, &search);
Brian Curtin07165f72012-06-20 15:36:14 -05001243 if (command != NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001244 debug(L"parse_shebang: found command: %ls\n", command);
Brian Curtin07165f72012-06-20 15:36:14 -05001245 if (!is_virt) {
1246 invoke_child(command, suffix, cmdline);
1247 }
1248 else {
1249 suffix = wcschr(command, L' ');
1250 if (suffix != NULL) {
1251 *suffix++ = L'\0';
1252 suffix = skip_whitespace(suffix);
1253 }
1254 if (wcsncmp(command, L"python", 6))
1255 error(RC_BAD_VIRTUAL_PATH, L"Unknown virtual \
Steve Dower84bcfb32015-01-02 18:07:46 -08001256path '%ls'", command);
Brian Curtin07165f72012-06-20 15:36:14 -05001257 command += 6; /* skip past "python" */
Vinay Sajip22c039b2013-06-07 15:37:28 +01001258 if (search && ((*command == L'\0') || isspace(*command))) {
1259 /* Command is eligible for path search, and there
1260 * is no version specification.
1261 */
1262 debug(L"searching PATH for python executable\n");
Vinay Sajipa5892ab2015-12-26 13:10:51 +00001263 cmd = find_on_path(PYTHON_EXECUTABLE);
Steve Dower84bcfb32015-01-02 18:07:46 -08001264 debug(L"Python on path: %ls\n", cmd ? cmd->value : L"<not found>");
Vinay Sajip22c039b2013-06-07 15:37:28 +01001265 if (cmd) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001266 debug(L"located python on PATH: %ls\n", cmd->value);
Vinay Sajip22c039b2013-06-07 15:37:28 +01001267 invoke_child(cmd->value, suffix, cmdline);
1268 /* Exit here, as we have found the command */
1269 return;
1270 }
1271 /* FALL THROUGH: No python found on PATH, so fall
1272 * back to locating the correct installed python.
1273 */
1274 }
Brian Curtin07165f72012-06-20 15:36:14 -05001275 if (*command && !validate_version(command))
1276 error(RC_BAD_VIRTUAL_PATH, L"Invalid version \
Steve Dower84bcfb32015-01-02 18:07:46 -08001277specification: '%ls'.\nIn the first line of the script, 'python' needs to be \
Brian Curtin07165f72012-06-20 15:36:14 -05001278followed by a valid version specifier.\nPlease check the documentation.",
1279 command);
1280 /* TODO could call validate_version(command) */
1281 ip = locate_python(command);
1282 if (ip == NULL) {
1283 error(RC_NO_PYTHON, L"Requested Python version \
Steve Dower84bcfb32015-01-02 18:07:46 -08001284(%ls) is not installed", command);
Brian Curtin07165f72012-06-20 15:36:14 -05001285 }
1286 else {
1287 invoke_child(ip->executable, suffix, cmdline);
1288 }
1289 }
1290 }
1291 }
1292 }
1293 }
1294}
1295
1296static wchar_t *
1297skip_me(wchar_t * cmdline)
1298{
1299 BOOL quoted;
1300 wchar_t c;
1301 wchar_t * result = cmdline;
1302
1303 quoted = cmdline[0] == L'\"';
1304 if (!quoted)
1305 c = L' ';
1306 else {
1307 c = L'\"';
1308 ++result;
1309 }
1310 result = wcschr(result, c);
1311 if (result == NULL) /* when, for example, just exe name on command line */
1312 result = L"";
1313 else {
1314 ++result; /* skip past space or closing quote */
1315 result = skip_whitespace(result);
1316 }
1317 return result;
1318}
1319
1320static DWORD version_high = 0;
1321static DWORD version_low = 0;
1322
1323static void
1324get_version_info(wchar_t * version_text, size_t size)
1325{
1326 WORD maj, min, rel, bld;
1327
1328 if (!version_high && !version_low)
1329 wcsncpy_s(version_text, size, L"0.1", _TRUNCATE); /* fallback */
1330 else {
1331 maj = HIWORD(version_high);
1332 min = LOWORD(version_high);
1333 rel = HIWORD(version_low);
1334 bld = LOWORD(version_low);
1335 _snwprintf_s(version_text, size, _TRUNCATE, L"%d.%d.%d.%d", maj,
1336 min, rel, bld);
1337 }
1338}
1339
1340static int
1341process(int argc, wchar_t ** argv)
1342{
1343 wchar_t * wp;
1344 wchar_t * command;
Steve Dower76998fe2015-02-26 14:25:33 -08001345 wchar_t * executable;
Brian Curtin07165f72012-06-20 15:36:14 -05001346 wchar_t * p;
1347 int rc = 0;
1348 size_t plen;
1349 INSTALLED_PYTHON * ip;
1350 BOOL valid;
1351 DWORD size, attrs;
1352 HRESULT hr;
1353 wchar_t message[MSGSIZE];
1354 wchar_t version_text [MAX_PATH];
1355 void * version_data;
1356 VS_FIXEDFILEINFO * file_info;
1357 UINT block_size;
Vinay Sajip2ae8c632013-01-29 22:29:25 +00001358 int index;
Vinay Sajipc985d082013-07-25 11:20:55 +01001359#if defined(SCRIPT_WRAPPER)
1360 int newlen;
1361 wchar_t * newcommand;
1362 wchar_t * av[2];
1363#endif
Brian Curtin07165f72012-06-20 15:36:14 -05001364
1365 wp = get_env(L"PYLAUNCH_DEBUG");
1366 if ((wp != NULL) && (*wp != L'\0'))
1367 log_fp = stderr;
1368
1369#if defined(_M_X64)
1370 debug(L"launcher build: 64bit\n");
1371#else
1372 debug(L"launcher build: 32bit\n");
1373#endif
1374#if defined(_WINDOWS)
1375 debug(L"launcher executable: Windows\n");
1376#else
1377 debug(L"launcher executable: Console\n");
1378#endif
1379 /* Get the local appdata folder (non-roaming) */
1380 hr = SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA,
1381 NULL, 0, appdata_ini_path);
1382 if (hr != S_OK) {
1383 debug(L"SHGetFolderPath failed: %X\n", hr);
1384 appdata_ini_path[0] = L'\0';
1385 }
1386 else {
1387 plen = wcslen(appdata_ini_path);
1388 p = &appdata_ini_path[plen];
1389 wcsncpy_s(p, MAX_PATH - plen, L"\\py.ini", _TRUNCATE);
1390 attrs = GetFileAttributesW(appdata_ini_path);
1391 if (attrs == INVALID_FILE_ATTRIBUTES) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001392 debug(L"File '%ls' non-existent\n", appdata_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001393 appdata_ini_path[0] = L'\0';
1394 } else {
Steve Dower84bcfb32015-01-02 18:07:46 -08001395 debug(L"Using local configuration file '%ls'\n", appdata_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001396 }
1397 }
1398 plen = GetModuleFileNameW(NULL, launcher_ini_path, MAX_PATH);
1399 size = GetFileVersionInfoSizeW(launcher_ini_path, &size);
1400 if (size == 0) {
1401 winerror(GetLastError(), message, MSGSIZE);
Steve Dower84bcfb32015-01-02 18:07:46 -08001402 debug(L"GetFileVersionInfoSize failed: %ls\n", message);
Brian Curtin07165f72012-06-20 15:36:14 -05001403 }
1404 else {
1405 version_data = malloc(size);
1406 if (version_data) {
1407 valid = GetFileVersionInfoW(launcher_ini_path, 0, size,
1408 version_data);
1409 if (!valid)
1410 debug(L"GetFileVersionInfo failed: %X\n", GetLastError());
1411 else {
Vinay Sajip404229b2013-01-29 22:52:57 +00001412 valid = VerQueryValueW(version_data, L"\\",
1413 (LPVOID *) &file_info, &block_size);
Brian Curtin07165f72012-06-20 15:36:14 -05001414 if (!valid)
1415 debug(L"VerQueryValue failed: %X\n", GetLastError());
1416 else {
1417 version_high = file_info->dwFileVersionMS;
1418 version_low = file_info->dwFileVersionLS;
1419 }
1420 }
1421 free(version_data);
1422 }
1423 }
1424 p = wcsrchr(launcher_ini_path, L'\\');
1425 if (p == NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001426 debug(L"GetModuleFileNameW returned value has no backslash: %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -05001427 launcher_ini_path);
1428 launcher_ini_path[0] = L'\0';
1429 }
1430 else {
1431 wcsncpy_s(p, MAX_PATH - (p - launcher_ini_path), L"\\py.ini",
1432 _TRUNCATE);
1433 attrs = GetFileAttributesW(launcher_ini_path);
1434 if (attrs == INVALID_FILE_ATTRIBUTES) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001435 debug(L"File '%ls' non-existent\n", launcher_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001436 launcher_ini_path[0] = L'\0';
1437 } else {
Steve Dower84bcfb32015-01-02 18:07:46 -08001438 debug(L"Using global configuration file '%ls'\n", launcher_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001439 }
1440 }
1441
1442 command = skip_me(GetCommandLineW());
Steve Dower84bcfb32015-01-02 18:07:46 -08001443 debug(L"Called with command line: %ls\n", command);
Vinay Sajipc985d082013-07-25 11:20:55 +01001444
1445#if defined(SCRIPT_WRAPPER)
1446 /* The launcher is being used in "script wrapper" mode.
1447 * There should therefore be a Python script named <exename>-script.py in
1448 * the same directory as the launcher executable.
1449 * Put the script name into argv as the first (script name) argument.
1450 */
1451
1452 /* Get the wrapped script name - if the script is not present, this will
1453 * terminate the program with an error.
1454 */
1455 locate_wrapped_script();
1456
1457 /* Add the wrapped script to the start of command */
1458 newlen = wcslen(wrapped_script_path) + wcslen(command) + 2; /* ' ' + NUL */
1459 newcommand = malloc(sizeof(wchar_t) * newlen);
1460 if (!newcommand) {
1461 error(RC_NO_MEMORY, L"Could not allocate new command line");
1462 }
1463 else {
1464 wcscpy_s(newcommand, newlen, wrapped_script_path);
1465 wcscat_s(newcommand, newlen, L" ");
1466 wcscat_s(newcommand, newlen, command);
Steve Dower84bcfb32015-01-02 18:07:46 -08001467 debug(L"Running wrapped script with command line '%ls'\n", newcommand);
Vinay Sajipc985d082013-07-25 11:20:55 +01001468 read_commands();
1469 av[0] = wrapped_script_path;
1470 av[1] = NULL;
1471 maybe_handle_shebang(av, newcommand);
1472 /* Returns if no shebang line - pass to default processing */
1473 command = newcommand;
1474 valid = FALSE;
1475 }
1476#else
Brian Curtin07165f72012-06-20 15:36:14 -05001477 if (argc <= 1) {
1478 valid = FALSE;
1479 p = NULL;
1480 }
1481 else {
1482 p = argv[1];
1483 plen = wcslen(p);
Brian Curtin07165f72012-06-20 15:36:14 -05001484 valid = (*p == L'-') && validate_version(&p[1]);
1485 if (valid) {
1486 ip = locate_python(&p[1]);
1487 if (ip == NULL)
Steve Dower84bcfb32015-01-02 18:07:46 -08001488 error(RC_NO_PYTHON, L"Requested Python version (%ls) not \
Brian Curtin07165f72012-06-20 15:36:14 -05001489installed", &p[1]);
Steve Dower76998fe2015-02-26 14:25:33 -08001490 executable = ip->executable;
Brian Curtin07165f72012-06-20 15:36:14 -05001491 command += wcslen(p);
1492 command = skip_whitespace(command);
1493 }
Vinay Sajip2ae8c632013-01-29 22:29:25 +00001494 else {
1495 for (index = 1; index < argc; ++index) {
1496 if (*argv[index] != L'-')
1497 break;
1498 }
1499 if (index < argc) {
1500 read_commands();
1501 maybe_handle_shebang(&argv[index], command);
1502 }
1503 }
Brian Curtin07165f72012-06-20 15:36:14 -05001504 }
Vinay Sajipc985d082013-07-25 11:20:55 +01001505#endif
1506
Brian Curtin07165f72012-06-20 15:36:14 -05001507 if (!valid) {
Steve Dower76998fe2015-02-26 14:25:33 -08001508 /* Look for an active virtualenv */
1509 executable = find_python_by_venv();
1510
1511 /* If we didn't find one, look for the default Python */
1512 if (executable == NULL) {
1513 ip = locate_python(L"");
1514 if (ip == NULL)
1515 error(RC_NO_PYTHON, L"Can't find a default Python.");
1516 executable = ip->executable;
1517 }
Brian Curtin07165f72012-06-20 15:36:14 -05001518 if ((argc == 2) && (!_wcsicmp(p, L"-h") || !_wcsicmp(p, L"--help"))) {
1519#if defined(_M_X64)
1520 BOOL canDo64bit = TRUE;
1521#else
1522 // If we are a 32bit process on a 64bit Windows, first hit the 64bit keys.
1523 BOOL canDo64bit = FALSE;
1524 IsWow64Process(GetCurrentProcess(), &canDo64bit);
1525#endif
1526
1527 get_version_info(version_text, MAX_PATH);
1528 fwprintf(stdout, L"\
Steve Dower84bcfb32015-01-02 18:07:46 -08001529Python Launcher for Windows Version %ls\n\n", version_text);
Brian Curtin07165f72012-06-20 15:36:14 -05001530 fwprintf(stdout, L"\
Steve Dower84bcfb32015-01-02 18:07:46 -08001531usage: %ls [ launcher-arguments ] [ python-arguments ] script [ script-arguments ]\n\n", argv[0]);
Brian Curtin07165f72012-06-20 15:36:14 -05001532 fputws(L"\
1533Launcher arguments:\n\n\
1534-2 : Launch the latest Python 2.x version\n\
1535-3 : Launch the latest Python 3.x version\n\
1536-X.Y : Launch the specified Python version\n", stdout);
1537 if (canDo64bit) {
1538 fputws(L"\
1539-X.Y-32: Launch the specified 32bit Python version", stdout);
1540 }
1541 fputws(L"\n\nThe following help text is from Python:\n\n", stdout);
1542 fflush(stdout);
1543 }
1544 }
Steve Dower76998fe2015-02-26 14:25:33 -08001545 invoke_child(executable, NULL, command);
Brian Curtin07165f72012-06-20 15:36:14 -05001546 return rc;
1547}
1548
1549#if defined(_WINDOWS)
1550
1551int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
1552 LPWSTR lpstrCmd, int nShow)
1553{
1554 return process(__argc, __wargv);
1555}
1556
1557#else
1558
1559int cdecl wmain(int argc, wchar_t ** argv)
1560{
1561 return process(argc, argv);
1562}
1563
Vinay Sajip2ae8c632013-01-29 22:29:25 +00001564#endif