VirtualBox

source: kBuild/trunk/src/kmk/w32/subproc/sub_proc.c@ 1280

Last change on this file since 1280 was 1167, checked in by bird, 17 years ago

skip some unnecessary system calls during process creation and termination.

  • Property svn:eol-style set to native
File size: 30.8 KB
Line 
1/* Process handling for Windows.
2Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
32006 Free Software Foundation, Inc.
4This file is part of GNU Make.
5
6GNU Make is free software; you can redistribute it and/or modify it under the
7terms of the GNU General Public License as published by the Free Software
8Foundation; either version 2, or (at your option) any later version.
9
10GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
11WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12A PARTICULAR PURPOSE. See the GNU General Public License for more details.
13
14You should have received a copy of the GNU General Public License along with
15GNU Make; see the file COPYING. If not, write to the Free Software
16Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */
17
18#include <stdlib.h>
19#include <stdio.h>
20#include <process.h> /* for msvc _beginthreadex, _endthreadex */
21#include <signal.h>
22#include <windows.h>
23
24#include "sub_proc.h"
25#include "proc.h"
26#include "w32err.h"
27#include "config.h"
28#include "debug.h"
29
30static char *make_command_line(char *shell_name, char *exec_path, char **argv);
31
32typedef struct sub_process_t {
33 int sv_stdin[2];
34 int sv_stdout[2];
35 int sv_stderr[2];
36 int using_pipes;
37 char *inp;
38 DWORD incnt;
39 char * volatile outp;
40 volatile DWORD outcnt;
41 char * volatile errp;
42 volatile DWORD errcnt;
43 int pid;
44 int exit_code;
45 int signal;
46 long last_err;
47 long lerrno;
48} sub_process;
49
50static long process_file_io_private(sub_process *pproc, BOOL fNeedToWait); /* bird */
51
52/* keep track of children so we can implement a waitpid-like routine */
53static sub_process *proc_array[MAXIMUM_WAIT_OBJECTS];
54static int proc_index = 0;
55static int fake_exits_pending = 0;
56
57/*
58 * When a process has been waited for, adjust the wait state
59 * array so that we don't wait for it again
60 */
61static void
62process_adjust_wait_state(sub_process* pproc)
63{
64 int i;
65
66 if (!proc_index)
67 return;
68
69 for (i = 0; i < proc_index; i++)
70 if (proc_array[i]->pid == pproc->pid)
71 break;
72
73 if (i < proc_index) {
74 proc_index--;
75 if (i != proc_index)
76 memmove(&proc_array[i], &proc_array[i+1],
77 (proc_index-i) * sizeof(sub_process*));
78 proc_array[proc_index] = NULL;
79 }
80}
81
82/*
83 * Waits for any of the registered child processes to finish.
84 */
85static sub_process *
86process_wait_for_any_private(void)
87{
88 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
89 DWORD retval, which;
90 int i;
91
92 if (!proc_index)
93 return NULL;
94
95 /* build array of handles to wait for */
96 for (i = 0; i < proc_index; i++) {
97 handles[i] = (HANDLE) proc_array[i]->pid;
98
99 if (fake_exits_pending && proc_array[i]->exit_code)
100 break;
101 }
102
103 /* wait for someone to exit */
104 if (!fake_exits_pending) {
105 retval = WaitForMultipleObjects(proc_index, handles, FALSE, INFINITE);
106 which = retval - WAIT_OBJECT_0;
107 } else {
108 fake_exits_pending--;
109 retval = !WAIT_FAILED;
110 which = i;
111 }
112
113 /* return pointer to process */
114 if (retval != WAIT_FAILED) {
115 sub_process* pproc = proc_array[which];
116 process_adjust_wait_state(pproc);
117 return pproc;
118 } else
119 return NULL;
120}
121
122/*
123 * Terminate a process.
124 */
125BOOL
126process_kill(HANDLE proc, int signal)
127{
128 sub_process* pproc = (sub_process*) proc;
129 pproc->signal = signal;
130 return (TerminateProcess((HANDLE) pproc->pid, signal));
131}
132
133/*
134 * Use this function to register processes you wish to wait for by
135 * calling process_file_io(NULL) or process_wait_any(). This must be done
136 * because it is possible for callers of this library to reuse the same
137 * handle for multiple processes launches :-(
138 */
139void
140process_register(HANDLE proc)
141{
142 if (proc_index < MAXIMUM_WAIT_OBJECTS)
143 proc_array[proc_index++] = (sub_process *) proc;
144}
145
146/*
147 * Return the number of processes that we are still waiting for.
148 */
149int
150process_used_slots(void)
151{
152 return proc_index;
153}
154
155/*
156 * Public function which works kind of like waitpid(). Wait for any
157 * of the children to die and return results. To call this function,
158 * you must do 1 of things:
159 *
160 * x = process_easy(...);
161 *
162 * or
163 *
164 * x = process_init_fd();
165 * process_register(x);
166 *
167 * or
168 *
169 * x = process_init();
170 * process_register(x);
171 *
172 * You must NOT then call process_pipe_io() because this function is
173 * not capable of handling automatic notification of any child
174 * death.
175 */
176
177HANDLE
178process_wait_for_any(void)
179{
180 sub_process* pproc = process_wait_for_any_private();
181
182 if (!pproc)
183 return NULL;
184 else {
185 /*
186 * Ouch! can't tell caller if this fails directly. Caller
187 * will have to use process_last_err()
188 */
189#ifdef KMK
190 (void) process_file_io_private(pproc, FALSE);
191#else
192 (void) process_file_io(pproc);
193#endif
194 return ((HANDLE) pproc);
195 }
196}
197
198long
199process_signal(HANDLE proc)
200{
201 if (proc == INVALID_HANDLE_VALUE) return 0;
202 return (((sub_process *)proc)->signal);
203}
204
205long
206process_last_err(HANDLE proc)
207{
208 if (proc == INVALID_HANDLE_VALUE) return ERROR_INVALID_HANDLE;
209 return (((sub_process *)proc)->last_err);
210}
211
212long
213process_exit_code(HANDLE proc)
214{
215 if (proc == INVALID_HANDLE_VALUE) return EXIT_FAILURE;
216 return (((sub_process *)proc)->exit_code);
217}
218
219/*
2202006-02:
221All the following functions are currently unused.
222All of them would crash gmake if called with argument INVALID_HANDLE_VALUE.
223Hence whoever wants to use one of this functions must invent and implement
224a reasonable error handling for this function.
225
226char *
227process_outbuf(HANDLE proc)
228{
229 return (((sub_process *)proc)->outp);
230}
231
232char *
233process_errbuf(HANDLE proc)
234{
235 return (((sub_process *)proc)->errp);
236}
237
238int
239process_outcnt(HANDLE proc)
240{
241 return (((sub_process *)proc)->outcnt);
242}
243
244int
245process_errcnt(HANDLE proc)
246{
247 return (((sub_process *)proc)->errcnt);
248}
249
250void
251process_pipes(HANDLE proc, int pipes[3])
252{
253 pipes[0] = ((sub_process *)proc)->sv_stdin[0];
254 pipes[1] = ((sub_process *)proc)->sv_stdout[0];
255 pipes[2] = ((sub_process *)proc)->sv_stderr[0];
256 return;
257}
258*/
259
260 HANDLE
261process_init()
262{
263 sub_process *pproc;
264 /*
265 * open file descriptors for attaching stdin/stdout/sterr
266 */
267 HANDLE stdin_pipes[2];
268 HANDLE stdout_pipes[2];
269 HANDLE stderr_pipes[2];
270 SECURITY_ATTRIBUTES inherit;
271 BYTE sd[SECURITY_DESCRIPTOR_MIN_LENGTH];
272
273 pproc = malloc(sizeof(*pproc));
274 memset(pproc, 0, sizeof(*pproc));
275
276 /* We can't use NULL for lpSecurityDescriptor because that
277 uses the default security descriptor of the calling process.
278 Instead we use a security descriptor with no DACL. This
279 allows nonrestricted access to the associated objects. */
280
281 if (!InitializeSecurityDescriptor((PSECURITY_DESCRIPTOR)(&sd),
282 SECURITY_DESCRIPTOR_REVISION)) {
283 pproc->last_err = GetLastError();
284 pproc->lerrno = E_SCALL;
285 return((HANDLE)pproc);
286 }
287
288 inherit.nLength = sizeof(inherit);
289 inherit.lpSecurityDescriptor = (PSECURITY_DESCRIPTOR)(&sd);
290 inherit.bInheritHandle = TRUE;
291
292 // By convention, parent gets pipe[0], and child gets pipe[1]
293 // This means the READ side of stdin pipe goes into pipe[1]
294 // and the WRITE side of the stdout and stderr pipes go into pipe[1]
295 if (CreatePipe( &stdin_pipes[1], &stdin_pipes[0], &inherit, 0) == FALSE ||
296 CreatePipe( &stdout_pipes[0], &stdout_pipes[1], &inherit, 0) == FALSE ||
297 CreatePipe( &stderr_pipes[0], &stderr_pipes[1], &inherit, 0) == FALSE) {
298
299 pproc->last_err = GetLastError();
300 pproc->lerrno = E_SCALL;
301 return((HANDLE)pproc);
302 }
303
304 //
305 // Mark the parent sides of the pipes as non-inheritable
306 //
307 if (SetHandleInformation(stdin_pipes[0],
308 HANDLE_FLAG_INHERIT, 0) == FALSE ||
309 SetHandleInformation(stdout_pipes[0],
310 HANDLE_FLAG_INHERIT, 0) == FALSE ||
311 SetHandleInformation(stderr_pipes[0],
312 HANDLE_FLAG_INHERIT, 0) == FALSE) {
313
314 pproc->last_err = GetLastError();
315 pproc->lerrno = E_SCALL;
316 return((HANDLE)pproc);
317 }
318 pproc->sv_stdin[0] = (int) stdin_pipes[0];
319 pproc->sv_stdin[1] = (int) stdin_pipes[1];
320 pproc->sv_stdout[0] = (int) stdout_pipes[0];
321 pproc->sv_stdout[1] = (int) stdout_pipes[1];
322 pproc->sv_stderr[0] = (int) stderr_pipes[0];
323 pproc->sv_stderr[1] = (int) stderr_pipes[1];
324
325 pproc->using_pipes = 1;
326
327 pproc->lerrno = 0;
328
329 return((HANDLE)pproc);
330}
331
332
333 HANDLE
334process_init_fd(HANDLE stdinh, HANDLE stdouth, HANDLE stderrh)
335{
336 sub_process *pproc;
337
338 pproc = malloc(sizeof(*pproc));
339 memset(pproc, 0, sizeof(*pproc));
340
341 /*
342 * Just pass the provided file handles to the 'child side' of the
343 * pipe, bypassing pipes altogether.
344 */
345 pproc->sv_stdin[1] = (int) stdinh;
346 pproc->sv_stdout[1] = (int) stdouth;
347 pproc->sv_stderr[1] = (int) stderrh;
348
349 pproc->last_err = pproc->lerrno = 0;
350
351 return((HANDLE)pproc);
352}
353
354
355static HANDLE
356find_file(char *exec_path, LPOFSTRUCT file_info)
357{
358 HANDLE exec_handle;
359 char *fname;
360 char *ext;
361#ifdef KMK
362 size_t exec_path_len;
363
364 /*
365 * if there is an .exe extension there already, don't waste time here.
366 * If .exe scripts become common, they can be handled in a CreateProcess
367 * failure path instead of here.
368 */
369 exec_path_len = strlen(exec_path);
370 if ( exec_path_len > 4
371 && exec_path[exec_path_len - 4] == '.'
372 && !stricmp(exec_path + exec_path_len - 3, "exe")){
373 return((HANDLE)HFILE_ERROR);
374 }
375
376 fname = malloc(exec_path_len + 5);
377#else
378 fname = malloc(strlen(exec_path) + 5);
379#endif
380 strcpy(fname, exec_path);
381 ext = fname + strlen(fname);
382
383 strcpy(ext, ".exe");
384 if ((exec_handle = (HANDLE)OpenFile(fname, file_info,
385 OF_READ | OF_SHARE_COMPAT)) != (HANDLE)HFILE_ERROR) {
386 free(fname);
387 return(exec_handle);
388 }
389
390 strcpy(ext, ".cmd");
391 if ((exec_handle = (HANDLE)OpenFile(fname, file_info,
392 OF_READ | OF_SHARE_COMPAT)) != (HANDLE)HFILE_ERROR) {
393 free(fname);
394 return(exec_handle);
395 }
396
397 strcpy(ext, ".bat");
398 if ((exec_handle = (HANDLE)OpenFile(fname, file_info,
399 OF_READ | OF_SHARE_COMPAT)) != (HANDLE)HFILE_ERROR) {
400 free(fname);
401 return(exec_handle);
402 }
403
404 /* should .com come before this case? */
405 if ((exec_handle = (HANDLE)OpenFile(exec_path, file_info,
406 OF_READ | OF_SHARE_COMPAT)) != (HANDLE)HFILE_ERROR) {
407 free(fname);
408 return(exec_handle);
409 }
410
411 strcpy(ext, ".com");
412 if ((exec_handle = (HANDLE)OpenFile(fname, file_info,
413 OF_READ | OF_SHARE_COMPAT)) != (HANDLE)HFILE_ERROR) {
414 free(fname);
415 return(exec_handle);
416 }
417
418 free(fname);
419 return(exec_handle);
420}
421
422
423/*
424 * Description: Create the child process to be helped
425 *
426 * Returns: success <=> 0
427 *
428 * Notes/Dependencies:
429 */
430long
431process_begin(
432 HANDLE proc,
433 char **argv,
434 char **envp,
435 char *exec_path,
436 char *as_user)
437{
438 sub_process *pproc = (sub_process *)proc;
439 char *shell_name = 0;
440 int file_not_found=0;
441 HANDLE exec_handle;
442 char buf[256];
443 DWORD bytes_returned;
444 DWORD flags;
445 char *command_line;
446 STARTUPINFO startInfo;
447 PROCESS_INFORMATION procInfo;
448 char *envblk=NULL;
449 OFSTRUCT file_info;
450
451
452 /*
453 * Shell script detection... if the exec_path starts with #! then
454 * we want to exec shell-script-name exec-path, not just exec-path
455 * NT doesn't recognize #!/bin/sh or #!/etc/Tivoli/bin/perl. We do not
456 * hard-code the path to the shell or perl or whatever: Instead, we
457 * assume it's in the path somewhere (generally, the NT tools
458 * bin directory)
459 * We use OpenFile here because it is capable of searching the Path.
460 */
461
462 exec_handle = find_file(exec_path, &file_info);
463
464 /*
465 * If we couldn't open the file, just assume that Windows32 will be able
466 * to find and execute it.
467 */
468 if (exec_handle == (HANDLE)HFILE_ERROR) {
469 file_not_found++;
470 }
471 else {
472 /* Attempt to read the first line of the file */
473 if (ReadFile( exec_handle,
474 buf, sizeof(buf) - 1, /* leave room for trailing NULL */
475 &bytes_returned, 0) == FALSE || bytes_returned < 2) {
476
477 pproc->last_err = GetLastError();
478 pproc->lerrno = E_IO;
479 CloseHandle(exec_handle);
480 return(-1);
481 }
482 if (buf[0] == '#' && buf[1] == '!') {
483 /*
484 * This is a shell script... Change the command line from
485 * exec_path args to shell_name exec_path args
486 */
487 char *p;
488
489 /* Make sure buf is NULL terminated */
490 buf[bytes_returned] = 0;
491 /*
492 * Depending on the file system type, etc. the first line
493 * of the shell script may end with newline or newline-carriage-return
494 * Whatever it ends with, cut it off.
495 */
496 p= strchr(buf, '\n');
497 if (p)
498 *p = 0;
499 p = strchr(buf, '\r');
500 if (p)
501 *p = 0;
502
503 /*
504 * Find base name of shell
505 */
506 shell_name = strrchr( buf, '/');
507 if (shell_name) {
508 shell_name++;
509 } else {
510 shell_name = &buf[2];/* skipping "#!" */
511 }
512
513 }
514 CloseHandle(exec_handle);
515 }
516
517 flags = 0;
518
519 if (file_not_found)
520 command_line = make_command_line( shell_name, exec_path, argv);
521 else
522 command_line = make_command_line( shell_name, file_info.szPathName,
523 argv);
524
525 if ( command_line == NULL ) {
526 pproc->last_err = 0;
527 pproc->lerrno = E_NO_MEM;
528 return(-1);
529 }
530
531 if (envp) {
532 if (arr2envblk(envp, &envblk) ==FALSE) {
533 pproc->last_err = 0;
534 pproc->lerrno = E_NO_MEM;
535 free( command_line );
536 return(-1);
537 }
538 }
539
540 if ((shell_name) || (file_not_found)) {
541 exec_path = 0; /* Search for the program in %Path% */
542 } else {
543 exec_path = file_info.szPathName;
544 }
545
546 /*
547 * Set up inherited stdin, stdout, stderr for child
548 */
549 GetStartupInfo(&startInfo);
550#ifndef KMK
551 startInfo.dwFlags = STARTF_USESTDHANDLES;
552#endif
553 startInfo.lpReserved = 0;
554 startInfo.cbReserved2 = 0;
555 startInfo.lpReserved2 = 0;
556 startInfo.lpTitle = shell_name ? shell_name : exec_path;
557#ifndef KMK
558 startInfo.hStdInput = (HANDLE)pproc->sv_stdin[1];
559 startInfo.hStdOutput = (HANDLE)pproc->sv_stdout[1];
560 startInfo.hStdError = (HANDLE)pproc->sv_stderr[1];
561#else
562 if ( pproc->sv_stdin[1]
563 || pproc->sv_stdout[1]
564 || pproc->sv_stderr[1]) {
565 startInfo.dwFlags = STARTF_USESTDHANDLES;
566 startInfo.hStdInput = (HANDLE)pproc->sv_stdin[1];
567 startInfo.hStdOutput = (HANDLE)pproc->sv_stdout[1];
568 startInfo.hStdError = (HANDLE)pproc->sv_stderr[1];
569 } else {
570 startInfo.dwFlags = 0;
571 startInfo.hStdInput = 0;
572 startInfo.hStdOutput = 0;
573 startInfo.hStdError = 0;
574 }
575#endif
576
577 if (as_user) {
578 if (envblk) free(envblk);
579 return -1;
580 } else {
581 DB (DB_JOBS, ("CreateProcess(%s,%s,...)\n",
582 exec_path ? exec_path : "NULL",
583 command_line ? command_line : "NULL"));
584 if (CreateProcess(
585 exec_path,
586 command_line,
587 NULL,
588 0, /* default security attributes for thread */
589 TRUE, /* inherit handles (e.g. helper pipes, oserv socket) */
590 flags,
591 envblk,
592 0, /* default starting directory */
593 &startInfo,
594 &procInfo) == FALSE) {
595
596 pproc->last_err = GetLastError();
597 pproc->lerrno = E_FORK;
598 fprintf(stderr, "process_begin: CreateProcess(%s, %s, ...) failed.\n",
599 exec_path ? exec_path : "NULL", command_line);
600 if (envblk) free(envblk);
601 free( command_line );
602 return(-1);
603 }
604 }
605
606 pproc->pid = (int)procInfo.hProcess;
607 /* Close the thread handle -- we'll just watch the process */
608 CloseHandle(procInfo.hThread);
609
610 /* Close the halves of the pipes we don't need */
611#ifndef KMK
612 CloseHandle((HANDLE)pproc->sv_stdin[1]);
613 CloseHandle((HANDLE)pproc->sv_stdout[1]);
614 CloseHandle((HANDLE)pproc->sv_stderr[1]);
615 pproc->sv_stdin[1] = 0;
616 pproc->sv_stdout[1] = 0;
617 pproc->sv_stderr[1] = 0;
618#else
619 if ((HANDLE)pproc->sv_stdin[1]) {
620 CloseHandle((HANDLE)pproc->sv_stdin[1]);
621 pproc->sv_stdin[1] = 0;
622 }
623 if ((HANDLE)pproc->sv_stdout[1]) {
624 CloseHandle((HANDLE)pproc->sv_stdout[1]);
625 pproc->sv_stdout[1] = 0;
626 }
627 if ((HANDLE)pproc->sv_stderr[1]) {
628 CloseHandle((HANDLE)pproc->sv_stderr[1]);
629 pproc->sv_stderr[1] = 0;
630 }
631#endif
632
633 free( command_line );
634 if (envblk) free(envblk);
635 pproc->lerrno=0;
636 return 0;
637}
638
639
640
641static DWORD
642proc_stdin_thread(sub_process *pproc)
643{
644 DWORD in_done;
645 for (;;) {
646 if (WriteFile( (HANDLE) pproc->sv_stdin[0], pproc->inp, pproc->incnt,
647 &in_done, NULL) == FALSE)
648 _endthreadex(0);
649 // This if should never be true for anonymous pipes, but gives
650 // us a chance to change I/O mechanisms later
651 if (in_done < pproc->incnt) {
652 pproc->incnt -= in_done;
653 pproc->inp += in_done;
654 } else {
655 _endthreadex(0);
656 }
657 }
658 return 0; // for compiler warnings only.. not reached
659}
660
661static DWORD
662proc_stdout_thread(sub_process *pproc)
663{
664 DWORD bufsize = 1024;
665 char c;
666 DWORD nread;
667 pproc->outp = malloc(bufsize);
668 if (pproc->outp == NULL)
669 _endthreadex(0);
670 pproc->outcnt = 0;
671
672 for (;;) {
673 if (ReadFile( (HANDLE)pproc->sv_stdout[0], &c, 1, &nread, NULL)
674 == FALSE) {
675/* map_windows32_error_to_string(GetLastError());*/
676 _endthreadex(0);
677 }
678 if (nread == 0)
679 _endthreadex(0);
680 if (pproc->outcnt + nread > bufsize) {
681 bufsize += nread + 512;
682 pproc->outp = realloc(pproc->outp, bufsize);
683 if (pproc->outp == NULL) {
684 pproc->outcnt = 0;
685 _endthreadex(0);
686 }
687 }
688 pproc->outp[pproc->outcnt++] = c;
689 }
690 return 0;
691}
692
693static DWORD
694proc_stderr_thread(sub_process *pproc)
695{
696 DWORD bufsize = 1024;
697 char c;
698 DWORD nread;
699 pproc->errp = malloc(bufsize);
700 if (pproc->errp == NULL)
701 _endthreadex(0);
702 pproc->errcnt = 0;
703
704 for (;;) {
705 if (ReadFile( (HANDLE)pproc->sv_stderr[0], &c, 1, &nread, NULL) == FALSE) {
706 map_windows32_error_to_string(GetLastError());
707 _endthreadex(0);
708 }
709 if (nread == 0)
710 _endthreadex(0);
711 if (pproc->errcnt + nread > bufsize) {
712 bufsize += nread + 512;
713 pproc->errp = realloc(pproc->errp, bufsize);
714 if (pproc->errp == NULL) {
715 pproc->errcnt = 0;
716 _endthreadex(0);
717 }
718 }
719 pproc->errp[pproc->errcnt++] = c;
720 }
721 return 0;
722}
723
724
725/*
726 * Purpose: collects output from child process and returns results
727 *
728 * Description:
729 *
730 * Returns:
731 *
732 * Notes/Dependencies:
733 */
734 long
735process_pipe_io(
736 HANDLE proc,
737 char *stdin_data,
738 int stdin_data_len)
739{
740 sub_process *pproc = (sub_process *)proc;
741 bool_t stdin_eof = FALSE, stdout_eof = FALSE, stderr_eof = FALSE;
742 HANDLE childhand = (HANDLE) pproc->pid;
743 HANDLE tStdin = NULL, tStdout = NULL, tStderr = NULL;
744 unsigned int dwStdin, dwStdout, dwStderr;
745 HANDLE wait_list[4];
746 DWORD wait_count;
747 DWORD wait_return;
748 HANDLE ready_hand;
749 bool_t child_dead = FALSE;
750 BOOL GetExitCodeResult;
751
752 /*
753 * Create stdin thread, if needed
754 */
755 pproc->inp = stdin_data;
756 pproc->incnt = stdin_data_len;
757 if (!pproc->inp) {
758 stdin_eof = TRUE;
759 CloseHandle((HANDLE)pproc->sv_stdin[0]);
760 pproc->sv_stdin[0] = 0;
761 } else {
762 tStdin = (HANDLE) _beginthreadex( 0, 1024,
763 (unsigned (__stdcall *) (void *))proc_stdin_thread,
764 pproc, 0, &dwStdin);
765 if (tStdin == 0) {
766 pproc->last_err = GetLastError();
767 pproc->lerrno = E_SCALL;
768 goto done;
769 }
770 }
771
772 /*
773 * Assume child will produce stdout and stderr
774 */
775 tStdout = (HANDLE) _beginthreadex( 0, 1024,
776 (unsigned (__stdcall *) (void *))proc_stdout_thread, pproc, 0,
777 &dwStdout);
778 tStderr = (HANDLE) _beginthreadex( 0, 1024,
779 (unsigned (__stdcall *) (void *))proc_stderr_thread, pproc, 0,
780 &dwStderr);
781
782 if (tStdout == 0 || tStderr == 0) {
783
784 pproc->last_err = GetLastError();
785 pproc->lerrno = E_SCALL;
786 goto done;
787 }
788
789
790 /*
791 * Wait for all I/O to finish and for the child process to exit
792 */
793
794 while (!stdin_eof || !stdout_eof || !stderr_eof || !child_dead) {
795 wait_count = 0;
796 if (!stdin_eof) {
797 wait_list[wait_count++] = tStdin;
798 }
799 if (!stdout_eof) {
800 wait_list[wait_count++] = tStdout;
801 }
802 if (!stderr_eof) {
803 wait_list[wait_count++] = tStderr;
804 }
805 if (!child_dead) {
806 wait_list[wait_count++] = childhand;
807 }
808
809 wait_return = WaitForMultipleObjects(wait_count, wait_list,
810 FALSE, /* don't wait for all: one ready will do */
811 child_dead? 1000 :INFINITE); /* after the child dies, subthreads have
812 one second to collect all remaining output */
813
814 if (wait_return == WAIT_FAILED) {
815/* map_windows32_error_to_string(GetLastError());*/
816 pproc->last_err = GetLastError();
817 pproc->lerrno = E_SCALL;
818 goto done;
819 }
820
821 ready_hand = wait_list[wait_return - WAIT_OBJECT_0];
822
823 if (ready_hand == tStdin) {
824 CloseHandle((HANDLE)pproc->sv_stdin[0]);
825 pproc->sv_stdin[0] = 0;
826 CloseHandle(tStdin);
827 tStdin = 0;
828 stdin_eof = TRUE;
829
830 } else if (ready_hand == tStdout) {
831
832 CloseHandle((HANDLE)pproc->sv_stdout[0]);
833 pproc->sv_stdout[0] = 0;
834 CloseHandle(tStdout);
835 tStdout = 0;
836 stdout_eof = TRUE;
837
838 } else if (ready_hand == tStderr) {
839
840 CloseHandle((HANDLE)pproc->sv_stderr[0]);
841 pproc->sv_stderr[0] = 0;
842 CloseHandle(tStderr);
843 tStderr = 0;
844 stderr_eof = TRUE;
845
846 } else if (ready_hand == childhand) {
847
848 DWORD ierr;
849 GetExitCodeResult = GetExitCodeProcess(childhand, &ierr);
850 if (ierr == CONTROL_C_EXIT) {
851 pproc->signal = SIGINT;
852 } else {
853 pproc->exit_code = ierr;
854 }
855 if (GetExitCodeResult == FALSE) {
856 pproc->last_err = GetLastError();
857 pproc->lerrno = E_SCALL;
858 goto done;
859 }
860 child_dead = TRUE;
861
862 } else {
863
864 /* ?? Got back a handle we didn't query ?? */
865 pproc->last_err = 0;
866 pproc->lerrno = E_FAIL;
867 goto done;
868 }
869 }
870
871 done:
872 if (tStdin != 0)
873 CloseHandle(tStdin);
874 if (tStdout != 0)
875 CloseHandle(tStdout);
876 if (tStderr != 0)
877 CloseHandle(tStderr);
878
879 if (pproc->lerrno)
880 return(-1);
881 else
882 return(0);
883
884}
885
886/*
887 * Purpose: collects output from child process and returns results
888 *
889 * Description:
890 *
891 * Returns:
892 *
893 * Notes/Dependencies:
894 */
895 long
896process_file_io(
897 HANDLE proc)
898{
899 sub_process *pproc;
900 if (proc == NULL)
901 pproc = process_wait_for_any_private();
902 else
903 pproc = (sub_process *)proc;
904
905 /* some sort of internal error */
906 if (!pproc)
907 return -1;
908
909 return process_file_io_private(proc, TRUE);
910}
911
912/* private function, avoid some kernel calls. (bird) */
913static long
914process_file_io_private(
915 sub_process *pproc,
916 BOOL fNeedToWait)
917{
918 HANDLE childhand;
919 DWORD wait_return;
920 BOOL GetExitCodeResult;
921 DWORD ierr;
922
923 childhand = (HANDLE) pproc->pid;
924
925 /*
926 * This function is poorly named, and could also be used just to wait
927 * for child death if you're doing your own pipe I/O. If that is
928 * the case, close the pipe handles here.
929 */
930 if (pproc->sv_stdin[0]) {
931 CloseHandle((HANDLE)pproc->sv_stdin[0]);
932 pproc->sv_stdin[0] = 0;
933 }
934 if (pproc->sv_stdout[0]) {
935 CloseHandle((HANDLE)pproc->sv_stdout[0]);
936 pproc->sv_stdout[0] = 0;
937 }
938 if (pproc->sv_stderr[0]) {
939 CloseHandle((HANDLE)pproc->sv_stderr[0]);
940 pproc->sv_stderr[0] = 0;
941 }
942
943 /*
944 * Wait for the child process to exit it we didn't do that already.
945 */
946 if (fNeedToWait) {
947 wait_return = WaitForSingleObject(childhand, INFINITE);
948 if (wait_return != WAIT_OBJECT_0) {
949/* map_windows32_error_to_string(GetLastError());*/
950 pproc->last_err = GetLastError();
951 pproc->lerrno = E_SCALL;
952 goto done2;
953 }
954 }
955
956 GetExitCodeResult = GetExitCodeProcess(childhand, &ierr);
957 if (ierr == CONTROL_C_EXIT) {
958 pproc->signal = SIGINT;
959 } else {
960 pproc->exit_code = ierr;
961 }
962 if (GetExitCodeResult == FALSE) {
963 pproc->last_err = GetLastError();
964 pproc->lerrno = E_SCALL;
965 }
966
967done2:
968 if (pproc->lerrno)
969 return(-1);
970 else
971 return(0);
972
973}
974
975/*
976 * Description: Clean up any leftover handles, etc. It is up to the
977 * caller to manage and free the input, ouput, and stderr buffers.
978 */
979 void
980process_cleanup(
981 HANDLE proc)
982{
983 sub_process *pproc = (sub_process *)proc;
984 int i;
985
986 if (pproc->using_pipes) {
987 for (i= 0; i <= 1; i++) {
988 if ((HANDLE)pproc->sv_stdin[i])
989 CloseHandle((HANDLE)pproc->sv_stdin[i]);
990 if ((HANDLE)pproc->sv_stdout[i])
991 CloseHandle((HANDLE)pproc->sv_stdout[i]);
992 if ((HANDLE)pproc->sv_stderr[i])
993 CloseHandle((HANDLE)pproc->sv_stderr[i]);
994 }
995 }
996 if ((HANDLE)pproc->pid)
997 CloseHandle((HANDLE)pproc->pid);
998
999 free(pproc);
1000}
1001
1002
1003/*
1004 * Description:
1005 * Create a command line buffer to pass to CreateProcess
1006 *
1007 * Returns: the buffer or NULL for failure
1008 * Shell case: sh_name a:/full/path/to/script argv[1] argv[2] ...
1009 * Otherwise: argv[0] argv[1] argv[2] ...
1010 *
1011 * Notes/Dependencies:
1012 * CreateProcess does not take an argv, so this command creates a
1013 * command line for the executable.
1014 */
1015
1016static char *
1017make_command_line( char *shell_name, char *full_exec_path, char **argv)
1018{
1019 int argc = 0;
1020 char** argvi;
1021 int* enclose_in_quotes = NULL;
1022 int* enclose_in_quotes_i;
1023 unsigned int bytes_required = 0;
1024 char* command_line;
1025 char* command_line_i;
1026 int cygwin_mode = 0; /* HAVE_CYGWIN_SHELL */
1027 int have_sh = 0; /* HAVE_CYGWIN_SHELL */
1028#undef HAVE_CYGWIN_SHELL
1029#ifdef HAVE_CYGWIN_SHELL
1030 have_sh = (shell_name != NULL || strstr(full_exec_path, "sh.exe"));
1031 cygwin_mode = 1;
1032#endif
1033
1034 if (shell_name && full_exec_path) {
1035 bytes_required
1036 = strlen(shell_name) + 1 + strlen(full_exec_path);
1037 /*
1038 * Skip argv[0] if any, when shell_name is given.
1039 */
1040 if (*argv) argv++;
1041 /*
1042 * Add one for the intervening space.
1043 */
1044 if (*argv) bytes_required++;
1045 }
1046
1047 argvi = argv;
1048 while (*(argvi++)) argc++;
1049
1050 if (argc) {
1051 enclose_in_quotes = (int*) calloc(1, argc * sizeof(int));
1052
1053 if (!enclose_in_quotes) {
1054 return NULL;
1055 }
1056 }
1057
1058 /* We have to make one pass through each argv[i] to see if we need
1059 * to enclose it in ", so we might as well figure out how much
1060 * memory we'll need on the same pass.
1061 */
1062
1063 argvi = argv;
1064 enclose_in_quotes_i = enclose_in_quotes;
1065 while(*argvi) {
1066 char* p = *argvi;
1067 unsigned int backslash_count = 0;
1068
1069 /*
1070 * We have to enclose empty arguments in ".
1071 */
1072 if (!(*p)) *enclose_in_quotes_i = 1;
1073
1074 while(*p) {
1075 switch (*p) {
1076 case '\"':
1077 /*
1078 * We have to insert a backslash for each "
1079 * and each \ that precedes the ".
1080 */
1081 bytes_required += (backslash_count + 1);
1082 backslash_count = 0;
1083 break;
1084
1085#if !defined(HAVE_MKS_SHELL) && !defined(HAVE_CYGWIN_SHELL)
1086 case '\\':
1087 backslash_count++;
1088 break;
1089#endif
1090 /*
1091 * At one time we set *enclose_in_quotes_i for '*' or '?' to suppress
1092 * wildcard expansion in programs linked with MSVC's SETARGV.OBJ so
1093 * that argv in always equals argv out. This was removed. Say you have
1094 * such a program named glob.exe. You enter
1095 * glob '*'
1096 * at the sh command prompt. Obviously the intent is to make glob do the
1097 * wildcarding instead of sh. If we set *enclose_in_quotes_i for '*' or '?',
1098 * then the command line that glob would see would be
1099 * glob "*"
1100 * and the _setargv in SETARGV.OBJ would _not_ expand the *.
1101 */
1102 case ' ':
1103 case '\t':
1104 *enclose_in_quotes_i = 1;
1105 /* fall through */
1106
1107 default:
1108 backslash_count = 0;
1109 break;
1110 }
1111
1112 /*
1113 * Add one for each character in argv[i].
1114 */
1115 bytes_required++;
1116
1117 p++;
1118 }
1119
1120 if (*enclose_in_quotes_i) {
1121 /*
1122 * Add one for each enclosing ",
1123 * and one for each \ that precedes the
1124 * closing ".
1125 */
1126 bytes_required += (backslash_count + 2);
1127 }
1128
1129 /*
1130 * Add one for the intervening space.
1131 */
1132 if (*(++argvi)) bytes_required++;
1133 enclose_in_quotes_i++;
1134 }
1135
1136 /*
1137 * Add one for the terminating NULL.
1138 */
1139 bytes_required++;
1140#ifdef KMK /* for the space before the final " in case we need it. */
1141 bytes_required++;
1142#endif
1143
1144 command_line = (char*) malloc(bytes_required);
1145
1146 if (!command_line) {
1147 if (enclose_in_quotes) free(enclose_in_quotes);
1148 return NULL;
1149 }
1150
1151 command_line_i = command_line;
1152
1153 if (shell_name && full_exec_path) {
1154 while(*shell_name) {
1155 *(command_line_i++) = *(shell_name++);
1156 }
1157
1158 *(command_line_i++) = ' ';
1159
1160 while(*full_exec_path) {
1161 *(command_line_i++) = *(full_exec_path++);
1162 }
1163
1164 if (*argv) {
1165 *(command_line_i++) = ' ';
1166 }
1167 }
1168
1169 argvi = argv;
1170 enclose_in_quotes_i = enclose_in_quotes;
1171
1172 while(*argvi) {
1173 char* p = *argvi;
1174 unsigned int backslash_count = 0;
1175
1176 if (*enclose_in_quotes_i) {
1177 *(command_line_i++) = '\"';
1178 }
1179
1180 while(*p) {
1181 if (*p == '\"') {
1182 if (cygwin_mode && have_sh) { /* HAVE_CYGWIN_SHELL */
1183 /* instead of a \", cygwin likes "" */
1184 *(command_line_i++) = '\"';
1185 } else {
1186
1187 /*
1188 * We have to insert a backslash for the "
1189 * and each \ that precedes the ".
1190 */
1191 backslash_count++;
1192
1193 while(backslash_count) {
1194 *(command_line_i++) = '\\';
1195 backslash_count--;
1196 };
1197 }
1198#if !defined(HAVE_MKS_SHELL) && !defined(HAVE_CYGWIN_SHELL)
1199 } else if (*p == '\\') {
1200 backslash_count++;
1201 } else {
1202 backslash_count = 0;
1203#endif
1204 }
1205
1206 /*
1207 * Copy the character.
1208 */
1209 *(command_line_i++) = *(p++);
1210 }
1211
1212 if (*enclose_in_quotes_i) {
1213#if !defined(HAVE_MKS_SHELL) && !defined(HAVE_CYGWIN_SHELL)
1214 /*
1215 * Add one \ for each \ that precedes the
1216 * closing ".
1217 */
1218 while(backslash_count--) {
1219 *(command_line_i++) = '\\';
1220 };
1221#endif
1222#ifdef KMK
1223 /*
1224 * ash it put off by echo "hello world" ending up as:
1225 * G:/.../kmk_ash.exe -c "echo ""hello world"""
1226 * It wants a space before the last '"'.
1227 * (The 'test_shell' goals in Makefile.kmk tests this problem.)
1228 */
1229 if (command_line_i[-1] == '\"' /* && cygwin_mode && have_sh*/ && !argvi[1]) {
1230 *(command_line_i++) = ' ';
1231 }
1232#endif
1233 *(command_line_i++) = '\"';
1234 }
1235
1236 /*
1237 * Append an intervening space.
1238 */
1239 if (*(++argvi)) {
1240 *(command_line_i++) = ' ';
1241 }
1242
1243 enclose_in_quotes_i++;
1244 }
1245
1246 /*
1247 * Append the terminating NULL.
1248 */
1249 *command_line_i = '\0';
1250
1251 if (enclose_in_quotes) free(enclose_in_quotes);
1252 return command_line;
1253}
1254
1255/*
1256 * Description: Given an argv and optional envp, launch the process
1257 * using the default stdin, stdout, and stderr handles.
1258 * Also, register process so that process_wait_for_any_private()
1259 * can be used via process_file_io(NULL) or
1260 * process_wait_for_any().
1261 *
1262 * Returns:
1263 *
1264 * Notes/Dependencies:
1265 */
1266HANDLE
1267process_easy(
1268 char **argv,
1269 char **envp)
1270{
1271#ifndef KMK
1272 HANDLE hIn;
1273 HANDLE hOut;
1274 HANDLE hErr;
1275#endif
1276 HANDLE hProcess;
1277
1278 if (proc_index >= MAXIMUM_WAIT_OBJECTS) {
1279 DB (DB_JOBS, ("process_easy: All process slots used up\n"));
1280 return INVALID_HANDLE_VALUE;
1281 }
1282#ifndef KMK
1283 if (DuplicateHandle(GetCurrentProcess(),
1284 GetStdHandle(STD_INPUT_HANDLE),
1285 GetCurrentProcess(),
1286 &hIn,
1287 0,
1288 TRUE,
1289 DUPLICATE_SAME_ACCESS) == FALSE) {
1290 fprintf(stderr,
1291 "process_easy: DuplicateHandle(In) failed (e=%ld)\n",
1292 GetLastError());
1293 return INVALID_HANDLE_VALUE;
1294 }
1295 if (DuplicateHandle(GetCurrentProcess(),
1296 GetStdHandle(STD_OUTPUT_HANDLE),
1297 GetCurrentProcess(),
1298 &hOut,
1299 0,
1300 TRUE,
1301 DUPLICATE_SAME_ACCESS) == FALSE) {
1302 fprintf(stderr,
1303 "process_easy: DuplicateHandle(Out) failed (e=%ld)\n",
1304 GetLastError());
1305 return INVALID_HANDLE_VALUE;
1306 }
1307 if (DuplicateHandle(GetCurrentProcess(),
1308 GetStdHandle(STD_ERROR_HANDLE),
1309 GetCurrentProcess(),
1310 &hErr,
1311 0,
1312 TRUE,
1313 DUPLICATE_SAME_ACCESS) == FALSE) {
1314 fprintf(stderr,
1315 "process_easy: DuplicateHandle(Err) failed (e=%ld)\n",
1316 GetLastError());
1317 return INVALID_HANDLE_VALUE;
1318 }
1319
1320 hProcess = process_init_fd(hIn, hOut, hErr);
1321#else
1322 hProcess = process_init_fd(0, 0, 0);
1323#endif /* !KMK */
1324
1325 if (process_begin(hProcess, argv, envp, argv[0], NULL)) {
1326 fake_exits_pending++;
1327 /* process_begin() failed: make a note of that. */
1328 if (!((sub_process*) hProcess)->last_err)
1329 ((sub_process*) hProcess)->last_err = -1;
1330 ((sub_process*) hProcess)->exit_code = process_last_err(hProcess);
1331
1332#ifndef KMK
1333 /* close up unused handles */
1334 CloseHandle(hIn);
1335 CloseHandle(hOut);
1336 CloseHandle(hErr);
1337#endif
1338 }
1339
1340 process_register(hProcess);
1341
1342 return hProcess;
1343}
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette