ยปCore Development>Code coverage>PC/launcher.c

Python code coverage for PC/launcher.c

#countcontent
1n/a/*
2n/a * Copyright (C) 2011-2013 Vinay Sajip.
3n/a * Licensed to PSF under a contributor agreement.
4n/a *
5n/a * Based on the work of:
6n/a *
7n/a * Mark Hammond (original author of Python version)
8n/a * Curt Hagenlocher (job management)
9n/a */
10n/a
11n/a#include <windows.h>
12n/a#include <shlobj.h>
13n/a#include <stdio.h>
14n/a#include <tchar.h>
15n/a
16n/a#define BUFSIZE 256
17n/a#define MSGSIZE 1024
18n/a
19n/a/* Build options. */
20n/a#define SKIP_PREFIX
21n/a#define SEARCH_PATH
22n/a
23n/a/* Error codes */
24n/a
25n/a#define RC_NO_STD_HANDLES 100
26n/a#define RC_CREATE_PROCESS 101
27n/a#define RC_BAD_VIRTUAL_PATH 102
28n/a#define RC_NO_PYTHON 103
29n/a#define RC_NO_MEMORY 104
30n/a/*
31n/a * SCRIPT_WRAPPER is used to choose between two variants of an executable built
32n/a * from this source file. If not defined, the PEP 397 Python launcher is built;
33n/a * if defined, a script launcher of the type used by setuptools is built, which
34n/a * looks for a script name related to the executable name and runs that script
35n/a * with the appropriate Python interpreter.
36n/a *
37n/a * SCRIPT_WRAPPER should be undefined in the source, and defined in a VS project
38n/a * which builds the setuptools-style launcher.
39n/a */
40n/a#if defined(SCRIPT_WRAPPER)
41n/a#define RC_NO_SCRIPT 105
42n/a#endif
43n/a
44n/a/* Just for now - static definition */
45n/a
46n/astatic FILE * log_fp = NULL;
47n/a
48n/astatic wchar_t *
49n/askip_whitespace(wchar_t * p)
50n/a{
51n/a while (*p && isspace(*p))
52n/a ++p;
53n/a return p;
54n/a}
55n/a
56n/astatic void
57n/adebug(wchar_t * format, ...)
58n/a{
59n/a va_list va;
60n/a
61n/a if (log_fp != NULL) {
62n/a va_start(va, format);
63n/a vfwprintf_s(log_fp, format, va);
64n/a }
65n/a}
66n/a
67n/astatic void
68n/awinerror(int rc, wchar_t * message, int size)
69n/a{
70n/a FormatMessageW(
71n/a FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
72n/a NULL, rc, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
73n/a message, size, NULL);
74n/a}
75n/a
76n/astatic void
77n/aerror(int rc, wchar_t * format, ... )
78n/a{
79n/a va_list va;
80n/a wchar_t message[MSGSIZE];
81n/a wchar_t win_message[MSGSIZE];
82n/a int len;
83n/a
84n/a va_start(va, format);
85n/a len = _vsnwprintf_s(message, MSGSIZE, _TRUNCATE, format, va);
86n/a
87n/a if (rc == 0) { /* a Windows error */
88n/a winerror(GetLastError(), win_message, MSGSIZE);
89n/a if (len >= 0) {
90n/a _snwprintf_s(&message[len], MSGSIZE - len, _TRUNCATE, L": %ls",
91n/a win_message);
92n/a }
93n/a }
94n/a
95n/a#if !defined(_WINDOWS)
96n/a fwprintf(stderr, L"%ls\n", message);
97n/a#else
98n/a MessageBox(NULL, message, TEXT("Python Launcher is sorry to say ..."),
99n/a MB_OK);
100n/a#endif
101n/a exit(rc);
102n/a}
103n/a
104n/a/*
105n/a * This function is here to simplify memory management
106n/a * and to treat blank values as if they are absent.
107n/a */
108n/astatic wchar_t * get_env(wchar_t * key)
109n/a{
110n/a /* This is not thread-safe, just like getenv */
111n/a static wchar_t buf[BUFSIZE];
112n/a DWORD result = GetEnvironmentVariableW(key, buf, BUFSIZE);
113n/a
114n/a if (result >= BUFSIZE) {
115n/a /* Large environment variable. Accept some leakage */
116n/a wchar_t *buf2 = (wchar_t*)malloc(sizeof(wchar_t) * (result+1));
117n/a if (buf2 == NULL) {
118n/a error(RC_NO_MEMORY, L"Could not allocate environment buffer");
119n/a }
120n/a GetEnvironmentVariableW(key, buf2, result);
121n/a return buf2;
122n/a }
123n/a
124n/a if (result == 0)
125n/a /* Either some error, e.g. ERROR_ENVVAR_NOT_FOUND,
126n/a or an empty environment variable. */
127n/a return NULL;
128n/a
129n/a return buf;
130n/a}
131n/a
132n/a#if defined(_WINDOWS)
133n/a
134n/a#define PYTHON_EXECUTABLE L"pythonw.exe"
135n/a
136n/a#else
137n/a
138n/a#define PYTHON_EXECUTABLE L"python.exe"
139n/a
140n/a#endif
141n/a
142n/a#define MAX_VERSION_SIZE 4
143n/a
144n/atypedef struct {
145n/a wchar_t version[MAX_VERSION_SIZE]; /* m.n */
146n/a int bits; /* 32 or 64 */
147n/a wchar_t executable[MAX_PATH];
148n/a} INSTALLED_PYTHON;
149n/a
150n/a/*
151n/a * To avoid messing about with heap allocations, just assume we can allocate
152n/a * statically and never have to deal with more versions than this.
153n/a */
154n/a#define MAX_INSTALLED_PYTHONS 100
155n/a
156n/astatic INSTALLED_PYTHON installed_pythons[MAX_INSTALLED_PYTHONS];
157n/a
158n/astatic size_t num_installed_pythons = 0;
159n/a
160n/a/*
161n/a * To hold SOFTWARE\Python\PythonCore\X.Y...\InstallPath
162n/a * The version name can be longer than MAX_VERSION_SIZE, but will be
163n/a * truncated to just X.Y for comparisons.
164n/a */
165n/a#define IP_BASE_SIZE 40
166n/a#define IP_VERSION_SIZE 8
167n/a#define IP_SIZE (IP_BASE_SIZE + IP_VERSION_SIZE)
168n/a#define CORE_PATH L"SOFTWARE\\Python\\PythonCore"
169n/a
170n/astatic wchar_t * location_checks[] = {
171n/a L"\\",
172n/a L"\\PCBuild\\win32\\",
173n/a L"\\PCBuild\\amd64\\",
174n/a // To support early 32bit versions of Python that stuck the build binaries
175n/a // directly in PCBuild...
176n/a L"\\PCBuild\\",
177n/a NULL
178n/a};
179n/a
180n/astatic INSTALLED_PYTHON *
181n/afind_existing_python(wchar_t * path)
182n/a{
183n/a INSTALLED_PYTHON * result = NULL;
184n/a size_t i;
185n/a INSTALLED_PYTHON * ip;
186n/a
187n/a for (i = 0, ip = installed_pythons; i < num_installed_pythons; i++, ip++) {
188n/a if (_wcsicmp(path, ip->executable) == 0) {
189n/a result = ip;
190n/a break;
191n/a }
192n/a }
193n/a return result;
194n/a}
195n/a
196n/astatic void
197n/alocate_pythons_for_key(HKEY root, REGSAM flags)
198n/a{
199n/a HKEY core_root, ip_key;
200n/a LSTATUS status = RegOpenKeyExW(root, CORE_PATH, 0, flags, &core_root);
201n/a wchar_t message[MSGSIZE];
202n/a DWORD i;
203n/a size_t n;
204n/a BOOL ok;
205n/a DWORD type, data_size, attrs;
206n/a INSTALLED_PYTHON * ip, * pip;
207n/a wchar_t ip_version[IP_VERSION_SIZE];
208n/a wchar_t ip_path[IP_SIZE];
209n/a wchar_t * check;
210n/a wchar_t ** checkp;
211n/a wchar_t *key_name = (root == HKEY_LOCAL_MACHINE) ? L"HKLM" : L"HKCU";
212n/a
213n/a if (status != ERROR_SUCCESS)
214n/a debug(L"locate_pythons_for_key: unable to open PythonCore key in %ls\n",
215n/a key_name);
216n/a else {
217n/a ip = &installed_pythons[num_installed_pythons];
218n/a for (i = 0; num_installed_pythons < MAX_INSTALLED_PYTHONS; i++) {
219n/a status = RegEnumKeyW(core_root, i, ip_version, IP_VERSION_SIZE);
220n/a if (status != ERROR_SUCCESS) {
221n/a if (status != ERROR_NO_MORE_ITEMS) {
222n/a /* unexpected error */
223n/a winerror(status, message, MSGSIZE);
224n/a debug(L"Can't enumerate registry key for version %ls: %ls\n",
225n/a ip_version, message);
226n/a }
227n/a break;
228n/a }
229n/a else {
230n/a wcsncpy_s(ip->version, MAX_VERSION_SIZE, ip_version,
231n/a MAX_VERSION_SIZE-1);
232n/a _snwprintf_s(ip_path, IP_SIZE, _TRUNCATE,
233n/a L"%ls\\%ls\\InstallPath", CORE_PATH, ip_version);
234n/a status = RegOpenKeyExW(root, ip_path, 0, flags, &ip_key);
235n/a if (status != ERROR_SUCCESS) {
236n/a winerror(status, message, MSGSIZE);
237n/a // Note: 'message' already has a trailing \n
238n/a debug(L"%ls\\%ls: %ls", key_name, ip_path, message);
239n/a continue;
240n/a }
241n/a data_size = sizeof(ip->executable) - 1;
242n/a status = RegQueryValueExW(ip_key, NULL, NULL, &type,
243n/a (LPBYTE)ip->executable, &data_size);
244n/a RegCloseKey(ip_key);
245n/a if (status != ERROR_SUCCESS) {
246n/a winerror(status, message, MSGSIZE);
247n/a debug(L"%ls\\%ls: %ls\n", key_name, ip_path, message);
248n/a continue;
249n/a }
250n/a if (type == REG_SZ) {
251n/a data_size = data_size / sizeof(wchar_t) - 1; /* for NUL */
252n/a if (ip->executable[data_size - 1] == L'\\')
253n/a --data_size; /* reg value ended in a backslash */
254n/a /* ip->executable is data_size long */
255n/a for (checkp = location_checks; *checkp; ++checkp) {
256n/a check = *checkp;
257n/a _snwprintf_s(&ip->executable[data_size],
258n/a MAX_PATH - data_size,
259n/a MAX_PATH - data_size,
260n/a L"%ls%ls", check, PYTHON_EXECUTABLE);
261n/a attrs = GetFileAttributesW(ip->executable);
262n/a if (attrs == INVALID_FILE_ATTRIBUTES) {
263n/a winerror(GetLastError(), message, MSGSIZE);
264n/a debug(L"locate_pythons_for_key: %ls: %ls",
265n/a ip->executable, message);
266n/a }
267n/a else if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
268n/a debug(L"locate_pythons_for_key: '%ls' is a \
269n/adirectory\n",
270n/a ip->executable, attrs);
271n/a }
272n/a else if (find_existing_python(ip->executable)) {
273n/a debug(L"locate_pythons_for_key: %ls: already \
274n/afound\n", ip->executable);
275n/a }
276n/a else {
277n/a /* check the executable type. */
278n/a ok = GetBinaryTypeW(ip->executable, &attrs);
279n/a if (!ok) {
280n/a debug(L"Failure getting binary type: %ls\n",
281n/a ip->executable);
282n/a }
283n/a else {
284n/a if (attrs == SCS_64BIT_BINARY)
285n/a ip->bits = 64;
286n/a else if (attrs == SCS_32BIT_BINARY)
287n/a ip->bits = 32;
288n/a else
289n/a ip->bits = 0;
290n/a if (ip->bits == 0) {
291n/a debug(L"locate_pythons_for_key: %ls: \
292n/ainvalid binary type: %X\n",
293n/a ip->executable, attrs);
294n/a }
295n/a else {
296n/a if (wcschr(ip->executable, L' ') != NULL) {
297n/a /* has spaces, so quote */
298n/a n = wcslen(ip->executable);
299n/a memmove(&ip->executable[1],
300n/a ip->executable, n * sizeof(wchar_t));
301n/a ip->executable[0] = L'\"';
302n/a ip->executable[n + 1] = L'\"';
303n/a ip->executable[n + 2] = L'\0';
304n/a }
305n/a debug(L"locate_pythons_for_key: %ls \
306n/ais a %dbit executable\n",
307n/a ip->executable, ip->bits);
308n/a ++num_installed_pythons;
309n/a pip = ip++;
310n/a if (num_installed_pythons >=
311n/a MAX_INSTALLED_PYTHONS)
312n/a break;
313n/a /* Copy over the attributes for the next */
314n/a *ip = *pip;
315n/a }
316n/a }
317n/a }
318n/a }
319n/a }
320n/a }
321n/a }
322n/a RegCloseKey(core_root);
323n/a }
324n/a}
325n/a
326n/astatic int
327n/acompare_pythons(const void * p1, const void * p2)
328n/a{
329n/a INSTALLED_PYTHON * ip1 = (INSTALLED_PYTHON *) p1;
330n/a INSTALLED_PYTHON * ip2 = (INSTALLED_PYTHON *) p2;
331n/a /* note reverse sorting on version */
332n/a int result = wcscmp(ip2->version, ip1->version);
333n/a
334n/a if (result == 0)
335n/a result = ip2->bits - ip1->bits; /* 64 before 32 */
336n/a return result;
337n/a}
338n/a
339n/astatic void
340n/alocate_all_pythons()
341n/a{
342n/a#if defined(_M_X64)
343n/a // If we are a 64bit process, first hit the 32bit keys.
344n/a debug(L"locating Pythons in 32bit registry\n");
345n/a locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ | KEY_WOW64_32KEY);
346n/a locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ | KEY_WOW64_32KEY);
347n/a#else
348n/a // If we are a 32bit process on a 64bit Windows, first hit the 64bit keys.
349n/a BOOL f64 = FALSE;
350n/a if (IsWow64Process(GetCurrentProcess(), &f64) && f64) {
351n/a debug(L"locating Pythons in 64bit registry\n");
352n/a locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ | KEY_WOW64_64KEY);
353n/a locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ | KEY_WOW64_64KEY);
354n/a }
355n/a#endif
356n/a // now hit the "native" key for this process bittedness.
357n/a debug(L"locating Pythons in native registry\n");
358n/a locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ);
359n/a locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ);
360n/a qsort(installed_pythons, num_installed_pythons, sizeof(INSTALLED_PYTHON),
361n/a compare_pythons);
362n/a}
363n/a
364n/astatic INSTALLED_PYTHON *
365n/afind_python_by_version(wchar_t const * wanted_ver)
366n/a{
367n/a INSTALLED_PYTHON * result = NULL;
368n/a INSTALLED_PYTHON * ip = installed_pythons;
369n/a size_t i, n;
370n/a size_t wlen = wcslen(wanted_ver);
371n/a int bits = 0;
372n/a
373n/a if (wcsstr(wanted_ver, L"-32"))
374n/a bits = 32;
375n/a for (i = 0; i < num_installed_pythons; i++, ip++) {
376n/a n = wcslen(ip->version);
377n/a if (n > wlen)
378n/a n = wlen;
379n/a if ((wcsncmp(ip->version, wanted_ver, n) == 0) &&
380n/a /* bits == 0 => don't care */
381n/a ((bits == 0) || (ip->bits == bits))) {
382n/a result = ip;
383n/a break;
384n/a }
385n/a }
386n/a return result;
387n/a}
388n/a
389n/a
390n/astatic wchar_t *
391n/afind_python_by_venv()
392n/a{
393n/a static wchar_t venv_python[MAX_PATH];
394n/a wchar_t *virtual_env = get_env(L"VIRTUAL_ENV");
395n/a DWORD attrs;
396n/a
397n/a /* Check for VIRTUAL_ENV environment variable */
398n/a if (virtual_env == NULL || virtual_env[0] == L'\0') {
399n/a return NULL;
400n/a }
401n/a
402n/a /* Check for a python executable in the venv */
403n/a debug(L"Checking for Python executable in virtual env '%ls'\n", virtual_env);
404n/a _snwprintf_s(venv_python, MAX_PATH, _TRUNCATE,
405n/a L"%ls\\Scripts\\%ls", virtual_env, PYTHON_EXECUTABLE);
406n/a attrs = GetFileAttributesW(venv_python);
407n/a if (attrs == INVALID_FILE_ATTRIBUTES) {
408n/a debug(L"Python executable %ls missing from virtual env\n", venv_python);
409n/a return NULL;
410n/a }
411n/a
412n/a return venv_python;
413n/a}
414n/a
415n/astatic wchar_t appdata_ini_path[MAX_PATH];
416n/astatic wchar_t launcher_ini_path[MAX_PATH];
417n/a
418n/a/*
419n/a * Get a value either from the environment or a configuration file.
420n/a * The key passed in will either be "python", "python2" or "python3".
421n/a */
422n/astatic wchar_t *
423n/aget_configured_value(wchar_t * key)
424n/a{
425n/a/*
426n/a * Note: this static value is used to return a configured value
427n/a * obtained either from the environment or configuration file.
428n/a * This should be OK since there wouldn't be any concurrent calls.
429n/a */
430n/a static wchar_t configured_value[MSGSIZE];
431n/a wchar_t * result = NULL;
432n/a wchar_t * found_in = L"environment";
433n/a DWORD size;
434n/a
435n/a /* First, search the environment. */
436n/a _snwprintf_s(configured_value, MSGSIZE, _TRUNCATE, L"py_%ls", key);
437n/a result = get_env(configured_value);
438n/a if (result == NULL && appdata_ini_path[0]) {
439n/a /* Not in environment: check local configuration. */
440n/a size = GetPrivateProfileStringW(L"defaults", key, NULL,
441n/a configured_value, MSGSIZE,
442n/a appdata_ini_path);
443n/a if (size > 0) {
444n/a result = configured_value;
445n/a found_in = appdata_ini_path;
446n/a }
447n/a }
448n/a if (result == NULL && launcher_ini_path[0]) {
449n/a /* Not in environment or local: check global configuration. */
450n/a size = GetPrivateProfileStringW(L"defaults", key, NULL,
451n/a configured_value, MSGSIZE,
452n/a launcher_ini_path);
453n/a if (size > 0) {
454n/a result = configured_value;
455n/a found_in = launcher_ini_path;
456n/a }
457n/a }
458n/a if (result) {
459n/a debug(L"found configured value '%ls=%ls' in %ls\n",
460n/a key, result, found_in ? found_in : L"(unknown)");
461n/a } else {
462n/a debug(L"found no configured value for '%ls'\n", key);
463n/a }
464n/a return result;
465n/a}
466n/a
467n/astatic INSTALLED_PYTHON *
468n/alocate_python(wchar_t * wanted_ver, BOOL from_shebang)
469n/a{
470n/a static wchar_t config_key [] = { L"pythonX" };
471n/a static wchar_t * last_char = &config_key[sizeof(config_key) /
472n/a sizeof(wchar_t) - 2];
473n/a INSTALLED_PYTHON * result = NULL;
474n/a size_t n = wcslen(wanted_ver);
475n/a wchar_t * configured_value;
476n/a
477n/a if (num_installed_pythons == 0)
478n/a locate_all_pythons();
479n/a
480n/a if (n == 1) { /* just major version specified */
481n/a *last_char = *wanted_ver;
482n/a configured_value = get_configured_value(config_key);
483n/a if (configured_value != NULL)
484n/a wanted_ver = configured_value;
485n/a }
486n/a if (*wanted_ver) {
487n/a result = find_python_by_version(wanted_ver);
488n/a debug(L"search for Python version '%ls' found ", wanted_ver);
489n/a if (result) {
490n/a debug(L"'%ls'\n", result->executable);
491n/a } else {
492n/a debug(L"no interpreter\n");
493n/a }
494n/a }
495n/a else {
496n/a *last_char = L'\0'; /* look for an overall default */
497n/a configured_value = get_configured_value(config_key);
498n/a if (configured_value)
499n/a result = find_python_by_version(configured_value);
500n/a /* Not found a value yet - try by major version.
501n/a * If we're looking for an interpreter specified in a shebang line,
502n/a * we want to try Python 2 first, then Python 3 (for Unix and backward
503n/a * compatibility). If we're being called interactively, assume the user
504n/a * wants the latest version available, so try Python 3 first, then
505n/a * Python 2.
506n/a */
507n/a if (result == NULL)
508n/a result = find_python_by_version(from_shebang ? L"2" : L"3");
509n/a if (result == NULL)
510n/a result = find_python_by_version(from_shebang ? L"3" : L"2");
511n/a debug(L"search for default Python found ");
512n/a if (result) {
513n/a debug(L"version %ls at '%ls'\n",
514n/a result->version, result->executable);
515n/a } else {
516n/a debug(L"no interpreter\n");
517n/a }
518n/a }
519n/a return result;
520n/a}
521n/a
522n/a#if defined(SCRIPT_WRAPPER)
523n/a/*
524n/a * Check for a script located alongside the executable
525n/a */
526n/a
527n/a#if defined(_WINDOWS)
528n/a#define SCRIPT_SUFFIX L"-script.pyw"
529n/a#else
530n/a#define SCRIPT_SUFFIX L"-script.py"
531n/a#endif
532n/a
533n/astatic wchar_t wrapped_script_path[MAX_PATH];
534n/a
535n/a/* Locate the script being wrapped.
536n/a *
537n/a * This code should store the name of the wrapped script in
538n/a * wrapped_script_path, or terminate the program with an error if there is no
539n/a * valid wrapped script file.
540n/a */
541n/astatic void
542n/alocate_wrapped_script()
543n/a{
544n/a wchar_t * p;
545n/a size_t plen;
546n/a DWORD attrs;
547n/a
548n/a plen = GetModuleFileNameW(NULL, wrapped_script_path, MAX_PATH);
549n/a p = wcsrchr(wrapped_script_path, L'.');
550n/a if (p == NULL) {
551n/a debug(L"GetModuleFileNameW returned value has no extension: %ls\n",
552n/a wrapped_script_path);
553n/a error(RC_NO_SCRIPT, L"Wrapper name '%ls' is not valid.", wrapped_script_path);
554n/a }
555n/a
556n/a wcsncpy_s(p, MAX_PATH - (p - wrapped_script_path) + 1, SCRIPT_SUFFIX, _TRUNCATE);
557n/a attrs = GetFileAttributesW(wrapped_script_path);
558n/a if (attrs == INVALID_FILE_ATTRIBUTES) {
559n/a debug(L"File '%ls' non-existent\n", wrapped_script_path);
560n/a error(RC_NO_SCRIPT, L"Script file '%ls' is not present.", wrapped_script_path);
561n/a }
562n/a
563n/a debug(L"Using wrapped script file '%ls'\n", wrapped_script_path);
564n/a}
565n/a#endif
566n/a
567n/a/*
568n/a * Process creation code
569n/a */
570n/a
571n/astatic BOOL
572n/asafe_duplicate_handle(HANDLE in, HANDLE * pout)
573n/a{
574n/a BOOL ok;
575n/a HANDLE process = GetCurrentProcess();
576n/a DWORD rc;
577n/a
578n/a *pout = NULL;
579n/a ok = DuplicateHandle(process, in, process, pout, 0, TRUE,
580n/a DUPLICATE_SAME_ACCESS);
581n/a if (!ok) {
582n/a rc = GetLastError();
583n/a if (rc == ERROR_INVALID_HANDLE) {
584n/a debug(L"DuplicateHandle returned ERROR_INVALID_HANDLE\n");
585n/a ok = TRUE;
586n/a }
587n/a else {
588n/a debug(L"DuplicateHandle returned %d\n", rc);
589n/a }
590n/a }
591n/a return ok;
592n/a}
593n/a
594n/astatic BOOL WINAPI
595n/actrl_c_handler(DWORD code)
596n/a{
597n/a return TRUE; /* We just ignore all control events. */
598n/a}
599n/a
600n/astatic void
601n/arun_child(wchar_t * cmdline)
602n/a{
603n/a HANDLE job;
604n/a JOBOBJECT_EXTENDED_LIMIT_INFORMATION info;
605n/a DWORD rc;
606n/a BOOL ok;
607n/a STARTUPINFOW si;
608n/a PROCESS_INFORMATION pi;
609n/a
610n/a#if defined(_WINDOWS)
611n/a // When explorer launches a Windows (GUI) application, it displays
612n/a // the "app starting" (the "pointer + hourglass") cursor for a number
613n/a // of seconds, or until the app does something UI-ish (eg, creating a
614n/a // window, or fetching a message). As this launcher doesn't do this
615n/a // directly, that cursor remains even after the child process does these
616n/a // things. We avoid that by doing a simple post+get message.
617n/a // See http://bugs.python.org/issue17290 and
618n/a // https://bitbucket.org/vinay.sajip/pylauncher/issue/20/busy-cursor-for-a-long-time-when-running
619n/a MSG msg;
620n/a
621n/a PostMessage(0, 0, 0, 0);
622n/a GetMessage(&msg, 0, 0, 0);
623n/a#endif
624n/a
625n/a debug(L"run_child: about to run '%ls'\n", cmdline);
626n/a job = CreateJobObject(NULL, NULL);
627n/a ok = QueryInformationJobObject(job, JobObjectExtendedLimitInformation,
628n/a &info, sizeof(info), &rc);
629n/a if (!ok || (rc != sizeof(info)) || !job)
630n/a error(RC_CREATE_PROCESS, L"Job information querying failed");
631n/a info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE |
632n/a JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK;
633n/a ok = SetInformationJobObject(job, JobObjectExtendedLimitInformation, &info,
634n/a sizeof(info));
635n/a if (!ok)
636n/a error(RC_CREATE_PROCESS, L"Job information setting failed");
637n/a memset(&si, 0, sizeof(si));
638n/a si.cb = sizeof(si);
639n/a ok = safe_duplicate_handle(GetStdHandle(STD_INPUT_HANDLE), &si.hStdInput);
640n/a if (!ok)
641n/a error(RC_NO_STD_HANDLES, L"stdin duplication failed");
642n/a ok = safe_duplicate_handle(GetStdHandle(STD_OUTPUT_HANDLE), &si.hStdOutput);
643n/a if (!ok)
644n/a error(RC_NO_STD_HANDLES, L"stdout duplication failed");
645n/a ok = safe_duplicate_handle(GetStdHandle(STD_ERROR_HANDLE), &si.hStdError);
646n/a if (!ok)
647n/a error(RC_NO_STD_HANDLES, L"stderr duplication failed");
648n/a
649n/a ok = SetConsoleCtrlHandler(ctrl_c_handler, TRUE);
650n/a if (!ok)
651n/a error(RC_CREATE_PROCESS, L"control handler setting failed");
652n/a
653n/a si.dwFlags = STARTF_USESTDHANDLES;
654n/a ok = CreateProcessW(NULL, cmdline, NULL, NULL, TRUE,
655n/a 0, NULL, NULL, &si, &pi);
656n/a if (!ok)
657n/a error(RC_CREATE_PROCESS, L"Unable to create process using '%ls'", cmdline);
658n/a AssignProcessToJobObject(job, pi.hProcess);
659n/a CloseHandle(pi.hThread);
660n/a WaitForSingleObjectEx(pi.hProcess, INFINITE, FALSE);
661n/a ok = GetExitCodeProcess(pi.hProcess, &rc);
662n/a if (!ok)
663n/a error(RC_CREATE_PROCESS, L"Failed to get exit code of process");
664n/a debug(L"child process exit code: %d\n", rc);
665n/a exit(rc);
666n/a}
667n/a
668n/astatic void
669n/ainvoke_child(wchar_t * executable, wchar_t * suffix, wchar_t * cmdline)
670n/a{
671n/a wchar_t * child_command;
672n/a size_t child_command_size;
673n/a BOOL no_suffix = (suffix == NULL) || (*suffix == L'\0');
674n/a BOOL no_cmdline = (*cmdline == L'\0');
675n/a
676n/a if (no_suffix && no_cmdline)
677n/a run_child(executable);
678n/a else {
679n/a if (no_suffix) {
680n/a /* add 2 for space separator + terminating NUL. */
681n/a child_command_size = wcslen(executable) + wcslen(cmdline) + 2;
682n/a }
683n/a else {
684n/a /* add 3 for 2 space separators + terminating NUL. */
685n/a child_command_size = wcslen(executable) + wcslen(suffix) +
686n/a wcslen(cmdline) + 3;
687n/a }
688n/a child_command = calloc(child_command_size, sizeof(wchar_t));
689n/a if (child_command == NULL)
690n/a error(RC_CREATE_PROCESS, L"unable to allocate %d bytes for child command.",
691n/a child_command_size);
692n/a if (no_suffix)
693n/a _snwprintf_s(child_command, child_command_size,
694n/a child_command_size - 1, L"%ls %ls",
695n/a executable, cmdline);
696n/a else
697n/a _snwprintf_s(child_command, child_command_size,
698n/a child_command_size - 1, L"%ls %ls %ls",
699n/a executable, suffix, cmdline);
700n/a run_child(child_command);
701n/a free(child_command);
702n/a }
703n/a}
704n/a
705n/atypedef struct {
706n/a wchar_t *shebang;
707n/a BOOL search;
708n/a} SHEBANG;
709n/a
710n/astatic SHEBANG builtin_virtual_paths [] = {
711n/a { L"/usr/bin/env python", TRUE },
712n/a { L"/usr/bin/python", FALSE },
713n/a { L"/usr/local/bin/python", FALSE },
714n/a { L"python", FALSE },
715n/a { NULL, FALSE },
716n/a};
717n/a
718n/a/* For now, a static array of commands. */
719n/a
720n/a#define MAX_COMMANDS 100
721n/a
722n/atypedef struct {
723n/a wchar_t key[MAX_PATH];
724n/a wchar_t value[MSGSIZE];
725n/a} COMMAND;
726n/a
727n/astatic COMMAND commands[MAX_COMMANDS];
728n/astatic int num_commands = 0;
729n/a
730n/a#if defined(SKIP_PREFIX)
731n/a
732n/astatic wchar_t * builtin_prefixes [] = {
733n/a /* These must be in an order that the longest matches should be found,
734n/a * i.e. if the prefix is "/usr/bin/env ", it should match that entry
735n/a * *before* matching "/usr/bin/".
736n/a */
737n/a L"/usr/bin/env ",
738n/a L"/usr/bin/",
739n/a L"/usr/local/bin/",
740n/a NULL
741n/a};
742n/a
743n/astatic wchar_t * skip_prefix(wchar_t * name)
744n/a{
745n/a wchar_t ** pp = builtin_prefixes;
746n/a wchar_t * result = name;
747n/a wchar_t * p;
748n/a size_t n;
749n/a
750n/a for (; p = *pp; pp++) {
751n/a n = wcslen(p);
752n/a if (_wcsnicmp(p, name, n) == 0) {
753n/a result += n; /* skip the prefix */
754n/a if (p[n - 1] == L' ') /* No empty strings in table, so n > 1 */
755n/a result = skip_whitespace(result);
756n/a break;
757n/a }
758n/a }
759n/a return result;
760n/a}
761n/a
762n/a#endif
763n/a
764n/a#if defined(SEARCH_PATH)
765n/a
766n/astatic COMMAND path_command;
767n/a
768n/astatic COMMAND * find_on_path(wchar_t * name)
769n/a{
770n/a wchar_t * pathext;
771n/a size_t varsize;
772n/a wchar_t * context = NULL;
773n/a wchar_t * extension;
774n/a COMMAND * result = NULL;
775n/a DWORD len;
776n/a errno_t rc;
777n/a
778n/a wcscpy_s(path_command.key, MAX_PATH, name);
779n/a if (wcschr(name, L'.') != NULL) {
780n/a /* assume it has an extension. */
781n/a len = SearchPathW(NULL, name, NULL, MSGSIZE, path_command.value, NULL);
782n/a if (len) {
783n/a result = &path_command;
784n/a }
785n/a }
786n/a else {
787n/a /* No extension - search using registered extensions. */
788n/a rc = _wdupenv_s(&pathext, &varsize, L"PATHEXT");
789n/a if (rc == 0) {
790n/a extension = wcstok_s(pathext, L";", &context);
791n/a while (extension) {
792n/a len = SearchPathW(NULL, name, extension, MSGSIZE, path_command.value, NULL);
793n/a if (len) {
794n/a result = &path_command;
795n/a break;
796n/a }
797n/a extension = wcstok_s(NULL, L";", &context);
798n/a }
799n/a free(pathext);
800n/a }
801n/a }
802n/a return result;
803n/a}
804n/a
805n/a#endif
806n/a
807n/astatic COMMAND * find_command(wchar_t * name)
808n/a{
809n/a COMMAND * result = NULL;
810n/a COMMAND * cp = commands;
811n/a int i;
812n/a
813n/a for (i = 0; i < num_commands; i++, cp++) {
814n/a if (_wcsicmp(cp->key, name) == 0) {
815n/a result = cp;
816n/a break;
817n/a }
818n/a }
819n/a#if defined(SEARCH_PATH)
820n/a if (result == NULL)
821n/a result = find_on_path(name);
822n/a#endif
823n/a return result;
824n/a}
825n/a
826n/astatic void
827n/aupdate_command(COMMAND * cp, wchar_t * name, wchar_t * cmdline)
828n/a{
829n/a wcsncpy_s(cp->key, MAX_PATH, name, _TRUNCATE);
830n/a wcsncpy_s(cp->value, MSGSIZE, cmdline, _TRUNCATE);
831n/a}
832n/a
833n/astatic void
834n/aadd_command(wchar_t * name, wchar_t * cmdline)
835n/a{
836n/a if (num_commands >= MAX_COMMANDS) {
837n/a debug(L"can't add %ls = '%ls': no room\n", name, cmdline);
838n/a }
839n/a else {
840n/a COMMAND * cp = &commands[num_commands++];
841n/a
842n/a update_command(cp, name, cmdline);
843n/a }
844n/a}
845n/a
846n/astatic void
847n/aread_config_file(wchar_t * config_path)
848n/a{
849n/a wchar_t keynames[MSGSIZE];
850n/a wchar_t value[MSGSIZE];
851n/a DWORD read;
852n/a wchar_t * key;
853n/a COMMAND * cp;
854n/a wchar_t * cmdp;
855n/a
856n/a read = GetPrivateProfileStringW(L"commands", NULL, NULL, keynames, MSGSIZE,
857n/a config_path);
858n/a if (read == MSGSIZE - 1) {
859n/a debug(L"read_commands: %ls: not enough space for names\n", config_path);
860n/a }
861n/a key = keynames;
862n/a while (*key) {
863n/a read = GetPrivateProfileStringW(L"commands", key, NULL, value, MSGSIZE,
864n/a config_path);
865n/a if (read == MSGSIZE - 1) {
866n/a debug(L"read_commands: %ls: not enough space for %ls\n",
867n/a config_path, key);
868n/a }
869n/a cmdp = skip_whitespace(value);
870n/a if (*cmdp) {
871n/a cp = find_command(key);
872n/a if (cp == NULL)
873n/a add_command(key, value);
874n/a else
875n/a update_command(cp, key, value);
876n/a }
877n/a key += wcslen(key) + 1;
878n/a }
879n/a}
880n/a
881n/astatic void read_commands()
882n/a{
883n/a if (launcher_ini_path[0])
884n/a read_config_file(launcher_ini_path);
885n/a if (appdata_ini_path[0])
886n/a read_config_file(appdata_ini_path);
887n/a}
888n/a
889n/astatic BOOL
890n/aparse_shebang(wchar_t * shebang_line, int nchars, wchar_t ** command,
891n/a wchar_t ** suffix, BOOL *search)
892n/a{
893n/a BOOL rc = FALSE;
894n/a SHEBANG * vpp;
895n/a size_t plen;
896n/a wchar_t * p;
897n/a wchar_t zapped;
898n/a wchar_t * endp = shebang_line + nchars - 1;
899n/a COMMAND * cp;
900n/a wchar_t * skipped;
901n/a
902n/a *command = NULL; /* failure return */
903n/a *suffix = NULL;
904n/a *search = FALSE;
905n/a
906n/a if ((*shebang_line++ == L'#') && (*shebang_line++ == L'!')) {
907n/a shebang_line = skip_whitespace(shebang_line);
908n/a if (*shebang_line) {
909n/a *command = shebang_line;
910n/a for (vpp = builtin_virtual_paths; vpp->shebang; ++vpp) {
911n/a plen = wcslen(vpp->shebang);
912n/a if (wcsncmp(shebang_line, vpp->shebang, plen) == 0) {
913n/a rc = TRUE;
914n/a *search = vpp->search;
915n/a /* We can do this because all builtin commands contain
916n/a * "python".
917n/a */
918n/a *command = wcsstr(shebang_line, L"python");
919n/a break;
920n/a }
921n/a }
922n/a if (vpp->shebang == NULL) {
923n/a /*
924n/a * Not found in builtins - look in customized commands.
925n/a *
926n/a * We can't permanently modify the shebang line in case
927n/a * it's not a customized command, but we can temporarily
928n/a * stick a NUL after the command while searching for it,
929n/a * then put back the char we zapped.
930n/a */
931n/a#if defined(SKIP_PREFIX)
932n/a skipped = skip_prefix(shebang_line);
933n/a#else
934n/a skipped = shebang_line;
935n/a#endif
936n/a p = wcspbrk(skipped, L" \t\r\n");
937n/a if (p != NULL) {
938n/a zapped = *p;
939n/a *p = L'\0';
940n/a }
941n/a cp = find_command(skipped);
942n/a if (p != NULL)
943n/a *p = zapped;
944n/a if (cp != NULL) {
945n/a *command = cp->value;
946n/a if (p != NULL)
947n/a *suffix = skip_whitespace(p);
948n/a }
949n/a }
950n/a /* remove trailing whitespace */
951n/a while ((endp > shebang_line) && isspace(*endp))
952n/a --endp;
953n/a if (endp > shebang_line)
954n/a endp[1] = L'\0';
955n/a }
956n/a }
957n/a return rc;
958n/a}
959n/a
960n/a/* #define CP_UTF8 65001 defined in winnls.h */
961n/a#define CP_UTF16LE 1200
962n/a#define CP_UTF16BE 1201
963n/a#define CP_UTF32LE 12000
964n/a#define CP_UTF32BE 12001
965n/a
966n/atypedef struct {
967n/a int length;
968n/a char sequence[4];
969n/a UINT code_page;
970n/a} BOM;
971n/a
972n/a/*
973n/a * Strictly, we don't need to handle UTF-16 and UTF-32, since Python itself
974n/a * doesn't. Never mind, one day it might - there's no harm leaving it in.
975n/a */
976n/astatic BOM BOMs[] = {
977n/a { 3, { 0xEF, 0xBB, 0xBF }, CP_UTF8 }, /* UTF-8 - keep first */
978n/a /* Test UTF-32LE before UTF-16LE since UTF-16LE BOM is a prefix
979n/a * of UTF-32LE BOM. */
980n/a { 4, { 0xFF, 0xFE, 0x00, 0x00 }, CP_UTF32LE }, /* UTF-32LE */
981n/a { 4, { 0x00, 0x00, 0xFE, 0xFF }, CP_UTF32BE }, /* UTF-32BE */
982n/a { 2, { 0xFF, 0xFE }, CP_UTF16LE }, /* UTF-16LE */
983n/a { 2, { 0xFE, 0xFF }, CP_UTF16BE }, /* UTF-16BE */
984n/a { 0 } /* sentinel */
985n/a};
986n/a
987n/astatic BOM *
988n/afind_BOM(char * buffer)
989n/a{
990n/a/*
991n/a * Look for a BOM in the input and return a pointer to the
992n/a * corresponding structure, or NULL if not found.
993n/a */
994n/a BOM * result = NULL;
995n/a BOM *bom;
996n/a
997n/a for (bom = BOMs; bom->length; bom++) {
998n/a if (strncmp(bom->sequence, buffer, bom->length) == 0) {
999n/a result = bom;
1000n/a break;
1001n/a }
1002n/a }
1003n/a return result;
1004n/a}
1005n/a
1006n/astatic char *
1007n/afind_terminator(char * buffer, int len, BOM *bom)
1008n/a{
1009n/a char * result = NULL;
1010n/a char * end = buffer + len;
1011n/a char * p;
1012n/a char c;
1013n/a int cp;
1014n/a
1015n/a for (p = buffer; p < end; p++) {
1016n/a c = *p;
1017n/a if (c == '\r') {
1018n/a result = p;
1019n/a break;
1020n/a }
1021n/a if (c == '\n') {
1022n/a result = p;
1023n/a break;
1024n/a }
1025n/a }
1026n/a if (result != NULL) {
1027n/a cp = bom->code_page;
1028n/a
1029n/a /* adjustments to include all bytes of the char */
1030n/a /* no adjustment needed for UTF-8 or big endian */
1031n/a if (cp == CP_UTF16LE)
1032n/a ++result;
1033n/a else if (cp == CP_UTF32LE)
1034n/a result += 3;
1035n/a ++result; /* point just past terminator */
1036n/a }
1037n/a return result;
1038n/a}
1039n/a
1040n/astatic BOOL
1041n/avalidate_version(wchar_t * p)
1042n/a{
1043n/a BOOL result = TRUE;
1044n/a
1045n/a if (!isdigit(*p)) /* expect major version */
1046n/a result = FALSE;
1047n/a else if (*++p) { /* more to do */
1048n/a if (*p != L'.') /* major/minor separator */
1049n/a result = FALSE;
1050n/a else {
1051n/a ++p;
1052n/a if (!isdigit(*p)) /* expect minor version */
1053n/a result = FALSE;
1054n/a else {
1055n/a ++p;
1056n/a if (*p) { /* more to do */
1057n/a if (*p != L'-')
1058n/a result = FALSE;
1059n/a else {
1060n/a ++p;
1061n/a if ((*p != '3') && (*++p != '2') && !*++p)
1062n/a result = FALSE;
1063n/a }
1064n/a }
1065n/a }
1066n/a }
1067n/a }
1068n/a return result;
1069n/a}
1070n/a
1071n/atypedef struct {
1072n/a unsigned short min;
1073n/a unsigned short max;
1074n/a wchar_t version[MAX_VERSION_SIZE];
1075n/a} PYC_MAGIC;
1076n/a
1077n/astatic PYC_MAGIC magic_values[] = {
1078n/a { 50823, 50823, L"2.0" },
1079n/a { 60202, 60202, L"2.1" },
1080n/a { 60717, 60717, L"2.2" },
1081n/a { 62011, 62021, L"2.3" },
1082n/a { 62041, 62061, L"2.4" },
1083n/a { 62071, 62131, L"2.5" },
1084n/a { 62151, 62161, L"2.6" },
1085n/a { 62171, 62211, L"2.7" },
1086n/a { 3000, 3131, L"3.0" },
1087n/a { 3141, 3151, L"3.1" },
1088n/a { 3160, 3180, L"3.2" },
1089n/a { 3190, 3230, L"3.3" },
1090n/a { 3250, 3310, L"3.4" },
1091n/a { 3320, 3351, L"3.5" },
1092n/a { 3360, 3379, L"3.6" },
1093n/a { 3390, 3399, L"3.7" },
1094n/a { 0 }
1095n/a};
1096n/a
1097n/astatic INSTALLED_PYTHON *
1098n/afind_by_magic(unsigned short magic)
1099n/a{
1100n/a INSTALLED_PYTHON * result = NULL;
1101n/a PYC_MAGIC * mp;
1102n/a
1103n/a for (mp = magic_values; mp->min; mp++) {
1104n/a if ((magic >= mp->min) && (magic <= mp->max)) {
1105n/a result = locate_python(mp->version, FALSE);
1106n/a if (result != NULL)
1107n/a break;
1108n/a }
1109n/a }
1110n/a return result;
1111n/a}
1112n/a
1113n/astatic void
1114n/amaybe_handle_shebang(wchar_t ** argv, wchar_t * cmdline)
1115n/a{
1116n/a/*
1117n/a * Look for a shebang line in the first argument. If found
1118n/a * and we spawn a child process, this never returns. If it
1119n/a * does return then we process the args "normally".
1120n/a *
1121n/a * argv[0] might be a filename with a shebang.
1122n/a */
1123n/a FILE * fp;
1124n/a errno_t rc = _wfopen_s(&fp, *argv, L"rb");
1125n/a char buffer[BUFSIZE];
1126n/a wchar_t shebang_line[BUFSIZE + 1];
1127n/a size_t read;
1128n/a char *p;
1129n/a char * start;
1130n/a char * shebang_alias = (char *) shebang_line;
1131n/a BOM* bom;
1132n/a int i, j, nchars = 0;
1133n/a int header_len;
1134n/a BOOL is_virt;
1135n/a BOOL search;
1136n/a wchar_t * command;
1137n/a wchar_t * suffix;
1138n/a COMMAND *cmd = NULL;
1139n/a INSTALLED_PYTHON * ip;
1140n/a
1141n/a if (rc == 0) {
1142n/a read = fread(buffer, sizeof(char), BUFSIZE, fp);
1143n/a debug(L"maybe_handle_shebang: read %d bytes\n", read);
1144n/a fclose(fp);
1145n/a
1146n/a if ((read >= 4) && (buffer[3] == '\n') && (buffer[2] == '\r')) {
1147n/a ip = find_by_magic((((unsigned char)buffer[1]) << 8 |
1148n/a (unsigned char)buffer[0]) & 0xFFFF);
1149n/a if (ip != NULL) {
1150n/a debug(L"script file is compiled against Python %ls\n",
1151n/a ip->version);
1152n/a invoke_child(ip->executable, NULL, cmdline);
1153n/a }
1154n/a }
1155n/a /* Look for BOM */
1156n/a bom = find_BOM(buffer);
1157n/a if (bom == NULL) {
1158n/a start = buffer;
1159n/a debug(L"maybe_handle_shebang: BOM not found, using UTF-8\n");
1160n/a bom = BOMs; /* points to UTF-8 entry - the default */
1161n/a }
1162n/a else {
1163n/a debug(L"maybe_handle_shebang: BOM found, code page %d\n",
1164n/a bom->code_page);
1165n/a start = &buffer[bom->length];
1166n/a }
1167n/a p = find_terminator(start, BUFSIZE, bom);
1168n/a /*
1169n/a * If no CR or LF was found in the heading,
1170n/a * we assume it's not a shebang file.
1171n/a */
1172n/a if (p == NULL) {
1173n/a debug(L"maybe_handle_shebang: No line terminator found\n");
1174n/a }
1175n/a else {
1176n/a /*
1177n/a * Found line terminator - parse the shebang.
1178n/a *
1179n/a * Strictly, we don't need to handle UTF-16 anf UTF-32,
1180n/a * since Python itself doesn't.
1181n/a * Never mind, one day it might.
1182n/a */
1183n/a header_len = (int) (p - start);
1184n/a switch(bom->code_page) {
1185n/a case CP_UTF8:
1186n/a nchars = MultiByteToWideChar(bom->code_page,
1187n/a 0,
1188n/a start, header_len, shebang_line,
1189n/a BUFSIZE);
1190n/a break;
1191n/a case CP_UTF16BE:
1192n/a if (header_len % 2 != 0) {
1193n/a debug(L"maybe_handle_shebang: UTF-16BE, but an odd number \
1194n/aof bytes: %d\n", header_len);
1195n/a /* nchars = 0; Not needed - initialised to 0. */
1196n/a }
1197n/a else {
1198n/a for (i = header_len; i > 0; i -= 2) {
1199n/a shebang_alias[i - 1] = start[i - 2];
1200n/a shebang_alias[i - 2] = start[i - 1];
1201n/a }
1202n/a nchars = header_len / sizeof(wchar_t);
1203n/a }
1204n/a break;
1205n/a case CP_UTF16LE:
1206n/a if ((header_len % 2) != 0) {
1207n/a debug(L"UTF-16LE, but an odd number of bytes: %d\n",
1208n/a header_len);
1209n/a /* nchars = 0; Not needed - initialised to 0. */
1210n/a }
1211n/a else {
1212n/a /* no actual conversion needed. */
1213n/a memcpy(shebang_line, start, header_len);
1214n/a nchars = header_len / sizeof(wchar_t);
1215n/a }
1216n/a break;
1217n/a case CP_UTF32BE:
1218n/a if (header_len % 4 != 0) {
1219n/a debug(L"UTF-32BE, but not divisible by 4: %d\n",
1220n/a header_len);
1221n/a /* nchars = 0; Not needed - initialised to 0. */
1222n/a }
1223n/a else {
1224n/a for (i = header_len, j = header_len / 2; i > 0; i -= 4,
1225n/a j -= 2) {
1226n/a shebang_alias[j - 1] = start[i - 2];
1227n/a shebang_alias[j - 2] = start[i - 1];
1228n/a }
1229n/a nchars = header_len / sizeof(wchar_t);
1230n/a }
1231n/a break;
1232n/a case CP_UTF32LE:
1233n/a if (header_len % 4 != 0) {
1234n/a debug(L"UTF-32LE, but not divisible by 4: %d\n",
1235n/a header_len);
1236n/a /* nchars = 0; Not needed - initialised to 0. */
1237n/a }
1238n/a else {
1239n/a for (i = header_len, j = header_len / 2; i > 0; i -= 4,
1240n/a j -= 2) {
1241n/a shebang_alias[j - 1] = start[i - 3];
1242n/a shebang_alias[j - 2] = start[i - 4];
1243n/a }
1244n/a nchars = header_len / sizeof(wchar_t);
1245n/a }
1246n/a break;
1247n/a }
1248n/a if (nchars > 0) {
1249n/a shebang_line[--nchars] = L'\0';
1250n/a is_virt = parse_shebang(shebang_line, nchars, &command,
1251n/a &suffix, &search);
1252n/a if (command != NULL) {
1253n/a debug(L"parse_shebang: found command: %ls\n", command);
1254n/a if (!is_virt) {
1255n/a invoke_child(command, suffix, cmdline);
1256n/a }
1257n/a else {
1258n/a suffix = wcschr(command, L' ');
1259n/a if (suffix != NULL) {
1260n/a *suffix++ = L'\0';
1261n/a suffix = skip_whitespace(suffix);
1262n/a }
1263n/a if (wcsncmp(command, L"python", 6))
1264n/a error(RC_BAD_VIRTUAL_PATH, L"Unknown virtual \
1265n/apath '%ls'", command);
1266n/a command += 6; /* skip past "python" */
1267n/a if (search && ((*command == L'\0') || isspace(*command))) {
1268n/a /* Command is eligible for path search, and there
1269n/a * is no version specification.
1270n/a */
1271n/a debug(L"searching PATH for python executable\n");
1272n/a cmd = find_on_path(PYTHON_EXECUTABLE);
1273n/a debug(L"Python on path: %ls\n", cmd ? cmd->value : L"<not found>");
1274n/a if (cmd) {
1275n/a debug(L"located python on PATH: %ls\n", cmd->value);
1276n/a invoke_child(cmd->value, suffix, cmdline);
1277n/a /* Exit here, as we have found the command */
1278n/a return;
1279n/a }
1280n/a /* FALL THROUGH: No python found on PATH, so fall
1281n/a * back to locating the correct installed python.
1282n/a */
1283n/a }
1284n/a if (*command && !validate_version(command))
1285n/a error(RC_BAD_VIRTUAL_PATH, L"Invalid version \
1286n/aspecification: '%ls'.\nIn the first line of the script, 'python' needs to be \
1287n/afollowed by a valid version specifier.\nPlease check the documentation.",
1288n/a command);
1289n/a /* TODO could call validate_version(command) */
1290n/a ip = locate_python(command, TRUE);
1291n/a if (ip == NULL) {
1292n/a error(RC_NO_PYTHON, L"Requested Python version \
1293n/a(%ls) is not installed", command);
1294n/a }
1295n/a else {
1296n/a invoke_child(ip->executable, suffix, cmdline);
1297n/a }
1298n/a }
1299n/a }
1300n/a }
1301n/a }
1302n/a }
1303n/a}
1304n/a
1305n/astatic wchar_t *
1306n/askip_me(wchar_t * cmdline)
1307n/a{
1308n/a BOOL quoted;
1309n/a wchar_t c;
1310n/a wchar_t * result = cmdline;
1311n/a
1312n/a quoted = cmdline[0] == L'\"';
1313n/a if (!quoted)
1314n/a c = L' ';
1315n/a else {
1316n/a c = L'\"';
1317n/a ++result;
1318n/a }
1319n/a result = wcschr(result, c);
1320n/a if (result == NULL) /* when, for example, just exe name on command line */
1321n/a result = L"";
1322n/a else {
1323n/a ++result; /* skip past space or closing quote */
1324n/a result = skip_whitespace(result);
1325n/a }
1326n/a return result;
1327n/a}
1328n/a
1329n/astatic DWORD version_high = 0;
1330n/astatic DWORD version_low = 0;
1331n/a
1332n/astatic void
1333n/aget_version_info(wchar_t * version_text, size_t size)
1334n/a{
1335n/a WORD maj, min, rel, bld;
1336n/a
1337n/a if (!version_high && !version_low)
1338n/a wcsncpy_s(version_text, size, L"0.1", _TRUNCATE); /* fallback */
1339n/a else {
1340n/a maj = HIWORD(version_high);
1341n/a min = LOWORD(version_high);
1342n/a rel = HIWORD(version_low);
1343n/a bld = LOWORD(version_low);
1344n/a _snwprintf_s(version_text, size, _TRUNCATE, L"%d.%d.%d.%d", maj,
1345n/a min, rel, bld);
1346n/a }
1347n/a}
1348n/a
1349n/astatic int
1350n/aprocess(int argc, wchar_t ** argv)
1351n/a{
1352n/a wchar_t * wp;
1353n/a wchar_t * command;
1354n/a wchar_t * executable;
1355n/a wchar_t * p;
1356n/a int rc = 0;
1357n/a size_t plen;
1358n/a INSTALLED_PYTHON * ip;
1359n/a BOOL valid;
1360n/a DWORD size, attrs;
1361n/a HRESULT hr;
1362n/a wchar_t message[MSGSIZE];
1363n/a wchar_t version_text [MAX_PATH];
1364n/a void * version_data;
1365n/a VS_FIXEDFILEINFO * file_info;
1366n/a UINT block_size;
1367n/a int index;
1368n/a#if defined(SCRIPT_WRAPPER)
1369n/a int newlen;
1370n/a wchar_t * newcommand;
1371n/a wchar_t * av[2];
1372n/a#endif
1373n/a
1374n/a setvbuf(stderr, (char *)NULL, _IONBF, 0);
1375n/a wp = get_env(L"PYLAUNCH_DEBUG");
1376n/a if ((wp != NULL) && (*wp != L'\0'))
1377n/a log_fp = stderr;
1378n/a
1379n/a#if defined(_M_X64)
1380n/a debug(L"launcher build: 64bit\n");
1381n/a#else
1382n/a debug(L"launcher build: 32bit\n");
1383n/a#endif
1384n/a#if defined(_WINDOWS)
1385n/a debug(L"launcher executable: Windows\n");
1386n/a#else
1387n/a debug(L"launcher executable: Console\n");
1388n/a#endif
1389n/a /* Get the local appdata folder (non-roaming) */
1390n/a hr = SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA,
1391n/a NULL, 0, appdata_ini_path);
1392n/a if (hr != S_OK) {
1393n/a debug(L"SHGetFolderPath failed: %X\n", hr);
1394n/a appdata_ini_path[0] = L'\0';
1395n/a }
1396n/a else {
1397n/a plen = wcslen(appdata_ini_path);
1398n/a p = &appdata_ini_path[plen];
1399n/a wcsncpy_s(p, MAX_PATH - plen, L"\\py.ini", _TRUNCATE);
1400n/a attrs = GetFileAttributesW(appdata_ini_path);
1401n/a if (attrs == INVALID_FILE_ATTRIBUTES) {
1402n/a debug(L"File '%ls' non-existent\n", appdata_ini_path);
1403n/a appdata_ini_path[0] = L'\0';
1404n/a } else {
1405n/a debug(L"Using local configuration file '%ls'\n", appdata_ini_path);
1406n/a }
1407n/a }
1408n/a plen = GetModuleFileNameW(NULL, launcher_ini_path, MAX_PATH);
1409n/a size = GetFileVersionInfoSizeW(launcher_ini_path, &size);
1410n/a if (size == 0) {
1411n/a winerror(GetLastError(), message, MSGSIZE);
1412n/a debug(L"GetFileVersionInfoSize failed: %ls\n", message);
1413n/a }
1414n/a else {
1415n/a version_data = malloc(size);
1416n/a if (version_data) {
1417n/a valid = GetFileVersionInfoW(launcher_ini_path, 0, size,
1418n/a version_data);
1419n/a if (!valid)
1420n/a debug(L"GetFileVersionInfo failed: %X\n", GetLastError());
1421n/a else {
1422n/a valid = VerQueryValueW(version_data, L"\\",
1423n/a (LPVOID *) &file_info, &block_size);
1424n/a if (!valid)
1425n/a debug(L"VerQueryValue failed: %X\n", GetLastError());
1426n/a else {
1427n/a version_high = file_info->dwFileVersionMS;
1428n/a version_low = file_info->dwFileVersionLS;
1429n/a }
1430n/a }
1431n/a free(version_data);
1432n/a }
1433n/a }
1434n/a p = wcsrchr(launcher_ini_path, L'\\');
1435n/a if (p == NULL) {
1436n/a debug(L"GetModuleFileNameW returned value has no backslash: %ls\n",
1437n/a launcher_ini_path);
1438n/a launcher_ini_path[0] = L'\0';
1439n/a }
1440n/a else {
1441n/a wcsncpy_s(p, MAX_PATH - (p - launcher_ini_path), L"\\py.ini",
1442n/a _TRUNCATE);
1443n/a attrs = GetFileAttributesW(launcher_ini_path);
1444n/a if (attrs == INVALID_FILE_ATTRIBUTES) {
1445n/a debug(L"File '%ls' non-existent\n", launcher_ini_path);
1446n/a launcher_ini_path[0] = L'\0';
1447n/a } else {
1448n/a debug(L"Using global configuration file '%ls'\n", launcher_ini_path);
1449n/a }
1450n/a }
1451n/a
1452n/a command = skip_me(GetCommandLineW());
1453n/a debug(L"Called with command line: %ls\n", command);
1454n/a
1455n/a#if defined(SCRIPT_WRAPPER)
1456n/a /* The launcher is being used in "script wrapper" mode.
1457n/a * There should therefore be a Python script named <exename>-script.py in
1458n/a * the same directory as the launcher executable.
1459n/a * Put the script name into argv as the first (script name) argument.
1460n/a */
1461n/a
1462n/a /* Get the wrapped script name - if the script is not present, this will
1463n/a * terminate the program with an error.
1464n/a */
1465n/a locate_wrapped_script();
1466n/a
1467n/a /* Add the wrapped script to the start of command */
1468n/a newlen = wcslen(wrapped_script_path) + wcslen(command) + 2; /* ' ' + NUL */
1469n/a newcommand = malloc(sizeof(wchar_t) * newlen);
1470n/a if (!newcommand) {
1471n/a error(RC_NO_MEMORY, L"Could not allocate new command line");
1472n/a }
1473n/a else {
1474n/a wcscpy_s(newcommand, newlen, wrapped_script_path);
1475n/a wcscat_s(newcommand, newlen, L" ");
1476n/a wcscat_s(newcommand, newlen, command);
1477n/a debug(L"Running wrapped script with command line '%ls'\n", newcommand);
1478n/a read_commands();
1479n/a av[0] = wrapped_script_path;
1480n/a av[1] = NULL;
1481n/a maybe_handle_shebang(av, newcommand);
1482n/a /* Returns if no shebang line - pass to default processing */
1483n/a command = newcommand;
1484n/a valid = FALSE;
1485n/a }
1486n/a#else
1487n/a if (argc <= 1) {
1488n/a valid = FALSE;
1489n/a p = NULL;
1490n/a }
1491n/a else {
1492n/a p = argv[1];
1493n/a plen = wcslen(p);
1494n/a valid = (*p == L'-') && validate_version(&p[1]);
1495n/a if (valid) {
1496n/a ip = locate_python(&p[1], FALSE);
1497n/a if (ip == NULL)
1498n/a error(RC_NO_PYTHON, L"Requested Python version (%ls) not \
1499n/ainstalled", &p[1]);
1500n/a executable = ip->executable;
1501n/a command += wcslen(p);
1502n/a command = skip_whitespace(command);
1503n/a }
1504n/a else {
1505n/a for (index = 1; index < argc; ++index) {
1506n/a if (*argv[index] != L'-')
1507n/a break;
1508n/a }
1509n/a if (index < argc) {
1510n/a read_commands();
1511n/a maybe_handle_shebang(&argv[index], command);
1512n/a }
1513n/a }
1514n/a }
1515n/a#endif
1516n/a
1517n/a if (!valid) {
1518n/a /* Look for an active virtualenv */
1519n/a executable = find_python_by_venv();
1520n/a
1521n/a /* If we didn't find one, look for the default Python */
1522n/a if (executable == NULL) {
1523n/a ip = locate_python(L"", FALSE);
1524n/a if (ip == NULL)
1525n/a error(RC_NO_PYTHON, L"Can't find a default Python.");
1526n/a executable = ip->executable;
1527n/a }
1528n/a if ((argc == 2) && (!_wcsicmp(p, L"-h") || !_wcsicmp(p, L"--help"))) {
1529n/a#if defined(_M_X64)
1530n/a BOOL canDo64bit = TRUE;
1531n/a#else
1532n/a // If we are a 32bit process on a 64bit Windows, first hit the 64bit keys.
1533n/a BOOL canDo64bit = FALSE;
1534n/a IsWow64Process(GetCurrentProcess(), &canDo64bit);
1535n/a#endif
1536n/a
1537n/a get_version_info(version_text, MAX_PATH);
1538n/a fwprintf(stdout, L"\
1539n/aPython Launcher for Windows Version %ls\n\n", version_text);
1540n/a fwprintf(stdout, L"\
1541n/ausage: %ls [ launcher-arguments ] [ python-arguments ] script [ script-arguments ]\n\n", argv[0]);
1542n/a fputws(L"\
1543n/aLauncher arguments:\n\n\
1544n/a-2 : Launch the latest Python 2.x version\n\
1545n/a-3 : Launch the latest Python 3.x version\n\
1546n/a-X.Y : Launch the specified Python version\n", stdout);
1547n/a if (canDo64bit) {
1548n/a fputws(L"\
1549n/a-X.Y-32: Launch the specified 32bit Python version", stdout);
1550n/a }
1551n/a fputws(L"\n\nThe following help text is from Python:\n\n", stdout);
1552n/a fflush(stdout);
1553n/a }
1554n/a }
1555n/a invoke_child(executable, NULL, command);
1556n/a return rc;
1557n/a}
1558n/a
1559n/a#if defined(_WINDOWS)
1560n/a
1561n/aint WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
1562n/a LPWSTR lpstrCmd, int nShow)
1563n/a{
1564n/a return process(__argc, __wargv);
1565n/a}
1566n/a
1567n/a#else
1568n/a
1569n/aint cdecl wmain(int argc, wchar_t ** argv)
1570n/a{
1571n/a return process(argc, argv);
1572n/a}
1573n/a
1574n/a#endif