blob: 22d2974d875d2422aad91e9c85f27806cb7da828 [file] [log] [blame]
Brian Curtin07165f72012-06-20 15:36:14 -05001/*
2 * Copyright (C) 2011-2012 Vinay Sajip. All rights reserved.
3 *
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
15 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
18 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
19 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
20 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
22 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
23 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
24 * POSSIBILITY OF SUCH DAMAGE.
25 *
26 * Based on the work of:
27 *
28 * Mark Hammond (original author of Python version)
29 * Curt Hagenlocher (job management)
30 */
31
32#include <windows.h>
33#include <shlobj.h>
34#include <stdio.h>
35#include <tchar.h>
36
37#define BUFSIZE 256
38#define MSGSIZE 1024
39
40/* Build options. */
41#define SKIP_PREFIX
42/* #define SEARCH_PATH */
43
44/* 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
56/*
57 * This function is here to minimise Visual Studio
58 * warnings about security implications of getenv, and to
59 * treat blank values as if they are absent.
60 */
61static wchar_t * get_env(wchar_t * key)
62{
63 wchar_t * result = _wgetenv(key);
64
65 if (result) {
66 result = skip_whitespace(result);
67 if (*result == L'\0')
68 result = NULL;
69 }
70 return result;
71}
72
73static void
74debug(wchar_t * format, ...)
75{
76 va_list va;
77
78 if (log_fp != NULL) {
79 va_start(va, format);
80 vfwprintf_s(log_fp, format, va);
81 }
82}
83
84static void
85winerror(int rc, wchar_t * message, int size)
86{
87 FormatMessageW(
88 FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
89 NULL, rc, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
90 message, size, NULL);
91}
92
93static void
94error(int rc, wchar_t * format, ... )
95{
96 va_list va;
97 wchar_t message[MSGSIZE];
98 wchar_t win_message[MSGSIZE];
99 int len;
100
101 va_start(va, format);
102 len = _vsnwprintf_s(message, MSGSIZE, _TRUNCATE, format, va);
103
104 if (rc == 0) { /* a Windows error */
105 winerror(GetLastError(), win_message, MSGSIZE);
106 if (len >= 0) {
107 _snwprintf_s(&message[len], MSGSIZE - len, _TRUNCATE, L": %s",
108 win_message);
109 }
110 }
111
112#if !defined(_WINDOWS)
113 fwprintf(stderr, L"%s\n", message);
114#else
115 MessageBox(NULL, message, TEXT("Python Launcher is sorry to say ..."), MB_OK);
116#endif
117 ExitProcess(rc);
118}
119
120#if defined(_WINDOWS)
121
122#define PYTHON_EXECUTABLE L"pythonw.exe"
123
124#else
125
126#define PYTHON_EXECUTABLE L"python.exe"
127
128#endif
129
130#define RC_NO_STD_HANDLES 100
131#define RC_CREATE_PROCESS 101
132#define RC_BAD_VIRTUAL_PATH 102
133#define RC_NO_PYTHON 103
134
135#define MAX_VERSION_SIZE 4
136
137typedef struct {
138 wchar_t version[MAX_VERSION_SIZE]; /* m.n */
139 int bits; /* 32 or 64 */
140 wchar_t executable[MAX_PATH];
141} INSTALLED_PYTHON;
142
143/*
144 * To avoid messing about with heap allocations, just assume we can allocate
145 * statically and never have to deal with more versions than this.
146 */
147#define MAX_INSTALLED_PYTHONS 100
148
149static INSTALLED_PYTHON installed_pythons[MAX_INSTALLED_PYTHONS];
150
151static size_t num_installed_pythons = 0;
152
153/* to hold SOFTWARE\Python\PythonCore\X.Y\InstallPath */
154#define IP_BASE_SIZE 40
155#define IP_SIZE (IP_BASE_SIZE + MAX_VERSION_SIZE)
156#define CORE_PATH L"SOFTWARE\\Python\\PythonCore"
157
158static wchar_t * location_checks[] = {
159 L"\\",
160 L"\\PCBuild\\",
161 L"\\PCBuild\\amd64\\",
162 NULL
163};
164
165static INSTALLED_PYTHON *
166find_existing_python(wchar_t * path)
167{
168 INSTALLED_PYTHON * result = NULL;
169 size_t i;
170 INSTALLED_PYTHON * ip;
171
172 for (i = 0, ip = installed_pythons; i < num_installed_pythons; i++, ip++) {
173 if (_wcsicmp(path, ip->executable) == 0) {
174 result = ip;
175 break;
176 }
177 }
178 return result;
179}
180
181static void
182locate_pythons_for_key(HKEY root, REGSAM flags)
183{
184 HKEY core_root, ip_key;
185 LSTATUS status = RegOpenKeyExW(root, CORE_PATH, 0, flags, &core_root);
186 wchar_t message[MSGSIZE];
187 DWORD i;
188 size_t n;
189 BOOL ok;
190 DWORD type, data_size, attrs;
191 INSTALLED_PYTHON * ip, * pip;
192 wchar_t ip_path[IP_SIZE];
193 wchar_t * check;
194 wchar_t ** checkp;
195 wchar_t *key_name = (root == HKEY_LOCAL_MACHINE) ? L"HKLM" : L"HKCU";
196
197 if (status != ERROR_SUCCESS)
198 debug(L"locate_pythons_for_key: unable to open PythonCore key in %s\n",
199 key_name);
200 else {
201 ip = &installed_pythons[num_installed_pythons];
202 for (i = 0; num_installed_pythons < MAX_INSTALLED_PYTHONS; i++) {
203 status = RegEnumKeyW(core_root, i, ip->version, MAX_VERSION_SIZE);
204 if (status != ERROR_SUCCESS) {
205 if (status != ERROR_NO_MORE_ITEMS) {
206 /* unexpected error */
207 winerror(status, message, MSGSIZE);
208 debug(L"Can't enumerate registry key for version %s: %s\n",
209 ip->version, message);
210 }
211 break;
212 }
213 else {
214 _snwprintf_s(ip_path, IP_SIZE, _TRUNCATE,
215 L"%s\\%s\\InstallPath", CORE_PATH, ip->version);
216 status = RegOpenKeyExW(root, ip_path, 0, flags, &ip_key);
217 if (status != ERROR_SUCCESS) {
218 winerror(status, message, MSGSIZE);
219 // Note: 'message' already has a trailing \n
220 debug(L"%s\\%s: %s", key_name, ip_path, message);
221 continue;
222 }
223 data_size = sizeof(ip->executable) - 1;
224 status = RegQueryValueEx(ip_key, NULL, NULL, &type,
225 (LPBYTE) ip->executable, &data_size);
226 RegCloseKey(ip_key);
227 if (status != ERROR_SUCCESS) {
228 winerror(status, message, MSGSIZE);
229 debug(L"%s\\%s: %s\n", key_name, ip_path, message);
230 continue;
231 }
232 if (type == REG_SZ) {
233 data_size = data_size / sizeof(wchar_t) - 1; /* for NUL */
234 if (ip->executable[data_size - 1] == L'\\')
235 --data_size; /* reg value ended in a backslash */
236 /* ip->executable is data_size long */
237 for (checkp = location_checks; *checkp; ++checkp) {
238 check = *checkp;
239 _snwprintf_s(&ip->executable[data_size],
240 MAX_PATH - data_size,
241 MAX_PATH - data_size,
242 L"%s%s", check, PYTHON_EXECUTABLE);
243 attrs = GetFileAttributesW(ip->executable);
244 if (attrs == INVALID_FILE_ATTRIBUTES) {
245 winerror(GetLastError(), message, MSGSIZE);
246 debug(L"locate_pythons_for_key: %s: %s",
247 ip->executable, message);
248 }
249 else if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
250 debug(L"locate_pythons_for_key: '%s' is a \
251directory\n",
252 ip->executable, attrs);
253 }
254 else if (find_existing_python(ip->executable)) {
255 debug(L"locate_pythons_for_key: %s: already \
256found: %s\n", ip->executable);
257 }
258 else {
259 /* check the executable type. */
260 ok = GetBinaryTypeW(ip->executable, &attrs);
261 if (!ok) {
262 debug(L"Failure getting binary type: %s\n",
263 ip->executable);
264 }
265 else {
266 if (attrs == SCS_64BIT_BINARY)
267 ip->bits = 64;
268 else if (attrs == SCS_32BIT_BINARY)
269 ip->bits = 32;
270 else
271 ip->bits = 0;
272 if (ip->bits == 0) {
273 debug(L"locate_pythons_for_key: %s: \
274invalid binary type: %X\n",
275 ip->executable, attrs);
276 }
277 else {
278 if (wcschr(ip->executable, L' ') != NULL) {
279 /* has spaces, so quote */
280 n = wcslen(ip->executable);
281 memmove(&ip->executable[1],
282 ip->executable, n * sizeof(wchar_t));
283 ip->executable[0] = L'\"';
284 ip->executable[n + 1] = L'\"';
285 ip->executable[n + 2] = L'\0';
286 }
287 debug(L"locate_pythons_for_key: %s \
288is a %dbit executable\n",
289 ip->executable, ip->bits);
290 ++num_installed_pythons;
291 pip = ip++;
292 if (num_installed_pythons >=
293 MAX_INSTALLED_PYTHONS)
294 break;
295 /* Copy over the attributes for the next */
296 *ip = *pip;
297 }
298 }
299 }
300 }
301 }
302 }
303 }
304 RegCloseKey(core_root);
305 }
306}
307
308static int
309compare_pythons(const void * p1, const void * p2)
310{
311 INSTALLED_PYTHON * ip1 = (INSTALLED_PYTHON *) p1;
312 INSTALLED_PYTHON * ip2 = (INSTALLED_PYTHON *) p2;
313 /* note reverse sorting on version */
314 int result = wcscmp(ip2->version, ip1->version);
315
316 if (result == 0)
317 result = ip2->bits - ip1->bits; /* 64 before 32 */
318 return result;
319}
320
321static void
322locate_all_pythons()
323{
324#if defined(_M_X64)
325 // If we are a 64bit process, first hit the 32bit keys.
326 debug(L"locating Pythons in 32bit registry\n");
327 locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ | KEY_WOW64_32KEY);
328 locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ | KEY_WOW64_32KEY);
329#else
330 // If we are a 32bit process on a 64bit Windows, first hit the 64bit keys.
331 BOOL f64 = FALSE;
332 if (IsWow64Process(GetCurrentProcess(), &f64) && f64) {
333 debug(L"locating Pythons in 64bit registry\n");
334 locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ | KEY_WOW64_64KEY);
335 locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ | KEY_WOW64_64KEY);
336 }
337#endif
338 // now hit the "native" key for this process bittedness.
339 debug(L"locating Pythons in native registry\n");
340 locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ);
341 locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ);
342 qsort(installed_pythons, num_installed_pythons, sizeof(INSTALLED_PYTHON),
343 compare_pythons);
344}
345
346static INSTALLED_PYTHON *
347find_python_by_version(wchar_t const * wanted_ver)
348{
349 INSTALLED_PYTHON * result = NULL;
350 INSTALLED_PYTHON * ip = installed_pythons;
351 size_t i, n;
352 size_t wlen = wcslen(wanted_ver);
353 int bits = 0;
354
355 if (wcsstr(wanted_ver, L"-32"))
356 bits = 32;
357 for (i = 0; i < num_installed_pythons; i++, ip++) {
358 n = wcslen(ip->version);
359 if (n > wlen)
360 n = wlen;
361 if ((wcsncmp(ip->version, wanted_ver, n) == 0) &&
362 /* bits == 0 => don't care */
363 ((bits == 0) || (ip->bits == bits))) {
364 result = ip;
365 break;
366 }
367 }
368 return result;
369}
370
371
372static wchar_t appdata_ini_path[MAX_PATH];
373static wchar_t launcher_ini_path[MAX_PATH];
374
375/*
376 * Get a value either from the environment or a configuration file.
377 * The key passed in will either be "python", "python2" or "python3".
378 */
379static wchar_t *
380get_configured_value(wchar_t * key)
381{
382/*
383 * Note: this static value is used to return a configured value
384 * obtained either from the environment or configuration file.
385 * This should be OK since there wouldn't be any concurrent calls.
386 */
387 static wchar_t configured_value[MSGSIZE];
388 wchar_t * result = NULL;
389 wchar_t * found_in = L"environment";
390 DWORD size;
391
392 /* First, search the environment. */
393 _snwprintf_s(configured_value, MSGSIZE, _TRUNCATE, L"py_%s", key);
394 result = get_env(configured_value);
395 if (result == NULL && appdata_ini_path[0]) {
396 /* Not in environment: check local configuration. */
397 size = GetPrivateProfileStringW(L"defaults", key, NULL,
398 configured_value, MSGSIZE,
399 appdata_ini_path);
400 if (size > 0) {
401 result = configured_value;
402 found_in = appdata_ini_path;
403 }
404 }
405 if (result == NULL && launcher_ini_path[0]) {
406 /* Not in environment or local: check global configuration. */
407 size = GetPrivateProfileStringW(L"defaults", key, NULL,
408 configured_value, MSGSIZE,
409 launcher_ini_path);
410 if (size > 0) {
411 result = configured_value;
412 found_in = launcher_ini_path;
413 }
414 }
415 if (result) {
416 debug(L"found configured value '%s=%s' in %s\n",
417 key, result, found_in ? found_in : L"(unknown)");
418 } else {
419 debug(L"found no configured value for '%s'\n", key);
420 }
421 return result;
422}
423
424static INSTALLED_PYTHON *
425locate_python(wchar_t * wanted_ver)
426{
427 static wchar_t config_key [] = { L"pythonX" };
428 static wchar_t * last_char = &config_key[sizeof(config_key) /
429 sizeof(wchar_t) - 2];
430 INSTALLED_PYTHON * result = NULL;
431 size_t n = wcslen(wanted_ver);
432 wchar_t * configured_value;
433
434 if (num_installed_pythons == 0)
435 locate_all_pythons();
436
437 if (n == 1) { /* just major version specified */
438 *last_char = *wanted_ver;
439 configured_value = get_configured_value(config_key);
440 if (configured_value != NULL)
441 wanted_ver = configured_value;
442 }
443 if (*wanted_ver) {
444 result = find_python_by_version(wanted_ver);
445 debug(L"search for Python version '%s' found ", wanted_ver);
446 if (result) {
447 debug(L"'%s'\n", result->executable);
448 } else {
449 debug(L"no interpreter\n");
450 }
451 }
452 else {
453 *last_char = L'\0'; /* look for an overall default */
454 configured_value = get_configured_value(config_key);
455 if (configured_value)
456 result = find_python_by_version(configured_value);
457 if (result == NULL)
458 result = find_python_by_version(L"2");
459 if (result == NULL)
460 result = find_python_by_version(L"3");
461 debug(L"search for default Python found ");
462 if (result) {
463 debug(L"version %s at '%s'\n",
464 result->version, result->executable);
465 } else {
466 debug(L"no interpreter\n");
467 }
468 }
469 return result;
470}
471
472/*
473 * Process creation code
474 */
475
476static BOOL
477safe_duplicate_handle(HANDLE in, HANDLE * pout)
478{
479 BOOL ok;
480 HANDLE process = GetCurrentProcess();
481 DWORD rc;
482
483 *pout = NULL;
484 ok = DuplicateHandle(process, in, process, pout, 0, TRUE,
485 DUPLICATE_SAME_ACCESS);
486 if (!ok) {
487 rc = GetLastError();
488 if (rc == ERROR_INVALID_HANDLE) {
489 debug(L"DuplicateHandle returned ERROR_INVALID_HANDLE\n");
490 ok = TRUE;
491 }
492 else {
493 debug(L"DuplicateHandle returned %d\n", rc);
494 }
495 }
496 return ok;
497}
498
499static BOOL WINAPI
500ctrl_c_handler(DWORD code)
501{
502 return TRUE; /* We just ignore all control events. */
503}
504
505static void
506run_child(wchar_t * cmdline)
507{
508 HANDLE job;
509 JOBOBJECT_EXTENDED_LIMIT_INFORMATION info;
510 DWORD rc;
511 BOOL ok;
512 STARTUPINFOW si;
513 PROCESS_INFORMATION pi;
514
515 debug(L"run_child: about to run '%s'\n", cmdline);
516 job = CreateJobObject(NULL, NULL);
517 ok = QueryInformationJobObject(job, JobObjectExtendedLimitInformation,
518 &info, sizeof(info), &rc);
519 if (!ok || (rc != sizeof(info)) || !job)
520 error(RC_CREATE_PROCESS, L"Job information querying failed");
521 info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE |
522 JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK;
523 ok = SetInformationJobObject(job, JobObjectExtendedLimitInformation, &info,
524 sizeof(info));
525 if (!ok)
526 error(RC_CREATE_PROCESS, L"Job information setting failed");
527 memset(&si, 0, sizeof(si));
528 si.cb = sizeof(si);
529 ok = safe_duplicate_handle(GetStdHandle(STD_INPUT_HANDLE), &si.hStdInput);
530 if (!ok)
531 error(RC_NO_STD_HANDLES, L"stdin duplication failed");
532 ok = safe_duplicate_handle(GetStdHandle(STD_OUTPUT_HANDLE), &si.hStdOutput);
533 if (!ok)
534 error(RC_NO_STD_HANDLES, L"stdout duplication failed");
535 ok = safe_duplicate_handle(GetStdHandle(STD_ERROR_HANDLE), &si.hStdError);
536 if (!ok)
537 error(RC_NO_STD_HANDLES, L"stderr duplication failed");
538
539 ok = SetConsoleCtrlHandler(ctrl_c_handler, TRUE);
540 if (!ok)
541 error(RC_CREATE_PROCESS, L"control handler setting failed");
542
543 si.dwFlags = STARTF_USESTDHANDLES;
544 ok = CreateProcessW(NULL, cmdline, NULL, NULL, TRUE,
545 0, NULL, NULL, &si, &pi);
546 if (!ok)
547 error(RC_CREATE_PROCESS, L"Unable to create process using '%s'", cmdline);
548 AssignProcessToJobObject(job, pi.hProcess);
549 CloseHandle(pi.hThread);
550 WaitForSingleObject(pi.hProcess, INFINITE);
551 ok = GetExitCodeProcess(pi.hProcess, &rc);
552 if (!ok)
553 error(RC_CREATE_PROCESS, L"Failed to get exit code of process");
554 debug(L"child process exit code: %d\n", rc);
555 ExitProcess(rc);
556}
557
558static void
559invoke_child(wchar_t * executable, wchar_t * suffix, wchar_t * cmdline)
560{
561 wchar_t * child_command;
562 size_t child_command_size;
563 BOOL no_suffix = (suffix == NULL) || (*suffix == L'\0');
564 BOOL no_cmdline = (*cmdline == L'\0');
565
566 if (no_suffix && no_cmdline)
567 run_child(executable);
568 else {
569 if (no_suffix) {
570 /* add 2 for space separator + terminating NUL. */
571 child_command_size = wcslen(executable) + wcslen(cmdline) + 2;
572 }
573 else {
574 /* add 3 for 2 space separators + terminating NUL. */
575 child_command_size = wcslen(executable) + wcslen(suffix) +
576 wcslen(cmdline) + 3;
577 }
578 child_command = calloc(child_command_size, sizeof(wchar_t));
579 if (child_command == NULL)
580 error(RC_CREATE_PROCESS, L"unable to allocate %d bytes for child command.",
581 child_command_size);
582 if (no_suffix)
583 _snwprintf_s(child_command, child_command_size,
584 child_command_size - 1, L"%s %s",
585 executable, cmdline);
586 else
587 _snwprintf_s(child_command, child_command_size,
588 child_command_size - 1, L"%s %s %s",
589 executable, suffix, cmdline);
590 run_child(child_command);
591 free(child_command);
592 }
593}
594
595static wchar_t * builtin_virtual_paths [] = {
596 L"/usr/bin/env python",
597 L"/usr/bin/python",
598 L"/usr/local/bin/python",
599 L"python",
600 NULL
601};
602
603/* For now, a static array of commands. */
604
605#define MAX_COMMANDS 100
606
607typedef struct {
608 wchar_t key[MAX_PATH];
609 wchar_t value[MSGSIZE];
610} COMMAND;
611
612static COMMAND commands[MAX_COMMANDS];
613static int num_commands = 0;
614
615#if defined(SKIP_PREFIX)
616
617static wchar_t * builtin_prefixes [] = {
618 /* These must be in an order that the longest matches should be found,
619 * i.e. if the prefix is "/usr/bin/env ", it should match that entry
620 * *before* matching "/usr/bin/".
621 */
622 L"/usr/bin/env ",
623 L"/usr/bin/",
624 L"/usr/local/bin/",
625 NULL
626};
627
628static wchar_t * skip_prefix(wchar_t * name)
629{
630 wchar_t ** pp = builtin_prefixes;
631 wchar_t * result = name;
632 wchar_t * p;
633 size_t n;
634
635 for (; p = *pp; pp++) {
636 n = wcslen(p);
637 if (_wcsnicmp(p, name, n) == 0) {
638 result += n; /* skip the prefix */
639 if (p[n - 1] == L' ') /* No empty strings in table, so n > 1 */
640 result = skip_whitespace(result);
641 break;
642 }
643 }
644 return result;
645}
646
647#endif
648
649#if defined(SEARCH_PATH)
650
651static COMMAND path_command;
652
653static COMMAND * find_on_path(wchar_t * name)
654{
655 wchar_t * pathext;
656 size_t varsize;
657 wchar_t * context = NULL;
658 wchar_t * extension;
659 COMMAND * result = NULL;
660 DWORD len;
661 errno_t rc;
662
663 wcscpy_s(path_command.key, MAX_PATH, name);
664 if (wcschr(name, L'.') != NULL) {
665 /* assume it has an extension. */
666 len = SearchPathW(NULL, name, NULL, MSGSIZE, path_command.value, NULL);
667 if (len) {
668 result = &path_command;
669 }
670 }
671 else {
672 /* No extension - search using registered extensions. */
673 rc = _wdupenv_s(&pathext, &varsize, L"PATHEXT");
674 if (rc == 0) {
675 extension = wcstok_s(pathext, L";", &context);
676 while (extension) {
677 len = SearchPathW(NULL, name, extension, MSGSIZE, path_command.value, NULL);
678 if (len) {
679 result = &path_command;
680 break;
681 }
682 extension = wcstok_s(NULL, L";", &context);
683 }
684 free(pathext);
685 }
686 }
687 return result;
688}
689
690#endif
691
692static COMMAND * find_command(wchar_t * name)
693{
694 COMMAND * result = NULL;
695 COMMAND * cp = commands;
696 int i;
697
698 for (i = 0; i < num_commands; i++, cp++) {
699 if (_wcsicmp(cp->key, name) == 0) {
700 result = cp;
701 break;
702 }
703 }
704#if defined(SEARCH_PATH)
705 if (result == NULL)
706 result = find_on_path(name);
707#endif
708 return result;
709}
710
711static void
712update_command(COMMAND * cp, wchar_t * name, wchar_t * cmdline)
713{
714 wcsncpy_s(cp->key, MAX_PATH, name, _TRUNCATE);
715 wcsncpy_s(cp->value, MSGSIZE, cmdline, _TRUNCATE);
716}
717
718static void
719add_command(wchar_t * name, wchar_t * cmdline)
720{
721 if (num_commands >= MAX_COMMANDS) {
722 debug(L"can't add %s = '%s': no room\n", name, cmdline);
723 }
724 else {
725 COMMAND * cp = &commands[num_commands++];
726
727 update_command(cp, name, cmdline);
728 }
729}
730
731static void
732read_config_file(wchar_t * config_path)
733{
734 wchar_t keynames[MSGSIZE];
735 wchar_t value[MSGSIZE];
736 DWORD read;
737 wchar_t * key;
738 COMMAND * cp;
739 wchar_t * cmdp;
740
741 read = GetPrivateProfileStringW(L"commands", NULL, NULL, keynames, MSGSIZE,
742 config_path);
743 if (read == MSGSIZE - 1) {
744 debug(L"read_commands: %s: not enough space for names\n", config_path);
745 }
746 key = keynames;
747 while (*key) {
748 read = GetPrivateProfileStringW(L"commands", key, NULL, value, MSGSIZE,
749 config_path);
750 if (read == MSGSIZE - 1) {
751 debug(L"read_commands: %s: not enough space for %s\n",
752 config_path, key);
753 }
754 cmdp = skip_whitespace(value);
755 if (*cmdp) {
756 cp = find_command(key);
757 if (cp == NULL)
758 add_command(key, value);
759 else
760 update_command(cp, key, value);
761 }
762 key += wcslen(key) + 1;
763 }
764}
765
766static void read_commands()
767{
768 if (launcher_ini_path[0])
769 read_config_file(launcher_ini_path);
770 if (appdata_ini_path[0])
771 read_config_file(appdata_ini_path);
772}
773
774static BOOL
775parse_shebang(wchar_t * shebang_line, int nchars, wchar_t ** command,
776 wchar_t ** suffix)
777{
778 BOOL rc = FALSE;
779 wchar_t ** vpp;
780 size_t plen;
781 wchar_t * p;
782 wchar_t zapped;
783 wchar_t * endp = shebang_line + nchars - 1;
784 COMMAND * cp;
785 wchar_t * skipped;
786
787 *command = NULL; /* failure return */
788 *suffix = NULL;
789
790 if ((*shebang_line++ == L'#') && (*shebang_line++ == L'!')) {
791 shebang_line = skip_whitespace(shebang_line);
792 if (*shebang_line) {
793 *command = shebang_line;
794 for (vpp = builtin_virtual_paths; *vpp; ++vpp) {
795 plen = wcslen(*vpp);
796 if (wcsncmp(shebang_line, *vpp, plen) == 0) {
797 rc = TRUE;
798 /* We can do this because all builtin commands contain
799 * "python".
800 */
801 *command = wcsstr(shebang_line, L"python");
802 break;
803 }
804 }
805 if (*vpp == NULL) {
806 /*
807 * Not found in builtins - look in customised commands.
808 *
809 * We can't permanently modify the shebang line in case
810 * it's not a customised command, but we can temporarily
811 * stick a NUL after the command while searching for it,
812 * then put back the char we zapped.
813 */
814#if defined(SKIP_PREFIX)
815 skipped = skip_prefix(shebang_line);
816#else
817 skipped = shebang_line;
818#endif
819 p = wcspbrk(skipped, L" \t\r\n");
820 if (p != NULL) {
821 zapped = *p;
822 *p = L'\0';
823 }
824 cp = find_command(skipped);
825 if (p != NULL)
826 *p = zapped;
827 if (cp != NULL) {
828 *command = cp->value;
829 if (p != NULL)
830 *suffix = skip_whitespace(p);
831 }
832 }
833 /* remove trailing whitespace */
834 while ((endp > shebang_line) && isspace(*endp))
835 --endp;
836 if (endp > shebang_line)
837 endp[1] = L'\0';
838 }
839 }
840 return rc;
841}
842
843/* #define CP_UTF8 65001 defined in winnls.h */
844#define CP_UTF16LE 1200
845#define CP_UTF16BE 1201
846#define CP_UTF32LE 12000
847#define CP_UTF32BE 12001
848
849typedef struct {
850 int length;
851 char sequence[4];
852 UINT code_page;
853} BOM;
854
855/*
856 * Strictly, we don't need to handle UTF-16 anf UTF-32, since Python itself
857 * doesn't. Never mind, one day it might - there's no harm leaving it in.
858 */
859static BOM BOMs[] = {
860 { 3, { 0xEF, 0xBB, 0xBF }, CP_UTF8 }, /* UTF-8 - keep first */
861 { 2, { 0xFF, 0xFE }, CP_UTF16LE }, /* UTF-16LE */
862 { 2, { 0xFE, 0xFF }, CP_UTF16BE }, /* UTF-16BE */
863 { 4, { 0xFF, 0xFE, 0x00, 0x00 }, CP_UTF32LE }, /* UTF-32LE */
864 { 4, { 0x00, 0x00, 0xFE, 0xFF }, CP_UTF32BE }, /* UTF-32BE */
865 { 0 } /* sentinel */
866};
867
868static BOM *
869find_BOM(char * buffer)
870{
871/*
872 * Look for a BOM in the input and return a pointer to the
873 * corresponding structure, or NULL if not found.
874 */
875 BOM * result = NULL;
876 BOM *bom;
877
878 for (bom = BOMs; bom->length; bom++) {
879 if (strncmp(bom->sequence, buffer, bom->length) == 0) {
880 result = bom;
881 break;
882 }
883 }
884 return result;
885}
886
887static char *
888find_terminator(char * buffer, int len, BOM *bom)
889{
890 char * result = NULL;
891 char * end = buffer + len;
892 char * p;
893 char c;
894 int cp;
895
896 for (p = buffer; p < end; p++) {
897 c = *p;
898 if (c == '\r') {
899 result = p;
900 break;
901 }
902 if (c == '\n') {
903 result = p;
904 break;
905 }
906 }
907 if (result != NULL) {
908 cp = bom->code_page;
909
910 /* adjustments to include all bytes of the char */
911 /* no adjustment needed for UTF-8 or big endian */
912 if (cp == CP_UTF16LE)
913 ++result;
914 else if (cp == CP_UTF32LE)
915 result += 3;
916 ++result; /* point just past terminator */
917 }
918 return result;
919}
920
921static BOOL
922validate_version(wchar_t * p)
923{
924 BOOL result = TRUE;
925
926 if (!isdigit(*p)) /* expect major version */
927 result = FALSE;
928 else if (*++p) { /* more to do */
929 if (*p != L'.') /* major/minor separator */
930 result = FALSE;
931 else {
932 ++p;
933 if (!isdigit(*p)) /* expect minor version */
934 result = FALSE;
935 else {
936 ++p;
937 if (*p) { /* more to do */
938 if (*p != L'-')
939 result = FALSE;
940 else {
941 ++p;
942 if ((*p != '3') && (*++p != '2') && !*++p)
943 result = FALSE;
944 }
945 }
946 }
947 }
948 }
949 return result;
950}
951
952typedef struct {
953 unsigned short min;
954 unsigned short max;
955 wchar_t version[MAX_VERSION_SIZE];
956} PYC_MAGIC;
957
958static PYC_MAGIC magic_values[] = {
959 { 0xc687, 0xc687, L"2.0" },
960 { 0xeb2a, 0xeb2a, L"2.1" },
961 { 0xed2d, 0xed2d, L"2.2" },
962 { 0xf23b, 0xf245, L"2.3" },
963 { 0xf259, 0xf26d, L"2.4" },
964 { 0xf277, 0xf2b3, L"2.5" },
965 { 0xf2c7, 0xf2d1, L"2.6" },
966 { 0xf2db, 0xf303, L"2.7" },
967 { 0x0bb8, 0x0c3b, L"3.0" },
968 { 0x0c45, 0x0c4f, L"3.1" },
969 { 0x0c58, 0x0c6c, L"3.2" },
970 { 0x0c76, 0x0c76, L"3.3" },
971 { 0 }
972};
973
974static INSTALLED_PYTHON *
975find_by_magic(unsigned short magic)
976{
977 INSTALLED_PYTHON * result = NULL;
978 PYC_MAGIC * mp;
979
980 for (mp = magic_values; mp->min; mp++) {
981 if ((magic >= mp->min) && (magic <= mp->max)) {
982 result = locate_python(mp->version);
983 if (result != NULL)
984 break;
985 }
986 }
987 return result;
988}
989
990static void
991maybe_handle_shebang(wchar_t ** argv, wchar_t * cmdline)
992{
993/*
994 * Look for a shebang line in the first argument. If found
995 * and we spawn a child process, this never returns. If it
996 * does return then we process the args "normally".
997 *
998 * argv[0] might be a filename with a shebang.
999 */
1000 FILE * fp;
1001 errno_t rc = _wfopen_s(&fp, *argv, L"rb");
1002 unsigned char buffer[BUFSIZE];
1003 wchar_t shebang_line[BUFSIZE + 1];
1004 size_t read;
1005 char *p;
1006 char * start;
1007 char * shebang_alias = (char *) shebang_line;
1008 BOM* bom;
1009 int i, j, nchars = 0;
1010 int header_len;
1011 BOOL is_virt;
1012 wchar_t * command;
1013 wchar_t * suffix;
1014 INSTALLED_PYTHON * ip;
1015
1016 if (rc == 0) {
1017 read = fread(buffer, sizeof(char), BUFSIZE, fp);
1018 debug(L"maybe_handle_shebang: read %d bytes\n", read);
1019 fclose(fp);
1020
1021 if ((read >= 4) && (buffer[3] == '\n') && (buffer[2] == '\r')) {
1022 ip = find_by_magic((buffer[1] << 8 | buffer[0]) & 0xFFFF);
1023 if (ip != NULL) {
1024 debug(L"script file is compiled against Python %s\n",
1025 ip->version);
1026 invoke_child(ip->executable, NULL, cmdline);
1027 }
1028 }
1029 /* Look for BOM */
1030 bom = find_BOM(buffer);
1031 if (bom == NULL) {
1032 start = buffer;
1033 debug(L"maybe_handle_shebang: BOM not found, using UTF-8\n");
1034 bom = BOMs; /* points to UTF-8 entry - the default */
1035 }
1036 else {
1037 debug(L"maybe_handle_shebang: BOM found, code page %d\n",
1038 bom->code_page);
1039 start = &buffer[bom->length];
1040 }
1041 p = find_terminator(start, BUFSIZE, bom);
1042 /*
1043 * If no CR or LF was found in the heading,
1044 * we assume it's not a shebang file.
1045 */
1046 if (p == NULL) {
1047 debug(L"maybe_handle_shebang: No line terminator found\n");
1048 }
1049 else {
1050 /*
1051 * Found line terminator - parse the shebang.
1052 *
1053 * Strictly, we don't need to handle UTF-16 anf UTF-32,
1054 * since Python itself doesn't.
1055 * Never mind, one day it might.
1056 */
1057 header_len = (int) (p - start);
1058 switch(bom->code_page) {
1059 case CP_UTF8:
1060 nchars = MultiByteToWideChar(bom->code_page,
1061 0,
1062 start, header_len, shebang_line,
1063 BUFSIZE);
1064 break;
1065 case CP_UTF16BE:
1066 if (header_len % 2 != 0) {
1067 debug(L"maybe_handle_shebang: UTF-16BE, but an odd number \
1068of bytes: %d\n", header_len);
1069 /* nchars = 0; Not needed - initialised to 0. */
1070 }
1071 else {
1072 for (i = header_len; i > 0; i -= 2) {
1073 shebang_alias[i - 1] = start[i - 2];
1074 shebang_alias[i - 2] = start[i - 1];
1075 }
1076 nchars = header_len / sizeof(wchar_t);
1077 }
1078 break;
1079 case CP_UTF16LE:
1080 if ((header_len % 2) != 0) {
1081 debug(L"UTF-16LE, but an odd number of bytes: %d\n",
1082 header_len);
1083 /* nchars = 0; Not needed - initialised to 0. */
1084 }
1085 else {
1086 /* no actual conversion needed. */
1087 memcpy(shebang_line, start, header_len);
1088 nchars = header_len / sizeof(wchar_t);
1089 }
1090 break;
1091 case CP_UTF32BE:
1092 if (header_len % 4 != 0) {
1093 debug(L"UTF-32BE, but not divisible by 4: %d\n",
1094 header_len);
1095 /* nchars = 0; Not needed - initialised to 0. */
1096 }
1097 else {
1098 for (i = header_len, j = header_len / 2; i > 0; i -= 4,
1099 j -= 2) {
1100 shebang_alias[j - 1] = start[i - 2];
1101 shebang_alias[j - 2] = start[i - 1];
1102 }
1103 nchars = header_len / sizeof(wchar_t);
1104 }
1105 break;
1106 case CP_UTF32LE:
1107 if (header_len % 4 != 0) {
1108 debug(L"UTF-32LE, but not divisible by 4: %d\n",
1109 header_len);
1110 /* nchars = 0; Not needed - initialised to 0. */
1111 }
1112 else {
1113 for (i = header_len, j = header_len / 2; i > 0; i -= 4,
1114 j -= 2) {
1115 shebang_alias[j - 1] = start[i - 3];
1116 shebang_alias[j - 2] = start[i - 4];
1117 }
1118 nchars = header_len / sizeof(wchar_t);
1119 }
1120 break;
1121 }
1122 if (nchars > 0) {
1123 shebang_line[--nchars] = L'\0';
1124 is_virt = parse_shebang(shebang_line, nchars, &command,
1125 &suffix);
1126 if (command != NULL) {
1127 debug(L"parse_shebang: found command: %s\n", command);
1128 if (!is_virt) {
1129 invoke_child(command, suffix, cmdline);
1130 }
1131 else {
1132 suffix = wcschr(command, L' ');
1133 if (suffix != NULL) {
1134 *suffix++ = L'\0';
1135 suffix = skip_whitespace(suffix);
1136 }
1137 if (wcsncmp(command, L"python", 6))
1138 error(RC_BAD_VIRTUAL_PATH, L"Unknown virtual \
1139path '%s'", command);
1140 command += 6; /* skip past "python" */
1141 if (*command && !validate_version(command))
1142 error(RC_BAD_VIRTUAL_PATH, L"Invalid version \
1143specification: '%s'.\nIn the first line of the script, 'python' needs to be \
1144followed by a valid version specifier.\nPlease check the documentation.",
1145 command);
1146 /* TODO could call validate_version(command) */
1147 ip = locate_python(command);
1148 if (ip == NULL) {
1149 error(RC_NO_PYTHON, L"Requested Python version \
1150(%s) is not installed", command);
1151 }
1152 else {
1153 invoke_child(ip->executable, suffix, cmdline);
1154 }
1155 }
1156 }
1157 }
1158 }
1159 }
1160}
1161
1162static wchar_t *
1163skip_me(wchar_t * cmdline)
1164{
1165 BOOL quoted;
1166 wchar_t c;
1167 wchar_t * result = cmdline;
1168
1169 quoted = cmdline[0] == L'\"';
1170 if (!quoted)
1171 c = L' ';
1172 else {
1173 c = L'\"';
1174 ++result;
1175 }
1176 result = wcschr(result, c);
1177 if (result == NULL) /* when, for example, just exe name on command line */
1178 result = L"";
1179 else {
1180 ++result; /* skip past space or closing quote */
1181 result = skip_whitespace(result);
1182 }
1183 return result;
1184}
1185
1186static DWORD version_high = 0;
1187static DWORD version_low = 0;
1188
1189static void
1190get_version_info(wchar_t * version_text, size_t size)
1191{
1192 WORD maj, min, rel, bld;
1193
1194 if (!version_high && !version_low)
1195 wcsncpy_s(version_text, size, L"0.1", _TRUNCATE); /* fallback */
1196 else {
1197 maj = HIWORD(version_high);
1198 min = LOWORD(version_high);
1199 rel = HIWORD(version_low);
1200 bld = LOWORD(version_low);
1201 _snwprintf_s(version_text, size, _TRUNCATE, L"%d.%d.%d.%d", maj,
1202 min, rel, bld);
1203 }
1204}
1205
1206static int
1207process(int argc, wchar_t ** argv)
1208{
1209 wchar_t * wp;
1210 wchar_t * command;
1211 wchar_t * p;
1212 int rc = 0;
1213 size_t plen;
1214 INSTALLED_PYTHON * ip;
1215 BOOL valid;
1216 DWORD size, attrs;
1217 HRESULT hr;
1218 wchar_t message[MSGSIZE];
1219 wchar_t version_text [MAX_PATH];
1220 void * version_data;
1221 VS_FIXEDFILEINFO * file_info;
1222 UINT block_size;
1223
1224 wp = get_env(L"PYLAUNCH_DEBUG");
1225 if ((wp != NULL) && (*wp != L'\0'))
1226 log_fp = stderr;
1227
1228#if defined(_M_X64)
1229 debug(L"launcher build: 64bit\n");
1230#else
1231 debug(L"launcher build: 32bit\n");
1232#endif
1233#if defined(_WINDOWS)
1234 debug(L"launcher executable: Windows\n");
1235#else
1236 debug(L"launcher executable: Console\n");
1237#endif
1238 /* Get the local appdata folder (non-roaming) */
1239 hr = SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA,
1240 NULL, 0, appdata_ini_path);
1241 if (hr != S_OK) {
1242 debug(L"SHGetFolderPath failed: %X\n", hr);
1243 appdata_ini_path[0] = L'\0';
1244 }
1245 else {
1246 plen = wcslen(appdata_ini_path);
1247 p = &appdata_ini_path[plen];
1248 wcsncpy_s(p, MAX_PATH - plen, L"\\py.ini", _TRUNCATE);
1249 attrs = GetFileAttributesW(appdata_ini_path);
1250 if (attrs == INVALID_FILE_ATTRIBUTES) {
1251 debug(L"File '%s' non-existent\n", appdata_ini_path);
1252 appdata_ini_path[0] = L'\0';
1253 } else {
1254 debug(L"Using local configuration file '%s'\n", appdata_ini_path);
1255 }
1256 }
1257 plen = GetModuleFileNameW(NULL, launcher_ini_path, MAX_PATH);
1258 size = GetFileVersionInfoSizeW(launcher_ini_path, &size);
1259 if (size == 0) {
1260 winerror(GetLastError(), message, MSGSIZE);
1261 debug(L"GetFileVersionInfoSize failed: %s\n", message);
1262 }
1263 else {
1264 version_data = malloc(size);
1265 if (version_data) {
1266 valid = GetFileVersionInfoW(launcher_ini_path, 0, size,
1267 version_data);
1268 if (!valid)
1269 debug(L"GetFileVersionInfo failed: %X\n", GetLastError());
1270 else {
1271 valid = VerQueryValueW(version_data, L"\\", &file_info,
1272 &block_size);
1273 if (!valid)
1274 debug(L"VerQueryValue failed: %X\n", GetLastError());
1275 else {
1276 version_high = file_info->dwFileVersionMS;
1277 version_low = file_info->dwFileVersionLS;
1278 }
1279 }
1280 free(version_data);
1281 }
1282 }
1283 p = wcsrchr(launcher_ini_path, L'\\');
1284 if (p == NULL) {
1285 debug(L"GetModuleFileNameW returned value has no backslash: %s\n",
1286 launcher_ini_path);
1287 launcher_ini_path[0] = L'\0';
1288 }
1289 else {
1290 wcsncpy_s(p, MAX_PATH - (p - launcher_ini_path), L"\\py.ini",
1291 _TRUNCATE);
1292 attrs = GetFileAttributesW(launcher_ini_path);
1293 if (attrs == INVALID_FILE_ATTRIBUTES) {
1294 debug(L"File '%s' non-existent\n", launcher_ini_path);
1295 launcher_ini_path[0] = L'\0';
1296 } else {
1297 debug(L"Using global configuration file '%s'\n", launcher_ini_path);
1298 }
1299 }
1300
1301 command = skip_me(GetCommandLineW());
1302 debug(L"Called with command line: %s", command);
1303 if (argc <= 1) {
1304 valid = FALSE;
1305 p = NULL;
1306 }
1307 else {
1308 p = argv[1];
1309 plen = wcslen(p);
1310 if (p[0] != L'-') {
1311 read_commands();
1312 maybe_handle_shebang(&argv[1], command);
1313 }
1314 /* No file with shebang, or an unrecognised shebang.
1315 * Is the first arg a special version qualifier?
1316 */
1317 valid = (*p == L'-') && validate_version(&p[1]);
1318 if (valid) {
1319 ip = locate_python(&p[1]);
1320 if (ip == NULL)
1321 error(RC_NO_PYTHON, L"Requested Python version (%s) not \
1322installed", &p[1]);
1323 command += wcslen(p);
1324 command = skip_whitespace(command);
1325 }
1326 }
1327 if (!valid) {
1328 ip = locate_python(L"");
1329 if (ip == NULL)
1330 error(RC_NO_PYTHON, L"Can't find a default Python.");
1331 if ((argc == 2) && (!_wcsicmp(p, L"-h") || !_wcsicmp(p, L"--help"))) {
1332#if defined(_M_X64)
1333 BOOL canDo64bit = TRUE;
1334#else
1335 // If we are a 32bit process on a 64bit Windows, first hit the 64bit keys.
1336 BOOL canDo64bit = FALSE;
1337 IsWow64Process(GetCurrentProcess(), &canDo64bit);
1338#endif
1339
1340 get_version_info(version_text, MAX_PATH);
1341 fwprintf(stdout, L"\
1342Python Launcher for Windows Version %s\n\n", version_text);
1343 fwprintf(stdout, L"\
1344usage: %s [ launcher-arguments ] script [ script-arguments ]\n\n", argv[0]);
1345 fputws(L"\
1346Launcher arguments:\n\n\
1347-2 : Launch the latest Python 2.x version\n\
1348-3 : Launch the latest Python 3.x version\n\
1349-X.Y : Launch the specified Python version\n", stdout);
1350 if (canDo64bit) {
1351 fputws(L"\
1352-X.Y-32: Launch the specified 32bit Python version", stdout);
1353 }
1354 fputws(L"\n\nThe following help text is from Python:\n\n", stdout);
1355 fflush(stdout);
1356 }
1357 }
1358 invoke_child(ip->executable, NULL, command);
1359 return rc;
1360}
1361
1362#if defined(_WINDOWS)
1363
1364int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
1365 LPWSTR lpstrCmd, int nShow)
1366{
1367 return process(__argc, __wargv);
1368}
1369
1370#else
1371
1372int cdecl wmain(int argc, wchar_t ** argv)
1373{
1374 return process(argc, argv);
1375}
1376
1377#endif