Avoid static analysis warning: https://msdn.microsoft.com/en-us/library/17b585f0...
[jimtcl.git] / jim-exec.c
blobf64f5cceb81ee1885fa00cfdf5bf1862d3d54d94
1 /*
2 * (c) 2008 Steve Bennett <steveb@workware.net.au>
4 * Implements the exec command for Jim
6 * Based on code originally from Tcl 6.7 by John Ousterhout.
7 * From that code:
9 * The Tcl_Fork and Tcl_WaitPids procedures are based on code
10 * contributed by Karl Lehenbauer, Mark Diekhans and Peter
11 * da Silva.
13 * Copyright 1987-1991 Regents of the University of California
14 * Permission to use, copy, modify, and distribute this
15 * software and its documentation for any purpose and without
16 * fee is hereby granted, provided that the above copyright
17 * notice appear in all copies. The University of California
18 * makes no representations about the suitability of this
19 * software for any purpose. It is provided "as is" without
20 * express or implied warranty.
23 #include <string.h>
24 #include <ctype.h>
26 #include "jimautoconf.h"
27 #include <jim.h>
29 #if (!defined(HAVE_VFORK) || !defined(HAVE_WAITPID)) && !defined(__MINGW32__)
30 /* Poor man's implementation of exec with system()
31 * The system() call *may* do command line redirection, etc.
32 * The standard output is not available.
33 * Can't redirect filehandles.
35 static int Jim_ExecCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
37 Jim_Obj *cmdlineObj = Jim_NewEmptyStringObj(interp);
38 int i, j;
39 int rc;
41 /* Create a quoted command line */
42 for (i = 1; i < argc; i++) {
43 int len;
44 const char *arg = Jim_GetString(argv[i], &len);
46 if (i > 1) {
47 Jim_AppendString(interp, cmdlineObj, " ", 1);
49 if (strpbrk(arg, "\\\" ") == NULL) {
50 /* No quoting required */
51 Jim_AppendString(interp, cmdlineObj, arg, len);
52 continue;
55 Jim_AppendString(interp, cmdlineObj, "\"", 1);
56 for (j = 0; j < len; j++) {
57 if (arg[j] == '\\' || arg[j] == '"') {
58 Jim_AppendString(interp, cmdlineObj, "\\", 1);
60 Jim_AppendString(interp, cmdlineObj, &arg[j], 1);
62 Jim_AppendString(interp, cmdlineObj, "\"", 1);
64 rc = system(Jim_String(cmdlineObj));
66 Jim_FreeNewObj(interp, cmdlineObj);
68 if (rc) {
69 Jim_Obj *errorCode = Jim_NewListObj(interp, NULL, 0);
70 Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, "CHILDSTATUS", -1));
71 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, 0));
72 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, rc));
73 Jim_SetGlobalVariableStr(interp, "errorCode", errorCode);
74 return JIM_ERR;
77 return JIM_OK;
80 int Jim_execInit(Jim_Interp *interp)
82 if (Jim_PackageProvide(interp, "exec", "1.0", JIM_ERRMSG))
83 return JIM_ERR;
85 Jim_CreateCommand(interp, "exec", Jim_ExecCmd, NULL, NULL);
86 return JIM_OK;
88 #else
89 /* Full exec implementation for unix and mingw */
91 #include <errno.h>
92 #include <signal.h>
94 #if defined(__MINGW32__)
95 /* XXX: Should we use this implementation for cygwin too? msvc? */
96 #ifndef STRICT
97 #define STRICT
98 #endif
99 #define WIN32_LEAN_AND_MEAN
100 #include <windows.h>
101 #include <fcntl.h>
103 typedef HANDLE fdtype;
104 typedef HANDLE pidtype;
105 #define JIM_BAD_FD INVALID_HANDLE_VALUE
106 #define JIM_BAD_PID INVALID_HANDLE_VALUE
107 #define JimCloseFd CloseHandle
109 #define WIFEXITED(STATUS) 1
110 #define WEXITSTATUS(STATUS) (STATUS)
111 #define WIFSIGNALED(STATUS) 0
112 #define WTERMSIG(STATUS) 0
113 #define WNOHANG 1
115 static fdtype JimFileno(FILE *fh);
116 static pidtype JimWaitPid(pidtype pid, int *status, int nohang);
117 static fdtype JimDupFd(fdtype infd);
118 static fdtype JimOpenForRead(const char *filename);
119 static FILE *JimFdOpenForRead(fdtype fd);
120 static int JimPipe(fdtype pipefd[2]);
121 static pidtype JimStartWinProcess(Jim_Interp *interp, char **argv, char *env,
122 fdtype inputId, fdtype outputId, fdtype errorId);
123 static int JimErrno(void);
124 #else
125 #include "jim-signal.h"
126 #include <unistd.h>
127 #include <fcntl.h>
128 #include <sys/wait.h>
129 #include <sys/stat.h>
131 typedef int fdtype;
132 typedef int pidtype;
133 #define JimPipe pipe
134 #define JimErrno() errno
135 #define JIM_BAD_FD -1
136 #define JIM_BAD_PID -1
137 #define JimFileno fileno
138 #define JimReadFd read
139 #define JimCloseFd close
140 #define JimWaitPid waitpid
141 #define JimDupFd dup
142 #define JimFdOpenForRead(FD) fdopen((FD), "r")
143 #define JimOpenForRead(NAME) open((NAME), O_RDONLY, 0)
145 #ifndef HAVE_EXECVPE
146 #define execvpe(ARG0, ARGV, ENV) execvp(ARG0, ARGV)
147 #endif
148 #endif
150 static const char *JimStrError(void);
151 static char **JimSaveEnv(char **env);
152 static void JimRestoreEnv(char **env);
153 static int JimCreatePipeline(Jim_Interp *interp, int argc, Jim_Obj *const *argv,
154 pidtype **pidArrayPtr, fdtype *inPipePtr, fdtype *outPipePtr, fdtype *errFilePtr);
155 static void JimDetachPids(Jim_Interp *interp, int numPids, const pidtype *pidPtr);
156 static int JimCleanupChildren(Jim_Interp *interp, int numPids, pidtype *pidPtr, Jim_Obj *errStrObj);
157 static fdtype JimCreateTemp(Jim_Interp *interp, const char *contents, int len);
158 static fdtype JimOpenForWrite(const char *filename, int append);
159 static int JimRewindFd(fdtype fd);
161 static void Jim_SetResultErrno(Jim_Interp *interp, const char *msg)
163 Jim_SetResultFormatted(interp, "%s: %s", msg, JimStrError());
166 static const char *JimStrError(void)
168 return strerror(JimErrno());
172 * If the last character of 'objPtr' is a newline, then remove
173 * the newline character.
175 static void Jim_RemoveTrailingNewline(Jim_Obj *objPtr)
177 int len;
178 const char *s = Jim_GetString(objPtr, &len);
180 if (len > 0 && s[len - 1] == '\n') {
181 objPtr->length--;
182 objPtr->bytes[objPtr->length] = '\0';
187 * Read from 'fd', append the data to strObj and close 'fd'.
188 * Returns 1 if data was added, 0 if not, or -1 on error.
190 static int JimAppendStreamToString(Jim_Interp *interp, fdtype fd, Jim_Obj *strObj)
192 char buf[256];
193 FILE *fh = JimFdOpenForRead(fd);
194 int ret = 0;
196 if (fh == NULL) {
197 return -1;
200 while (1) {
201 int retval = fread(buf, 1, sizeof(buf), fh);
202 if (retval > 0) {
203 ret = 1;
204 Jim_AppendString(interp, strObj, buf, retval);
206 if (retval != sizeof(buf)) {
207 break;
210 fclose(fh);
211 return ret;
215 * Builds the environment array from $::env
217 * If $::env is not set, simply returns environ.
219 * Otherwise allocates the environ array from the contents of $::env
221 * If the exec fails, memory can be freed via JimFreeEnv()
223 static char **JimBuildEnv(Jim_Interp *interp)
225 int i;
226 int size;
227 int num;
228 int n;
229 char **envptr;
230 char *envdata;
232 Jim_Obj *objPtr = Jim_GetGlobalVariableStr(interp, "env", JIM_NONE);
234 if (!objPtr) {
235 return Jim_GetEnviron();
238 /* We build the array as a single block consisting of the pointers followed by
239 * the strings. This has the advantage of being easy to allocate/free and being
240 * compatible with both unix and windows
243 /* Calculate the required size */
244 num = Jim_ListLength(interp, objPtr);
245 if (num % 2) {
246 /* Silently drop the last element if not a valid dictionary */
247 num--;
249 /* We need one \0 and one equal sign for each element.
250 * A list has at least one space for each element except the first.
251 * We need one extra char for the extra null terminator and one for the equal sign.
253 size = Jim_Length(objPtr) + 2;
255 envptr = Jim_Alloc(sizeof(*envptr) * (num / 2 + 1) + size);
256 envdata = (char *)&envptr[num / 2 + 1];
258 n = 0;
259 for (i = 0; i < num; i += 2) {
260 const char *s1, *s2;
261 Jim_Obj *elemObj;
263 Jim_ListIndex(interp, objPtr, i, &elemObj, JIM_NONE);
264 s1 = Jim_String(elemObj);
265 Jim_ListIndex(interp, objPtr, i + 1, &elemObj, JIM_NONE);
266 s2 = Jim_String(elemObj);
268 envptr[n] = envdata;
269 envdata += sprintf(envdata, "%s=%s", s1, s2);
270 envdata++;
271 n++;
273 envptr[n] = NULL;
274 *envdata = 0;
276 return envptr;
280 * Frees the environment allocated by JimBuildEnv()
282 * Must pass original_environ.
284 static void JimFreeEnv(char **env, char **original_environ)
286 if (env != original_environ) {
287 Jim_Free(env);
291 #ifndef jim_ext_signal
292 /* Implement trivial Jim_SignalId() and Jim_SignalName(), just good enough for JimCheckWaitStatus() */
293 const char *Jim_SignalId(int sig)
295 static char buf[10];
296 snprintf(buf, sizeof(buf), "%d", sig);
297 return buf;
300 const char *Jim_SignalName(int sig)
302 return Jim_SignalId(sig);
304 #endif
307 * Create and store an appropriate value for the global variable $::errorCode
308 * Based on pid and waitStatus.
310 * Returns JIM_OK for a normal exit with code 0, otherwise returns JIM_ERR.
312 * Note that $::errorCode is left unchanged for a normal exit.
313 * Details of any abnormal exit is appended to the errStrObj, unless it is NULL.
315 static int JimCheckWaitStatus(Jim_Interp *interp, pidtype pid, int waitStatus, Jim_Obj *errStrObj)
317 Jim_Obj *errorCode;
319 if (WIFEXITED(waitStatus) && WEXITSTATUS(waitStatus) == 0) {
320 return JIM_OK;
322 errorCode = Jim_NewListObj(interp, NULL, 0);
324 if (WIFEXITED(waitStatus)) {
325 Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, "CHILDSTATUS", -1));
326 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, (long)pid));
327 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, WEXITSTATUS(waitStatus)));
329 else {
330 const char *type;
331 const char *action;
333 if (WIFSIGNALED(waitStatus)) {
334 type = "CHILDKILLED";
335 action = "killed";
337 else {
338 type = "CHILDSUSP";
339 action = "suspended";
342 Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, type, -1));
344 if (errStrObj) {
345 /* Append the message to 'errStrObj' with a newline.
346 * The last newline will be stripped later
348 Jim_AppendStrings(interp, errStrObj, "child ", action, " by signal ", Jim_SignalId(WTERMSIG(waitStatus)), "\n", NULL);
351 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, pid));
352 Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, Jim_SignalId(WTERMSIG(waitStatus)), -1));
353 Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, Jim_SignalName(WTERMSIG(waitStatus)), -1));
355 Jim_SetGlobalVariableStr(interp, "errorCode", errorCode);
357 return JIM_ERR;
361 * Data structures of the following type are used by JimFork and
362 * JimWaitPids to keep track of child processes.
365 struct WaitInfo
367 pidtype pid; /* Process id of child. */
368 int status; /* Status returned when child exited or suspended. */
369 int flags; /* Various flag bits; see below for definitions. */
372 struct WaitInfoTable {
373 struct WaitInfo *info; /* Table of outstanding processes */
374 int size; /* Size of the allocated table */
375 int used; /* Number of entries in use */
379 * Flag bits in WaitInfo structures:
381 * WI_DETACHED - Non-zero means no-one cares about the
382 * process anymore. Ignore it until it
383 * exits, then forget about it.
386 #define WI_DETACHED 2
388 #define WAIT_TABLE_GROW_BY 4
390 static void JimFreeWaitInfoTable(struct Jim_Interp *interp, void *privData)
392 struct WaitInfoTable *table = privData;
394 Jim_Free(table->info);
395 Jim_Free(table);
398 static struct WaitInfoTable *JimAllocWaitInfoTable(void)
400 struct WaitInfoTable *table = Jim_Alloc(sizeof(*table));
401 table->info = NULL;
402 table->size = table->used = 0;
404 return table;
408 * The main [exec] command
410 static int Jim_ExecCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
412 fdtype outputId; /* File id for output pipe. -1 means command overrode. */
413 fdtype errorId; /* File id for temporary file containing error output. */
414 pidtype *pidPtr;
415 int numPids, result;
416 int child_siginfo = 1;
417 Jim_Obj *childErrObj;
418 Jim_Obj *errStrObj;
421 * See if the command is to be run in the background; if so, create
422 * the command, detach it, and return.
424 if (argc > 1 && Jim_CompareStringImmediate(interp, argv[argc - 1], "&")) {
425 Jim_Obj *listObj;
426 int i;
428 argc--;
429 numPids = JimCreatePipeline(interp, argc - 1, argv + 1, &pidPtr, NULL, NULL, NULL);
430 if (numPids < 0) {
431 return JIM_ERR;
433 /* The return value is a list of the pids */
434 listObj = Jim_NewListObj(interp, NULL, 0);
435 for (i = 0; i < numPids; i++) {
436 Jim_ListAppendElement(interp, listObj, Jim_NewIntObj(interp, (long)pidPtr[i]));
438 Jim_SetResult(interp, listObj);
439 JimDetachPids(interp, numPids, pidPtr);
440 Jim_Free(pidPtr);
441 return JIM_OK;
445 * Create the command's pipeline.
447 numPids =
448 JimCreatePipeline(interp, argc - 1, argv + 1, &pidPtr, NULL, &outputId, &errorId);
450 if (numPids < 0) {
451 return JIM_ERR;
454 result = JIM_OK;
456 errStrObj = Jim_NewStringObj(interp, "", 0);
458 /* Read from the output pipe until EOF */
459 if (outputId != JIM_BAD_FD) {
460 if (JimAppendStreamToString(interp, outputId, errStrObj) < 0) {
461 result = JIM_ERR;
462 Jim_SetResultErrno(interp, "error reading from output pipe");
466 /* Now wait for children to finish. Any abnormal results are appended to childErrObj */
467 childErrObj = Jim_NewStringObj(interp, "", 0);
468 Jim_IncrRefCount(childErrObj);
470 if (JimCleanupChildren(interp, numPids, pidPtr, childErrObj) != JIM_OK) {
471 result = JIM_ERR;
475 * Read the child's error output (if any) and put it into the result.
477 * Note that unlike Tcl, the presence of stderr output does not cause
478 * exec to return an error.
480 if (errorId != JIM_BAD_FD) {
481 int ret;
482 JimRewindFd(errorId);
483 ret = JimAppendStreamToString(interp, errorId, errStrObj);
484 if (ret < 0) {
485 Jim_SetResultErrno(interp, "error reading from error pipe");
486 result = JIM_ERR;
488 else if (ret > 0) {
489 /* Got some error output, so discard the abnormal info string */
490 child_siginfo = 0;
494 if (child_siginfo) {
495 /* Append the child siginfo to the result */
496 Jim_AppendObj(interp, errStrObj, childErrObj);
498 Jim_DecrRefCount(interp, childErrObj);
500 /* Finally remove any trailing newline from the result */
501 Jim_RemoveTrailingNewline(errStrObj);
503 /* Set this as the result */
504 Jim_SetResult(interp, errStrObj);
506 return result;
509 static void JimReapDetachedPids(struct WaitInfoTable *table)
511 struct WaitInfo *waitPtr;
512 int count;
513 int dest;
515 if (!table) {
516 return;
519 waitPtr = table->info;
520 dest = 0;
521 for (count = table->used; count > 0; waitPtr++, count--) {
522 if (waitPtr->flags & WI_DETACHED) {
523 int status;
524 pidtype pid = JimWaitPid(waitPtr->pid, &status, WNOHANG);
525 if (pid == waitPtr->pid) {
526 /* Process has exited, so remove it from the table */
527 table->used--;
528 continue;
531 if (waitPtr != &table->info[dest]) {
532 table->info[dest] = *waitPtr;
534 dest++;
539 * Does waitpid() on the given pid, and then removes the
540 * entry from the wait table.
542 * Returns the pid if OK and updates *statusPtr with the status,
543 * or JIM_BAD_PID if the pid was not in the table.
545 static pidtype JimWaitForProcess(struct WaitInfoTable *table, pidtype pid, int *statusPtr)
547 int i;
549 /* Find it in the table */
550 for (i = 0; i < table->used; i++) {
551 if (pid == table->info[i].pid) {
552 /* wait for it */
553 JimWaitPid(pid, statusPtr, 0);
555 /* Remove it from the table */
556 if (i != table->used - 1) {
557 table->info[i] = table->info[table->used - 1];
559 table->used--;
560 return pid;
564 /* Not found */
565 return JIM_BAD_PID;
569 * Indicates that one or more child processes have been placed in
570 * background and are no longer cared about.
571 * These children can be cleaned up with JimReapDetachedPids().
573 static void JimDetachPids(Jim_Interp *interp, int numPids, const pidtype *pidPtr)
575 int j;
576 struct WaitInfoTable *table = Jim_CmdPrivData(interp);
578 for (j = 0; j < numPids; j++) {
579 /* Find it in the table */
580 int i;
581 for (i = 0; i < table->used; i++) {
582 if (pidPtr[j] == table->info[i].pid) {
583 table->info[i].flags |= WI_DETACHED;
584 break;
590 static FILE *JimGetAioFilehandle(Jim_Interp *interp, const char *name)
592 FILE *fh;
593 Jim_Obj *fhObj;
595 fhObj = Jim_NewStringObj(interp, name, -1);
596 Jim_IncrRefCount(fhObj);
597 fh = Jim_AioFilehandle(interp, fhObj);
598 Jim_DecrRefCount(interp, fhObj);
600 return fh;
604 *----------------------------------------------------------------------
606 * JimCreatePipeline --
608 * Given an argc/argv array, instantiate a pipeline of processes
609 * as described by the argv.
611 * Results:
612 * The return value is a count of the number of new processes
613 * created, or -1 if an error occurred while creating the pipeline.
614 * *pidArrayPtr is filled in with the address of a dynamically
615 * allocated array giving the ids of all of the processes. It
616 * is up to the caller to free this array when it isn't needed
617 * anymore. If inPipePtr is non-NULL, *inPipePtr is filled in
618 * with the file id for the input pipe for the pipeline (if any):
619 * the caller must eventually close this file. If outPipePtr
620 * isn't NULL, then *outPipePtr is filled in with the file id
621 * for the output pipe from the pipeline: the caller must close
622 * this file. If errFilePtr isn't NULL, then *errFilePtr is filled
623 * with a file id that may be used to read error output after the
624 * pipeline completes.
626 * Side effects:
627 * Processes and pipes are created.
629 *----------------------------------------------------------------------
631 static int
632 JimCreatePipeline(Jim_Interp *interp, int argc, Jim_Obj *const *argv, pidtype **pidArrayPtr,
633 fdtype *inPipePtr, fdtype *outPipePtr, fdtype *errFilePtr)
635 pidtype *pidPtr = NULL; /* Points to malloc-ed array holding all
636 * the pids of child processes. */
637 int numPids = 0; /* Actual number of processes that exist
638 * at *pidPtr right now. */
639 int cmdCount; /* Count of number of distinct commands
640 * found in argc/argv. */
641 const char *input = NULL; /* Describes input for pipeline, depending
642 * on "inputFile". NULL means take input
643 * from stdin/pipe. */
644 int input_len = 0; /* Length of input, if relevant */
646 #define FILE_NAME 0 /* input/output: filename */
647 #define FILE_APPEND 1 /* output only: filename, append */
648 #define FILE_HANDLE 2 /* input/output: filehandle */
649 #define FILE_TEXT 3 /* input only: input is actual text */
651 int inputFile = FILE_NAME; /* 1 means input is name of input file.
652 * 2 means input is filehandle name.
653 * 0 means input holds actual
654 * text to be input to command. */
656 int outputFile = FILE_NAME; /* 0 means output is the name of output file.
657 * 1 means output is the name of output file, and append.
658 * 2 means output is filehandle name.
659 * All this is ignored if output is NULL
661 int errorFile = FILE_NAME; /* 0 means error is the name of error file.
662 * 1 means error is the name of error file, and append.
663 * 2 means error is filehandle name.
664 * All this is ignored if error is NULL
666 const char *output = NULL; /* Holds name of output file to pipe to,
667 * or NULL if output goes to stdout/pipe. */
668 const char *error = NULL; /* Holds name of stderr file to pipe to,
669 * or NULL if stderr goes to stderr/pipe. */
670 fdtype inputId = JIM_BAD_FD;
671 /* Readable file id input to current command in
672 * pipeline (could be file or pipe). JIM_BAD_FD
673 * means use stdin. */
674 fdtype outputId = JIM_BAD_FD;
675 /* Writable file id for output from current
676 * command in pipeline (could be file or pipe).
677 * JIM_BAD_FD means use stdout. */
678 fdtype errorId = JIM_BAD_FD;
679 /* Writable file id for all standard error
680 * output from all commands in pipeline. JIM_BAD_FD
681 * means use stderr. */
682 fdtype lastOutputId = JIM_BAD_FD;
683 /* Write file id for output from last command
684 * in pipeline (could be file or pipe).
685 * -1 means use stdout. */
686 fdtype pipeIds[2]; /* File ids for pipe that's being created. */
687 int firstArg, lastArg; /* Indexes of first and last arguments in
688 * current command. */
689 int lastBar;
690 int i;
691 pidtype pid;
692 char **save_environ;
693 struct WaitInfoTable *table = Jim_CmdPrivData(interp);
695 /* Holds the args which will be used to exec */
696 char **arg_array = Jim_Alloc(sizeof(*arg_array) * (argc + 1));
697 int arg_count = 0;
699 JimReapDetachedPids(table);
701 if (inPipePtr != NULL) {
702 *inPipePtr = JIM_BAD_FD;
704 if (outPipePtr != NULL) {
705 *outPipePtr = JIM_BAD_FD;
707 if (errFilePtr != NULL) {
708 *errFilePtr = JIM_BAD_FD;
710 pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
713 * First, scan through all the arguments to figure out the structure
714 * of the pipeline. Count the number of distinct processes (it's the
715 * number of "|" arguments). If there are "<", "<<", or ">" arguments
716 * then make note of input and output redirection and remove these
717 * arguments and the arguments that follow them.
719 cmdCount = 1;
720 lastBar = -1;
721 for (i = 0; i < argc; i++) {
722 const char *arg = Jim_String(argv[i]);
724 if (arg[0] == '<') {
725 inputFile = FILE_NAME;
726 input = arg + 1;
727 if (*input == '<') {
728 inputFile = FILE_TEXT;
729 input_len = Jim_Length(argv[i]) - 2;
730 input++;
732 else if (*input == '@') {
733 inputFile = FILE_HANDLE;
734 input++;
737 if (!*input && ++i < argc) {
738 input = Jim_GetString(argv[i], &input_len);
741 else if (arg[0] == '>') {
742 int dup_error = 0;
744 outputFile = FILE_NAME;
746 output = arg + 1;
747 if (*output == '>') {
748 outputFile = FILE_APPEND;
749 output++;
751 if (*output == '&') {
752 /* Redirect stderr too */
753 output++;
754 dup_error = 1;
756 if (*output == '@') {
757 outputFile = FILE_HANDLE;
758 output++;
760 if (!*output && ++i < argc) {
761 output = Jim_String(argv[i]);
763 if (dup_error) {
764 errorFile = outputFile;
765 error = output;
768 else if (arg[0] == '2' && arg[1] == '>') {
769 error = arg + 2;
770 errorFile = FILE_NAME;
772 if (*error == '@') {
773 errorFile = FILE_HANDLE;
774 error++;
776 else if (*error == '>') {
777 errorFile = FILE_APPEND;
778 error++;
780 if (!*error && ++i < argc) {
781 error = Jim_String(argv[i]);
784 else {
785 if (strcmp(arg, "|") == 0 || strcmp(arg, "|&") == 0) {
786 if (i == lastBar + 1 || i == argc - 1) {
787 Jim_SetResultString(interp, "illegal use of | or |& in command", -1);
788 goto badargs;
790 lastBar = i;
791 cmdCount++;
793 /* Either |, |& or a "normal" arg, so store it in the arg array */
794 arg_array[arg_count++] = (char *)arg;
795 continue;
798 if (i >= argc) {
799 Jim_SetResultFormatted(interp, "can't specify \"%s\" as last word in command", arg);
800 goto badargs;
804 if (arg_count == 0) {
805 Jim_SetResultString(interp, "didn't specify command to execute", -1);
806 badargs:
807 Jim_Free(arg_array);
808 return -1;
811 /* Must do this before vfork(), so do it now */
812 save_environ = JimSaveEnv(JimBuildEnv(interp));
815 * Set up the redirected input source for the pipeline, if
816 * so requested.
818 if (input != NULL) {
819 if (inputFile == FILE_TEXT) {
821 * Immediate data in command. Create temporary file and
822 * put data into file.
824 inputId = JimCreateTemp(interp, input, input_len);
825 if (inputId == JIM_BAD_FD) {
826 goto error;
829 else if (inputFile == FILE_HANDLE) {
830 /* Should be a file descriptor */
831 FILE *fh = JimGetAioFilehandle(interp, input);
833 if (fh == NULL) {
834 goto error;
836 inputId = JimDupFd(JimFileno(fh));
838 else {
840 * File redirection. Just open the file.
842 inputId = JimOpenForRead(input);
843 if (inputId == JIM_BAD_FD) {
844 Jim_SetResultFormatted(interp, "couldn't read file \"%s\": %s", input, JimStrError());
845 goto error;
849 else if (inPipePtr != NULL) {
850 if (JimPipe(pipeIds) != 0) {
851 Jim_SetResultErrno(interp, "couldn't create input pipe for command");
852 goto error;
854 inputId = pipeIds[0];
855 *inPipePtr = pipeIds[1];
856 pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
860 * Set up the redirected output sink for the pipeline from one
861 * of two places, if requested.
863 if (output != NULL) {
864 if (outputFile == FILE_HANDLE) {
865 FILE *fh = JimGetAioFilehandle(interp, output);
866 if (fh == NULL) {
867 goto error;
869 fflush(fh);
870 lastOutputId = JimDupFd(JimFileno(fh));
872 else {
874 * Output is to go to a file.
876 lastOutputId = JimOpenForWrite(output, outputFile == FILE_APPEND);
877 if (lastOutputId == JIM_BAD_FD) {
878 Jim_SetResultFormatted(interp, "couldn't write file \"%s\": %s", output, JimStrError());
879 goto error;
883 else if (outPipePtr != NULL) {
885 * Output is to go to a pipe.
887 if (JimPipe(pipeIds) != 0) {
888 Jim_SetResultErrno(interp, "couldn't create output pipe");
889 goto error;
891 lastOutputId = pipeIds[1];
892 *outPipePtr = pipeIds[0];
893 pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
895 /* If we are redirecting stderr with 2>filename or 2>@fileId, then we ignore errFilePtr */
896 if (error != NULL) {
897 if (errorFile == FILE_HANDLE) {
898 if (strcmp(error, "1") == 0) {
899 /* Special 2>@1 */
900 if (lastOutputId != JIM_BAD_FD) {
901 errorId = JimDupFd(lastOutputId);
903 else {
904 /* No redirection of stdout, so just use 2>@stdout */
905 error = "stdout";
908 if (errorId == JIM_BAD_FD) {
909 FILE *fh = JimGetAioFilehandle(interp, error);
910 if (fh == NULL) {
911 goto error;
913 fflush(fh);
914 errorId = JimDupFd(JimFileno(fh));
917 else {
919 * Output is to go to a file.
921 errorId = JimOpenForWrite(error, errorFile == FILE_APPEND);
922 if (errorId == JIM_BAD_FD) {
923 Jim_SetResultFormatted(interp, "couldn't write file \"%s\": %s", error, JimStrError());
924 goto error;
928 else if (errFilePtr != NULL) {
930 * Set up the standard error output sink for the pipeline, if
931 * requested. Use a temporary file which is opened, then deleted.
932 * Could potentially just use pipe, but if it filled up it could
933 * cause the pipeline to deadlock: we'd be waiting for processes
934 * to complete before reading stderr, and processes couldn't complete
935 * because stderr was backed up.
937 errorId = JimCreateTemp(interp, NULL, 0);
938 if (errorId == JIM_BAD_FD) {
939 goto error;
941 *errFilePtr = JimDupFd(errorId);
945 * Scan through the argc array, forking off a process for each
946 * group of arguments between "|" arguments.
949 pidPtr = Jim_Alloc(cmdCount * sizeof(*pidPtr));
950 for (i = 0; i < numPids; i++) {
951 pidPtr[i] = JIM_BAD_PID;
953 for (firstArg = 0; firstArg < arg_count; numPids++, firstArg = lastArg + 1) {
954 int pipe_dup_err = 0;
955 fdtype origErrorId = errorId;
957 for (lastArg = firstArg; lastArg < arg_count; lastArg++) {
958 if (arg_array[lastArg][0] == '|') {
959 if (arg_array[lastArg][1] == '&') {
960 pipe_dup_err = 1;
962 break;
965 /* Replace | with NULL for execv() */
966 arg_array[lastArg] = NULL;
967 if (lastArg == arg_count) {
968 outputId = lastOutputId;
970 else {
971 if (JimPipe(pipeIds) != 0) {
972 Jim_SetResultErrno(interp, "couldn't create pipe");
973 goto error;
975 outputId = pipeIds[1];
978 /* Need to do this befor vfork() */
979 if (pipe_dup_err) {
980 errorId = outputId;
983 /* Now fork the child */
985 #ifdef __MINGW32__
986 pid = JimStartWinProcess(interp, &arg_array[firstArg], save_environ ? save_environ[0] : NULL, inputId, outputId, errorId);
987 if (pid == JIM_BAD_PID) {
988 Jim_SetResultFormatted(interp, "couldn't exec \"%s\"", arg_array[firstArg]);
989 goto error;
991 #else
993 * Make a new process and enter it into the table if the fork
994 * is successful.
996 pid = vfork();
997 if (pid < 0) {
998 Jim_SetResultErrno(interp, "couldn't fork child process");
999 goto error;
1001 if (pid == 0) {
1002 /* Child */
1004 if (inputId != -1) dup2(inputId, 0);
1005 if (outputId != -1) dup2(outputId, 1);
1006 if (errorId != -1) dup2(errorId, 2);
1008 for (i = 3; (i <= outputId) || (i <= inputId) || (i <= errorId); i++) {
1009 close(i);
1012 /* Restore SIGPIPE behaviour */
1013 (void)signal(SIGPIPE, SIG_DFL);
1015 execvpe(arg_array[firstArg], &arg_array[firstArg], Jim_GetEnviron());
1017 /* Need to prep an error message before vfork(), just in case */
1018 fprintf(stderr, "couldn't exec \"%s\"\n", arg_array[firstArg]);
1019 _exit(127);
1021 #endif
1023 /* parent */
1026 * Enlarge the wait table if there isn't enough space for a new
1027 * entry.
1029 if (table->used == table->size) {
1030 table->size += WAIT_TABLE_GROW_BY;
1031 table->info = Jim_Realloc(table->info, table->size * sizeof(*table->info));
1034 table->info[table->used].pid = pid;
1035 table->info[table->used].flags = 0;
1036 table->used++;
1038 pidPtr[numPids] = pid;
1040 /* Restore in case of pipe_dup_err */
1041 errorId = origErrorId;
1044 * Close off our copies of file descriptors that were set up for
1045 * this child, then set up the input for the next child.
1048 if (inputId != JIM_BAD_FD) {
1049 JimCloseFd(inputId);
1051 if (outputId != JIM_BAD_FD) {
1052 JimCloseFd(outputId);
1054 inputId = pipeIds[0];
1055 pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
1057 *pidArrayPtr = pidPtr;
1060 * All done. Cleanup open files lying around and then return.
1063 cleanup:
1064 if (inputId != JIM_BAD_FD) {
1065 JimCloseFd(inputId);
1067 if (lastOutputId != JIM_BAD_FD) {
1068 JimCloseFd(lastOutputId);
1070 if (errorId != JIM_BAD_FD) {
1071 JimCloseFd(errorId);
1073 Jim_Free(arg_array);
1075 JimRestoreEnv(save_environ);
1077 return numPids;
1080 * An error occurred. There could have been extra files open, such
1081 * as pipes between children. Clean them all up. Detach any child
1082 * processes that have been created.
1085 error:
1086 if ((inPipePtr != NULL) && (*inPipePtr != JIM_BAD_FD)) {
1087 JimCloseFd(*inPipePtr);
1088 *inPipePtr = JIM_BAD_FD;
1090 if ((outPipePtr != NULL) && (*outPipePtr != JIM_BAD_FD)) {
1091 JimCloseFd(*outPipePtr);
1092 *outPipePtr = JIM_BAD_FD;
1094 if ((errFilePtr != NULL) && (*errFilePtr != JIM_BAD_FD)) {
1095 JimCloseFd(*errFilePtr);
1096 *errFilePtr = JIM_BAD_FD;
1098 if (pipeIds[0] != JIM_BAD_FD) {
1099 JimCloseFd(pipeIds[0]);
1101 if (pipeIds[1] != JIM_BAD_FD) {
1102 JimCloseFd(pipeIds[1]);
1104 if (pidPtr != NULL) {
1105 for (i = 0; i < numPids; i++) {
1106 if (pidPtr[i] != JIM_BAD_PID) {
1107 JimDetachPids(interp, 1, &pidPtr[i]);
1110 Jim_Free(pidPtr);
1112 numPids = -1;
1113 goto cleanup;
1117 *----------------------------------------------------------------------
1119 * JimCleanupChildren --
1121 * This is a utility procedure used to wait for child processes
1122 * to exit, record information about abnormal exits.
1124 * Results:
1125 * The return value is a standard Tcl result. If anything at
1126 * weird happened with the child processes, JIM_ERR is returned
1127 * and a structured message is left in $::errorCode.
1128 * If errStrObj is not NULL, abnormal exit details are appended to this object.
1130 * Side effects:
1131 * pidPtr is freed
1133 *----------------------------------------------------------------------
1136 static int JimCleanupChildren(Jim_Interp *interp, int numPids, pidtype *pidPtr, Jim_Obj *errStrObj)
1138 struct WaitInfoTable *table = Jim_CmdPrivData(interp);
1139 int result = JIM_OK;
1140 int i;
1142 /* Now check the return status of each child */
1143 for (i = 0; i < numPids; i++) {
1144 int waitStatus = 0;
1145 if (JimWaitForProcess(table, pidPtr[i], &waitStatus) != JIM_BAD_PID) {
1146 if (JimCheckWaitStatus(interp, pidPtr[i], waitStatus, errStrObj) != JIM_OK) {
1147 result = JIM_ERR;
1151 Jim_Free(pidPtr);
1153 return result;
1156 int Jim_execInit(Jim_Interp *interp)
1158 if (Jim_PackageProvide(interp, "exec", "1.0", JIM_ERRMSG))
1159 return JIM_ERR;
1161 #ifdef SIGPIPE
1163 * Disable SIGPIPE signals: if they were allowed, this process
1164 * might go away unexpectedly if children misbehave. This code
1165 * can potentially interfere with other application code that
1166 * expects to handle SIGPIPEs.
1168 * By doing this in the init function, applications can override
1169 * this later. Note that child processes have SIGPIPE restored
1170 * to the default after vfork().
1172 (void)signal(SIGPIPE, SIG_IGN);
1173 #endif
1175 Jim_CreateCommand(interp, "exec", Jim_ExecCmd, JimAllocWaitInfoTable(), JimFreeWaitInfoTable);
1176 return JIM_OK;
1179 #if defined(__MINGW32__)
1180 /* Windows-specific (mingw) implementation */
1182 static SECURITY_ATTRIBUTES *JimStdSecAttrs(void)
1184 static SECURITY_ATTRIBUTES secAtts;
1186 secAtts.nLength = sizeof(SECURITY_ATTRIBUTES);
1187 secAtts.lpSecurityDescriptor = NULL;
1188 secAtts.bInheritHandle = TRUE;
1189 return &secAtts;
1192 static int JimErrno(void)
1194 switch (GetLastError()) {
1195 case ERROR_FILE_NOT_FOUND: return ENOENT;
1196 case ERROR_PATH_NOT_FOUND: return ENOENT;
1197 case ERROR_TOO_MANY_OPEN_FILES: return EMFILE;
1198 case ERROR_ACCESS_DENIED: return EACCES;
1199 case ERROR_INVALID_HANDLE: return EBADF;
1200 case ERROR_BAD_ENVIRONMENT: return E2BIG;
1201 case ERROR_BAD_FORMAT: return ENOEXEC;
1202 case ERROR_INVALID_ACCESS: return EACCES;
1203 case ERROR_INVALID_DRIVE: return ENOENT;
1204 case ERROR_CURRENT_DIRECTORY: return EACCES;
1205 case ERROR_NOT_SAME_DEVICE: return EXDEV;
1206 case ERROR_NO_MORE_FILES: return ENOENT;
1207 case ERROR_WRITE_PROTECT: return EROFS;
1208 case ERROR_BAD_UNIT: return ENXIO;
1209 case ERROR_NOT_READY: return EBUSY;
1210 case ERROR_BAD_COMMAND: return EIO;
1211 case ERROR_CRC: return EIO;
1212 case ERROR_BAD_LENGTH: return EIO;
1213 case ERROR_SEEK: return EIO;
1214 case ERROR_WRITE_FAULT: return EIO;
1215 case ERROR_READ_FAULT: return EIO;
1216 case ERROR_GEN_FAILURE: return EIO;
1217 case ERROR_SHARING_VIOLATION: return EACCES;
1218 case ERROR_LOCK_VIOLATION: return EACCES;
1219 case ERROR_SHARING_BUFFER_EXCEEDED: return ENFILE;
1220 case ERROR_HANDLE_DISK_FULL: return ENOSPC;
1221 case ERROR_NOT_SUPPORTED: return ENODEV;
1222 case ERROR_REM_NOT_LIST: return EBUSY;
1223 case ERROR_DUP_NAME: return EEXIST;
1224 case ERROR_BAD_NETPATH: return ENOENT;
1225 case ERROR_NETWORK_BUSY: return EBUSY;
1226 case ERROR_DEV_NOT_EXIST: return ENODEV;
1227 case ERROR_TOO_MANY_CMDS: return EAGAIN;
1228 case ERROR_ADAP_HDW_ERR: return EIO;
1229 case ERROR_BAD_NET_RESP: return EIO;
1230 case ERROR_UNEXP_NET_ERR: return EIO;
1231 case ERROR_NETNAME_DELETED: return ENOENT;
1232 case ERROR_NETWORK_ACCESS_DENIED: return EACCES;
1233 case ERROR_BAD_DEV_TYPE: return ENODEV;
1234 case ERROR_BAD_NET_NAME: return ENOENT;
1235 case ERROR_TOO_MANY_NAMES: return ENFILE;
1236 case ERROR_TOO_MANY_SESS: return EIO;
1237 case ERROR_SHARING_PAUSED: return EAGAIN;
1238 case ERROR_REDIR_PAUSED: return EAGAIN;
1239 case ERROR_FILE_EXISTS: return EEXIST;
1240 case ERROR_CANNOT_MAKE: return ENOSPC;
1241 case ERROR_OUT_OF_STRUCTURES: return ENFILE;
1242 case ERROR_ALREADY_ASSIGNED: return EEXIST;
1243 case ERROR_INVALID_PASSWORD: return EPERM;
1244 case ERROR_NET_WRITE_FAULT: return EIO;
1245 case ERROR_NO_PROC_SLOTS: return EAGAIN;
1246 case ERROR_DISK_CHANGE: return EXDEV;
1247 case ERROR_BROKEN_PIPE: return EPIPE;
1248 case ERROR_OPEN_FAILED: return ENOENT;
1249 case ERROR_DISK_FULL: return ENOSPC;
1250 case ERROR_NO_MORE_SEARCH_HANDLES: return EMFILE;
1251 case ERROR_INVALID_TARGET_HANDLE: return EBADF;
1252 case ERROR_INVALID_NAME: return ENOENT;
1253 case ERROR_PROC_NOT_FOUND: return ESRCH;
1254 case ERROR_WAIT_NO_CHILDREN: return ECHILD;
1255 case ERROR_CHILD_NOT_COMPLETE: return ECHILD;
1256 case ERROR_DIRECT_ACCESS_HANDLE: return EBADF;
1257 case ERROR_SEEK_ON_DEVICE: return ESPIPE;
1258 case ERROR_BUSY_DRIVE: return EAGAIN;
1259 case ERROR_DIR_NOT_EMPTY: return EEXIST;
1260 case ERROR_NOT_LOCKED: return EACCES;
1261 case ERROR_BAD_PATHNAME: return ENOENT;
1262 case ERROR_LOCK_FAILED: return EACCES;
1263 case ERROR_ALREADY_EXISTS: return EEXIST;
1264 case ERROR_FILENAME_EXCED_RANGE: return ENAMETOOLONG;
1265 case ERROR_BAD_PIPE: return EPIPE;
1266 case ERROR_PIPE_BUSY: return EAGAIN;
1267 case ERROR_PIPE_NOT_CONNECTED: return EPIPE;
1268 case ERROR_DIRECTORY: return ENOTDIR;
1270 return EINVAL;
1273 static int JimPipe(fdtype pipefd[2])
1275 if (CreatePipe(&pipefd[0], &pipefd[1], NULL, 0)) {
1276 return 0;
1278 return -1;
1281 static fdtype JimDupFd(fdtype infd)
1283 fdtype dupfd;
1284 pidtype pid = GetCurrentProcess();
1286 if (DuplicateHandle(pid, infd, pid, &dupfd, 0, TRUE, DUPLICATE_SAME_ACCESS)) {
1287 return dupfd;
1289 return JIM_BAD_FD;
1292 static int JimRewindFd(fdtype fd)
1294 return SetFilePointer(fd, 0, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER ? -1 : 0;
1297 #if 0
1298 static int JimReadFd(fdtype fd, char *buffer, size_t len)
1300 DWORD num;
1302 if (ReadFile(fd, buffer, len, &num, NULL)) {
1303 return num;
1305 if (GetLastError() == ERROR_HANDLE_EOF || GetLastError() == ERROR_BROKEN_PIPE) {
1306 return 0;
1308 return -1;
1310 #endif
1312 static FILE *JimFdOpenForRead(fdtype fd)
1314 return _fdopen(_open_osfhandle((int)fd, _O_RDONLY | _O_TEXT), "r");
1317 static fdtype JimFileno(FILE *fh)
1319 return (fdtype)_get_osfhandle(_fileno(fh));
1322 static fdtype JimOpenForRead(const char *filename)
1324 return CreateFile(filename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
1325 JimStdSecAttrs(), OPEN_EXISTING, 0, NULL);
1328 static fdtype JimOpenForWrite(const char *filename, int append)
1330 return CreateFile(filename, append ? FILE_APPEND_DATA : GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
1331 JimStdSecAttrs(), append ? OPEN_ALWAYS : CREATE_ALWAYS, 0, (HANDLE) NULL);
1334 static FILE *JimFdOpenForWrite(fdtype fd)
1336 return _fdopen(_open_osfhandle((int)fd, _O_TEXT), "w");
1339 static pidtype JimWaitPid(pidtype pid, int *status, int nohang)
1341 DWORD ret = WaitForSingleObject(pid, nohang ? 0 : INFINITE);
1342 if (ret == WAIT_TIMEOUT || ret == WAIT_FAILED) {
1343 /* WAIT_TIMEOUT can only happend with WNOHANG */
1344 return JIM_BAD_PID;
1346 GetExitCodeProcess(pid, &ret);
1347 *status = ret;
1348 CloseHandle(pid);
1349 return pid;
1352 static HANDLE JimCreateTemp(Jim_Interp *interp, const char *contents, int len)
1354 char name[MAX_PATH];
1355 HANDLE handle;
1357 if (!GetTempPath(MAX_PATH, name) || !GetTempFileName(name, "JIM", 0, name)) {
1358 return JIM_BAD_FD;
1361 handle = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, JimStdSecAttrs(),
1362 CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE,
1363 NULL);
1365 if (handle == INVALID_HANDLE_VALUE) {
1366 goto error;
1369 if (contents != NULL) {
1370 /* Use fdopen() to get automatic text-mode translation */
1371 FILE *fh = JimFdOpenForWrite(JimDupFd(handle));
1372 if (fh == NULL) {
1373 goto error;
1376 if (fwrite(contents, len, 1, fh) != 1) {
1377 fclose(fh);
1378 goto error;
1380 fseek(fh, 0, SEEK_SET);
1381 fclose(fh);
1383 return handle;
1385 error:
1386 Jim_SetResultErrno(interp, "failed to create temp file");
1387 CloseHandle(handle);
1388 DeleteFile(name);
1389 return JIM_BAD_FD;
1392 static int
1393 JimWinFindExecutable(const char *originalName, char fullPath[MAX_PATH])
1395 int i;
1396 static char extensions[][5] = {".exe", "", ".bat"};
1398 for (i = 0; i < (int) (sizeof(extensions) / sizeof(extensions[0])); i++) {
1399 lstrcpyn(fullPath, originalName, MAX_PATH - 5);
1400 lstrcat(fullPath, extensions[i]);
1402 if (SearchPath(NULL, fullPath, NULL, MAX_PATH, fullPath, NULL) == 0) {
1403 continue;
1405 if (GetFileAttributes(fullPath) & FILE_ATTRIBUTE_DIRECTORY) {
1406 continue;
1408 return 0;
1411 return -1;
1414 static char **JimSaveEnv(char **env)
1416 return env;
1419 static void JimRestoreEnv(char **env)
1421 JimFreeEnv(env, Jim_GetEnviron());
1424 static Jim_Obj *
1425 JimWinBuildCommandLine(Jim_Interp *interp, char **argv)
1427 char *start, *special;
1428 int quote, i;
1430 Jim_Obj *strObj = Jim_NewStringObj(interp, "", 0);
1432 for (i = 0; argv[i]; i++) {
1433 if (i > 0) {
1434 Jim_AppendString(interp, strObj, " ", 1);
1437 if (argv[i][0] == '\0') {
1438 quote = 1;
1440 else {
1441 quote = 0;
1442 for (start = argv[i]; *start != '\0'; start++) {
1443 if (isspace(UCHAR(*start))) {
1444 quote = 1;
1445 break;
1449 if (quote) {
1450 Jim_AppendString(interp, strObj, "\"" , 1);
1453 start = argv[i];
1454 for (special = argv[i]; ; ) {
1455 if ((*special == '\\') && (special[1] == '\\' ||
1456 special[1] == '"' || (quote && special[1] == '\0'))) {
1457 Jim_AppendString(interp, strObj, start, special - start);
1458 start = special;
1459 while (1) {
1460 special++;
1461 if (*special == '"' || (quote && *special == '\0')) {
1463 * N backslashes followed a quote -> insert
1464 * N * 2 + 1 backslashes then a quote.
1467 Jim_AppendString(interp, strObj, start, special - start);
1468 break;
1470 if (*special != '\\') {
1471 break;
1474 Jim_AppendString(interp, strObj, start, special - start);
1475 start = special;
1477 if (*special == '"') {
1478 if (special == start) {
1479 Jim_AppendString(interp, strObj, "\"", 1);
1481 else {
1482 Jim_AppendString(interp, strObj, start, special - start);
1484 Jim_AppendString(interp, strObj, "\\\"", 2);
1485 start = special + 1;
1487 if (*special == '\0') {
1488 break;
1490 special++;
1492 Jim_AppendString(interp, strObj, start, special - start);
1493 if (quote) {
1494 Jim_AppendString(interp, strObj, "\"", 1);
1497 return strObj;
1500 static pidtype
1501 JimStartWinProcess(Jim_Interp *interp, char **argv, char *env, fdtype inputId, fdtype outputId, fdtype errorId)
1503 STARTUPINFO startInfo;
1504 PROCESS_INFORMATION procInfo;
1505 HANDLE hProcess, h;
1506 char execPath[MAX_PATH];
1507 pidtype pid = JIM_BAD_PID;
1508 Jim_Obj *cmdLineObj;
1510 if (JimWinFindExecutable(argv[0], execPath) < 0) {
1511 return JIM_BAD_PID;
1513 argv[0] = execPath;
1515 hProcess = GetCurrentProcess();
1516 cmdLineObj = JimWinBuildCommandLine(interp, argv);
1519 * STARTF_USESTDHANDLES must be used to pass handles to child process.
1520 * Using SetStdHandle() and/or dup2() only works when a console mode
1521 * parent process is spawning an attached console mode child process.
1524 ZeroMemory(&startInfo, sizeof(startInfo));
1525 startInfo.cb = sizeof(startInfo);
1526 startInfo.dwFlags = STARTF_USESTDHANDLES;
1527 startInfo.hStdInput = INVALID_HANDLE_VALUE;
1528 startInfo.hStdOutput= INVALID_HANDLE_VALUE;
1529 startInfo.hStdError = INVALID_HANDLE_VALUE;
1532 * Duplicate all the handles which will be passed off as stdin, stdout
1533 * and stderr of the child process. The duplicate handles are set to
1534 * be inheritable, so the child process can use them.
1536 if (inputId == JIM_BAD_FD) {
1537 if (CreatePipe(&startInfo.hStdInput, &h, JimStdSecAttrs(), 0) != FALSE) {
1538 CloseHandle(h);
1540 } else {
1541 DuplicateHandle(hProcess, inputId, hProcess, &startInfo.hStdInput,
1542 0, TRUE, DUPLICATE_SAME_ACCESS);
1544 if (startInfo.hStdInput == JIM_BAD_FD) {
1545 goto end;
1548 if (outputId == JIM_BAD_FD) {
1549 startInfo.hStdOutput = CreateFile("NUL:", GENERIC_WRITE, 0,
1550 JimStdSecAttrs(), OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1551 } else {
1552 DuplicateHandle(hProcess, outputId, hProcess, &startInfo.hStdOutput,
1553 0, TRUE, DUPLICATE_SAME_ACCESS);
1555 if (startInfo.hStdOutput == JIM_BAD_FD) {
1556 goto end;
1559 if (errorId == JIM_BAD_FD) {
1561 * If handle was not set, errors should be sent to an infinitely
1562 * deep sink.
1565 startInfo.hStdError = CreateFile("NUL:", GENERIC_WRITE, 0,
1566 JimStdSecAttrs(), OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1567 } else {
1568 DuplicateHandle(hProcess, errorId, hProcess, &startInfo.hStdError,
1569 0, TRUE, DUPLICATE_SAME_ACCESS);
1571 if (startInfo.hStdError == JIM_BAD_FD) {
1572 goto end;
1575 if (!CreateProcess(NULL, (char *)Jim_String(cmdLineObj), NULL, NULL, TRUE,
1576 0, env, NULL, &startInfo, &procInfo)) {
1577 goto end;
1581 * "When an application spawns a process repeatedly, a new thread
1582 * instance will be created for each process but the previous
1583 * instances may not be cleaned up. This results in a significant
1584 * virtual memory loss each time the process is spawned. If there
1585 * is a WaitForInputIdle() call between CreateProcess() and
1586 * CloseHandle(), the problem does not occur." PSS ID Number: Q124121
1589 WaitForInputIdle(procInfo.hProcess, 5000);
1590 CloseHandle(procInfo.hThread);
1592 pid = procInfo.hProcess;
1594 end:
1595 Jim_FreeNewObj(interp, cmdLineObj);
1596 if (startInfo.hStdInput != JIM_BAD_FD) {
1597 CloseHandle(startInfo.hStdInput);
1599 if (startInfo.hStdOutput != JIM_BAD_FD) {
1600 CloseHandle(startInfo.hStdOutput);
1602 if (startInfo.hStdError != JIM_BAD_FD) {
1603 CloseHandle(startInfo.hStdError);
1605 return pid;
1607 #else
1608 /* Unix-specific implementation */
1609 static int JimOpenForWrite(const char *filename, int append)
1611 return open(filename, O_WRONLY | O_CREAT | (append ? O_APPEND : O_TRUNC), 0666);
1614 static int JimRewindFd(int fd)
1616 return lseek(fd, 0L, SEEK_SET);
1619 static int JimCreateTemp(Jim_Interp *interp, const char *contents, int len)
1621 int fd = Jim_MakeTempFile(interp, NULL);
1623 if (fd != JIM_BAD_FD) {
1624 unlink(Jim_String(Jim_GetResult(interp)));
1625 if (contents) {
1626 if (write(fd, contents, len) != len) {
1627 Jim_SetResultErrno(interp, "couldn't write temp file");
1628 close(fd);
1629 return -1;
1631 lseek(fd, 0L, SEEK_SET);
1634 return fd;
1637 static char **JimSaveEnv(char **env)
1639 char **saveenv = Jim_GetEnviron();
1640 Jim_SetEnviron(env);
1641 return saveenv;
1644 static void JimRestoreEnv(char **env)
1646 JimFreeEnv(Jim_GetEnviron(), env);
1647 Jim_SetEnviron(env);
1649 #endif
1650 #endif