blob: eac01f8ad8a8f5ceb4c69722dde92ceb6a8761a1 [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 *
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);
Vinay Sajipaab9f462015-12-26 12:35:47 +0000658 exit(rc);
Brian Curtin07165f72012-06-20 15:36:14 -0500659}
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[] = {
1071 { 0xc687, 0xc687, L"2.0" },
1072 { 0xeb2a, 0xeb2a, L"2.1" },
1073 { 0xed2d, 0xed2d, L"2.2" },
1074 { 0xf23b, 0xf245, L"2.3" },
1075 { 0xf259, 0xf26d, L"2.4" },
1076 { 0xf277, 0xf2b3, L"2.5" },
1077 { 0xf2c7, 0xf2d1, L"2.6" },
1078 { 0xf2db, 0xf303, L"2.7" },
1079 { 0x0bb8, 0x0c3b, L"3.0" },
1080 { 0x0c45, 0x0c4f, L"3.1" },
1081 { 0x0c58, 0x0c6c, L"3.2" },
Steve Dower87fb7f62016-01-16 13:48:06 -08001082 { 0x0c76, 0x0c9e, L"3.3" },
1083 { 0x0cb2, 0x0cee, L"3.4" },
1084 { 0x0cf8, 0x0d16, L"3.5" },
1085 { 0x0d20, 0x0d20, 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");
Serhiy Storchakaf8ed0042015-12-18 10:19:30 +02001117 char buffer[BUFSIZE];
Brian Curtin07165f72012-06-20 15:36:14 -05001118 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')) {
Serhiy Storchakaf8ed0042015-12-18 10:19:30 +02001139 ip = find_by_magic((((unsigned char)buffer[1]) << 8 |
1140 (unsigned char)buffer[0]) & 0xFFFF);
Brian Curtin07165f72012-06-20 15:36:14 -05001141 if (ip != NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001142 debug(L"script file is compiled against Python %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -05001143 ip->version);
1144 invoke_child(ip->executable, NULL, cmdline);
1145 }
1146 }
1147 /* Look for BOM */
1148 bom = find_BOM(buffer);
1149 if (bom == NULL) {
1150 start = buffer;
1151 debug(L"maybe_handle_shebang: BOM not found, using UTF-8\n");
1152 bom = BOMs; /* points to UTF-8 entry - the default */
1153 }
1154 else {
1155 debug(L"maybe_handle_shebang: BOM found, code page %d\n",
1156 bom->code_page);
1157 start = &buffer[bom->length];
1158 }
1159 p = find_terminator(start, BUFSIZE, bom);
1160 /*
1161 * If no CR or LF was found in the heading,
1162 * we assume it's not a shebang file.
1163 */
1164 if (p == NULL) {
1165 debug(L"maybe_handle_shebang: No line terminator found\n");
1166 }
1167 else {
1168 /*
1169 * Found line terminator - parse the shebang.
1170 *
1171 * Strictly, we don't need to handle UTF-16 anf UTF-32,
1172 * since Python itself doesn't.
1173 * Never mind, one day it might.
1174 */
1175 header_len = (int) (p - start);
1176 switch(bom->code_page) {
1177 case CP_UTF8:
1178 nchars = MultiByteToWideChar(bom->code_page,
1179 0,
1180 start, header_len, shebang_line,
1181 BUFSIZE);
1182 break;
1183 case CP_UTF16BE:
1184 if (header_len % 2 != 0) {
1185 debug(L"maybe_handle_shebang: UTF-16BE, but an odd number \
1186of bytes: %d\n", header_len);
1187 /* nchars = 0; Not needed - initialised to 0. */
1188 }
1189 else {
1190 for (i = header_len; i > 0; i -= 2) {
1191 shebang_alias[i - 1] = start[i - 2];
1192 shebang_alias[i - 2] = start[i - 1];
1193 }
1194 nchars = header_len / sizeof(wchar_t);
1195 }
1196 break;
1197 case CP_UTF16LE:
1198 if ((header_len % 2) != 0) {
1199 debug(L"UTF-16LE, but an odd number of bytes: %d\n",
1200 header_len);
1201 /* nchars = 0; Not needed - initialised to 0. */
1202 }
1203 else {
1204 /* no actual conversion needed. */
1205 memcpy(shebang_line, start, header_len);
1206 nchars = header_len / sizeof(wchar_t);
1207 }
1208 break;
1209 case CP_UTF32BE:
1210 if (header_len % 4 != 0) {
1211 debug(L"UTF-32BE, but not divisible by 4: %d\n",
1212 header_len);
1213 /* nchars = 0; Not needed - initialised to 0. */
1214 }
1215 else {
1216 for (i = header_len, j = header_len / 2; i > 0; i -= 4,
1217 j -= 2) {
1218 shebang_alias[j - 1] = start[i - 2];
1219 shebang_alias[j - 2] = start[i - 1];
1220 }
1221 nchars = header_len / sizeof(wchar_t);
1222 }
1223 break;
1224 case CP_UTF32LE:
1225 if (header_len % 4 != 0) {
1226 debug(L"UTF-32LE, but not divisible by 4: %d\n",
1227 header_len);
1228 /* nchars = 0; Not needed - initialised to 0. */
1229 }
1230 else {
1231 for (i = header_len, j = header_len / 2; i > 0; i -= 4,
1232 j -= 2) {
1233 shebang_alias[j - 1] = start[i - 3];
1234 shebang_alias[j - 2] = start[i - 4];
1235 }
1236 nchars = header_len / sizeof(wchar_t);
1237 }
1238 break;
1239 }
1240 if (nchars > 0) {
1241 shebang_line[--nchars] = L'\0';
1242 is_virt = parse_shebang(shebang_line, nchars, &command,
Vinay Sajip22c039b2013-06-07 15:37:28 +01001243 &suffix, &search);
Brian Curtin07165f72012-06-20 15:36:14 -05001244 if (command != NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001245 debug(L"parse_shebang: found command: %ls\n", command);
Brian Curtin07165f72012-06-20 15:36:14 -05001246 if (!is_virt) {
1247 invoke_child(command, suffix, cmdline);
1248 }
1249 else {
1250 suffix = wcschr(command, L' ');
1251 if (suffix != NULL) {
1252 *suffix++ = L'\0';
1253 suffix = skip_whitespace(suffix);
1254 }
1255 if (wcsncmp(command, L"python", 6))
1256 error(RC_BAD_VIRTUAL_PATH, L"Unknown virtual \
Steve Dower84bcfb32015-01-02 18:07:46 -08001257path '%ls'", command);
Brian Curtin07165f72012-06-20 15:36:14 -05001258 command += 6; /* skip past "python" */
Vinay Sajip22c039b2013-06-07 15:37:28 +01001259 if (search && ((*command == L'\0') || isspace(*command))) {
1260 /* Command is eligible for path search, and there
1261 * is no version specification.
1262 */
1263 debug(L"searching PATH for python executable\n");
Vinay Sajipa5892ab2015-12-26 13:10:51 +00001264 cmd = find_on_path(PYTHON_EXECUTABLE);
Steve Dower84bcfb32015-01-02 18:07:46 -08001265 debug(L"Python on path: %ls\n", cmd ? cmd->value : L"<not found>");
Vinay Sajip22c039b2013-06-07 15:37:28 +01001266 if (cmd) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001267 debug(L"located python on PATH: %ls\n", cmd->value);
Vinay Sajip22c039b2013-06-07 15:37:28 +01001268 invoke_child(cmd->value, suffix, cmdline);
1269 /* Exit here, as we have found the command */
1270 return;
1271 }
1272 /* FALL THROUGH: No python found on PATH, so fall
1273 * back to locating the correct installed python.
1274 */
1275 }
Brian Curtin07165f72012-06-20 15:36:14 -05001276 if (*command && !validate_version(command))
1277 error(RC_BAD_VIRTUAL_PATH, L"Invalid version \
Steve Dower84bcfb32015-01-02 18:07:46 -08001278specification: '%ls'.\nIn the first line of the script, 'python' needs to be \
Brian Curtin07165f72012-06-20 15:36:14 -05001279followed by a valid version specifier.\nPlease check the documentation.",
1280 command);
1281 /* TODO could call validate_version(command) */
1282 ip = locate_python(command);
1283 if (ip == NULL) {
1284 error(RC_NO_PYTHON, L"Requested Python version \
Steve Dower84bcfb32015-01-02 18:07:46 -08001285(%ls) is not installed", command);
Brian Curtin07165f72012-06-20 15:36:14 -05001286 }
1287 else {
1288 invoke_child(ip->executable, suffix, cmdline);
1289 }
1290 }
1291 }
1292 }
1293 }
1294 }
1295}
1296
1297static wchar_t *
1298skip_me(wchar_t * cmdline)
1299{
1300 BOOL quoted;
1301 wchar_t c;
1302 wchar_t * result = cmdline;
1303
1304 quoted = cmdline[0] == L'\"';
1305 if (!quoted)
1306 c = L' ';
1307 else {
1308 c = L'\"';
1309 ++result;
1310 }
1311 result = wcschr(result, c);
1312 if (result == NULL) /* when, for example, just exe name on command line */
1313 result = L"";
1314 else {
1315 ++result; /* skip past space or closing quote */
1316 result = skip_whitespace(result);
1317 }
1318 return result;
1319}
1320
1321static DWORD version_high = 0;
1322static DWORD version_low = 0;
1323
1324static void
1325get_version_info(wchar_t * version_text, size_t size)
1326{
1327 WORD maj, min, rel, bld;
1328
1329 if (!version_high && !version_low)
1330 wcsncpy_s(version_text, size, L"0.1", _TRUNCATE); /* fallback */
1331 else {
1332 maj = HIWORD(version_high);
1333 min = LOWORD(version_high);
1334 rel = HIWORD(version_low);
1335 bld = LOWORD(version_low);
1336 _snwprintf_s(version_text, size, _TRUNCATE, L"%d.%d.%d.%d", maj,
1337 min, rel, bld);
1338 }
1339}
1340
1341static int
1342process(int argc, wchar_t ** argv)
1343{
1344 wchar_t * wp;
1345 wchar_t * command;
Steve Dower76998fe2015-02-26 14:25:33 -08001346 wchar_t * executable;
Brian Curtin07165f72012-06-20 15:36:14 -05001347 wchar_t * p;
1348 int rc = 0;
1349 size_t plen;
1350 INSTALLED_PYTHON * ip;
1351 BOOL valid;
1352 DWORD size, attrs;
1353 HRESULT hr;
1354 wchar_t message[MSGSIZE];
1355 wchar_t version_text [MAX_PATH];
1356 void * version_data;
1357 VS_FIXEDFILEINFO * file_info;
1358 UINT block_size;
Vinay Sajip2ae8c632013-01-29 22:29:25 +00001359 int index;
Vinay Sajipc985d082013-07-25 11:20:55 +01001360#if defined(SCRIPT_WRAPPER)
1361 int newlen;
1362 wchar_t * newcommand;
1363 wchar_t * av[2];
1364#endif
Brian Curtin07165f72012-06-20 15:36:14 -05001365
Vinay Sajipaab9f462015-12-26 12:35:47 +00001366 setvbuf(stderr, (char *)NULL, _IONBF, 0);
Brian Curtin07165f72012-06-20 15:36:14 -05001367 wp = get_env(L"PYLAUNCH_DEBUG");
1368 if ((wp != NULL) && (*wp != L'\0'))
1369 log_fp = stderr;
1370
1371#if defined(_M_X64)
1372 debug(L"launcher build: 64bit\n");
1373#else
1374 debug(L"launcher build: 32bit\n");
1375#endif
1376#if defined(_WINDOWS)
1377 debug(L"launcher executable: Windows\n");
1378#else
1379 debug(L"launcher executable: Console\n");
1380#endif
1381 /* Get the local appdata folder (non-roaming) */
1382 hr = SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA,
1383 NULL, 0, appdata_ini_path);
1384 if (hr != S_OK) {
1385 debug(L"SHGetFolderPath failed: %X\n", hr);
1386 appdata_ini_path[0] = L'\0';
1387 }
1388 else {
1389 plen = wcslen(appdata_ini_path);
1390 p = &appdata_ini_path[plen];
1391 wcsncpy_s(p, MAX_PATH - plen, L"\\py.ini", _TRUNCATE);
1392 attrs = GetFileAttributesW(appdata_ini_path);
1393 if (attrs == INVALID_FILE_ATTRIBUTES) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001394 debug(L"File '%ls' non-existent\n", appdata_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001395 appdata_ini_path[0] = L'\0';
1396 } else {
Steve Dower84bcfb32015-01-02 18:07:46 -08001397 debug(L"Using local configuration file '%ls'\n", appdata_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001398 }
1399 }
1400 plen = GetModuleFileNameW(NULL, launcher_ini_path, MAX_PATH);
1401 size = GetFileVersionInfoSizeW(launcher_ini_path, &size);
1402 if (size == 0) {
1403 winerror(GetLastError(), message, MSGSIZE);
Steve Dower84bcfb32015-01-02 18:07:46 -08001404 debug(L"GetFileVersionInfoSize failed: %ls\n", message);
Brian Curtin07165f72012-06-20 15:36:14 -05001405 }
1406 else {
1407 version_data = malloc(size);
1408 if (version_data) {
1409 valid = GetFileVersionInfoW(launcher_ini_path, 0, size,
1410 version_data);
1411 if (!valid)
1412 debug(L"GetFileVersionInfo failed: %X\n", GetLastError());
1413 else {
Vinay Sajip404229b2013-01-29 22:52:57 +00001414 valid = VerQueryValueW(version_data, L"\\",
1415 (LPVOID *) &file_info, &block_size);
Brian Curtin07165f72012-06-20 15:36:14 -05001416 if (!valid)
1417 debug(L"VerQueryValue failed: %X\n", GetLastError());
1418 else {
1419 version_high = file_info->dwFileVersionMS;
1420 version_low = file_info->dwFileVersionLS;
1421 }
1422 }
1423 free(version_data);
1424 }
1425 }
1426 p = wcsrchr(launcher_ini_path, L'\\');
1427 if (p == NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001428 debug(L"GetModuleFileNameW returned value has no backslash: %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -05001429 launcher_ini_path);
1430 launcher_ini_path[0] = L'\0';
1431 }
1432 else {
1433 wcsncpy_s(p, MAX_PATH - (p - launcher_ini_path), L"\\py.ini",
1434 _TRUNCATE);
1435 attrs = GetFileAttributesW(launcher_ini_path);
1436 if (attrs == INVALID_FILE_ATTRIBUTES) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001437 debug(L"File '%ls' non-existent\n", launcher_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001438 launcher_ini_path[0] = L'\0';
1439 } else {
Steve Dower84bcfb32015-01-02 18:07:46 -08001440 debug(L"Using global configuration file '%ls'\n", launcher_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001441 }
1442 }
1443
1444 command = skip_me(GetCommandLineW());
Steve Dower84bcfb32015-01-02 18:07:46 -08001445 debug(L"Called with command line: %ls\n", command);
Vinay Sajipc985d082013-07-25 11:20:55 +01001446
1447#if defined(SCRIPT_WRAPPER)
1448 /* The launcher is being used in "script wrapper" mode.
1449 * There should therefore be a Python script named <exename>-script.py in
1450 * the same directory as the launcher executable.
1451 * Put the script name into argv as the first (script name) argument.
1452 */
1453
1454 /* Get the wrapped script name - if the script is not present, this will
1455 * terminate the program with an error.
1456 */
1457 locate_wrapped_script();
1458
1459 /* Add the wrapped script to the start of command */
1460 newlen = wcslen(wrapped_script_path) + wcslen(command) + 2; /* ' ' + NUL */
1461 newcommand = malloc(sizeof(wchar_t) * newlen);
1462 if (!newcommand) {
1463 error(RC_NO_MEMORY, L"Could not allocate new command line");
1464 }
1465 else {
1466 wcscpy_s(newcommand, newlen, wrapped_script_path);
1467 wcscat_s(newcommand, newlen, L" ");
1468 wcscat_s(newcommand, newlen, command);
Steve Dower84bcfb32015-01-02 18:07:46 -08001469 debug(L"Running wrapped script with command line '%ls'\n", newcommand);
Vinay Sajipc985d082013-07-25 11:20:55 +01001470 read_commands();
1471 av[0] = wrapped_script_path;
1472 av[1] = NULL;
1473 maybe_handle_shebang(av, newcommand);
1474 /* Returns if no shebang line - pass to default processing */
1475 command = newcommand;
1476 valid = FALSE;
1477 }
1478#else
Brian Curtin07165f72012-06-20 15:36:14 -05001479 if (argc <= 1) {
1480 valid = FALSE;
1481 p = NULL;
1482 }
1483 else {
1484 p = argv[1];
1485 plen = wcslen(p);
Brian Curtin07165f72012-06-20 15:36:14 -05001486 valid = (*p == L'-') && validate_version(&p[1]);
1487 if (valid) {
1488 ip = locate_python(&p[1]);
1489 if (ip == NULL)
Steve Dower84bcfb32015-01-02 18:07:46 -08001490 error(RC_NO_PYTHON, L"Requested Python version (%ls) not \
Brian Curtin07165f72012-06-20 15:36:14 -05001491installed", &p[1]);
Steve Dower76998fe2015-02-26 14:25:33 -08001492 executable = ip->executable;
Brian Curtin07165f72012-06-20 15:36:14 -05001493 command += wcslen(p);
1494 command = skip_whitespace(command);
1495 }
Vinay Sajip2ae8c632013-01-29 22:29:25 +00001496 else {
1497 for (index = 1; index < argc; ++index) {
1498 if (*argv[index] != L'-')
1499 break;
1500 }
1501 if (index < argc) {
1502 read_commands();
1503 maybe_handle_shebang(&argv[index], command);
1504 }
1505 }
Brian Curtin07165f72012-06-20 15:36:14 -05001506 }
Vinay Sajipc985d082013-07-25 11:20:55 +01001507#endif
1508
Brian Curtin07165f72012-06-20 15:36:14 -05001509 if (!valid) {
Steve Dower76998fe2015-02-26 14:25:33 -08001510 /* Look for an active virtualenv */
1511 executable = find_python_by_venv();
1512
1513 /* If we didn't find one, look for the default Python */
1514 if (executable == NULL) {
1515 ip = locate_python(L"");
1516 if (ip == NULL)
1517 error(RC_NO_PYTHON, L"Can't find a default Python.");
1518 executable = ip->executable;
1519 }
Brian Curtin07165f72012-06-20 15:36:14 -05001520 if ((argc == 2) && (!_wcsicmp(p, L"-h") || !_wcsicmp(p, L"--help"))) {
1521#if defined(_M_X64)
1522 BOOL canDo64bit = TRUE;
1523#else
1524 // If we are a 32bit process on a 64bit Windows, first hit the 64bit keys.
1525 BOOL canDo64bit = FALSE;
1526 IsWow64Process(GetCurrentProcess(), &canDo64bit);
1527#endif
1528
1529 get_version_info(version_text, MAX_PATH);
1530 fwprintf(stdout, L"\
Steve Dower84bcfb32015-01-02 18:07:46 -08001531Python Launcher for Windows Version %ls\n\n", version_text);
Brian Curtin07165f72012-06-20 15:36:14 -05001532 fwprintf(stdout, L"\
Steve Dower84bcfb32015-01-02 18:07:46 -08001533usage: %ls [ launcher-arguments ] [ python-arguments ] script [ script-arguments ]\n\n", argv[0]);
Brian Curtin07165f72012-06-20 15:36:14 -05001534 fputws(L"\
1535Launcher arguments:\n\n\
1536-2 : Launch the latest Python 2.x version\n\
1537-3 : Launch the latest Python 3.x version\n\
1538-X.Y : Launch the specified Python version\n", stdout);
1539 if (canDo64bit) {
1540 fputws(L"\
1541-X.Y-32: Launch the specified 32bit Python version", stdout);
1542 }
1543 fputws(L"\n\nThe following help text is from Python:\n\n", stdout);
1544 fflush(stdout);
1545 }
1546 }
Steve Dower76998fe2015-02-26 14:25:33 -08001547 invoke_child(executable, NULL, command);
Brian Curtin07165f72012-06-20 15:36:14 -05001548 return rc;
1549}
1550
1551#if defined(_WINDOWS)
1552
1553int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
1554 LPWSTR lpstrCmd, int nShow)
1555{
1556 return process(__argc, __wargv);
1557}
1558
1559#else
1560
1561int cdecl wmain(int argc, wchar_t ** argv)
1562{
1563 return process(argc, argv);
1564}
1565
Vinay Sajip2ae8c632013-01-29 22:29:25 +00001566#endif