1 /* run.c --- routines for executing subprocesses under Windows NT.
3 This file is part of GNU CVS.
5 GNU CVS is free software; you can redistribute it and/or modify it
6 under the terms of the GNU General Public License as published by the
7 Free Software Foundation; either version 2, or (at your option) any
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details. */
17 #define WIN32_LEAN_AND_MEAN
28 * To exec a program under CVS, first call run_setup() to setup any initial
29 * arguments. The options to run_setup are essentially like printf(). The
30 * arguments will be parsed into whitespace separated words and added to the
31 * global run_argv list.
33 * Then, optionally call run_arg() for each additional argument that you'd like
34 * to pass to the executed program.
36 * Finally, call run_exec() to execute the program with the specified arguments.
37 * The execvp() syscall will be used, so that the PATH is searched correctly.
38 * File redirections can be performed in the call to run_exec().
40 static char **run_argv;
42 static size_t run_arg_allocated;
47 run_arg_free_p (int argc, char **argv)
50 for (i = 0; i < argc; i++)
58 run_setup (const char *prog)
65 /* clean out any malloc'ed values from run_argv */
66 for (i = 0; i < run_argc; i++)
71 run_argv[i] = (char *) 0;
76 run_prog = xstrdup (prog);
78 /* put each word into run_argv, allocating it as we go */
79 for (cp = strtok (run_prog, " \t"); cp; cp = strtok ((char *) NULL, " \t"))
87 /* Return a malloc'd copy of s, with double quotes around it. */
93 char *scan = (char *) s;
95 /* scan string for extra quotes ... */
98 s_len += 2; /* one extra for the quote character */
101 /* allocate length + byte for ending zero + for double quotes around */
102 scan = copy = xmalloc(s_len + 3);
110 /* ending quote and closing zero */
119 run_add_arg_p (int *iargc, size_t *iarg_allocated, char ***iargv,
122 /* allocate more argv entries if we've run out */
123 if (*iargc >= *iarg_allocated)
125 *iarg_allocated += 50;
126 *iargv = xnrealloc (*iargv, *iarg_allocated, sizeof (char **));
130 (*iargv)[(*iargc)++] = xstrdup (s);
132 (*iargv)[*iargc] = NULL; /* not post-incremented on purpose! */
138 run_add_arg (const char *s)
140 run_add_arg_p (&run_argc, &run_arg_allocated, &run_argv, s);
146 run_exec (const char *stin, const char *stout, const char *sterr, int flags)
148 int shin, shout, sherr;
149 int sain, saout, saerr; /* saved handles */
150 int mode_out, mode_err;
154 void (*old_sigint) (int);
156 if (trace) /* if in trace mode */
158 (void) fprintf (stderr, "-> system(");
160 (void) fprintf (stderr, ")\n");
163 /* Flush standard output and standard error, or otherwise we end
164 up with strange interleavings of stuff called from CYGWIN
170 if (noexec && (flags & RUN_REALLY) == 0) /* if in noexec mode */
174 * start the engine and take off
177 /* make sure that we are null terminated, since we didn't calloc */
178 run_add_arg ((char *) 0);
180 /* setup default file descriptor numbers */
185 /* set the file modes for stdout and stderr */
186 mode_out = mode_err = O_WRONLY | O_CREAT;
187 mode_out |= ((flags & RUN_STDOUT_APPEND) ? O_APPEND : O_TRUNC);
188 mode_err |= ((flags & RUN_STDERR_APPEND) ? O_APPEND : O_TRUNC);
190 /* open the files as required, shXX are shadows of stdin... */
191 if (stin && (shin = open (stin, O_RDONLY)) == -1)
194 error (0, errno, "cannot open %s for reading (prog %s)",
198 if (stout && (shout = open (stout, mode_out, 0666)) == -1)
201 error (0, errno, "cannot open %s for writing (prog %s)",
205 if (sterr && (flags & RUN_COMBINED) == 0)
207 if ((sherr = open (sterr, mode_err, 0666)) == -1)
210 error (0, errno, "cannot open %s for writing (prog %s)",
215 /* now save the standard handles */
216 sain = saout = saerr = -1;
217 sain = dup( 0); /* dup stdin */
218 saout = dup( 1); /* dup stdout */
219 saerr = dup( 2); /* dup stderr */
221 /* the new handles will be dup'd to the standard handles
227 (void) dup2 (shin, 0);
232 (void) dup2 (shout, 1);
233 (void) close (shout);
235 if (flags & RUN_COMBINED)
239 (void) dup2 (sherr, 2);
240 (void) close (sherr);
243 /* Ignore signals while we're running this. */
244 old_sigint = signal (SIGINT, SIG_IGN);
246 /* dup'ing is done. try to run it now */
247 rval = spawnvp ( P_WAIT, run_argv[0], run_argv);
249 /* Restore signal handling. */
250 signal (SIGINT, old_sigint);
252 /* restore the original file handles */
254 (void) dup2( sain, 0); /* re-connect stdin */
258 (void) dup2( saout, 1); /* re-connect stdout */
259 (void) close( saout);
262 (void) dup2( saerr, 2); /* re-connect stderr */
263 (void) close( saerr);
266 /* Flush standard output and standard error, or otherwise we end
267 up with strange interleavings of stuff called from CYGWIN
273 /* Recognize the return code for an interrupted subprocess. */
274 if (rval == CONTROL_C_EXIT)
277 return rval; /* end, if all went coorect */
280 /* cleanup the open file descriptors */
283 (void) close (shout);
299 for (i = 0; i < run_argc; i++)
301 (void) fprintf (fp, "'%s'", run_argv[i]);
302 if (i != run_argc - 1)
303 (void) fprintf (fp, " ");
308 requote (const char *cmd)
310 char *requoted = xmalloc (strlen (cmd) + 1);
313 strcpy (requoted, cmd);
314 while ((p = strchr (p, '\'')) != NULL)
323 run_popen (const char *cmd, const char *mode)
326 #ifdef SERVER_SUPPORT
327 (void) fprintf (stderr, "%c-> run_popen(%s,%s)\n",
328 (server_active) ? 'S' : ' ', cmd, mode);
330 (void) fprintf (stderr, "-> run_popen(%s,%s)\n", cmd, mode);
335 /* If the command string uses single quotes, turn them into
338 char *requoted = requote (cmd);
339 /* Save and restore our file descriptors to work around
340 apparent bugs in _popen. We are perhaps better off using
341 the win32 functions instead of _popen. */
342 int old_stdin = dup (STDIN_FILENO);
343 int old_stdout = dup (STDOUT_FILENO);
344 int old_stderr = dup (STDERR_FILENO);
346 FILE *result = popen (requoted, mode);
348 dup2 (old_stdin, STDIN_FILENO);
349 dup2 (old_stdout, STDOUT_FILENO);
350 dup2 (old_stderr, STDERR_FILENO);
361 /* Running children with pipes connected to them. */
363 /* It's kind of ridiculous the hoops we're jumping through to get
364 this working. _pipe and dup2 and _spawnmumble work just fine, except
365 that the child inherits a file descriptor for the writing end of the
366 pipe, and thus will never receive end-of-file on it. If you know of
367 a better way to implement the piped_child function, please let me know.
369 You can apparently specify _O_NOINHERIT when you open a file, but there's
370 apparently no fcntl function, so you can't change that bit on an existing
373 /* Given a handle, make an inheritable duplicate of it, and close
376 inheritable (HANDLE in)
379 HANDLE self = GetCurrentProcess ();
381 if (! DuplicateHandle (self, in, self, ©,
383 DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE))
384 return INVALID_HANDLE_VALUE;
390 /* Initialize the SECURITY_ATTRIBUTES structure *LPSA. Set its
391 bInheritHandle flag according to INHERIT. */
393 init_sa (LPSECURITY_ATTRIBUTES lpsa, BOOL inherit)
395 lpsa->nLength = sizeof(*lpsa);
396 lpsa->bInheritHandle = inherit;
397 lpsa->lpSecurityDescriptor = NULL;
401 enum inherit_pipe { inherit_reading, inherit_writing };
403 /* Create a pipe. Set READWRITE[0] to its reading end, and
404 READWRITE[1] to its writing end. If END is inherit_reading,
405 make the only the handle for the pipe's reading end inheritable.
406 If END is inherit_writing, make only the handle for the pipe's
407 writing end inheritable. Return 0 if we succeed, -1 if we fail.
409 Why does inheritability matter? Consider the case of a
410 pipe carrying data from the parent process to the child
411 process. The child wants to read data from the parent until
412 it reaches the EOF. Now, the only way to send an EOF on a pipe
413 is to close all the handles to its writing end. Obviously, the
414 parent has a handle to the writing end when it creates the child.
415 If the child inherits this handle, then it will never close it
416 (the child has no idea it's inherited it), and will thus never
417 receive an EOF on the pipe because it's holding a handle
420 In Unix, the child process closes the pipe ends before it execs.
421 In Windows NT, you create the pipe with uninheritable handles, and then use
422 DuplicateHandle to make the appropriate ends inheritable. */
425 my_pipe (HANDLE *readwrite, enum inherit_pipe end)
428 SECURITY_ATTRIBUTES sa;
431 if (! CreatePipe (&read, &write, &sa, 1 << 13))
436 if (end == inherit_reading)
437 read = inheritable (read);
439 write = inheritable (write);
441 if (read == INVALID_HANDLE_VALUE
442 || write == INVALID_HANDLE_VALUE)
451 readwrite[1] = write;
457 /* Initialize the STARTUPINFO structure *LPSI. */
459 init_si (LPSTARTUPINFO lpsi)
461 memset (lpsi, 0, sizeof (*lpsi));
462 lpsi->cb = sizeof(*lpsi);
463 lpsi->lpReserved = NULL;
464 lpsi->lpTitle = NULL;
465 lpsi->lpReserved2 = NULL;
466 lpsi->cbReserved2 = 0;
467 lpsi->lpDesktop = NULL;
472 /* Create a child process running COMMAND with IN as its standard input,
473 and OUT as its standard output. Return a handle to the child, or
474 INVALID_HANDLE_VALUE. */
476 start_child (char *command, HANDLE in, HANDLE out)
479 PROCESS_INFORMATION pi;
482 /* The STARTUPINFO structure can specify handles to pass to the
483 child as its standard input, output, and error. */
487 si.hStdError = (HANDLE) _get_osfhandle (2);
488 si.dwFlags = STARTF_USESTDHANDLES;
490 status = CreateProcess ((LPCTSTR) NULL,
492 (LPSECURITY_ATTRIBUTES) NULL, /* lpsaProcess */
493 (LPSECURITY_ATTRIBUTES) NULL, /* lpsaThread */
494 TRUE, /* fInheritHandles */
496 (LPVOID) 0, /* lpvEnvironment */
497 (LPCTSTR) 0, /* lpszCurDir */
498 &si, /* lpsiStartInfo */
499 &pi); /* lppiProcInfo */
503 DWORD error_code = GetLastError ();
506 case ERROR_NOT_ENOUGH_MEMORY:
507 case ERROR_OUTOFMEMORY:
508 errno = ENOMEM; break;
509 case ERROR_BAD_EXE_FORMAT:
510 errno = ENOEXEC; break;
511 case ERROR_ACCESS_DENIED:
512 errno = EACCES; break;
513 case ERROR_NOT_READY:
514 case ERROR_FILE_NOT_FOUND:
515 case ERROR_PATH_NOT_FOUND:
517 errno = ENOENT; break;
519 return (int) INVALID_HANDLE_VALUE;
522 /* The _spawn and _cwait functions in the C runtime library
523 seem to operate on raw NT handles, not PID's. Odd, but we'll
525 return (int) pi.hProcess;
529 /* Given an array of arguments that one might pass to spawnv,
530 construct a command line that one might pass to CreateProcess.
531 Try to quote things appropriately. */
533 build_command (char *const *argv)
537 /* Compute the total length the command will have. */
542 for (i = 0; argv[i]; i++)
546 len += 2; /* for the double quotes */
548 for (p = argv[i]; *p; p++)
555 len++; /* for the space or the '\0' */
560 /* The + 10 is in case len is 0. */
561 char *command = (char *) malloc (len + 10);
573 /* copy each element of argv to command, putting each command
574 in double quotes, and backslashing any quotes that appear
575 within an argument. */
576 for (i = 0; argv[i]; i++)
580 for (a = argv[i]; *a; a++)
583 *p++ = '\\', *p++ = '"';
598 /* Create an asynchronous child process executing ARGV,
599 with its standard input and output connected to the
600 parent with pipes. Set *TO to the file descriptor on
601 which one writes data for the child; set *FROM to
602 the file descriptor from which one reads data from the child.
603 Return the handle of the child process (this is what
604 _cwait and waitpid expect). */
606 piped_child (char *const *argv, int *to, int *from, bool fix_stderr)
609 HANDLE pipein[2], pipeout[2];
612 /* Turn argv into a form acceptable to CreateProcess. */
613 command = build_command (argv);
617 /* Create pipes for communicating with child. Arrange for
618 the child not to inherit the ends it won't use. */
619 if (my_pipe (pipein, inherit_reading) == -1
620 || my_pipe (pipeout, inherit_writing) == -1)
623 child = start_child (command, pipein[0], pipeout[1]);
625 if (child == (int) INVALID_HANDLE_VALUE)
628 /* Close the pipe ends the parent doesn't use. */
629 CloseHandle (pipein[0]);
630 CloseHandle (pipeout[1]);
632 /* Given the pipe handles, turn them into file descriptors for
633 use by the caller. */
634 if ((*to = _open_osfhandle ((long) pipein[1], _O_BINARY)) == -1
635 || (*from = _open_osfhandle ((long) pipeout[0], _O_BINARY)) == -1)
642 * dir = 0 : main proc writes to new proc, which writes to oldfd
643 * dir = 1 : main proc reads from new proc, which reads from oldfd
645 * Returns: a file descriptor. On failure (e.g., the exec fails),
646 * then filter_stream_through_program() complains and dies.
650 filter_stream_through_program (int oldfd, int dir, char **prog, pid_t *pidp)
659 /* Get the OS handle associated with oldfd, to be passed to the child. */
660 if ((oldfd_handle = (HANDLE) _get_osfhandle (oldfd)) < 0)
661 error (1, errno, "cannot _get_osfhandle");
665 /* insert child before parent, pipe goes child->parent. */
666 if (my_pipe (pipe, inherit_writing) == -1)
667 error (1, errno, "cannot my_pipe");
668 if ((command = build_command (prog)) == NULL)
669 error (1, errno, "cannot build_command");
670 child = start_child (command, oldfd_handle, pipe[1]);
672 if (child == (int) INVALID_HANDLE_VALUE)
673 error (1, errno, "cannot start_child");
675 CloseHandle (pipe[1]);
676 newfd_handle = pipe[0];
680 /* insert child after parent, pipe goes parent->child. */
681 if (my_pipe (pipe, inherit_reading) == -1)
682 error (1, errno, "cannot my_pipe");
683 if ((command = build_command (prog)) == NULL)
684 error (1, errno, "cannot build_command");
685 child = start_child (command, pipe[0], oldfd_handle);
687 if (child == (int) INVALID_HANDLE_VALUE)
688 error (1, errno, "cannot start_child");
690 CloseHandle (pipe[0]);
691 newfd_handle = pipe[1];
694 if ((newfd = _open_osfhandle ((long) newfd_handle, _O_BINARY)) == -1)
695 error (1, errno, "cannot _open_osfhandle");
705 run_piped (int *tofdp, int *fromfdp)
708 return piped_child (run_argv, tofdp, fromfdp, false);
713 /* Arrange for the file descriptor FD to not be inherited by child
714 processes. At the moment, CVS uses this function only on pipes
715 returned by piped_child, and our implementation of piped_child
716 takes care of setting the file handles' inheritability, so this
719 close_on_exec (int fd)