Improve performance of script validation commit
[jimtcl.git] / jim-exec.c
blob47b327a8ba0df7bdbc7c160351b0d551a6044d56
1 /*
2 * (c) 2008 Steve Bennett <steveb@workware.net.au>
4 * Implements the exec command for Jim
6 * Based on code originally from Tcl 6.7 by John Ousterhout.
7 * From that code:
9 * The Tcl_Fork and Tcl_WaitPids procedures are based on code
10 * contributed by Karl Lehenbauer, Mark Diekhans and Peter
11 * da Silva.
13 * Copyright 1987-1991 Regents of the University of California
14 * Permission to use, copy, modify, and distribute this
15 * software and its documentation for any purpose and without
16 * fee is hereby granted, provided that the above copyright
17 * notice appear in all copies. The University of California
18 * makes no representations about the suitability of this
19 * software for any purpose. It is provided "as is" without
20 * express or implied warranty.
23 #include <string.h>
24 #include <ctype.h>
26 #include "jimautoconf.h"
27 #include <jim.h>
29 #if (!defined(HAVE_VFORK) || !defined(HAVE_WAITPID)) && !defined(__MINGW32__)
30 /* Poor man's implementation of exec with system()
31 * The system() call *may* do command line redirection, etc.
32 * The standard output is not available.
33 * Can't redirect filehandles.
35 static int Jim_ExecCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
37 Jim_Obj *cmdlineObj = Jim_NewEmptyStringObj(interp);
38 int i, j;
39 int rc;
41 /* Create a quoted command line */
42 for (i = 1; i < argc; i++) {
43 int len;
44 const char *arg = Jim_GetString(argv[i], &len);
46 if (i > 1) {
47 Jim_AppendString(interp, cmdlineObj, " ", 1);
49 if (strpbrk(arg, "\\\" ") == NULL) {
50 /* No quoting required */
51 Jim_AppendString(interp, cmdlineObj, arg, len);
52 continue;
55 Jim_AppendString(interp, cmdlineObj, "\"", 1);
56 for (j = 0; j < len; j++) {
57 if (arg[j] == '\\' || arg[j] == '"') {
58 Jim_AppendString(interp, cmdlineObj, "\\", 1);
60 Jim_AppendString(interp, cmdlineObj, &arg[j], 1);
62 Jim_AppendString(interp, cmdlineObj, "\"", 1);
64 rc = system(Jim_String(cmdlineObj));
66 Jim_FreeNewObj(interp, cmdlineObj);
68 if (rc) {
69 Jim_Obj *errorCode = Jim_NewListObj(interp, NULL, 0);
70 Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, "CHILDSTATUS", -1));
71 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, 0));
72 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, rc));
73 Jim_SetGlobalVariableStr(interp, "errorCode", errorCode);
74 return JIM_ERR;
77 return JIM_OK;
80 int Jim_execInit(Jim_Interp *interp)
82 if (Jim_PackageProvide(interp, "exec", "1.0", JIM_ERRMSG))
83 return JIM_ERR;
85 Jim_CreateCommand(interp, "exec", Jim_ExecCmd, NULL, NULL);
86 return JIM_OK;
88 #else
89 /* Full exec implementation for unix and mingw */
91 #include <errno.h>
92 #include <signal.h>
94 #if defined(__MINGW32__)
95 /* XXX: Should we use this implementation for cygwin too? msvc? */
96 #ifndef STRICT
97 #define STRICT
98 #endif
99 #define WIN32_LEAN_AND_MEAN
100 #include <windows.h>
101 #include <fcntl.h>
103 typedef HANDLE fdtype;
104 typedef HANDLE pidtype;
105 #define JIM_BAD_FD INVALID_HANDLE_VALUE
106 #define JIM_BAD_PID INVALID_HANDLE_VALUE
107 #define JimCloseFd CloseHandle
109 #define WIFEXITED(STATUS) 1
110 #define WEXITSTATUS(STATUS) (STATUS)
111 #define WIFSIGNALED(STATUS) 0
112 #define WTERMSIG(STATUS) 0
113 #define WNOHANG 1
115 static fdtype JimFileno(FILE *fh);
116 static pidtype JimWaitPid(pidtype pid, int *status, int nohang);
117 static fdtype JimDupFd(fdtype infd);
118 static fdtype JimOpenForRead(const char *filename);
119 static FILE *JimFdOpenForRead(fdtype fd);
120 static int JimPipe(fdtype pipefd[2]);
121 static pidtype JimStartWinProcess(Jim_Interp *interp, char **argv, char *env,
122 fdtype inputId, fdtype outputId, fdtype errorId);
123 static int JimErrno(void);
124 #else
125 #include "jim-signal.h"
126 #include <unistd.h>
127 #include <fcntl.h>
128 #include <sys/wait.h>
129 #include <sys/stat.h>
131 typedef int fdtype;
132 typedef int pidtype;
133 #define JimPipe pipe
134 #define JimErrno() errno
135 #define JIM_BAD_FD -1
136 #define JIM_BAD_PID -1
137 #define JimFileno fileno
138 #define JimReadFd read
139 #define JimCloseFd close
140 #define JimWaitPid waitpid
141 #define JimDupFd dup
142 #define JimFdOpenForRead(FD) fdopen((FD), "r")
143 #define JimOpenForRead(NAME) open((NAME), O_RDONLY, 0)
145 #ifndef HAVE_EXECVPE
146 #define execvpe(ARG0, ARGV, ENV) execvp(ARG0, ARGV)
147 #endif
148 #endif
150 static const char *JimStrError(void);
151 static char **JimSaveEnv(char **env);
152 static void JimRestoreEnv(char **env);
153 static int JimCreatePipeline(Jim_Interp *interp, int argc, Jim_Obj *const *argv,
154 pidtype **pidArrayPtr, fdtype *inPipePtr, fdtype *outPipePtr, fdtype *errFilePtr);
155 static void JimDetachPids(Jim_Interp *interp, int numPids, const pidtype *pidPtr);
156 static int JimCleanupChildren(Jim_Interp *interp, int numPids, pidtype *pidPtr, fdtype errorId);
157 static fdtype JimCreateTemp(Jim_Interp *interp, const char *contents, int len);
158 static fdtype JimOpenForWrite(const char *filename, int append);
159 static int JimRewindFd(fdtype fd);
161 static void Jim_SetResultErrno(Jim_Interp *interp, const char *msg)
163 Jim_SetResultFormatted(interp, "%s: %s", msg, JimStrError());
166 static const char *JimStrError(void)
168 return strerror(JimErrno());
172 * If the last character of 'objPtr' is a newline, then remove
173 * the newline character.
175 static void Jim_RemoveTrailingNewline(Jim_Obj *objPtr)
177 int len;
178 const char *s = Jim_GetString(objPtr, &len);
180 if (len > 0 && s[len - 1] == '\n') {
181 objPtr->length--;
182 objPtr->bytes[objPtr->length] = '\0';
187 * Read from 'fd', append the data to strObj and close 'fd'.
188 * Returns JIM_OK if OK, or JIM_ERR on error.
190 static int JimAppendStreamToString(Jim_Interp *interp, fdtype fd, Jim_Obj *strObj)
192 char buf[256];
193 FILE *fh = JimFdOpenForRead(fd);
194 if (fh == NULL) {
195 return JIM_ERR;
198 while (1) {
199 int retval = fread(buf, 1, sizeof(buf), fh);
200 if (retval > 0) {
201 Jim_AppendString(interp, strObj, buf, retval);
203 if (retval != sizeof(buf)) {
204 break;
207 Jim_RemoveTrailingNewline(strObj);
208 fclose(fh);
209 return JIM_OK;
213 * Builds the environment array from $::env
215 * If $::env is not set, simply returns environ.
217 * Otherwise allocates the environ array from the contents of $::env
219 * If the exec fails, memory can be freed via JimFreeEnv()
221 static char **JimBuildEnv(Jim_Interp *interp)
223 int i;
224 int size;
225 int num;
226 int n;
227 char **envptr;
228 char *envdata;
230 Jim_Obj *objPtr = Jim_GetGlobalVariableStr(interp, "env", JIM_NONE);
232 if (!objPtr) {
233 return Jim_GetEnviron();
236 /* We build the array as a single block consisting of the pointers followed by
237 * the strings. This has the advantage of being easy to allocate/free and being
238 * compatible with both unix and windows
241 /* Calculate the required size */
242 num = Jim_ListLength(interp, objPtr);
243 if (num % 2) {
244 /* Silently drop the last element if not a valid dictionary */
245 num--;
247 /* We need one \0 and one equal sign for each element.
248 * A list has at least one space for each element except the first.
249 * We need one extra char for the extra null terminator and one for the equal sign.
251 size = Jim_Length(objPtr) + 2;
253 envptr = Jim_Alloc(sizeof(*envptr) * (num / 2 + 1) + size);
254 envdata = (char *)&envptr[num / 2 + 1];
256 n = 0;
257 for (i = 0; i < num; i += 2) {
258 const char *s1, *s2;
259 Jim_Obj *elemObj;
261 Jim_ListIndex(interp, objPtr, i, &elemObj, JIM_NONE);
262 s1 = Jim_String(elemObj);
263 Jim_ListIndex(interp, objPtr, i + 1, &elemObj, JIM_NONE);
264 s2 = Jim_String(elemObj);
266 envptr[n] = envdata;
267 envdata += sprintf(envdata, "%s=%s", s1, s2);
268 envdata++;
269 n++;
271 envptr[n] = NULL;
272 *envdata = 0;
274 return envptr;
278 * Frees the environment allocated by JimBuildEnv()
280 * Must pass original_environ.
282 static void JimFreeEnv(char **env, char **original_environ)
284 if (env != original_environ) {
285 Jim_Free(env);
290 * Create and store an appropriate value for the global variable $::errorCode
291 * Based on pid and waitStatus.
293 * Returns JIM_OK for a normal exit with code 0, otherwise returns JIM_ERR.
295 static int JimCheckWaitStatus(Jim_Interp *interp, pidtype pid, int waitStatus)
297 Jim_Obj *errorCode = Jim_NewListObj(interp, NULL, 0);
298 int rc = JIM_ERR;
300 if (WIFEXITED(waitStatus)) {
301 if (WEXITSTATUS(waitStatus) == 0) {
302 Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, "NONE", -1));
303 rc = JIM_OK;
305 else {
306 Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, "CHILDSTATUS", -1));
307 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, (long)pid));
308 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, WEXITSTATUS(waitStatus)));
311 else {
312 const char *type;
313 const char *action;
315 if (WIFSIGNALED(waitStatus)) {
316 type = "CHILDKILLED";
317 action = "killed";
319 else {
320 type = "CHILDSUSP";
321 action = "suspended";
324 Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, type, -1));
326 #ifdef jim_ext_signal
327 Jim_SetResultFormatted(interp, "child %s by signal %s", action, Jim_SignalId(WTERMSIG(waitStatus)));
328 Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, Jim_SignalId(WTERMSIG(waitStatus)), -1));
329 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, pid));
330 Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, Jim_SignalName(WTERMSIG(waitStatus)), -1));
331 #else
332 Jim_SetResultFormatted(interp, "child %s by signal %d", action, WTERMSIG(waitStatus));
333 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, WTERMSIG(waitStatus)));
334 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, (long)pid));
335 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, WTERMSIG(waitStatus)));
336 #endif
338 Jim_SetGlobalVariableStr(interp, "errorCode", errorCode);
339 return rc;
343 * Data structures of the following type are used by JimFork and
344 * JimWaitPids to keep track of child processes.
347 struct WaitInfo
349 pidtype pid; /* Process id of child. */
350 int status; /* Status returned when child exited or suspended. */
351 int flags; /* Various flag bits; see below for definitions. */
354 struct WaitInfoTable {
355 struct WaitInfo *info; /* Table of outstanding processes */
356 int size; /* Size of the allocated table */
357 int used; /* Number of entries in use */
361 * Flag bits in WaitInfo structures:
363 * WI_DETACHED - Non-zero means no-one cares about the
364 * process anymore. Ignore it until it
365 * exits, then forget about it.
368 #define WI_DETACHED 2
370 #define WAIT_TABLE_GROW_BY 4
372 static void JimFreeWaitInfoTable(struct Jim_Interp *interp, void *privData)
374 struct WaitInfoTable *table = privData;
376 Jim_Free(table->info);
377 Jim_Free(table);
380 static struct WaitInfoTable *JimAllocWaitInfoTable(void)
382 struct WaitInfoTable *table = Jim_Alloc(sizeof(*table));
383 table->info = NULL;
384 table->size = table->used = 0;
386 return table;
390 * The main [exec] command
392 static int Jim_ExecCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
394 fdtype outputId; /* File id for output pipe. -1 means command overrode. */
395 fdtype errorId; /* File id for temporary file containing error output. */
396 pidtype *pidPtr;
397 int numPids, result;
400 * See if the command is to be run in the background; if so, create
401 * the command, detach it, and return.
403 if (argc > 1 && Jim_CompareStringImmediate(interp, argv[argc - 1], "&")) {
404 Jim_Obj *listObj;
405 int i;
407 argc--;
408 numPids = JimCreatePipeline(interp, argc - 1, argv + 1, &pidPtr, NULL, NULL, NULL);
409 if (numPids < 0) {
410 return JIM_ERR;
412 /* The return value is a list of the pids */
413 listObj = Jim_NewListObj(interp, NULL, 0);
414 for (i = 0; i < numPids; i++) {
415 Jim_ListAppendElement(interp, listObj, Jim_NewIntObj(interp, (long)pidPtr[i]));
417 Jim_SetResult(interp, listObj);
418 JimDetachPids(interp, numPids, pidPtr);
419 Jim_Free(pidPtr);
420 return JIM_OK;
424 * Create the command's pipeline.
426 numPids =
427 JimCreatePipeline(interp, argc - 1, argv + 1, &pidPtr, NULL, &outputId, &errorId);
429 if (numPids < 0) {
430 return JIM_ERR;
434 * Read the child's output (if any) and put it into the result.
436 Jim_SetResultString(interp, "", 0);
438 result = JIM_OK;
439 if (outputId != JIM_BAD_FD) {
440 result = JimAppendStreamToString(interp, outputId, Jim_GetResult(interp));
441 if (result < 0) {
442 Jim_SetResultErrno(interp, "error reading from output pipe");
446 if (JimCleanupChildren(interp, numPids, pidPtr, errorId) != JIM_OK) {
447 result = JIM_ERR;
449 return result;
452 static void JimReapDetachedPids(struct WaitInfoTable *table)
454 struct WaitInfo *waitPtr;
455 int count;
456 int dest;
458 if (!table) {
459 return;
462 waitPtr = table->info;
463 dest = 0;
464 for (count = table->used; count > 0; waitPtr++, count--) {
465 if (waitPtr->flags & WI_DETACHED) {
466 int status;
467 pidtype pid = JimWaitPid(waitPtr->pid, &status, WNOHANG);
468 if (pid == waitPtr->pid) {
469 /* Process has exited, so remove it from the table */
470 table->used--;
471 continue;
474 if (waitPtr != &table->info[dest]) {
475 table->info[dest] = *waitPtr;
477 dest++;
482 * Does waitpid() on the given pid, and then removes the
483 * entry from the wait table.
485 * Returns the pid if OK and updates *statusPtr with the status,
486 * or JIM_BAD_PID if the pid was not in the table.
488 static pidtype JimWaitForProcess(struct WaitInfoTable *table, pidtype pid, int *statusPtr)
490 int i;
492 /* Find it in the table */
493 for (i = 0; i < table->used; i++) {
494 if (pid == table->info[i].pid) {
495 /* wait for it */
496 JimWaitPid(pid, statusPtr, 0);
498 /* Remove it from the table */
499 if (i != table->used - 1) {
500 table->info[i] = table->info[table->used - 1];
502 table->used--;
503 return pid;
507 /* Not found */
508 return JIM_BAD_PID;
512 * Indicates that one or more child processes have been placed in
513 * background and are no longer cared about.
514 * These children can be cleaned up with JimReapDetachedPids().
516 static void JimDetachPids(Jim_Interp *interp, int numPids, const pidtype *pidPtr)
518 int j;
519 struct WaitInfoTable *table = Jim_CmdPrivData(interp);
521 for (j = 0; j < numPids; j++) {
522 /* Find it in the table */
523 int i;
524 for (i = 0; i < table->used; i++) {
525 if (pidPtr[j] == table->info[i].pid) {
526 table->info[i].flags |= WI_DETACHED;
527 break;
533 static FILE *JimGetAioFilehandle(Jim_Interp *interp, const char *name)
535 FILE *fh;
536 Jim_Obj *fhObj;
538 fhObj = Jim_NewStringObj(interp, name, -1);
539 Jim_IncrRefCount(fhObj);
540 fh = Jim_AioFilehandle(interp, fhObj);
541 Jim_DecrRefCount(interp, fhObj);
543 return fh;
547 *----------------------------------------------------------------------
549 * JimCreatePipeline --
551 * Given an argc/argv array, instantiate a pipeline of processes
552 * as described by the argv.
554 * Results:
555 * The return value is a count of the number of new processes
556 * created, or -1 if an error occurred while creating the pipeline.
557 * *pidArrayPtr is filled in with the address of a dynamically
558 * allocated array giving the ids of all of the processes. It
559 * is up to the caller to free this array when it isn't needed
560 * anymore. If inPipePtr is non-NULL, *inPipePtr is filled in
561 * with the file id for the input pipe for the pipeline (if any):
562 * the caller must eventually close this file. If outPipePtr
563 * isn't NULL, then *outPipePtr is filled in with the file id
564 * for the output pipe from the pipeline: the caller must close
565 * this file. If errFilePtr isn't NULL, then *errFilePtr is filled
566 * with a file id that may be used to read error output after the
567 * pipeline completes.
569 * Side effects:
570 * Processes and pipes are created.
572 *----------------------------------------------------------------------
574 static int
575 JimCreatePipeline(Jim_Interp *interp, int argc, Jim_Obj *const *argv, pidtype **pidArrayPtr,
576 fdtype *inPipePtr, fdtype *outPipePtr, fdtype *errFilePtr)
578 pidtype *pidPtr = NULL; /* Points to malloc-ed array holding all
579 * the pids of child processes. */
580 int numPids = 0; /* Actual number of processes that exist
581 * at *pidPtr right now. */
582 int cmdCount; /* Count of number of distinct commands
583 * found in argc/argv. */
584 const char *input = NULL; /* Describes input for pipeline, depending
585 * on "inputFile". NULL means take input
586 * from stdin/pipe. */
587 int input_len = 0; /* Length of input, if relevant */
589 #define FILE_NAME 0 /* input/output: filename */
590 #define FILE_APPEND 1 /* output only: filename, append */
591 #define FILE_HANDLE 2 /* input/output: filehandle */
592 #define FILE_TEXT 3 /* input only: input is actual text */
594 int inputFile = FILE_NAME; /* 1 means input is name of input file.
595 * 2 means input is filehandle name.
596 * 0 means input holds actual
597 * text to be input to command. */
599 int outputFile = FILE_NAME; /* 0 means output is the name of output file.
600 * 1 means output is the name of output file, and append.
601 * 2 means output is filehandle name.
602 * All this is ignored if output is NULL
604 int errorFile = FILE_NAME; /* 0 means error is the name of error file.
605 * 1 means error is the name of error file, and append.
606 * 2 means error is filehandle name.
607 * All this is ignored if error is NULL
609 const char *output = NULL; /* Holds name of output file to pipe to,
610 * or NULL if output goes to stdout/pipe. */
611 const char *error = NULL; /* Holds name of stderr file to pipe to,
612 * or NULL if stderr goes to stderr/pipe. */
613 fdtype inputId = JIM_BAD_FD;
614 /* Readable file id input to current command in
615 * pipeline (could be file or pipe). JIM_BAD_FD
616 * means use stdin. */
617 fdtype outputId = JIM_BAD_FD;
618 /* Writable file id for output from current
619 * command in pipeline (could be file or pipe).
620 * JIM_BAD_FD means use stdout. */
621 fdtype errorId = JIM_BAD_FD;
622 /* Writable file id for all standard error
623 * output from all commands in pipeline. JIM_BAD_FD
624 * means use stderr. */
625 fdtype lastOutputId = JIM_BAD_FD;
626 /* Write file id for output from last command
627 * in pipeline (could be file or pipe).
628 * -1 means use stdout. */
629 fdtype pipeIds[2]; /* File ids for pipe that's being created. */
630 int firstArg, lastArg; /* Indexes of first and last arguments in
631 * current command. */
632 int lastBar;
633 int i;
634 pidtype pid;
635 char **save_environ;
636 struct WaitInfoTable *table = Jim_CmdPrivData(interp);
638 /* Holds the args which will be used to exec */
639 char **arg_array = Jim_Alloc(sizeof(*arg_array) * (argc + 1));
640 int arg_count = 0;
642 JimReapDetachedPids(table);
644 if (inPipePtr != NULL) {
645 *inPipePtr = JIM_BAD_FD;
647 if (outPipePtr != NULL) {
648 *outPipePtr = JIM_BAD_FD;
650 if (errFilePtr != NULL) {
651 *errFilePtr = JIM_BAD_FD;
653 pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
656 * First, scan through all the arguments to figure out the structure
657 * of the pipeline. Count the number of distinct processes (it's the
658 * number of "|" arguments). If there are "<", "<<", or ">" arguments
659 * then make note of input and output redirection and remove these
660 * arguments and the arguments that follow them.
662 cmdCount = 1;
663 lastBar = -1;
664 for (i = 0; i < argc; i++) {
665 const char *arg = Jim_String(argv[i]);
667 if (arg[0] == '<') {
668 inputFile = FILE_NAME;
669 input = arg + 1;
670 if (*input == '<') {
671 inputFile = FILE_TEXT;
672 input_len = Jim_Length(argv[i]) - 2;
673 input++;
675 else if (*input == '@') {
676 inputFile = FILE_HANDLE;
677 input++;
680 if (!*input && ++i < argc) {
681 input = Jim_GetString(argv[i], &input_len);
684 else if (arg[0] == '>') {
685 int dup_error = 0;
687 outputFile = FILE_NAME;
689 output = arg + 1;
690 if (*output == '>') {
691 outputFile = FILE_APPEND;
692 output++;
694 if (*output == '&') {
695 /* Redirect stderr too */
696 output++;
697 dup_error = 1;
699 if (*output == '@') {
700 outputFile = FILE_HANDLE;
701 output++;
703 if (!*output && ++i < argc) {
704 output = Jim_String(argv[i]);
706 if (dup_error) {
707 errorFile = outputFile;
708 error = output;
711 else if (arg[0] == '2' && arg[1] == '>') {
712 error = arg + 2;
713 errorFile = FILE_NAME;
715 if (*error == '@') {
716 errorFile = FILE_HANDLE;
717 error++;
719 else if (*error == '>') {
720 errorFile = FILE_APPEND;
721 error++;
723 if (!*error && ++i < argc) {
724 error = Jim_String(argv[i]);
727 else {
728 if (strcmp(arg, "|") == 0 || strcmp(arg, "|&") == 0) {
729 if (i == lastBar + 1 || i == argc - 1) {
730 Jim_SetResultString(interp, "illegal use of | or |& in command", -1);
731 goto badargs;
733 lastBar = i;
734 cmdCount++;
736 /* Either |, |& or a "normal" arg, so store it in the arg array */
737 arg_array[arg_count++] = (char *)arg;
738 continue;
741 if (i >= argc) {
742 Jim_SetResultFormatted(interp, "can't specify \"%s\" as last word in command", arg);
743 goto badargs;
747 if (arg_count == 0) {
748 Jim_SetResultString(interp, "didn't specify command to execute", -1);
749 badargs:
750 Jim_Free(arg_array);
751 return -1;
754 /* Must do this before vfork(), so do it now */
755 save_environ = JimSaveEnv(JimBuildEnv(interp));
758 * Set up the redirected input source for the pipeline, if
759 * so requested.
761 if (input != NULL) {
762 if (inputFile == FILE_TEXT) {
764 * Immediate data in command. Create temporary file and
765 * put data into file.
767 inputId = JimCreateTemp(interp, input, input_len);
768 if (inputId == JIM_BAD_FD) {
769 goto error;
772 else if (inputFile == FILE_HANDLE) {
773 /* Should be a file descriptor */
774 FILE *fh = JimGetAioFilehandle(interp, input);
776 if (fh == NULL) {
777 goto error;
779 inputId = JimDupFd(JimFileno(fh));
781 else {
783 * File redirection. Just open the file.
785 inputId = JimOpenForRead(input);
786 if (inputId == JIM_BAD_FD) {
787 Jim_SetResultFormatted(interp, "couldn't read file \"%s\": %s", input, JimStrError());
788 goto error;
792 else if (inPipePtr != NULL) {
793 if (JimPipe(pipeIds) != 0) {
794 Jim_SetResultErrno(interp, "couldn't create input pipe for command");
795 goto error;
797 inputId = pipeIds[0];
798 *inPipePtr = pipeIds[1];
799 pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
803 * Set up the redirected output sink for the pipeline from one
804 * of two places, if requested.
806 if (output != NULL) {
807 if (outputFile == FILE_HANDLE) {
808 FILE *fh = JimGetAioFilehandle(interp, output);
809 if (fh == NULL) {
810 goto error;
812 fflush(fh);
813 lastOutputId = JimDupFd(JimFileno(fh));
815 else {
817 * Output is to go to a file.
819 lastOutputId = JimOpenForWrite(output, outputFile == FILE_APPEND);
820 if (lastOutputId == JIM_BAD_FD) {
821 Jim_SetResultFormatted(interp, "couldn't write file \"%s\": %s", output, JimStrError());
822 goto error;
826 else if (outPipePtr != NULL) {
828 * Output is to go to a pipe.
830 if (JimPipe(pipeIds) != 0) {
831 Jim_SetResultErrno(interp, "couldn't create output pipe");
832 goto error;
834 lastOutputId = pipeIds[1];
835 *outPipePtr = pipeIds[0];
836 pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
838 /* If we are redirecting stderr with 2>filename or 2>@fileId, then we ignore errFilePtr */
839 if (error != NULL) {
840 if (errorFile == FILE_HANDLE) {
841 if (strcmp(error, "1") == 0) {
842 /* Special 2>@1 */
843 if (lastOutputId != JIM_BAD_FD) {
844 errorId = JimDupFd(lastOutputId);
846 else {
847 /* No redirection of stdout, so just use 2>@stdout */
848 error = "stdout";
851 if (errorId == JIM_BAD_FD) {
852 FILE *fh = JimGetAioFilehandle(interp, error);
853 if (fh == NULL) {
854 goto error;
856 fflush(fh);
857 errorId = JimDupFd(JimFileno(fh));
860 else {
862 * Output is to go to a file.
864 errorId = JimOpenForWrite(error, errorFile == FILE_APPEND);
865 if (errorId == JIM_BAD_FD) {
866 Jim_SetResultFormatted(interp, "couldn't write file \"%s\": %s", error, JimStrError());
867 goto error;
871 else if (errFilePtr != NULL) {
873 * Set up the standard error output sink for the pipeline, if
874 * requested. Use a temporary file which is opened, then deleted.
875 * Could potentially just use pipe, but if it filled up it could
876 * cause the pipeline to deadlock: we'd be waiting for processes
877 * to complete before reading stderr, and processes couldn't complete
878 * because stderr was backed up.
880 errorId = JimCreateTemp(interp, NULL, 0);
881 if (errorId == JIM_BAD_FD) {
882 goto error;
884 *errFilePtr = JimDupFd(errorId);
888 * Scan through the argc array, forking off a process for each
889 * group of arguments between "|" arguments.
892 pidPtr = Jim_Alloc(cmdCount * sizeof(*pidPtr));
893 for (i = 0; i < numPids; i++) {
894 pidPtr[i] = JIM_BAD_PID;
896 for (firstArg = 0; firstArg < arg_count; numPids++, firstArg = lastArg + 1) {
897 int pipe_dup_err = 0;
898 fdtype origErrorId = errorId;
900 for (lastArg = firstArg; lastArg < arg_count; lastArg++) {
901 if (arg_array[lastArg][0] == '|') {
902 if (arg_array[lastArg][1] == '&') {
903 pipe_dup_err = 1;
905 break;
908 /* Replace | with NULL for execv() */
909 arg_array[lastArg] = NULL;
910 if (lastArg == arg_count) {
911 outputId = lastOutputId;
913 else {
914 if (JimPipe(pipeIds) != 0) {
915 Jim_SetResultErrno(interp, "couldn't create pipe");
916 goto error;
918 outputId = pipeIds[1];
921 /* Need to do this befor vfork() */
922 if (pipe_dup_err) {
923 errorId = outputId;
926 /* Now fork the child */
928 #ifdef __MINGW32__
929 pid = JimStartWinProcess(interp, &arg_array[firstArg], save_environ ? save_environ[0] : NULL, inputId, outputId, errorId);
930 if (pid == JIM_BAD_PID) {
931 Jim_SetResultFormatted(interp, "couldn't exec \"%s\"", arg_array[firstArg]);
932 goto error;
934 #else
936 * Make a new process and enter it into the table if the fork
937 * is successful.
939 pid = vfork();
940 if (pid < 0) {
941 Jim_SetResultErrno(interp, "couldn't fork child process");
942 goto error;
944 if (pid == 0) {
945 /* Child */
947 if (inputId != -1) dup2(inputId, 0);
948 if (outputId != -1) dup2(outputId, 1);
949 if (errorId != -1) dup2(errorId, 2);
951 for (i = 3; (i <= outputId) || (i <= inputId) || (i <= errorId); i++) {
952 close(i);
955 /* Restore SIGPIPE behaviour */
956 (void)signal(SIGPIPE, SIG_DFL);
958 execvpe(arg_array[firstArg], &arg_array[firstArg], Jim_GetEnviron());
960 /* Need to prep an error message before vfork(), just in case */
961 fprintf(stderr, "couldn't exec \"%s\"\n", arg_array[firstArg]);
962 _exit(127);
964 #endif
966 /* parent */
969 * Enlarge the wait table if there isn't enough space for a new
970 * entry.
972 if (table->used == table->size) {
973 table->size += WAIT_TABLE_GROW_BY;
974 table->info = Jim_Realloc(table->info, table->size * sizeof(*table->info));
977 table->info[table->used].pid = pid;
978 table->info[table->used].flags = 0;
979 table->used++;
981 pidPtr[numPids] = pid;
983 /* Restore in case of pipe_dup_err */
984 errorId = origErrorId;
987 * Close off our copies of file descriptors that were set up for
988 * this child, then set up the input for the next child.
991 if (inputId != JIM_BAD_FD) {
992 JimCloseFd(inputId);
994 if (outputId != JIM_BAD_FD) {
995 JimCloseFd(outputId);
997 inputId = pipeIds[0];
998 pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
1000 *pidArrayPtr = pidPtr;
1003 * All done. Cleanup open files lying around and then return.
1006 cleanup:
1007 if (inputId != JIM_BAD_FD) {
1008 JimCloseFd(inputId);
1010 if (lastOutputId != JIM_BAD_FD) {
1011 JimCloseFd(lastOutputId);
1013 if (errorId != JIM_BAD_FD) {
1014 JimCloseFd(errorId);
1016 Jim_Free(arg_array);
1018 JimRestoreEnv(save_environ);
1020 return numPids;
1023 * An error occurred. There could have been extra files open, such
1024 * as pipes between children. Clean them all up. Detach any child
1025 * processes that have been created.
1028 error:
1029 if ((inPipePtr != NULL) && (*inPipePtr != JIM_BAD_FD)) {
1030 JimCloseFd(*inPipePtr);
1031 *inPipePtr = JIM_BAD_FD;
1033 if ((outPipePtr != NULL) && (*outPipePtr != JIM_BAD_FD)) {
1034 JimCloseFd(*outPipePtr);
1035 *outPipePtr = JIM_BAD_FD;
1037 if ((errFilePtr != NULL) && (*errFilePtr != JIM_BAD_FD)) {
1038 JimCloseFd(*errFilePtr);
1039 *errFilePtr = JIM_BAD_FD;
1041 if (pipeIds[0] != JIM_BAD_FD) {
1042 JimCloseFd(pipeIds[0]);
1044 if (pipeIds[1] != JIM_BAD_FD) {
1045 JimCloseFd(pipeIds[1]);
1047 if (pidPtr != NULL) {
1048 for (i = 0; i < numPids; i++) {
1049 if (pidPtr[i] != JIM_BAD_PID) {
1050 JimDetachPids(interp, 1, &pidPtr[i]);
1053 Jim_Free(pidPtr);
1055 numPids = -1;
1056 goto cleanup;
1060 *----------------------------------------------------------------------
1062 * JimCleanupChildren --
1064 * This is a utility procedure used to wait for child processes
1065 * to exit, record information about abnormal exits, and then
1066 * collect any stderr output generated by them.
1068 * Results:
1069 * The return value is a standard Tcl result. If anything at
1070 * weird happened with the child processes, JIM_ERROR is returned
1071 * and a message is left in interp->result.
1073 * Side effects:
1074 * If the last character of interp->result is a newline, then it
1075 * is removed. File errorId gets closed, and pidPtr is freed
1076 * back to the storage allocator.
1078 *----------------------------------------------------------------------
1081 static int JimCleanupChildren(Jim_Interp *interp, int numPids, pidtype *pidPtr, fdtype errorId)
1083 struct WaitInfoTable *table = Jim_CmdPrivData(interp);
1084 int result = JIM_OK;
1085 int i;
1087 for (i = 0; i < numPids; i++) {
1088 int waitStatus = 0;
1089 if (JimWaitForProcess(table, pidPtr[i], &waitStatus) != JIM_BAD_PID) {
1090 if (JimCheckWaitStatus(interp, pidPtr[i], waitStatus) != JIM_OK) {
1091 result = JIM_ERR;
1095 Jim_Free(pidPtr);
1098 * Read the standard error file. If there's anything there,
1099 * then add the file's contents to the result
1100 * string.
1102 if (errorId != JIM_BAD_FD) {
1103 JimRewindFd(errorId);
1104 if (JimAppendStreamToString(interp, errorId, Jim_GetResult(interp)) != JIM_OK) {
1105 result = JIM_ERR;
1109 Jim_RemoveTrailingNewline(Jim_GetResult(interp));
1111 return result;
1114 int Jim_execInit(Jim_Interp *interp)
1116 if (Jim_PackageProvide(interp, "exec", "1.0", JIM_ERRMSG))
1117 return JIM_ERR;
1119 #ifdef SIGPIPE
1121 * Disable SIGPIPE signals: if they were allowed, this process
1122 * might go away unexpectedly if children misbehave. This code
1123 * can potentially interfere with other application code that
1124 * expects to handle SIGPIPEs.
1126 * By doing this in the init function, applications can override
1127 * this later. Note that child processes have SIGPIPE restored
1128 * to the default after vfork().
1130 (void)signal(SIGPIPE, SIG_IGN);
1131 #endif
1133 Jim_CreateCommand(interp, "exec", Jim_ExecCmd, JimAllocWaitInfoTable(), JimFreeWaitInfoTable);
1134 return JIM_OK;
1137 #if defined(__MINGW32__)
1138 /* Windows-specific (mingw) implementation */
1140 static SECURITY_ATTRIBUTES *JimStdSecAttrs(void)
1142 static SECURITY_ATTRIBUTES secAtts;
1144 secAtts.nLength = sizeof(SECURITY_ATTRIBUTES);
1145 secAtts.lpSecurityDescriptor = NULL;
1146 secAtts.bInheritHandle = TRUE;
1147 return &secAtts;
1150 static int JimErrno(void)
1152 switch (GetLastError()) {
1153 case ERROR_FILE_NOT_FOUND: return ENOENT;
1154 case ERROR_PATH_NOT_FOUND: return ENOENT;
1155 case ERROR_TOO_MANY_OPEN_FILES: return EMFILE;
1156 case ERROR_ACCESS_DENIED: return EACCES;
1157 case ERROR_INVALID_HANDLE: return EBADF;
1158 case ERROR_BAD_ENVIRONMENT: return E2BIG;
1159 case ERROR_BAD_FORMAT: return ENOEXEC;
1160 case ERROR_INVALID_ACCESS: return EACCES;
1161 case ERROR_INVALID_DRIVE: return ENOENT;
1162 case ERROR_CURRENT_DIRECTORY: return EACCES;
1163 case ERROR_NOT_SAME_DEVICE: return EXDEV;
1164 case ERROR_NO_MORE_FILES: return ENOENT;
1165 case ERROR_WRITE_PROTECT: return EROFS;
1166 case ERROR_BAD_UNIT: return ENXIO;
1167 case ERROR_NOT_READY: return EBUSY;
1168 case ERROR_BAD_COMMAND: return EIO;
1169 case ERROR_CRC: return EIO;
1170 case ERROR_BAD_LENGTH: return EIO;
1171 case ERROR_SEEK: return EIO;
1172 case ERROR_WRITE_FAULT: return EIO;
1173 case ERROR_READ_FAULT: return EIO;
1174 case ERROR_GEN_FAILURE: return EIO;
1175 case ERROR_SHARING_VIOLATION: return EACCES;
1176 case ERROR_LOCK_VIOLATION: return EACCES;
1177 case ERROR_SHARING_BUFFER_EXCEEDED: return ENFILE;
1178 case ERROR_HANDLE_DISK_FULL: return ENOSPC;
1179 case ERROR_NOT_SUPPORTED: return ENODEV;
1180 case ERROR_REM_NOT_LIST: return EBUSY;
1181 case ERROR_DUP_NAME: return EEXIST;
1182 case ERROR_BAD_NETPATH: return ENOENT;
1183 case ERROR_NETWORK_BUSY: return EBUSY;
1184 case ERROR_DEV_NOT_EXIST: return ENODEV;
1185 case ERROR_TOO_MANY_CMDS: return EAGAIN;
1186 case ERROR_ADAP_HDW_ERR: return EIO;
1187 case ERROR_BAD_NET_RESP: return EIO;
1188 case ERROR_UNEXP_NET_ERR: return EIO;
1189 case ERROR_NETNAME_DELETED: return ENOENT;
1190 case ERROR_NETWORK_ACCESS_DENIED: return EACCES;
1191 case ERROR_BAD_DEV_TYPE: return ENODEV;
1192 case ERROR_BAD_NET_NAME: return ENOENT;
1193 case ERROR_TOO_MANY_NAMES: return ENFILE;
1194 case ERROR_TOO_MANY_SESS: return EIO;
1195 case ERROR_SHARING_PAUSED: return EAGAIN;
1196 case ERROR_REDIR_PAUSED: return EAGAIN;
1197 case ERROR_FILE_EXISTS: return EEXIST;
1198 case ERROR_CANNOT_MAKE: return ENOSPC;
1199 case ERROR_OUT_OF_STRUCTURES: return ENFILE;
1200 case ERROR_ALREADY_ASSIGNED: return EEXIST;
1201 case ERROR_INVALID_PASSWORD: return EPERM;
1202 case ERROR_NET_WRITE_FAULT: return EIO;
1203 case ERROR_NO_PROC_SLOTS: return EAGAIN;
1204 case ERROR_DISK_CHANGE: return EXDEV;
1205 case ERROR_BROKEN_PIPE: return EPIPE;
1206 case ERROR_OPEN_FAILED: return ENOENT;
1207 case ERROR_DISK_FULL: return ENOSPC;
1208 case ERROR_NO_MORE_SEARCH_HANDLES: return EMFILE;
1209 case ERROR_INVALID_TARGET_HANDLE: return EBADF;
1210 case ERROR_INVALID_NAME: return ENOENT;
1211 case ERROR_PROC_NOT_FOUND: return ESRCH;
1212 case ERROR_WAIT_NO_CHILDREN: return ECHILD;
1213 case ERROR_CHILD_NOT_COMPLETE: return ECHILD;
1214 case ERROR_DIRECT_ACCESS_HANDLE: return EBADF;
1215 case ERROR_SEEK_ON_DEVICE: return ESPIPE;
1216 case ERROR_BUSY_DRIVE: return EAGAIN;
1217 case ERROR_DIR_NOT_EMPTY: return EEXIST;
1218 case ERROR_NOT_LOCKED: return EACCES;
1219 case ERROR_BAD_PATHNAME: return ENOENT;
1220 case ERROR_LOCK_FAILED: return EACCES;
1221 case ERROR_ALREADY_EXISTS: return EEXIST;
1222 case ERROR_FILENAME_EXCED_RANGE: return ENAMETOOLONG;
1223 case ERROR_BAD_PIPE: return EPIPE;
1224 case ERROR_PIPE_BUSY: return EAGAIN;
1225 case ERROR_PIPE_NOT_CONNECTED: return EPIPE;
1226 case ERROR_DIRECTORY: return ENOTDIR;
1228 return EINVAL;
1231 static int JimPipe(fdtype pipefd[2])
1233 if (CreatePipe(&pipefd[0], &pipefd[1], NULL, 0)) {
1234 return 0;
1236 return -1;
1239 static fdtype JimDupFd(fdtype infd)
1241 fdtype dupfd;
1242 pidtype pid = GetCurrentProcess();
1244 if (DuplicateHandle(pid, infd, pid, &dupfd, 0, TRUE, DUPLICATE_SAME_ACCESS)) {
1245 return dupfd;
1247 return JIM_BAD_FD;
1250 static int JimRewindFd(fdtype fd)
1252 return SetFilePointer(fd, 0, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER ? -1 : 0;
1255 #if 0
1256 static int JimReadFd(fdtype fd, char *buffer, size_t len)
1258 DWORD num;
1260 if (ReadFile(fd, buffer, len, &num, NULL)) {
1261 return num;
1263 if (GetLastError() == ERROR_HANDLE_EOF || GetLastError() == ERROR_BROKEN_PIPE) {
1264 return 0;
1266 return -1;
1268 #endif
1270 static FILE *JimFdOpenForRead(fdtype fd)
1272 return _fdopen(_open_osfhandle((int)fd, _O_RDONLY | _O_TEXT), "r");
1275 static fdtype JimFileno(FILE *fh)
1277 return (fdtype)_get_osfhandle(_fileno(fh));
1280 static fdtype JimOpenForRead(const char *filename)
1282 return CreateFile(filename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
1283 JimStdSecAttrs(), OPEN_EXISTING, 0, NULL);
1286 static fdtype JimOpenForWrite(const char *filename, int append)
1288 return CreateFile(filename, append ? FILE_APPEND_DATA : GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
1289 JimStdSecAttrs(), append ? OPEN_ALWAYS : CREATE_ALWAYS, 0, (HANDLE) NULL);
1292 static FILE *JimFdOpenForWrite(fdtype fd)
1294 return _fdopen(_open_osfhandle((int)fd, _O_TEXT), "w");
1297 static pidtype JimWaitPid(pidtype pid, int *status, int nohang)
1299 DWORD ret = WaitForSingleObject(pid, nohang ? 0 : INFINITE);
1300 if (ret == WAIT_TIMEOUT || ret == WAIT_FAILED) {
1301 /* WAIT_TIMEOUT can only happend with WNOHANG */
1302 return JIM_BAD_PID;
1304 GetExitCodeProcess(pid, &ret);
1305 *status = ret;
1306 CloseHandle(pid);
1307 return pid;
1310 static HANDLE JimCreateTemp(Jim_Interp *interp, const char *contents, int len)
1312 char name[MAX_PATH];
1313 HANDLE handle;
1315 if (!GetTempPath(MAX_PATH, name) || !GetTempFileName(name, "JIM", 0, name)) {
1316 return JIM_BAD_FD;
1319 handle = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, JimStdSecAttrs(),
1320 CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE,
1321 NULL);
1323 if (handle == INVALID_HANDLE_VALUE) {
1324 goto error;
1327 if (contents != NULL) {
1328 /* Use fdopen() to get automatic text-mode translation */
1329 FILE *fh = JimFdOpenForWrite(JimDupFd(handle));
1330 if (fh == NULL) {
1331 goto error;
1334 if (fwrite(contents, len, 1, fh) != 1) {
1335 fclose(fh);
1336 goto error;
1338 fseek(fh, 0, SEEK_SET);
1339 fclose(fh);
1341 return handle;
1343 error:
1344 Jim_SetResultErrno(interp, "failed to create temp file");
1345 CloseHandle(handle);
1346 DeleteFile(name);
1347 return JIM_BAD_FD;
1350 static int
1351 JimWinFindExecutable(const char *originalName, char fullPath[MAX_PATH])
1353 int i;
1354 static char extensions[][5] = {".exe", "", ".bat"};
1356 for (i = 0; i < (int) (sizeof(extensions) / sizeof(extensions[0])); i++) {
1357 lstrcpyn(fullPath, originalName, MAX_PATH - 5);
1358 lstrcat(fullPath, extensions[i]);
1360 if (SearchPath(NULL, fullPath, NULL, MAX_PATH, fullPath, NULL) == 0) {
1361 continue;
1363 if (GetFileAttributes(fullPath) & FILE_ATTRIBUTE_DIRECTORY) {
1364 continue;
1366 return 0;
1369 return -1;
1372 static char **JimSaveEnv(char **env)
1374 return env;
1377 static void JimRestoreEnv(char **env)
1379 JimFreeEnv(env, Jim_GetEnviron());
1382 static Jim_Obj *
1383 JimWinBuildCommandLine(Jim_Interp *interp, char **argv)
1385 char *start, *special;
1386 int quote, i;
1388 Jim_Obj *strObj = Jim_NewStringObj(interp, "", 0);
1390 for (i = 0; argv[i]; i++) {
1391 if (i > 0) {
1392 Jim_AppendString(interp, strObj, " ", 1);
1395 if (argv[i][0] == '\0') {
1396 quote = 1;
1398 else {
1399 quote = 0;
1400 for (start = argv[i]; *start != '\0'; start++) {
1401 if (isspace(UCHAR(*start))) {
1402 quote = 1;
1403 break;
1407 if (quote) {
1408 Jim_AppendString(interp, strObj, "\"" , 1);
1411 start = argv[i];
1412 for (special = argv[i]; ; ) {
1413 if ((*special == '\\') && (special[1] == '\\' ||
1414 special[1] == '"' || (quote && special[1] == '\0'))) {
1415 Jim_AppendString(interp, strObj, start, special - start);
1416 start = special;
1417 while (1) {
1418 special++;
1419 if (*special == '"' || (quote && *special == '\0')) {
1421 * N backslashes followed a quote -> insert
1422 * N * 2 + 1 backslashes then a quote.
1425 Jim_AppendString(interp, strObj, start, special - start);
1426 break;
1428 if (*special != '\\') {
1429 break;
1432 Jim_AppendString(interp, strObj, start, special - start);
1433 start = special;
1435 if (*special == '"') {
1436 if (special == start) {
1437 Jim_AppendString(interp, strObj, "\"", 1);
1439 else {
1440 Jim_AppendString(interp, strObj, start, special - start);
1442 Jim_AppendString(interp, strObj, "\\\"", 2);
1443 start = special + 1;
1445 if (*special == '\0') {
1446 break;
1448 special++;
1450 Jim_AppendString(interp, strObj, start, special - start);
1451 if (quote) {
1452 Jim_AppendString(interp, strObj, "\"", 1);
1455 return strObj;
1458 static pidtype
1459 JimStartWinProcess(Jim_Interp *interp, char **argv, char *env, fdtype inputId, fdtype outputId, fdtype errorId)
1461 STARTUPINFO startInfo;
1462 PROCESS_INFORMATION procInfo;
1463 HANDLE hProcess, h;
1464 char execPath[MAX_PATH];
1465 pidtype pid = JIM_BAD_PID;
1466 Jim_Obj *cmdLineObj;
1468 if (JimWinFindExecutable(argv[0], execPath) < 0) {
1469 return JIM_BAD_PID;
1471 argv[0] = execPath;
1473 hProcess = GetCurrentProcess();
1474 cmdLineObj = JimWinBuildCommandLine(interp, argv);
1477 * STARTF_USESTDHANDLES must be used to pass handles to child process.
1478 * Using SetStdHandle() and/or dup2() only works when a console mode
1479 * parent process is spawning an attached console mode child process.
1482 ZeroMemory(&startInfo, sizeof(startInfo));
1483 startInfo.cb = sizeof(startInfo);
1484 startInfo.dwFlags = STARTF_USESTDHANDLES;
1485 startInfo.hStdInput = INVALID_HANDLE_VALUE;
1486 startInfo.hStdOutput= INVALID_HANDLE_VALUE;
1487 startInfo.hStdError = INVALID_HANDLE_VALUE;
1490 * Duplicate all the handles which will be passed off as stdin, stdout
1491 * and stderr of the child process. The duplicate handles are set to
1492 * be inheritable, so the child process can use them.
1494 if (inputId == JIM_BAD_FD) {
1495 if (CreatePipe(&startInfo.hStdInput, &h, JimStdSecAttrs(), 0) != FALSE) {
1496 CloseHandle(h);
1498 } else {
1499 DuplicateHandle(hProcess, inputId, hProcess, &startInfo.hStdInput,
1500 0, TRUE, DUPLICATE_SAME_ACCESS);
1502 if (startInfo.hStdInput == JIM_BAD_FD) {
1503 goto end;
1506 if (outputId == JIM_BAD_FD) {
1507 startInfo.hStdOutput = CreateFile("NUL:", GENERIC_WRITE, 0,
1508 JimStdSecAttrs(), OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1509 } else {
1510 DuplicateHandle(hProcess, outputId, hProcess, &startInfo.hStdOutput,
1511 0, TRUE, DUPLICATE_SAME_ACCESS);
1513 if (startInfo.hStdOutput == JIM_BAD_FD) {
1514 goto end;
1517 if (errorId == JIM_BAD_FD) {
1519 * If handle was not set, errors should be sent to an infinitely
1520 * deep sink.
1523 startInfo.hStdError = CreateFile("NUL:", GENERIC_WRITE, 0,
1524 JimStdSecAttrs(), OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1525 } else {
1526 DuplicateHandle(hProcess, errorId, hProcess, &startInfo.hStdError,
1527 0, TRUE, DUPLICATE_SAME_ACCESS);
1529 if (startInfo.hStdError == JIM_BAD_FD) {
1530 goto end;
1533 if (!CreateProcess(NULL, (char *)Jim_String(cmdLineObj), NULL, NULL, TRUE,
1534 0, env, NULL, &startInfo, &procInfo)) {
1535 goto end;
1539 * "When an application spawns a process repeatedly, a new thread
1540 * instance will be created for each process but the previous
1541 * instances may not be cleaned up. This results in a significant
1542 * virtual memory loss each time the process is spawned. If there
1543 * is a WaitForInputIdle() call between CreateProcess() and
1544 * CloseHandle(), the problem does not occur." PSS ID Number: Q124121
1547 WaitForInputIdle(procInfo.hProcess, 5000);
1548 CloseHandle(procInfo.hThread);
1550 pid = procInfo.hProcess;
1552 end:
1553 Jim_FreeNewObj(interp, cmdLineObj);
1554 if (startInfo.hStdInput != JIM_BAD_FD) {
1555 CloseHandle(startInfo.hStdInput);
1557 if (startInfo.hStdOutput != JIM_BAD_FD) {
1558 CloseHandle(startInfo.hStdOutput);
1560 if (startInfo.hStdError != JIM_BAD_FD) {
1561 CloseHandle(startInfo.hStdError);
1563 return pid;
1565 #else
1566 /* Unix-specific implementation */
1567 static int JimOpenForWrite(const char *filename, int append)
1569 return open(filename, O_WRONLY | O_CREAT | (append ? O_APPEND : O_TRUNC), 0666);
1572 static int JimRewindFd(int fd)
1574 return lseek(fd, 0L, SEEK_SET);
1577 static int JimCreateTemp(Jim_Interp *interp, const char *contents, int len)
1579 int fd = Jim_MakeTempFile(interp, NULL);
1581 if (fd != JIM_BAD_FD) {
1582 unlink(Jim_String(Jim_GetResult(interp)));
1583 if (contents) {
1584 if (write(fd, contents, len) != len) {
1585 Jim_SetResultErrno(interp, "couldn't write temp file");
1586 close(fd);
1587 return -1;
1589 lseek(fd, 0L, SEEK_SET);
1592 return fd;
1595 static char **JimSaveEnv(char **env)
1597 char **saveenv = Jim_GetEnviron();
1598 Jim_SetEnviron(env);
1599 return saveenv;
1602 static void JimRestoreEnv(char **env)
1604 JimFreeEnv(Jim_GetEnviron(), env);
1605 Jim_SetEnviron(env);
1607 #endif
1608 #endif