4 * This file implements the Windows-specific exec pipeline functions, the
5 * "pipe" channel driver, and the "pid" Tcl command.
7 * Copyright (c) 1996-1997 by Sun Microsystems, Inc.
9 * See the file "license.terms" for information on usage and redistribution of
10 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
13 #include "tclWinInt.h"
16 * The following variable is used to tell whether this module has been
20 static int initialized = 0;
23 * The pipeMutex locks around access to the initialized and procList
24 * variables, and it is used to protect background threads from being
25 * terminated while they are using APIs that hold locks.
28 TCL_DECLARE_MUTEX(pipeMutex)
31 * The following defines identify the various types of applications that run
32 * under windows. There is special case code for the various types.
41 * The following constants and structures are used to encapsulate the state of
42 * various types of files used in a pipeline. This used to have a 1 && 2 that
46 #define WIN_FILE 3 /* Basic Win32 file. */
49 * This structure encapsulates the common state associated with all file types
54 int type; /* One of the file types defined above. */
55 HANDLE handle; /* Open file handle. */
59 * This list is used to map from pids to process handles.
62 typedef struct ProcInfo {
65 struct ProcInfo *nextPtr;
68 static ProcInfo *procList;
71 * Bit masks used in the flags field of the PipeInfo structure below.
74 #define PIPE_PENDING (1<<0) /* Message is pending in the queue. */
75 #define PIPE_ASYNC (1<<1) /* Channel is non-blocking. */
78 * Bit masks used in the sharedFlags field of the PipeInfo structure below.
81 #define PIPE_EOF (1<<2) /* Pipe has reached EOF. */
82 #define PIPE_EXTRABYTE (1<<3) /* The reader thread has consumed one byte. */
85 * TODO: It appears the whole EXTRABYTE machinery is in place to support
86 * outdated Win 95 systems. If this can be confirmed, much code can be
91 * This structure describes per-instance data for a pipe based channel.
94 typedef struct PipeInfo {
95 struct PipeInfo *nextPtr; /* Pointer to next registered pipe. */
96 Tcl_Channel channel; /* Pointer to channel structure. */
97 int validMask; /* OR'ed combination of TCL_READABLE,
98 * TCL_WRITABLE, or TCL_EXCEPTION: indicates
99 * which operations are valid on the file. */
100 int watchMask; /* OR'ed combination of TCL_READABLE,
101 * TCL_WRITABLE, or TCL_EXCEPTION: indicates
102 * which events should be reported. */
103 int flags; /* State flags, see above for a list. */
104 TclFile readFile; /* Output from pipe. */
105 TclFile writeFile; /* Input from pipe. */
106 TclFile errorFile; /* Error output from pipe. */
107 int numPids; /* Number of processes attached to pipe. */
108 Tcl_Pid *pidPtr; /* Pids of attached processes. */
109 Tcl_ThreadId threadId; /* Thread to which events should be reported.
110 * This value is used by the reader/writer
112 TclPipeThreadInfo *writeTI; /* Thread info of writer and reader, this */
113 TclPipeThreadInfo *readTI; /* structure owned by corresponding thread. */
114 HANDLE writeThread; /* Handle to writer thread. */
115 HANDLE readThread; /* Handle to reader thread. */
117 HANDLE writable; /* Manual-reset event to signal when the
118 * writer thread has finished waiting for the
119 * current buffer to be written. */
120 HANDLE readable; /* Manual-reset event to signal when the
121 * reader thread has finished waiting for
123 DWORD writeError; /* An error caused by the last background
124 * write. Set to 0 if no error has been
125 * detected. This word is shared with the
126 * writer thread so access must be
127 * synchronized with the writable object. */
128 char *writeBuf; /* Current background output buffer. Access is
129 * synchronized with the writable object. */
130 int writeBufLen; /* Size of write buffer. Access is
131 * synchronized with the writable object. */
132 int toWrite; /* Current amount to be written. Access is
133 * synchronized with the writable object. */
134 int readFlags; /* Flags that are shared with the reader
135 * thread. Access is synchronized with the
136 * readable object. */
137 char extraByte; /* Buffer for extra character consumed by
138 * reader thread. This byte is shared with the
139 * reader thread so access must be
140 * synchronized with the readable object. */
145 * The following pointer refers to the head of the list of pipes that are
146 * being watched for file events.
149 PipeInfo *firstPipePtr;
150 } ThreadSpecificData;
152 static Tcl_ThreadDataKey dataKey;
155 * The following structure is what is added to the Tcl event queue when pipe
156 * events are generated.
160 Tcl_Event header; /* Information that is standard for all
162 PipeInfo *infoPtr; /* Pointer to pipe info structure. Note that
163 * we still have to verify that the pipe
164 * exists before dereferencing this
169 * Declarations for functions used only in this file.
172 static int ApplicationType(Tcl_Interp *interp,
173 const char *fileName, char *fullName);
174 static void BuildCommandLine(const char *executable, int argc,
175 const char **argv, Tcl_DString *linePtr);
176 static BOOL HasConsole(void);
177 static int PipeBlockModeProc(ClientData instanceData, int mode);
178 static void PipeCheckProc(ClientData clientData, int flags);
179 static int PipeClose2Proc(ClientData instanceData,
180 Tcl_Interp *interp, int flags);
181 static int PipeEventProc(Tcl_Event *evPtr, int flags);
182 static int PipeGetHandleProc(ClientData instanceData,
183 int direction, ClientData *handlePtr);
184 static void PipeInit(void);
185 static int PipeInputProc(ClientData instanceData, char *buf,
186 int toRead, int *errorCode);
187 static int PipeOutputProc(ClientData instanceData,
188 const char *buf, int toWrite, int *errorCode);
189 static DWORD WINAPI PipeReaderThread(LPVOID arg);
190 static void PipeSetupProc(ClientData clientData, int flags);
191 static void PipeWatchProc(ClientData instanceData, int mask);
192 static DWORD WINAPI PipeWriterThread(LPVOID arg);
193 static int TempFileName(WCHAR name[MAX_PATH]);
194 static int WaitForRead(PipeInfo *infoPtr, int blocking);
195 static void PipeThreadActionProc(ClientData instanceData,
199 * This structure describes the channel type structure for command pipe based
203 static const Tcl_ChannelType pipeChannelType = {
204 "pipe", /* Type name. */
205 TCL_CHANNEL_VERSION_5, /* v5 channel */
206 TCL_CLOSE2PROC, /* Close proc. */
207 PipeInputProc, /* Input proc. */
208 PipeOutputProc, /* Output proc. */
209 NULL, /* Seek proc. */
210 NULL, /* Set option proc. */
211 NULL, /* Get option proc. */
212 PipeWatchProc, /* Set up notifier to watch the channel. */
213 PipeGetHandleProc, /* Get an OS handle from channel. */
214 PipeClose2Proc, /* close2proc */
215 PipeBlockModeProc, /* Set blocking or non-blocking mode.*/
216 NULL, /* flush proc. */
217 NULL, /* handler proc. */
218 NULL, /* wide seek proc */
219 PipeThreadActionProc, /* thread action proc */
224 *----------------------------------------------------------------------
228 * This function initializes the static variables for this file.
234 * Creates a new event source.
236 *----------------------------------------------------------------------
242 ThreadSpecificData *tsdPtr;
245 * Check the initialized flag first, then check again in the mutex. This
246 * is a speed enhancement.
250 Tcl_MutexLock(&pipeMutex);
255 Tcl_MutexUnlock(&pipeMutex);
258 tsdPtr = (ThreadSpecificData *)TclThreadDataKeyGet(&dataKey);
259 if (tsdPtr == NULL) {
260 tsdPtr = TCL_TSD_INIT(&dataKey);
261 tsdPtr->firstPipePtr = NULL;
262 Tcl_CreateEventSource(PipeSetupProc, PipeCheckProc, NULL);
267 *----------------------------------------------------------------------
269 * TclpFinalizePipes --
271 * This function is called from Tcl_FinalizeThread to finalize the
272 * platform specific pipe subsystem.
278 * Removes the pipe event source.
280 *----------------------------------------------------------------------
284 TclpFinalizePipes(void)
286 ThreadSpecificData *tsdPtr;
288 tsdPtr = (ThreadSpecificData *)TclThreadDataKeyGet(&dataKey);
289 if (tsdPtr != NULL) {
290 Tcl_DeleteEventSource(PipeSetupProc, PipeCheckProc, NULL);
295 *----------------------------------------------------------------------
299 * This function is invoked before Tcl_DoOneEvent blocks waiting for an
306 * Adjusts the block time if needed.
308 *----------------------------------------------------------------------
313 ClientData data, /* Not used. */
314 int flags) /* Event flags as passed to Tcl_DoOneEvent. */
317 Tcl_Time blockTime = { 0, 0 };
319 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
321 if (!(flags & TCL_FILE_EVENTS)) {
326 * Look to see if any events are already pending. If they are, poll.
329 for (infoPtr = tsdPtr->firstPipePtr; infoPtr != NULL;
330 infoPtr = infoPtr->nextPtr) {
331 if (infoPtr->watchMask & TCL_WRITABLE) {
332 if (WaitForSingleObject(infoPtr->writable, 0) != WAIT_TIMEOUT) {
336 if (infoPtr->watchMask & TCL_READABLE) {
337 if (WaitForRead(infoPtr, 0) >= 0) {
343 Tcl_SetMaxBlockTime(&blockTime);
348 *----------------------------------------------------------------------
352 * This function is called by Tcl_DoOneEvent to check the pipe event
359 * May queue an event.
361 *----------------------------------------------------------------------
366 ClientData data, /* Not used. */
367 int flags) /* Event flags as passed to Tcl_DoOneEvent. */
372 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
374 if (!(flags & TCL_FILE_EVENTS)) {
379 * Queue events for any ready pipes that don't already have events queued.
382 for (infoPtr = tsdPtr->firstPipePtr; infoPtr != NULL;
383 infoPtr = infoPtr->nextPtr) {
384 if (infoPtr->flags & PIPE_PENDING) {
389 * Queue an event if the pipe is signaled for reading or writing.
393 if ((infoPtr->watchMask & TCL_WRITABLE) &&
394 (WaitForSingleObject(infoPtr->writable, 0) != WAIT_TIMEOUT)) {
398 if ((infoPtr->watchMask & TCL_READABLE) &&
399 (WaitForRead(infoPtr, 0) >= 0)) {
404 infoPtr->flags |= PIPE_PENDING;
405 evPtr = ckalloc(sizeof(PipeEvent));
406 evPtr->header.proc = PipeEventProc;
407 evPtr->infoPtr = infoPtr;
408 Tcl_QueueEvent((Tcl_Event *) evPtr, TCL_QUEUE_TAIL);
414 *----------------------------------------------------------------------
418 * This function constructs a new TclFile from a given data and type
422 * Returns a newly allocated WinFile as a TclFile.
427 *----------------------------------------------------------------------
432 HANDLE handle) /* Type-specific data. */
436 filePtr = ckalloc(sizeof(WinFile));
437 filePtr->type = WIN_FILE;
438 filePtr->handle = handle;
440 return (TclFile)filePtr;
444 *----------------------------------------------------------------------
448 * Gets a temporary file name and deals with the fact that the temporary
449 * file path provided by Windows may not actually exist if the TMP or
450 * TEMP environment variables refer to a non-existent directory.
453 * 0 if error, non-zero otherwise. If non-zero is returned, the name
454 * buffer will be filled with a name that can be used to construct a
460 *----------------------------------------------------------------------
465 WCHAR name[MAX_PATH]) /* Buffer in which name for temporary file
468 const WCHAR *prefix = L"TCL";
469 if (GetTempPathW(MAX_PATH, name) != 0) {
470 if (GetTempFileNameW(name, prefix, 0, name) != 0) {
476 return GetTempFileNameW(name, prefix, 0, name);
480 *----------------------------------------------------------------------
484 * Make a TclFile from a channel.
487 * Returns a new TclFile or NULL on failure.
492 *----------------------------------------------------------------------
497 Tcl_Channel channel, /* Channel to get file from. */
498 int direction) /* Either TCL_READABLE or TCL_WRITABLE. */
502 if (Tcl_GetChannelHandle(channel, direction,
503 (ClientData *) &handle) == TCL_OK) {
504 return TclWinMakeFile(handle);
506 return (TclFile) NULL;
511 *----------------------------------------------------------------------
515 * This function opens files for use in a pipeline.
518 * Returns a newly allocated TclFile structure containing the file
524 *----------------------------------------------------------------------
529 const char *path, /* The name of the file to open. */
530 int mode) /* In what mode to open the file? */
533 DWORD accessMode, createMode, shareMode, flags;
535 const WCHAR *nativePath;
538 * Map the access bits to the NT access mode.
541 switch (mode & (O_RDONLY | O_WRONLY | O_RDWR)) {
543 accessMode = GENERIC_READ;
546 accessMode = GENERIC_WRITE;
549 accessMode = (GENERIC_READ | GENERIC_WRITE);
552 TclWinConvertError(ERROR_INVALID_FUNCTION);
557 * Map the creation flags to the NT create mode.
560 switch (mode & (O_CREAT | O_EXCL | O_TRUNC)) {
561 case (O_CREAT | O_EXCL):
562 case (O_CREAT | O_EXCL | O_TRUNC):
563 createMode = CREATE_NEW;
565 case (O_CREAT | O_TRUNC):
566 createMode = CREATE_ALWAYS;
569 createMode = OPEN_ALWAYS;
572 case (O_TRUNC | O_EXCL):
573 createMode = TRUNCATE_EXISTING;
576 createMode = OPEN_EXISTING;
580 nativePath = (WCHAR *)Tcl_WinUtfToTChar(path, -1, &ds);
583 * If the file is not being created, use the existing file attributes.
587 if (!(mode & O_CREAT)) {
588 flags = GetFileAttributesW(nativePath);
589 if (flags == 0xFFFFFFFF) {
595 * Set up the file sharing mode. We want to allow simultaneous access.
598 shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
601 * Now we get to create the file.
604 handle = CreateFileW(nativePath, accessMode, shareMode,
605 NULL, createMode, flags, NULL);
606 Tcl_DStringFree(&ds);
608 if (handle == INVALID_HANDLE_VALUE) {
611 err = GetLastError();
612 if ((err & 0xFFFFL) == ERROR_OPEN_FAILED) {
613 err = (mode & O_CREAT) ? ERROR_FILE_EXISTS : ERROR_FILE_NOT_FOUND;
615 TclWinConvertError(err);
620 * Seek to the end of file if we are writing.
623 if (mode & (O_WRONLY|O_APPEND)) {
624 SetFilePointer(handle, 0, NULL, FILE_END);
627 return TclWinMakeFile(handle);
631 *----------------------------------------------------------------------
633 * TclpCreateTempFile --
635 * This function opens a unique file with the property that it will be
636 * deleted when its file handle is closed. The temporary file is created
637 * in the system temporary directory.
640 * Returns a valid TclFile, or NULL on failure.
643 * Creates a new temporary file.
645 *----------------------------------------------------------------------
650 const char *contents) /* String to write into temp file, or NULL. */
652 WCHAR name[MAX_PATH];
657 if (TempFileName(name) == 0) {
661 handle = CreateFileW(name,
662 GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
663 FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE, NULL);
664 if (handle == INVALID_HANDLE_VALUE) {
669 * Write the file out, doing line translations on the way.
672 if (contents != NULL) {
673 DWORD result, length;
678 * Convert the contents from UTF to native encoding
681 native = Tcl_UtfToExternalDString(NULL, contents, -1, &dstring);
683 toCopy = Tcl_DStringLength(&dstring);
684 for (p = native; toCopy > 0; p++, toCopy--) {
688 if (!WriteFile(handle, native, length, &result, NULL)) {
692 if (!WriteFile(handle, "\r\n", 2, &result, NULL)) {
700 if (!WriteFile(handle, native, length, &result, NULL)) {
704 Tcl_DStringFree(&dstring);
705 if (SetFilePointer(handle, 0, NULL, FILE_BEGIN) == 0xFFFFFFFF) {
710 return TclWinMakeFile(handle);
714 * Free the native representation of the contents if necessary.
717 if (contents != NULL) {
718 Tcl_DStringFree(&dstring);
721 TclWinConvertError(GetLastError());
728 *----------------------------------------------------------------------
730 * TclpTempFileName --
732 * This function returns a unique filename.
735 * Returns a valid Tcl_Obj* with refCount 0, or NULL on failure.
740 *----------------------------------------------------------------------
744 TclpTempFileName(void)
746 WCHAR fileName[MAX_PATH];
748 if (TempFileName(fileName) == 0) {
752 return TclpNativeToNormalized(fileName);
756 *----------------------------------------------------------------------
760 * Creates an anonymous pipe.
763 * Returns 1 on success, 0 on failure.
768 *----------------------------------------------------------------------
773 TclFile *readPipe, /* Location to store file handle for read side
775 TclFile *writePipe) /* Location to store file handle for write
778 HANDLE readHandle, writeHandle;
780 if (CreatePipe(&readHandle, &writeHandle, NULL, 0) != 0) {
781 *readPipe = TclWinMakeFile(readHandle);
782 *writePipe = TclWinMakeFile(writeHandle);
786 TclWinConvertError(GetLastError());
791 *----------------------------------------------------------------------
795 * Closes a pipeline file handle. These handles are created by
796 * TclpOpenFile, TclpCreatePipe, or TclpMakeFile.
799 * 0 on success, -1 on failure.
802 * The file is closed and deallocated.
804 *----------------------------------------------------------------------
809 TclFile file) /* The file to close. */
811 WinFile *filePtr = (WinFile *) file;
813 switch (filePtr->type) {
816 * Don't close the Win32 handle if the handle is a standard channel
817 * during the thread exit process. Otherwise, one thread may kill the
821 if (!TclInThreadExit()
822 || ((GetStdHandle(STD_INPUT_HANDLE) != filePtr->handle)
823 && (GetStdHandle(STD_OUTPUT_HANDLE) != filePtr->handle)
824 && (GetStdHandle(STD_ERROR_HANDLE) != filePtr->handle))) {
825 if (filePtr->handle != NULL &&
826 CloseHandle(filePtr->handle) == FALSE) {
827 TclWinConvertError(GetLastError());
835 Tcl_Panic("TclpCloseFile: unexpected file type");
843 *--------------------------------------------------------------------------
847 * Given a HANDLE to a child process, return the process id for that
851 * Returns the process id for the child process. If the pid was not known
852 * by Tcl, either because the pid was not created by Tcl or the child
853 * process has already been reaped, -1 is returned.
858 *--------------------------------------------------------------------------
863 Tcl_Pid pid) /* The HANDLE of the child process. */
869 Tcl_MutexLock(&pipeMutex);
870 for (infoPtr = procList; infoPtr != NULL; infoPtr = infoPtr->nextPtr) {
871 if (infoPtr->hProcess == (HANDLE) pid) {
872 Tcl_MutexUnlock(&pipeMutex);
873 return infoPtr->dwProcessId;
876 Tcl_MutexUnlock(&pipeMutex);
877 return (unsigned long) -1;
881 *----------------------------------------------------------------------
883 * TclpCreateProcess --
885 * Create a child process that has the specified files as its standard
886 * input, output, and error. The child process runs asynchronously under
887 * Windows NT and Windows 9x, and runs with the same environment
888 * variables as the creating process.
890 * The complete Windows search path is searched to find the specified
891 * executable. If an executable by the given name is not found,
892 * automatically tries appending standard extensions to the
896 * The return value is TCL_ERROR and an error message is left in the
897 * interp's result if there was a problem creating the child process.
898 * Otherwise, the return value is TCL_OK and *pidPtr is filled with the
899 * process id of the child process.
902 * A process is created.
904 *----------------------------------------------------------------------
909 Tcl_Interp *interp, /* Interpreter in which to leave errors that
910 * occurred when creating the child process.
911 * Error messages from the child process
912 * itself are sent to errorFile. */
913 int argc, /* Number of arguments in following array. */
914 const char **argv, /* Array of argument strings. argv[0] contains
915 * the name of the executable converted to
916 * native format (using the
917 * Tcl_TranslateFileName call). Additional
918 * arguments have not been converted. */
919 TclFile inputFile, /* If non-NULL, gives the file to use as input
920 * for the child process. If inputFile file is
921 * not readable or is NULL, the child will
922 * receive no standard input. */
923 TclFile outputFile, /* If non-NULL, gives the file that receives
924 * output from the child process. If
925 * outputFile file is not writeable or is
926 * NULL, output from the child will be
928 TclFile errorFile, /* If non-NULL, gives the file that receives
929 * errors from the child process. If errorFile
930 * file is not writeable or is NULL, errors
931 * from the child will be discarded. errorFile
932 * may be the same as outputFile. */
933 Tcl_Pid *pidPtr) /* If this function is successful, pidPtr is
934 * filled with the process id of the child
937 int result, applType, createFlags;
938 Tcl_DString cmdLine; /* Complete command line (WCHAR). */
939 STARTUPINFOW startInfo;
940 PROCESS_INFORMATION procInfo;
941 SECURITY_ATTRIBUTES secAtts;
942 HANDLE hProcess, h, inputHandle, outputHandle, errorHandle;
943 char execPath[MAX_PATH * TCL_UTF_MAX];
948 applType = ApplicationType(interp, argv[0], execPath);
949 if (applType == APPL_NONE) {
954 Tcl_DStringInit(&cmdLine);
955 hProcess = GetCurrentProcess();
958 * STARTF_USESTDHANDLES must be used to pass handles to child process.
959 * Using SetStdHandle() and/or dup2() only works when a console mode
960 * parent process is spawning an attached console mode child process.
963 ZeroMemory(&startInfo, sizeof(startInfo));
964 startInfo.cb = sizeof(startInfo);
965 startInfo.dwFlags = STARTF_USESTDHANDLES;
966 startInfo.hStdInput = INVALID_HANDLE_VALUE;
967 startInfo.hStdOutput= INVALID_HANDLE_VALUE;
968 startInfo.hStdError = INVALID_HANDLE_VALUE;
970 secAtts.nLength = sizeof(SECURITY_ATTRIBUTES);
971 secAtts.lpSecurityDescriptor = NULL;
972 secAtts.bInheritHandle = TRUE;
975 * We have to check the type of each file, since we cannot duplicate some
979 inputHandle = INVALID_HANDLE_VALUE;
980 if (inputFile != NULL) {
981 filePtr = (WinFile *)inputFile;
982 if (filePtr->type == WIN_FILE) {
983 inputHandle = filePtr->handle;
986 outputHandle = INVALID_HANDLE_VALUE;
987 if (outputFile != NULL) {
988 filePtr = (WinFile *)outputFile;
989 if (filePtr->type == WIN_FILE) {
990 outputHandle = filePtr->handle;
993 errorHandle = INVALID_HANDLE_VALUE;
994 if (errorFile != NULL) {
995 filePtr = (WinFile *)errorFile;
996 if (filePtr->type == WIN_FILE) {
997 errorHandle = filePtr->handle;
1002 * Duplicate all the handles which will be passed off as stdin, stdout and
1003 * stderr of the child process. The duplicate handles are set to be
1004 * inheritable, so the child process can use them.
1007 if (inputHandle == INVALID_HANDLE_VALUE) {
1009 * If handle was not set, stdin should return immediate EOF. Under
1010 * Windows95, some applications (both 16 and 32 bit!) cannot read from
1011 * the NUL device; they read from console instead. When running tk,
1012 * this is fatal because the child process would hang forever waiting
1013 * for EOF from the unmapped console window used by the helper
1016 * Fortunately, the helper application detects a closed pipe as an
1017 * immediate EOF and can pass that information to the child process.
1020 if (CreatePipe(&startInfo.hStdInput, &h, &secAtts, 0) != FALSE) {
1024 DuplicateHandle(hProcess, inputHandle, hProcess, &startInfo.hStdInput,
1025 0, TRUE, DUPLICATE_SAME_ACCESS);
1027 if (startInfo.hStdInput == INVALID_HANDLE_VALUE) {
1028 TclWinConvertError(GetLastError());
1029 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1030 "couldn't duplicate input handle: %s",
1031 Tcl_PosixError(interp)));
1035 if (outputHandle == INVALID_HANDLE_VALUE) {
1037 * If handle was not set, output should be sent to an infinitely deep
1038 * sink. Under Windows 95, some 16 bit applications cannot have stdout
1039 * redirected to NUL; they send their output to the console instead.
1040 * Some applications, like "more" or "dir /p", when outputting
1041 * multiple pages to the console, also then try and read from the
1042 * console to go the next page. When running tk, this is fatal because
1043 * the child process would hang forever waiting for input from the
1044 * unmapped console window used by the helper application.
1046 * Fortunately, the helper application will detect a closed pipe as a
1050 startInfo.hStdOutput = CreateFileW(L"NUL:", GENERIC_WRITE, 0,
1051 &secAtts, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1053 DuplicateHandle(hProcess, outputHandle, hProcess,
1054 &startInfo.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS);
1056 if (startInfo.hStdOutput == INVALID_HANDLE_VALUE) {
1057 TclWinConvertError(GetLastError());
1058 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1059 "couldn't duplicate output handle: %s",
1060 Tcl_PosixError(interp)));
1064 if (errorHandle == INVALID_HANDLE_VALUE) {
1066 * If handle was not set, errors should be sent to an infinitely deep
1070 startInfo.hStdError = CreateFileW(L"NUL:", GENERIC_WRITE, 0,
1071 &secAtts, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1073 DuplicateHandle(hProcess, errorHandle, hProcess, &startInfo.hStdError,
1074 0, TRUE, DUPLICATE_SAME_ACCESS);
1076 if (startInfo.hStdError == INVALID_HANDLE_VALUE) {
1077 TclWinConvertError(GetLastError());
1078 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1079 "couldn't duplicate error handle: %s",
1080 Tcl_PosixError(interp)));
1085 * If we do not have a console window, then we must run DOS and WIN32
1086 * console mode applications as detached processes. This tells the loader
1087 * that the child application should not inherit the console, and that it
1088 * should not create a new console window for the child application. The
1089 * child application should get its stdio from the redirection handles
1090 * provided by this application, and run in the background.
1092 * If we are starting a GUI process, they don't automatically get a
1093 * console, so it doesn't matter if they are started as foreground or
1094 * detached processes. The GUI window will still pop up to the foreground.
1097 if (TclWinGetPlatformId() == VER_PLATFORM_WIN32_NT) {
1100 } else if (applType == APPL_DOS) {
1102 * Under NT, 16-bit DOS applications will not run unless they can
1103 * be attached to a console. If we are running without a console,
1104 * run the 16-bit program as an normal process inside of a hidden
1105 * console application, and then run that hidden console as a
1109 startInfo.wShowWindow = SW_HIDE;
1110 startInfo.dwFlags |= STARTF_USESHOWWINDOW;
1111 createFlags = CREATE_NEW_CONSOLE;
1112 TclDStringAppendLiteral(&cmdLine, "cmd.exe /c");
1114 createFlags = DETACHED_PROCESS;
1120 createFlags = DETACHED_PROCESS;
1123 if (applType == APPL_DOS) {
1124 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1125 "DOS application process not supported on this platform",
1127 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "EXEC", "DOS_APP",
1134 * cmdLine gets the full command line used to invoke the executable,
1135 * including the name of the executable itself. The command line arguments
1136 * in argv[] are stored in cmdLine separated by spaces. Special characters
1137 * in individual arguments from argv[] must be quoted when being stored in
1140 * When calling any application, bear in mind that arguments that specify
1141 * a path name are not converted. If an argument contains forward slashes
1142 * as path separators, it may or may not be recognized as a path name,
1143 * depending on the program. In general, most applications accept forward
1144 * slashes only as option delimiters and backslashes only as paths.
1146 * Additionally, when calling a 16-bit dos or windows application, all
1147 * path names must use the short, cryptic, path format (e.g., using
1148 * ab~1.def instead of "a b.default").
1151 BuildCommandLine(execPath, argc, argv, &cmdLine);
1153 if (CreateProcessW(NULL, (WCHAR *) Tcl_DStringValue(&cmdLine),
1154 NULL, NULL, TRUE, (DWORD) createFlags, NULL, NULL, &startInfo,
1156 TclWinConvertError(GetLastError());
1157 Tcl_SetObjResult(interp, Tcl_ObjPrintf("couldn't execute \"%s\": %s",
1158 argv[0], Tcl_PosixError(interp)));
1163 * This wait is used to force the OS to give some time to the DOS process.
1166 if (applType == APPL_DOS) {
1167 WaitForSingleObject(procInfo.hProcess, 50);
1171 * "When an application spawns a process repeatedly, a new thread instance
1172 * will be created for each process but the previous instances may not be
1173 * cleaned up. This results in a significant virtual memory loss each time
1174 * the process is spawned. If there is a WaitForInputIdle() call between
1175 * CreateProcess() and CloseHandle(), the problem does not occur." PSS ID
1179 WaitForInputIdle(procInfo.hProcess, 5000);
1180 CloseHandle(procInfo.hThread);
1182 *pidPtr = (Tcl_Pid) procInfo.hProcess;
1184 TclWinAddProcess(procInfo.hProcess, procInfo.dwProcessId);
1189 Tcl_DStringFree(&cmdLine);
1190 if (startInfo.hStdInput != INVALID_HANDLE_VALUE) {
1191 CloseHandle(startInfo.hStdInput);
1193 if (startInfo.hStdOutput != INVALID_HANDLE_VALUE) {
1194 CloseHandle(startInfo.hStdOutput);
1196 if (startInfo.hStdError != INVALID_HANDLE_VALUE) {
1197 CloseHandle(startInfo.hStdError);
1204 *----------------------------------------------------------------------
1208 * Determines whether the current application is attached to a console.
1211 * Returns TRUE if this application has a console, else FALSE.
1216 *----------------------------------------------------------------------
1224 handle = CreateFileW(L"CONOUT$", GENERIC_WRITE, FILE_SHARE_WRITE,
1225 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1227 if (handle != INVALID_HANDLE_VALUE) {
1228 CloseHandle(handle);
1236 *--------------------------------------------------------------------
1238 * ApplicationType --
1240 * Search for the specified program and identify if it refers to a DOS,
1241 * Windows 3.X, or Win32 program. Used to determine how to invoke a
1242 * program, or if it can even be invoked.
1244 * It is possible to almost positively identify DOS and Windows
1245 * applications that contain the appropriate magic numbers. However, DOS
1246 * .com files do not seem to contain a magic number; if the program name
1247 * ends with .com and could not be identified as a Windows .com file, it
1248 * will be assumed to be a DOS application, even if it was just random
1249 * data. If the program name does not end with .com, no such assumption
1252 * The Win32 function GetBinaryType incorrectly identifies any junk file
1253 * that ends with .exe as a dos executable and some executables that
1254 * don't end with .exe as not executable. Plus it doesn't exist under
1255 * win95, so I won't feel bad about reimplementing functionality.
1258 * The return value is one of APPL_DOS, APPL_WIN3X, or APPL_WIN32 if the
1259 * filename referred to the corresponding application type. If the file
1260 * name could not be found or did not refer to any known application
1261 * type, APPL_NONE is returned and an error message is left in interp.
1262 * .bat files are identified as APPL_DOS.
1267 *----------------------------------------------------------------------
1272 Tcl_Interp *interp, /* Interp, for error message. */
1273 const char *originalName, /* Name of the application to find. */
1274 char fullName[]) /* Filled with complete path to
1277 int applType, i, nameLen, found;
1283 IMAGE_DOS_HEADER header;
1284 Tcl_DString nameBuf, ds;
1285 const WCHAR *nativeName;
1286 WCHAR nativeFullPath[MAX_PATH];
1287 static const char extensions[][5] = {"", ".com", ".exe", ".bat", ".cmd"};
1290 * Look for the program as an external program. First try the name as it
1291 * is, then try adding .com, .exe, .bat and .cmd, in that order, to the name,
1292 * looking for an executable.
1294 * Using the raw SearchPathW() function doesn't do quite what is necessary.
1295 * If the name of the executable already contains a '.' character, it will
1296 * not try appending the specified extension when searching (in other
1297 * words, SearchPathW will not find the program "a.b.exe" if the arguments
1298 * specified "a.b" and ".exe"). So, first look for the file as it is
1299 * named. Then manually append the extensions, looking for a match.
1302 applType = APPL_NONE;
1303 Tcl_DStringInit(&nameBuf);
1304 Tcl_DStringAppend(&nameBuf, originalName, -1);
1305 nameLen = Tcl_DStringLength(&nameBuf);
1307 for (i = 0; i < (int) (sizeof(extensions) / sizeof(extensions[0])); i++) {
1308 Tcl_DStringSetLength(&nameBuf, nameLen);
1309 Tcl_DStringAppend(&nameBuf, extensions[i], -1);
1310 nativeName = (WCHAR *)Tcl_WinUtfToTChar(Tcl_DStringValue(&nameBuf),
1311 Tcl_DStringLength(&nameBuf), &ds);
1312 found = SearchPathW(NULL, nativeName, NULL, MAX_PATH,
1313 nativeFullPath, &rest);
1314 Tcl_DStringFree(&ds);
1320 * Ignore matches on directories or data files, return if identified a
1324 attr = GetFileAttributesW(nativeFullPath);
1325 if ((attr == 0xFFFFFFFF) || (attr & FILE_ATTRIBUTE_DIRECTORY)) {
1328 strcpy(fullName, Tcl_WinTCharToUtf((TCHAR *)nativeFullPath, -1, &ds));
1329 Tcl_DStringFree(&ds);
1331 ext = strrchr(fullName, '.');
1332 if ((ext != NULL) &&
1333 (strcasecmp(ext, ".cmd") == 0 || strcasecmp(ext, ".bat") == 0)) {
1334 applType = APPL_DOS;
1338 hFile = CreateFileW(nativeFullPath,
1339 GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
1340 FILE_ATTRIBUTE_NORMAL, NULL);
1341 if (hFile == INVALID_HANDLE_VALUE) {
1346 ReadFile(hFile, (void *) &header, sizeof(header), &read, NULL);
1347 if (header.e_magic != IMAGE_DOS_SIGNATURE) {
1349 * Doesn't have the magic number for relocatable executables. If
1350 * filename ends with .com, assume it's a DOS application anyhow.
1351 * Note that we didn't make this assumption at first, because some
1352 * supposed .com files are really 32-bit executables with all the
1353 * magic numbers and everything.
1357 if ((ext != NULL) && (strcasecmp(ext, ".com") == 0)) {
1358 applType = APPL_DOS;
1363 if (header.e_lfarlc != sizeof(header)) {
1365 * All Windows 3.X and Win32 and some DOS programs have this value
1366 * set here. If it doesn't, assume that since it already had the
1367 * other magic number it was a DOS application.
1371 applType = APPL_DOS;
1376 * The DWORD at header.e_lfanew points to yet another magic number.
1380 SetFilePointer(hFile, header.e_lfanew, NULL, FILE_BEGIN);
1381 ReadFile(hFile, (void *) buf, 2, &read, NULL);
1384 if ((buf[0] == 'N') && (buf[1] == 'E')) {
1385 applType = APPL_WIN3X;
1386 } else if ((buf[0] == 'P') && (buf[1] == 'E')) {
1387 applType = APPL_WIN32;
1390 * Strictly speaking, there should be a test that there is an 'L'
1391 * and 'E' at buf[0..1], to identify the type as DOS, but of
1392 * course we ran into a DOS executable that _doesn't_ have the
1393 * magic number - specifically, one compiled using the Lahey
1394 * Fortran90 compiler.
1397 applType = APPL_DOS;
1401 Tcl_DStringFree(&nameBuf);
1403 if (applType == APPL_NONE) {
1404 TclWinConvertError(GetLastError());
1405 Tcl_SetObjResult(interp, Tcl_ObjPrintf("couldn't execute \"%s\": %s",
1406 originalName, Tcl_PosixError(interp)));
1410 if (applType == APPL_WIN3X) {
1412 * Replace long path name of executable with short path name for
1413 * 16-bit applications. Otherwise the application may not be able to
1414 * correctly parse its own command line to separate off the
1415 * application name from the arguments.
1418 GetShortPathNameW(nativeFullPath, nativeFullPath, MAX_PATH);
1419 strcpy(fullName, Tcl_WinTCharToUtf((TCHAR *)nativeFullPath, -1, &ds));
1420 Tcl_DStringFree(&ds);
1426 *----------------------------------------------------------------------
1428 * BuildCommandLine --
1430 * The command line arguments are stored in linePtr separated by spaces,
1431 * in a form that CreateProcess() understands. Special characters in
1432 * individual arguments from argv[] must be quoted when being stored in
1441 *----------------------------------------------------------------------
1445 BuildCmdLineBypassBS(
1446 const char *current,
1450 * Mark first backslash position.
1458 } while (*current == '\\');
1463 QuoteCmdLineBackslash(
1466 const char *current,
1470 if (current > start) { /* part before current (special) */
1471 Tcl_DStringAppend(dsPtr, start, (int) (current - start));
1474 if (bspos > start) { /* part before first backslash */
1475 Tcl_DStringAppend(dsPtr, start, (int) (bspos - start));
1477 while (bspos++ < current) { /* each backslash twice */
1478 TclDStringAppendLiteral(dsPtr, "\\\\");
1487 const char *special,
1488 const char *specMetaChars,
1493 * Rest before special (before quote).
1496 QuoteCmdLineBackslash(dsPtr, start, special, NULL);
1500 * Rest before first backslash and backslashes into new quoted block.
1503 QuoteCmdLineBackslash(dsPtr, start, *bspos, NULL);
1508 * escape all special chars enclosed in quotes like `"..."`, note that
1509 * here we don't must escape `\` (with `\`), because it's outside of the
1510 * main quotes, so `\` remains `\`, but important - not at end of part,
1511 * because results as before the quote, so `%\%\` should be escaped as
1515 TclDStringAppendLiteral(dsPtr, "\""); /* opening escape quote-char */
1519 if (*special == '\\') {
1521 * Bypass backslashes (and mark first backslash position).
1524 special = BuildCmdLineBypassBS(special, bspos);
1525 if (*special == '\0') {
1529 } while (*special && strchr(specMetaChars, *special));
1532 * Unescaped rest before quote.
1535 QuoteCmdLineBackslash(dsPtr, start, special, NULL);
1538 * Unescaped rest before first backslash (rather belongs to the main
1542 QuoteCmdLineBackslash(dsPtr, start, *bspos, NULL);
1544 TclDStringAppendLiteral(dsPtr, "\""); /* closing escape quote-char */
1550 const char *executable, /* Full path of executable (including
1551 * extension). Replacement for argv[0]. */
1552 int argc, /* Number of arguments. */
1553 const char **argv, /* Argument strings in UTF. */
1554 Tcl_DString *linePtr) /* Initialized Tcl_DString that receives the
1555 * command line (WCHAR). */
1557 const char *arg, *start, *special, *bspos;
1560 static const char specMetaChars[] = "&|^<>!()%";
1561 /* Characters to enclose in quotes if unpaired
1562 * quote flag set. */
1563 static const char specMetaChars2[] = "%";
1564 /* Character to enclose in quotes in any case
1565 * (regardless of unpaired-flag). */
1568 * CL_ESCAPE - escape argument;
1569 * CL_QUOTE - enclose in quotes;
1570 * CL_UNPAIRED - previous arguments chain contains unpaired quote-char;
1572 enum {CL_ESCAPE = 1, CL_QUOTE = 2, CL_UNPAIRED = 4};
1574 Tcl_DStringInit(&ds);
1577 * Prime the path. Add a space separator if we were primed with something.
1580 TclDStringAppendDString(&ds, linePtr);
1581 if (Tcl_DStringLength(linePtr) > 0) {
1582 TclDStringAppendLiteral(&ds, " ");
1585 for (i = 0; i < argc; i++) {
1590 TclDStringAppendLiteral(&ds, " ");
1593 quote &= ~(CL_ESCAPE|CL_QUOTE); /* reset escape flags */
1595 if (arg[0] == '\0') {
1600 (quote & (CL_ESCAPE|CL_QUOTE)) != (CL_ESCAPE|CL_QUOTE);
1602 if (*start & 0x80) {
1605 if (TclIsSpaceProc(*start)) {
1606 quote |= CL_QUOTE; /* quote only */
1607 if (bspos) { /* if backslash found, escape & quote */
1613 if (strchr(specMetaChars, *start)) {
1614 quote |= (CL_ESCAPE|CL_QUOTE); /* escape & quote */
1617 if (*start == '"') {
1618 quote |= CL_ESCAPE; /* escape only */
1621 if (*start == '\\') {
1623 if (quote & CL_QUOTE) { /* if quote, escape & quote */
1632 if (quote & CL_QUOTE) {
1634 * Start of argument (main opening quote-char).
1637 TclDStringAppendLiteral(&ds, "\"");
1639 if (!(quote & CL_ESCAPE)) {
1641 * Nothing to escape.
1644 Tcl_DStringAppend(&ds, arg, -1);
1647 for (special = arg; *special != '\0'; ) {
1649 * Position of `\` is important before quote or at end (equal
1650 * `\"` because quoted).
1653 if (*special == '\\') {
1655 * Bypass backslashes (and mark first backslash position)
1658 special = BuildCmdLineBypassBS(special, &bspos);
1659 if (*special == '\0') {
1664 if (*special == '"') {
1666 * Invert the unpaired flag - observe unpaired quotes
1669 quote ^= CL_UNPAIRED;
1672 * Add part before (and escape backslashes before quote).
1675 QuoteCmdLineBackslash(&ds, start, special, bspos);
1679 * Escape using backslash
1682 TclDStringAppendLiteral(&ds, "\\\"");
1688 * Unpaired (escaped) quote causes special handling on
1692 if ((quote & CL_UNPAIRED) && strchr(specMetaChars, *special)) {
1693 special = QuoteCmdLinePart(&ds, start, special,
1694 specMetaChars, &bspos);
1697 * Start to current or first backslash
1700 start = !bspos ? special : bspos;
1705 * Special case for % - should be enclosed always (paired
1709 if (strchr(specMetaChars2, *special)) {
1710 special = QuoteCmdLinePart(&ds, start, special,
1711 specMetaChars2, &bspos);
1714 * Start to current or first backslash.
1717 start = !bspos ? special : bspos;
1722 * Other not special (and not meta) character
1725 bspos = NULL; /* reset last backslash position (not
1731 * Rest of argument (and escape backslashes before closing main
1735 QuoteCmdLineBackslash(&ds, start, special,
1736 (quote & CL_QUOTE) ? bspos : NULL);
1738 if (quote & CL_QUOTE) {
1740 * End of argument (main closing quote-char)
1743 TclDStringAppendLiteral(&ds, "\"");
1746 Tcl_DStringFree(linePtr);
1747 Tcl_WinUtfToTChar(Tcl_DStringValue(&ds), Tcl_DStringLength(&ds), linePtr);
1748 Tcl_DStringFree(&ds);
1752 *----------------------------------------------------------------------
1754 * TclpCreateCommandChannel --
1756 * This function is called by Tcl_OpenCommandChannel to perform the
1757 * platform specific channel initialization for a command channel.
1760 * Returns a new channel or NULL on failure.
1763 * Allocates a new channel.
1765 *----------------------------------------------------------------------
1769 TclpCreateCommandChannel(
1770 TclFile readFile, /* If non-null, gives the file for reading. */
1771 TclFile writeFile, /* If non-null, gives the file for writing. */
1772 TclFile errorFile, /* If non-null, gives the file where errors
1774 int numPids, /* The number of pids in the pid array. */
1775 Tcl_Pid *pidPtr) /* An array of process identifiers. */
1777 char channelName[16 + TCL_INTEGER_SPACE];
1778 PipeInfo *infoPtr = ckalloc(sizeof(PipeInfo));
1782 infoPtr->watchMask = 0;
1784 infoPtr->readFlags = 0;
1785 infoPtr->readFile = readFile;
1786 infoPtr->writeFile = writeFile;
1787 infoPtr->errorFile = errorFile;
1788 infoPtr->numPids = numPids;
1789 infoPtr->pidPtr = pidPtr;
1790 infoPtr->writeBuf = 0;
1791 infoPtr->writeBufLen = 0;
1792 infoPtr->writeError = 0;
1793 infoPtr->channel = NULL;
1795 infoPtr->validMask = 0;
1797 infoPtr->threadId = Tcl_GetCurrentThread();
1799 if (readFile != NULL) {
1801 * Start the background reader thread.
1804 infoPtr->readable = CreateEventW(NULL, TRUE, TRUE, NULL);
1805 infoPtr->readThread = CreateThread(NULL, 256, PipeReaderThread,
1806 TclPipeThreadCreateTI(&infoPtr->readTI, infoPtr, infoPtr->readable),
1808 SetThreadPriority(infoPtr->readThread, THREAD_PRIORITY_HIGHEST);
1809 infoPtr->validMask |= TCL_READABLE;
1811 infoPtr->readTI = NULL;
1812 infoPtr->readThread = 0;
1814 if (writeFile != NULL) {
1816 * Start the background writer thread.
1819 infoPtr->writable = CreateEventW(NULL, TRUE, TRUE, NULL);
1820 infoPtr->writeThread = CreateThread(NULL, 256, PipeWriterThread,
1821 TclPipeThreadCreateTI(&infoPtr->writeTI, infoPtr, infoPtr->writable),
1823 SetThreadPriority(infoPtr->writeThread, THREAD_PRIORITY_HIGHEST);
1824 infoPtr->validMask |= TCL_WRITABLE;
1826 infoPtr->writeTI = NULL;
1827 infoPtr->writeThread = 0;
1831 * For backward compatibility with previous versions of Tcl, we use
1832 * "file%d" as the base name for pipes even though it would be more
1833 * natural to use "pipe%d". Use the pointer to keep the channel names
1834 * unique, in case channels share handles (stdin/stdout).
1837 sprintf(channelName, "file%" TCL_Z_MODIFIER "x", (size_t) infoPtr);
1838 infoPtr->channel = Tcl_CreateChannel(&pipeChannelType, channelName,
1839 infoPtr, infoPtr->validMask);
1842 * Pipes have AUTO translation mode on Windows and ^Z eof char, which
1843 * means that a ^Z will be appended to them at close. This is needed for
1844 * Windows programs that expect a ^Z at EOF.
1847 Tcl_SetChannelOption(NULL, infoPtr->channel, "-translation", "auto");
1848 Tcl_SetChannelOption(NULL, infoPtr->channel, "-eofchar", "\032 {}");
1849 return infoPtr->channel;
1853 *----------------------------------------------------------------------
1857 * System dependent interface to create a pipe for the [chan pipe]
1858 * command. Stolen from TclX.
1861 * TCL_OK or TCL_ERROR.
1863 *----------------------------------------------------------------------
1868 Tcl_Interp *interp, /* Errors returned in result.*/
1869 Tcl_Channel *rchan, /* Where to return the read side. */
1870 Tcl_Channel *wchan, /* Where to return the write side. */
1871 int flags) /* Reserved for future use. */
1873 HANDLE readHandle, writeHandle;
1874 SECURITY_ATTRIBUTES sec;
1876 sec.nLength = sizeof(SECURITY_ATTRIBUTES);
1877 sec.lpSecurityDescriptor = NULL;
1878 sec.bInheritHandle = FALSE;
1880 if (!CreatePipe(&readHandle, &writeHandle, &sec, 0)) {
1881 TclWinConvertError(GetLastError());
1882 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1883 "pipe creation failed: %s", Tcl_PosixError(interp)));
1887 *rchan = Tcl_MakeFileChannel((ClientData) readHandle, TCL_READABLE);
1888 Tcl_RegisterChannel(interp, *rchan);
1890 *wchan = Tcl_MakeFileChannel((ClientData) writeHandle, TCL_WRITABLE);
1891 Tcl_RegisterChannel(interp, *wchan);
1897 *----------------------------------------------------------------------
1899 * TclGetAndDetachPids --
1901 * Stores a list of the command PIDs for a command channel in the
1908 * Modifies the interp's result.
1910 *----------------------------------------------------------------------
1914 TclGetAndDetachPids(
1919 const Tcl_ChannelType *chanTypePtr;
1924 * Punt if the channel is not a command channel.
1927 chanTypePtr = Tcl_GetChannelType(chan);
1928 if (chanTypePtr != &pipeChannelType) {
1932 pipePtr = Tcl_GetChannelInstanceData(chan);
1934 for (i = 0; i < pipePtr->numPids; i++) {
1935 Tcl_ListObjAppendElement(NULL, pidsObj,
1936 Tcl_NewWideIntObj((unsigned)
1937 TclpGetPid(pipePtr->pidPtr[i])));
1938 Tcl_DetachPids(1, &pipePtr->pidPtr[i]);
1940 Tcl_SetObjResult(interp, pidsObj);
1941 if (pipePtr->numPids > 0) {
1942 ckfree(pipePtr->pidPtr);
1943 pipePtr->numPids = 0;
1948 *----------------------------------------------------------------------
1950 * PipeBlockModeProc --
1952 * Set blocking or non-blocking mode on channel.
1955 * 0 if successful, errno when failed.
1958 * Sets the device into blocking or non-blocking mode.
1960 *----------------------------------------------------------------------
1965 ClientData instanceData, /* Instance data for channel. */
1966 int mode) /* TCL_MODE_BLOCKING or
1967 * TCL_MODE_NONBLOCKING. */
1969 PipeInfo *infoPtr = (PipeInfo *) instanceData;
1972 * Pipes on Windows can not be switched between blocking and nonblocking,
1973 * hence we have to emulate the behavior. This is done in the input
1974 * function by checking against a bit in the state. We set or unset the
1975 * bit here to cause the input function to emulate the correct behavior.
1978 if (mode == TCL_MODE_NONBLOCKING) {
1979 infoPtr->flags |= PIPE_ASYNC;
1981 infoPtr->flags &= ~(PIPE_ASYNC);
1987 *----------------------------------------------------------------------
1991 * Closes a pipe based IO channel.
1994 * 0 on success, errno otherwise.
1997 * Closes the physical channel.
1999 *----------------------------------------------------------------------
2004 ClientData instanceData, /* Pointer to PipeInfo structure. */
2005 Tcl_Interp *interp, /* For error reporting. */
2006 int flags) /* Flags that indicate which side to close. */
2008 PipeInfo *pipePtr = (PipeInfo *) instanceData;
2009 Tcl_Channel errChan;
2010 int errorCode, result;
2011 PipeInfo *infoPtr, **nextPtrPtr;
2012 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
2013 int inExit = (TclInExit() || TclInThreadExit());
2018 if ((!flags || flags & TCL_CLOSE_READ) && (pipePtr->readFile != NULL)) {
2020 * Clean up the background thread if necessary. Note that this must be
2021 * done before we can close the file, since the thread may be blocking
2022 * trying to read from the pipe.
2025 if (pipePtr->readThread) {
2027 TclPipeThreadStop(&pipePtr->readTI, pipePtr->readThread);
2028 CloseHandle(pipePtr->readThread);
2029 CloseHandle(pipePtr->readable);
2030 pipePtr->readThread = NULL;
2032 if (TclpCloseFile(pipePtr->readFile) != 0) {
2035 pipePtr->validMask &= ~TCL_READABLE;
2036 pipePtr->readFile = NULL;
2038 if ((!flags || flags & TCL_CLOSE_WRITE) && (pipePtr->writeFile != NULL)) {
2039 if (pipePtr->writeThread) {
2042 * Wait for the writer thread to finish the current buffer, then
2043 * terminate the thread and close the handles. If the channel is
2044 * nonblocking or may block during exit, bail out since the worker
2045 * thread is not interruptible and we want TIP#398-fast-exit.
2047 if ((pipePtr->flags & PIPE_ASYNC) && inExit) {
2049 /* give it a chance to leave honorably */
2050 TclPipeThreadStopSignal(&pipePtr->writeTI, pipePtr->writable);
2052 if (WaitForSingleObject(pipePtr->writable, 20) == WAIT_TIMEOUT) {
2058 WaitForSingleObject(pipePtr->writable, inExit ? 5000 : INFINITE);
2062 TclPipeThreadStop(&pipePtr->writeTI, pipePtr->writeThread);
2064 CloseHandle(pipePtr->writable);
2065 CloseHandle(pipePtr->writeThread);
2066 pipePtr->writeThread = NULL;
2068 if (TclpCloseFile(pipePtr->writeFile) != 0) {
2069 if (errorCode == 0) {
2073 pipePtr->validMask &= ~TCL_WRITABLE;
2074 pipePtr->writeFile = NULL;
2077 pipePtr->watchMask &= pipePtr->validMask;
2080 * Don't free the channel if any of the flags were set.
2088 * Remove the file from the list of watched files.
2091 for (nextPtrPtr = &(tsdPtr->firstPipePtr), infoPtr = *nextPtrPtr;
2093 nextPtrPtr = &infoPtr->nextPtr, infoPtr = *nextPtrPtr) {
2094 if (infoPtr == (PipeInfo *)pipePtr) {
2095 *nextPtrPtr = infoPtr->nextPtr;
2100 if ((pipePtr->flags & PIPE_ASYNC) || inExit) {
2102 * If the channel is non-blocking or Tcl is being cleaned up, just
2103 * detach the children PIDs, reap them (important if we are in a
2104 * dynamic load module), and discard the errorFile.
2107 Tcl_DetachPids(pipePtr->numPids, pipePtr->pidPtr);
2108 Tcl_ReapDetachedProcs();
2110 if (pipePtr->errorFile) {
2111 if (TclpCloseFile(pipePtr->errorFile) != 0) {
2112 if (errorCode == 0) {
2120 * Wrap the error file into a channel and give it to the cleanup
2124 if (pipePtr->errorFile) {
2125 WinFile *filePtr = (WinFile *) pipePtr->errorFile;
2127 errChan = Tcl_MakeFileChannel((ClientData) filePtr->handle,
2134 result = TclCleanupChildren(interp, pipePtr->numPids,
2135 pipePtr->pidPtr, errChan);
2138 if (pipePtr->numPids > 0) {
2139 ckfree(pipePtr->pidPtr);
2142 if (pipePtr->writeBuf != NULL) {
2143 ckfree(pipePtr->writeBuf);
2148 if (errorCode == 0) {
2155 *----------------------------------------------------------------------
2159 * Reads input from the IO channel into the buffer given. Returns count
2160 * of how many bytes were actually read, and an error indication.
2163 * A count of how many bytes were read is returned and an error
2164 * indication is returned in an output argument.
2167 * Reads input from the actual channel.
2169 *----------------------------------------------------------------------
2174 ClientData instanceData, /* Pipe state. */
2175 char *buf, /* Where to store data read. */
2176 int bufSize, /* How much space is available in the
2178 int *errorCode) /* Where to store error code. */
2180 PipeInfo *infoPtr = (PipeInfo *) instanceData;
2181 WinFile *filePtr = (WinFile*) infoPtr->readFile;
2182 DWORD count, bytesRead = 0;
2187 * Synchronize with the reader thread.
2190 result = WaitForRead(infoPtr, (infoPtr->flags & PIPE_ASYNC) ? 0 : 1);
2193 * If an error occurred, return immediately.
2201 if (infoPtr->readFlags & PIPE_EXTRABYTE) {
2203 * The reader thread consumed 1 byte as a side effect of waiting so we
2204 * need to move it into the buffer.
2207 *buf = infoPtr->extraByte;
2208 infoPtr->readFlags &= ~PIPE_EXTRABYTE;
2214 * If further read attempts would block, return what we have.
2223 * Attempt to read bufSize bytes. The read will return immediately if
2224 * there is any data available. Otherwise it will block until at least one
2225 * byte is available or an EOF occurs.
2228 if (ReadFile(filePtr->handle, (LPVOID) buf, (DWORD) bufSize, &count,
2229 (LPOVERLAPPED) NULL) == TRUE) {
2230 return bytesRead + count;
2231 } else if (bytesRead) {
2233 * Ignore errors if we have data to return.
2239 TclWinConvertError(GetLastError());
2240 if (errno == EPIPE) {
2241 infoPtr->readFlags |= PIPE_EOF;
2249 *----------------------------------------------------------------------
2253 * Writes the given output on the IO channel. Returns count of how many
2254 * characters were actually written, and an error indication.
2257 * A count of how many characters were written is returned and an error
2258 * indication is returned in an output argument.
2261 * Writes output on the actual channel.
2263 *----------------------------------------------------------------------
2268 ClientData instanceData, /* Pipe state. */
2269 const char *buf, /* The data buffer. */
2270 int toWrite, /* How many bytes to write? */
2271 int *errorCode) /* Where to store error code. */
2273 PipeInfo *infoPtr = (PipeInfo *) instanceData;
2274 WinFile *filePtr = (WinFile*) infoPtr->writeFile;
2275 DWORD bytesWritten, timeout;
2279 /* avoid blocking if pipe-thread exited */
2280 timeout = ((infoPtr->flags & PIPE_ASYNC)
2281 || !TclPipeThreadIsAlive(&infoPtr->writeTI)
2282 || TclInExit() || TclInThreadExit()) ? 0 : INFINITE;
2283 if (WaitForSingleObject(infoPtr->writable, timeout) == WAIT_TIMEOUT) {
2285 * The writer thread is blocked waiting for a write to complete and
2286 * the channel is in non-blocking mode.
2289 errno = EWOULDBLOCK;
2294 * Check for a background error on the last write.
2297 if (infoPtr->writeError) {
2298 TclWinConvertError(infoPtr->writeError);
2299 infoPtr->writeError = 0;
2303 if (infoPtr->flags & PIPE_ASYNC) {
2305 * The pipe is non-blocking, so copy the data into the output buffer
2306 * and restart the writer thread.
2309 if (toWrite > infoPtr->writeBufLen) {
2311 * Reallocate the buffer to be large enough to hold the data.
2314 if (infoPtr->writeBuf) {
2315 ckfree(infoPtr->writeBuf);
2317 infoPtr->writeBufLen = toWrite;
2318 infoPtr->writeBuf = ckalloc(toWrite);
2320 memcpy(infoPtr->writeBuf, buf, toWrite);
2321 infoPtr->toWrite = toWrite;
2322 ResetEvent(infoPtr->writable);
2323 TclPipeThreadSignal(&infoPtr->writeTI);
2324 bytesWritten = toWrite;
2327 * In the blocking case, just try to write the buffer directly. This
2328 * avoids an unnecessary copy.
2331 if (WriteFile(filePtr->handle, (LPVOID) buf, (DWORD) toWrite,
2332 &bytesWritten, (LPOVERLAPPED) NULL) == FALSE) {
2333 TclWinConvertError(GetLastError());
2337 return bytesWritten;
2346 *----------------------------------------------------------------------
2350 * This function is invoked by Tcl_ServiceEvent when a file event reaches
2351 * the front of the event queue. This function invokes Tcl_NotifyChannel
2355 * Returns 1 if the event was handled, meaning it should be removed from
2356 * the queue. Returns 0 if the event was not handled, meaning it should
2357 * stay on the queue. The only time the event isn't handled is if the
2358 * TCL_FILE_EVENTS flag bit isn't set.
2361 * Whatever the notifier callback does.
2363 *----------------------------------------------------------------------
2368 Tcl_Event *evPtr, /* Event to service. */
2369 int flags) /* Flags that indicate what events to
2370 * handle, such as TCL_FILE_EVENTS. */
2372 PipeEvent *pipeEvPtr = (PipeEvent *)evPtr;
2375 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
2377 if (!(flags & TCL_FILE_EVENTS)) {
2382 * Search through the list of watched pipes for the one whose handle
2383 * matches the event. We do this rather than simply dereferencing the
2384 * handle in the event so that pipes can be deleted while the event is in
2388 for (infoPtr = tsdPtr->firstPipePtr; infoPtr != NULL;
2389 infoPtr = infoPtr->nextPtr) {
2390 if (pipeEvPtr->infoPtr == infoPtr) {
2391 infoPtr->flags &= ~(PIPE_PENDING);
2397 * Remove stale events.
2405 * Check to see if the pipe is readable. Note that we can't tell if a pipe
2406 * is writable, so we always report it as being writable unless we have
2411 if ((infoPtr->watchMask & TCL_WRITABLE) &&
2412 (WaitForSingleObject(infoPtr->writable, 0) != WAIT_TIMEOUT)) {
2413 mask = TCL_WRITABLE;
2416 if ((infoPtr->watchMask & TCL_READABLE) && (WaitForRead(infoPtr,0) >= 0)) {
2417 if (infoPtr->readFlags & PIPE_EOF) {
2418 mask = TCL_READABLE;
2420 mask |= TCL_READABLE;
2425 * Inform the channel of the events.
2428 Tcl_NotifyChannel(infoPtr->channel, infoPtr->watchMask & mask);
2433 *----------------------------------------------------------------------
2437 * Called by the notifier to set up to watch for events on this channel.
2445 *----------------------------------------------------------------------
2450 ClientData instanceData, /* Pipe state. */
2451 int mask) /* What events to watch for, OR-ed combination
2452 * of TCL_READABLE, TCL_WRITABLE and
2455 PipeInfo **nextPtrPtr, *ptr;
2456 PipeInfo *infoPtr = (PipeInfo *) instanceData;
2457 int oldMask = infoPtr->watchMask;
2458 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
2461 * Since most of the work is handled by the background threads, we just
2462 * need to update the watchMask and then force the notifier to poll once.
2465 infoPtr->watchMask = mask & infoPtr->validMask;
2466 if (infoPtr->watchMask) {
2467 Tcl_Time blockTime = { 0, 0 };
2470 infoPtr->nextPtr = tsdPtr->firstPipePtr;
2471 tsdPtr->firstPipePtr = infoPtr;
2473 Tcl_SetMaxBlockTime(&blockTime);
2477 * Remove the pipe from the list of watched pipes.
2480 for (nextPtrPtr = &(tsdPtr->firstPipePtr), ptr = *nextPtrPtr;
2482 nextPtrPtr = &ptr->nextPtr, ptr = *nextPtrPtr) {
2483 if (infoPtr == ptr) {
2484 *nextPtrPtr = ptr->nextPtr;
2493 *----------------------------------------------------------------------
2495 * PipeGetHandleProc --
2497 * Called from Tcl_GetChannelHandle to retrieve OS handles from inside a
2498 * command pipeline based channel.
2501 * Returns TCL_OK with the fd in handlePtr, or TCL_ERROR if there is no
2502 * handle for the specified direction.
2507 *----------------------------------------------------------------------
2512 ClientData instanceData, /* The pipe state. */
2513 int direction, /* TCL_READABLE or TCL_WRITABLE */
2514 ClientData *handlePtr) /* Where to store the handle. */
2516 PipeInfo *infoPtr = (PipeInfo *) instanceData;
2519 if (direction == TCL_READABLE && infoPtr->readFile) {
2520 filePtr = (WinFile*) infoPtr->readFile;
2521 *handlePtr = (ClientData) filePtr->handle;
2524 if (direction == TCL_WRITABLE && infoPtr->writeFile) {
2525 filePtr = (WinFile*) infoPtr->writeFile;
2526 *handlePtr = (ClientData) filePtr->handle;
2533 *----------------------------------------------------------------------
2537 * Emulates the waitpid system call.
2540 * Returns 0 if the process is still alive, -1 on an error, or the pid on
2544 * Unless WNOHANG is set and the wait times out, the process information
2545 * record will be deleted and the process handle will be closed.
2547 *----------------------------------------------------------------------
2556 ProcInfo *infoPtr = NULL, **prevPtrPtr;
2559 DWORD ret, exitCode;
2564 * If no pid is specified, do nothing.
2573 * Find the process and cut it from the process list.
2576 Tcl_MutexLock(&pipeMutex);
2577 prevPtrPtr = &procList;
2578 for (infoPtr = procList; infoPtr != NULL;
2579 prevPtrPtr = &infoPtr->nextPtr, infoPtr = infoPtr->nextPtr) {
2580 if (infoPtr->hProcess == (HANDLE) pid) {
2581 *prevPtrPtr = infoPtr->nextPtr;
2585 Tcl_MutexUnlock(&pipeMutex);
2588 * If the pid is not one of the processes we know about (we started it)
2592 if (infoPtr == NULL) {
2598 * Officially "wait" for it to finish. We either poll (WNOHANG) or wait
2599 * for an infinite amount of time.
2602 if (options & WNOHANG) {
2607 ret = WaitForSingleObject(infoPtr->hProcess, flags);
2608 if (ret == WAIT_TIMEOUT) {
2610 if (options & WNOHANG) {
2612 * Re-insert this infoPtr back on the list.
2615 Tcl_MutexLock(&pipeMutex);
2616 infoPtr->nextPtr = procList;
2618 Tcl_MutexUnlock(&pipeMutex);
2623 } else if (ret == WAIT_OBJECT_0) {
2624 GetExitCodeProcess(infoPtr->hProcess, &exitCode);
2627 * Does the exit code look like one of the exception codes?
2631 case EXCEPTION_FLT_DENORMAL_OPERAND:
2632 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
2633 case EXCEPTION_FLT_INEXACT_RESULT:
2634 case EXCEPTION_FLT_INVALID_OPERATION:
2635 case EXCEPTION_FLT_OVERFLOW:
2636 case EXCEPTION_FLT_STACK_CHECK:
2637 case EXCEPTION_FLT_UNDERFLOW:
2638 case EXCEPTION_INT_DIVIDE_BY_ZERO:
2639 case EXCEPTION_INT_OVERFLOW:
2640 *statPtr = 0xC0000000 | SIGFPE;
2643 case EXCEPTION_PRIV_INSTRUCTION:
2644 case EXCEPTION_ILLEGAL_INSTRUCTION:
2645 *statPtr = 0xC0000000 | SIGILL;
2648 case EXCEPTION_ACCESS_VIOLATION:
2649 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
2650 case EXCEPTION_STACK_OVERFLOW:
2651 case EXCEPTION_NONCONTINUABLE_EXCEPTION:
2652 case EXCEPTION_INVALID_DISPOSITION:
2653 case EXCEPTION_GUARD_PAGE:
2654 case EXCEPTION_INVALID_HANDLE:
2655 *statPtr = 0xC0000000 | SIGSEGV;
2658 case EXCEPTION_DATATYPE_MISALIGNMENT:
2659 *statPtr = 0xC0000000 | SIGBUS;
2662 case EXCEPTION_BREAKPOINT:
2663 case EXCEPTION_SINGLE_STEP:
2664 *statPtr = 0xC0000000 | SIGTRAP;
2667 case CONTROL_C_EXIT:
2668 *statPtr = 0xC0000000 | SIGINT;
2673 * Non-exceptional, normal, exit code. Note that the exit code is
2674 * truncated to a signed short range [-32768,32768) whether it
2675 * fits into this range or not.
2677 * BUG: Even though the exit code is a DWORD, it is understood by
2678 * convention to be a signed integer, yet there isn't enough room
2679 * to fit this into the POSIX style waitstatus mask without
2683 *statPtr = exitCode;
2689 *statPtr = 0xC0000000 | ECHILD;
2690 result = (Tcl_Pid) -1;
2694 * Officially close the process handle.
2697 CloseHandle(infoPtr->hProcess);
2704 *----------------------------------------------------------------------
2706 * TclWinAddProcess --
2708 * Add a process to the process list so that we can use Tcl_WaitPid on
2715 * Adds the specified process handle to the process list so Tcl_WaitPid
2718 *----------------------------------------------------------------------
2723 void *hProcess, /* Handle to process */
2724 unsigned long id) /* Global process identifier */
2726 ProcInfo *procPtr = ckalloc(sizeof(ProcInfo));
2730 procPtr->hProcess = hProcess;
2731 procPtr->dwProcessId = id;
2732 Tcl_MutexLock(&pipeMutex);
2733 procPtr->nextPtr = procList;
2735 Tcl_MutexUnlock(&pipeMutex);
2739 *----------------------------------------------------------------------
2743 * This function is invoked to process the "pid" Tcl command. See the
2744 * user documentation for details on what it does.
2747 * A standard Tcl result.
2750 * See the user documentation.
2752 *----------------------------------------------------------------------
2757 ClientData dummy, /* Not used. */
2758 Tcl_Interp *interp, /* Current interpreter. */
2759 int objc, /* Number of arguments. */
2760 Tcl_Obj *const *objv) /* Argument strings. */
2763 const Tcl_ChannelType *chanTypePtr;
2769 Tcl_WrongNumArgs(interp, 1, objv, "?channelId?");
2773 Tcl_SetObjResult(interp, Tcl_NewWideIntObj((unsigned) getpid()));
2775 chan = Tcl_GetChannel(interp, Tcl_GetString(objv[1]),
2777 if (chan == (Tcl_Channel) NULL) {
2780 chanTypePtr = Tcl_GetChannelType(chan);
2781 if (chanTypePtr != &pipeChannelType) {
2785 pipePtr = (PipeInfo *) Tcl_GetChannelInstanceData(chan);
2786 TclNewObj(resultPtr);
2787 for (i = 0; i < pipePtr->numPids; i++) {
2788 Tcl_ListObjAppendElement(/*interp*/ NULL, resultPtr,
2789 Tcl_NewWideIntObj((unsigned)
2790 TclpGetPid(pipePtr->pidPtr[i])));
2792 Tcl_SetObjResult(interp, resultPtr);
2798 *----------------------------------------------------------------------
2802 * Wait until some data is available, the pipe is at EOF or the reader
2803 * thread is blocked waiting for data (if the channel is in non-blocking
2807 * Returns 1 if pipe is readable. Returns 0 if there is no data on the
2808 * pipe, but there is buffered data. Returns -1 if an error occurred. If
2809 * an error occurred, the threads may not be synchronized.
2812 * Updates the shared state flags and may consume 1 byte of data from the
2813 * pipe. If no error occurred, the reader thread is blocked waiting for a
2814 * signal from the main thread.
2816 *----------------------------------------------------------------------
2821 PipeInfo *infoPtr, /* Pipe state. */
2822 int blocking) /* Indicates whether call should be blocking
2825 DWORD timeout, count;
2826 HANDLE *handle = ((WinFile *) infoPtr->readFile)->handle;
2830 * Synchronize with the reader thread.
2833 /* avoid blocking if pipe-thread exited */
2834 timeout = (!blocking || !TclPipeThreadIsAlive(&infoPtr->readTI)
2835 || TclInExit() || TclInThreadExit()) ? 0 : INFINITE;
2836 if (WaitForSingleObject(infoPtr->readable, timeout) == WAIT_TIMEOUT) {
2838 * The reader thread is blocked waiting for data and the channel
2839 * is in non-blocking mode.
2842 errno = EWOULDBLOCK;
2847 * At this point, the two threads are synchronized, so it is safe to
2848 * access shared state.
2852 * If the pipe has hit EOF, it is always readable.
2855 if (infoPtr->readFlags & PIPE_EOF) {
2860 * Check to see if there is any data sitting in the pipe.
2863 if (PeekNamedPipe(handle, (LPVOID) NULL, (DWORD) 0,
2864 (LPDWORD) NULL, &count, (LPDWORD) NULL) != TRUE) {
2865 TclWinConvertError(GetLastError());
2868 * Check to see if the peek failed because of EOF.
2871 if (errno == EPIPE) {
2872 infoPtr->readFlags |= PIPE_EOF;
2877 * Ignore errors if there is data in the buffer.
2880 if (infoPtr->readFlags & PIPE_EXTRABYTE) {
2888 * We found some data in the pipe, so it must be readable.
2896 * The pipe isn't readable, but there is some data sitting in the
2897 * buffer, so return immediately.
2900 if (infoPtr->readFlags & PIPE_EXTRABYTE) {
2905 * There wasn't any data available, so reset the thread and try again.
2908 ResetEvent(infoPtr->readable);
2909 TclPipeThreadSignal(&infoPtr->readTI);
2914 *----------------------------------------------------------------------
2916 * PipeReaderThread --
2918 * This function runs in a separate thread and waits for input to become
2919 * available on a pipe.
2925 * Signals the main thread when input become available. May cause the
2926 * main thread to wake up by posting a message. May consume one byte from
2927 * the pipe for each wait operation. Will cause a memory leak of ~4k, if
2928 * forcefully terminated with TerminateThread().
2930 *----------------------------------------------------------------------
2937 TclPipeThreadInfo *pipeTI = (TclPipeThreadInfo *) arg;
2938 PipeInfo *infoPtr = NULL; /* access info only after success init/wait */
2939 HANDLE handle = NULL;
2945 * Wait for the main thread to signal before attempting to wait on the
2946 * pipe becoming readable.
2949 if (!TclPipeThreadWaitForSignal(&pipeTI)) {
2955 infoPtr = (PipeInfo *) pipeTI->clientData;
2956 handle = ((WinFile *) infoPtr->readFile)->handle;
2960 * Try waiting for 0 bytes. This will block until some data is
2961 * available on NT, but will return immediately on Win 95. So, if no
2962 * data is available after the first read, we block until we can read
2963 * a single byte off of the pipe.
2966 if (ReadFile(handle, NULL, 0, &count, NULL) == FALSE ||
2967 PeekNamedPipe(handle, NULL, 0, NULL, &count, NULL) == FALSE) {
2969 * The error is a result of an EOF condition, so set the EOF bit
2970 * before signalling the main thread.
2973 err = GetLastError();
2974 if (err == ERROR_BROKEN_PIPE) {
2975 infoPtr->readFlags |= PIPE_EOF;
2977 } else if (err == ERROR_INVALID_HANDLE) {
2980 } else if (count == 0) {
2981 if (ReadFile(handle, &(infoPtr->extraByte), 1, &count, NULL)
2984 * One byte was consumed as a side effect of waiting for the
2985 * pipe to become readable.
2988 infoPtr->readFlags |= PIPE_EXTRABYTE;
2990 err = GetLastError();
2991 if (err == ERROR_BROKEN_PIPE) {
2993 * The error is a result of an EOF condition, so set the
2994 * EOF bit before signalling the main thread.
2997 infoPtr->readFlags |= PIPE_EOF;
2999 } else if (err == ERROR_INVALID_HANDLE) {
3006 * Signal the main thread by signalling the readable event and then
3007 * waking up the notifier thread.
3010 SetEvent(infoPtr->readable);
3013 * Alert the foreground thread. Note that we need to treat this like a
3014 * critical section so the foreground thread does not terminate this
3015 * thread while we are holding a mutex in the notifier code.
3018 Tcl_MutexLock(&pipeMutex);
3019 if (infoPtr->threadId != NULL) {
3021 * TIP #218. When in flight ignore the event, no one will receive
3025 Tcl_ThreadAlert(infoPtr->threadId);
3027 Tcl_MutexUnlock(&pipeMutex);
3031 * If state of thread was set to stop, we can sane free info structure,
3032 * otherwise it is shared with main thread, so main thread will own it
3034 TclPipeThreadExit(&pipeTI);
3040 *----------------------------------------------------------------------
3042 * PipeWriterThread --
3044 * This function runs in a separate thread and writes data onto a pipe.
3050 * Signals the main thread when an output operation is completed. May
3051 * cause the main thread to wake up by posting a message.
3053 *----------------------------------------------------------------------
3060 TclPipeThreadInfo *pipeTI = (TclPipeThreadInfo *)arg;
3061 PipeInfo *infoPtr = NULL; /* access info only after success init/wait */
3062 HANDLE handle = NULL;
3063 DWORD count, toWrite;
3069 * Wait for the main thread to signal before attempting to write.
3071 if (!TclPipeThreadWaitForSignal(&pipeTI)) {
3077 infoPtr = (PipeInfo *)pipeTI->clientData;
3078 handle = ((WinFile *) infoPtr->writeFile)->handle;
3081 buf = infoPtr->writeBuf;
3082 toWrite = infoPtr->toWrite;
3085 * Loop until all of the bytes are written or an error occurs.
3088 while (toWrite > 0) {
3089 if (WriteFile(handle, buf, toWrite, &count, NULL) == FALSE) {
3090 infoPtr->writeError = GetLastError();
3100 * Signal the main thread by signalling the writable event and then
3101 * waking up the notifier thread.
3104 SetEvent(infoPtr->writable);
3107 * Alert the foreground thread. Note that we need to treat this like a
3108 * critical section so the foreground thread does not terminate this
3109 * thread while we are holding a mutex in the notifier code.
3112 Tcl_MutexLock(&pipeMutex);
3113 if (infoPtr->threadId != NULL) {
3115 * TIP #218. When in flight ignore the event, no one will receive
3119 Tcl_ThreadAlert(infoPtr->threadId);
3121 Tcl_MutexUnlock(&pipeMutex);
3125 * If state of thread was set to stop, we can sane free info structure,
3126 * otherwise it is shared with main thread, so main thread will own it.
3128 TclPipeThreadExit(&pipeTI);
3134 *----------------------------------------------------------------------
3136 * PipeThreadActionProc --
3138 * Insert or remove any thread local refs to this channel.
3144 * Changes thread local list of valid channels.
3146 *----------------------------------------------------------------------
3150 PipeThreadActionProc(
3151 ClientData instanceData,
3154 PipeInfo *infoPtr = (PipeInfo *) instanceData;
3157 * We do not access firstPipePtr in the thread structures. This is not for
3158 * all pipes managed by the thread, but only those we are watching.
3159 * Removal of the filevent handlers before transfer thus takes care of
3163 Tcl_MutexLock(&pipeMutex);
3164 if (action == TCL_CHANNEL_THREAD_INSERT) {
3166 * We can't copy the thread information from the channel when the
3167 * channel is created. At this time the channel back pointer has not
3168 * been set yet. However in that case the threadId has already been
3169 * set by TclpCreateCommandChannel itself, so the structure is still
3174 if (infoPtr->channel != NULL) {
3175 infoPtr->threadId = Tcl_GetChannelThread(infoPtr->channel);
3178 infoPtr->threadId = NULL;
3180 Tcl_MutexUnlock(&pipeMutex);
3184 *----------------------------------------------------------------------
3186 * TclpOpenTemporaryFile --
3188 * Creates a temporary file, possibly based on the supplied bits and
3189 * pieces of template supplied in the first three arguments. If the
3190 * fourth argument is non-NULL, it contains a Tcl_Obj to store the name
3191 * of the temporary file in (and it is caller's responsibility to clean
3192 * up). If the fourth argument is NULL, try to arrange for the temporary
3193 * file to go away once it is no longer needed.
3196 * A read-write Tcl Channel open on the file.
3198 *----------------------------------------------------------------------
3202 TclpOpenTemporaryFile(
3204 Tcl_Obj *basenameObj,
3205 Tcl_Obj *extensionObj,
3206 Tcl_Obj *resultingNameObj)
3208 WCHAR name[MAX_PATH];
3211 DWORD flags = FILE_ATTRIBUTE_TEMPORARY;
3212 int length, counter, counter2;
3215 if (!resultingNameObj) {
3216 flags |= FILE_FLAG_DELETE_ON_CLOSE;
3219 namePtr = (char *) name;
3220 length = GetTempPathW(MAX_PATH, name);
3224 namePtr += length * sizeof(WCHAR);
3226 const char *string = Tcl_GetString(basenameObj);
3228 Tcl_WinUtfToTChar(string, basenameObj->length, &buf);
3229 memcpy(namePtr, Tcl_DStringValue(&buf), Tcl_DStringLength(&buf));
3230 namePtr += Tcl_DStringLength(&buf);
3231 Tcl_DStringFree(&buf);
3233 const WCHAR *baseStr = L"TCL";
3234 length = 3 * sizeof(WCHAR);
3236 memcpy(namePtr, baseStr, length);
3239 counter = TclpGetClicks() % 65533;
3240 counter2 = 1024; /* Only try this many times! Prevents
3241 * an infinite loop. */
3244 char number[TCL_INTEGER_SPACE + 4];
3246 sprintf(number, "%d.TMP", counter);
3247 counter = (unsigned short) (counter + 1);
3248 Tcl_WinUtfToTChar(number, strlen(number), &buf);
3249 Tcl_DStringSetLength(&buf, Tcl_DStringLength(&buf) + 1);
3250 memcpy(namePtr, Tcl_DStringValue(&buf), Tcl_DStringLength(&buf) + 1);
3251 Tcl_DStringFree(&buf);
3253 handle = CreateFileW(name,
3254 GENERIC_READ|GENERIC_WRITE, 0, NULL, CREATE_NEW, flags, NULL);
3255 } while (handle == INVALID_HANDLE_VALUE
3257 && GetLastError() == ERROR_FILE_EXISTS);
3258 if (handle == INVALID_HANDLE_VALUE) {
3262 if (resultingNameObj) {
3263 Tcl_Obj *tmpObj = TclpNativeToNormalized(name);
3265 Tcl_AppendObjToObj(resultingNameObj, tmpObj);
3266 TclDecrRefCount(tmpObj);
3269 return Tcl_MakeFileChannel((ClientData) handle,
3270 TCL_READABLE|TCL_WRITABLE);
3273 TclWinConvertError(GetLastError());
3278 *----------------------------------------------------------------------
3280 * TclPipeThreadCreateTI --
3282 * Creates a thread info structure, can be owned by worker.
3285 * Pointer to created TI structure.
3287 *----------------------------------------------------------------------
3291 TclPipeThreadCreateTI(
3292 TclPipeThreadInfo **pipeTIPtr,
3293 ClientData clientData,
3296 TclPipeThreadInfo *pipeTI;
3297 #ifndef _PTI_USE_CKALLOC
3298 pipeTI = malloc(sizeof(TclPipeThreadInfo));
3300 pipeTI = ckalloc(sizeof(TclPipeThreadInfo));
3301 #endif /* !_PTI_USE_CKALLOC */
3302 pipeTI->evControl = CreateEventW(NULL, FALSE, FALSE, NULL);
3303 pipeTI->state = PTI_STATE_IDLE;
3304 pipeTI->clientData = clientData;
3305 pipeTI->evWakeUp = wakeEvent;
3306 return (*pipeTIPtr = pipeTI);
3310 *----------------------------------------------------------------------
3312 * TclPipeThreadWaitForSignal --
3314 * Wait for work/stop signals inside pipe worker.
3317 * 1 if signaled to work, 0 if signaled to stop.
3320 * If this function returns 0, TI-structure pointer given via pipeTIPtr
3321 * may be NULL, so not accessible (can be owned by main thread).
3323 *----------------------------------------------------------------------
3327 TclPipeThreadWaitForSignal(
3328 TclPipeThreadInfo **pipeTIPtr)
3330 TclPipeThreadInfo *pipeTI = *pipeTIPtr;
3339 wakeEvent = pipeTI->evWakeUp;
3342 * Wait for the main thread to signal before attempting to do the work.
3346 * Reset work state of thread (idle/waiting)
3349 state = InterlockedCompareExchange(&pipeTI->state, PTI_STATE_IDLE,
3351 if (state & (PTI_STATE_STOP|PTI_STATE_END)) {
3353 * End of work, check the owner of structure.
3363 waitResult = WaitForSingleObject(pipeTI->evControl, INFINITE);
3364 if (waitResult != WAIT_OBJECT_0) {
3366 * The control event was not signaled, so end of work (unexpected
3367 * behaviour, main thread can be dead?).
3374 * Try to set work state of thread
3377 state = InterlockedCompareExchange(&pipeTI->state, PTI_STATE_WORK,
3379 if (state & (PTI_STATE_STOP|PTI_STATE_END)) {
3395 * End of work, check the owner of the TI structure.
3398 if (state != PTI_STATE_STOP) {
3401 pipeTI->evWakeUp = NULL;
3404 SetEvent(wakeEvent);
3410 *----------------------------------------------------------------------
3412 * TclPipeThreadStopSignal --
3414 * Send stop signal to the pipe worker (without waiting).
3416 * After calling of this function, TI-structure pointer given via pipeTIPtr
3420 * 1 if signaled (or pipe-thread is down), 0 if pipe thread still working.
3422 *----------------------------------------------------------------------
3426 TclPipeThreadStopSignal(
3427 TclPipeThreadInfo **pipeTIPtr,
3430 TclPipeThreadInfo *pipeTI = *pipeTIPtr;
3437 evControl = pipeTI->evControl;
3438 pipeTI->evWakeUp = wakeEvent;
3439 state = InterlockedCompareExchange(&pipeTI->state, PTI_STATE_STOP,
3442 case PTI_STATE_IDLE:
3444 * Thread was idle/waiting, notify it goes teardown
3447 SetEvent(evControl);
3450 case PTI_STATE_DOWN:
3455 * Thread works currently, we should try to end it, own the TI
3456 * structure (because of possible sharing the joint structures with
3460 InterlockedExchange(&pipeTI->state, PTI_STATE_END);
3468 *----------------------------------------------------------------------
3470 * TclPipeThreadStop --
3472 * Send stop signal to the pipe worker and wait for thread completion.
3474 * May be combined with TclPipeThreadStopSignal.
3476 * After calling of this function, TI-structure pointer given via pipeTIPtr
3477 * is not accessible (owned by pipe worker or released here).
3483 * Can terminate pipe worker (and / or stop its synchronous operations).
3485 *----------------------------------------------------------------------
3490 TclPipeThreadInfo **pipeTIPtr,
3493 TclPipeThreadInfo *pipeTI = *pipeTIPtr;
3500 pipeTI = *pipeTIPtr;
3501 evControl = pipeTI->evControl;
3502 pipeTI->evWakeUp = NULL;
3505 * Try to sane stop the pipe worker, corresponding its current state
3508 state = InterlockedCompareExchange(&pipeTI->state, PTI_STATE_STOP,
3511 case PTI_STATE_IDLE:
3513 * Thread was idle/waiting, notify it goes teardown
3516 SetEvent(evControl);
3519 * We don't need to wait for it at all, thread frees himself (owns the
3526 case PTI_STATE_STOP:
3528 * Already stopped, thread frees himself (owns the TI structure)
3533 case PTI_STATE_DOWN:
3535 * Thread already down (?), do nothing
3539 * We don't need to wait for it, but we should free pipeTI
3544 /* case PTI_STATE_WORK: */
3547 * Thread works currently, we should try to end it, own the TI
3548 * structure (because of possible sharing the joint structures with
3552 state = InterlockedCompareExchange(&pipeTI->state, PTI_STATE_END,
3554 if (state == PTI_STATE_DOWN) {
3556 * We don't need to wait for it, but we should free pipeTI
3563 if (pipeTI && hThread) {
3567 * The thread may already have closed on its own. Check its exit
3571 GetExitCodeThread(hThread, &exitCode);
3573 if (exitCode == STILL_ACTIVE) {
3574 int inExit = (TclInExit() || TclInThreadExit());
3577 * Set the stop event so that if the pipe thread is blocked
3578 * somewhere, it may hereafter sane exit cleanly.
3581 SetEvent(evControl);
3584 * Cancel all sync-IO of this thread (may be blocked there).
3587 if (tclWinProcs.cancelSynchronousIo) {
3588 tclWinProcs.cancelSynchronousIo(hThread);
3592 * Wait at most 20 milliseconds for the reader thread to close
3593 * (regarding TIP#398-fast-exit).
3597 * If we want TIP#398-fast-exit.
3600 if (WaitForSingleObject(hThread, inExit ? 0 : 20) == WAIT_TIMEOUT) {
3602 * The thread must be blocked waiting for the pipe to become
3603 * readable in ReadFile(). There isn't a clean way to exit the
3604 * thread from this condition. We should terminate the child
3605 * process instead to get the reader thread to fall out of
3606 * ReadFile with a FALSE. (below) is not the correct way to do
3607 * this, but will stay here until a better solution is found.
3609 * Note that we need to guard against terminating the thread
3610 * while it is in the middle of Tcl_ThreadAlert because it
3611 * won't be able to release the notifier lock.
3613 * Also note that terminating threads during their
3614 * initialization or teardown phase may result in ntdll.dll's
3615 * LoaderLock to remain locked indefinitely. This causes
3616 * ntdll.dll's LdrpInitializeThread() to deadlock trying to
3617 * acquire LoaderLock. LdrpInitializeThread() is executed
3618 * within new threads to perform initialization and to execute
3619 * DllMain() of all loaded dlls. As a result, all new threads
3620 * are deadlocked in their initialization phase and never
3621 * execute, even though CreateThread() reports successful
3622 * thread creation. This results in a very weird process-wide
3623 * behavior, which is extremely hard to debug.
3625 * THREADS SHOULD NEVER BE TERMINATED. Period.
3627 * But for now, check if thread is exiting, and if so, let it
3630 * Also don't terminate if in exit (otherwise deadlocked in
3634 if (pipeTI->state != PTI_STATE_DOWN
3635 && WaitForSingleObject(hThread,
3636 inExit ? 50 : 5000) != WAIT_OBJECT_0) {
3637 /* BUG: this leaks memory */
3638 if (inExit || !TerminateThread(hThread, 0)) {
3640 * in exit or terminate fails, just give thread a
3644 if (InterlockedExchange(&pipeTI->state,
3645 PTI_STATE_STOP) != PTI_STATE_DOWN) {
3656 if (pipeTI->evWakeUp) {
3657 SetEvent(pipeTI->evWakeUp);
3659 CloseHandle(pipeTI->evControl);
3660 #ifndef _PTI_USE_CKALLOC
3664 #endif /* !_PTI_USE_CKALLOC */
3669 *----------------------------------------------------------------------
3671 * TclPipeThreadExit --
3673 * Clean-up for the pipe thread (removes owned TI-structure in worker).
3675 * Should be executed on worker exit, to inform the main thread or
3676 * free TI-structure (if owned).
3678 * After calling of this function, TI-structure pointer given via pipeTIPtr
3679 * is not accessible (owned by main thread or released here).
3684 *----------------------------------------------------------------------
3689 TclPipeThreadInfo **pipeTIPtr)
3692 TclPipeThreadInfo *pipeTI = *pipeTIPtr;
3695 * If state of thread was set to stop (exactly), we can sane free its info
3696 * structure, otherwise it is shared with main thread, so main thread will
3704 state = InterlockedExchange(&pipeTI->state, PTI_STATE_DOWN);
3705 if (state == PTI_STATE_STOP) {
3706 CloseHandle(pipeTI->evControl);
3707 if (pipeTI->evWakeUp) {
3708 SetEvent(pipeTI->evWakeUp);
3710 #ifndef _PTI_USE_CKALLOC
3714 /* be sure all subsystems used are finalized */
3715 Tcl_FinalizeThread();
3716 #endif /* !_PTI_USE_CKALLOC */