Debian Codegraph @

PC/launcher.c

raw symbols SCIP
1 /*
2 * Copyright (C) 2011-2022 Vinay Sajip. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are met:
6 *
7 * 1. Redistributions of source code must retain the above copyright notice,
8 * this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright notice,
10 * this list of conditions and the following disclaimer in the documentation
11 * and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
14 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
17 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
23 * POSSIBILITY OF SUCH DAMAGE.
24 */
25
26 #ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista.
27 #define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows.
28 #endif
29
30 #include <stdio.h>
31 #include <io.h>
32 #include <stdlib.h>
33 #include <windows.h>
34 #include <Shlwapi.h>
35
36 #pragma comment (lib, "Shlwapi.lib")
37
38 #define APPENDED_ARCHIVE
39 #define USE_ENVIRONMENT
40 #define SUPPORT_RELATIVE_PATH
41
42 #define MSGSIZE 1024
43
44 #if !defined(APPENDED_ARCHIVE)
45
46 static wchar_t suffix[] = {
47 #if defined(_CONSOLE)
48 L"-script.py"
49 #else
50 L"-script.pyw"
51 #endif
52 };
53
54 #endif
55
56 #if defined(SUPPORT_RELATIVE_PATH)
57
58 #define RELATIVE_PREFIX L"<launcher_dir>\\"
59 #define RELATIVE_PREFIX_LENGTH 15
60
61 #endif
62
63 #if !defined(_CONSOLE)
64
65 typedef int (__stdcall *MSGBOXWAPIA)(IN HWND hWnd,
66 IN LPCSTR lpText, IN LPCSTR lpCaption,
67 IN UINT uType, IN WORD wLanguageId, IN DWORD dwMilliseconds);
68
69 typedef int (__stdcall *MSGBOXWAPIW)(IN HWND hWnd,
70 IN LPWSTR lpText, IN LPWSTR lpCaption,
71 IN UINT uType, IN WORD wLanguageId, IN DWORD dwMilliseconds);
72
73 #define MB_TIMEDOUT 32000
74
75 int MessageBoxTimeoutA(HWND hWnd, LPCSTR lpText,
76 LPCSTR lpCaption, UINT uType, WORD wLanguageId, DWORD dwMilliseconds)
77 {
78 static MSGBOXWAPIA MsgBoxTOA = NULL;
79 HMODULE hUser = LoadLibraryA("user32.dll");
80
81 if (!MsgBoxTOA) {
82 if (hUser)
83 MsgBoxTOA = (MSGBOXWAPIA)GetProcAddress(hUser,
84 "MessageBoxTimeoutA");
85 else {
86 /*
87 * stuff happened, add code to handle it here
88 * (possibly just call MessageBox())
89 */
90 }
91 }
92
93 if (MsgBoxTOA)
94 return MsgBoxTOA(hWnd, lpText, lpCaption, uType, wLanguageId,
95 dwMilliseconds);
96 if (hUser)
97 FreeLibrary(hUser);
98 return 0;
99 }
100
101 int MessageBoxTimeoutW(HWND hWnd, LPWSTR lpText,
102 LPWSTR lpCaption, UINT uType, WORD wLanguageId, DWORD dwMilliseconds)
103 {
104 static MSGBOXWAPIW MsgBoxTOW = NULL;
105 HMODULE hUser = LoadLibraryA("user32.dll");
106
107 if (!MsgBoxTOW) {
108 if (hUser)
109 MsgBoxTOW = (MSGBOXWAPIW)GetProcAddress(hUser,
110 "MessageBoxTimeoutW");
111 else {
112 /*
113 * stuff happened, add code to handle it here
114 * (possibly just call MessageBox())
115 */
116 }
117 }
118
119 if (MsgBoxTOW)
120 return MsgBoxTOW(hWnd, lpText, lpCaption, uType, wLanguageId,
121 dwMilliseconds);
122 if (hUser)
123 FreeLibrary(hUser);
124 return 0;
125 }
126
127 #endif
128
129 static void
130 wassert(BOOL condition, wchar_t * format, ... )
131 {
132 if (!condition) {
133 va_list va;
134 wchar_t message[MSGSIZE];
135 int len;
136
137 va_start(va, format);
138 len = _vsnwprintf_s(message, MSGSIZE, MSGSIZE - 1, format, va);
139 #if defined(_CONSOLE)
140 fwprintf(stderr, L"Fatal error in launcher: %s\n", message);
141 #else
142 MessageBoxTimeoutW(NULL, message, L"Fatal Error in Launcher",
143 MB_OK | MB_SETFOREGROUND | MB_ICONERROR,
144 0, 3000);
145 #endif
146 ExitProcess(1);
147 }
148 }
149
150 static void
151 assert(BOOL condition, char * format, ... )
152 {
153 if (!condition) {
154 va_list va;
155 char message[MSGSIZE];
156 int len;
157
158 va_start(va, format);
159 len = vsnprintf_s(message, MSGSIZE, MSGSIZE - 1, format, va);
160 #if defined(_CONSOLE)
161 fprintf(stderr, "Fatal error in launcher: %s\n", message);
162 #else
163 MessageBoxTimeoutA(NULL, message, "Fatal Error in Launcher",
164 MB_OK | MB_SETFOREGROUND | MB_ICONERROR,
165 0, 3000);
166 #endif
167 ExitProcess(1);
168 }
169 }
170
171 static wchar_t script_path[MAX_PATH];
172
173 #if defined(APPENDED_ARCHIVE)
174
175 #define LARGE_BUFSIZE (65 * 1024 * 1024)
176
177 typedef struct {
178 DWORD sig;
179 DWORD unused_disk_nos;
180 DWORD unused_numrecs;
181 DWORD cdsize;
182 DWORD cdoffset;
183 } ENDCDR;
184
185 /* We don't want to pick up this variable when scanning the executable.
186 * So we initialise it statically, but fill in the first byte later.
187 */
188 static char
189 end_cdr_sig [4] = { 0x00, 0x4B, 0x05, 0x06 };
190
191 static char *
192 find_pattern(char *buffer, size_t bufsize, char * pattern, size_t patsize)
193 {
194 char * result = NULL;
195 char * p;
196 char * bp = buffer;
197 size_t n;
198
199 while ((n = bufsize - (bp - buffer) - patsize) >= 0) {
200 p = (char *) memchr(bp, pattern[0], n);
201 if (p == NULL)
202 break;
203 if (memcmp(pattern, p, patsize) == 0) {
204 result = p; /* keep trying - we want the last one */
205 }
206 bp = p + 1;
207 }
208 return result;
209 }
210
211 static char *
212 find_shebang(char * buffer, size_t bufsize)
213 {
214 FILE * fp = NULL;
215 errno_t rc;
216 char * result = NULL;
217 char * p;
218 size_t read;
219 long pos;
220 __int64 file_size;
221 __int64 end_cdr_offset = -1;
222 ENDCDR end_cdr;
223
224 rc = _wfopen_s(&fp, script_path, L"rb");
225 assert(rc == 0, "Failed to open executable");
226 fseek(fp, 0, SEEK_END);
227 file_size = ftell(fp);
228 pos = (long) (file_size - bufsize);
229 if (pos < 0)
230 pos = 0;
231 fseek(fp, pos, SEEK_SET);
232 read = fread(buffer, sizeof(char), bufsize, fp);
233 p = find_pattern(buffer, read, end_cdr_sig, sizeof(end_cdr_sig));
234 if (p != NULL) {
235 end_cdr = *((ENDCDR *) p);
236 end_cdr_offset = pos + (p - buffer);
237 }
238 else {
239 /*
240 * Try a larger buffer. A comment can only be 64K long, so
241 * go for the largest size.
242 */
243 char * big_buffer = malloc(LARGE_BUFSIZE);
244 int n = (int) LARGE_BUFSIZE;
245
246 pos = (long) (file_size - n);
247
248 if (pos < 0)
249 pos = 0;
250 fseek(fp, pos, SEEK_SET);
251 read = fread(big_buffer, sizeof(char), n, fp);
252 p = find_pattern(big_buffer, read, end_cdr_sig, sizeof(end_cdr_sig));
253 assert(p != NULL, "Unable to find an appended archive.");
254 end_cdr = *((ENDCDR *) p);
255 end_cdr_offset = pos + (p - big_buffer);
256 free(big_buffer);
257 }
258 end_cdr_offset -= end_cdr.cdsize + end_cdr.cdoffset;
259 /*
260 * end_cdr_offset should now be pointing to the start of the archive.
261 * However, the "start of the archive" is a little ill-defined, as
262 * not all means of prepending data to a zipfile handle the central
263 * directory offset the same way (simple file content appends leave
264 * it alone, obviously, but the stdlib zipapp and zipfile modules
265 * reflect the prepended data in the offset).
266 * We consider two possibilities here:
267 * 1. end_cdr_offset points to the start of the shebang (zipapp)
268 * 2. end_cdr_offset points to the end of the shebang (data copy)
269 * We'll assume the shebang line has no # or ! chars except at the
270 * beginning, and fits into bufsize (which should be MAX_PATH).
271 */
272
273 /* Check for case 1 - we are at the start of the shebang */
274 fseek(fp, (long) end_cdr_offset, SEEK_SET);
275 read = fread(buffer, sizeof(char), bufsize, fp);
276 assert(read > 0, "Unable to read from file");
277 if (memcmp(buffer, "#!", 2) == 0) {
278 result = buffer;
279 }
280 else {
281 /* We are not at the start, so check backward bufsize bytes */
282 pos = (long) (end_cdr_offset - bufsize);
283 if (pos < 0)
284 pos = 0;
285 fseek(fp, pos, SEEK_SET);
286 read = fread(buffer, sizeof(char), bufsize, fp);
287 assert(read > 0, "Unable to read from file");
288 p = &buffer[read - 1];
289 while (p >= buffer) {
290 if (memcmp(p, "#!", 2) == 0) {
291 result = p;
292 break;
293 }
294 --p;
295 }
296 }
297 fclose(fp);
298 return result;
299 }
300
301 #endif
302
303 #if defined(USE_ENVIRONMENT)
304 /*
305 * Where to place any executable found on the path. Should be OK to use a
306 * static as there's only one of these per invocation of this executable.
307 */
308 static wchar_t path_executable[MSGSIZE];
309
310 static BOOL find_on_path(wchar_t * name)
311 {
312 wchar_t * pathext;
313 size_t varsize;
314 wchar_t * context = NULL;
315 wchar_t * extension;
316 DWORD len;
317 errno_t rc;
318 BOOL found = FALSE;
319
320 if (wcschr(name, L'.') != NULL) {
321 /* assume it has an extension. */
322 if (SearchPathW(NULL, name, NULL, MSGSIZE, path_executable, NULL))
323 found = TRUE;
324 }
325 else {
326 /* No extension - search using registered extensions. */
327 rc = _wdupenv_s(&pathext, &varsize, L"PATHEXT");
328 _wcslwr_s(pathext, varsize);
329 if (rc == 0) {
330 extension = wcstok_s(pathext, L";", &context);
331 while (extension) {
332 len = SearchPathW(NULL, name, extension, MSGSIZE, path_executable, NULL);
333 if (len) {
334 found = TRUE;
335 break;
336 }
337 extension = wcstok_s(NULL, L";", &context);
338 }
339 free(pathext);
340 }
341 }
342 return found;
343 }
344
345 /*
346 * Find an executable in the environment. For now, we just look in the path,
347 * but potentially we could expand this to look in the registry, etc.
348 */
349 static wchar_t *
350 find_environment_executable(wchar_t * line) {
351 BOOL found = find_on_path(line);
352
353 return found ? path_executable : NULL;
354 }
355
356 #endif
357
358 static wchar_t *
359 skip_ws(wchar_t *p)
360 {
361 while (*p && iswspace(*p))
362 ++p;
363 return p;
364 }
365
366 static wchar_t *
367 skip_me(wchar_t * p)
368 {
369 wchar_t * result;
370 wchar_t terminator;
371
372 if (*p != L'\"')
373 terminator = L' ';
374 else {
375 terminator = *p++;
376 ++p;
377 }
378 result = wcschr(p, terminator);
379 if (result == NULL) /* perhaps nothing more on the command line */
380 result = L"";
381 else
382 result = skip_ws(++result);
383 return result;
384 }
385
386 static char *
387 find_terminator(char *buffer, size_t size)
388 {
389 char c;
390 char * result = NULL;
391 char * end = buffer + size;
392 char * p;
393
394 for (p = buffer; p < end; p++) {
395 c = *p;
396 if (c == '\r') {
397 result = p;
398 break;
399 }
400 if (c == '\n') {
401 result = p;
402 break;
403 }
404 }
405 return result;
406 }
407
408 #if defined(DUPLICATE_HANDLES)
409
410 static BOOL
411 safe_duplicate_handle(HANDLE in, HANDLE * pout)
412 {
413 BOOL ok;
414 HANDLE process = GetCurrentProcess();
415 #if defined(_CONSOLE)
416 DWORD rc;
417 #endif
418
419 *pout = NULL;
420 /*
421 * See https://github.com/pypa/pip/issues/10444 - for the GUI launcher,
422 * errors are returned by DuplicateHandle. There may be no good reason
423 * why a GUI process would want to use these handles, but for now we
424 * attempt duplication but ignore errors in the GUI case.
425 */
426 ok = DuplicateHandle(process, in, process, pout, 0, TRUE,
427 DUPLICATE_SAME_ACCESS);
428 #if defined(_CONSOLE)
429 if (!ok) {
430 rc = GetLastError();
431 if (rc == ERROR_INVALID_HANDLE)
432 ok = TRUE;
433 }
434 return ok;
435 #else
436 return TRUE;
437 #endif
438 }
439
440 #endif
441
442 /*
443 * These items are global so that thet can be accessed
444 * from the Ctrl-C handler or other auxiliary routine.
445 */
446 static PROCESS_INFORMATION child_process_info;
447 static JOBOBJECT_EXTENDED_LIMIT_INFORMATION job_info;
448 static HANDLE job;
449
450 static BOOL
451 control_key_handler(DWORD type)
452 {
453 /*
454 * See https://github.com/pypa/pip/issues/10444
455 */
456 #if defined(OLD_LOGIC)
457 if ((type == CTRL_C_EVENT) || (type == CTRL_BREAK_EVENT)) {
458 return TRUE;
459 }
460 WaitForSingleObject(child_process_info.hProcess, INFINITE);
461 #else
462 switch (type) {
463 case CTRL_CLOSE_EVENT:
464 case CTRL_LOGOFF_EVENT:
465 case CTRL_SHUTDOWN_EVENT:
466 /*
467 * Allow the child to outlive the launcher, to carry out any
468 * cleanup for a graceful exit. It will either exit or get
469 * terminated by the session server.
470 */
471 if (job != NULL) {
472 job_info.BasicLimitInformation.LimitFlags &=
473 ~JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
474 SetInformationJobObject(
475 job, JobObjectExtendedLimitInformation,
476 &job_info, sizeof(job_info));
477 }
478 }
479 #endif
480 return TRUE;
481 }
482
483 #if !defined(_CONSOLE)
484
485 /*
486 * End the launcher's "app starting" cursor state.
487 *
488 * When Explorer launches a Windows (GUI) application, it displays
489 * the "app starting" (the "pointer + hourglass") cursor for a number
490 * of seconds, or until the app does something UI-ish (eg, creating a
491 * window, or fetching a message). As this launcher doesn't do this
492 * directly, that cursor remains even after the child process does these
493 * things. We avoid that by doing the stuff in here.
494 * See http://bugs.python.org/issue17290 and
495 * https://github.com/pypa/pip/issues/10444#issuecomment-973408601
496 */
497
498 static void
499 clear_app_starting_state() {
500 MSG msg;
501 HWND hwnd;
502
503 PostMessageW(0, 0, 0, 0);
504 GetMessageW(&msg, 0, 0, 0);
505 /* Proxy the child's input idle event. */
506 WaitForInputIdle(child_process_info.hProcess, INFINITE);
507 /*
508 * Signal the process input idle event by creating a window and pumping
509 * sent messages. The window class isn't important, so just use the
510 * system "STATIC" class.
511 */
512 hwnd = CreateWindowExW(0, L"STATIC", L"PyLauncher", 0, 0, 0, 0, 0,
513 HWND_MESSAGE, NULL, NULL, NULL);
514 /* Process all sent messages and signal input idle. */
515 PeekMessageW(&msg, hwnd, 0, 0, 0);
516 DestroyWindow(hwnd);
517 }
518
519 #endif
520
521 /*
522 * See https://github.com/pypa/pip/issues/10444#issuecomment-1055392299
523 */
524 static BOOL
525 make_handle_inheritable(HANDLE handle)
526 {
527 DWORD file_type = GetFileType(handle);
528 // Ignore an invalid handle, non-file object type, unsupported file type,
529 // or a console file prior to Windows 8.
530 if (file_type == FILE_TYPE_UNKNOWN ||
531 (file_type == FILE_TYPE_CHAR && ((ULONG_PTR)handle & 3))) {
532 return TRUE;
533 }
534
535 return SetHandleInformation(handle, HANDLE_FLAG_INHERIT,
536 HANDLE_FLAG_INHERIT);
537 }
538
539 static void
540 __cdecl
541 silent_invalid_parameter_handler(
542 wchar_t const* expression,
543 wchar_t const* function,
544 wchar_t const* file,
545 unsigned int line,
546 uintptr_t pReserved
547 )
548 {
549 }
550
551 /*
552 * Best-effort cleanup of any C file descriptors that were inherited
553 * from the parent process. This cleans up all fds except 0-2.
554 */
555 static void
556 cleanup_fds(WORD cbReserved2, LPBYTE lpReserved2)
557 {
558 int handle_count = 0;
559 UNALIGNED HANDLE* first_handle = NULL;
560 UNALIGNED HANDLE* current_handle = NULL;
561 _invalid_parameter_handler old_handler = NULL;
562
563 // The structure is: <handle_count>, <handle_count bytes with flags>, <handle_count HANDLEs>
564
565 if (cbReserved2 < sizeof(int) || NULL == lpReserved2)
566 {
567 return;
568 }
569
570 handle_count = *(UNALIGNED int*)lpReserved2;
571
572 // Verify the buffer is large enough
573 if (cbReserved2 < sizeof(int) + handle_count + sizeof(HANDLE) * handle_count)
574 {
575 return;
576 }
577
578 first_handle = (UNALIGNED HANDLE *)(lpReserved2 + sizeof(int) + handle_count);
579
580 old_handler = _set_invalid_parameter_handler(&silent_invalid_parameter_handler);
581 {
582 // Close all fds inherited from the parent, except for the standard I/O fds.
583 // We'll deal with those later.
584 for (current_handle = first_handle + 3; current_handle < first_handle + handle_count; ++current_handle)
585 {
586 // Ignore invalid handles, as that means this fd was not inherited.
587 // -2 is a special value (https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/get-osfhandle?view=msvc-170)
588 // that we check for just in case.
589 if (NULL == *current_handle || INVALID_HANDLE_VALUE == *current_handle || (HANDLE)-2 == *current_handle)
590 {
591 continue;
592 }
593
594 _close((int)(current_handle - first_handle));
595 }
596 }
597 _set_invalid_parameter_handler(old_handler);
598 }
599
600 /*
601 * Returns the HANDLE associated with a FILE* object, or INVALID_HANDLE_VALUE
602 * on error.
603 */
604 static HANDLE
605 get_stream_handle(FILE * stream)
606 {
607 _invalid_parameter_handler old_handler = NULL;
608 int fd = -1;
609 HANDLE handle = INVALID_HANDLE_VALUE;
610
611 old_handler = _set_invalid_parameter_handler(&silent_invalid_parameter_handler);
612 {
613 fd = _fileno(stream);
614 if (fd >= 0)
615 {
616 handle = (HANDLE)_get_osfhandle(fd);
617 }
618 else
619 {
620 handle = INVALID_HANDLE_VALUE;
621 }
622 }
623 _set_invalid_parameter_handler(old_handler);
624
625 return handle;
626 }
627
628 /*
629 * Closes the Windows standard I/O handles (GetStdHandle)
630 * in a best-effort manner. Ensures that the stderr stream is left untouched.
631 */
632 static void
633 cleanup_standard_io(void)
634 {
635 HANDLE stdin_handle = INVALID_HANDLE_VALUE;
636 HANDLE stdout_handle = INVALID_HANDLE_VALUE;
637 HANDLE stderr_handle = INVALID_HANDLE_VALUE;
638 HANDLE hStdIn = INVALID_HANDLE_VALUE;
639 HANDLE hStdOut = INVALID_HANDLE_VALUE;
640 HANDLE hStdErr = INVALID_HANDLE_VALUE;
641
642 // We need to close both the C streams stdin and stdout,
643 // and the Windows standard I/O handles. However, these may be equal,
644 // so care must be taken not to close a handle twice. Moreover,
645 // handles for several C streams may be equal as well.
646 // Fun all around.
647
648 // Get the handles associated with the standard I/O streams.
649 stdin_handle = get_stream_handle(stdin);
650 stdout_handle = get_stream_handle(stdout);
651 stderr_handle = get_stream_handle(stderr);
652
653 // If any two underlying handles are equal, drop everything and return.
654 // There's bound to be trouble if we continue with closing the streams.
655 if (((INVALID_HANDLE_VALUE != stdin_handle) && (stdin_handle == stdout_handle || stdin_handle == stderr_handle))
656 || ((INVALID_HANDLE_VALUE != stdout_handle) && (stdout_handle == stdin_handle || stdout_handle == stderr_handle))
657 || ((INVALID_HANDLE_VALUE != stderr_handle) && (stderr_handle == stdin_handle || stderr_handle == stdout_handle)))
658 {
659 return;
660 }
661
662 // Get the Windows I/O handles before we do anything.
663 hStdIn = GetStdHandle(STD_INPUT_HANDLE);
664 hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
665 hStdErr = GetStdHandle(STD_ERROR_HANDLE);
666
667 // At this point, we have confirmed that the I/O streams all have different
668 // handles, and we have the Windows standard I/O handles as well.
669 // Proceed with closing the streams.
670
671 fclose(stdin);
672 fclose(stdout);
673
674 // Now we need to close the Windows standard I/O handles, as they might
675 // differ from the handles for the C streams.
676
677 // First, make sure we don't close handles that we have already closed
678 // by closing the streams.
679 if (stdin_handle == hStdIn || stdout_handle == hStdIn)
680 {
681 SetStdHandle(STD_INPUT_HANDLE, NULL);
682 hStdIn = NULL;
683 }
684 if (stdin_handle == hStdOut || stdout_handle == hStdOut)
685 {
686 SetStdHandle(STD_OUTPUT_HANDLE, NULL);
687 hStdOut = NULL;
688 }
689 if (stdin_handle == hStdErr || stdout_handle == hStdErr)
690 {
691 SetStdHandle(STD_ERROR_HANDLE, NULL);
692 hStdErr = NULL;
693 }
694
695 // Ensure we don't accidentally close the standard error handle.
696 if (stderr_handle == hStdIn)
697 {
698 hStdIn = NULL;
699 }
700 if (stderr_handle == hStdOut)
701 {
702 hStdOut = NULL;
703 }
704 if (stderr_handle == hStdErr)
705 {
706 hStdErr = NULL;
707 }
708
709 // Close 'em.
710 if (NULL != hStdIn && INVALID_HANDLE_VALUE != hStdIn)
711 {
712 CloseHandle(hStdIn);
713 SetStdHandle(STD_INPUT_HANDLE, NULL);
714 }
715 if (NULL != hStdOut && INVALID_HANDLE_VALUE != hStdOut)
716 {
717 CloseHandle(hStdOut);
718 SetStdHandle(STD_OUTPUT_HANDLE, NULL);
719 }
720 if (NULL != hStdErr && INVALID_HANDLE_VALUE != hStdErr)
721 {
722 CloseHandle(hStdErr);
723 SetStdHandle(STD_ERROR_HANDLE, NULL);
724 }
725 }
726
727 #define SWITCH_WORKING_DIR
728
729 #if defined(SWITCH_WORKING_DIR)
730
731 /*
732 * Switch the working directory to the user's temp directory.
733 */
734
735 static void
736 switch_working_directory() {
737 WCHAR tempDir[MAX_PATH + 1];
738 DWORD len = GetTempPathW(MAX_PATH + 1, tempDir);
739 if (len > 0 && len <= MAX_PATH) {
740 SetCurrentDirectoryW(tempDir);
741 }
742 }
743 #endif
744
745 /*
746 * Best-effort cleanup of file descriptors and handles after spawning the child
747 * process.
748 * See discussion starting from here: https://github.com/pypa/pip/issues/10444#issuecomment-1055392299
749 */
750 static void
751 post_spawn_cleanup(WORD cbReserved2, LPBYTE lpReserved2)
752 {
753 cleanup_fds(cbReserved2, lpReserved2);
754
755 cleanup_standard_io();
756 #if defined(SWITCH_WORKING_DIR)
757 switch_working_directory();
758 #endif
759 }
760
761 /*
762 * See https://github.com/pypa/pip/issues/10444#issuecomment-971921420
763 */
764 #define STARTF_UNDOC_MONITOR 0x400
765 /*
766 * See https://github.com/pypa/pip/issues/10444#issuecomment-973396812
767 */
768
769 static void
770 run_child(wchar_t * cmdline)
771 {
772 DWORD rc;
773 BOOL ok;
774 STARTUPINFOW si;
775
776 job = CreateJobObject(NULL, NULL);
777 assert(job != NULL, "Job creation failed");
778 ok = QueryInformationJobObject(job, JobObjectExtendedLimitInformation,
779 &job_info, sizeof(job_info), &rc);
780 assert(ok && (rc == sizeof(job_info)), "Job information querying failed");
781 job_info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE |
782 JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK;
783 ok = SetInformationJobObject(job, JobObjectExtendedLimitInformation, &job_info,
784 sizeof(job_info));
785 assert(ok, "Job information setting failed");
786 memset(&si, 0, sizeof(si));
787 GetStartupInfoW(&si);
788 /*
789 * See https://github.com/pypa/pip/issues/10444#issuecomment-973396812
790 */
791 if ((si.dwFlags & (STARTF_USEHOTKEY | STARTF_UNDOC_MONITOR)) == 0) {
792 HANDLE hIn = GetStdHandle(STD_INPUT_HANDLE);
793 HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
794 HANDLE hErr = GetStdHandle(STD_ERROR_HANDLE);
795
796 #if defined(DUPLICATE_HANDLES)
797 ok = safe_duplicate_handle(hIn, &si.hStdInput);
798 assert(ok, "stdin duplication failed");
799 CloseHandle(hIn);
800
801 ok = safe_duplicate_handle(hOut, &si.hStdOutput);
802 assert(ok, "stdout duplication failed");
803 CloseHandle(hOut);
804 /* We might need stderr late, so don't close it but mark as non-inheritable */
805 SetHandleInformation(hErr, HANDLE_FLAG_INHERIT, 0);
806
807 ok = safe_duplicate_handle(hErr, &si.hStdError);
808 assert(ok, "stderr duplication failed");
809 #else
810 /*
811 * See https://github.com/pypa/pip/issues/10444#issuecomment-1055392299
812 */
813 ok = make_handle_inheritable(hIn);
814 assert(ok, "making stdin inheritable failed");
815 ok = make_handle_inheritable(hOut);
816 assert(ok, "making stdout inheritable failed");
817 ok = make_handle_inheritable(hErr);
818 assert(ok, "making stderr inheritable failed");
819 si.hStdInput = hIn;
820 si.hStdOutput = hOut;
821 si.hStdError = hErr;
822 #endif
823 si.dwFlags |= STARTF_USESTDHANDLES;
824 }
825 ok = CreateProcessW(NULL, cmdline, NULL, NULL, TRUE, 0, NULL, NULL, &si, &child_process_info);
826 if (!ok) {
827 // Failed to create process. See if we can find out why.
828 DWORD err = GetLastError();
829 wchar_t emessage[MSGSIZE];
830 FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err,
831 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), emessage, MSGSIZE, NULL);
832 wassert(ok, L"Unable to create process using '%ls': %ls", cmdline, emessage);
833 }
834 // Assign the process to the job straight away. See https://github.com/pypa/distlib/issues/175
835 AssignProcessToJobObject(job, child_process_info.hProcess);
836 post_spawn_cleanup(si.cbReserved2, si.lpReserved2);
837 /*
838 * Control handler setting is now done after process creation because the handler needs access
839 * to the child_process_info structure, which is populated by the CreateProcessW call above.
840 */
841 ok = SetConsoleCtrlHandler((PHANDLER_ROUTINE) control_key_handler, TRUE);
842 assert(ok, "control handler setting failed");
843 #if !defined(_CONSOLE)
844 clear_app_starting_state(&child_process_info);
845 #endif
846 CloseHandle(child_process_info.hThread);
847 WaitForSingleObjectEx(child_process_info.hProcess, INFINITE, FALSE);
848 ok = GetExitCodeProcess(child_process_info.hProcess, &rc);
849 assert(ok, "Failed to get exit code of process");
850 ExitProcess(rc);
851 }
852
853 static wchar_t *
854 find_exe_extension(wchar_t * line) {
855 wchar_t * p;
856
857 while ((p = StrStrIW(line, L".exe")) != NULL) {
858 wchar_t c = p[4];
859
860 if ((c == L'\0') || (c == L'"') || iswspace(c))
861 break;
862 line = &p[4];
863 }
864 return p;
865 }
866
867 static wchar_t *
868 find_executable_and_args(wchar_t * line, wchar_t ** argp)
869 {
870 wchar_t * p = find_exe_extension(line);
871 #if defined(USE_ENVIRONMENT)
872 wchar_t * q;
873 int n;
874 #endif
875 wchar_t * result;
876
877 #if !defined(USE_ENVIRONMENT)
878 assert(p != NULL, "Expected to find a command ending in '.exe' in shebang line: %ls", line);
879 p += 4; /* skip past the '.exe' */
880 result = line;
881 #else
882 if (p != NULL) {
883 p += 4; /* skip past the '.exe' */
884 result = line;
885 }
886 else {
887 n = _wcsnicmp(line, L"/usr/bin/env", 12);
888 assert(n == 0, "Expected to find a command ending in '.exe' in shebang line: %ls", line);
889 p = line + 12; /* past the '/usr/bin/env' */
890 assert(*p && iswspace(*p), "Expected to find whitespace after '/usr/bin/env': %ls", line);
891 do {
892 ++p;
893 } while (*p && iswspace(*p));
894 /* Now, p points to what comes after /usr/bin/env and any following whitespace. */
895 q = p;
896 /* Skip past executable name and NUL-terminate it. */
897 while (*q && !iswspace(*q))
898 ++q;
899 if (iswspace(*q))
900 *q++ = L'\0';
901 result = find_environment_executable(p);
902 assert(result != NULL, "Unable to find executable in environment: %ls", line);
903 p = q; /* point past name of executable in shebang */
904 }
905 #endif
906 if (*line == L'"') {
907 assert(*p == L'"', "Expected terminating double-quote for executable in shebang line: %ls", line);
908 *p++ = L'\0';
909 ++line;
910 ++result; /* See https://bitbucket.org/pypa/distlib/issues/104 */
911 }
912 /* p points just past the executable. It must either be a NUL or whitespace. */
913 #if !defined(SUPPORT_RELATIVE_PATH)
914 assert(*p != L'"', "Terminating quote without starting quote for executable in shebang line: %ls", line);
915 #else
916 if (_wcsnicmp(line, RELATIVE_PREFIX, RELATIVE_PREFIX_LENGTH) && (line[RELATIVE_PREFIX_LENGTH] != L'\"')) {
917 assert(*p != L'"', "Terminating quote without starting quote for executable in shebang line: %ls", line);
918 }
919 #endif
920 /* if p is whitespace, make it NUL to truncate 'line', and advance */
921 if (*p && iswspace(*p))
922 *p++ = L'\0';
923 /* Now we can skip the whitespace, having checked that it's there. */
924 while(*p && iswspace(*p))
925 ++p;
926 *argp = p;
927 return result;
928 }
929
930 static int
931 process(int argc, char * argv[])
932 {
933 wchar_t * cmdline = skip_me(GetCommandLineW());
934 wchar_t * psp;
935 size_t len = GetModuleFileNameW(NULL, script_path, MAX_PATH);
936 FILE *fp = NULL;
937 char buffer[MAX_PATH];
938 wchar_t wbuffer[MAX_PATH];
939 #if defined(SUPPORT_RELATIVE_PATH)
940 wchar_t dbuffer[MAX_PATH];
941 wchar_t pbuffer[MAX_PATH];
942 wchar_t * qp;
943 int prefix_offset;
944 #endif
945 char *cp;
946 wchar_t * wcp;
947 wchar_t * cmdp;
948 char * p;
949 wchar_t * wp;
950 int n;
951 #if !defined(APPENDED_ARCHIVE)
952 errno_t rc;
953 #endif
954
955 if (script_path[0] != L'\"')
956 psp = script_path;
957 else {
958 psp = &script_path[1];
959 len -= 2;
960 }
961 psp[len] = L'\0';
962
963 #if !defined(APPENDED_ARCHIVE)
964 /* Replace the .exe with -script.py(w) */
965 wp = wcsstr(psp, L".exe");
966 assert(wp != NULL, "Failed to find \".exe\" in executable name");
967
968 len = MAX_PATH - (wp - script_path);
969 assert(len > sizeof(suffix), "Failed to append \"%ls\" suffix", suffix);
970 wcsncpy_s(wp, len, suffix, sizeof(suffix));
971 #endif
972 #if defined(APPENDED_ARCHIVE)
973 /* Initialise signature dynamically so that it doesn't appear in
974 * a stock executable.
975 */
976 end_cdr_sig[0] = 0x50;
977
978 p = find_shebang(buffer, MAX_PATH);
979 assert(p != NULL, "Failed to find shebang");
980 #else
981 rc = _wfopen_s(&fp, psp, L"rb");
982 assert(rc == 0, "Failed to open script file '%ls'", psp);
983 fread(buffer, sizeof(char), MAX_PATH, fp);
984 fclose(fp);
985 p = buffer;
986 #endif
987 cp = find_terminator(p, MAX_PATH);
988 assert(cp != NULL, "Expected to find terminator in shebang line");
989 *cp = '\0';
990 // Decode as UTF-8
991 n = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, p, (int) (cp - p), wbuffer, MAX_PATH);
992 assert(n != 0, "Expected to decode shebang line using UTF-8");
993 wbuffer[n] = L'\0';
994 wcp = wbuffer;
995 while (*wcp && iswspace(*wcp))
996 ++wcp;
997 assert(*wcp == L'#', "Expected to find \'#\' at start of shebang line");
998 ++wcp;
999 while (*wcp && iswspace(*wcp))
1000 ++wcp;
1001 assert(*wcp == L'!', "Expected to find \'!\' following \'#\' in shebang line");
1002 ++wcp;
1003 while (*wcp && iswspace(*wcp))
1004 ++wcp;
1005 wp = NULL;
1006 wcp = find_executable_and_args(wcp, &wp);
1007 assert(wcp != NULL, "Expected to find executable in shebang line");
1008 assert(wp != NULL, "Expected to find arguments (even if empty) in shebang line");
1009 #if defined(SUPPORT_RELATIVE_PATH)
1010 /*
1011 If the executable starts with the relative prefix, resolve the following path
1012 relative to the launcher's directory.
1013 */
1014 prefix_offset = RELATIVE_PREFIX_LENGTH;
1015 if (!_wcsnicmp(RELATIVE_PREFIX, wcp, prefix_offset)) {
1016 wcscpy_s(dbuffer, MAX_PATH, script_path);
1017 PathRemoveFileSpecW(dbuffer);
1018 if (wcp[prefix_offset] == L'\"') {
1019 prefix_offset++;
1020 qp = wcschr(&wcp[prefix_offset], L'\"');
1021 assert(qp != NULL, "Expected terminating double-quote for executable in shebang line: %ls", wcp);
1022 *qp = L'\0';
1023 }
1024 // The following call appears to canonicalize the path, so no need to
1025 // worry about doing that
1026 PathCombineW(pbuffer, dbuffer, &wcp[prefix_offset]);
1027 wcp = pbuffer;
1028 }
1029 #endif
1030 /* 3 spaces + 4 quotes + NUL */
1031 len = wcslen(wcp) + wcslen(wp) + 8 + wcslen(psp) + wcslen(cmdline);
1032 cmdp = (wchar_t *) calloc(len, sizeof(wchar_t));
1033 assert(cmdp != NULL, "Expected to be able to allocate command line memory");
1034 _snwprintf_s(cmdp, len, len, L"\"%ls\" %ls \"%ls\" %ls", wcp, wp, psp, cmdline);
1035 run_child(cmdp); /* never actually returns */
1036 free(cmdp);
1037 return 0;
1038 }
1039
1040 #if defined(_CONSOLE)
1041
1042 int main(int argc, char* argv[])
1043 {
1044 return process(argc, argv);
1045 }
1046
1047 #else
1048
1049 int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
1050 LPSTR lpCmdLine, int nCmdShow)
1051 {
1052 return process(__argc, __argv);
1053 }
1054
1055 #endif