sqlite3: Add -Wall and fix a compiler warning
[jimtcl.git] / jim-exec.c
blob60084903b255e526df90884f8c1fc99a10445171
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)
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;
555 static FILE *JimGetAioFilehandle(Jim_Interp *interp, const char *name)
557 FILE *fh;
558 Jim_Obj *fhObj;
560 fhObj = Jim_NewStringObj(interp, name, -1);
561 Jim_IncrRefCount(fhObj);
562 fh = Jim_AioFilehandle(interp, fhObj);
563 Jim_DecrRefCount(interp, fhObj);
565 return fh;
569 *----------------------------------------------------------------------
571 * JimCreatePipeline --
573 * Given an argc/argv array, instantiate a pipeline of processes
574 * as described by the argv.
576 * Results:
577 * The return value is a count of the number of new processes
578 * created, or -1 if an error occurred while creating the pipeline.
579 * *pidArrayPtr is filled in with the address of a dynamically
580 * allocated array giving the ids of all of the processes. It
581 * is up to the caller to free this array when it isn't needed
582 * anymore. If inPipePtr is non-NULL, *inPipePtr is filled in
583 * with the file id for the input pipe for the pipeline (if any):
584 * the caller must eventually close this file. If outPipePtr
585 * isn't NULL, then *outPipePtr is filled in with the file id
586 * for the output pipe from the pipeline: the caller must close
587 * this file. If errFilePtr isn't NULL, then *errFilePtr is filled
588 * with a file id that may be used to read error output after the
589 * pipeline completes.
591 * Side effects:
592 * Processes and pipes are created.
594 *----------------------------------------------------------------------
596 static int
597 JimCreatePipeline(Jim_Interp *interp, int argc, Jim_Obj *const *argv, pidtype **pidArrayPtr,
598 fdtype *inPipePtr, fdtype *outPipePtr, fdtype *errFilePtr)
600 pidtype *pidPtr = NULL; /* Points to malloc-ed array holding all
601 * the pids of child processes. */
602 int numPids = 0; /* Actual number of processes that exist
603 * at *pidPtr right now. */
604 int cmdCount; /* Count of number of distinct commands
605 * found in argc/argv. */
606 const char *input = NULL; /* Describes input for pipeline, depending
607 * on "inputFile". NULL means take input
608 * from stdin/pipe. */
610 #define FILE_NAME 0 /* input/output: filename */
611 #define FILE_APPEND 1 /* output only: filename, append */
612 #define FILE_HANDLE 2 /* input/output: filehandle */
613 #define FILE_TEXT 3 /* input only: input is actual text */
615 int inputFile = FILE_NAME; /* 1 means input is name of input file.
616 * 2 means input is filehandle name.
617 * 0 means input holds actual
618 * text to be input to command. */
620 int outputFile = FILE_NAME; /* 0 means output is the name of output file.
621 * 1 means output is the name of output file, and append.
622 * 2 means output is filehandle name.
623 * All this is ignored if output is NULL
625 int errorFile = FILE_NAME; /* 0 means error is the name of error file.
626 * 1 means error is the name of error file, and append.
627 * 2 means error is filehandle name.
628 * All this is ignored if error is NULL
630 const char *output = NULL; /* Holds name of output file to pipe to,
631 * or NULL if output goes to stdout/pipe. */
632 const char *error = NULL; /* Holds name of stderr file to pipe to,
633 * or NULL if stderr goes to stderr/pipe. */
634 fdtype inputId = JIM_BAD_FD;
635 /* Readable file id input to current command in
636 * pipeline (could be file or pipe). JIM_BAD_FD
637 * means use stdin. */
638 fdtype outputId = JIM_BAD_FD;
639 /* Writable file id for output from current
640 * command in pipeline (could be file or pipe).
641 * JIM_BAD_FD means use stdout. */
642 fdtype errorId = JIM_BAD_FD;
643 /* Writable file id for all standard error
644 * output from all commands in pipeline. JIM_BAD_FD
645 * means use stderr. */
646 fdtype lastOutputId = JIM_BAD_FD;
647 /* Write file id for output from last command
648 * in pipeline (could be file or pipe).
649 * -1 means use stdout. */
650 fdtype pipeIds[2]; /* File ids for pipe that's being created. */
651 int firstArg, lastArg; /* Indexes of first and last arguments in
652 * current command. */
653 int lastBar;
654 int i;
655 pidtype pid;
656 char **save_environ;
657 struct WaitInfoTable *table = Jim_CmdPrivData(interp);
659 /* Holds the args which will be used to exec */
660 char **arg_array = Jim_Alloc(sizeof(*arg_array) * (argc + 1));
661 int arg_count = 0;
663 JimReapDetachedPids(table);
665 if (inPipePtr != NULL) {
666 *inPipePtr = JIM_BAD_FD;
668 if (outPipePtr != NULL) {
669 *outPipePtr = JIM_BAD_FD;
671 if (errFilePtr != NULL) {
672 *errFilePtr = JIM_BAD_FD;
674 pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
677 * First, scan through all the arguments to figure out the structure
678 * of the pipeline. Count the number of distinct processes (it's the
679 * number of "|" arguments). If there are "<", "<<", or ">" arguments
680 * then make note of input and output redirection and remove these
681 * arguments and the arguments that follow them.
683 cmdCount = 1;
684 lastBar = -1;
685 for (i = 0; i < argc; i++) {
686 const char *arg = Jim_String(argv[i]);
688 if (arg[0] == '<') {
689 inputFile = FILE_NAME;
690 input = arg + 1;
691 if (*input == '<') {
692 inputFile = FILE_TEXT;
693 input++;
695 else if (*input == '@') {
696 inputFile = FILE_HANDLE;
697 input++;
700 if (!*input && ++i < argc) {
701 input = Jim_String(argv[i]);
704 else if (arg[0] == '>') {
705 int dup_error = 0;
707 outputFile = FILE_NAME;
709 output = arg + 1;
710 if (*output == '>') {
711 outputFile = FILE_APPEND;
712 output++;
714 if (*output == '&') {
715 /* Redirect stderr too */
716 output++;
717 dup_error = 1;
719 if (*output == '@') {
720 outputFile = FILE_HANDLE;
721 output++;
723 if (!*output && ++i < argc) {
724 output = Jim_String(argv[i]);
726 if (dup_error) {
727 errorFile = outputFile;
728 error = output;
731 else if (arg[0] == '2' && arg[1] == '>') {
732 error = arg + 2;
733 errorFile = FILE_NAME;
735 if (*error == '@') {
736 errorFile = FILE_HANDLE;
737 error++;
739 else if (*error == '>') {
740 errorFile = FILE_APPEND;
741 error++;
743 if (!*error && ++i < argc) {
744 error = Jim_String(argv[i]);
747 else {
748 if (strcmp(arg, "|") == 0 || strcmp(arg, "|&") == 0) {
749 if (i == lastBar + 1 || i == argc - 1) {
750 Jim_SetResultString(interp, "illegal use of | or |& in command", -1);
751 goto badargs;
753 lastBar = i;
754 cmdCount++;
756 /* Either |, |& or a "normal" arg, so store it in the arg array */
757 arg_array[arg_count++] = (char *)arg;
758 continue;
761 if (i >= argc) {
762 Jim_SetResultFormatted(interp, "can't specify \"%s\" as last word in command", arg);
763 goto badargs;
767 if (arg_count == 0) {
768 Jim_SetResultString(interp, "didn't specify command to execute", -1);
769 badargs:
770 Jim_Free(arg_array);
771 return -1;
774 /* Must do this before vfork(), so do it now */
775 save_environ = JimSaveEnv(JimBuildEnv(interp));
778 * Set up the redirected input source for the pipeline, if
779 * so requested.
781 if (input != NULL) {
782 if (inputFile == FILE_TEXT) {
784 * Immediate data in command. Create temporary file and
785 * put data into file.
787 inputId = JimCreateTemp(interp, input);
788 if (inputId == JIM_BAD_FD) {
789 goto error;
792 else if (inputFile == FILE_HANDLE) {
793 /* Should be a file descriptor */
794 FILE *fh = JimGetAioFilehandle(interp, input);
796 if (fh == NULL) {
797 goto error;
799 inputId = JimDupFd(JimFileno(fh));
801 else {
803 * File redirection. Just open the file.
805 inputId = JimOpenForRead(input);
806 if (inputId == JIM_BAD_FD) {
807 Jim_SetResultFormatted(interp, "couldn't read file \"%s\": %s", input, JimStrError());
808 goto error;
812 else if (inPipePtr != NULL) {
813 if (JimPipe(pipeIds) != 0) {
814 Jim_SetResultErrno(interp, "couldn't create input pipe for command");
815 goto error;
817 inputId = pipeIds[0];
818 *inPipePtr = pipeIds[1];
819 pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
823 * Set up the redirected output sink for the pipeline from one
824 * of two places, if requested.
826 if (output != NULL) {
827 if (outputFile == FILE_HANDLE) {
828 FILE *fh = JimGetAioFilehandle(interp, output);
829 if (fh == NULL) {
830 goto error;
832 fflush(fh);
833 lastOutputId = JimDupFd(JimFileno(fh));
835 else {
837 * Output is to go to a file.
839 lastOutputId = JimOpenForWrite(output, outputFile == FILE_APPEND);
840 if (lastOutputId == JIM_BAD_FD) {
841 Jim_SetResultFormatted(interp, "couldn't write file \"%s\": %s", output, JimStrError());
842 goto error;
846 else if (outPipePtr != NULL) {
848 * Output is to go to a pipe.
850 if (JimPipe(pipeIds) != 0) {
851 Jim_SetResultErrno(interp, "couldn't create output pipe");
852 goto error;
854 lastOutputId = pipeIds[1];
855 *outPipePtr = pipeIds[0];
856 pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
858 /* If we are redirecting stderr with 2>filename or 2>@fileId, then we ignore errFilePtr */
859 if (error != NULL) {
860 if (errorFile == FILE_HANDLE) {
861 if (strcmp(error, "1") == 0) {
862 /* Special 2>@1 */
863 if (lastOutputId != JIM_BAD_FD) {
864 errorId = JimDupFd(lastOutputId);
866 else {
867 /* No redirection of stdout, so just use 2>@stdout */
868 error = "stdout";
871 if (errorId == JIM_BAD_FD) {
872 FILE *fh = JimGetAioFilehandle(interp, error);
873 if (fh == NULL) {
874 goto error;
876 fflush(fh);
877 errorId = JimDupFd(JimFileno(fh));
880 else {
882 * Output is to go to a file.
884 errorId = JimOpenForWrite(error, errorFile == FILE_APPEND);
885 if (errorId == JIM_BAD_FD) {
886 Jim_SetResultFormatted(interp, "couldn't write file \"%s\": %s", error, JimStrError());
887 goto error;
891 else if (errFilePtr != NULL) {
893 * Set up the standard error output sink for the pipeline, if
894 * requested. Use a temporary file which is opened, then deleted.
895 * Could potentially just use pipe, but if it filled up it could
896 * cause the pipeline to deadlock: we'd be waiting for processes
897 * to complete before reading stderr, and processes couldn't complete
898 * because stderr was backed up.
900 errorId = JimCreateTemp(interp, NULL);
901 if (errorId == JIM_BAD_FD) {
902 goto error;
904 *errFilePtr = JimDupFd(errorId);
908 * Scan through the argc array, forking off a process for each
909 * group of arguments between "|" arguments.
912 pidPtr = Jim_Alloc(cmdCount * sizeof(*pidPtr));
913 for (i = 0; i < numPids; i++) {
914 pidPtr[i] = JIM_BAD_PID;
916 for (firstArg = 0; firstArg < arg_count; numPids++, firstArg = lastArg + 1) {
917 int pipe_dup_err = 0;
918 fdtype origErrorId = errorId;
920 for (lastArg = firstArg; lastArg < arg_count; lastArg++) {
921 if (arg_array[lastArg][0] == '|') {
922 if (arg_array[lastArg][1] == '&') {
923 pipe_dup_err = 1;
925 break;
928 /* Replace | with NULL for execv() */
929 arg_array[lastArg] = NULL;
930 if (lastArg == arg_count) {
931 outputId = lastOutputId;
933 else {
934 if (JimPipe(pipeIds) != 0) {
935 Jim_SetResultErrno(interp, "couldn't create pipe");
936 goto error;
938 outputId = pipeIds[1];
941 /* Now fork the child */
943 #ifdef __MINGW32__
944 pid = JimStartWinProcess(interp, &arg_array[firstArg], save_environ ? save_environ[0] : NULL, inputId, outputId, errorId);
945 if (pid == JIM_BAD_PID) {
946 Jim_SetResultFormatted(interp, "couldn't exec \"%s\"", arg_array[firstArg]);
947 goto error;
949 #else
951 * Disable SIGPIPE signals: if they were allowed, this process
952 * might go away unexpectedly if children misbehave. This code
953 * can potentially interfere with other application code that
954 * expects to handle SIGPIPEs; what's really needed is an
955 * arbiter for signals to allow them to be "shared".
957 if (table->info == NULL) {
958 (void)signal(SIGPIPE, SIG_IGN);
961 /* Need to do this befor vfork() */
962 if (pipe_dup_err) {
963 errorId = outputId;
967 * Make a new process and enter it into the table if the fork
968 * is successful.
970 pid = vfork();
971 if (pid < 0) {
972 Jim_SetResultErrno(interp, "couldn't fork child process");
973 goto error;
975 if (pid == 0) {
976 /* Child */
978 if (inputId != -1) dup2(inputId, 0);
979 if (outputId != -1) dup2(outputId, 1);
980 if (errorId != -1) dup2(errorId, 2);
982 for (i = 3; (i <= outputId) || (i <= inputId) || (i <= errorId); i++) {
983 close(i);
986 execvp(arg_array[firstArg], &arg_array[firstArg]);
988 /* Need to prep an error message before vfork(), just in case */
989 fprintf(stderr, "couldn't exec \"%s\"", arg_array[firstArg]);
990 _exit(127);
992 #endif
994 /* parent */
997 * Enlarge the wait table if there isn't enough space for a new
998 * entry.
1000 if (table->used == table->size) {
1001 table->size += WAIT_TABLE_GROW_BY;
1002 table->info = Jim_Realloc(table->info, table->size * sizeof(*table->info));
1005 table->info[table->used].pid = pid;
1006 table->info[table->used].flags = 0;
1007 table->used++;
1009 pidPtr[numPids] = pid;
1011 /* Restore in case of pipe_dup_err */
1012 errorId = origErrorId;
1015 * Close off our copies of file descriptors that were set up for
1016 * this child, then set up the input for the next child.
1019 if (inputId != JIM_BAD_FD) {
1020 JimCloseFd(inputId);
1022 if (outputId != JIM_BAD_FD) {
1023 JimCloseFd(outputId);
1025 inputId = pipeIds[0];
1026 pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
1028 *pidArrayPtr = pidPtr;
1031 * All done. Cleanup open files lying around and then return.
1034 cleanup:
1035 if (inputId != JIM_BAD_FD) {
1036 JimCloseFd(inputId);
1038 if (lastOutputId != JIM_BAD_FD) {
1039 JimCloseFd(lastOutputId);
1041 if (errorId != JIM_BAD_FD) {
1042 JimCloseFd(errorId);
1044 Jim_Free(arg_array);
1046 JimRestoreEnv(save_environ);
1048 return numPids;
1051 * An error occurred. There could have been extra files open, such
1052 * as pipes between children. Clean them all up. Detach any child
1053 * processes that have been created.
1056 error:
1057 if ((inPipePtr != NULL) && (*inPipePtr != JIM_BAD_FD)) {
1058 JimCloseFd(*inPipePtr);
1059 *inPipePtr = JIM_BAD_FD;
1061 if ((outPipePtr != NULL) && (*outPipePtr != JIM_BAD_FD)) {
1062 JimCloseFd(*outPipePtr);
1063 *outPipePtr = JIM_BAD_FD;
1065 if ((errFilePtr != NULL) && (*errFilePtr != JIM_BAD_FD)) {
1066 JimCloseFd(*errFilePtr);
1067 *errFilePtr = JIM_BAD_FD;
1069 if (pipeIds[0] != JIM_BAD_FD) {
1070 JimCloseFd(pipeIds[0]);
1072 if (pipeIds[1] != JIM_BAD_FD) {
1073 JimCloseFd(pipeIds[1]);
1075 if (pidPtr != NULL) {
1076 for (i = 0; i < numPids; i++) {
1077 if (pidPtr[i] != JIM_BAD_PID) {
1078 JimDetachPids(interp, 1, &pidPtr[i]);
1081 Jim_Free(pidPtr);
1083 numPids = -1;
1084 goto cleanup;
1088 *----------------------------------------------------------------------
1090 * JimCleanupChildren --
1092 * This is a utility procedure used to wait for child processes
1093 * to exit, record information about abnormal exits, and then
1094 * collect any stderr output generated by them.
1096 * Results:
1097 * The return value is a standard Tcl result. If anything at
1098 * weird happened with the child processes, JIM_ERROR is returned
1099 * and a message is left in interp->result.
1101 * Side effects:
1102 * If the last character of interp->result is a newline, then it
1103 * is removed. File errorId gets closed, and pidPtr is freed
1104 * back to the storage allocator.
1106 *----------------------------------------------------------------------
1109 static int JimCleanupChildren(Jim_Interp *interp, int numPids, pidtype *pidPtr, fdtype errorId)
1111 struct WaitInfoTable *table = Jim_CmdPrivData(interp);
1112 int result = JIM_OK;
1113 int i;
1115 for (i = 0; i < numPids; i++) {
1116 int waitStatus = 0;
1117 if (JimWaitForProcess(table, pidPtr[i], &waitStatus) != JIM_BAD_PID) {
1118 if (JimCheckWaitStatus(interp, pidPtr[i], waitStatus) != JIM_OK) {
1119 result = JIM_ERR;
1123 Jim_Free(pidPtr);
1126 * Read the standard error file. If there's anything there,
1127 * then add the file's contents to the result
1128 * string.
1130 if (errorId != JIM_BAD_FD) {
1131 JimRewindFd(errorId);
1132 if (JimAppendStreamToString(interp, errorId, Jim_GetResult(interp)) != JIM_OK) {
1133 result = JIM_ERR;
1137 JimTrimTrailingNewline(interp);
1139 return result;
1142 int Jim_execInit(Jim_Interp *interp)
1144 if (Jim_PackageProvide(interp, "exec", "1.0", JIM_ERRMSG))
1145 return JIM_ERR;
1146 Jim_CreateCommand(interp, "exec", Jim_ExecCmd, JimAllocWaitInfoTable(), JimFreeWaitInfoTable);
1147 return JIM_OK;
1150 #if defined(__MINGW32__)
1151 /* Windows-specific (mingw) implementation */
1153 static SECURITY_ATTRIBUTES *JimStdSecAttrs(void)
1155 static SECURITY_ATTRIBUTES secAtts;
1157 secAtts.nLength = sizeof(SECURITY_ATTRIBUTES);
1158 secAtts.lpSecurityDescriptor = NULL;
1159 secAtts.bInheritHandle = TRUE;
1160 return &secAtts;
1163 static int JimErrno(void)
1165 switch (GetLastError()) {
1166 case ERROR_FILE_NOT_FOUND: return ENOENT;
1167 case ERROR_PATH_NOT_FOUND: return ENOENT;
1168 case ERROR_TOO_MANY_OPEN_FILES: return EMFILE;
1169 case ERROR_ACCESS_DENIED: return EACCES;
1170 case ERROR_INVALID_HANDLE: return EBADF;
1171 case ERROR_BAD_ENVIRONMENT: return E2BIG;
1172 case ERROR_BAD_FORMAT: return ENOEXEC;
1173 case ERROR_INVALID_ACCESS: return EACCES;
1174 case ERROR_INVALID_DRIVE: return ENOENT;
1175 case ERROR_CURRENT_DIRECTORY: return EACCES;
1176 case ERROR_NOT_SAME_DEVICE: return EXDEV;
1177 case ERROR_NO_MORE_FILES: return ENOENT;
1178 case ERROR_WRITE_PROTECT: return EROFS;
1179 case ERROR_BAD_UNIT: return ENXIO;
1180 case ERROR_NOT_READY: return EBUSY;
1181 case ERROR_BAD_COMMAND: return EIO;
1182 case ERROR_CRC: return EIO;
1183 case ERROR_BAD_LENGTH: return EIO;
1184 case ERROR_SEEK: return EIO;
1185 case ERROR_WRITE_FAULT: return EIO;
1186 case ERROR_READ_FAULT: return EIO;
1187 case ERROR_GEN_FAILURE: return EIO;
1188 case ERROR_SHARING_VIOLATION: return EACCES;
1189 case ERROR_LOCK_VIOLATION: return EACCES;
1190 case ERROR_SHARING_BUFFER_EXCEEDED: return ENFILE;
1191 case ERROR_HANDLE_DISK_FULL: return ENOSPC;
1192 case ERROR_NOT_SUPPORTED: return ENODEV;
1193 case ERROR_REM_NOT_LIST: return EBUSY;
1194 case ERROR_DUP_NAME: return EEXIST;
1195 case ERROR_BAD_NETPATH: return ENOENT;
1196 case ERROR_NETWORK_BUSY: return EBUSY;
1197 case ERROR_DEV_NOT_EXIST: return ENODEV;
1198 case ERROR_TOO_MANY_CMDS: return EAGAIN;
1199 case ERROR_ADAP_HDW_ERR: return EIO;
1200 case ERROR_BAD_NET_RESP: return EIO;
1201 case ERROR_UNEXP_NET_ERR: return EIO;
1202 case ERROR_NETNAME_DELETED: return ENOENT;
1203 case ERROR_NETWORK_ACCESS_DENIED: return EACCES;
1204 case ERROR_BAD_DEV_TYPE: return ENODEV;
1205 case ERROR_BAD_NET_NAME: return ENOENT;
1206 case ERROR_TOO_MANY_NAMES: return ENFILE;
1207 case ERROR_TOO_MANY_SESS: return EIO;
1208 case ERROR_SHARING_PAUSED: return EAGAIN;
1209 case ERROR_REDIR_PAUSED: return EAGAIN;
1210 case ERROR_FILE_EXISTS: return EEXIST;
1211 case ERROR_CANNOT_MAKE: return ENOSPC;
1212 case ERROR_OUT_OF_STRUCTURES: return ENFILE;
1213 case ERROR_ALREADY_ASSIGNED: return EEXIST;
1214 case ERROR_INVALID_PASSWORD: return EPERM;
1215 case ERROR_NET_WRITE_FAULT: return EIO;
1216 case ERROR_NO_PROC_SLOTS: return EAGAIN;
1217 case ERROR_DISK_CHANGE: return EXDEV;
1218 case ERROR_BROKEN_PIPE: return EPIPE;
1219 case ERROR_OPEN_FAILED: return ENOENT;
1220 case ERROR_DISK_FULL: return ENOSPC;
1221 case ERROR_NO_MORE_SEARCH_HANDLES: return EMFILE;
1222 case ERROR_INVALID_TARGET_HANDLE: return EBADF;
1223 case ERROR_INVALID_NAME: return ENOENT;
1224 case ERROR_PROC_NOT_FOUND: return ESRCH;
1225 case ERROR_WAIT_NO_CHILDREN: return ECHILD;
1226 case ERROR_CHILD_NOT_COMPLETE: return ECHILD;
1227 case ERROR_DIRECT_ACCESS_HANDLE: return EBADF;
1228 case ERROR_SEEK_ON_DEVICE: return ESPIPE;
1229 case ERROR_BUSY_DRIVE: return EAGAIN;
1230 case ERROR_DIR_NOT_EMPTY: return EEXIST;
1231 case ERROR_NOT_LOCKED: return EACCES;
1232 case ERROR_BAD_PATHNAME: return ENOENT;
1233 case ERROR_LOCK_FAILED: return EACCES;
1234 case ERROR_ALREADY_EXISTS: return EEXIST;
1235 case ERROR_FILENAME_EXCED_RANGE: return ENAMETOOLONG;
1236 case ERROR_BAD_PIPE: return EPIPE;
1237 case ERROR_PIPE_BUSY: return EAGAIN;
1238 case ERROR_PIPE_NOT_CONNECTED: return EPIPE;
1239 case ERROR_DIRECTORY: return ENOTDIR;
1241 return EINVAL;
1244 static int JimPipe(fdtype pipefd[2])
1246 if (CreatePipe(&pipefd[0], &pipefd[1], NULL, 0)) {
1247 return 0;
1249 return -1;
1252 static fdtype JimDupFd(fdtype infd)
1254 fdtype dupfd;
1255 pidtype pid = GetCurrentProcess();
1257 if (DuplicateHandle(pid, infd, pid, &dupfd, 0, TRUE, DUPLICATE_SAME_ACCESS)) {
1258 return dupfd;
1260 return JIM_BAD_FD;
1263 static int JimRewindFd(fdtype fd)
1265 return SetFilePointer(fd, 0, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER ? -1 : 0;
1268 #if 0
1269 static int JimReadFd(fdtype fd, char *buffer, size_t len)
1271 DWORD num;
1273 if (ReadFile(fd, buffer, len, &num, NULL)) {
1274 return num;
1276 if (GetLastError() == ERROR_HANDLE_EOF || GetLastError() == ERROR_BROKEN_PIPE) {
1277 return 0;
1279 return -1;
1281 #endif
1283 static FILE *JimFdOpenForRead(fdtype fd)
1285 return _fdopen(_open_osfhandle((int)fd, _O_RDONLY | _O_TEXT), "r");
1288 static fdtype JimFileno(FILE *fh)
1290 return (fdtype)_get_osfhandle(_fileno(fh));
1293 static fdtype JimOpenForRead(const char *filename)
1295 return CreateFile(filename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
1296 JimStdSecAttrs(), OPEN_EXISTING, 0, NULL);
1299 static fdtype JimOpenForWrite(const char *filename, int append)
1301 return CreateFile(filename, append ? FILE_APPEND_DATA : GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
1302 JimStdSecAttrs(), append ? OPEN_ALWAYS : CREATE_ALWAYS, 0, (HANDLE) NULL);
1305 static FILE *JimFdOpenForWrite(fdtype fd)
1307 return _fdopen(_open_osfhandle((int)fd, _O_TEXT), "w");
1310 static pidtype JimWaitPid(pidtype pid, int *status, int nohang)
1312 DWORD ret = WaitForSingleObject(pid, nohang ? 0 : INFINITE);
1313 if (ret == WAIT_TIMEOUT || ret == WAIT_FAILED) {
1314 /* WAIT_TIMEOUT can only happend with WNOHANG */
1315 return JIM_BAD_PID;
1317 GetExitCodeProcess(pid, &ret);
1318 *status = ret;
1319 CloseHandle(pid);
1320 return pid;
1323 static HANDLE JimCreateTemp(Jim_Interp *interp, const char *contents)
1325 char name[MAX_PATH];
1326 HANDLE handle;
1328 if (!GetTempPath(MAX_PATH, name) || !GetTempFileName(name, "JIM", 0, name)) {
1329 return JIM_BAD_FD;
1332 handle = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, JimStdSecAttrs(),
1333 CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE,
1334 NULL);
1336 if (handle == INVALID_HANDLE_VALUE) {
1337 goto error;
1340 if (contents != NULL) {
1341 /* Use fdopen() to get automatic text-mode translation */
1342 FILE *fh = JimFdOpenForWrite(JimDupFd(handle));
1343 if (fh == NULL) {
1344 goto error;
1347 if (fwrite(contents, strlen(contents), 1, fh) != 1) {
1348 fclose(fh);
1349 goto error;
1351 fseek(fh, 0, SEEK_SET);
1352 fclose(fh);
1354 return handle;
1356 error:
1357 Jim_SetResultErrno(interp, "failed to create temp file");
1358 CloseHandle(handle);
1359 DeleteFile(name);
1360 return JIM_BAD_FD;
1363 static int
1364 JimWinFindExecutable(const char *originalName, char fullPath[MAX_PATH])
1366 int i;
1367 static char extensions[][5] = {".exe", "", ".bat"};
1369 for (i = 0; i < (int) (sizeof(extensions) / sizeof(extensions[0])); i++) {
1370 lstrcpyn(fullPath, originalName, MAX_PATH - 5);
1371 lstrcat(fullPath, extensions[i]);
1373 if (SearchPath(NULL, fullPath, NULL, MAX_PATH, fullPath, NULL) == 0) {
1374 continue;
1376 if (GetFileAttributes(fullPath) & FILE_ATTRIBUTE_DIRECTORY) {
1377 continue;
1379 return 0;
1382 return -1;
1385 static char **JimSaveEnv(char **env)
1387 return env;
1390 static void JimRestoreEnv(char **env)
1392 JimFreeEnv(env, NULL);
1395 static Jim_Obj *
1396 JimWinBuildCommandLine(Jim_Interp *interp, char **argv)
1398 char *start, *special;
1399 int quote, i;
1401 Jim_Obj *strObj = Jim_NewStringObj(interp, "", 0);
1403 for (i = 0; argv[i]; i++) {
1404 if (i > 0) {
1405 Jim_AppendString(interp, strObj, " ", 1);
1408 if (argv[i][0] == '\0') {
1409 quote = 1;
1411 else {
1412 quote = 0;
1413 for (start = argv[i]; *start != '\0'; start++) {
1414 if (isspace(UCHAR(*start))) {
1415 quote = 1;
1416 break;
1420 if (quote) {
1421 Jim_AppendString(interp, strObj, "\"" , 1);
1424 start = argv[i];
1425 for (special = argv[i]; ; ) {
1426 if ((*special == '\\') && (special[1] == '\\' ||
1427 special[1] == '"' || (quote && special[1] == '\0'))) {
1428 Jim_AppendString(interp, strObj, start, special - start);
1429 start = special;
1430 while (1) {
1431 special++;
1432 if (*special == '"' || (quote && *special == '\0')) {
1434 * N backslashes followed a quote -> insert
1435 * N * 2 + 1 backslashes then a quote.
1438 Jim_AppendString(interp, strObj, start, special - start);
1439 break;
1441 if (*special != '\\') {
1442 break;
1445 Jim_AppendString(interp, strObj, start, special - start);
1446 start = special;
1448 if (*special == '"') {
1449 if (special == start) {
1450 Jim_AppendString(interp, strObj, "\"", 1);
1452 else {
1453 Jim_AppendString(interp, strObj, start, special - start);
1455 Jim_AppendString(interp, strObj, "\\\"", 2);
1456 start = special + 1;
1458 if (*special == '\0') {
1459 break;
1461 special++;
1463 Jim_AppendString(interp, strObj, start, special - start);
1464 if (quote) {
1465 Jim_AppendString(interp, strObj, "\"", 1);
1468 return strObj;
1471 static pidtype
1472 JimStartWinProcess(Jim_Interp *interp, char **argv, char *env, fdtype inputId, fdtype outputId, fdtype errorId)
1474 STARTUPINFO startInfo;
1475 PROCESS_INFORMATION procInfo;
1476 HANDLE hProcess, h;
1477 char execPath[MAX_PATH];
1478 char *originalName;
1479 pidtype pid = JIM_BAD_PID;
1480 Jim_Obj *cmdLineObj;
1482 if (JimWinFindExecutable(argv[0], execPath) < 0) {
1483 return JIM_BAD_PID;
1485 originalName = argv[0];
1486 argv[0] = execPath;
1488 hProcess = GetCurrentProcess();
1489 cmdLineObj = JimWinBuildCommandLine(interp, argv);
1492 * STARTF_USESTDHANDLES must be used to pass handles to child process.
1493 * Using SetStdHandle() and/or dup2() only works when a console mode
1494 * parent process is spawning an attached console mode child process.
1497 ZeroMemory(&startInfo, sizeof(startInfo));
1498 startInfo.cb = sizeof(startInfo);
1499 startInfo.dwFlags = STARTF_USESTDHANDLES;
1500 startInfo.hStdInput = INVALID_HANDLE_VALUE;
1501 startInfo.hStdOutput= INVALID_HANDLE_VALUE;
1502 startInfo.hStdError = INVALID_HANDLE_VALUE;
1505 * Duplicate all the handles which will be passed off as stdin, stdout
1506 * and stderr of the child process. The duplicate handles are set to
1507 * be inheritable, so the child process can use them.
1509 if (inputId == JIM_BAD_FD) {
1510 if (CreatePipe(&startInfo.hStdInput, &h, JimStdSecAttrs(), 0) != FALSE) {
1511 CloseHandle(h);
1513 } else {
1514 DuplicateHandle(hProcess, inputId, hProcess, &startInfo.hStdInput,
1515 0, TRUE, DUPLICATE_SAME_ACCESS);
1517 if (startInfo.hStdInput == JIM_BAD_FD) {
1518 goto end;
1521 if (outputId == JIM_BAD_FD) {
1522 startInfo.hStdOutput = CreateFile("NUL:", GENERIC_WRITE, 0,
1523 JimStdSecAttrs(), OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1524 } else {
1525 DuplicateHandle(hProcess, outputId, hProcess, &startInfo.hStdOutput,
1526 0, TRUE, DUPLICATE_SAME_ACCESS);
1528 if (startInfo.hStdOutput == JIM_BAD_FD) {
1529 goto end;
1532 if (errorId == JIM_BAD_FD) {
1534 * If handle was not set, errors should be sent to an infinitely
1535 * deep sink.
1538 startInfo.hStdError = CreateFile("NUL:", GENERIC_WRITE, 0,
1539 JimStdSecAttrs(), OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1540 } else {
1541 DuplicateHandle(hProcess, errorId, hProcess, &startInfo.hStdError,
1542 0, TRUE, DUPLICATE_SAME_ACCESS);
1544 if (startInfo.hStdError == JIM_BAD_FD) {
1545 goto end;
1548 if (!CreateProcess(NULL, (char *)Jim_String(cmdLineObj), NULL, NULL, TRUE,
1549 0, env, NULL, &startInfo, &procInfo)) {
1550 goto end;
1554 * "When an application spawns a process repeatedly, a new thread
1555 * instance will be created for each process but the previous
1556 * instances may not be cleaned up. This results in a significant
1557 * virtual memory loss each time the process is spawned. If there
1558 * is a WaitForInputIdle() call between CreateProcess() and
1559 * CloseHandle(), the problem does not occur." PSS ID Number: Q124121
1562 WaitForInputIdle(procInfo.hProcess, 5000);
1563 CloseHandle(procInfo.hThread);
1565 pid = procInfo.hProcess;
1567 end:
1568 Jim_FreeNewObj(interp, cmdLineObj);
1569 if (startInfo.hStdInput != JIM_BAD_FD) {
1570 CloseHandle(startInfo.hStdInput);
1572 if (startInfo.hStdOutput != JIM_BAD_FD) {
1573 CloseHandle(startInfo.hStdOutput);
1575 if (startInfo.hStdError != JIM_BAD_FD) {
1576 CloseHandle(startInfo.hStdError);
1578 return pid;
1580 #else
1581 /* Unix-specific implementation */
1582 static int JimOpenForWrite(const char *filename, int append)
1584 return open(filename, O_WRONLY | O_CREAT | (append ? O_APPEND : O_TRUNC), 0666);
1587 static int JimRewindFd(int fd)
1589 return lseek(fd, 0L, SEEK_SET);
1592 static int JimCreateTemp(Jim_Interp *interp, const char *contents)
1594 char inName[] = "/tmp/tcl.tmp.XXXXXX";
1596 int fd = mkstemp(inName);
1597 if (fd == JIM_BAD_FD) {
1598 Jim_SetResultErrno(interp, "couldn't create temp file");
1599 return -1;
1601 unlink(inName);
1602 if (contents) {
1603 int length = strlen(contents);
1604 if (write(fd, contents, length) != length) {
1605 Jim_SetResultErrno(interp, "couldn't write temp file");
1606 close(fd);
1607 return -1;
1609 lseek(fd, 0L, SEEK_SET);
1611 return fd;
1614 static char **JimSaveEnv(char **env)
1616 char **saveenv = Jim_GetEnviron();
1617 Jim_SetEnviron(env);
1618 return saveenv;
1621 static void JimRestoreEnv(char **env)
1623 JimFreeEnv(Jim_GetEnviron(), env);
1624 Jim_SetEnviron(env);
1626 #endif
1627 #endif