Avoid re-defining _GNU_SOURCE
[jimtcl.git] / jim-exec.c
blob6690c7529676f7adaaa5d00f96e8ba1c6e31a66c
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 #ifndef _GNU_SOURCE
24 #define _GNU_SOURCE
25 #endif
26 #include <string.h>
27 #include <ctype.h>
29 #include "jimautoconf.h"
30 #include <jim.h>
32 #if (!defined(HAVE_VFORK) || !defined(HAVE_WAITPID)) && !defined(__MINGW32__)
33 /* Poor man's implementation of exec with system()
34 * The system() call *may* do command line redirection, etc.
35 * The standard output is not available.
36 * Can't redirect filehandles.
38 static int Jim_ExecCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
40 Jim_Obj *cmdlineObj = Jim_NewEmptyStringObj(interp);
41 int i, j;
42 int rc;
44 /* Create a quoted command line */
45 for (i = 1; i < argc; i++) {
46 int len;
47 const char *arg = Jim_GetString(argv[i], &len);
49 if (i > 1) {
50 Jim_AppendString(interp, cmdlineObj, " ", 1);
52 if (strpbrk(arg, "\\\" ") == NULL) {
53 /* No quoting required */
54 Jim_AppendString(interp, cmdlineObj, arg, len);
55 continue;
58 Jim_AppendString(interp, cmdlineObj, "\"", 1);
59 for (j = 0; j < len; j++) {
60 if (arg[j] == '\\' || arg[j] == '"') {
61 Jim_AppendString(interp, cmdlineObj, "\\", 1);
63 Jim_AppendString(interp, cmdlineObj, &arg[j], 1);
65 Jim_AppendString(interp, cmdlineObj, "\"", 1);
67 rc = system(Jim_String(cmdlineObj));
69 Jim_FreeNewObj(interp, cmdlineObj);
71 if (rc) {
72 Jim_Obj *errorCode = Jim_NewListObj(interp, NULL, 0);
73 Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, "CHILDSTATUS", -1));
74 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, 0));
75 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, rc));
76 Jim_SetGlobalVariableStr(interp, "errorCode", errorCode);
77 return JIM_ERR;
80 return JIM_OK;
83 int Jim_execInit(Jim_Interp *interp)
85 if (Jim_PackageProvide(interp, "exec", "1.0", JIM_ERRMSG))
86 return JIM_ERR;
88 Jim_CreateCommand(interp, "exec", Jim_ExecCmd, NULL, NULL);
89 return JIM_OK;
91 #else
92 /* Full exec implementation for unix and mingw */
94 #include <errno.h>
95 #include <signal.h>
97 #if defined(__MINGW32__)
98 /* XXX: Should we use this implementation for cygwin too? msvc? */
99 #ifndef STRICT
100 #define STRICT
101 #endif
102 #define WIN32_LEAN_AND_MEAN
103 #include <windows.h>
104 #include <fcntl.h>
106 typedef HANDLE fdtype;
107 typedef HANDLE pidtype;
108 #define JIM_BAD_FD INVALID_HANDLE_VALUE
109 #define JIM_BAD_PID INVALID_HANDLE_VALUE
110 #define JimCloseFd CloseHandle
112 #define WIFEXITED(STATUS) 1
113 #define WEXITSTATUS(STATUS) (STATUS)
114 #define WIFSIGNALED(STATUS) 0
115 #define WTERMSIG(STATUS) 0
116 #define WNOHANG 1
118 static fdtype JimFileno(FILE *fh);
119 static pidtype JimWaitPid(pidtype pid, int *status, int nohang);
120 static fdtype JimDupFd(fdtype infd);
121 static fdtype JimOpenForRead(const char *filename);
122 static FILE *JimFdOpenForRead(fdtype fd);
123 static int JimPipe(fdtype pipefd[2]);
124 static pidtype JimStartWinProcess(Jim_Interp *interp, char **argv, char *env,
125 fdtype inputId, fdtype outputId, fdtype errorId);
126 static int JimErrno(void);
127 #else
128 #include "jim-signal.h"
129 #include <unistd.h>
130 #include <fcntl.h>
131 #include <sys/wait.h>
132 #include <sys/stat.h>
134 typedef int fdtype;
135 typedef int pidtype;
136 #define JimPipe pipe
137 #define JimErrno() errno
138 #define JIM_BAD_FD -1
139 #define JIM_BAD_PID -1
140 #define JimFileno fileno
141 #define JimReadFd read
142 #define JimCloseFd close
143 #define JimWaitPid waitpid
144 #define JimDupFd dup
145 #define JimFdOpenForRead(FD) fdopen((FD), "r")
146 #define JimOpenForRead(NAME) open((NAME), O_RDONLY, 0)
148 #ifndef HAVE_EXECVPE
149 #define execvpe(ARG0, ARGV, ENV) execvp(ARG0, ARGV)
150 #endif
151 #endif
153 static const char *JimStrError(void);
154 static char **JimSaveEnv(char **env);
155 static void JimRestoreEnv(char **env);
156 static int JimCreatePipeline(Jim_Interp *interp, int argc, Jim_Obj *const *argv,
157 pidtype **pidArrayPtr, fdtype *inPipePtr, fdtype *outPipePtr, fdtype *errFilePtr);
158 static void JimDetachPids(Jim_Interp *interp, int numPids, const pidtype *pidPtr);
159 static int JimCleanupChildren(Jim_Interp *interp, int numPids, pidtype *pidPtr, Jim_Obj *errStrObj);
160 static fdtype JimCreateTemp(Jim_Interp *interp, const char *contents, int len);
161 static fdtype JimOpenForWrite(const char *filename, int append);
162 static int JimRewindFd(fdtype fd);
164 static void Jim_SetResultErrno(Jim_Interp *interp, const char *msg)
166 Jim_SetResultFormatted(interp, "%s: %s", msg, JimStrError());
169 static const char *JimStrError(void)
171 return strerror(JimErrno());
175 * If the last character of 'objPtr' is a newline, then remove
176 * the newline character.
178 static void Jim_RemoveTrailingNewline(Jim_Obj *objPtr)
180 int len;
181 const char *s = Jim_GetString(objPtr, &len);
183 if (len > 0 && s[len - 1] == '\n') {
184 objPtr->length--;
185 objPtr->bytes[objPtr->length] = '\0';
190 * Read from 'fd', append the data to strObj and close 'fd'.
191 * Returns 1 if data was added, 0 if not, or -1 on error.
193 static int JimAppendStreamToString(Jim_Interp *interp, fdtype fd, Jim_Obj *strObj)
195 char buf[256];
196 FILE *fh = JimFdOpenForRead(fd);
197 int ret = 0;
199 if (fh == NULL) {
200 return -1;
203 while (1) {
204 int retval = fread(buf, 1, sizeof(buf), fh);
205 if (retval > 0) {
206 ret = 1;
207 Jim_AppendString(interp, strObj, buf, retval);
209 if (retval != sizeof(buf)) {
210 break;
213 fclose(fh);
214 return ret;
218 * Builds the environment array from $::env
220 * If $::env is not set, simply returns environ.
222 * Otherwise allocates the environ array from the contents of $::env
224 * If the exec fails, memory can be freed via JimFreeEnv()
226 static char **JimBuildEnv(Jim_Interp *interp)
228 int i;
229 int size;
230 int num;
231 int n;
232 char **envptr;
233 char *envdata;
235 Jim_Obj *objPtr = Jim_GetGlobalVariableStr(interp, "env", JIM_NONE);
237 if (!objPtr) {
238 return Jim_GetEnviron();
241 /* We build the array as a single block consisting of the pointers followed by
242 * the strings. This has the advantage of being easy to allocate/free and being
243 * compatible with both unix and windows
246 /* Calculate the required size */
247 num = Jim_ListLength(interp, objPtr);
248 if (num % 2) {
249 /* Silently drop the last element if not a valid dictionary */
250 num--;
252 /* We need one \0 and one equal sign for each element.
253 * A list has at least one space for each element except the first.
254 * We need one extra char for the extra null terminator and one for the equal sign.
256 size = Jim_Length(objPtr) + 2;
258 envptr = Jim_Alloc(sizeof(*envptr) * (num / 2 + 1) + size);
259 envdata = (char *)&envptr[num / 2 + 1];
261 n = 0;
262 for (i = 0; i < num; i += 2) {
263 const char *s1, *s2;
264 Jim_Obj *elemObj;
266 Jim_ListIndex(interp, objPtr, i, &elemObj, JIM_NONE);
267 s1 = Jim_String(elemObj);
268 Jim_ListIndex(interp, objPtr, i + 1, &elemObj, JIM_NONE);
269 s2 = Jim_String(elemObj);
271 envptr[n] = envdata;
272 envdata += sprintf(envdata, "%s=%s", s1, s2);
273 envdata++;
274 n++;
276 envptr[n] = NULL;
277 *envdata = 0;
279 return envptr;
283 * Frees the environment allocated by JimBuildEnv()
285 * Must pass original_environ.
287 static void JimFreeEnv(char **env, char **original_environ)
289 if (env != original_environ) {
290 Jim_Free(env);
294 #ifndef jim_ext_signal
295 /* Implement trivial Jim_SignalId() and Jim_SignalName(), just good enough for JimCheckWaitStatus() */
296 const char *Jim_SignalId(int sig)
298 static char buf[10];
299 snprintf(buf, sizeof(buf), "%d", sig);
300 return buf;
303 const char *Jim_SignalName(int sig)
305 return Jim_SignalId(sig);
307 #endif
310 * Create and store an appropriate value for the global variable $::errorCode
311 * Based on pid and waitStatus.
313 * Returns JIM_OK for a normal exit with code 0, otherwise returns JIM_ERR.
315 * Note that $::errorCode is left unchanged for a normal exit.
316 * Details of any abnormal exit is appended to the errStrObj, unless it is NULL.
318 static int JimCheckWaitStatus(Jim_Interp *interp, pidtype pid, int waitStatus, Jim_Obj *errStrObj)
320 Jim_Obj *errorCode;
322 if (WIFEXITED(waitStatus) && WEXITSTATUS(waitStatus) == 0) {
323 return JIM_OK;
325 errorCode = Jim_NewListObj(interp, NULL, 0);
327 if (WIFEXITED(waitStatus)) {
328 Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, "CHILDSTATUS", -1));
329 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, (long)pid));
330 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, WEXITSTATUS(waitStatus)));
332 else {
333 const char *type;
334 const char *action;
336 if (WIFSIGNALED(waitStatus)) {
337 type = "CHILDKILLED";
338 action = "killed";
340 else {
341 type = "CHILDSUSP";
342 action = "suspended";
345 Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, type, -1));
347 if (errStrObj) {
348 /* Append the message to 'errStrObj' with a newline.
349 * The last newline will be stripped later
351 Jim_AppendStrings(interp, errStrObj, "child ", action, " by signal ", Jim_SignalId(WTERMSIG(waitStatus)), "\n", NULL);
354 Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, (long)pid));
355 Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, Jim_SignalId(WTERMSIG(waitStatus)), -1));
356 Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, Jim_SignalName(WTERMSIG(waitStatus)), -1));
358 Jim_SetGlobalVariableStr(interp, "errorCode", errorCode);
360 return JIM_ERR;
364 * Data structures of the following type are used by JimFork and
365 * JimWaitPids to keep track of child processes.
368 struct WaitInfo
370 pidtype pid; /* Process id of child. */
371 int status; /* Status returned when child exited or suspended. */
372 int flags; /* Various flag bits; see below for definitions. */
375 struct WaitInfoTable {
376 struct WaitInfo *info; /* Table of outstanding processes */
377 int size; /* Size of the allocated table */
378 int used; /* Number of entries in use */
382 * Flag bits in WaitInfo structures:
384 * WI_DETACHED - Non-zero means no-one cares about the
385 * process anymore. Ignore it until it
386 * exits, then forget about it.
389 #define WI_DETACHED 2
391 #define WAIT_TABLE_GROW_BY 4
393 static void JimFreeWaitInfoTable(struct Jim_Interp *interp, void *privData)
395 struct WaitInfoTable *table = privData;
397 Jim_Free(table->info);
398 Jim_Free(table);
401 static struct WaitInfoTable *JimAllocWaitInfoTable(void)
403 struct WaitInfoTable *table = Jim_Alloc(sizeof(*table));
404 table->info = NULL;
405 table->size = table->used = 0;
407 return table;
411 * The main [exec] command
413 static int Jim_ExecCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
415 fdtype outputId; /* File id for output pipe. -1 means command overrode. */
416 fdtype errorId; /* File id for temporary file containing error output. */
417 pidtype *pidPtr;
418 int numPids, result;
419 int child_siginfo = 1;
420 Jim_Obj *childErrObj;
421 Jim_Obj *errStrObj;
424 * See if the command is to be run in the background; if so, create
425 * the command, detach it, and return.
427 if (argc > 1 && Jim_CompareStringImmediate(interp, argv[argc - 1], "&")) {
428 Jim_Obj *listObj;
429 int i;
431 argc--;
432 numPids = JimCreatePipeline(interp, argc - 1, argv + 1, &pidPtr, NULL, NULL, NULL);
433 if (numPids < 0) {
434 return JIM_ERR;
436 /* The return value is a list of the pids */
437 listObj = Jim_NewListObj(interp, NULL, 0);
438 for (i = 0; i < numPids; i++) {
439 Jim_ListAppendElement(interp, listObj, Jim_NewIntObj(interp, (long)pidPtr[i]));
441 Jim_SetResult(interp, listObj);
442 JimDetachPids(interp, numPids, pidPtr);
443 Jim_Free(pidPtr);
444 return JIM_OK;
448 * Create the command's pipeline.
450 numPids =
451 JimCreatePipeline(interp, argc - 1, argv + 1, &pidPtr, NULL, &outputId, &errorId);
453 if (numPids < 0) {
454 return JIM_ERR;
457 result = JIM_OK;
459 errStrObj = Jim_NewStringObj(interp, "", 0);
461 /* Read from the output pipe until EOF */
462 if (outputId != JIM_BAD_FD) {
463 if (JimAppendStreamToString(interp, outputId, errStrObj) < 0) {
464 result = JIM_ERR;
465 Jim_SetResultErrno(interp, "error reading from output pipe");
469 /* Now wait for children to finish. Any abnormal results are appended to childErrObj */
470 childErrObj = Jim_NewStringObj(interp, "", 0);
471 Jim_IncrRefCount(childErrObj);
473 if (JimCleanupChildren(interp, numPids, pidPtr, childErrObj) != JIM_OK) {
474 result = JIM_ERR;
478 * Read the child's error output (if any) and put it into the result.
480 * Note that unlike Tcl, the presence of stderr output does not cause
481 * exec to return an error.
483 if (errorId != JIM_BAD_FD) {
484 int ret;
485 JimRewindFd(errorId);
486 ret = JimAppendStreamToString(interp, errorId, errStrObj);
487 if (ret < 0) {
488 Jim_SetResultErrno(interp, "error reading from error pipe");
489 result = JIM_ERR;
491 else if (ret > 0) {
492 /* Got some error output, so discard the abnormal info string */
493 child_siginfo = 0;
497 if (child_siginfo) {
498 /* Append the child siginfo to the result */
499 Jim_AppendObj(interp, errStrObj, childErrObj);
501 Jim_DecrRefCount(interp, childErrObj);
503 /* Finally remove any trailing newline from the result */
504 Jim_RemoveTrailingNewline(errStrObj);
506 /* Set this as the result */
507 Jim_SetResult(interp, errStrObj);
509 return result;
512 static void JimReapDetachedPids(struct WaitInfoTable *table)
514 struct WaitInfo *waitPtr;
515 int count;
516 int dest;
518 if (!table) {
519 return;
522 waitPtr = table->info;
523 dest = 0;
524 for (count = table->used; count > 0; waitPtr++, count--) {
525 if (waitPtr->flags & WI_DETACHED) {
526 int status;
527 pidtype pid = JimWaitPid(waitPtr->pid, &status, WNOHANG);
528 if (pid == waitPtr->pid) {
529 /* Process has exited, so remove it from the table */
530 table->used--;
531 continue;
534 if (waitPtr != &table->info[dest]) {
535 table->info[dest] = *waitPtr;
537 dest++;
542 * Does waitpid() on the given pid, and then removes the
543 * entry from the wait table.
545 * Returns the pid if OK and updates *statusPtr with the status,
546 * or JIM_BAD_PID if the pid was not in the table.
548 static pidtype JimWaitForProcess(struct WaitInfoTable *table, pidtype pid, int *statusPtr)
550 int i;
552 /* Find it in the table */
553 for (i = 0; i < table->used; i++) {
554 if (pid == table->info[i].pid) {
555 /* wait for it */
556 JimWaitPid(pid, statusPtr, 0);
558 /* Remove it from the table */
559 if (i != table->used - 1) {
560 table->info[i] = table->info[table->used - 1];
562 table->used--;
563 return pid;
567 /* Not found */
568 return JIM_BAD_PID;
572 * Indicates that one or more child processes have been placed in
573 * background and are no longer cared about.
574 * These children can be cleaned up with JimReapDetachedPids().
576 static void JimDetachPids(Jim_Interp *interp, int numPids, const pidtype *pidPtr)
578 int j;
579 struct WaitInfoTable *table = Jim_CmdPrivData(interp);
581 for (j = 0; j < numPids; j++) {
582 /* Find it in the table */
583 int i;
584 for (i = 0; i < table->used; i++) {
585 if (pidPtr[j] == table->info[i].pid) {
586 table->info[i].flags |= WI_DETACHED;
587 break;
593 static FILE *JimGetAioFilehandle(Jim_Interp *interp, const char *name)
595 FILE *fh;
596 Jim_Obj *fhObj;
598 fhObj = Jim_NewStringObj(interp, name, -1);
599 Jim_IncrRefCount(fhObj);
600 fh = Jim_AioFilehandle(interp, fhObj);
601 Jim_DecrRefCount(interp, fhObj);
603 return fh;
607 *----------------------------------------------------------------------
609 * JimCreatePipeline --
611 * Given an argc/argv array, instantiate a pipeline of processes
612 * as described by the argv.
614 * Results:
615 * The return value is a count of the number of new processes
616 * created, or -1 if an error occurred while creating the pipeline.
617 * *pidArrayPtr is filled in with the address of a dynamically
618 * allocated array giving the ids of all of the processes. It
619 * is up to the caller to free this array when it isn't needed
620 * anymore. If inPipePtr is non-NULL, *inPipePtr is filled in
621 * with the file id for the input pipe for the pipeline (if any):
622 * the caller must eventually close this file. If outPipePtr
623 * isn't NULL, then *outPipePtr is filled in with the file id
624 * for the output pipe from the pipeline: the caller must close
625 * this file. If errFilePtr isn't NULL, then *errFilePtr is filled
626 * with a file id that may be used to read error output after the
627 * pipeline completes.
629 * Side effects:
630 * Processes and pipes are created.
632 *----------------------------------------------------------------------
634 static int
635 JimCreatePipeline(Jim_Interp *interp, int argc, Jim_Obj *const *argv, pidtype **pidArrayPtr,
636 fdtype *inPipePtr, fdtype *outPipePtr, fdtype *errFilePtr)
638 pidtype *pidPtr = NULL; /* Points to malloc-ed array holding all
639 * the pids of child processes. */
640 int numPids = 0; /* Actual number of processes that exist
641 * at *pidPtr right now. */
642 int cmdCount; /* Count of number of distinct commands
643 * found in argc/argv. */
644 const char *input = NULL; /* Describes input for pipeline, depending
645 * on "inputFile". NULL means take input
646 * from stdin/pipe. */
647 int input_len = 0; /* Length of input, if relevant */
649 #define FILE_NAME 0 /* input/output: filename */
650 #define FILE_APPEND 1 /* output only: filename, append */
651 #define FILE_HANDLE 2 /* input/output: filehandle */
652 #define FILE_TEXT 3 /* input only: input is actual text */
654 int inputFile = FILE_NAME; /* 1 means input is name of input file.
655 * 2 means input is filehandle name.
656 * 0 means input holds actual
657 * text to be input to command. */
659 int outputFile = FILE_NAME; /* 0 means output is the name of output file.
660 * 1 means output is the name of output file, and append.
661 * 2 means output is filehandle name.
662 * All this is ignored if output is NULL
664 int errorFile = FILE_NAME; /* 0 means error is the name of error file.
665 * 1 means error is the name of error file, and append.
666 * 2 means error is filehandle name.
667 * All this is ignored if error is NULL
669 const char *output = NULL; /* Holds name of output file to pipe to,
670 * or NULL if output goes to stdout/pipe. */
671 const char *error = NULL; /* Holds name of stderr file to pipe to,
672 * or NULL if stderr goes to stderr/pipe. */
673 fdtype inputId = JIM_BAD_FD;
674 /* Readable file id input to current command in
675 * pipeline (could be file or pipe). JIM_BAD_FD
676 * means use stdin. */
677 fdtype outputId = JIM_BAD_FD;
678 /* Writable file id for output from current
679 * command in pipeline (could be file or pipe).
680 * JIM_BAD_FD means use stdout. */
681 fdtype errorId = JIM_BAD_FD;
682 /* Writable file id for all standard error
683 * output from all commands in pipeline. JIM_BAD_FD
684 * means use stderr. */
685 fdtype lastOutputId = JIM_BAD_FD;
686 /* Write file id for output from last command
687 * in pipeline (could be file or pipe).
688 * -1 means use stdout. */
689 fdtype pipeIds[2]; /* File ids for pipe that's being created. */
690 int firstArg, lastArg; /* Indexes of first and last arguments in
691 * current command. */
692 int lastBar;
693 int i;
694 pidtype pid;
695 char **save_environ;
696 struct WaitInfoTable *table = Jim_CmdPrivData(interp);
698 /* Holds the args which will be used to exec */
699 char **arg_array = Jim_Alloc(sizeof(*arg_array) * (argc + 1));
700 int arg_count = 0;
702 JimReapDetachedPids(table);
704 if (inPipePtr != NULL) {
705 *inPipePtr = JIM_BAD_FD;
707 if (outPipePtr != NULL) {
708 *outPipePtr = JIM_BAD_FD;
710 if (errFilePtr != NULL) {
711 *errFilePtr = JIM_BAD_FD;
713 pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
716 * First, scan through all the arguments to figure out the structure
717 * of the pipeline. Count the number of distinct processes (it's the
718 * number of "|" arguments). If there are "<", "<<", or ">" arguments
719 * then make note of input and output redirection and remove these
720 * arguments and the arguments that follow them.
722 cmdCount = 1;
723 lastBar = -1;
724 for (i = 0; i < argc; i++) {
725 const char *arg = Jim_String(argv[i]);
727 if (arg[0] == '<') {
728 inputFile = FILE_NAME;
729 input = arg + 1;
730 if (*input == '<') {
731 inputFile = FILE_TEXT;
732 input_len = Jim_Length(argv[i]) - 2;
733 input++;
735 else if (*input == '@') {
736 inputFile = FILE_HANDLE;
737 input++;
740 if (!*input && ++i < argc) {
741 input = Jim_GetString(argv[i], &input_len);
744 else if (arg[0] == '>') {
745 int dup_error = 0;
747 outputFile = FILE_NAME;
749 output = arg + 1;
750 if (*output == '>') {
751 outputFile = FILE_APPEND;
752 output++;
754 if (*output == '&') {
755 /* Redirect stderr too */
756 output++;
757 dup_error = 1;
759 if (*output == '@') {
760 outputFile = FILE_HANDLE;
761 output++;
763 if (!*output && ++i < argc) {
764 output = Jim_String(argv[i]);
766 if (dup_error) {
767 errorFile = outputFile;
768 error = output;
771 else if (arg[0] == '2' && arg[1] == '>') {
772 error = arg + 2;
773 errorFile = FILE_NAME;
775 if (*error == '@') {
776 errorFile = FILE_HANDLE;
777 error++;
779 else if (*error == '>') {
780 errorFile = FILE_APPEND;
781 error++;
783 if (!*error && ++i < argc) {
784 error = Jim_String(argv[i]);
787 else {
788 if (strcmp(arg, "|") == 0 || strcmp(arg, "|&") == 0) {
789 if (i == lastBar + 1 || i == argc - 1) {
790 Jim_SetResultString(interp, "illegal use of | or |& in command", -1);
791 goto badargs;
793 lastBar = i;
794 cmdCount++;
796 /* Either |, |& or a "normal" arg, so store it in the arg array */
797 arg_array[arg_count++] = (char *)arg;
798 continue;
801 if (i >= argc) {
802 Jim_SetResultFormatted(interp, "can't specify \"%s\" as last word in command", arg);
803 goto badargs;
807 if (arg_count == 0) {
808 Jim_SetResultString(interp, "didn't specify command to execute", -1);
809 badargs:
810 Jim_Free(arg_array);
811 return -1;
814 /* Must do this before vfork(), so do it now */
815 save_environ = JimSaveEnv(JimBuildEnv(interp));
818 * Set up the redirected input source for the pipeline, if
819 * so requested.
821 if (input != NULL) {
822 if (inputFile == FILE_TEXT) {
824 * Immediate data in command. Create temporary file and
825 * put data into file.
827 inputId = JimCreateTemp(interp, input, input_len);
828 if (inputId == JIM_BAD_FD) {
829 goto error;
832 else if (inputFile == FILE_HANDLE) {
833 /* Should be a file descriptor */
834 FILE *fh = JimGetAioFilehandle(interp, input);
836 if (fh == NULL) {
837 goto error;
839 inputId = JimDupFd(JimFileno(fh));
841 else {
843 * File redirection. Just open the file.
845 inputId = JimOpenForRead(input);
846 if (inputId == JIM_BAD_FD) {
847 Jim_SetResultFormatted(interp, "couldn't read file \"%s\": %s", input, JimStrError());
848 goto error;
852 else if (inPipePtr != NULL) {
853 if (JimPipe(pipeIds) != 0) {
854 Jim_SetResultErrno(interp, "couldn't create input pipe for command");
855 goto error;
857 inputId = pipeIds[0];
858 *inPipePtr = pipeIds[1];
859 pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
863 * Set up the redirected output sink for the pipeline from one
864 * of two places, if requested.
866 if (output != NULL) {
867 if (outputFile == FILE_HANDLE) {
868 FILE *fh = JimGetAioFilehandle(interp, output);
869 if (fh == NULL) {
870 goto error;
872 fflush(fh);
873 lastOutputId = JimDupFd(JimFileno(fh));
875 else {
877 * Output is to go to a file.
879 lastOutputId = JimOpenForWrite(output, outputFile == FILE_APPEND);
880 if (lastOutputId == JIM_BAD_FD) {
881 Jim_SetResultFormatted(interp, "couldn't write file \"%s\": %s", output, JimStrError());
882 goto error;
886 else if (outPipePtr != NULL) {
888 * Output is to go to a pipe.
890 if (JimPipe(pipeIds) != 0) {
891 Jim_SetResultErrno(interp, "couldn't create output pipe");
892 goto error;
894 lastOutputId = pipeIds[1];
895 *outPipePtr = pipeIds[0];
896 pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
898 /* If we are redirecting stderr with 2>filename or 2>@fileId, then we ignore errFilePtr */
899 if (error != NULL) {
900 if (errorFile == FILE_HANDLE) {
901 if (strcmp(error, "1") == 0) {
902 /* Special 2>@1 */
903 if (lastOutputId != JIM_BAD_FD) {
904 errorId = JimDupFd(lastOutputId);
906 else {
907 /* No redirection of stdout, so just use 2>@stdout */
908 error = "stdout";
911 if (errorId == JIM_BAD_FD) {
912 FILE *fh = JimGetAioFilehandle(interp, error);
913 if (fh == NULL) {
914 goto error;
916 fflush(fh);
917 errorId = JimDupFd(JimFileno(fh));
920 else {
922 * Output is to go to a file.
924 errorId = JimOpenForWrite(error, errorFile == FILE_APPEND);
925 if (errorId == JIM_BAD_FD) {
926 Jim_SetResultFormatted(interp, "couldn't write file \"%s\": %s", error, JimStrError());
927 goto error;
931 else if (errFilePtr != NULL) {
933 * Set up the standard error output sink for the pipeline, if
934 * requested. Use a temporary file which is opened, then deleted.
935 * Could potentially just use pipe, but if it filled up it could
936 * cause the pipeline to deadlock: we'd be waiting for processes
937 * to complete before reading stderr, and processes couldn't complete
938 * because stderr was backed up.
940 errorId = JimCreateTemp(interp, NULL, 0);
941 if (errorId == JIM_BAD_FD) {
942 goto error;
944 *errFilePtr = JimDupFd(errorId);
948 * Scan through the argc array, forking off a process for each
949 * group of arguments between "|" arguments.
952 pidPtr = Jim_Alloc(cmdCount * sizeof(*pidPtr));
953 for (i = 0; i < numPids; i++) {
954 pidPtr[i] = JIM_BAD_PID;
956 for (firstArg = 0; firstArg < arg_count; numPids++, firstArg = lastArg + 1) {
957 int pipe_dup_err = 0;
958 fdtype origErrorId = errorId;
960 for (lastArg = firstArg; lastArg < arg_count; lastArg++) {
961 if (arg_array[lastArg][0] == '|') {
962 if (arg_array[lastArg][1] == '&') {
963 pipe_dup_err = 1;
965 break;
968 /* Replace | with NULL for execv() */
969 arg_array[lastArg] = NULL;
970 if (lastArg == arg_count) {
971 outputId = lastOutputId;
973 else {
974 if (JimPipe(pipeIds) != 0) {
975 Jim_SetResultErrno(interp, "couldn't create pipe");
976 goto error;
978 outputId = pipeIds[1];
981 /* Need to do this befor vfork() */
982 if (pipe_dup_err) {
983 errorId = outputId;
986 /* Now fork the child */
988 #ifdef __MINGW32__
989 pid = JimStartWinProcess(interp, &arg_array[firstArg], save_environ ? save_environ[0] : NULL, inputId, outputId, errorId);
990 if (pid == JIM_BAD_PID) {
991 Jim_SetResultFormatted(interp, "couldn't exec \"%s\"", arg_array[firstArg]);
992 goto error;
994 #else
996 * Make a new process and enter it into the table if the fork
997 * is successful.
999 pid = vfork();
1000 if (pid < 0) {
1001 Jim_SetResultErrno(interp, "couldn't fork child process");
1002 goto error;
1004 if (pid == 0) {
1005 /* Child */
1007 if (inputId != -1) dup2(inputId, 0);
1008 if (outputId != -1) dup2(outputId, 1);
1009 if (errorId != -1) dup2(errorId, 2);
1011 for (i = 3; (i <= outputId) || (i <= inputId) || (i <= errorId); i++) {
1012 close(i);
1015 /* Restore SIGPIPE behaviour */
1016 (void)signal(SIGPIPE, SIG_DFL);
1018 execvpe(arg_array[firstArg], &arg_array[firstArg], Jim_GetEnviron());
1020 /* Need to prep an error message before vfork(), just in case */
1021 fprintf(stderr, "couldn't exec \"%s\"\n", arg_array[firstArg]);
1022 #ifdef JIM_MAINTAINER
1024 /* Keep valgrind happy */
1025 static char *const false_argv[2] = {"false", NULL};
1026 execvp(false_argv[0],false_argv);
1028 #endif
1029 _exit(127);
1031 #endif
1033 /* parent */
1036 * Enlarge the wait table if there isn't enough space for a new
1037 * entry.
1039 if (table->used == table->size) {
1040 table->size += WAIT_TABLE_GROW_BY;
1041 table->info = Jim_Realloc(table->info, table->size * sizeof(*table->info));
1044 table->info[table->used].pid = pid;
1045 table->info[table->used].flags = 0;
1046 table->used++;
1048 pidPtr[numPids] = pid;
1050 /* Restore in case of pipe_dup_err */
1051 errorId = origErrorId;
1054 * Close off our copies of file descriptors that were set up for
1055 * this child, then set up the input for the next child.
1058 if (inputId != JIM_BAD_FD) {
1059 JimCloseFd(inputId);
1061 if (outputId != JIM_BAD_FD) {
1062 JimCloseFd(outputId);
1063 outputId = JIM_BAD_FD;
1065 inputId = pipeIds[0];
1066 pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
1068 *pidArrayPtr = pidPtr;
1071 * All done. Cleanup open files lying around and then return.
1074 cleanup:
1075 if (inputId != JIM_BAD_FD) {
1076 JimCloseFd(inputId);
1078 if (lastOutputId != JIM_BAD_FD) {
1079 JimCloseFd(lastOutputId);
1081 if (errorId != JIM_BAD_FD) {
1082 JimCloseFd(errorId);
1084 Jim_Free(arg_array);
1086 JimRestoreEnv(save_environ);
1088 return numPids;
1091 * An error occurred. There could have been extra files open, such
1092 * as pipes between children. Clean them all up. Detach any child
1093 * processes that have been created.
1096 error:
1097 if ((inPipePtr != NULL) && (*inPipePtr != JIM_BAD_FD)) {
1098 JimCloseFd(*inPipePtr);
1099 *inPipePtr = JIM_BAD_FD;
1101 if ((outPipePtr != NULL) && (*outPipePtr != JIM_BAD_FD)) {
1102 JimCloseFd(*outPipePtr);
1103 *outPipePtr = JIM_BAD_FD;
1105 if ((errFilePtr != NULL) && (*errFilePtr != JIM_BAD_FD)) {
1106 JimCloseFd(*errFilePtr);
1107 *errFilePtr = JIM_BAD_FD;
1109 if (pipeIds[0] != JIM_BAD_FD) {
1110 JimCloseFd(pipeIds[0]);
1112 if (pipeIds[1] != JIM_BAD_FD) {
1113 JimCloseFd(pipeIds[1]);
1115 if (pidPtr != NULL) {
1116 for (i = 0; i < numPids; i++) {
1117 if (pidPtr[i] != JIM_BAD_PID) {
1118 JimDetachPids(interp, 1, &pidPtr[i]);
1121 Jim_Free(pidPtr);
1123 numPids = -1;
1124 goto cleanup;
1128 *----------------------------------------------------------------------
1130 * JimCleanupChildren --
1132 * This is a utility procedure used to wait for child processes
1133 * to exit, record information about abnormal exits.
1135 * Results:
1136 * The return value is a standard Tcl result. If anything at
1137 * weird happened with the child processes, JIM_ERR is returned
1138 * and a structured message is left in $::errorCode.
1139 * If errStrObj is not NULL, abnormal exit details are appended to this object.
1141 * Side effects:
1142 * pidPtr is freed
1144 *----------------------------------------------------------------------
1147 static int JimCleanupChildren(Jim_Interp *interp, int numPids, pidtype *pidPtr, Jim_Obj *errStrObj)
1149 struct WaitInfoTable *table = Jim_CmdPrivData(interp);
1150 int result = JIM_OK;
1151 int i;
1153 /* Now check the return status of each child */
1154 for (i = 0; i < numPids; i++) {
1155 int waitStatus = 0;
1156 if (JimWaitForProcess(table, pidPtr[i], &waitStatus) != JIM_BAD_PID) {
1157 if (JimCheckWaitStatus(interp, pidPtr[i], waitStatus, errStrObj) != JIM_OK) {
1158 result = JIM_ERR;
1162 Jim_Free(pidPtr);
1164 return result;
1167 int Jim_execInit(Jim_Interp *interp)
1169 if (Jim_PackageProvide(interp, "exec", "1.0", JIM_ERRMSG))
1170 return JIM_ERR;
1172 #ifdef SIGPIPE
1174 * Disable SIGPIPE signals: if they were allowed, this process
1175 * might go away unexpectedly if children misbehave. This code
1176 * can potentially interfere with other application code that
1177 * expects to handle SIGPIPEs.
1179 * By doing this in the init function, applications can override
1180 * this later. Note that child processes have SIGPIPE restored
1181 * to the default after vfork().
1183 (void)signal(SIGPIPE, SIG_IGN);
1184 #endif
1186 Jim_CreateCommand(interp, "exec", Jim_ExecCmd, JimAllocWaitInfoTable(), JimFreeWaitInfoTable);
1187 return JIM_OK;
1190 #if defined(__MINGW32__)
1191 /* Windows-specific (mingw) implementation */
1193 static SECURITY_ATTRIBUTES *JimStdSecAttrs(void)
1195 static SECURITY_ATTRIBUTES secAtts;
1197 secAtts.nLength = sizeof(SECURITY_ATTRIBUTES);
1198 secAtts.lpSecurityDescriptor = NULL;
1199 secAtts.bInheritHandle = TRUE;
1200 return &secAtts;
1203 static int JimErrno(void)
1205 switch (GetLastError()) {
1206 case ERROR_FILE_NOT_FOUND: return ENOENT;
1207 case ERROR_PATH_NOT_FOUND: return ENOENT;
1208 case ERROR_TOO_MANY_OPEN_FILES: return EMFILE;
1209 case ERROR_ACCESS_DENIED: return EACCES;
1210 case ERROR_INVALID_HANDLE: return EBADF;
1211 case ERROR_BAD_ENVIRONMENT: return E2BIG;
1212 case ERROR_BAD_FORMAT: return ENOEXEC;
1213 case ERROR_INVALID_ACCESS: return EACCES;
1214 case ERROR_INVALID_DRIVE: return ENOENT;
1215 case ERROR_CURRENT_DIRECTORY: return EACCES;
1216 case ERROR_NOT_SAME_DEVICE: return EXDEV;
1217 case ERROR_NO_MORE_FILES: return ENOENT;
1218 case ERROR_WRITE_PROTECT: return EROFS;
1219 case ERROR_BAD_UNIT: return ENXIO;
1220 case ERROR_NOT_READY: return EBUSY;
1221 case ERROR_BAD_COMMAND: return EIO;
1222 case ERROR_CRC: return EIO;
1223 case ERROR_BAD_LENGTH: return EIO;
1224 case ERROR_SEEK: return EIO;
1225 case ERROR_WRITE_FAULT: return EIO;
1226 case ERROR_READ_FAULT: return EIO;
1227 case ERROR_GEN_FAILURE: return EIO;
1228 case ERROR_SHARING_VIOLATION: return EACCES;
1229 case ERROR_LOCK_VIOLATION: return EACCES;
1230 case ERROR_SHARING_BUFFER_EXCEEDED: return ENFILE;
1231 case ERROR_HANDLE_DISK_FULL: return ENOSPC;
1232 case ERROR_NOT_SUPPORTED: return ENODEV;
1233 case ERROR_REM_NOT_LIST: return EBUSY;
1234 case ERROR_DUP_NAME: return EEXIST;
1235 case ERROR_BAD_NETPATH: return ENOENT;
1236 case ERROR_NETWORK_BUSY: return EBUSY;
1237 case ERROR_DEV_NOT_EXIST: return ENODEV;
1238 case ERROR_TOO_MANY_CMDS: return EAGAIN;
1239 case ERROR_ADAP_HDW_ERR: return EIO;
1240 case ERROR_BAD_NET_RESP: return EIO;
1241 case ERROR_UNEXP_NET_ERR: return EIO;
1242 case ERROR_NETNAME_DELETED: return ENOENT;
1243 case ERROR_NETWORK_ACCESS_DENIED: return EACCES;
1244 case ERROR_BAD_DEV_TYPE: return ENODEV;
1245 case ERROR_BAD_NET_NAME: return ENOENT;
1246 case ERROR_TOO_MANY_NAMES: return ENFILE;
1247 case ERROR_TOO_MANY_SESS: return EIO;
1248 case ERROR_SHARING_PAUSED: return EAGAIN;
1249 case ERROR_REDIR_PAUSED: return EAGAIN;
1250 case ERROR_FILE_EXISTS: return EEXIST;
1251 case ERROR_CANNOT_MAKE: return ENOSPC;
1252 case ERROR_OUT_OF_STRUCTURES: return ENFILE;
1253 case ERROR_ALREADY_ASSIGNED: return EEXIST;
1254 case ERROR_INVALID_PASSWORD: return EPERM;
1255 case ERROR_NET_WRITE_FAULT: return EIO;
1256 case ERROR_NO_PROC_SLOTS: return EAGAIN;
1257 case ERROR_DISK_CHANGE: return EXDEV;
1258 case ERROR_BROKEN_PIPE: return EPIPE;
1259 case ERROR_OPEN_FAILED: return ENOENT;
1260 case ERROR_DISK_FULL: return ENOSPC;
1261 case ERROR_NO_MORE_SEARCH_HANDLES: return EMFILE;
1262 case ERROR_INVALID_TARGET_HANDLE: return EBADF;
1263 case ERROR_INVALID_NAME: return ENOENT;
1264 case ERROR_PROC_NOT_FOUND: return ESRCH;
1265 case ERROR_WAIT_NO_CHILDREN: return ECHILD;
1266 case ERROR_CHILD_NOT_COMPLETE: return ECHILD;
1267 case ERROR_DIRECT_ACCESS_HANDLE: return EBADF;
1268 case ERROR_SEEK_ON_DEVICE: return ESPIPE;
1269 case ERROR_BUSY_DRIVE: return EAGAIN;
1270 case ERROR_DIR_NOT_EMPTY: return EEXIST;
1271 case ERROR_NOT_LOCKED: return EACCES;
1272 case ERROR_BAD_PATHNAME: return ENOENT;
1273 case ERROR_LOCK_FAILED: return EACCES;
1274 case ERROR_ALREADY_EXISTS: return EEXIST;
1275 case ERROR_FILENAME_EXCED_RANGE: return ENAMETOOLONG;
1276 case ERROR_BAD_PIPE: return EPIPE;
1277 case ERROR_PIPE_BUSY: return EAGAIN;
1278 case ERROR_PIPE_NOT_CONNECTED: return EPIPE;
1279 case ERROR_DIRECTORY: return ENOTDIR;
1281 return EINVAL;
1284 static int JimPipe(fdtype pipefd[2])
1286 if (CreatePipe(&pipefd[0], &pipefd[1], NULL, 0)) {
1287 return 0;
1289 return -1;
1292 static fdtype JimDupFd(fdtype infd)
1294 fdtype dupfd;
1295 pidtype pid = GetCurrentProcess();
1297 if (DuplicateHandle(pid, infd, pid, &dupfd, 0, TRUE, DUPLICATE_SAME_ACCESS)) {
1298 return dupfd;
1300 return JIM_BAD_FD;
1303 static int JimRewindFd(fdtype fd)
1305 return SetFilePointer(fd, 0, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER ? -1 : 0;
1308 #if 0
1309 static int JimReadFd(fdtype fd, char *buffer, size_t len)
1311 DWORD num;
1313 if (ReadFile(fd, buffer, len, &num, NULL)) {
1314 return num;
1316 if (GetLastError() == ERROR_HANDLE_EOF || GetLastError() == ERROR_BROKEN_PIPE) {
1317 return 0;
1319 return -1;
1321 #endif
1323 static FILE *JimFdOpenForRead(fdtype fd)
1325 return _fdopen(_open_osfhandle((int)fd, _O_RDONLY | _O_TEXT), "r");
1328 static fdtype JimFileno(FILE *fh)
1330 return (fdtype)_get_osfhandle(_fileno(fh));
1333 static fdtype JimOpenForRead(const char *filename)
1335 return CreateFile(filename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
1336 JimStdSecAttrs(), OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1339 static fdtype JimOpenForWrite(const char *filename, int append)
1341 fdtype fd = CreateFile(filename, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
1342 JimStdSecAttrs(), append ? OPEN_ALWAYS : CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, (HANDLE) NULL);
1343 if (append && fd != JIM_BAD_FD) {
1344 SetFilePointer(fd, 0, NULL, FILE_END);
1346 return fd;
1349 static FILE *JimFdOpenForWrite(fdtype fd)
1351 return _fdopen(_open_osfhandle((int)fd, _O_TEXT), "w");
1354 static pidtype JimWaitPid(pidtype pid, int *status, int nohang)
1356 DWORD ret = WaitForSingleObject(pid, nohang ? 0 : INFINITE);
1357 if (ret == WAIT_TIMEOUT || ret == WAIT_FAILED) {
1358 /* WAIT_TIMEOUT can only happend with WNOHANG */
1359 return JIM_BAD_PID;
1361 GetExitCodeProcess(pid, &ret);
1362 *status = ret;
1363 CloseHandle(pid);
1364 return pid;
1367 static HANDLE JimCreateTemp(Jim_Interp *interp, const char *contents, int len)
1369 char name[MAX_PATH];
1370 HANDLE handle;
1372 if (!GetTempPath(MAX_PATH, name) || !GetTempFileName(name, "JIM", 0, name)) {
1373 return JIM_BAD_FD;
1376 handle = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, JimStdSecAttrs(),
1377 CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE,
1378 NULL);
1380 if (handle == INVALID_HANDLE_VALUE) {
1381 goto error;
1384 if (contents != NULL) {
1385 /* Use fdopen() to get automatic text-mode translation */
1386 FILE *fh = JimFdOpenForWrite(JimDupFd(handle));
1387 if (fh == NULL) {
1388 goto error;
1391 if (fwrite(contents, len, 1, fh) != 1) {
1392 fclose(fh);
1393 goto error;
1395 fseek(fh, 0, SEEK_SET);
1396 fclose(fh);
1398 return handle;
1400 error:
1401 Jim_SetResultErrno(interp, "failed to create temp file");
1402 CloseHandle(handle);
1403 DeleteFile(name);
1404 return JIM_BAD_FD;
1407 static int
1408 JimWinFindExecutable(const char *originalName, char fullPath[MAX_PATH])
1410 int i;
1411 static char extensions[][5] = {".exe", "", ".bat"};
1413 for (i = 0; i < (int) (sizeof(extensions) / sizeof(extensions[0])); i++) {
1414 snprintf(fullPath, MAX_PATH, "%s%s", originalName, extensions[i]);
1416 if (SearchPath(NULL, fullPath, NULL, MAX_PATH, fullPath, NULL) == 0) {
1417 continue;
1419 if (GetFileAttributes(fullPath) & FILE_ATTRIBUTE_DIRECTORY) {
1420 continue;
1422 return 0;
1425 return -1;
1428 static char **JimSaveEnv(char **env)
1430 return env;
1433 static void JimRestoreEnv(char **env)
1435 JimFreeEnv(env, Jim_GetEnviron());
1438 static Jim_Obj *
1439 JimWinBuildCommandLine(Jim_Interp *interp, char **argv)
1441 char *start, *special;
1442 int quote, i;
1444 Jim_Obj *strObj = Jim_NewStringObj(interp, "", 0);
1446 for (i = 0; argv[i]; i++) {
1447 if (i > 0) {
1448 Jim_AppendString(interp, strObj, " ", 1);
1451 if (argv[i][0] == '\0') {
1452 quote = 1;
1454 else {
1455 quote = 0;
1456 for (start = argv[i]; *start != '\0'; start++) {
1457 if (isspace(UCHAR(*start))) {
1458 quote = 1;
1459 break;
1463 if (quote) {
1464 Jim_AppendString(interp, strObj, "\"" , 1);
1467 start = argv[i];
1468 for (special = argv[i]; ; ) {
1469 if ((*special == '\\') && (special[1] == '\\' ||
1470 special[1] == '"' || (quote && special[1] == '\0'))) {
1471 Jim_AppendString(interp, strObj, start, special - start);
1472 start = special;
1473 while (1) {
1474 special++;
1475 if (*special == '"' || (quote && *special == '\0')) {
1477 * N backslashes followed a quote -> insert
1478 * N * 2 + 1 backslashes then a quote.
1481 Jim_AppendString(interp, strObj, start, special - start);
1482 break;
1484 if (*special != '\\') {
1485 break;
1488 Jim_AppendString(interp, strObj, start, special - start);
1489 start = special;
1491 if (*special == '"') {
1492 if (special == start) {
1493 Jim_AppendString(interp, strObj, "\"", 1);
1495 else {
1496 Jim_AppendString(interp, strObj, start, special - start);
1498 Jim_AppendString(interp, strObj, "\\\"", 2);
1499 start = special + 1;
1501 if (*special == '\0') {
1502 break;
1504 special++;
1506 Jim_AppendString(interp, strObj, start, special - start);
1507 if (quote) {
1508 Jim_AppendString(interp, strObj, "\"", 1);
1511 return strObj;
1514 static pidtype
1515 JimStartWinProcess(Jim_Interp *interp, char **argv, char *env, fdtype inputId, fdtype outputId, fdtype errorId)
1517 STARTUPINFO startInfo;
1518 PROCESS_INFORMATION procInfo;
1519 HANDLE hProcess, h;
1520 char execPath[MAX_PATH];
1521 pidtype pid = JIM_BAD_PID;
1522 Jim_Obj *cmdLineObj;
1524 if (JimWinFindExecutable(argv[0], execPath) < 0) {
1525 return JIM_BAD_PID;
1527 argv[0] = execPath;
1529 hProcess = GetCurrentProcess();
1530 cmdLineObj = JimWinBuildCommandLine(interp, argv);
1533 * STARTF_USESTDHANDLES must be used to pass handles to child process.
1534 * Using SetStdHandle() and/or dup2() only works when a console mode
1535 * parent process is spawning an attached console mode child process.
1538 ZeroMemory(&startInfo, sizeof(startInfo));
1539 startInfo.cb = sizeof(startInfo);
1540 startInfo.dwFlags = STARTF_USESTDHANDLES;
1541 startInfo.hStdInput = INVALID_HANDLE_VALUE;
1542 startInfo.hStdOutput= INVALID_HANDLE_VALUE;
1543 startInfo.hStdError = INVALID_HANDLE_VALUE;
1546 * Duplicate all the handles which will be passed off as stdin, stdout
1547 * and stderr of the child process. The duplicate handles are set to
1548 * be inheritable, so the child process can use them.
1550 if (inputId == JIM_BAD_FD) {
1551 if (CreatePipe(&startInfo.hStdInput, &h, JimStdSecAttrs(), 0) != FALSE) {
1552 CloseHandle(h);
1554 } else {
1555 DuplicateHandle(hProcess, inputId, hProcess, &startInfo.hStdInput,
1556 0, TRUE, DUPLICATE_SAME_ACCESS);
1558 if (startInfo.hStdInput == JIM_BAD_FD) {
1559 goto end;
1562 if (outputId == JIM_BAD_FD) {
1563 startInfo.hStdOutput = CreateFile("NUL:", GENERIC_WRITE, 0,
1564 JimStdSecAttrs(), OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1565 } else {
1566 DuplicateHandle(hProcess, outputId, hProcess, &startInfo.hStdOutput,
1567 0, TRUE, DUPLICATE_SAME_ACCESS);
1569 if (startInfo.hStdOutput == JIM_BAD_FD) {
1570 goto end;
1573 if (errorId == JIM_BAD_FD) {
1575 * If handle was not set, errors should be sent to an infinitely
1576 * deep sink.
1579 startInfo.hStdError = CreateFile("NUL:", GENERIC_WRITE, 0,
1580 JimStdSecAttrs(), OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1581 } else {
1582 DuplicateHandle(hProcess, errorId, hProcess, &startInfo.hStdError,
1583 0, TRUE, DUPLICATE_SAME_ACCESS);
1585 if (startInfo.hStdError == JIM_BAD_FD) {
1586 goto end;
1589 if (!CreateProcess(NULL, (char *)Jim_String(cmdLineObj), NULL, NULL, TRUE,
1590 0, env, NULL, &startInfo, &procInfo)) {
1591 goto end;
1595 * "When an application spawns a process repeatedly, a new thread
1596 * instance will be created for each process but the previous
1597 * instances may not be cleaned up. This results in a significant
1598 * virtual memory loss each time the process is spawned. If there
1599 * is a WaitForInputIdle() call between CreateProcess() and
1600 * CloseHandle(), the problem does not occur." PSS ID Number: Q124121
1603 WaitForInputIdle(procInfo.hProcess, 5000);
1604 CloseHandle(procInfo.hThread);
1606 pid = procInfo.hProcess;
1608 end:
1609 Jim_FreeNewObj(interp, cmdLineObj);
1610 if (startInfo.hStdInput != JIM_BAD_FD) {
1611 CloseHandle(startInfo.hStdInput);
1613 if (startInfo.hStdOutput != JIM_BAD_FD) {
1614 CloseHandle(startInfo.hStdOutput);
1616 if (startInfo.hStdError != JIM_BAD_FD) {
1617 CloseHandle(startInfo.hStdError);
1619 return pid;
1621 #else
1622 /* Unix-specific implementation */
1623 static int JimOpenForWrite(const char *filename, int append)
1625 return open(filename, O_WRONLY | O_CREAT | (append ? O_APPEND : O_TRUNC), 0666);
1628 static int JimRewindFd(int fd)
1630 return lseek(fd, 0L, SEEK_SET);
1633 static int JimCreateTemp(Jim_Interp *interp, const char *contents, int len)
1635 int fd = Jim_MakeTempFile(interp, NULL);
1637 if (fd != JIM_BAD_FD) {
1638 unlink(Jim_String(Jim_GetResult(interp)));
1639 if (contents) {
1640 if (write(fd, contents, len) != len) {
1641 Jim_SetResultErrno(interp, "couldn't write temp file");
1642 close(fd);
1643 return -1;
1645 lseek(fd, 0L, SEEK_SET);
1648 return fd;
1651 static char **JimSaveEnv(char **env)
1653 char **saveenv = Jim_GetEnviron();
1654 Jim_SetEnviron(env);
1655 return saveenv;
1658 static void JimRestoreEnv(char **env)
1660 JimFreeEnv(Jim_GetEnviron(), env);
1661 Jim_SetEnviron(env);
1663 #endif
1664 #endif