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