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