Fix bug that was causing the system "environ" variable to be freed, which caused...
[jimtcl.git] / jim-exec.c
blob14f6e20792ec465e514d68e392a6800d328af2fc
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;
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)
143 #ifndef HAVE_EXECVPE
144 #define execvpe(ARG0, ARGV, ENV) execvp(ARG0, ARGV)
145 #endif
146 #endif
148 static const char *JimStrError(void);
149 static char **JimSaveEnv(char **env);
150 static void JimRestoreEnv(char **env);
151 static int JimCreatePipeline(Jim_Interp *interp, int argc, Jim_Obj *const *argv,
152 pidtype **pidArrayPtr, fdtype *inPipePtr, fdtype *outPipePtr, fdtype *errFilePtr);
153 static void JimDetachPids(Jim_Interp *interp, int numPids, const pidtype *pidPtr);
154 static int JimCleanupChildren(Jim_Interp *interp, int numPids, pidtype *pidPtr, fdtype errorId);
155 static fdtype JimCreateTemp(Jim_Interp *interp, const char *contents);
156 static fdtype JimOpenForWrite(const char *filename, int append);
157 static int JimRewindFd(fdtype fd);
159 static void Jim_SetResultErrno(Jim_Interp *interp, const char *msg)
161 Jim_SetResultFormatted(interp, "%s: %s", msg, JimStrError());
164 static const char *JimStrError(void)
166 return strerror(JimErrno());
169 static void Jim_RemoveTrailingNewline(Jim_Obj *objPtr)
171 int len;
172 const char *s = Jim_GetString(objPtr, &len);
174 if (len > 0 && s[len - 1] == '\n') {
175 objPtr->length--;
176 objPtr->bytes[objPtr->length] = '\0';
181 * Read from 'fd', append the data to strObj and close 'fd'.
182 * Returns JIM_OK if OK, or JIM_ERR on error.
184 static int JimAppendStreamToString(Jim_Interp *interp, fdtype fd, Jim_Obj *strObj)
186 char buf[256];
187 FILE *fh = JimFdOpenForRead(fd);
188 if (fh == NULL) {
189 return JIM_ERR;
192 while (1) {
193 int retval = fread(buf, 1, sizeof(buf), fh);
194 if (retval > 0) {
195 Jim_AppendString(interp, strObj, buf, retval);
197 if (retval != sizeof(buf)) {
198 break;
201 Jim_RemoveTrailingNewline(strObj);
202 fclose(fh);
203 return JIM_OK;
207 * If the last character of the result is a newline, then remove
208 * the newline character (the newline would just confuse things).
210 * Note: Ideally we could do this by just reducing the length of stringrep
211 * by 1, but there is no API for this :-(
213 static void JimTrimTrailingNewline(Jim_Interp *interp)
215 int len;
216 const char *p = Jim_GetString(Jim_GetResult(interp), &len);
218 if (len > 0 && p[len - 1] == '\n') {
219 Jim_SetResultString(interp, p, len - 1);
224 * Builds the environment array from $::env
226 * If $::env is not set, simply returns environ.
228 * Otherwise allocates the environ array from the contents of $::env
230 * If the exec fails, memory can be freed via JimFreeEnv()
232 static char **JimBuildEnv(Jim_Interp *interp)
234 #if defined(jim_ext_tclcompat)
235 int i;
236 int size;
237 int num;
238 int n;
239 char **envptr;
240 char *envdata;
242 Jim_Obj *objPtr = Jim_GetGlobalVariableStr(interp, "env", JIM_NONE);
244 if (!objPtr) {
245 return Jim_GetEnviron();
248 /* We build the array as a single block consisting of the pointers followed by
249 * the strings. This has the advantage of being easy to allocate/free and being
250 * compatible with both unix and windows
253 /* Calculate the required size */
254 num = Jim_ListLength(interp, objPtr);
255 if (num % 2) {
256 num--;
258 /* We need one \0 and one equal sign for each element.
259 * A list has at least one space for each element except the first.
260 * We need one extra char for the extra null terminator and one for the equal sign.
262 size = Jim_Length(objPtr) + 2;
264 envptr = Jim_Alloc(sizeof(*envptr) * (num / 2 + 1) + size);
265 envdata = (char *)&envptr[num / 2 + 1];
267 n = 0;
268 for (i = 0; i < num; i += 2) {
269 const char *s1, *s2;
270 Jim_Obj *elemObj;
272 Jim_ListIndex(interp, objPtr, i, &elemObj, JIM_NONE);
273 s1 = Jim_String(elemObj);
274 Jim_ListIndex(interp, objPtr, i + 1, &elemObj, JIM_NONE);
275 s2 = Jim_String(elemObj);
277 envptr[n] = envdata;
278 envdata += sprintf(envdata, "%s=%s", s1, s2);
279 envdata++;
280 n++;
282 envptr[n] = NULL;
283 *envdata = 0;
285 return envptr;
286 #else
287 return Jim_GetEnviron();
288 #endif
292 * Frees the environment allocated by JimBuildEnv()
294 * Must pass original_environ.
296 static void JimFreeEnv(char **env, char **original_environ)
298 #ifdef jim_ext_tclcompat
299 if (env != original_environ) {
300 Jim_Free(env);
302 #endif
306 * Create error messages for unusual process exits. An
307 * extra newline gets appended to each error message, but
308 * it gets removed below (in the same fashion that an
309 * extra newline in the command's output is removed).
311 static int JimCheckWaitStatus(Jim_Interp *interp, pidtype pid, int waitStatus)
313 Jim_Obj *errorCode = Jim_NewListObj(interp, NULL, 0);
314 int rc = JIM_ERR;
316 if (WIFEXITED(waitStatus)) {
317 if (WEXITSTATUS(waitStatus) == 0) {
318 Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, "NONE", -1));
319 rc = JIM_OK;
321 else {
322 Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, "CHILDSTATUS", -1));
323 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, (long)pid));
324 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, WEXITSTATUS(waitStatus)));
327 else {
328 const char *type;
329 const char *action;
331 if (WIFSIGNALED(waitStatus)) {
332 type = "CHILDKILLED";
333 action = "killed";
335 else {
336 type = "CHILDSUSP";
337 action = "suspended";
340 Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, type, -1));
342 #ifdef jim_ext_signal
343 Jim_SetResultFormatted(interp, "child %s by signal %s", action, Jim_SignalId(WTERMSIG(waitStatus)));
344 Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, Jim_SignalId(WTERMSIG(waitStatus)), -1));
345 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, pid));
346 Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, Jim_SignalName(WTERMSIG(waitStatus)), -1));
347 #else
348 Jim_SetResultFormatted(interp, "child %s by signal %d", action, WTERMSIG(waitStatus));
349 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, WTERMSIG(waitStatus)));
350 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, (long)pid));
351 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, WTERMSIG(waitStatus)));
352 #endif
354 Jim_SetGlobalVariableStr(interp, "errorCode", errorCode);
355 return rc;
359 * Data structures of the following type are used by JimFork and
360 * JimWaitPids to keep track of child processes.
363 struct WaitInfo
365 pidtype pid; /* Process id of child. */
366 int status; /* Status returned when child exited or suspended. */
367 int flags; /* Various flag bits; see below for definitions. */
370 struct WaitInfoTable {
371 struct WaitInfo *info;
372 int size;
373 int used;
377 * Flag bits in WaitInfo structures:
379 * WI_DETACHED - Non-zero means no-one cares about the
380 * process anymore. Ignore it until it
381 * exits, then forget about it.
384 #define WI_DETACHED 2
386 #define WAIT_TABLE_GROW_BY 4
388 static void JimFreeWaitInfoTable(struct Jim_Interp *interp, void *privData)
390 struct WaitInfoTable *table = privData;
392 Jim_Free(table->info);
393 Jim_Free(table);
396 static struct WaitInfoTable *JimAllocWaitInfoTable(void)
398 struct WaitInfoTable *table = Jim_Alloc(sizeof(*table));
399 table->info = NULL;
400 table->size = table->used = 0;
402 return table;
406 * The main [exec] command
408 static int Jim_ExecCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
410 fdtype outputId; /* File id for output pipe. -1
411 * means command overrode. */
412 fdtype errorId; /* File id for temporary file
413 * containing error output. */
414 pidtype *pidPtr;
415 int numPids, result;
418 * See if the command is to be run in background; if so, create
419 * the command, detach it, and return.
421 if (argc > 1 && Jim_CompareStringImmediate(interp, argv[argc - 1], "&")) {
422 Jim_Obj *listObj;
423 int i;
425 argc--;
426 numPids = JimCreatePipeline(interp, argc - 1, argv + 1, &pidPtr, NULL, NULL, NULL);
427 if (numPids < 0) {
428 return JIM_ERR;
430 /* The return value is a list of the pids */
431 listObj = Jim_NewListObj(interp, NULL, 0);
432 for (i = 0; i < numPids; i++) {
433 Jim_ListAppendElement(interp, listObj, Jim_NewIntObj(interp, (long)pidPtr[i]));
435 Jim_SetResult(interp, listObj);
436 JimDetachPids(interp, numPids, pidPtr);
437 Jim_Free(pidPtr);
438 return JIM_OK;
442 * Create the command's pipeline.
444 numPids =
445 JimCreatePipeline(interp, argc - 1, argv + 1, &pidPtr, NULL, &outputId, &errorId);
447 if (numPids < 0) {
448 return JIM_ERR;
452 * Read the child's output (if any) and put it into the result.
454 Jim_SetResultString(interp, "", 0);
456 result = JIM_OK;
457 if (outputId != JIM_BAD_FD) {
458 result = JimAppendStreamToString(interp, outputId, Jim_GetResult(interp));
459 if (result < 0) {
460 Jim_SetResultErrno(interp, "error reading from output pipe");
464 if (JimCleanupChildren(interp, numPids, pidPtr, errorId) != JIM_OK) {
465 result = JIM_ERR;
467 return result;
470 static void JimReapDetachedPids(struct WaitInfoTable *table)
472 struct WaitInfo *waitPtr;
473 int count;
475 if (!table) {
476 return;
479 for (waitPtr = table->info, count = table->used; count > 0; waitPtr++, count--) {
480 if (waitPtr->flags & WI_DETACHED) {
481 int status;
482 pidtype pid = JimWaitPid(waitPtr->pid, &status, WNOHANG);
483 if (pid != JIM_BAD_PID) {
484 if (waitPtr != &table->info[table->used - 1]) {
485 *waitPtr = table->info[table->used - 1];
487 table->used--;
494 * Does waitpid() on the given pid, and then removes the
495 * entry from the wait table.
497 * Returns the pid if OK and updates *statusPtr with the status,
498 * or JIM_BAD_PID if the pid was not in the table.
500 static pidtype JimWaitForProcess(struct WaitInfoTable *table, pidtype pid, int *statusPtr)
502 int i;
504 /* Find it in the table */
505 for (i = 0; i < table->used; i++) {
506 if (pid == table->info[i].pid) {
507 /* wait for it */
508 JimWaitPid(pid, statusPtr, 0);
510 /* Remove it from the table */
511 if (i != table->used - 1) {
512 table->info[i] = table->info[table->used - 1];
514 table->used--;
515 return pid;
519 /* Not found */
520 return JIM_BAD_PID;
524 *----------------------------------------------------------------------
526 * JimDetachPids --
528 * This procedure is called to indicate that one or more child
529 * processes have been placed in background and are no longer
530 * cared about. These children can be cleaned up with JimReapDetachedPids().
532 * Results:
533 * None.
535 * Side effects:
536 * None.
538 *----------------------------------------------------------------------
541 static void JimDetachPids(Jim_Interp *interp, int numPids, const pidtype *pidPtr)
543 int j;
544 struct WaitInfoTable *table = Jim_CmdPrivData(interp);
546 for (j = 0; j < numPids; j++) {
547 /* Find it in the table */
548 int i;
549 for (i = 0; i < table->used; i++) {
550 if (pidPtr[j] == table->info[i].pid) {
551 table->info[i].flags |= WI_DETACHED;
552 break;
558 static FILE *JimGetAioFilehandle(Jim_Interp *interp, const char *name)
560 FILE *fh;
561 Jim_Obj *fhObj;
563 fhObj = Jim_NewStringObj(interp, name, -1);
564 Jim_IncrRefCount(fhObj);
565 fh = Jim_AioFilehandle(interp, fhObj);
566 Jim_DecrRefCount(interp, fhObj);
568 return fh;
572 *----------------------------------------------------------------------
574 * JimCreatePipeline --
576 * Given an argc/argv array, instantiate a pipeline of processes
577 * as described by the argv.
579 * Results:
580 * The return value is a count of the number of new processes
581 * created, or -1 if an error occurred while creating the pipeline.
582 * *pidArrayPtr is filled in with the address of a dynamically
583 * allocated array giving the ids of all of the processes. It
584 * is up to the caller to free this array when it isn't needed
585 * anymore. If inPipePtr is non-NULL, *inPipePtr is filled in
586 * with the file id for the input pipe for the pipeline (if any):
587 * the caller must eventually close this file. If outPipePtr
588 * isn't NULL, then *outPipePtr is filled in with the file id
589 * for the output pipe from the pipeline: the caller must close
590 * this file. If errFilePtr isn't NULL, then *errFilePtr is filled
591 * with a file id that may be used to read error output after the
592 * pipeline completes.
594 * Side effects:
595 * Processes and pipes are created.
597 *----------------------------------------------------------------------
599 static int
600 JimCreatePipeline(Jim_Interp *interp, int argc, Jim_Obj *const *argv, pidtype **pidArrayPtr,
601 fdtype *inPipePtr, fdtype *outPipePtr, fdtype *errFilePtr)
603 pidtype *pidPtr = NULL; /* Points to malloc-ed array holding all
604 * the pids of child processes. */
605 int numPids = 0; /* Actual number of processes that exist
606 * at *pidPtr right now. */
607 int cmdCount; /* Count of number of distinct commands
608 * found in argc/argv. */
609 const char *input = NULL; /* Describes input for pipeline, depending
610 * on "inputFile". NULL means take input
611 * from stdin/pipe. */
613 #define FILE_NAME 0 /* input/output: filename */
614 #define FILE_APPEND 1 /* output only: filename, append */
615 #define FILE_HANDLE 2 /* input/output: filehandle */
616 #define FILE_TEXT 3 /* input only: input is actual text */
618 int inputFile = FILE_NAME; /* 1 means input is name of input file.
619 * 2 means input is filehandle name.
620 * 0 means input holds actual
621 * text to be input to command. */
623 int outputFile = FILE_NAME; /* 0 means output is the name of output file.
624 * 1 means output is the name of output file, and append.
625 * 2 means output is filehandle name.
626 * All this is ignored if output is NULL
628 int errorFile = FILE_NAME; /* 0 means error is the name of error file.
629 * 1 means error is the name of error file, and append.
630 * 2 means error is filehandle name.
631 * All this is ignored if error is NULL
633 const char *output = NULL; /* Holds name of output file to pipe to,
634 * or NULL if output goes to stdout/pipe. */
635 const char *error = NULL; /* Holds name of stderr file to pipe to,
636 * or NULL if stderr goes to stderr/pipe. */
637 fdtype inputId = JIM_BAD_FD;
638 /* Readable file id input to current command in
639 * pipeline (could be file or pipe). JIM_BAD_FD
640 * means use stdin. */
641 fdtype outputId = JIM_BAD_FD;
642 /* Writable file id for output from current
643 * command in pipeline (could be file or pipe).
644 * JIM_BAD_FD means use stdout. */
645 fdtype errorId = JIM_BAD_FD;
646 /* Writable file id for all standard error
647 * output from all commands in pipeline. JIM_BAD_FD
648 * means use stderr. */
649 fdtype lastOutputId = JIM_BAD_FD;
650 /* Write file id for output from last command
651 * in pipeline (could be file or pipe).
652 * -1 means use stdout. */
653 fdtype pipeIds[2]; /* File ids for pipe that's being created. */
654 int firstArg, lastArg; /* Indexes of first and last arguments in
655 * current command. */
656 int lastBar;
657 int i;
658 pidtype pid;
659 char **save_environ;
660 struct WaitInfoTable *table = Jim_CmdPrivData(interp);
662 /* Holds the args which will be used to exec */
663 char **arg_array = Jim_Alloc(sizeof(*arg_array) * (argc + 1));
664 int arg_count = 0;
666 JimReapDetachedPids(table);
668 if (inPipePtr != NULL) {
669 *inPipePtr = JIM_BAD_FD;
671 if (outPipePtr != NULL) {
672 *outPipePtr = JIM_BAD_FD;
674 if (errFilePtr != NULL) {
675 *errFilePtr = JIM_BAD_FD;
677 pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
680 * First, scan through all the arguments to figure out the structure
681 * of the pipeline. Count the number of distinct processes (it's the
682 * number of "|" arguments). If there are "<", "<<", or ">" arguments
683 * then make note of input and output redirection and remove these
684 * arguments and the arguments that follow them.
686 cmdCount = 1;
687 lastBar = -1;
688 for (i = 0; i < argc; i++) {
689 const char *arg = Jim_String(argv[i]);
691 if (arg[0] == '<') {
692 inputFile = FILE_NAME;
693 input = arg + 1;
694 if (*input == '<') {
695 inputFile = FILE_TEXT;
696 input++;
698 else if (*input == '@') {
699 inputFile = FILE_HANDLE;
700 input++;
703 if (!*input && ++i < argc) {
704 input = Jim_String(argv[i]);
707 else if (arg[0] == '>') {
708 int dup_error = 0;
710 outputFile = FILE_NAME;
712 output = arg + 1;
713 if (*output == '>') {
714 outputFile = FILE_APPEND;
715 output++;
717 if (*output == '&') {
718 /* Redirect stderr too */
719 output++;
720 dup_error = 1;
722 if (*output == '@') {
723 outputFile = FILE_HANDLE;
724 output++;
726 if (!*output && ++i < argc) {
727 output = Jim_String(argv[i]);
729 if (dup_error) {
730 errorFile = outputFile;
731 error = output;
734 else if (arg[0] == '2' && arg[1] == '>') {
735 error = arg + 2;
736 errorFile = FILE_NAME;
738 if (*error == '@') {
739 errorFile = FILE_HANDLE;
740 error++;
742 else if (*error == '>') {
743 errorFile = FILE_APPEND;
744 error++;
746 if (!*error && ++i < argc) {
747 error = Jim_String(argv[i]);
750 else {
751 if (strcmp(arg, "|") == 0 || strcmp(arg, "|&") == 0) {
752 if (i == lastBar + 1 || i == argc - 1) {
753 Jim_SetResultString(interp, "illegal use of | or |& in command", -1);
754 goto badargs;
756 lastBar = i;
757 cmdCount++;
759 /* Either |, |& or a "normal" arg, so store it in the arg array */
760 arg_array[arg_count++] = (char *)arg;
761 continue;
764 if (i >= argc) {
765 Jim_SetResultFormatted(interp, "can't specify \"%s\" as last word in command", arg);
766 goto badargs;
770 if (arg_count == 0) {
771 Jim_SetResultString(interp, "didn't specify command to execute", -1);
772 badargs:
773 Jim_Free(arg_array);
774 return -1;
777 /* Must do this before vfork(), so do it now */
778 save_environ = JimSaveEnv(JimBuildEnv(interp));
781 * Set up the redirected input source for the pipeline, if
782 * so requested.
784 if (input != NULL) {
785 if (inputFile == FILE_TEXT) {
787 * Immediate data in command. Create temporary file and
788 * put data into file.
790 inputId = JimCreateTemp(interp, input);
791 if (inputId == JIM_BAD_FD) {
792 goto error;
795 else if (inputFile == FILE_HANDLE) {
796 /* Should be a file descriptor */
797 FILE *fh = JimGetAioFilehandle(interp, input);
799 if (fh == NULL) {
800 goto error;
802 inputId = JimDupFd(JimFileno(fh));
804 else {
806 * File redirection. Just open the file.
808 inputId = JimOpenForRead(input);
809 if (inputId == JIM_BAD_FD) {
810 Jim_SetResultFormatted(interp, "couldn't read file \"%s\": %s", input, JimStrError());
811 goto error;
815 else if (inPipePtr != NULL) {
816 if (JimPipe(pipeIds) != 0) {
817 Jim_SetResultErrno(interp, "couldn't create input pipe for command");
818 goto error;
820 inputId = pipeIds[0];
821 *inPipePtr = pipeIds[1];
822 pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
826 * Set up the redirected output sink for the pipeline from one
827 * of two places, if requested.
829 if (output != NULL) {
830 if (outputFile == FILE_HANDLE) {
831 FILE *fh = JimGetAioFilehandle(interp, output);
832 if (fh == NULL) {
833 goto error;
835 fflush(fh);
836 lastOutputId = JimDupFd(JimFileno(fh));
838 else {
840 * Output is to go to a file.
842 lastOutputId = JimOpenForWrite(output, outputFile == FILE_APPEND);
843 if (lastOutputId == JIM_BAD_FD) {
844 Jim_SetResultFormatted(interp, "couldn't write file \"%s\": %s", output, JimStrError());
845 goto error;
849 else if (outPipePtr != NULL) {
851 * Output is to go to a pipe.
853 if (JimPipe(pipeIds) != 0) {
854 Jim_SetResultErrno(interp, "couldn't create output pipe");
855 goto error;
857 lastOutputId = pipeIds[1];
858 *outPipePtr = pipeIds[0];
859 pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
861 /* If we are redirecting stderr with 2>filename or 2>@fileId, then we ignore errFilePtr */
862 if (error != NULL) {
863 if (errorFile == FILE_HANDLE) {
864 if (strcmp(error, "1") == 0) {
865 /* Special 2>@1 */
866 if (lastOutputId != JIM_BAD_FD) {
867 errorId = JimDupFd(lastOutputId);
869 else {
870 /* No redirection of stdout, so just use 2>@stdout */
871 error = "stdout";
874 if (errorId == JIM_BAD_FD) {
875 FILE *fh = JimGetAioFilehandle(interp, error);
876 if (fh == NULL) {
877 goto error;
879 fflush(fh);
880 errorId = JimDupFd(JimFileno(fh));
883 else {
885 * Output is to go to a file.
887 errorId = JimOpenForWrite(error, errorFile == FILE_APPEND);
888 if (errorId == JIM_BAD_FD) {
889 Jim_SetResultFormatted(interp, "couldn't write file \"%s\": %s", error, JimStrError());
890 goto error;
894 else if (errFilePtr != NULL) {
896 * Set up the standard error output sink for the pipeline, if
897 * requested. Use a temporary file which is opened, then deleted.
898 * Could potentially just use pipe, but if it filled up it could
899 * cause the pipeline to deadlock: we'd be waiting for processes
900 * to complete before reading stderr, and processes couldn't complete
901 * because stderr was backed up.
903 errorId = JimCreateTemp(interp, NULL);
904 if (errorId == JIM_BAD_FD) {
905 goto error;
907 *errFilePtr = JimDupFd(errorId);
911 * Scan through the argc array, forking off a process for each
912 * group of arguments between "|" arguments.
915 pidPtr = Jim_Alloc(cmdCount * sizeof(*pidPtr));
916 for (i = 0; i < numPids; i++) {
917 pidPtr[i] = JIM_BAD_PID;
919 for (firstArg = 0; firstArg < arg_count; numPids++, firstArg = lastArg + 1) {
920 int pipe_dup_err = 0;
921 fdtype origErrorId = errorId;
923 for (lastArg = firstArg; lastArg < arg_count; lastArg++) {
924 if (arg_array[lastArg][0] == '|') {
925 if (arg_array[lastArg][1] == '&') {
926 pipe_dup_err = 1;
928 break;
931 /* Replace | with NULL for execv() */
932 arg_array[lastArg] = NULL;
933 if (lastArg == arg_count) {
934 outputId = lastOutputId;
936 else {
937 if (JimPipe(pipeIds) != 0) {
938 Jim_SetResultErrno(interp, "couldn't create pipe");
939 goto error;
941 outputId = pipeIds[1];
944 /* Now fork the child */
946 #ifdef __MINGW32__
947 pid = JimStartWinProcess(interp, &arg_array[firstArg], save_environ ? save_environ[0] : NULL, inputId, outputId, errorId);
948 if (pid == JIM_BAD_PID) {
949 Jim_SetResultFormatted(interp, "couldn't exec \"%s\"", arg_array[firstArg]);
950 goto error;
952 #else
954 * Disable SIGPIPE signals: if they were allowed, this process
955 * might go away unexpectedly if children misbehave. This code
956 * can potentially interfere with other application code that
957 * expects to handle SIGPIPEs; what's really needed is an
958 * arbiter for signals to allow them to be "shared".
960 if (table->info == NULL) {
961 (void)signal(SIGPIPE, SIG_IGN);
964 /* Need to do this befor vfork() */
965 if (pipe_dup_err) {
966 errorId = outputId;
970 * Make a new process and enter it into the table if the fork
971 * is successful.
973 pid = vfork();
974 if (pid < 0) {
975 Jim_SetResultErrno(interp, "couldn't fork child process");
976 goto error;
978 if (pid == 0) {
979 /* Child */
981 if (inputId != -1) dup2(inputId, 0);
982 if (outputId != -1) dup2(outputId, 1);
983 if (errorId != -1) dup2(errorId, 2);
985 for (i = 3; (i <= outputId) || (i <= inputId) || (i <= errorId); i++) {
986 close(i);
989 execvpe(arg_array[firstArg], &arg_array[firstArg], Jim_GetEnviron());
991 /* Need to prep an error message before vfork(), just in case */
992 fprintf(stderr, "couldn't exec \"%s\"", arg_array[firstArg]);
993 _exit(127);
995 #endif
997 /* parent */
1000 * Enlarge the wait table if there isn't enough space for a new
1001 * entry.
1003 if (table->used == table->size) {
1004 table->size += WAIT_TABLE_GROW_BY;
1005 table->info = Jim_Realloc(table->info, table->size * sizeof(*table->info));
1008 table->info[table->used].pid = pid;
1009 table->info[table->used].flags = 0;
1010 table->used++;
1012 pidPtr[numPids] = pid;
1014 /* Restore in case of pipe_dup_err */
1015 errorId = origErrorId;
1018 * Close off our copies of file descriptors that were set up for
1019 * this child, then set up the input for the next child.
1022 if (inputId != JIM_BAD_FD) {
1023 JimCloseFd(inputId);
1025 if (outputId != JIM_BAD_FD) {
1026 JimCloseFd(outputId);
1028 inputId = pipeIds[0];
1029 pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
1031 *pidArrayPtr = pidPtr;
1034 * All done. Cleanup open files lying around and then return.
1037 cleanup:
1038 if (inputId != JIM_BAD_FD) {
1039 JimCloseFd(inputId);
1041 if (lastOutputId != JIM_BAD_FD) {
1042 JimCloseFd(lastOutputId);
1044 if (errorId != JIM_BAD_FD) {
1045 JimCloseFd(errorId);
1047 Jim_Free(arg_array);
1049 JimRestoreEnv(save_environ);
1051 return numPids;
1054 * An error occurred. There could have been extra files open, such
1055 * as pipes between children. Clean them all up. Detach any child
1056 * processes that have been created.
1059 error:
1060 if ((inPipePtr != NULL) && (*inPipePtr != JIM_BAD_FD)) {
1061 JimCloseFd(*inPipePtr);
1062 *inPipePtr = JIM_BAD_FD;
1064 if ((outPipePtr != NULL) && (*outPipePtr != JIM_BAD_FD)) {
1065 JimCloseFd(*outPipePtr);
1066 *outPipePtr = JIM_BAD_FD;
1068 if ((errFilePtr != NULL) && (*errFilePtr != JIM_BAD_FD)) {
1069 JimCloseFd(*errFilePtr);
1070 *errFilePtr = JIM_BAD_FD;
1072 if (pipeIds[0] != JIM_BAD_FD) {
1073 JimCloseFd(pipeIds[0]);
1075 if (pipeIds[1] != JIM_BAD_FD) {
1076 JimCloseFd(pipeIds[1]);
1078 if (pidPtr != NULL) {
1079 for (i = 0; i < numPids; i++) {
1080 if (pidPtr[i] != JIM_BAD_PID) {
1081 JimDetachPids(interp, 1, &pidPtr[i]);
1084 Jim_Free(pidPtr);
1086 numPids = -1;
1087 goto cleanup;
1091 *----------------------------------------------------------------------
1093 * JimCleanupChildren --
1095 * This is a utility procedure used to wait for child processes
1096 * to exit, record information about abnormal exits, and then
1097 * collect any stderr output generated by them.
1099 * Results:
1100 * The return value is a standard Tcl result. If anything at
1101 * weird happened with the child processes, JIM_ERROR is returned
1102 * and a message is left in interp->result.
1104 * Side effects:
1105 * If the last character of interp->result is a newline, then it
1106 * is removed. File errorId gets closed, and pidPtr is freed
1107 * back to the storage allocator.
1109 *----------------------------------------------------------------------
1112 static int JimCleanupChildren(Jim_Interp *interp, int numPids, pidtype *pidPtr, fdtype errorId)
1114 struct WaitInfoTable *table = Jim_CmdPrivData(interp);
1115 int result = JIM_OK;
1116 int i;
1118 for (i = 0; i < numPids; i++) {
1119 int waitStatus = 0;
1120 if (JimWaitForProcess(table, pidPtr[i], &waitStatus) != JIM_BAD_PID) {
1121 if (JimCheckWaitStatus(interp, pidPtr[i], waitStatus) != JIM_OK) {
1122 result = JIM_ERR;
1126 Jim_Free(pidPtr);
1129 * Read the standard error file. If there's anything there,
1130 * then add the file's contents to the result
1131 * string.
1133 if (errorId != JIM_BAD_FD) {
1134 JimRewindFd(errorId);
1135 if (JimAppendStreamToString(interp, errorId, Jim_GetResult(interp)) != JIM_OK) {
1136 result = JIM_ERR;
1140 JimTrimTrailingNewline(interp);
1142 return result;
1145 int Jim_execInit(Jim_Interp *interp)
1147 if (Jim_PackageProvide(interp, "exec", "1.0", JIM_ERRMSG))
1148 return JIM_ERR;
1149 Jim_CreateCommand(interp, "exec", Jim_ExecCmd, JimAllocWaitInfoTable(), JimFreeWaitInfoTable);
1150 return JIM_OK;
1153 #if defined(__MINGW32__)
1154 /* Windows-specific (mingw) implementation */
1156 static SECURITY_ATTRIBUTES *JimStdSecAttrs(void)
1158 static SECURITY_ATTRIBUTES secAtts;
1160 secAtts.nLength = sizeof(SECURITY_ATTRIBUTES);
1161 secAtts.lpSecurityDescriptor = NULL;
1162 secAtts.bInheritHandle = TRUE;
1163 return &secAtts;
1166 static int JimErrno(void)
1168 switch (GetLastError()) {
1169 case ERROR_FILE_NOT_FOUND: return ENOENT;
1170 case ERROR_PATH_NOT_FOUND: return ENOENT;
1171 case ERROR_TOO_MANY_OPEN_FILES: return EMFILE;
1172 case ERROR_ACCESS_DENIED: return EACCES;
1173 case ERROR_INVALID_HANDLE: return EBADF;
1174 case ERROR_BAD_ENVIRONMENT: return E2BIG;
1175 case ERROR_BAD_FORMAT: return ENOEXEC;
1176 case ERROR_INVALID_ACCESS: return EACCES;
1177 case ERROR_INVALID_DRIVE: return ENOENT;
1178 case ERROR_CURRENT_DIRECTORY: return EACCES;
1179 case ERROR_NOT_SAME_DEVICE: return EXDEV;
1180 case ERROR_NO_MORE_FILES: return ENOENT;
1181 case ERROR_WRITE_PROTECT: return EROFS;
1182 case ERROR_BAD_UNIT: return ENXIO;
1183 case ERROR_NOT_READY: return EBUSY;
1184 case ERROR_BAD_COMMAND: return EIO;
1185 case ERROR_CRC: return EIO;
1186 case ERROR_BAD_LENGTH: return EIO;
1187 case ERROR_SEEK: return EIO;
1188 case ERROR_WRITE_FAULT: return EIO;
1189 case ERROR_READ_FAULT: return EIO;
1190 case ERROR_GEN_FAILURE: return EIO;
1191 case ERROR_SHARING_VIOLATION: return EACCES;
1192 case ERROR_LOCK_VIOLATION: return EACCES;
1193 case ERROR_SHARING_BUFFER_EXCEEDED: return ENFILE;
1194 case ERROR_HANDLE_DISK_FULL: return ENOSPC;
1195 case ERROR_NOT_SUPPORTED: return ENODEV;
1196 case ERROR_REM_NOT_LIST: return EBUSY;
1197 case ERROR_DUP_NAME: return EEXIST;
1198 case ERROR_BAD_NETPATH: return ENOENT;
1199 case ERROR_NETWORK_BUSY: return EBUSY;
1200 case ERROR_DEV_NOT_EXIST: return ENODEV;
1201 case ERROR_TOO_MANY_CMDS: return EAGAIN;
1202 case ERROR_ADAP_HDW_ERR: return EIO;
1203 case ERROR_BAD_NET_RESP: return EIO;
1204 case ERROR_UNEXP_NET_ERR: return EIO;
1205 case ERROR_NETNAME_DELETED: return ENOENT;
1206 case ERROR_NETWORK_ACCESS_DENIED: return EACCES;
1207 case ERROR_BAD_DEV_TYPE: return ENODEV;
1208 case ERROR_BAD_NET_NAME: return ENOENT;
1209 case ERROR_TOO_MANY_NAMES: return ENFILE;
1210 case ERROR_TOO_MANY_SESS: return EIO;
1211 case ERROR_SHARING_PAUSED: return EAGAIN;
1212 case ERROR_REDIR_PAUSED: return EAGAIN;
1213 case ERROR_FILE_EXISTS: return EEXIST;
1214 case ERROR_CANNOT_MAKE: return ENOSPC;
1215 case ERROR_OUT_OF_STRUCTURES: return ENFILE;
1216 case ERROR_ALREADY_ASSIGNED: return EEXIST;
1217 case ERROR_INVALID_PASSWORD: return EPERM;
1218 case ERROR_NET_WRITE_FAULT: return EIO;
1219 case ERROR_NO_PROC_SLOTS: return EAGAIN;
1220 case ERROR_DISK_CHANGE: return EXDEV;
1221 case ERROR_BROKEN_PIPE: return EPIPE;
1222 case ERROR_OPEN_FAILED: return ENOENT;
1223 case ERROR_DISK_FULL: return ENOSPC;
1224 case ERROR_NO_MORE_SEARCH_HANDLES: return EMFILE;
1225 case ERROR_INVALID_TARGET_HANDLE: return EBADF;
1226 case ERROR_INVALID_NAME: return ENOENT;
1227 case ERROR_PROC_NOT_FOUND: return ESRCH;
1228 case ERROR_WAIT_NO_CHILDREN: return ECHILD;
1229 case ERROR_CHILD_NOT_COMPLETE: return ECHILD;
1230 case ERROR_DIRECT_ACCESS_HANDLE: return EBADF;
1231 case ERROR_SEEK_ON_DEVICE: return ESPIPE;
1232 case ERROR_BUSY_DRIVE: return EAGAIN;
1233 case ERROR_DIR_NOT_EMPTY: return EEXIST;
1234 case ERROR_NOT_LOCKED: return EACCES;
1235 case ERROR_BAD_PATHNAME: return ENOENT;
1236 case ERROR_LOCK_FAILED: return EACCES;
1237 case ERROR_ALREADY_EXISTS: return EEXIST;
1238 case ERROR_FILENAME_EXCED_RANGE: return ENAMETOOLONG;
1239 case ERROR_BAD_PIPE: return EPIPE;
1240 case ERROR_PIPE_BUSY: return EAGAIN;
1241 case ERROR_PIPE_NOT_CONNECTED: return EPIPE;
1242 case ERROR_DIRECTORY: return ENOTDIR;
1244 return EINVAL;
1247 static int JimPipe(fdtype pipefd[2])
1249 if (CreatePipe(&pipefd[0], &pipefd[1], NULL, 0)) {
1250 return 0;
1252 return -1;
1255 static fdtype JimDupFd(fdtype infd)
1257 fdtype dupfd;
1258 pidtype pid = GetCurrentProcess();
1260 if (DuplicateHandle(pid, infd, pid, &dupfd, 0, TRUE, DUPLICATE_SAME_ACCESS)) {
1261 return dupfd;
1263 return JIM_BAD_FD;
1266 static int JimRewindFd(fdtype fd)
1268 return SetFilePointer(fd, 0, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER ? -1 : 0;
1271 #if 0
1272 static int JimReadFd(fdtype fd, char *buffer, size_t len)
1274 DWORD num;
1276 if (ReadFile(fd, buffer, len, &num, NULL)) {
1277 return num;
1279 if (GetLastError() == ERROR_HANDLE_EOF || GetLastError() == ERROR_BROKEN_PIPE) {
1280 return 0;
1282 return -1;
1284 #endif
1286 static FILE *JimFdOpenForRead(fdtype fd)
1288 return _fdopen(_open_osfhandle((int)fd, _O_RDONLY | _O_TEXT), "r");
1291 static fdtype JimFileno(FILE *fh)
1293 return (fdtype)_get_osfhandle(_fileno(fh));
1296 static fdtype JimOpenForRead(const char *filename)
1298 return CreateFile(filename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
1299 JimStdSecAttrs(), OPEN_EXISTING, 0, NULL);
1302 static fdtype JimOpenForWrite(const char *filename, int append)
1304 return CreateFile(filename, append ? FILE_APPEND_DATA : GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
1305 JimStdSecAttrs(), append ? OPEN_ALWAYS : CREATE_ALWAYS, 0, (HANDLE) NULL);
1308 static FILE *JimFdOpenForWrite(fdtype fd)
1310 return _fdopen(_open_osfhandle((int)fd, _O_TEXT), "w");
1313 static pidtype JimWaitPid(pidtype pid, int *status, int nohang)
1315 DWORD ret = WaitForSingleObject(pid, nohang ? 0 : INFINITE);
1316 if (ret == WAIT_TIMEOUT || ret == WAIT_FAILED) {
1317 /* WAIT_TIMEOUT can only happend with WNOHANG */
1318 return JIM_BAD_PID;
1320 GetExitCodeProcess(pid, &ret);
1321 *status = ret;
1322 CloseHandle(pid);
1323 return pid;
1326 static HANDLE JimCreateTemp(Jim_Interp *interp, const char *contents)
1328 char name[MAX_PATH];
1329 HANDLE handle;
1331 if (!GetTempPath(MAX_PATH, name) || !GetTempFileName(name, "JIM", 0, name)) {
1332 return JIM_BAD_FD;
1335 handle = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, JimStdSecAttrs(),
1336 CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE,
1337 NULL);
1339 if (handle == INVALID_HANDLE_VALUE) {
1340 goto error;
1343 if (contents != NULL) {
1344 /* Use fdopen() to get automatic text-mode translation */
1345 FILE *fh = JimFdOpenForWrite(JimDupFd(handle));
1346 if (fh == NULL) {
1347 goto error;
1350 if (fwrite(contents, strlen(contents), 1, fh) != 1) {
1351 fclose(fh);
1352 goto error;
1354 fseek(fh, 0, SEEK_SET);
1355 fclose(fh);
1357 return handle;
1359 error:
1360 Jim_SetResultErrno(interp, "failed to create temp file");
1361 CloseHandle(handle);
1362 DeleteFile(name);
1363 return JIM_BAD_FD;
1366 static int
1367 JimWinFindExecutable(const char *originalName, char fullPath[MAX_PATH])
1369 int i;
1370 static char extensions[][5] = {".exe", "", ".bat"};
1372 for (i = 0; i < (int) (sizeof(extensions) / sizeof(extensions[0])); i++) {
1373 lstrcpyn(fullPath, originalName, MAX_PATH - 5);
1374 lstrcat(fullPath, extensions[i]);
1376 if (SearchPath(NULL, fullPath, NULL, MAX_PATH, fullPath, NULL) == 0) {
1377 continue;
1379 if (GetFileAttributes(fullPath) & FILE_ATTRIBUTE_DIRECTORY) {
1380 continue;
1382 return 0;
1385 return -1;
1388 static char **JimSaveEnv(char **env)
1390 return env;
1393 static void JimRestoreEnv(char **env)
1395 JimFreeEnv(env, Jim_GetEnviron());
1398 static Jim_Obj *
1399 JimWinBuildCommandLine(Jim_Interp *interp, char **argv)
1401 char *start, *special;
1402 int quote, i;
1404 Jim_Obj *strObj = Jim_NewStringObj(interp, "", 0);
1406 for (i = 0; argv[i]; i++) {
1407 if (i > 0) {
1408 Jim_AppendString(interp, strObj, " ", 1);
1411 if (argv[i][0] == '\0') {
1412 quote = 1;
1414 else {
1415 quote = 0;
1416 for (start = argv[i]; *start != '\0'; start++) {
1417 if (isspace(UCHAR(*start))) {
1418 quote = 1;
1419 break;
1423 if (quote) {
1424 Jim_AppendString(interp, strObj, "\"" , 1);
1427 start = argv[i];
1428 for (special = argv[i]; ; ) {
1429 if ((*special == '\\') && (special[1] == '\\' ||
1430 special[1] == '"' || (quote && special[1] == '\0'))) {
1431 Jim_AppendString(interp, strObj, start, special - start);
1432 start = special;
1433 while (1) {
1434 special++;
1435 if (*special == '"' || (quote && *special == '\0')) {
1437 * N backslashes followed a quote -> insert
1438 * N * 2 + 1 backslashes then a quote.
1441 Jim_AppendString(interp, strObj, start, special - start);
1442 break;
1444 if (*special != '\\') {
1445 break;
1448 Jim_AppendString(interp, strObj, start, special - start);
1449 start = special;
1451 if (*special == '"') {
1452 if (special == start) {
1453 Jim_AppendString(interp, strObj, "\"", 1);
1455 else {
1456 Jim_AppendString(interp, strObj, start, special - start);
1458 Jim_AppendString(interp, strObj, "\\\"", 2);
1459 start = special + 1;
1461 if (*special == '\0') {
1462 break;
1464 special++;
1466 Jim_AppendString(interp, strObj, start, special - start);
1467 if (quote) {
1468 Jim_AppendString(interp, strObj, "\"", 1);
1471 return strObj;
1474 static pidtype
1475 JimStartWinProcess(Jim_Interp *interp, char **argv, char *env, fdtype inputId, fdtype outputId, fdtype errorId)
1477 STARTUPINFO startInfo;
1478 PROCESS_INFORMATION procInfo;
1479 HANDLE hProcess, h;
1480 char execPath[MAX_PATH];
1481 char *originalName;
1482 pidtype pid = JIM_BAD_PID;
1483 Jim_Obj *cmdLineObj;
1485 if (JimWinFindExecutable(argv[0], execPath) < 0) {
1486 return JIM_BAD_PID;
1488 originalName = argv[0];
1489 argv[0] = execPath;
1491 hProcess = GetCurrentProcess();
1492 cmdLineObj = JimWinBuildCommandLine(interp, argv);
1495 * STARTF_USESTDHANDLES must be used to pass handles to child process.
1496 * Using SetStdHandle() and/or dup2() only works when a console mode
1497 * parent process is spawning an attached console mode child process.
1500 ZeroMemory(&startInfo, sizeof(startInfo));
1501 startInfo.cb = sizeof(startInfo);
1502 startInfo.dwFlags = STARTF_USESTDHANDLES;
1503 startInfo.hStdInput = INVALID_HANDLE_VALUE;
1504 startInfo.hStdOutput= INVALID_HANDLE_VALUE;
1505 startInfo.hStdError = INVALID_HANDLE_VALUE;
1508 * Duplicate all the handles which will be passed off as stdin, stdout
1509 * and stderr of the child process. The duplicate handles are set to
1510 * be inheritable, so the child process can use them.
1512 if (inputId == JIM_BAD_FD) {
1513 if (CreatePipe(&startInfo.hStdInput, &h, JimStdSecAttrs(), 0) != FALSE) {
1514 CloseHandle(h);
1516 } else {
1517 DuplicateHandle(hProcess, inputId, hProcess, &startInfo.hStdInput,
1518 0, TRUE, DUPLICATE_SAME_ACCESS);
1520 if (startInfo.hStdInput == JIM_BAD_FD) {
1521 goto end;
1524 if (outputId == JIM_BAD_FD) {
1525 startInfo.hStdOutput = CreateFile("NUL:", GENERIC_WRITE, 0,
1526 JimStdSecAttrs(), OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1527 } else {
1528 DuplicateHandle(hProcess, outputId, hProcess, &startInfo.hStdOutput,
1529 0, TRUE, DUPLICATE_SAME_ACCESS);
1531 if (startInfo.hStdOutput == JIM_BAD_FD) {
1532 goto end;
1535 if (errorId == JIM_BAD_FD) {
1537 * If handle was not set, errors should be sent to an infinitely
1538 * deep sink.
1541 startInfo.hStdError = CreateFile("NUL:", GENERIC_WRITE, 0,
1542 JimStdSecAttrs(), OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1543 } else {
1544 DuplicateHandle(hProcess, errorId, hProcess, &startInfo.hStdError,
1545 0, TRUE, DUPLICATE_SAME_ACCESS);
1547 if (startInfo.hStdError == JIM_BAD_FD) {
1548 goto end;
1551 if (!CreateProcess(NULL, (char *)Jim_String(cmdLineObj), NULL, NULL, TRUE,
1552 0, env, NULL, &startInfo, &procInfo)) {
1553 goto end;
1557 * "When an application spawns a process repeatedly, a new thread
1558 * instance will be created for each process but the previous
1559 * instances may not be cleaned up. This results in a significant
1560 * virtual memory loss each time the process is spawned. If there
1561 * is a WaitForInputIdle() call between CreateProcess() and
1562 * CloseHandle(), the problem does not occur." PSS ID Number: Q124121
1565 WaitForInputIdle(procInfo.hProcess, 5000);
1566 CloseHandle(procInfo.hThread);
1568 pid = procInfo.hProcess;
1570 end:
1571 Jim_FreeNewObj(interp, cmdLineObj);
1572 if (startInfo.hStdInput != JIM_BAD_FD) {
1573 CloseHandle(startInfo.hStdInput);
1575 if (startInfo.hStdOutput != JIM_BAD_FD) {
1576 CloseHandle(startInfo.hStdOutput);
1578 if (startInfo.hStdError != JIM_BAD_FD) {
1579 CloseHandle(startInfo.hStdError);
1581 return pid;
1583 #else
1584 /* Unix-specific implementation */
1585 static int JimOpenForWrite(const char *filename, int append)
1587 return open(filename, O_WRONLY | O_CREAT | (append ? O_APPEND : O_TRUNC), 0666);
1590 static int JimRewindFd(int fd)
1592 return lseek(fd, 0L, SEEK_SET);
1595 static int JimCreateTemp(Jim_Interp *interp, const char *contents)
1597 char inName[] = "/tmp/tcl.tmp.XXXXXX";
1599 int fd = mkstemp(inName);
1600 if (fd == JIM_BAD_FD) {
1601 Jim_SetResultErrno(interp, "couldn't create temp file");
1602 return -1;
1604 unlink(inName);
1605 if (contents) {
1606 int length = strlen(contents);
1607 if (write(fd, contents, length) != length) {
1608 Jim_SetResultErrno(interp, "couldn't write temp file");
1609 close(fd);
1610 return -1;
1612 lseek(fd, 0L, SEEK_SET);
1614 return fd;
1617 static char **JimSaveEnv(char **env)
1619 char **saveenv = Jim_GetEnviron();
1620 Jim_SetEnviron(env);
1621 return saveenv;
1624 static void JimRestoreEnv(char **env)
1626 JimFreeEnv(Jim_GetEnviron(), env);
1627 Jim_SetEnviron(env);
1629 #endif
1630 #endif