Add a general purpose hashtable pattern matcher
[jimtcl.git] / jim-exec.c
blobfbc60ce8706757cbdc0a7b3dab166df79eb26d7b
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 "jim.h"
27 #include "jimautoconf.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;
84 Jim_CreateCommand(interp, "exec", Jim_ExecCmd, NULL, NULL);
85 return JIM_OK;
87 #else
88 /* Full exec implementation for unix and mingw */
90 #include <errno.h>
91 #include <signal.h>
93 #if defined(__MINGW32__)
94 /* XXX: Should we use this implementation for cygwin too? msvc? */
95 #ifndef STRICT
96 #define STRICT
97 #endif
98 #define WIN32_LEAN_AND_MEAN
99 #include <windows.h>
100 #include <fcntl.h>
102 typedef HANDLE fdtype;
103 typedef HANDLE pidtype;
104 #define JIM_BAD_FD INVALID_HANDLE_VALUE
105 #define JIM_BAD_PID INVALID_HANDLE_VALUE
106 #define JimCloseFd CloseHandle
108 #define WIFEXITED(STATUS) 1
109 #define WEXITSTATUS(STATUS) (STATUS)
110 #define WIFSIGNALED(STATUS) 0
111 #define WTERMSIG(STATUS) 0
112 #define WNOHANG 1
114 static fdtype JimFileno(FILE *fh);
115 static pidtype JimWaitPid(pidtype pid, int *status, int nohang);
116 static fdtype JimDupFd(fdtype infd);
117 static fdtype JimOpenForRead(const char *filename);
118 static FILE *JimFdOpenForRead(fdtype fd);
119 static int JimPipe(fdtype pipefd[2]);
120 static pidtype JimStartWinProcess(Jim_Interp *interp, char **argv, char *env,
121 fdtype inputId, fdtype outputId, fdtype errorId);
122 static int JimErrno(void);
123 #else
124 #include "jim-signal.h"
125 #include <unistd.h>
126 #include <fcntl.h>
127 #include <sys/wait.h>
129 typedef int fdtype;
130 typedef int pidtype;
131 #define JimPipe pipe
132 #define JimErrno() errno
133 #define JIM_BAD_FD -1
134 #define JIM_BAD_PID -1
135 #define JimFileno fileno
136 #define JimReadFd read
137 #define JimCloseFd close
138 #define JimWaitPid waitpid
139 #define JimDupFd dup
140 #define JimFdOpenForRead(FD) fdopen((FD), "r")
141 #define JimOpenForRead(NAME) open((NAME), O_RDONLY, 0)
142 #endif
144 static const char *JimStrError(void);
145 static char **JimSaveEnv(char **env);
146 static void JimRestoreEnv(char **env);
147 static int JimCreatePipeline(Jim_Interp *interp, int argc, Jim_Obj *const *argv,
148 pidtype **pidArrayPtr, fdtype *inPipePtr, fdtype *outPipePtr, fdtype *errFilePtr);
149 static void JimDetachPids(Jim_Interp *interp, int numPids, const pidtype *pidPtr);
150 static int JimCleanupChildren(Jim_Interp *interp, int numPids, pidtype *pidPtr, fdtype errorId);
151 static fdtype JimCreateTemp(Jim_Interp *interp, const char *contents);
152 static fdtype JimOpenForWrite(const char *filename, int append);
153 static int JimRewindFd(fdtype fd);
155 static void Jim_SetResultErrno(Jim_Interp *interp, const char *msg)
157 Jim_SetResultFormatted(interp, "%s: %s", msg, JimStrError());
160 static const char *JimStrError(void)
162 return strerror(JimErrno());
165 static void Jim_RemoveTrailingNewline(Jim_Obj *objPtr)
167 int len;
168 const char *s = Jim_GetString(objPtr, &len);
170 if (len > 0 && s[len - 1] == '\n') {
171 objPtr->length--;
172 objPtr->bytes[objPtr->length] = '\0';
177 * Read from 'fd', append the data to strObj and close 'fd'.
178 * Returns JIM_OK if OK, or JIM_ERR on error.
180 static int JimAppendStreamToString(Jim_Interp *interp, fdtype fd, Jim_Obj *strObj)
182 char buf[256];
183 FILE *fh = JimFdOpenForRead(fd);
184 if (fh == NULL) {
185 return JIM_ERR;
188 while (1) {
189 int retval = fread(buf, 1, sizeof(buf), fh);
190 if (retval > 0) {
191 Jim_AppendString(interp, strObj, buf, retval);
193 if (retval != sizeof(buf)) {
194 break;
197 Jim_RemoveTrailingNewline(strObj);
198 fclose(fh);
199 return JIM_OK;
203 * If the last character of the result is a newline, then remove
204 * the newline character (the newline would just confuse things).
206 * Note: Ideally we could do this by just reducing the length of stringrep
207 * by 1, but there is no API for this :-(
209 static void JimTrimTrailingNewline(Jim_Interp *interp)
211 int len;
212 const char *p = Jim_GetString(Jim_GetResult(interp), &len);
214 if (len > 0 && p[len - 1] == '\n') {
215 Jim_SetResultString(interp, p, len - 1);
220 * Builds the environment array from $::env
222 * If $::env is not set, simply returns environ.
224 * Otherwise allocates the environ array from the contents of $::env
226 * If the exec fails, memory can be freed via JimFreeEnv()
228 static char **JimBuildEnv(Jim_Interp *interp)
230 #if defined(jim_ext_tclcompat)
231 int i;
232 int size;
233 int num;
234 int n;
235 char **envptr;
236 char *envdata;
238 Jim_Obj *objPtr = Jim_GetGlobalVariableStr(interp, "env", JIM_NONE);
240 if (!objPtr) {
241 return Jim_GetEnviron();
244 /* We build the array as a single block consisting of the pointers followed by
245 * the strings. This has the advantage of being easy to allocate/free and being
246 * compatible with both unix and windows
249 /* Calculate the required size */
250 num = Jim_ListLength(interp, objPtr);
251 if (num % 2) {
252 num--;
254 size = Jim_Length(objPtr);
255 /* We need one \0 and one equal sign for each element.
256 * A list has at least one space for each element except the first.
257 * We only need one extra char for the extra null terminator.
259 size++;
261 envptr = Jim_Alloc(sizeof(*envptr) * (num / 2 + 1) + size);
262 envdata = (char *)&envptr[num / 2 + 1];
264 n = 0;
265 for (i = 0; i < num; i += 2) {
266 const char *s1, *s2;
267 Jim_Obj *elemObj;
269 Jim_ListIndex(interp, objPtr, i, &elemObj, JIM_NONE);
270 s1 = Jim_String(elemObj);
271 Jim_ListIndex(interp, objPtr, i + 1, &elemObj, JIM_NONE);
272 s2 = Jim_String(elemObj);
274 envptr[n] = envdata;
275 envdata += sprintf(envdata, "%s=%s", s1, s2);
276 envdata++;
277 n++;
279 envptr[n] = NULL;
280 *envdata = 0;
282 return envptr;
283 #else
284 return Jim_GetEnviron();
285 #endif
289 * Frees the environment allocated by JimBuildEnv()
291 * Must pass original_environ.
293 static void JimFreeEnv(char **env, char **original_environ)
295 #ifdef jim_ext_tclcompat
296 if (env != original_environ) {
297 Jim_Free(env);
299 #endif
303 * Create error messages for unusual process exits. An
304 * extra newline gets appended to each error message, but
305 * it gets removed below (in the same fashion that an
306 * extra newline in the command's output is removed).
308 static int JimCheckWaitStatus(Jim_Interp *interp, pidtype pid, int waitStatus)
310 Jim_Obj *errorCode = Jim_NewListObj(interp, NULL, 0);
311 int rc = JIM_ERR;
313 if (WIFEXITED(waitStatus)) {
314 if (WEXITSTATUS(waitStatus) == 0) {
315 Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, "NONE", -1));
316 rc = JIM_OK;
318 else {
319 Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, "CHILDSTATUS", -1));
320 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, (long)pid));
321 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, WEXITSTATUS(waitStatus)));
324 else {
325 const char *type;
326 const char *action;
328 if (WIFSIGNALED(waitStatus)) {
329 type = "CHILDKILLED";
330 action = "killed";
332 else {
333 type = "CHILDSUSP";
334 action = "suspended";
337 Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, type, -1));
339 #ifdef jim_ext_signal
340 Jim_SetResultFormatted(interp, "child %s by signal %s", action, Jim_SignalId(WTERMSIG(waitStatus)));
341 Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, Jim_SignalId(WTERMSIG(waitStatus)), -1));
342 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, pid));
343 Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, Jim_SignalName(WTERMSIG(waitStatus)), -1));
344 #else
345 Jim_SetResultFormatted(interp, "child %s by signal %d", action, WTERMSIG(waitStatus));
346 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, WTERMSIG(waitStatus)));
347 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, (long)pid));
348 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, WTERMSIG(waitStatus)));
349 #endif
351 Jim_SetGlobalVariableStr(interp, "errorCode", errorCode);
352 return rc;
356 * Data structures of the following type are used by JimFork and
357 * JimWaitPids to keep track of child processes.
360 struct WaitInfo
362 pidtype pid; /* Process id of child. */
363 int status; /* Status returned when child exited or suspended. */
364 int flags; /* Various flag bits; see below for definitions. */
367 struct WaitInfoTable {
368 struct WaitInfo *info;
369 int size;
370 int used;
374 * Flag bits in WaitInfo structures:
376 * WI_DETACHED - Non-zero means no-one cares about the
377 * process anymore. Ignore it until it
378 * exits, then forget about it.
381 #define WI_DETACHED 2
383 #define WAIT_TABLE_GROW_BY 4
385 static void JimFreeWaitInfoTable(struct Jim_Interp *interp, void *privData)
387 struct WaitInfoTable *table = privData;
389 Jim_Free(table->info);
390 Jim_Free(table);
393 static struct WaitInfoTable *JimAllocWaitInfoTable(void)
395 struct WaitInfoTable *table = Jim_Alloc(sizeof(*table));
396 table->info = NULL;
397 table->size = table->used = 0;
399 return table;
403 * The main [exec] command
405 static int Jim_ExecCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
407 fdtype outputId; /* File id for output pipe. -1
408 * means command overrode. */
409 fdtype errorId; /* File id for temporary file
410 * containing error output. */
411 pidtype *pidPtr;
412 int numPids, result;
415 * See if the command is to be run in background; if so, create
416 * the command, detach it, and return.
418 if (argc > 1 && Jim_CompareStringImmediate(interp, argv[argc - 1], "&")) {
419 Jim_Obj *listObj;
420 int i;
422 argc--;
423 numPids = JimCreatePipeline(interp, argc - 1, argv + 1, &pidPtr, NULL, NULL, NULL);
424 if (numPids < 0) {
425 return JIM_ERR;
427 /* The return value is a list of the pids */
428 listObj = Jim_NewListObj(interp, NULL, 0);
429 for (i = 0; i < numPids; i++) {
430 Jim_ListAppendElement(interp, listObj, Jim_NewIntObj(interp, (long)pidPtr[i]));
432 Jim_SetResult(interp, listObj);
433 JimDetachPids(interp, numPids, pidPtr);
434 Jim_Free(pidPtr);
435 return JIM_OK;
439 * Create the command's pipeline.
441 numPids =
442 JimCreatePipeline(interp, argc - 1, argv + 1, &pidPtr, NULL, &outputId, &errorId);
444 if (numPids < 0) {
445 return JIM_ERR;
449 * Read the child's output (if any) and put it into the result.
451 Jim_SetResultString(interp, "", 0);
453 result = JIM_OK;
454 if (outputId != JIM_BAD_FD) {
455 result = JimAppendStreamToString(interp, outputId, Jim_GetResult(interp));
456 if (result < 0) {
457 Jim_SetResultErrno(interp, "error reading from output pipe");
461 if (JimCleanupChildren(interp, numPids, pidPtr, errorId) != JIM_OK) {
462 result = JIM_ERR;
464 return result;
467 static void JimReapDetachedPids(struct WaitInfoTable *table)
469 struct WaitInfo *waitPtr;
470 int count;
472 if (!table) {
473 return;
476 for (waitPtr = table->info, count = table->used; count > 0; waitPtr++, count--) {
477 if (waitPtr->flags & WI_DETACHED) {
478 int status;
479 pidtype pid = JimWaitPid(waitPtr->pid, &status, WNOHANG);
480 if (pid != JIM_BAD_PID) {
481 if (waitPtr != &table->info[table->used - 1]) {
482 *waitPtr = table->info[table->used - 1];
484 table->used--;
491 * Does waitpid() on the given pid, and then removes the
492 * entry from the wait table.
494 * Returns the pid if OK and updates *statusPtr with the status,
495 * or JIM_BAD_PID if the pid was not in the table.
497 static pidtype JimWaitForProcess(struct WaitInfoTable *table, pidtype pid, int *statusPtr)
499 int i;
501 /* Find it in the table */
502 for (i = 0; i < table->used; i++) {
503 if (pid == table->info[i].pid) {
504 /* wait for it */
505 JimWaitPid(pid, statusPtr, 0);
507 /* Remove it from the table */
508 if (i != table->used - 1) {
509 table->info[i] = table->info[table->used - 1];
511 table->used--;
512 return pid;
516 /* Not found */
517 return JIM_BAD_PID;
521 *----------------------------------------------------------------------
523 * JimDetachPids --
525 * This procedure is called to indicate that one or more child
526 * processes have been placed in background and are no longer
527 * cared about. These children can be cleaned up with JimReapDetachedPids().
529 * Results:
530 * None.
532 * Side effects:
533 * None.
535 *----------------------------------------------------------------------
538 static void JimDetachPids(Jim_Interp *interp, int numPids, const pidtype *pidPtr)
540 int j;
541 struct WaitInfoTable *table = Jim_CmdPrivData(interp);
543 for (j = 0; j < numPids; j++) {
544 /* Find it in the table */
545 int i;
546 for (i = 0; i < table->used; i++) {
547 if (pidPtr[j] == table->info[i].pid) {
548 table->info[i].flags |= WI_DETACHED;
549 break;
556 *----------------------------------------------------------------------
558 * JimCreatePipeline --
560 * Given an argc/argv array, instantiate a pipeline of processes
561 * as described by the argv.
563 * Results:
564 * The return value is a count of the number of new processes
565 * created, or -1 if an error occurred while creating the pipeline.
566 * *pidArrayPtr is filled in with the address of a dynamically
567 * allocated array giving the ids of all of the processes. It
568 * is up to the caller to free this array when it isn't needed
569 * anymore. If inPipePtr is non-NULL, *inPipePtr is filled in
570 * with the file id for the input pipe for the pipeline (if any):
571 * the caller must eventually close this file. If outPipePtr
572 * isn't NULL, then *outPipePtr is filled in with the file id
573 * for the output pipe from the pipeline: the caller must close
574 * this file. If errFilePtr isn't NULL, then *errFilePtr is filled
575 * with a file id that may be used to read error output after the
576 * pipeline completes.
578 * Side effects:
579 * Processes and pipes are created.
581 *----------------------------------------------------------------------
583 static int
584 JimCreatePipeline(Jim_Interp *interp, int argc, Jim_Obj *const *argv, pidtype **pidArrayPtr,
585 fdtype *inPipePtr, fdtype *outPipePtr, fdtype *errFilePtr)
587 pidtype *pidPtr = NULL; /* Points to malloc-ed array holding all
588 * the pids of child processes. */
589 int numPids = 0; /* Actual number of processes that exist
590 * at *pidPtr right now. */
591 int cmdCount; /* Count of number of distinct commands
592 * found in argc/argv. */
593 const char *input = NULL; /* Describes input for pipeline, depending
594 * on "inputFile". NULL means take input
595 * from stdin/pipe. */
597 #define FILE_NAME 0 /* input/output: filename */
598 #define FILE_APPEND 1 /* output only: filename, append */
599 #define FILE_HANDLE 2 /* input/output: filehandle */
600 #define FILE_TEXT 3 /* input only: input is actual text */
602 int inputFile = FILE_NAME; /* 1 means input is name of input file.
603 * 2 means input is filehandle name.
604 * 0 means input holds actual
605 * text to be input to command. */
607 int outputFile = FILE_NAME; /* 0 means output is the name of output file.
608 * 1 means output is the name of output file, and append.
609 * 2 means output is filehandle name.
610 * All this is ignored if output is NULL
612 int errorFile = FILE_NAME; /* 0 means error is the name of error file.
613 * 1 means error is the name of error file, and append.
614 * 2 means error is filehandle name.
615 * All this is ignored if error is NULL
617 const char *output = NULL; /* Holds name of output file to pipe to,
618 * or NULL if output goes to stdout/pipe. */
619 const char *error = NULL; /* Holds name of stderr file to pipe to,
620 * or NULL if stderr goes to stderr/pipe. */
621 fdtype inputId = JIM_BAD_FD;
622 /* Readable file id input to current command in
623 * pipeline (could be file or pipe). JIM_BAD_FD
624 * means use stdin. */
625 fdtype outputId = JIM_BAD_FD;
626 /* Writable file id for output from current
627 * command in pipeline (could be file or pipe).
628 * JIM_BAD_FD means use stdout. */
629 fdtype errorId = JIM_BAD_FD;
630 /* Writable file id for all standard error
631 * output from all commands in pipeline. JIM_BAD_FD
632 * means use stderr. */
633 fdtype lastOutputId = JIM_BAD_FD;
634 /* Write file id for output from last command
635 * in pipeline (could be file or pipe).
636 * -1 means use stdout. */
637 fdtype pipeIds[2]; /* File ids for pipe that's being created. */
638 int firstArg, lastArg; /* Indexes of first and last arguments in
639 * current command. */
640 int lastBar;
641 int i;
642 pidtype pid;
643 char **save_environ;
644 struct WaitInfoTable *table = Jim_CmdPrivData(interp);
646 /* Holds the args which will be used to exec */
647 char **arg_array = Jim_Alloc(sizeof(*arg_array) * (argc + 1));
648 int arg_count = 0;
650 JimReapDetachedPids(table);
652 if (inPipePtr != NULL) {
653 *inPipePtr = JIM_BAD_FD;
655 if (outPipePtr != NULL) {
656 *outPipePtr = JIM_BAD_FD;
658 if (errFilePtr != NULL) {
659 *errFilePtr = JIM_BAD_FD;
661 pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
664 * First, scan through all the arguments to figure out the structure
665 * of the pipeline. Count the number of distinct processes (it's the
666 * number of "|" arguments). If there are "<", "<<", or ">" arguments
667 * then make note of input and output redirection and remove these
668 * arguments and the arguments that follow them.
670 cmdCount = 1;
671 lastBar = -1;
672 for (i = 0; i < argc; i++) {
673 const char *arg = Jim_String(argv[i]);
675 if (arg[0] == '<') {
676 inputFile = FILE_NAME;
677 input = arg + 1;
678 if (*input == '<') {
679 inputFile = FILE_TEXT;
680 input++;
682 else if (*input == '@') {
683 inputFile = FILE_HANDLE;
684 input++;
687 if (!*input && ++i < argc) {
688 input = Jim_String(argv[i]);
691 else if (arg[0] == '>') {
692 int dup_error = 0;
694 outputFile = FILE_NAME;
696 output = arg + 1;
697 if (*output == '>') {
698 outputFile = FILE_APPEND;
699 output++;
701 if (*output == '&') {
702 /* Redirect stderr too */
703 output++;
704 dup_error = 1;
706 if (*output == '@') {
707 outputFile = FILE_HANDLE;
708 output++;
710 if (!*output && ++i < argc) {
711 output = Jim_String(argv[i]);
713 if (dup_error) {
714 errorFile = outputFile;
715 error = output;
718 else if (arg[0] == '2' && arg[1] == '>') {
719 error = arg + 2;
720 errorFile = FILE_NAME;
722 if (*error == '@') {
723 errorFile = FILE_HANDLE;
724 error++;
726 else if (*error == '>') {
727 errorFile = FILE_APPEND;
728 error++;
730 if (!*error && ++i < argc) {
731 error = Jim_String(argv[i]);
734 else {
735 if (strcmp(arg, "|") == 0 || strcmp(arg, "|&") == 0) {
736 if (i == lastBar + 1 || i == argc - 1) {
737 Jim_SetResultString(interp, "illegal use of | or |& in command", -1);
738 goto badargs;
740 lastBar = i;
741 cmdCount++;
743 /* Either |, |& or a "normal" arg, so store it in the arg array */
744 arg_array[arg_count++] = (char *)arg;
745 continue;
748 if (i >= argc) {
749 Jim_SetResultFormatted(interp, "can't specify \"%s\" as last word in command", arg);
750 goto badargs;
754 if (arg_count == 0) {
755 Jim_SetResultString(interp, "didn't specify command to execute", -1);
756 badargs:
757 Jim_Free(arg_array);
758 return -1;
761 /* Must do this before vfork(), so do it now */
762 save_environ = JimSaveEnv(JimBuildEnv(interp));
765 * Set up the redirected input source for the pipeline, if
766 * so requested.
768 if (input != NULL) {
769 if (inputFile == FILE_TEXT) {
771 * Immediate data in command. Create temporary file and
772 * put data into file.
774 inputId = JimCreateTemp(interp, input);
775 if (inputId == JIM_BAD_FD) {
776 goto error;
779 else if (inputFile == FILE_HANDLE) {
780 /* Should be a file descriptor */
781 Jim_Obj *fhObj = Jim_NewStringObj(interp, input, -1);
782 FILE *fh = Jim_AioFilehandle(interp, fhObj);
784 Jim_FreeNewObj(interp, fhObj);
785 if (fh == NULL) {
786 goto error;
788 inputId = JimDupFd(JimFileno(fh));
790 else {
792 * File redirection. Just open the file.
794 inputId = JimOpenForRead(input);
795 if (inputId == JIM_BAD_FD) {
796 Jim_SetResultFormatted(interp, "couldn't read file \"%s\": %s", input, JimStrError());
797 goto error;
801 else if (inPipePtr != NULL) {
802 if (JimPipe(pipeIds) != 0) {
803 Jim_SetResultErrno(interp, "couldn't create input pipe for command");
804 goto error;
806 inputId = pipeIds[0];
807 *inPipePtr = pipeIds[1];
808 pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
812 * Set up the redirected output sink for the pipeline from one
813 * of two places, if requested.
815 if (output != NULL) {
816 if (outputFile == FILE_HANDLE) {
817 Jim_Obj *fhObj = Jim_NewStringObj(interp, output, -1);
818 FILE *fh = Jim_AioFilehandle(interp, fhObj);
820 Jim_FreeNewObj(interp, fhObj);
821 if (fh == NULL) {
822 goto error;
824 fflush(fh);
825 lastOutputId = JimDupFd(JimFileno(fh));
827 else {
829 * Output is to go to a file.
831 lastOutputId = JimOpenForWrite(output, outputFile == FILE_APPEND);
832 if (lastOutputId == JIM_BAD_FD) {
833 Jim_SetResultFormatted(interp, "couldn't write file \"%s\": %s", output, JimStrError());
834 goto error;
838 else if (outPipePtr != NULL) {
840 * Output is to go to a pipe.
842 if (JimPipe(pipeIds) != 0) {
843 Jim_SetResultErrno(interp, "couldn't create output pipe");
844 goto error;
846 lastOutputId = pipeIds[1];
847 *outPipePtr = pipeIds[0];
848 pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
850 /* If we are redirecting stderr with 2>filename or 2>@fileId, then we ignore errFilePtr */
851 if (error != NULL) {
852 if (errorFile == FILE_HANDLE) {
853 if (strcmp(error, "1") == 0) {
854 /* Special 2>@1 */
855 if (lastOutputId != JIM_BAD_FD) {
856 errorId = JimDupFd(lastOutputId);
858 else {
859 /* No redirection of stdout, so just use 2>@stdout */
860 error = "stdout";
863 if (errorId == JIM_BAD_FD) {
864 Jim_Obj *fhObj = Jim_NewStringObj(interp, error, -1);
865 FILE *fh = Jim_AioFilehandle(interp, fhObj);
867 Jim_FreeNewObj(interp, fhObj);
868 if (fh == NULL) {
869 goto error;
871 fflush(fh);
872 errorId = JimDupFd(JimFileno(fh));
875 else {
877 * Output is to go to a file.
879 errorId = JimOpenForWrite(error, errorFile == FILE_APPEND);
880 if (errorId == JIM_BAD_FD) {
881 Jim_SetResultFormatted(interp, "couldn't write file \"%s\": %s", error, JimStrError());
882 goto error;
886 else if (errFilePtr != NULL) {
888 * Set up the standard error output sink for the pipeline, if
889 * requested. Use a temporary file which is opened, then deleted.
890 * Could potentially just use pipe, but if it filled up it could
891 * cause the pipeline to deadlock: we'd be waiting for processes
892 * to complete before reading stderr, and processes couldn't complete
893 * because stderr was backed up.
895 errorId = JimCreateTemp(interp, NULL);
896 if (errorId == JIM_BAD_FD) {
897 goto error;
899 *errFilePtr = JimDupFd(errorId);
903 * Scan through the argc array, forking off a process for each
904 * group of arguments between "|" arguments.
907 pidPtr = Jim_Alloc(cmdCount * sizeof(*pidPtr));
908 for (i = 0; i < numPids; i++) {
909 pidPtr[i] = JIM_BAD_PID;
911 for (firstArg = 0; firstArg < arg_count; numPids++, firstArg = lastArg + 1) {
912 int pipe_dup_err = 0;
913 fdtype origErrorId = errorId;
915 for (lastArg = firstArg; lastArg < arg_count; lastArg++) {
916 if (arg_array[lastArg][0] == '|') {
917 if (arg_array[lastArg][1] == '&') {
918 pipe_dup_err = 1;
920 break;
923 /* Replace | with NULL for execv() */
924 arg_array[lastArg] = NULL;
925 if (lastArg == arg_count) {
926 outputId = lastOutputId;
928 else {
929 if (JimPipe(pipeIds) != 0) {
930 Jim_SetResultErrno(interp, "couldn't create pipe");
931 goto error;
933 outputId = pipeIds[1];
936 /* Now fork the child */
938 #ifdef __MINGW32__
939 pid = JimStartWinProcess(interp, &arg_array[firstArg], save_environ ? save_environ[0] : NULL, inputId, outputId, errorId);
940 if (pid == JIM_BAD_PID) {
941 Jim_SetResultFormatted(interp, "couldn't exec \"%s\"", arg_array[firstArg]);
942 goto error;
944 #else
946 * Disable SIGPIPE signals: if they were allowed, this process
947 * might go away unexpectedly if children misbehave. This code
948 * can potentially interfere with other application code that
949 * expects to handle SIGPIPEs; what's really needed is an
950 * arbiter for signals to allow them to be "shared".
952 if (table->info == NULL) {
953 (void)signal(SIGPIPE, SIG_IGN);
956 /* Need to do this befor vfork() */
957 if (pipe_dup_err) {
958 errorId = outputId;
962 * Make a new process and enter it into the table if the fork
963 * is successful.
965 pid = vfork();
966 if (pid < 0) {
967 Jim_SetResultErrno(interp, "couldn't fork child process");
968 goto error;
970 if (pid == 0) {
971 /* Child */
973 if (inputId != -1) dup2(inputId, 0);
974 if (outputId != -1) dup2(outputId, 1);
975 if (errorId != -1) dup2(errorId, 2);
977 for (i = 3; (i <= outputId) || (i <= inputId) || (i <= errorId); i++) {
978 close(i);
981 execvp(arg_array[firstArg], &arg_array[firstArg]);
983 /* Need to prep an error message before vfork(), just in case */
984 fprintf(stderr, "couldn't exec \"%s\"", arg_array[firstArg]);
985 _exit(127);
987 #endif
989 /* parent */
992 * Enlarge the wait table if there isn't enough space for a new
993 * entry.
995 if (table->used == table->size) {
996 table->size += WAIT_TABLE_GROW_BY;
997 table->info = Jim_Realloc(table->info, table->size * sizeof(*table->info));
1000 table->info[table->used].pid = pid;
1001 table->info[table->used].flags = 0;
1002 table->used++;
1004 pidPtr[numPids] = pid;
1006 /* Restore in case of pipe_dup_err */
1007 errorId = origErrorId;
1010 * Close off our copies of file descriptors that were set up for
1011 * this child, then set up the input for the next child.
1014 if (inputId != JIM_BAD_FD) {
1015 JimCloseFd(inputId);
1017 if (outputId != JIM_BAD_FD) {
1018 JimCloseFd(outputId);
1020 inputId = pipeIds[0];
1021 pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
1023 *pidArrayPtr = pidPtr;
1026 * All done. Cleanup open files lying around and then return.
1029 cleanup:
1030 if (inputId != JIM_BAD_FD) {
1031 JimCloseFd(inputId);
1033 if (lastOutputId != JIM_BAD_FD) {
1034 JimCloseFd(lastOutputId);
1036 if (errorId != JIM_BAD_FD) {
1037 JimCloseFd(errorId);
1039 Jim_Free(arg_array);
1041 JimRestoreEnv(save_environ);
1043 return numPids;
1046 * An error occurred. There could have been extra files open, such
1047 * as pipes between children. Clean them all up. Detach any child
1048 * processes that have been created.
1051 error:
1052 if ((inPipePtr != NULL) && (*inPipePtr != JIM_BAD_FD)) {
1053 JimCloseFd(*inPipePtr);
1054 *inPipePtr = JIM_BAD_FD;
1056 if ((outPipePtr != NULL) && (*outPipePtr != JIM_BAD_FD)) {
1057 JimCloseFd(*outPipePtr);
1058 *outPipePtr = JIM_BAD_FD;
1060 if ((errFilePtr != NULL) && (*errFilePtr != JIM_BAD_FD)) {
1061 JimCloseFd(*errFilePtr);
1062 *errFilePtr = JIM_BAD_FD;
1064 if (pipeIds[0] != JIM_BAD_FD) {
1065 JimCloseFd(pipeIds[0]);
1067 if (pipeIds[1] != JIM_BAD_FD) {
1068 JimCloseFd(pipeIds[1]);
1070 if (pidPtr != NULL) {
1071 for (i = 0; i < numPids; i++) {
1072 if (pidPtr[i] != JIM_BAD_PID) {
1073 JimDetachPids(interp, 1, &pidPtr[i]);
1076 Jim_Free(pidPtr);
1078 numPids = -1;
1079 goto cleanup;
1083 *----------------------------------------------------------------------
1085 * JimCleanupChildren --
1087 * This is a utility procedure used to wait for child processes
1088 * to exit, record information about abnormal exits, and then
1089 * collect any stderr output generated by them.
1091 * Results:
1092 * The return value is a standard Tcl result. If anything at
1093 * weird happened with the child processes, JIM_ERROR is returned
1094 * and a message is left in interp->result.
1096 * Side effects:
1097 * If the last character of interp->result is a newline, then it
1098 * is removed. File errorId gets closed, and pidPtr is freed
1099 * back to the storage allocator.
1101 *----------------------------------------------------------------------
1104 static int JimCleanupChildren(Jim_Interp *interp, int numPids, pidtype *pidPtr, fdtype errorId)
1106 struct WaitInfoTable *table = Jim_CmdPrivData(interp);
1107 int result = JIM_OK;
1108 int i;
1110 for (i = 0; i < numPids; i++) {
1111 int waitStatus = 0;
1112 if (JimWaitForProcess(table, pidPtr[i], &waitStatus) != JIM_BAD_PID) {
1113 if (JimCheckWaitStatus(interp, pidPtr[i], waitStatus) != JIM_OK) {
1114 result = JIM_ERR;
1118 Jim_Free(pidPtr);
1121 * Read the standard error file. If there's anything there,
1122 * then add the file's contents to the result
1123 * string.
1125 if (errorId != JIM_BAD_FD) {
1126 JimRewindFd(errorId);
1127 if (JimAppendStreamToString(interp, errorId, Jim_GetResult(interp)) != JIM_OK) {
1128 result = JIM_ERR;
1132 JimTrimTrailingNewline(interp);
1134 return result;
1137 int Jim_execInit(Jim_Interp *interp)
1139 if (Jim_PackageProvide(interp, "exec", "1.0", JIM_ERRMSG))
1140 return JIM_ERR;
1141 Jim_CreateCommand(interp, "exec", Jim_ExecCmd, JimAllocWaitInfoTable(), JimFreeWaitInfoTable);
1142 return JIM_OK;
1145 #if defined(__MINGW32__)
1146 /* Windows-specific (mingw) implementation */
1148 static SECURITY_ATTRIBUTES *JimStdSecAttrs(void)
1150 static SECURITY_ATTRIBUTES secAtts;
1152 secAtts.nLength = sizeof(SECURITY_ATTRIBUTES);
1153 secAtts.lpSecurityDescriptor = NULL;
1154 secAtts.bInheritHandle = TRUE;
1155 return &secAtts;
1158 static int JimErrno(void)
1160 switch (GetLastError()) {
1161 case ERROR_FILE_NOT_FOUND: return ENOENT;
1162 case ERROR_PATH_NOT_FOUND: return ENOENT;
1163 case ERROR_TOO_MANY_OPEN_FILES: return EMFILE;
1164 case ERROR_ACCESS_DENIED: return EACCES;
1165 case ERROR_INVALID_HANDLE: return EBADF;
1166 case ERROR_BAD_ENVIRONMENT: return E2BIG;
1167 case ERROR_BAD_FORMAT: return ENOEXEC;
1168 case ERROR_INVALID_ACCESS: return EACCES;
1169 case ERROR_INVALID_DRIVE: return ENOENT;
1170 case ERROR_CURRENT_DIRECTORY: return EACCES;
1171 case ERROR_NOT_SAME_DEVICE: return EXDEV;
1172 case ERROR_NO_MORE_FILES: return ENOENT;
1173 case ERROR_WRITE_PROTECT: return EROFS;
1174 case ERROR_BAD_UNIT: return ENXIO;
1175 case ERROR_NOT_READY: return EBUSY;
1176 case ERROR_BAD_COMMAND: return EIO;
1177 case ERROR_CRC: return EIO;
1178 case ERROR_BAD_LENGTH: return EIO;
1179 case ERROR_SEEK: return EIO;
1180 case ERROR_WRITE_FAULT: return EIO;
1181 case ERROR_READ_FAULT: return EIO;
1182 case ERROR_GEN_FAILURE: return EIO;
1183 case ERROR_SHARING_VIOLATION: return EACCES;
1184 case ERROR_LOCK_VIOLATION: return EACCES;
1185 case ERROR_SHARING_BUFFER_EXCEEDED: return ENFILE;
1186 case ERROR_HANDLE_DISK_FULL: return ENOSPC;
1187 case ERROR_NOT_SUPPORTED: return ENODEV;
1188 case ERROR_REM_NOT_LIST: return EBUSY;
1189 case ERROR_DUP_NAME: return EEXIST;
1190 case ERROR_BAD_NETPATH: return ENOENT;
1191 case ERROR_NETWORK_BUSY: return EBUSY;
1192 case ERROR_DEV_NOT_EXIST: return ENODEV;
1193 case ERROR_TOO_MANY_CMDS: return EAGAIN;
1194 case ERROR_ADAP_HDW_ERR: return EIO;
1195 case ERROR_BAD_NET_RESP: return EIO;
1196 case ERROR_UNEXP_NET_ERR: return EIO;
1197 case ERROR_NETNAME_DELETED: return ENOENT;
1198 case ERROR_NETWORK_ACCESS_DENIED: return EACCES;
1199 case ERROR_BAD_DEV_TYPE: return ENODEV;
1200 case ERROR_BAD_NET_NAME: return ENOENT;
1201 case ERROR_TOO_MANY_NAMES: return ENFILE;
1202 case ERROR_TOO_MANY_SESS: return EIO;
1203 case ERROR_SHARING_PAUSED: return EAGAIN;
1204 case ERROR_REDIR_PAUSED: return EAGAIN;
1205 case ERROR_FILE_EXISTS: return EEXIST;
1206 case ERROR_CANNOT_MAKE: return ENOSPC;
1207 case ERROR_OUT_OF_STRUCTURES: return ENFILE;
1208 case ERROR_ALREADY_ASSIGNED: return EEXIST;
1209 case ERROR_INVALID_PASSWORD: return EPERM;
1210 case ERROR_NET_WRITE_FAULT: return EIO;
1211 case ERROR_NO_PROC_SLOTS: return EAGAIN;
1212 case ERROR_DISK_CHANGE: return EXDEV;
1213 case ERROR_BROKEN_PIPE: return EPIPE;
1214 case ERROR_OPEN_FAILED: return ENOENT;
1215 case ERROR_DISK_FULL: return ENOSPC;
1216 case ERROR_NO_MORE_SEARCH_HANDLES: return EMFILE;
1217 case ERROR_INVALID_TARGET_HANDLE: return EBADF;
1218 case ERROR_INVALID_NAME: return ENOENT;
1219 case ERROR_PROC_NOT_FOUND: return ESRCH;
1220 case ERROR_WAIT_NO_CHILDREN: return ECHILD;
1221 case ERROR_CHILD_NOT_COMPLETE: return ECHILD;
1222 case ERROR_DIRECT_ACCESS_HANDLE: return EBADF;
1223 case ERROR_SEEK_ON_DEVICE: return ESPIPE;
1224 case ERROR_BUSY_DRIVE: return EAGAIN;
1225 case ERROR_DIR_NOT_EMPTY: return EEXIST;
1226 case ERROR_NOT_LOCKED: return EACCES;
1227 case ERROR_BAD_PATHNAME: return ENOENT;
1228 case ERROR_LOCK_FAILED: return EACCES;
1229 case ERROR_ALREADY_EXISTS: return EEXIST;
1230 case ERROR_FILENAME_EXCED_RANGE: return ENAMETOOLONG;
1231 case ERROR_BAD_PIPE: return EPIPE;
1232 case ERROR_PIPE_BUSY: return EAGAIN;
1233 case ERROR_PIPE_NOT_CONNECTED: return EPIPE;
1234 case ERROR_DIRECTORY: return ENOTDIR;
1236 return EINVAL;
1239 static int JimPipe(fdtype pipefd[2])
1241 if (CreatePipe(&pipefd[0], &pipefd[1], NULL, 0)) {
1242 return 0;
1244 return -1;
1247 static fdtype JimDupFd(fdtype infd)
1249 fdtype dupfd;
1250 pidtype pid = GetCurrentProcess();
1252 if (DuplicateHandle(pid, infd, pid, &dupfd, 0, TRUE, DUPLICATE_SAME_ACCESS)) {
1253 return dupfd;
1255 return JIM_BAD_FD;
1258 static int JimRewindFd(fdtype fd)
1260 return SetFilePointer(fd, 0, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER ? -1 : 0;
1263 #if 0
1264 static int JimReadFd(fdtype fd, char *buffer, size_t len)
1266 DWORD num;
1268 if (ReadFile(fd, buffer, len, &num, NULL)) {
1269 return num;
1271 if (GetLastError() == ERROR_HANDLE_EOF || GetLastError() == ERROR_BROKEN_PIPE) {
1272 return 0;
1274 return -1;
1276 #endif
1278 static FILE *JimFdOpenForRead(fdtype fd)
1280 return _fdopen(_open_osfhandle((int)fd, _O_RDONLY | _O_TEXT), "r");
1283 static fdtype JimFileno(FILE *fh)
1285 return (fdtype)_get_osfhandle(_fileno(fh));
1288 static fdtype JimOpenForRead(const char *filename)
1290 return CreateFile(filename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
1291 JimStdSecAttrs(), OPEN_EXISTING, 0, NULL);
1294 static fdtype JimOpenForWrite(const char *filename, int append)
1296 return CreateFile(filename, append ? FILE_APPEND_DATA : GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
1297 JimStdSecAttrs(), append ? OPEN_ALWAYS : CREATE_ALWAYS, 0, (HANDLE) NULL);
1300 static FILE *JimFdOpenForWrite(fdtype fd)
1302 return _fdopen(_open_osfhandle((int)fd, _O_TEXT), "w");
1305 static pidtype JimWaitPid(pidtype pid, int *status, int nohang)
1307 DWORD ret = WaitForSingleObject(pid, nohang ? 0 : INFINITE);
1308 if (ret == WAIT_TIMEOUT || ret == WAIT_FAILED) {
1309 /* WAIT_TIMEOUT can only happend with WNOHANG */
1310 return JIM_BAD_PID;
1312 GetExitCodeProcess(pid, &ret);
1313 *status = ret;
1314 CloseHandle(pid);
1315 return pid;
1318 static HANDLE JimCreateTemp(Jim_Interp *interp, const char *contents)
1320 char name[MAX_PATH];
1321 HANDLE handle;
1323 if (!GetTempPath(MAX_PATH, name) || !GetTempFileName(name, "JIM", 0, name)) {
1324 return JIM_BAD_FD;
1327 handle = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, JimStdSecAttrs(),
1328 CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE,
1329 NULL);
1331 if (handle == INVALID_HANDLE_VALUE) {
1332 goto error;
1335 if (contents != NULL) {
1336 /* Use fdopen() to get automatic text-mode translation */
1337 FILE *fh = JimFdOpenForWrite(JimDupFd(handle));
1338 if (fh == NULL) {
1339 goto error;
1342 if (fwrite(contents, strlen(contents), 1, fh) != 1) {
1343 fclose(fh);
1344 goto error;
1346 fseek(fh, 0, SEEK_SET);
1347 fclose(fh);
1349 return handle;
1351 error:
1352 Jim_SetResultErrno(interp, "failed to create temp file");
1353 CloseHandle(handle);
1354 DeleteFile(name);
1355 return JIM_BAD_FD;
1358 static int
1359 JimWinFindExecutable(const char *originalName, char fullPath[MAX_PATH])
1361 int i;
1362 static char extensions[][5] = {".exe", "", ".bat"};
1364 for (i = 0; i < (int) (sizeof(extensions) / sizeof(extensions[0])); i++) {
1365 lstrcpyn(fullPath, originalName, MAX_PATH - 5);
1366 lstrcat(fullPath, extensions[i]);
1368 if (SearchPath(NULL, fullPath, NULL, MAX_PATH, fullPath, NULL) == 0) {
1369 continue;
1371 if (GetFileAttributes(fullPath) & FILE_ATTRIBUTE_DIRECTORY) {
1372 continue;
1374 return 0;
1377 return -1;
1380 static char **JimSaveEnv(char **env)
1382 return env;
1385 static void JimRestoreEnv(char **env)
1387 JimFreeEnv(env, NULL);
1390 static Jim_Obj *
1391 JimWinBuildCommandLine(Jim_Interp *interp, char **argv)
1393 char *start, *special;
1394 int quote, i;
1396 Jim_Obj *strObj = Jim_NewStringObj(interp, "", 0);
1398 for (i = 0; argv[i]; i++) {
1399 if (i > 0) {
1400 Jim_AppendString(interp, strObj, " ", 1);
1403 if (argv[i][0] == '\0') {
1404 quote = 1;
1406 else {
1407 quote = 0;
1408 for (start = argv[i]; *start != '\0'; start++) {
1409 if (isspace(UCHAR(*start))) {
1410 quote = 1;
1411 break;
1415 if (quote) {
1416 Jim_AppendString(interp, strObj, "\"" , 1);
1419 start = argv[i];
1420 for (special = argv[i]; ; ) {
1421 if ((*special == '\\') && (special[1] == '\\' ||
1422 special[1] == '"' || (quote && special[1] == '\0'))) {
1423 Jim_AppendString(interp, strObj, start, special - start);
1424 start = special;
1425 while (1) {
1426 special++;
1427 if (*special == '"' || (quote && *special == '\0')) {
1429 * N backslashes followed a quote -> insert
1430 * N * 2 + 1 backslashes then a quote.
1433 Jim_AppendString(interp, strObj, start, special - start);
1434 break;
1436 if (*special != '\\') {
1437 break;
1440 Jim_AppendString(interp, strObj, start, special - start);
1441 start = special;
1443 if (*special == '"') {
1444 if (special == start) {
1445 Jim_AppendString(interp, strObj, "\"", 1);
1447 else {
1448 Jim_AppendString(interp, strObj, start, special - start);
1450 Jim_AppendString(interp, strObj, "\\\"", 2);
1451 start = special + 1;
1453 if (*special == '\0') {
1454 break;
1456 special++;
1458 Jim_AppendString(interp, strObj, start, special - start);
1459 if (quote) {
1460 Jim_AppendString(interp, strObj, "\"", 1);
1463 return strObj;
1466 static pidtype
1467 JimStartWinProcess(Jim_Interp *interp, char **argv, char *env, fdtype inputId, fdtype outputId, fdtype errorId)
1469 STARTUPINFO startInfo;
1470 PROCESS_INFORMATION procInfo;
1471 HANDLE hProcess, h;
1472 char execPath[MAX_PATH];
1473 char *originalName;
1474 pidtype pid = JIM_BAD_PID;
1475 Jim_Obj *cmdLineObj;
1477 if (JimWinFindExecutable(argv[0], execPath) < 0) {
1478 return JIM_BAD_PID;
1480 originalName = argv[0];
1481 argv[0] = execPath;
1483 hProcess = GetCurrentProcess();
1484 cmdLineObj = JimWinBuildCommandLine(interp, argv);
1487 * STARTF_USESTDHANDLES must be used to pass handles to child process.
1488 * Using SetStdHandle() and/or dup2() only works when a console mode
1489 * parent process is spawning an attached console mode child process.
1492 ZeroMemory(&startInfo, sizeof(startInfo));
1493 startInfo.cb = sizeof(startInfo);
1494 startInfo.dwFlags = STARTF_USESTDHANDLES;
1495 startInfo.hStdInput = INVALID_HANDLE_VALUE;
1496 startInfo.hStdOutput= INVALID_HANDLE_VALUE;
1497 startInfo.hStdError = INVALID_HANDLE_VALUE;
1500 * Duplicate all the handles which will be passed off as stdin, stdout
1501 * and stderr of the child process. The duplicate handles are set to
1502 * be inheritable, so the child process can use them.
1504 if (inputId == JIM_BAD_FD) {
1505 if (CreatePipe(&startInfo.hStdInput, &h, JimStdSecAttrs(), 0) != FALSE) {
1506 CloseHandle(h);
1508 } else {
1509 DuplicateHandle(hProcess, inputId, hProcess, &startInfo.hStdInput,
1510 0, TRUE, DUPLICATE_SAME_ACCESS);
1512 if (startInfo.hStdInput == JIM_BAD_FD) {
1513 goto end;
1516 if (outputId == JIM_BAD_FD) {
1517 startInfo.hStdOutput = CreateFile("NUL:", GENERIC_WRITE, 0,
1518 JimStdSecAttrs(), OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1519 } else {
1520 DuplicateHandle(hProcess, outputId, hProcess, &startInfo.hStdOutput,
1521 0, TRUE, DUPLICATE_SAME_ACCESS);
1523 if (startInfo.hStdOutput == JIM_BAD_FD) {
1524 goto end;
1527 if (errorId == JIM_BAD_FD) {
1529 * If handle was not set, errors should be sent to an infinitely
1530 * deep sink.
1533 startInfo.hStdError = CreateFile("NUL:", GENERIC_WRITE, 0,
1534 JimStdSecAttrs(), OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1535 } else {
1536 DuplicateHandle(hProcess, errorId, hProcess, &startInfo.hStdError,
1537 0, TRUE, DUPLICATE_SAME_ACCESS);
1539 if (startInfo.hStdError == JIM_BAD_FD) {
1540 goto end;
1543 if (!CreateProcess(NULL, (char *)Jim_String(cmdLineObj), NULL, NULL, TRUE,
1544 0, env, NULL, &startInfo, &procInfo)) {
1545 goto end;
1549 * "When an application spawns a process repeatedly, a new thread
1550 * instance will be created for each process but the previous
1551 * instances may not be cleaned up. This results in a significant
1552 * virtual memory loss each time the process is spawned. If there
1553 * is a WaitForInputIdle() call between CreateProcess() and
1554 * CloseHandle(), the problem does not occur." PSS ID Number: Q124121
1557 WaitForInputIdle(procInfo.hProcess, 5000);
1558 CloseHandle(procInfo.hThread);
1560 pid = procInfo.hProcess;
1562 end:
1563 Jim_FreeNewObj(interp, cmdLineObj);
1564 if (startInfo.hStdInput != JIM_BAD_FD) {
1565 CloseHandle(startInfo.hStdInput);
1567 if (startInfo.hStdOutput != JIM_BAD_FD) {
1568 CloseHandle(startInfo.hStdOutput);
1570 if (startInfo.hStdError != JIM_BAD_FD) {
1571 CloseHandle(startInfo.hStdError);
1573 return pid;
1575 #else
1576 /* Unix-specific implementation */
1577 static int JimOpenForWrite(const char *filename, int append)
1579 return open(filename, O_WRONLY | O_CREAT | (append ? O_APPEND : O_TRUNC), 0666);
1582 static int JimRewindFd(int fd)
1584 return lseek(fd, 0L, SEEK_SET);
1587 static int JimCreateTemp(Jim_Interp *interp, const char *contents)
1589 char inName[] = "/tmp/tcl.tmp.XXXXXX";
1591 int fd = mkstemp(inName);
1592 if (fd == JIM_BAD_FD) {
1593 Jim_SetResultErrno(interp, "couldn't create temp file");
1594 return -1;
1596 unlink(inName);
1597 if (contents) {
1598 int length = strlen(contents);
1599 if (write(fd, contents, length) != length) {
1600 Jim_SetResultErrno(interp, "couldn't write temp file");
1601 close(fd);
1602 return -1;
1604 lseek(fd, 0L, SEEK_SET);
1606 return fd;
1609 static char **JimSaveEnv(char **env)
1611 char **saveenv = Jim_GetEnviron();
1612 Jim_SetEnviron(env);
1613 return saveenv;
1616 static void JimRestoreEnv(char **env)
1618 JimFreeEnv(Jim_GetEnviron(), env);
1619 Jim_SetEnviron(env);
1621 #endif
1622 #endif