blob: 121aa5bfabe32a528d122c095cc0493873df5903 [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\\",
174 NULL
175};
176
177static INSTALLED_PYTHON *
178find_existing_python(wchar_t * path)
179{
180 INSTALLED_PYTHON * result = NULL;
181 size_t i;
182 INSTALLED_PYTHON * ip;
183
184 for (i = 0, ip = installed_pythons; i < num_installed_pythons; i++, ip++) {
185 if (_wcsicmp(path, ip->executable) == 0) {
186 result = ip;
187 break;
188 }
189 }
190 return result;
191}
192
193static void
194locate_pythons_for_key(HKEY root, REGSAM flags)
195{
196 HKEY core_root, ip_key;
197 LSTATUS status = RegOpenKeyExW(root, CORE_PATH, 0, flags, &core_root);
198 wchar_t message[MSGSIZE];
199 DWORD i;
200 size_t n;
201 BOOL ok;
202 DWORD type, data_size, attrs;
203 INSTALLED_PYTHON * ip, * pip;
Steve Dowerbb240872015-02-05 22:08:48 -0800204 wchar_t ip_version[IP_VERSION_SIZE];
Brian Curtin07165f72012-06-20 15:36:14 -0500205 wchar_t ip_path[IP_SIZE];
206 wchar_t * check;
207 wchar_t ** checkp;
208 wchar_t *key_name = (root == HKEY_LOCAL_MACHINE) ? L"HKLM" : L"HKCU";
209
210 if (status != ERROR_SUCCESS)
Steve Dower84bcfb32015-01-02 18:07:46 -0800211 debug(L"locate_pythons_for_key: unable to open PythonCore key in %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500212 key_name);
213 else {
214 ip = &installed_pythons[num_installed_pythons];
215 for (i = 0; num_installed_pythons < MAX_INSTALLED_PYTHONS; i++) {
Steve Dowerbb240872015-02-05 22:08:48 -0800216 status = RegEnumKeyW(core_root, i, ip_version, IP_VERSION_SIZE);
Brian Curtin07165f72012-06-20 15:36:14 -0500217 if (status != ERROR_SUCCESS) {
218 if (status != ERROR_NO_MORE_ITEMS) {
219 /* unexpected error */
220 winerror(status, message, MSGSIZE);
Steve Dower84bcfb32015-01-02 18:07:46 -0800221 debug(L"Can't enumerate registry key for version %ls: %ls\n",
Steve Dowerbb240872015-02-05 22:08:48 -0800222 ip_version, message);
Brian Curtin07165f72012-06-20 15:36:14 -0500223 }
224 break;
225 }
226 else {
Steve Dowerbb240872015-02-05 22:08:48 -0800227 wcsncpy_s(ip->version, MAX_VERSION_SIZE, ip_version,
228 MAX_VERSION_SIZE-1);
Brian Curtin07165f72012-06-20 15:36:14 -0500229 _snwprintf_s(ip_path, IP_SIZE, _TRUNCATE,
Steve Dowerbb240872015-02-05 22:08:48 -0800230 L"%ls\\%ls\\InstallPath", CORE_PATH, ip_version);
Brian Curtin07165f72012-06-20 15:36:14 -0500231 status = RegOpenKeyExW(root, ip_path, 0, flags, &ip_key);
232 if (status != ERROR_SUCCESS) {
233 winerror(status, message, MSGSIZE);
234 // Note: 'message' already has a trailing \n
Steve Dower84bcfb32015-01-02 18:07:46 -0800235 debug(L"%ls\\%ls: %ls", key_name, ip_path, message);
Brian Curtin07165f72012-06-20 15:36:14 -0500236 continue;
237 }
238 data_size = sizeof(ip->executable) - 1;
Martin v. Löwisaf21ebb2012-06-21 18:15:54 +0200239 status = RegQueryValueExW(ip_key, NULL, NULL, &type,
240 (LPBYTE)ip->executable, &data_size);
Brian Curtin07165f72012-06-20 15:36:14 -0500241 RegCloseKey(ip_key);
242 if (status != ERROR_SUCCESS) {
243 winerror(status, message, MSGSIZE);
Steve Dower84bcfb32015-01-02 18:07:46 -0800244 debug(L"%ls\\%ls: %ls\n", key_name, ip_path, message);
Brian Curtin07165f72012-06-20 15:36:14 -0500245 continue;
246 }
247 if (type == REG_SZ) {
248 data_size = data_size / sizeof(wchar_t) - 1; /* for NUL */
249 if (ip->executable[data_size - 1] == L'\\')
250 --data_size; /* reg value ended in a backslash */
251 /* ip->executable is data_size long */
252 for (checkp = location_checks; *checkp; ++checkp) {
253 check = *checkp;
254 _snwprintf_s(&ip->executable[data_size],
255 MAX_PATH - data_size,
256 MAX_PATH - data_size,
Steve Dower84bcfb32015-01-02 18:07:46 -0800257 L"%ls%ls", check, PYTHON_EXECUTABLE);
Brian Curtin07165f72012-06-20 15:36:14 -0500258 attrs = GetFileAttributesW(ip->executable);
259 if (attrs == INVALID_FILE_ATTRIBUTES) {
260 winerror(GetLastError(), message, MSGSIZE);
Steve Dower84bcfb32015-01-02 18:07:46 -0800261 debug(L"locate_pythons_for_key: %ls: %ls",
Brian Curtin07165f72012-06-20 15:36:14 -0500262 ip->executable, message);
263 }
264 else if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800265 debug(L"locate_pythons_for_key: '%ls' is a \
Brian Curtin07165f72012-06-20 15:36:14 -0500266directory\n",
267 ip->executable, attrs);
268 }
269 else if (find_existing_python(ip->executable)) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800270 debug(L"locate_pythons_for_key: %ls: already \
Steve Dower13be8c22015-03-10 19:38:25 -0700271found\n", ip->executable);
Brian Curtin07165f72012-06-20 15:36:14 -0500272 }
273 else {
274 /* check the executable type. */
275 ok = GetBinaryTypeW(ip->executable, &attrs);
276 if (!ok) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800277 debug(L"Failure getting binary type: %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500278 ip->executable);
279 }
280 else {
281 if (attrs == SCS_64BIT_BINARY)
282 ip->bits = 64;
283 else if (attrs == SCS_32BIT_BINARY)
284 ip->bits = 32;
285 else
286 ip->bits = 0;
287 if (ip->bits == 0) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800288 debug(L"locate_pythons_for_key: %ls: \
Brian Curtin07165f72012-06-20 15:36:14 -0500289invalid binary type: %X\n",
290 ip->executable, attrs);
291 }
292 else {
293 if (wcschr(ip->executable, L' ') != NULL) {
294 /* has spaces, so quote */
295 n = wcslen(ip->executable);
296 memmove(&ip->executable[1],
297 ip->executable, n * sizeof(wchar_t));
298 ip->executable[0] = L'\"';
299 ip->executable[n + 1] = L'\"';
300 ip->executable[n + 2] = L'\0';
301 }
Steve Dower84bcfb32015-01-02 18:07:46 -0800302 debug(L"locate_pythons_for_key: %ls \
Brian Curtin07165f72012-06-20 15:36:14 -0500303is a %dbit executable\n",
304 ip->executable, ip->bits);
305 ++num_installed_pythons;
306 pip = ip++;
307 if (num_installed_pythons >=
308 MAX_INSTALLED_PYTHONS)
309 break;
310 /* Copy over the attributes for the next */
311 *ip = *pip;
312 }
313 }
314 }
315 }
316 }
317 }
318 }
319 RegCloseKey(core_root);
320 }
321}
322
323static int
324compare_pythons(const void * p1, const void * p2)
325{
326 INSTALLED_PYTHON * ip1 = (INSTALLED_PYTHON *) p1;
327 INSTALLED_PYTHON * ip2 = (INSTALLED_PYTHON *) p2;
328 /* note reverse sorting on version */
329 int result = wcscmp(ip2->version, ip1->version);
330
331 if (result == 0)
332 result = ip2->bits - ip1->bits; /* 64 before 32 */
333 return result;
334}
335
336static void
337locate_all_pythons()
338{
339#if defined(_M_X64)
340 // If we are a 64bit process, first hit the 32bit keys.
341 debug(L"locating Pythons in 32bit registry\n");
342 locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ | KEY_WOW64_32KEY);
343 locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ | KEY_WOW64_32KEY);
344#else
345 // If we are a 32bit process on a 64bit Windows, first hit the 64bit keys.
346 BOOL f64 = FALSE;
347 if (IsWow64Process(GetCurrentProcess(), &f64) && f64) {
348 debug(L"locating Pythons in 64bit registry\n");
349 locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ | KEY_WOW64_64KEY);
350 locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ | KEY_WOW64_64KEY);
351 }
Serhiy Storchaka009b8112015-03-18 21:53:15 +0200352#endif
Brian Curtin07165f72012-06-20 15:36:14 -0500353 // now hit the "native" key for this process bittedness.
354 debug(L"locating Pythons in native registry\n");
355 locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ);
356 locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ);
357 qsort(installed_pythons, num_installed_pythons, sizeof(INSTALLED_PYTHON),
358 compare_pythons);
359}
360
361static INSTALLED_PYTHON *
362find_python_by_version(wchar_t const * wanted_ver)
363{
364 INSTALLED_PYTHON * result = NULL;
365 INSTALLED_PYTHON * ip = installed_pythons;
366 size_t i, n;
367 size_t wlen = wcslen(wanted_ver);
368 int bits = 0;
369
370 if (wcsstr(wanted_ver, L"-32"))
371 bits = 32;
372 for (i = 0; i < num_installed_pythons; i++, ip++) {
373 n = wcslen(ip->version);
374 if (n > wlen)
375 n = wlen;
376 if ((wcsncmp(ip->version, wanted_ver, n) == 0) &&
377 /* bits == 0 => don't care */
378 ((bits == 0) || (ip->bits == bits))) {
379 result = ip;
380 break;
381 }
382 }
383 return result;
384}
385
386
Steve Dower76998fe2015-02-26 14:25:33 -0800387static wchar_t *
388find_python_by_venv()
389{
390 static wchar_t venv_python[MAX_PATH];
391 wchar_t *virtual_env = get_env(L"VIRTUAL_ENV");
392 DWORD attrs;
393
394 /* Check for VIRTUAL_ENV environment variable */
395 if (virtual_env == NULL || virtual_env[0] == L'\0') {
396 return NULL;
397 }
398
399 /* Check for a python executable in the venv */
400 debug(L"Checking for Python executable in virtual env '%ls'\n", virtual_env);
401 _snwprintf_s(venv_python, MAX_PATH, _TRUNCATE,
402 L"%ls\\Scripts\\%ls", virtual_env, PYTHON_EXECUTABLE);
403 attrs = GetFileAttributesW(venv_python);
404 if (attrs == INVALID_FILE_ATTRIBUTES) {
405 debug(L"Python executable %ls missing from virtual env\n", venv_python);
406 return NULL;
407 }
408
409 return venv_python;
410}
411
Brian Curtin07165f72012-06-20 15:36:14 -0500412static wchar_t appdata_ini_path[MAX_PATH];
413static wchar_t launcher_ini_path[MAX_PATH];
414
415/*
416 * Get a value either from the environment or a configuration file.
417 * The key passed in will either be "python", "python2" or "python3".
418 */
419static wchar_t *
420get_configured_value(wchar_t * key)
421{
422/*
423 * Note: this static value is used to return a configured value
424 * obtained either from the environment or configuration file.
425 * This should be OK since there wouldn't be any concurrent calls.
426 */
427 static wchar_t configured_value[MSGSIZE];
428 wchar_t * result = NULL;
429 wchar_t * found_in = L"environment";
430 DWORD size;
431
432 /* First, search the environment. */
Steve Dower84bcfb32015-01-02 18:07:46 -0800433 _snwprintf_s(configured_value, MSGSIZE, _TRUNCATE, L"py_%ls", key);
Brian Curtin07165f72012-06-20 15:36:14 -0500434 result = get_env(configured_value);
435 if (result == NULL && appdata_ini_path[0]) {
436 /* Not in environment: check local configuration. */
437 size = GetPrivateProfileStringW(L"defaults", key, NULL,
438 configured_value, MSGSIZE,
439 appdata_ini_path);
440 if (size > 0) {
441 result = configured_value;
442 found_in = appdata_ini_path;
443 }
444 }
445 if (result == NULL && launcher_ini_path[0]) {
446 /* Not in environment or local: check global configuration. */
447 size = GetPrivateProfileStringW(L"defaults", key, NULL,
448 configured_value, MSGSIZE,
449 launcher_ini_path);
450 if (size > 0) {
451 result = configured_value;
452 found_in = launcher_ini_path;
453 }
454 }
455 if (result) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800456 debug(L"found configured value '%ls=%ls' in %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500457 key, result, found_in ? found_in : L"(unknown)");
458 } else {
Steve Dower84bcfb32015-01-02 18:07:46 -0800459 debug(L"found no configured value for '%ls'\n", key);
Brian Curtin07165f72012-06-20 15:36:14 -0500460 }
461 return result;
462}
463
464static INSTALLED_PYTHON *
465locate_python(wchar_t * wanted_ver)
466{
467 static wchar_t config_key [] = { L"pythonX" };
468 static wchar_t * last_char = &config_key[sizeof(config_key) /
469 sizeof(wchar_t) - 2];
470 INSTALLED_PYTHON * result = NULL;
471 size_t n = wcslen(wanted_ver);
472 wchar_t * configured_value;
473
474 if (num_installed_pythons == 0)
475 locate_all_pythons();
476
477 if (n == 1) { /* just major version specified */
478 *last_char = *wanted_ver;
479 configured_value = get_configured_value(config_key);
480 if (configured_value != NULL)
481 wanted_ver = configured_value;
482 }
483 if (*wanted_ver) {
484 result = find_python_by_version(wanted_ver);
Steve Dower84bcfb32015-01-02 18:07:46 -0800485 debug(L"search for Python version '%ls' found ", wanted_ver);
Brian Curtin07165f72012-06-20 15:36:14 -0500486 if (result) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800487 debug(L"'%ls'\n", result->executable);
Brian Curtin07165f72012-06-20 15:36:14 -0500488 } else {
489 debug(L"no interpreter\n");
490 }
491 }
492 else {
493 *last_char = L'\0'; /* look for an overall default */
494 configured_value = get_configured_value(config_key);
495 if (configured_value)
496 result = find_python_by_version(configured_value);
497 if (result == NULL)
498 result = find_python_by_version(L"2");
499 if (result == NULL)
500 result = find_python_by_version(L"3");
501 debug(L"search for default Python found ");
502 if (result) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800503 debug(L"version %ls at '%ls'\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500504 result->version, result->executable);
505 } else {
506 debug(L"no interpreter\n");
507 }
508 }
509 return result;
510}
511
Vinay Sajipc985d082013-07-25 11:20:55 +0100512#if defined(SCRIPT_WRAPPER)
513/*
514 * Check for a script located alongside the executable
515 */
516
517#if defined(_WINDOWS)
518#define SCRIPT_SUFFIX L"-script.pyw"
519#else
520#define SCRIPT_SUFFIX L"-script.py"
521#endif
522
523static wchar_t wrapped_script_path[MAX_PATH];
524
525/* Locate the script being wrapped.
526 *
527 * This code should store the name of the wrapped script in
528 * wrapped_script_path, or terminate the program with an error if there is no
529 * valid wrapped script file.
530 */
531static void
532locate_wrapped_script()
533{
534 wchar_t * p;
535 size_t plen;
536 DWORD attrs;
537
538 plen = GetModuleFileNameW(NULL, wrapped_script_path, MAX_PATH);
539 p = wcsrchr(wrapped_script_path, L'.');
540 if (p == NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800541 debug(L"GetModuleFileNameW returned value has no extension: %ls\n",
Vinay Sajipc985d082013-07-25 11:20:55 +0100542 wrapped_script_path);
Steve Dower84bcfb32015-01-02 18:07:46 -0800543 error(RC_NO_SCRIPT, L"Wrapper name '%ls' is not valid.", wrapped_script_path);
Vinay Sajipc985d082013-07-25 11:20:55 +0100544 }
545
546 wcsncpy_s(p, MAX_PATH - (p - wrapped_script_path) + 1, SCRIPT_SUFFIX, _TRUNCATE);
547 attrs = GetFileAttributesW(wrapped_script_path);
548 if (attrs == INVALID_FILE_ATTRIBUTES) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800549 debug(L"File '%ls' non-existent\n", wrapped_script_path);
550 error(RC_NO_SCRIPT, L"Script file '%ls' is not present.", wrapped_script_path);
Vinay Sajipc985d082013-07-25 11:20:55 +0100551 }
552
Steve Dower84bcfb32015-01-02 18:07:46 -0800553 debug(L"Using wrapped script file '%ls'\n", wrapped_script_path);
Vinay Sajipc985d082013-07-25 11:20:55 +0100554}
555#endif
556
Brian Curtin07165f72012-06-20 15:36:14 -0500557/*
558 * Process creation code
559 */
560
561static BOOL
562safe_duplicate_handle(HANDLE in, HANDLE * pout)
563{
564 BOOL ok;
565 HANDLE process = GetCurrentProcess();
566 DWORD rc;
567
568 *pout = NULL;
569 ok = DuplicateHandle(process, in, process, pout, 0, TRUE,
570 DUPLICATE_SAME_ACCESS);
571 if (!ok) {
572 rc = GetLastError();
573 if (rc == ERROR_INVALID_HANDLE) {
574 debug(L"DuplicateHandle returned ERROR_INVALID_HANDLE\n");
575 ok = TRUE;
576 }
577 else {
578 debug(L"DuplicateHandle returned %d\n", rc);
579 }
580 }
581 return ok;
582}
583
584static BOOL WINAPI
585ctrl_c_handler(DWORD code)
586{
587 return TRUE; /* We just ignore all control events. */
588}
589
590static void
591run_child(wchar_t * cmdline)
592{
593 HANDLE job;
594 JOBOBJECT_EXTENDED_LIMIT_INFORMATION info;
595 DWORD rc;
596 BOOL ok;
597 STARTUPINFOW si;
598 PROCESS_INFORMATION pi;
599
Vinay Sajip66fef9f2013-02-26 16:29:06 +0000600#if defined(_WINDOWS)
601 // When explorer launches a Windows (GUI) application, it displays
602 // the "app starting" (the "pointer + hourglass") cursor for a number
603 // of seconds, or until the app does something UI-ish (eg, creating a
604 // window, or fetching a message). As this launcher doesn't do this
605 // directly, that cursor remains even after the child process does these
606 // things. We avoid that by doing a simple post+get message.
Serhiy Storchaka009b8112015-03-18 21:53:15 +0200607 // See http://bugs.python.org/issue17290 and
Vinay Sajip66fef9f2013-02-26 16:29:06 +0000608 // https://bitbucket.org/vinay.sajip/pylauncher/issue/20/busy-cursor-for-a-long-time-when-running
609 MSG msg;
610
611 PostMessage(0, 0, 0, 0);
612 GetMessage(&msg, 0, 0, 0);
613#endif
614
Steve Dower84bcfb32015-01-02 18:07:46 -0800615 debug(L"run_child: about to run '%ls'\n", cmdline);
Brian Curtin07165f72012-06-20 15:36:14 -0500616 job = CreateJobObject(NULL, NULL);
617 ok = QueryInformationJobObject(job, JobObjectExtendedLimitInformation,
618 &info, sizeof(info), &rc);
619 if (!ok || (rc != sizeof(info)) || !job)
620 error(RC_CREATE_PROCESS, L"Job information querying failed");
621 info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE |
622 JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK;
623 ok = SetInformationJobObject(job, JobObjectExtendedLimitInformation, &info,
624 sizeof(info));
625 if (!ok)
626 error(RC_CREATE_PROCESS, L"Job information setting failed");
627 memset(&si, 0, sizeof(si));
628 si.cb = sizeof(si);
629 ok = safe_duplicate_handle(GetStdHandle(STD_INPUT_HANDLE), &si.hStdInput);
630 if (!ok)
631 error(RC_NO_STD_HANDLES, L"stdin duplication failed");
632 ok = safe_duplicate_handle(GetStdHandle(STD_OUTPUT_HANDLE), &si.hStdOutput);
633 if (!ok)
634 error(RC_NO_STD_HANDLES, L"stdout duplication failed");
635 ok = safe_duplicate_handle(GetStdHandle(STD_ERROR_HANDLE), &si.hStdError);
636 if (!ok)
637 error(RC_NO_STD_HANDLES, L"stderr duplication failed");
638
639 ok = SetConsoleCtrlHandler(ctrl_c_handler, TRUE);
640 if (!ok)
641 error(RC_CREATE_PROCESS, L"control handler setting failed");
642
643 si.dwFlags = STARTF_USESTDHANDLES;
644 ok = CreateProcessW(NULL, cmdline, NULL, NULL, TRUE,
645 0, NULL, NULL, &si, &pi);
646 if (!ok)
Steve Dower84bcfb32015-01-02 18:07:46 -0800647 error(RC_CREATE_PROCESS, L"Unable to create process using '%ls'", cmdline);
Brian Curtin07165f72012-06-20 15:36:14 -0500648 AssignProcessToJobObject(job, pi.hProcess);
649 CloseHandle(pi.hThread);
Martin v. Löwisb26a9b12013-01-25 14:25:48 +0100650 WaitForSingleObjectEx(pi.hProcess, INFINITE, FALSE);
Brian Curtin07165f72012-06-20 15:36:14 -0500651 ok = GetExitCodeProcess(pi.hProcess, &rc);
652 if (!ok)
653 error(RC_CREATE_PROCESS, L"Failed to get exit code of process");
654 debug(L"child process exit code: %d\n", rc);
655 ExitProcess(rc);
656}
657
658static void
659invoke_child(wchar_t * executable, wchar_t * suffix, wchar_t * cmdline)
660{
661 wchar_t * child_command;
662 size_t child_command_size;
663 BOOL no_suffix = (suffix == NULL) || (*suffix == L'\0');
664 BOOL no_cmdline = (*cmdline == L'\0');
665
666 if (no_suffix && no_cmdline)
667 run_child(executable);
668 else {
669 if (no_suffix) {
670 /* add 2 for space separator + terminating NUL. */
671 child_command_size = wcslen(executable) + wcslen(cmdline) + 2;
672 }
673 else {
674 /* add 3 for 2 space separators + terminating NUL. */
675 child_command_size = wcslen(executable) + wcslen(suffix) +
676 wcslen(cmdline) + 3;
677 }
678 child_command = calloc(child_command_size, sizeof(wchar_t));
679 if (child_command == NULL)
680 error(RC_CREATE_PROCESS, L"unable to allocate %d bytes for child command.",
681 child_command_size);
682 if (no_suffix)
683 _snwprintf_s(child_command, child_command_size,
Steve Dower84bcfb32015-01-02 18:07:46 -0800684 child_command_size - 1, L"%ls %ls",
Brian Curtin07165f72012-06-20 15:36:14 -0500685 executable, cmdline);
686 else
687 _snwprintf_s(child_command, child_command_size,
Steve Dower84bcfb32015-01-02 18:07:46 -0800688 child_command_size - 1, L"%ls %ls %ls",
Brian Curtin07165f72012-06-20 15:36:14 -0500689 executable, suffix, cmdline);
690 run_child(child_command);
691 free(child_command);
692 }
693}
694
Vinay Sajip22c039b2013-06-07 15:37:28 +0100695typedef struct {
696 wchar_t *shebang;
697 BOOL search;
698} SHEBANG;
699
700static SHEBANG builtin_virtual_paths [] = {
701 { L"/usr/bin/env python", TRUE },
702 { L"/usr/bin/python", FALSE },
703 { L"/usr/local/bin/python", FALSE },
704 { L"python", FALSE },
705 { NULL, FALSE },
Brian Curtin07165f72012-06-20 15:36:14 -0500706};
707
708/* For now, a static array of commands. */
709
710#define MAX_COMMANDS 100
711
712typedef struct {
713 wchar_t key[MAX_PATH];
714 wchar_t value[MSGSIZE];
715} COMMAND;
716
717static COMMAND commands[MAX_COMMANDS];
718static int num_commands = 0;
719
720#if defined(SKIP_PREFIX)
721
722static wchar_t * builtin_prefixes [] = {
723 /* These must be in an order that the longest matches should be found,
724 * i.e. if the prefix is "/usr/bin/env ", it should match that entry
725 * *before* matching "/usr/bin/".
726 */
727 L"/usr/bin/env ",
728 L"/usr/bin/",
729 L"/usr/local/bin/",
730 NULL
731};
732
733static wchar_t * skip_prefix(wchar_t * name)
734{
735 wchar_t ** pp = builtin_prefixes;
736 wchar_t * result = name;
737 wchar_t * p;
738 size_t n;
739
740 for (; p = *pp; pp++) {
741 n = wcslen(p);
742 if (_wcsnicmp(p, name, n) == 0) {
743 result += n; /* skip the prefix */
744 if (p[n - 1] == L' ') /* No empty strings in table, so n > 1 */
745 result = skip_whitespace(result);
746 break;
747 }
748 }
749 return result;
750}
751
752#endif
753
754#if defined(SEARCH_PATH)
755
756static COMMAND path_command;
757
758static COMMAND * find_on_path(wchar_t * name)
759{
760 wchar_t * pathext;
761 size_t varsize;
762 wchar_t * context = NULL;
763 wchar_t * extension;
764 COMMAND * result = NULL;
765 DWORD len;
766 errno_t rc;
767
768 wcscpy_s(path_command.key, MAX_PATH, name);
769 if (wcschr(name, L'.') != NULL) {
770 /* assume it has an extension. */
771 len = SearchPathW(NULL, name, NULL, MSGSIZE, path_command.value, NULL);
772 if (len) {
773 result = &path_command;
774 }
775 }
776 else {
777 /* No extension - search using registered extensions. */
778 rc = _wdupenv_s(&pathext, &varsize, L"PATHEXT");
779 if (rc == 0) {
780 extension = wcstok_s(pathext, L";", &context);
781 while (extension) {
782 len = SearchPathW(NULL, name, extension, MSGSIZE, path_command.value, NULL);
783 if (len) {
784 result = &path_command;
785 break;
786 }
787 extension = wcstok_s(NULL, L";", &context);
788 }
789 free(pathext);
790 }
791 }
792 return result;
793}
794
795#endif
796
797static COMMAND * find_command(wchar_t * name)
798{
799 COMMAND * result = NULL;
800 COMMAND * cp = commands;
801 int i;
802
803 for (i = 0; i < num_commands; i++, cp++) {
804 if (_wcsicmp(cp->key, name) == 0) {
805 result = cp;
806 break;
807 }
808 }
809#if defined(SEARCH_PATH)
810 if (result == NULL)
811 result = find_on_path(name);
812#endif
813 return result;
814}
815
816static void
817update_command(COMMAND * cp, wchar_t * name, wchar_t * cmdline)
818{
819 wcsncpy_s(cp->key, MAX_PATH, name, _TRUNCATE);
820 wcsncpy_s(cp->value, MSGSIZE, cmdline, _TRUNCATE);
821}
822
823static void
824add_command(wchar_t * name, wchar_t * cmdline)
825{
826 if (num_commands >= MAX_COMMANDS) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800827 debug(L"can't add %ls = '%ls': no room\n", name, cmdline);
Brian Curtin07165f72012-06-20 15:36:14 -0500828 }
829 else {
830 COMMAND * cp = &commands[num_commands++];
831
832 update_command(cp, name, cmdline);
833 }
834}
835
836static void
837read_config_file(wchar_t * config_path)
838{
839 wchar_t keynames[MSGSIZE];
840 wchar_t value[MSGSIZE];
841 DWORD read;
842 wchar_t * key;
843 COMMAND * cp;
844 wchar_t * cmdp;
845
846 read = GetPrivateProfileStringW(L"commands", NULL, NULL, keynames, MSGSIZE,
847 config_path);
848 if (read == MSGSIZE - 1) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800849 debug(L"read_commands: %ls: not enough space for names\n", config_path);
Brian Curtin07165f72012-06-20 15:36:14 -0500850 }
851 key = keynames;
852 while (*key) {
853 read = GetPrivateProfileStringW(L"commands", key, NULL, value, MSGSIZE,
854 config_path);
855 if (read == MSGSIZE - 1) {
Steve Dower84bcfb32015-01-02 18:07:46 -0800856 debug(L"read_commands: %ls: not enough space for %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -0500857 config_path, key);
858 }
859 cmdp = skip_whitespace(value);
860 if (*cmdp) {
861 cp = find_command(key);
862 if (cp == NULL)
863 add_command(key, value);
864 else
865 update_command(cp, key, value);
866 }
867 key += wcslen(key) + 1;
868 }
869}
870
871static void read_commands()
872{
873 if (launcher_ini_path[0])
874 read_config_file(launcher_ini_path);
875 if (appdata_ini_path[0])
876 read_config_file(appdata_ini_path);
877}
878
879static BOOL
880parse_shebang(wchar_t * shebang_line, int nchars, wchar_t ** command,
Vinay Sajip22c039b2013-06-07 15:37:28 +0100881 wchar_t ** suffix, BOOL *search)
Brian Curtin07165f72012-06-20 15:36:14 -0500882{
883 BOOL rc = FALSE;
Vinay Sajip22c039b2013-06-07 15:37:28 +0100884 SHEBANG * vpp;
Brian Curtin07165f72012-06-20 15:36:14 -0500885 size_t plen;
886 wchar_t * p;
887 wchar_t zapped;
888 wchar_t * endp = shebang_line + nchars - 1;
889 COMMAND * cp;
890 wchar_t * skipped;
891
892 *command = NULL; /* failure return */
893 *suffix = NULL;
Vinay Sajip22c039b2013-06-07 15:37:28 +0100894 *search = FALSE;
Brian Curtin07165f72012-06-20 15:36:14 -0500895
896 if ((*shebang_line++ == L'#') && (*shebang_line++ == L'!')) {
897 shebang_line = skip_whitespace(shebang_line);
898 if (*shebang_line) {
899 *command = shebang_line;
Vinay Sajip22c039b2013-06-07 15:37:28 +0100900 for (vpp = builtin_virtual_paths; vpp->shebang; ++vpp) {
901 plen = wcslen(vpp->shebang);
902 if (wcsncmp(shebang_line, vpp->shebang, plen) == 0) {
Brian Curtin07165f72012-06-20 15:36:14 -0500903 rc = TRUE;
Vinay Sajip22c039b2013-06-07 15:37:28 +0100904 *search = vpp->search;
Brian Curtin07165f72012-06-20 15:36:14 -0500905 /* We can do this because all builtin commands contain
906 * "python".
907 */
908 *command = wcsstr(shebang_line, L"python");
909 break;
910 }
911 }
Vinay Sajip22c039b2013-06-07 15:37:28 +0100912 if (vpp->shebang == NULL) {
Brian Curtin07165f72012-06-20 15:36:14 -0500913 /*
Vinay Sajip9c10d6b2013-11-15 20:58:13 +0000914 * Not found in builtins - look in customized commands.
Brian Curtin07165f72012-06-20 15:36:14 -0500915 *
916 * We can't permanently modify the shebang line in case
Vinay Sajip9c10d6b2013-11-15 20:58:13 +0000917 * it's not a customized command, but we can temporarily
Brian Curtin07165f72012-06-20 15:36:14 -0500918 * stick a NUL after the command while searching for it,
919 * then put back the char we zapped.
920 */
921#if defined(SKIP_PREFIX)
922 skipped = skip_prefix(shebang_line);
923#else
924 skipped = shebang_line;
925#endif
926 p = wcspbrk(skipped, L" \t\r\n");
927 if (p != NULL) {
928 zapped = *p;
929 *p = L'\0';
930 }
931 cp = find_command(skipped);
932 if (p != NULL)
933 *p = zapped;
934 if (cp != NULL) {
935 *command = cp->value;
936 if (p != NULL)
937 *suffix = skip_whitespace(p);
938 }
939 }
940 /* remove trailing whitespace */
941 while ((endp > shebang_line) && isspace(*endp))
942 --endp;
943 if (endp > shebang_line)
944 endp[1] = L'\0';
945 }
946 }
947 return rc;
948}
949
950/* #define CP_UTF8 65001 defined in winnls.h */
951#define CP_UTF16LE 1200
952#define CP_UTF16BE 1201
953#define CP_UTF32LE 12000
954#define CP_UTF32BE 12001
955
956typedef struct {
957 int length;
958 char sequence[4];
959 UINT code_page;
960} BOM;
961
962/*
Vinay Sajipc985d082013-07-25 11:20:55 +0100963 * Strictly, we don't need to handle UTF-16 and UTF-32, since Python itself
Brian Curtin07165f72012-06-20 15:36:14 -0500964 * doesn't. Never mind, one day it might - there's no harm leaving it in.
965 */
966static BOM BOMs[] = {
967 { 3, { 0xEF, 0xBB, 0xBF }, CP_UTF8 }, /* UTF-8 - keep first */
Serhiy Storchaka29e2aa62015-12-18 10:23:09 +0200968 /* Test UTF-32LE before UTF-16LE since UTF-16LE BOM is a prefix
969 * of UTF-32LE BOM. */
Brian Curtin07165f72012-06-20 15:36:14 -0500970 { 4, { 0xFF, 0xFE, 0x00, 0x00 }, CP_UTF32LE }, /* UTF-32LE */
971 { 4, { 0x00, 0x00, 0xFE, 0xFF }, CP_UTF32BE }, /* UTF-32BE */
Serhiy Storchaka29e2aa62015-12-18 10:23:09 +0200972 { 2, { 0xFF, 0xFE }, CP_UTF16LE }, /* UTF-16LE */
973 { 2, { 0xFE, 0xFF }, CP_UTF16BE }, /* UTF-16BE */
Brian Curtin07165f72012-06-20 15:36:14 -0500974 { 0 } /* sentinel */
975};
976
977static BOM *
978find_BOM(char * buffer)
979{
980/*
981 * Look for a BOM in the input and return a pointer to the
982 * corresponding structure, or NULL if not found.
983 */
984 BOM * result = NULL;
985 BOM *bom;
986
987 for (bom = BOMs; bom->length; bom++) {
988 if (strncmp(bom->sequence, buffer, bom->length) == 0) {
989 result = bom;
990 break;
991 }
992 }
993 return result;
994}
995
996static char *
997find_terminator(char * buffer, int len, BOM *bom)
998{
999 char * result = NULL;
1000 char * end = buffer + len;
1001 char * p;
1002 char c;
1003 int cp;
1004
1005 for (p = buffer; p < end; p++) {
1006 c = *p;
1007 if (c == '\r') {
1008 result = p;
1009 break;
1010 }
1011 if (c == '\n') {
1012 result = p;
1013 break;
1014 }
1015 }
1016 if (result != NULL) {
1017 cp = bom->code_page;
1018
1019 /* adjustments to include all bytes of the char */
1020 /* no adjustment needed for UTF-8 or big endian */
1021 if (cp == CP_UTF16LE)
1022 ++result;
1023 else if (cp == CP_UTF32LE)
1024 result += 3;
1025 ++result; /* point just past terminator */
1026 }
1027 return result;
1028}
1029
1030static BOOL
1031validate_version(wchar_t * p)
1032{
1033 BOOL result = TRUE;
1034
1035 if (!isdigit(*p)) /* expect major version */
1036 result = FALSE;
1037 else if (*++p) { /* more to do */
1038 if (*p != L'.') /* major/minor separator */
1039 result = FALSE;
1040 else {
1041 ++p;
1042 if (!isdigit(*p)) /* expect minor version */
1043 result = FALSE;
1044 else {
1045 ++p;
1046 if (*p) { /* more to do */
1047 if (*p != L'-')
1048 result = FALSE;
1049 else {
1050 ++p;
1051 if ((*p != '3') && (*++p != '2') && !*++p)
1052 result = FALSE;
1053 }
1054 }
1055 }
1056 }
1057 }
1058 return result;
1059}
1060
1061typedef struct {
1062 unsigned short min;
1063 unsigned short max;
1064 wchar_t version[MAX_VERSION_SIZE];
1065} PYC_MAGIC;
1066
1067static PYC_MAGIC magic_values[] = {
1068 { 0xc687, 0xc687, L"2.0" },
1069 { 0xeb2a, 0xeb2a, L"2.1" },
1070 { 0xed2d, 0xed2d, L"2.2" },
1071 { 0xf23b, 0xf245, L"2.3" },
1072 { 0xf259, 0xf26d, L"2.4" },
1073 { 0xf277, 0xf2b3, L"2.5" },
1074 { 0xf2c7, 0xf2d1, L"2.6" },
1075 { 0xf2db, 0xf303, L"2.7" },
1076 { 0x0bb8, 0x0c3b, L"3.0" },
1077 { 0x0c45, 0x0c4f, L"3.1" },
1078 { 0x0c58, 0x0c6c, L"3.2" },
1079 { 0x0c76, 0x0c76, L"3.3" },
1080 { 0 }
1081};
1082
1083static INSTALLED_PYTHON *
1084find_by_magic(unsigned short magic)
1085{
1086 INSTALLED_PYTHON * result = NULL;
1087 PYC_MAGIC * mp;
1088
1089 for (mp = magic_values; mp->min; mp++) {
1090 if ((magic >= mp->min) && (magic <= mp->max)) {
1091 result = locate_python(mp->version);
1092 if (result != NULL)
1093 break;
1094 }
1095 }
1096 return result;
1097}
1098
1099static void
1100maybe_handle_shebang(wchar_t ** argv, wchar_t * cmdline)
1101{
1102/*
1103 * Look for a shebang line in the first argument. If found
1104 * and we spawn a child process, this never returns. If it
1105 * does return then we process the args "normally".
1106 *
1107 * argv[0] might be a filename with a shebang.
1108 */
1109 FILE * fp;
1110 errno_t rc = _wfopen_s(&fp, *argv, L"rb");
1111 unsigned char buffer[BUFSIZE];
1112 wchar_t shebang_line[BUFSIZE + 1];
1113 size_t read;
1114 char *p;
1115 char * start;
1116 char * shebang_alias = (char *) shebang_line;
1117 BOM* bom;
1118 int i, j, nchars = 0;
1119 int header_len;
1120 BOOL is_virt;
Vinay Sajip22c039b2013-06-07 15:37:28 +01001121 BOOL search;
Brian Curtin07165f72012-06-20 15:36:14 -05001122 wchar_t * command;
1123 wchar_t * suffix;
Vinay Sajip22c039b2013-06-07 15:37:28 +01001124 COMMAND *cmd = NULL;
Brian Curtin07165f72012-06-20 15:36:14 -05001125 INSTALLED_PYTHON * ip;
1126
1127 if (rc == 0) {
1128 read = fread(buffer, sizeof(char), BUFSIZE, fp);
1129 debug(L"maybe_handle_shebang: read %d bytes\n", read);
1130 fclose(fp);
1131
1132 if ((read >= 4) && (buffer[3] == '\n') && (buffer[2] == '\r')) {
1133 ip = find_by_magic((buffer[1] << 8 | buffer[0]) & 0xFFFF);
1134 if (ip != NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001135 debug(L"script file is compiled against Python %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -05001136 ip->version);
1137 invoke_child(ip->executable, NULL, cmdline);
1138 }
1139 }
1140 /* Look for BOM */
1141 bom = find_BOM(buffer);
1142 if (bom == NULL) {
1143 start = buffer;
1144 debug(L"maybe_handle_shebang: BOM not found, using UTF-8\n");
1145 bom = BOMs; /* points to UTF-8 entry - the default */
1146 }
1147 else {
1148 debug(L"maybe_handle_shebang: BOM found, code page %d\n",
1149 bom->code_page);
1150 start = &buffer[bom->length];
1151 }
1152 p = find_terminator(start, BUFSIZE, bom);
1153 /*
1154 * If no CR or LF was found in the heading,
1155 * we assume it's not a shebang file.
1156 */
1157 if (p == NULL) {
1158 debug(L"maybe_handle_shebang: No line terminator found\n");
1159 }
1160 else {
1161 /*
1162 * Found line terminator - parse the shebang.
1163 *
1164 * Strictly, we don't need to handle UTF-16 anf UTF-32,
1165 * since Python itself doesn't.
1166 * Never mind, one day it might.
1167 */
1168 header_len = (int) (p - start);
1169 switch(bom->code_page) {
1170 case CP_UTF8:
1171 nchars = MultiByteToWideChar(bom->code_page,
1172 0,
1173 start, header_len, shebang_line,
1174 BUFSIZE);
1175 break;
1176 case CP_UTF16BE:
1177 if (header_len % 2 != 0) {
1178 debug(L"maybe_handle_shebang: UTF-16BE, but an odd number \
1179of bytes: %d\n", header_len);
1180 /* nchars = 0; Not needed - initialised to 0. */
1181 }
1182 else {
1183 for (i = header_len; i > 0; i -= 2) {
1184 shebang_alias[i - 1] = start[i - 2];
1185 shebang_alias[i - 2] = start[i - 1];
1186 }
1187 nchars = header_len / sizeof(wchar_t);
1188 }
1189 break;
1190 case CP_UTF16LE:
1191 if ((header_len % 2) != 0) {
1192 debug(L"UTF-16LE, but an odd number of bytes: %d\n",
1193 header_len);
1194 /* nchars = 0; Not needed - initialised to 0. */
1195 }
1196 else {
1197 /* no actual conversion needed. */
1198 memcpy(shebang_line, start, header_len);
1199 nchars = header_len / sizeof(wchar_t);
1200 }
1201 break;
1202 case CP_UTF32BE:
1203 if (header_len % 4 != 0) {
1204 debug(L"UTF-32BE, but not divisible by 4: %d\n",
1205 header_len);
1206 /* nchars = 0; Not needed - initialised to 0. */
1207 }
1208 else {
1209 for (i = header_len, j = header_len / 2; i > 0; i -= 4,
1210 j -= 2) {
1211 shebang_alias[j - 1] = start[i - 2];
1212 shebang_alias[j - 2] = start[i - 1];
1213 }
1214 nchars = header_len / sizeof(wchar_t);
1215 }
1216 break;
1217 case CP_UTF32LE:
1218 if (header_len % 4 != 0) {
1219 debug(L"UTF-32LE, but not divisible by 4: %d\n",
1220 header_len);
1221 /* nchars = 0; Not needed - initialised to 0. */
1222 }
1223 else {
1224 for (i = header_len, j = header_len / 2; i > 0; i -= 4,
1225 j -= 2) {
1226 shebang_alias[j - 1] = start[i - 3];
1227 shebang_alias[j - 2] = start[i - 4];
1228 }
1229 nchars = header_len / sizeof(wchar_t);
1230 }
1231 break;
1232 }
1233 if (nchars > 0) {
1234 shebang_line[--nchars] = L'\0';
1235 is_virt = parse_shebang(shebang_line, nchars, &command,
Vinay Sajip22c039b2013-06-07 15:37:28 +01001236 &suffix, &search);
Brian Curtin07165f72012-06-20 15:36:14 -05001237 if (command != NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001238 debug(L"parse_shebang: found command: %ls\n", command);
Brian Curtin07165f72012-06-20 15:36:14 -05001239 if (!is_virt) {
1240 invoke_child(command, suffix, cmdline);
1241 }
1242 else {
1243 suffix = wcschr(command, L' ');
1244 if (suffix != NULL) {
1245 *suffix++ = L'\0';
1246 suffix = skip_whitespace(suffix);
1247 }
1248 if (wcsncmp(command, L"python", 6))
1249 error(RC_BAD_VIRTUAL_PATH, L"Unknown virtual \
Steve Dower84bcfb32015-01-02 18:07:46 -08001250path '%ls'", command);
Brian Curtin07165f72012-06-20 15:36:14 -05001251 command += 6; /* skip past "python" */
Vinay Sajip22c039b2013-06-07 15:37:28 +01001252 if (search && ((*command == L'\0') || isspace(*command))) {
1253 /* Command is eligible for path search, and there
1254 * is no version specification.
1255 */
1256 debug(L"searching PATH for python executable\n");
1257 cmd = find_on_path(L"python");
Steve Dower84bcfb32015-01-02 18:07:46 -08001258 debug(L"Python on path: %ls\n", cmd ? cmd->value : L"<not found>");
Vinay Sajip22c039b2013-06-07 15:37:28 +01001259 if (cmd) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001260 debug(L"located python on PATH: %ls\n", cmd->value);
Vinay Sajip22c039b2013-06-07 15:37:28 +01001261 invoke_child(cmd->value, suffix, cmdline);
1262 /* Exit here, as we have found the command */
1263 return;
1264 }
1265 /* FALL THROUGH: No python found on PATH, so fall
1266 * back to locating the correct installed python.
1267 */
1268 }
Brian Curtin07165f72012-06-20 15:36:14 -05001269 if (*command && !validate_version(command))
1270 error(RC_BAD_VIRTUAL_PATH, L"Invalid version \
Steve Dower84bcfb32015-01-02 18:07:46 -08001271specification: '%ls'.\nIn the first line of the script, 'python' needs to be \
Brian Curtin07165f72012-06-20 15:36:14 -05001272followed by a valid version specifier.\nPlease check the documentation.",
1273 command);
1274 /* TODO could call validate_version(command) */
1275 ip = locate_python(command);
1276 if (ip == NULL) {
1277 error(RC_NO_PYTHON, L"Requested Python version \
Steve Dower84bcfb32015-01-02 18:07:46 -08001278(%ls) is not installed", command);
Brian Curtin07165f72012-06-20 15:36:14 -05001279 }
1280 else {
1281 invoke_child(ip->executable, suffix, cmdline);
1282 }
1283 }
1284 }
1285 }
1286 }
1287 }
1288}
1289
1290static wchar_t *
1291skip_me(wchar_t * cmdline)
1292{
1293 BOOL quoted;
1294 wchar_t c;
1295 wchar_t * result = cmdline;
1296
1297 quoted = cmdline[0] == L'\"';
1298 if (!quoted)
1299 c = L' ';
1300 else {
1301 c = L'\"';
1302 ++result;
1303 }
1304 result = wcschr(result, c);
1305 if (result == NULL) /* when, for example, just exe name on command line */
1306 result = L"";
1307 else {
1308 ++result; /* skip past space or closing quote */
1309 result = skip_whitespace(result);
1310 }
1311 return result;
1312}
1313
1314static DWORD version_high = 0;
1315static DWORD version_low = 0;
1316
1317static void
1318get_version_info(wchar_t * version_text, size_t size)
1319{
1320 WORD maj, min, rel, bld;
1321
1322 if (!version_high && !version_low)
1323 wcsncpy_s(version_text, size, L"0.1", _TRUNCATE); /* fallback */
1324 else {
1325 maj = HIWORD(version_high);
1326 min = LOWORD(version_high);
1327 rel = HIWORD(version_low);
1328 bld = LOWORD(version_low);
1329 _snwprintf_s(version_text, size, _TRUNCATE, L"%d.%d.%d.%d", maj,
1330 min, rel, bld);
1331 }
1332}
1333
1334static int
1335process(int argc, wchar_t ** argv)
1336{
1337 wchar_t * wp;
1338 wchar_t * command;
Steve Dower76998fe2015-02-26 14:25:33 -08001339 wchar_t * executable;
Brian Curtin07165f72012-06-20 15:36:14 -05001340 wchar_t * p;
1341 int rc = 0;
1342 size_t plen;
1343 INSTALLED_PYTHON * ip;
1344 BOOL valid;
1345 DWORD size, attrs;
1346 HRESULT hr;
1347 wchar_t message[MSGSIZE];
1348 wchar_t version_text [MAX_PATH];
1349 void * version_data;
1350 VS_FIXEDFILEINFO * file_info;
1351 UINT block_size;
Vinay Sajip2ae8c632013-01-29 22:29:25 +00001352 int index;
Vinay Sajipc985d082013-07-25 11:20:55 +01001353#if defined(SCRIPT_WRAPPER)
1354 int newlen;
1355 wchar_t * newcommand;
1356 wchar_t * av[2];
1357#endif
Brian Curtin07165f72012-06-20 15:36:14 -05001358
1359 wp = get_env(L"PYLAUNCH_DEBUG");
1360 if ((wp != NULL) && (*wp != L'\0'))
1361 log_fp = stderr;
1362
1363#if defined(_M_X64)
1364 debug(L"launcher build: 64bit\n");
1365#else
1366 debug(L"launcher build: 32bit\n");
1367#endif
1368#if defined(_WINDOWS)
1369 debug(L"launcher executable: Windows\n");
1370#else
1371 debug(L"launcher executable: Console\n");
1372#endif
1373 /* Get the local appdata folder (non-roaming) */
1374 hr = SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA,
1375 NULL, 0, appdata_ini_path);
1376 if (hr != S_OK) {
1377 debug(L"SHGetFolderPath failed: %X\n", hr);
1378 appdata_ini_path[0] = L'\0';
1379 }
1380 else {
1381 plen = wcslen(appdata_ini_path);
1382 p = &appdata_ini_path[plen];
1383 wcsncpy_s(p, MAX_PATH - plen, L"\\py.ini", _TRUNCATE);
1384 attrs = GetFileAttributesW(appdata_ini_path);
1385 if (attrs == INVALID_FILE_ATTRIBUTES) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001386 debug(L"File '%ls' non-existent\n", appdata_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001387 appdata_ini_path[0] = L'\0';
1388 } else {
Steve Dower84bcfb32015-01-02 18:07:46 -08001389 debug(L"Using local configuration file '%ls'\n", appdata_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001390 }
1391 }
1392 plen = GetModuleFileNameW(NULL, launcher_ini_path, MAX_PATH);
1393 size = GetFileVersionInfoSizeW(launcher_ini_path, &size);
1394 if (size == 0) {
1395 winerror(GetLastError(), message, MSGSIZE);
Steve Dower84bcfb32015-01-02 18:07:46 -08001396 debug(L"GetFileVersionInfoSize failed: %ls\n", message);
Brian Curtin07165f72012-06-20 15:36:14 -05001397 }
1398 else {
1399 version_data = malloc(size);
1400 if (version_data) {
1401 valid = GetFileVersionInfoW(launcher_ini_path, 0, size,
1402 version_data);
1403 if (!valid)
1404 debug(L"GetFileVersionInfo failed: %X\n", GetLastError());
1405 else {
Vinay Sajip404229b2013-01-29 22:52:57 +00001406 valid = VerQueryValueW(version_data, L"\\",
1407 (LPVOID *) &file_info, &block_size);
Brian Curtin07165f72012-06-20 15:36:14 -05001408 if (!valid)
1409 debug(L"VerQueryValue failed: %X\n", GetLastError());
1410 else {
1411 version_high = file_info->dwFileVersionMS;
1412 version_low = file_info->dwFileVersionLS;
1413 }
1414 }
1415 free(version_data);
1416 }
1417 }
1418 p = wcsrchr(launcher_ini_path, L'\\');
1419 if (p == NULL) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001420 debug(L"GetModuleFileNameW returned value has no backslash: %ls\n",
Brian Curtin07165f72012-06-20 15:36:14 -05001421 launcher_ini_path);
1422 launcher_ini_path[0] = L'\0';
1423 }
1424 else {
1425 wcsncpy_s(p, MAX_PATH - (p - launcher_ini_path), L"\\py.ini",
1426 _TRUNCATE);
1427 attrs = GetFileAttributesW(launcher_ini_path);
1428 if (attrs == INVALID_FILE_ATTRIBUTES) {
Steve Dower84bcfb32015-01-02 18:07:46 -08001429 debug(L"File '%ls' non-existent\n", launcher_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001430 launcher_ini_path[0] = L'\0';
1431 } else {
Steve Dower84bcfb32015-01-02 18:07:46 -08001432 debug(L"Using global configuration file '%ls'\n", launcher_ini_path);
Brian Curtin07165f72012-06-20 15:36:14 -05001433 }
1434 }
1435
1436 command = skip_me(GetCommandLineW());
Steve Dower84bcfb32015-01-02 18:07:46 -08001437 debug(L"Called with command line: %ls\n", command);
Vinay Sajipc985d082013-07-25 11:20:55 +01001438
1439#if defined(SCRIPT_WRAPPER)
1440 /* The launcher is being used in "script wrapper" mode.
1441 * There should therefore be a Python script named <exename>-script.py in
1442 * the same directory as the launcher executable.
1443 * Put the script name into argv as the first (script name) argument.
1444 */
1445
1446 /* Get the wrapped script name - if the script is not present, this will
1447 * terminate the program with an error.
1448 */
1449 locate_wrapped_script();
1450
1451 /* Add the wrapped script to the start of command */
1452 newlen = wcslen(wrapped_script_path) + wcslen(command) + 2; /* ' ' + NUL */
1453 newcommand = malloc(sizeof(wchar_t) * newlen);
1454 if (!newcommand) {
1455 error(RC_NO_MEMORY, L"Could not allocate new command line");
1456 }
1457 else {
1458 wcscpy_s(newcommand, newlen, wrapped_script_path);
1459 wcscat_s(newcommand, newlen, L" ");
1460 wcscat_s(newcommand, newlen, command);
Steve Dower84bcfb32015-01-02 18:07:46 -08001461 debug(L"Running wrapped script with command line '%ls'\n", newcommand);
Vinay Sajipc985d082013-07-25 11:20:55 +01001462 read_commands();
1463 av[0] = wrapped_script_path;
1464 av[1] = NULL;
1465 maybe_handle_shebang(av, newcommand);
1466 /* Returns if no shebang line - pass to default processing */
1467 command = newcommand;
1468 valid = FALSE;
1469 }
1470#else
Brian Curtin07165f72012-06-20 15:36:14 -05001471 if (argc <= 1) {
1472 valid = FALSE;
1473 p = NULL;
1474 }
1475 else {
1476 p = argv[1];
1477 plen = wcslen(p);
Brian Curtin07165f72012-06-20 15:36:14 -05001478 valid = (*p == L'-') && validate_version(&p[1]);
1479 if (valid) {
1480 ip = locate_python(&p[1]);
1481 if (ip == NULL)
Steve Dower84bcfb32015-01-02 18:07:46 -08001482 error(RC_NO_PYTHON, L"Requested Python version (%ls) not \
Brian Curtin07165f72012-06-20 15:36:14 -05001483installed", &p[1]);
Steve Dower76998fe2015-02-26 14:25:33 -08001484 executable = ip->executable;
Brian Curtin07165f72012-06-20 15:36:14 -05001485 command += wcslen(p);
1486 command = skip_whitespace(command);
1487 }
Vinay Sajip2ae8c632013-01-29 22:29:25 +00001488 else {
1489 for (index = 1; index < argc; ++index) {
1490 if (*argv[index] != L'-')
1491 break;
1492 }
1493 if (index < argc) {
1494 read_commands();
1495 maybe_handle_shebang(&argv[index], command);
1496 }
1497 }
Brian Curtin07165f72012-06-20 15:36:14 -05001498 }
Vinay Sajipc985d082013-07-25 11:20:55 +01001499#endif
1500
Brian Curtin07165f72012-06-20 15:36:14 -05001501 if (!valid) {
Steve Dower76998fe2015-02-26 14:25:33 -08001502 /* Look for an active virtualenv */
1503 executable = find_python_by_venv();
1504
1505 /* If we didn't find one, look for the default Python */
1506 if (executable == NULL) {
1507 ip = locate_python(L"");
1508 if (ip == NULL)
1509 error(RC_NO_PYTHON, L"Can't find a default Python.");
1510 executable = ip->executable;
1511 }
Brian Curtin07165f72012-06-20 15:36:14 -05001512 if ((argc == 2) && (!_wcsicmp(p, L"-h") || !_wcsicmp(p, L"--help"))) {
1513#if defined(_M_X64)
1514 BOOL canDo64bit = TRUE;
1515#else
1516 // If we are a 32bit process on a 64bit Windows, first hit the 64bit keys.
1517 BOOL canDo64bit = FALSE;
1518 IsWow64Process(GetCurrentProcess(), &canDo64bit);
1519#endif
1520
1521 get_version_info(version_text, MAX_PATH);
1522 fwprintf(stdout, L"\
Steve Dower84bcfb32015-01-02 18:07:46 -08001523Python Launcher for Windows Version %ls\n\n", version_text);
Brian Curtin07165f72012-06-20 15:36:14 -05001524 fwprintf(stdout, L"\
Steve Dower84bcfb32015-01-02 18:07:46 -08001525usage: %ls [ launcher-arguments ] [ python-arguments ] script [ script-arguments ]\n\n", argv[0]);
Brian Curtin07165f72012-06-20 15:36:14 -05001526 fputws(L"\
1527Launcher arguments:\n\n\
1528-2 : Launch the latest Python 2.x version\n\
1529-3 : Launch the latest Python 3.x version\n\
1530-X.Y : Launch the specified Python version\n", stdout);
1531 if (canDo64bit) {
1532 fputws(L"\
1533-X.Y-32: Launch the specified 32bit Python version", stdout);
1534 }
1535 fputws(L"\n\nThe following help text is from Python:\n\n", stdout);
1536 fflush(stdout);
1537 }
1538 }
Steve Dower76998fe2015-02-26 14:25:33 -08001539 invoke_child(executable, NULL, command);
Brian Curtin07165f72012-06-20 15:36:14 -05001540 return rc;
1541}
1542
1543#if defined(_WINDOWS)
1544
1545int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
1546 LPWSTR lpstrCmd, int nShow)
1547{
1548 return process(__argc, __wargv);
1549}
1550
1551#else
1552
1553int cdecl wmain(int argc, wchar_t ** argv)
1554{
1555 return process(argc, argv);
1556}
1557
Vinay Sajip2ae8c632013-01-29 22:29:25 +00001558#endif