1 /*
2  * tclWinPipe.c --
3  *
4  *	This file implements the Windows-specific exec pipeline functions,
5  *	the "pipe" channel driver, and the "pid" Tcl command.
6  *
7  * Copyright (c) 1996-1997 by Sun Microsystems, Inc.
8  *
9  * See the file "license.terms" for information on usage and redistribution
10  * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
11  *
12  * RCS: @(#) $Id: tclWinPipe.c,v 1.33.2.5 2003/10/21 22:57:18 andreas_kupries Exp $
13  */
14 
15 #include "tclWinInt.h"
16 
17 #include <fcntl.h>
18 #include <io.h>
19 #include <sys/stat.h>
20 
21 /*
22  * The following variable is used to tell whether this module has been
23  * initialized.
24  */
25 
26 static int initialized = 0;
27 
28 /*
29  * The pipeMutex locks around access to the initialized and procList variables,
30  * and it is used to protect background threads from being terminated while
31  * they are using APIs that hold locks.
32  */
33 
34 TCL_DECLARE_MUTEX(pipeMutex)
35 
36 /*
37  * The following defines identify the various types of applications that
38  * run under windows.  There is special case code for the various types.
39  */
40 
41 #define APPL_NONE	0
42 #define APPL_DOS	1
43 #define APPL_WIN3X	2
44 #define APPL_WIN32	3
45 
46 /*
47  * The following constants and structures are used to encapsulate the state
48  * of various types of files used in a pipeline.
49  * This used to have a 1 && 2 that supported Win32s.
50  */
51 
52 #define WIN_FILE 3		/* Basic Win32 file. */
53 
54 /*
55  * This structure encapsulates the common state associated with all file
56  * types used in a pipeline.
57  */
58 
59 typedef struct WinFile {
60     int type;			/* One of the file types defined above. */
61     HANDLE handle;		/* Open file handle. */
62 } WinFile;
63 
64 /*
65  * This list is used to map from pids to process handles.
66  */
67 
68 typedef struct ProcInfo {
69     HANDLE hProcess;
70     DWORD dwProcessId;
71     struct ProcInfo *nextPtr;
72 } ProcInfo;
73 
74 static ProcInfo *procList;
75 
76 /*
77  * Bit masks used in the flags field of the PipeInfo structure below.
78  */
79 
80 #define PIPE_PENDING	(1<<0)	/* Message is pending in the queue. */
81 #define PIPE_ASYNC	(1<<1)	/* Channel is non-blocking. */
82 
83 /*
84  * Bit masks used in the sharedFlags field of the PipeInfo structure below.
85  */
86 
87 #define PIPE_EOF	(1<<2)	/* Pipe has reached EOF. */
88 #define PIPE_EXTRABYTE	(1<<3)	/* The reader thread has consumed one byte. */
89 
90 /*
91  * This structure describes per-instance data for a pipe based channel.
92  */
93 
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
111 				 * threads. */
112     HANDLE writeThread;		/* Handle to writer thread. */
113     HANDLE readThread;		/* Handle to reader thread. */
114     HANDLE writable;		/* Manual-reset event to signal when the
115 				 * writer thread has finished waiting for
116 				 * the current buffer to be written. */
117     HANDLE readable;		/* Manual-reset event to signal when the
118 				 * reader thread has finished waiting for
119 				 * input. */
120     HANDLE startWriter;		/* Auto-reset event used by the main thread to
121 				 * signal when the writer thread should attempt
122 				 * to write to the pipe. */
123     HANDLE stopWriter;		/* Manual-reset event used to alert the reader
124 				 * thread to fall-out and exit */
125     HANDLE startReader;		/* Auto-reset event used by the main thread to
126 				 * signal when the reader thread should attempt
127 				 * to read from the pipe. */
128     HANDLE stopReader;		/* Manual-reset event used to alert the reader
129 				 * thread to fall-out and exit */
130     DWORD writeError;		/* An error caused by the last background
131 				 * write.  Set to 0 if no error has been
132 				 * detected.  This word is shared with the
133 				 * writer thread so access must be
134 				 * synchronized with the writable object.
135 				 */
136     char *writeBuf;		/* Current background output buffer.
137 				 * Access is synchronized with the writable
138 				 * object. */
139     int writeBufLen;		/* Size of write buffer.  Access is
140 				 * synchronized with the writable
141 				 * object. */
142     int toWrite;		/* Current amount to be written.  Access is
143 				 * synchronized with the writable object. */
144     int readFlags;		/* Flags that are shared with the reader
145 				 * thread.  Access is synchronized with the
146 				 * readable object.  */
147     char extraByte;		/* Buffer for extra character consumed by
148 				 * reader thread.  This byte is shared with
149 				 * the reader thread so access must be
150 				 * synchronized with the readable object. */
151 } PipeInfo;
152 
153 typedef struct ThreadSpecificData {
154     /*
155      * The following pointer refers to the head of the list of pipes
156      * that are being watched for file events.
157      */
158 
159     PipeInfo *firstPipePtr;
160 } ThreadSpecificData;
161 
162 static Tcl_ThreadDataKey dataKey;
163 
164 /*
165  * The following structure is what is added to the Tcl event queue when
166  * pipe events are generated.
167  */
168 
169 typedef struct PipeEvent {
170     Tcl_Event header;		/* Information that is standard for
171 				 * all events. */
172     PipeInfo *infoPtr;		/* Pointer to pipe info structure.  Note
173 				 * that we still have to verify that the
174 				 * pipe exists before dereferencing this
175 				 * pointer. */
176 } PipeEvent;
177 
178 /*
179  * Declarations for functions used only in this file.
180  */
181 
182 static int		ApplicationType(Tcl_Interp *interp,
183 			    const char *fileName, char *fullName);
184 static void		BuildCommandLine(const char *executable, int argc,
185 			    CONST char **argv, Tcl_DString *linePtr);
186 static BOOL		HasConsole(void);
187 static int		PipeBlockModeProc(ClientData instanceData, int mode);
188 static void		PipeCheckProc(ClientData clientData, int flags);
189 static int		PipeClose2Proc(ClientData instanceData,
190 			    Tcl_Interp *interp, int flags);
191 static int		PipeEventProc(Tcl_Event *evPtr, int flags);
192 static void		PipeExitHandler(ClientData clientData);
193 static int		PipeGetHandleProc(ClientData instanceData,
194 			    int direction, ClientData *handlePtr);
195 static void		PipeInit(void);
196 static int		PipeInputProc(ClientData instanceData, char *buf,
197 			    int toRead, int *errorCode);
198 static int		PipeOutputProc(ClientData instanceData,
199 			    CONST char *buf, int toWrite, int *errorCode);
200 static DWORD WINAPI	PipeReaderThread(LPVOID arg);
201 static void		PipeSetupProc(ClientData clientData, int flags);
202 static void		PipeWatchProc(ClientData instanceData, int mask);
203 static DWORD WINAPI	PipeWriterThread(LPVOID arg);
204 static void		ProcExitHandler(ClientData clientData);
205 static int		TempFileName(WCHAR name[MAX_PATH]);
206 static int		WaitForRead(PipeInfo *infoPtr, int blocking);
207 
208 /*
209  * This structure describes the channel type structure for command pipe
210  * based IO.
211  */
212 
213 static Tcl_ChannelType pipeChannelType = {
214     "pipe",			/* Type name. */
215     TCL_CHANNEL_VERSION_2,	/* v2 channel */
216     TCL_CLOSE2PROC,		/* Close proc. */
217     PipeInputProc,		/* Input proc. */
218     PipeOutputProc,		/* Output proc. */
219     NULL,			/* Seek proc. */
220     NULL,			/* Set option proc. */
221     NULL,			/* Get option proc. */
222     PipeWatchProc,		/* Set up notifier to watch the channel. */
223     PipeGetHandleProc,		/* Get an OS handle from channel. */
224     PipeClose2Proc,		/* close2proc */
225     PipeBlockModeProc,		/* Set blocking or non-blocking mode.*/
226     NULL,			/* flush proc. */
227     NULL,			/* handler proc. */
228 };
229 
230 /*
231  *----------------------------------------------------------------------
232  *
233  * PipeInit --
234  *
235  *	This function initializes the static variables for this file.
236  *
237  * Results:
238  *	None.
239  *
240  * Side effects:
241  *	Creates a new event source.
242  *
243  *----------------------------------------------------------------------
244  */
245 
246 static void
PipeInit()247 PipeInit()
248 {
249     ThreadSpecificData *tsdPtr;
250 
251     /*
252      * Check the initialized flag first, then check again in the mutex.
253      * This is a speed enhancement.
254      */
255 
256     if (!initialized) {
257 	Tcl_MutexLock(&pipeMutex);
258 	if (!initialized) {
259 	    initialized = 1;
260 	    procList = NULL;
261 	    Tcl_CreateExitHandler(ProcExitHandler, NULL);
262 	}
263 	Tcl_MutexUnlock(&pipeMutex);
264     }
265 
266     tsdPtr = (ThreadSpecificData *)TclThreadDataKeyGet(&dataKey);
267     if (tsdPtr == NULL) {
268 	tsdPtr = TCL_TSD_INIT(&dataKey);
269 	tsdPtr->firstPipePtr = NULL;
270 	Tcl_CreateEventSource(PipeSetupProc, PipeCheckProc, NULL);
271 	Tcl_CreateThreadExitHandler(PipeExitHandler, NULL);
272     }
273 }
274 
275 /*
276  *----------------------------------------------------------------------
277  *
278  * PipeExitHandler --
279  *
280  *	This function is called to cleanup the pipe module before
281  *	Tcl is unloaded.
282  *
283  * Results:
284  *	None.
285  *
286  * Side effects:
287  *	Removes the pipe event source.
288  *
289  *----------------------------------------------------------------------
290  */
291 
292 static void
PipeExitHandler(ClientData clientData)293 PipeExitHandler(
294     ClientData clientData)	/* Old window proc */
295 {
296     Tcl_DeleteEventSource(PipeSetupProc, PipeCheckProc, NULL);
297 }
298 
299 /*
300  *----------------------------------------------------------------------
301  *
302  * ProcExitHandler --
303  *
304  *	This function is called to cleanup the process list before
305  *	Tcl is unloaded.
306  *
307  * Results:
308  *	None.
309  *
310  * Side effects:
311  *	Resets the process list.
312  *
313  *----------------------------------------------------------------------
314  */
315 
316 static void
ProcExitHandler(ClientData clientData)317 ProcExitHandler(
318     ClientData clientData)	/* Old window proc */
319 {
320     Tcl_MutexLock(&pipeMutex);
321     initialized = 0;
322     Tcl_MutexUnlock(&pipeMutex);
323 }
324 
325 /*
326  *----------------------------------------------------------------------
327  *
328  * PipeSetupProc --
329  *
330  *	This procedure is invoked before Tcl_DoOneEvent blocks waiting
331  *	for an event.
332  *
333  * Results:
334  *	None.
335  *
336  * Side effects:
337  *	Adjusts the block time if needed.
338  *
339  *----------------------------------------------------------------------
340  */
341 
342 void
PipeSetupProc(ClientData data,int flags)343 PipeSetupProc(
344     ClientData data,		/* Not used. */
345     int flags)			/* Event flags as passed to Tcl_DoOneEvent. */
346 {
347     PipeInfo *infoPtr;
348     Tcl_Time blockTime = { 0, 0 };
349     int block = 1;
350     WinFile *filePtr;
351     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
352 
353     if (!(flags & TCL_FILE_EVENTS)) {
354 	return;
355     }
356 
357     /*
358      * Look to see if any events are already pending.  If they are, poll.
359      */
360 
361     for (infoPtr = tsdPtr->firstPipePtr; infoPtr != NULL;
362 	    infoPtr = infoPtr->nextPtr) {
363 	if (infoPtr->watchMask & TCL_WRITABLE) {
364 	    filePtr = (WinFile*) infoPtr->writeFile;
365 	    if (WaitForSingleObject(infoPtr->writable, 0) != WAIT_TIMEOUT) {
366 		block = 0;
367 	    }
368 	}
369 	if (infoPtr->watchMask & TCL_READABLE) {
370 	    filePtr = (WinFile*) infoPtr->readFile;
371 	    if (WaitForRead(infoPtr, 0) >= 0) {
372 		block = 0;
373 	    }
374 	}
375     }
376     if (!block) {
377 	Tcl_SetMaxBlockTime(&blockTime);
378     }
379 }
380 
381 /*
382  *----------------------------------------------------------------------
383  *
384  * PipeCheckProc --
385  *
386  *	This procedure is called by Tcl_DoOneEvent to check the pipe
387  *	event source for events.
388  *
389  * Results:
390  *	None.
391  *
392  * Side effects:
393  *	May queue an event.
394  *
395  *----------------------------------------------------------------------
396  */
397 
398 static void
PipeCheckProc(ClientData data,int flags)399 PipeCheckProc(
400     ClientData data,		/* Not used. */
401     int flags)			/* Event flags as passed to Tcl_DoOneEvent. */
402 {
403     PipeInfo *infoPtr;
404     PipeEvent *evPtr;
405     WinFile *filePtr;
406     int needEvent;
407     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
408 
409     if (!(flags & TCL_FILE_EVENTS)) {
410 	return;
411     }
412 
413     /*
414      * Queue events for any ready pipes that don't already have events
415      * queued.
416      */
417 
418     for (infoPtr = tsdPtr->firstPipePtr; infoPtr != NULL;
419 	    infoPtr = infoPtr->nextPtr) {
420 	if (infoPtr->flags & PIPE_PENDING) {
421 	    continue;
422 	}
423 
424 	/*
425 	 * Queue an event if the pipe is signaled for reading or writing.
426 	 */
427 
428 	needEvent = 0;
429 	filePtr = (WinFile*) infoPtr->writeFile;
430 	if ((infoPtr->watchMask & TCL_WRITABLE) &&
431 		(WaitForSingleObject(infoPtr->writable, 0) != WAIT_TIMEOUT)) {
432 	    needEvent = 1;
433 	}
434 
435 	filePtr = (WinFile*) infoPtr->readFile;
436 	if ((infoPtr->watchMask & TCL_READABLE) &&
437 		(WaitForRead(infoPtr, 0) >= 0)) {
438 	    needEvent = 1;
439 	}
440 
441 	if (needEvent) {
442 	    infoPtr->flags |= PIPE_PENDING;
443 	    evPtr = (PipeEvent *) ckalloc(sizeof(PipeEvent));
444 	    evPtr->header.proc = PipeEventProc;
445 	    evPtr->infoPtr = infoPtr;
446 	    Tcl_QueueEvent((Tcl_Event *) evPtr, TCL_QUEUE_TAIL);
447 	}
448     }
449 }
450 
451 /*
452  *----------------------------------------------------------------------
453  *
454  * TclWinMakeFile --
455  *
456  *	This function constructs a new TclFile from a given data and
457  *	type value.
458  *
459  * Results:
460  *	Returns a newly allocated WinFile as a TclFile.
461  *
462  * Side effects:
463  *	None.
464  *
465  *----------------------------------------------------------------------
466  */
467 
468 TclFile
TclWinMakeFile(HANDLE handle)469 TclWinMakeFile(
470     HANDLE handle)		/* Type-specific data. */
471 {
472     WinFile *filePtr;
473 
474     filePtr = (WinFile *) ckalloc(sizeof(WinFile));
475     filePtr->type = WIN_FILE;
476     filePtr->handle = handle;
477 
478     return (TclFile)filePtr;
479 }
480 
481 /*
482  *----------------------------------------------------------------------
483  *
484  * TempFileName --
485  *
486  *	Gets a temporary file name and deals with the fact that the
487  *	temporary file path provided by Windows may not actually exist
488  *	if the TMP or TEMP environment variables refer to a
489  *	non-existent directory.
490  *
491  * Results:
492  *	0 if error, non-zero otherwise.  If non-zero is returned, the
493  *	name buffer will be filled with a name that can be used to
494  *	construct a temporary file.
495  *
496  * Side effects:
497  *	None.
498  *
499  *----------------------------------------------------------------------
500  */
501 
502 static int
TempFileName(name)503 TempFileName(name)
504     WCHAR name[MAX_PATH];	/* Buffer in which name for temporary
505 				 * file gets stored. */
506 {
507     TCHAR *prefix;
508 
509     prefix = (tclWinProcs->useWide) ? (TCHAR *) L"TCL" : (TCHAR *) "TCL";
510     if ((*tclWinProcs->getTempPathProc)(MAX_PATH, name) != 0) {
511 	if ((*tclWinProcs->getTempFileNameProc)((TCHAR *) name, prefix, 0,
512 		name) != 0) {
513 	    return 1;
514 	}
515     }
516     if (tclWinProcs->useWide) {
517 	((WCHAR *) name)[0] = '.';
518 	((WCHAR *) name)[1] = '\0';
519     } else {
520 	((char *) name)[0] = '.';
521 	((char *) name)[1] = '\0';
522     }
523     return (*tclWinProcs->getTempFileNameProc)((TCHAR *) name, prefix, 0,
524 	    name);
525 }
526 
527 /*
528  *----------------------------------------------------------------------
529  *
530  * TclpMakeFile --
531  *
532  *	Make a TclFile from a channel.
533  *
534  * Results:
535  *	Returns a new TclFile or NULL on failure.
536  *
537  * Side effects:
538  *	None.
539  *
540  *----------------------------------------------------------------------
541  */
542 
543 TclFile
TclpMakeFile(channel,direction)544 TclpMakeFile(channel, direction)
545     Tcl_Channel channel;	/* Channel to get file from. */
546     int direction;		/* Either TCL_READABLE or TCL_WRITABLE. */
547 {
548     HANDLE handle;
549 
550     if (Tcl_GetChannelHandle(channel, direction,
551 	    (ClientData *) &handle) == TCL_OK) {
552 	return TclWinMakeFile(handle);
553     } else {
554 	return (TclFile) NULL;
555     }
556 }
557 
558 /*
559  *----------------------------------------------------------------------
560  *
561  * TclpOpenFile --
562  *
563  *	This function opens files for use in a pipeline.
564  *
565  * Results:
566  *	Returns a newly allocated TclFile structure containing the
567  *	file handle.
568  *
569  * Side effects:
570  *	None.
571  *
572  *----------------------------------------------------------------------
573  */
574 
575 TclFile
TclpOpenFile(path,mode)576 TclpOpenFile(path, mode)
577     CONST char *path;		/* The name of the file to open. */
578     int mode;			/* In what mode to open the file? */
579 {
580     HANDLE handle;
581     DWORD accessMode, createMode, shareMode, flags;
582     Tcl_DString ds;
583     CONST TCHAR *nativePath;
584 
585     /*
586      * Map the access bits to the NT access mode.
587      */
588 
589     switch (mode & (O_RDONLY | O_WRONLY | O_RDWR)) {
590 	case O_RDONLY:
591 	    accessMode = GENERIC_READ;
592 	    break;
593 	case O_WRONLY:
594 	    accessMode = GENERIC_WRITE;
595 	    break;
596 	case O_RDWR:
597 	    accessMode = (GENERIC_READ | GENERIC_WRITE);
598 	    break;
599 	default:
600 	    TclWinConvertError(ERROR_INVALID_FUNCTION);
601 	    return NULL;
602     }
603 
604     /*
605      * Map the creation flags to the NT create mode.
606      */
607 
608     switch (mode & (O_CREAT | O_EXCL | O_TRUNC)) {
609 	case (O_CREAT | O_EXCL):
610 	case (O_CREAT | O_EXCL | O_TRUNC):
611 	    createMode = CREATE_NEW;
612 	    break;
613 	case (O_CREAT | O_TRUNC):
614 	    createMode = CREATE_ALWAYS;
615 	    break;
616 	case O_CREAT:
617 	    createMode = OPEN_ALWAYS;
618 	    break;
619 	case O_TRUNC:
620 	case (O_TRUNC | O_EXCL):
621 	    createMode = TRUNCATE_EXISTING;
622 	    break;
623 	default:
624 	    createMode = OPEN_EXISTING;
625 	    break;
626     }
627 
628     nativePath = Tcl_WinUtfToTChar(path, -1, &ds);
629 
630     /*
631      * If the file is not being created, use the existing file attributes.
632      */
633 
634     flags = 0;
635     if (!(mode & O_CREAT)) {
636 	flags = (*tclWinProcs->getFileAttributesProc)(nativePath);
637 	if (flags == 0xFFFFFFFF) {
638 	    flags = 0;
639 	}
640     }
641 
642     /*
643      * Set up the file sharing mode.  We want to allow simultaneous access.
644      */
645 
646     shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
647 
648     /*
649      * Now we get to create the file.
650      */
651 
652     handle = (*tclWinProcs->createFileProc)(nativePath, accessMode,
653 	    shareMode, NULL, createMode, flags, NULL);
654     Tcl_DStringFree(&ds);
655 
656     if (handle == INVALID_HANDLE_VALUE) {
657 	DWORD err;
658 
659 	err = GetLastError();
660 	if ((err & 0xffffL) == ERROR_OPEN_FAILED) {
661 	    err = (mode & O_CREAT) ? ERROR_FILE_EXISTS : ERROR_FILE_NOT_FOUND;
662 	}
663         TclWinConvertError(err);
664         return NULL;
665     }
666 
667     /*
668      * Seek to the end of file if we are writing.
669      */
670 
671     if (mode & O_WRONLY) {
672 	SetFilePointer(handle, 0, NULL, FILE_END);
673     }
674 
675     return TclWinMakeFile(handle);
676 }
677 
678 /*
679  *----------------------------------------------------------------------
680  *
681  * TclpCreateTempFile --
682  *
683  *	This function opens a unique file with the property that it
684  *	will be deleted when its file handle is closed.  The temporary
685  *	file is created in the system temporary directory.
686  *
687  * Results:
688  *	Returns a valid TclFile, or NULL on failure.
689  *
690  * Side effects:
691  *	Creates a new temporary file.
692  *
693  *----------------------------------------------------------------------
694  */
695 
696 TclFile
TclpCreateTempFile(contents)697 TclpCreateTempFile(contents)
698     CONST char *contents;	/* String to write into temp file, or NULL. */
699 {
700     WCHAR name[MAX_PATH];
701     CONST char *native;
702     Tcl_DString dstring;
703     HANDLE handle;
704 
705     if (TempFileName(name) == 0) {
706 	return NULL;
707     }
708 
709     handle = (*tclWinProcs->createFileProc)((TCHAR *) name,
710 	    GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
711 	    FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE, NULL);
712     if (handle == INVALID_HANDLE_VALUE) {
713 	goto error;
714     }
715 
716     /*
717      * Write the file out, doing line translations on the way.
718      */
719 
720     if (contents != NULL) {
721 	DWORD result, length;
722 	CONST char *p;
723 
724 	/*
725 	 * Convert the contents from UTF to native encoding
726 	 */
727 	native = Tcl_UtfToExternalDString(NULL, contents, -1, &dstring);
728 
729 	for (p = native; *p != '\0'; p++) {
730 	    if (*p == '\n') {
731 		length = p - native;
732 		if (length > 0) {
733 		    if (!WriteFile(handle, native, length, &result, NULL)) {
734 			goto error;
735 		    }
736 		}
737 		if (!WriteFile(handle, "\r\n", 2, &result, NULL)) {
738 		    goto error;
739 		}
740 		native = p+1;
741 	    }
742 	}
743 	length = p - native;
744 	if (length > 0) {
745 	    if (!WriteFile(handle, native, length, &result, NULL)) {
746 		goto error;
747 	    }
748 	}
749 	Tcl_DStringFree(&dstring);
750 	if (SetFilePointer(handle, 0, NULL, FILE_BEGIN) == 0xFFFFFFFF) {
751 	    goto error;
752 	}
753     }
754 
755     return TclWinMakeFile(handle);
756 
757   error:
758     /* Free the native representation of the contents if necessary */
759     if (contents != NULL) {
760 	Tcl_DStringFree(&dstring);
761     }
762 
763     TclWinConvertError(GetLastError());
764     CloseHandle(handle);
765     (*tclWinProcs->deleteFileProc)((TCHAR *) name);
766     return NULL;
767 }
768 
769 /*
770  *----------------------------------------------------------------------
771  *
772  * TclpTempFileName --
773  *
774  *	This function returns a unique filename.
775  *
776  * Results:
777  *	Returns a valid Tcl_Obj* with refCount 0, or NULL on failure.
778  *
779  * Side effects:
780  *	None.
781  *
782  *----------------------------------------------------------------------
783  */
784 
785 Tcl_Obj*
TclpTempFileName()786 TclpTempFileName()
787 {
788     WCHAR fileName[MAX_PATH];
789 
790     if (TempFileName(fileName) == 0) {
791 	return NULL;
792     }
793 
794     return TclpNativeToNormalized((ClientData) fileName);
795 }
796 
797 /*
798  *----------------------------------------------------------------------
799  *
800  * TclpCreatePipe --
801  *
802  *      Creates an anonymous pipe.
803  *
804  * Results:
805  *      Returns 1 on success, 0 on failure.
806  *
807  * Side effects:
808  *      Creates a pipe.
809  *
810  *----------------------------------------------------------------------
811  */
812 
813 int
TclpCreatePipe(TclFile * readPipe,TclFile * writePipe)814 TclpCreatePipe(
815     TclFile *readPipe,	/* Location to store file handle for
816 				 * read side of pipe. */
817     TclFile *writePipe)	/* Location to store file handle for
818 				 * write side of pipe. */
819 {
820     HANDLE readHandle, writeHandle;
821 
822     if (CreatePipe(&readHandle, &writeHandle, NULL, 0) != 0) {
823 	*readPipe = TclWinMakeFile(readHandle);
824 	*writePipe = TclWinMakeFile(writeHandle);
825 	return 1;
826     }
827 
828     TclWinConvertError(GetLastError());
829     return 0;
830 }
831 
832 /*
833  *----------------------------------------------------------------------
834  *
835  * TclpCloseFile --
836  *
837  *	Closes a pipeline file handle.  These handles are created by
838  *	TclpOpenFile, TclpCreatePipe, or TclpMakeFile.
839  *
840  * Results:
841  *	0 on success, -1 on failure.
842  *
843  * Side effects:
844  *	The file is closed and deallocated.
845  *
846  *----------------------------------------------------------------------
847  */
848 
849 int
TclpCloseFile(TclFile file)850 TclpCloseFile(
851     TclFile file)	/* The file to close. */
852 {
853     WinFile *filePtr = (WinFile *) file;
854 
855     switch (filePtr->type) {
856 	case WIN_FILE:
857 	    /*
858 	     * Don't close the Win32 handle if the handle is a standard channel
859 	     * during the thread exit process.  Otherwise, one thread may kill
860 	     * the stdio of another.
861 	     */
862 
863 	    if (!TclInThreadExit()
864 		    || ((GetStdHandle(STD_INPUT_HANDLE) != filePtr->handle)
865 			    && (GetStdHandle(STD_OUTPUT_HANDLE) != filePtr->handle)
866 			    && (GetStdHandle(STD_ERROR_HANDLE) != filePtr->handle))) {
867 		if (filePtr->handle != NULL &&
868 			CloseHandle(filePtr->handle) == FALSE) {
869 		    TclWinConvertError(GetLastError());
870 		    ckfree((char *) filePtr);
871 		    return -1;
872 		}
873 	    }
874 	    break;
875 
876 	default:
877 	    panic("TclpCloseFile: unexpected file type");
878     }
879 
880     ckfree((char *) filePtr);
881     return 0;
882 }
883 
884 /*
885  *--------------------------------------------------------------------------
886  *
887  * TclpGetPid --
888  *
889  *	Given a HANDLE to a child process, return the process id for that
890  *	child process.
891  *
892  * Results:
893  *	Returns the process id for the child process.  If the pid was not
894  *	known by Tcl, either because the pid was not created by Tcl or the
895  *	child process has already been reaped, -1 is returned.
896  *
897  * Side effects:
898  *	None.
899  *
900  *--------------------------------------------------------------------------
901  */
902 
903 unsigned long
TclpGetPid(Tcl_Pid pid)904 TclpGetPid(
905     Tcl_Pid pid)		/* The HANDLE of the child process. */
906 {
907     ProcInfo *infoPtr;
908 
909     Tcl_MutexLock(&pipeMutex);
910     for (infoPtr = procList; infoPtr != NULL; infoPtr = infoPtr->nextPtr) {
911 	if (infoPtr->hProcess == (HANDLE) pid) {
912 	    Tcl_MutexUnlock(&pipeMutex);
913 	    return infoPtr->dwProcessId;
914 	}
915     }
916     Tcl_MutexUnlock(&pipeMutex);
917     return (unsigned long) -1;
918 }
919 
920 /*
921  *----------------------------------------------------------------------
922  *
923  * TclpCreateProcess --
924  *
925  *	Create a child process that has the specified files as its
926  *	standard input, output, and error.  The child process runs
927  *	asynchronously under Windows NT and Windows 9x, and runs
928  *	with the same environment variables as the creating process.
929  *
930  *	The complete Windows search path is searched to find the specified
931  *	executable.  If an executable by the given name is not found,
932  *	automatically tries appending ".com", ".exe", and ".bat" to the
933  *	executable name.
934  *
935  * Results:
936  *	The return value is TCL_ERROR and an error message is left in
937  *	the interp's result if there was a problem creating the child
938  *	process.  Otherwise, the return value is TCL_OK and *pidPtr is
939  *	filled with the process id of the child process.
940  *
941  * Side effects:
942  *	A process is created.
943  *
944  *----------------------------------------------------------------------
945  */
946 
947 int
TclpCreateProcess(Tcl_Interp * interp,int argc,CONST char ** argv,TclFile inputFile,TclFile outputFile,TclFile errorFile,Tcl_Pid * pidPtr)948 TclpCreateProcess(
949     Tcl_Interp *interp,		/* Interpreter in which to leave errors that
950 				 * occurred when creating the child process.
951 				 * Error messages from the child process
952 				 * itself are sent to errorFile. */
953     int argc,			/* Number of arguments in following array. */
954     CONST char **argv,		/* Array of argument strings.  argv[0]
955 				 * contains the name of the executable
956 				 * converted to native format (using the
957 				 * Tcl_TranslateFileName call).  Additional
958 				 * arguments have not been converted. */
959     TclFile inputFile,		/* If non-NULL, gives the file to use as
960 				 * input for the child process.  If inputFile
961 				 * file is not readable or is NULL, the child
962 				 * will receive no standard input. */
963     TclFile outputFile,		/* If non-NULL, gives the file that
964 				 * receives output from the child process.  If
965 				 * outputFile file is not writeable or is
966 				 * NULL, output from the child will be
967 				 * discarded. */
968     TclFile errorFile,		/* If non-NULL, gives the file that
969 				 * receives errors from the child process.  If
970 				 * errorFile file is not writeable or is NULL,
971 				 * errors from the child will be discarded.
972 				 * errorFile may be the same as outputFile. */
973     Tcl_Pid *pidPtr)		/* If this procedure is successful, pidPtr
974 				 * is filled with the process id of the child
975 				 * process. */
976 {
977     int result, applType, createFlags;
978     Tcl_DString cmdLine;	/* Complete command line (TCHAR). */
979     STARTUPINFOA startInfo;
980     PROCESS_INFORMATION procInfo;
981     SECURITY_ATTRIBUTES secAtts;
982     HANDLE hProcess, h, inputHandle, outputHandle, errorHandle;
983     char execPath[MAX_PATH * TCL_UTF_MAX];
984     WinFile *filePtr;
985 
986     PipeInit();
987 
988     applType = ApplicationType(interp, argv[0], execPath);
989     if (applType == APPL_NONE) {
990 	return TCL_ERROR;
991     }
992 
993     result = TCL_ERROR;
994     Tcl_DStringInit(&cmdLine);
995     hProcess = GetCurrentProcess();
996 
997     /*
998      * STARTF_USESTDHANDLES must be used to pass handles to child process.
999      * Using SetStdHandle() and/or dup2() only works when a console mode
1000      * parent process is spawning an attached console mode child process.
1001      */
1002 
1003     ZeroMemory(&startInfo, sizeof(startInfo));
1004     startInfo.cb = sizeof(startInfo);
1005     startInfo.dwFlags   = STARTF_USESTDHANDLES;
1006     startInfo.hStdInput	= INVALID_HANDLE_VALUE;
1007     startInfo.hStdOutput= INVALID_HANDLE_VALUE;
1008     startInfo.hStdError = INVALID_HANDLE_VALUE;
1009 
1010     secAtts.nLength = sizeof(SECURITY_ATTRIBUTES);
1011     secAtts.lpSecurityDescriptor = NULL;
1012     secAtts.bInheritHandle = TRUE;
1013 
1014     /*
1015      * We have to check the type of each file, since we cannot duplicate
1016      * some file types.
1017      */
1018 
1019     inputHandle = INVALID_HANDLE_VALUE;
1020     if (inputFile != NULL) {
1021 	filePtr = (WinFile *)inputFile;
1022 	if (filePtr->type == WIN_FILE) {
1023 	    inputHandle = filePtr->handle;
1024 	}
1025     }
1026     outputHandle = INVALID_HANDLE_VALUE;
1027     if (outputFile != NULL) {
1028 	filePtr = (WinFile *)outputFile;
1029 	if (filePtr->type == WIN_FILE) {
1030 	    outputHandle = filePtr->handle;
1031 	}
1032     }
1033     errorHandle = INVALID_HANDLE_VALUE;
1034     if (errorFile != NULL) {
1035 	filePtr = (WinFile *)errorFile;
1036 	if (filePtr->type == WIN_FILE) {
1037 	    errorHandle = filePtr->handle;
1038 	}
1039     }
1040 
1041     /*
1042      * Duplicate all the handles which will be passed off as stdin, stdout
1043      * and stderr of the child process. The duplicate handles are set to
1044      * be inheritable, so the child process can use them.
1045      */
1046 
1047     if (inputHandle == INVALID_HANDLE_VALUE) {
1048 	/*
1049 	 * If handle was not set, stdin should return immediate EOF.
1050 	 * Under Windows95, some applications (both 16 and 32 bit!)
1051 	 * cannot read from the NUL device; they read from console
1052 	 * instead.  When running tk, this is fatal because the child
1053 	 * process would hang forever waiting for EOF from the unmapped
1054 	 * console window used by the helper application.
1055 	 *
1056 	 * Fortunately, the helper application detects a closed pipe
1057 	 * as an immediate EOF and can pass that information to the
1058 	 * child process.
1059 	 */
1060 
1061 	if (CreatePipe(&startInfo.hStdInput, &h, &secAtts, 0) != FALSE) {
1062 	    CloseHandle(h);
1063 	}
1064     } else {
1065 	DuplicateHandle(hProcess, inputHandle, hProcess, &startInfo.hStdInput,
1066 		0, TRUE, DUPLICATE_SAME_ACCESS);
1067     }
1068     if (startInfo.hStdInput == INVALID_HANDLE_VALUE) {
1069 	TclWinConvertError(GetLastError());
1070 	Tcl_AppendResult(interp, "couldn't duplicate input handle: ",
1071 		Tcl_PosixError(interp), (char *) NULL);
1072 	goto end;
1073     }
1074 
1075     if (outputHandle == INVALID_HANDLE_VALUE) {
1076 	/*
1077 	 * If handle was not set, output should be sent to an infinitely
1078 	 * deep sink.  Under Windows 95, some 16 bit applications cannot
1079 	 * have stdout redirected to NUL; they send their output to
1080 	 * the console instead.  Some applications, like "more" or "dir /p",
1081 	 * when outputting multiple pages to the console, also then try and
1082 	 * read from the console to go the next page.  When running tk, this
1083 	 * is fatal because the child process would hang forever waiting
1084 	 * for input from the unmapped console window used by the helper
1085 	 * application.
1086 	 *
1087 	 * Fortunately, the helper application will detect a closed pipe
1088 	 * as a sink.
1089 	 */
1090 
1091 	if ((TclWinGetPlatformId() == VER_PLATFORM_WIN32_WINDOWS)
1092 		&& (applType == APPL_DOS)) {
1093 	    if (CreatePipe(&h, &startInfo.hStdOutput, &secAtts, 0) != FALSE) {
1094 		CloseHandle(h);
1095 	    }
1096 	} else {
1097 	    startInfo.hStdOutput = CreateFileA("NUL:", GENERIC_WRITE, 0,
1098 		    &secAtts, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1099 	}
1100     } else {
1101 	DuplicateHandle(hProcess, outputHandle, hProcess, &startInfo.hStdOutput,
1102 		0, TRUE, DUPLICATE_SAME_ACCESS);
1103     }
1104     if (startInfo.hStdOutput == INVALID_HANDLE_VALUE) {
1105 	TclWinConvertError(GetLastError());
1106 	Tcl_AppendResult(interp, "couldn't duplicate output handle: ",
1107 		Tcl_PosixError(interp), (char *) NULL);
1108 	goto end;
1109     }
1110 
1111     if (errorHandle == INVALID_HANDLE_VALUE) {
1112 	/*
1113 	 * If handle was not set, errors should be sent to an infinitely
1114 	 * deep sink.
1115 	 */
1116 
1117 	startInfo.hStdError = CreateFileA("NUL:", GENERIC_WRITE, 0,
1118 		&secAtts, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1119     } else {
1120 	DuplicateHandle(hProcess, errorHandle, hProcess, &startInfo.hStdError,
1121 		0, TRUE, DUPLICATE_SAME_ACCESS);
1122     }
1123     if (startInfo.hStdError == INVALID_HANDLE_VALUE) {
1124 	TclWinConvertError(GetLastError());
1125 	Tcl_AppendResult(interp, "couldn't duplicate error handle: ",
1126 		Tcl_PosixError(interp), (char *) NULL);
1127 	goto end;
1128     }
1129     /*
1130      * If we do not have a console window, then we must run DOS and
1131      * WIN32 console mode applications as detached processes. This tells
1132      * the loader that the child application should not inherit the
1133      * console, and that it should not create a new console window for
1134      * the child application.  The child application should get its stdio
1135      * from the redirection handles provided by this application, and run
1136      * in the background.
1137      *
1138      * If we are starting a GUI process, they don't automatically get a
1139      * console, so it doesn't matter if they are started as foreground or
1140      * detached processes.  The GUI window will still pop up to the
1141      * foreground.
1142      */
1143 
1144     if (TclWinGetPlatformId() == VER_PLATFORM_WIN32_NT) {
1145 	if (HasConsole()) {
1146 	    createFlags = 0;
1147 	} else if (applType == APPL_DOS) {
1148 	    /*
1149 	     * Under NT, 16-bit DOS applications will not run unless they
1150 	     * can be attached to a console.  If we are running without a
1151 	     * console, run the 16-bit program as an normal process inside
1152 	     * of a hidden console application, and then run that hidden
1153 	     * console as a detached process.
1154 	     */
1155 
1156 	    startInfo.wShowWindow = SW_HIDE;
1157 	    startInfo.dwFlags |= STARTF_USESHOWWINDOW;
1158 	    createFlags = CREATE_NEW_CONSOLE;
1159 	    Tcl_DStringAppend(&cmdLine, "cmd.exe /c ", -1);
1160 	} else {
1161 	    createFlags = DETACHED_PROCESS;
1162 	}
1163     } else {
1164 	if (HasConsole()) {
1165 	    createFlags = 0;
1166 	} else {
1167 	    createFlags = DETACHED_PROCESS;
1168 	}
1169 
1170 	if (applType == APPL_DOS) {
1171 	    /*
1172 	     * Under Windows 95, 16-bit DOS applications do not work well
1173 	     * with pipes:
1174 	     *
1175 	     * 1. EOF on a pipe between a detached 16-bit DOS application
1176 	     * and another application is not seen at the other
1177 	     * end of the pipe, so the listening process blocks forever on
1178 	     * reads.  This inablity to detect EOF happens when either a
1179 	     * 16-bit app or the 32-bit app is the listener.
1180 	     *
1181 	     * 2. If a 16-bit DOS application (detached or not) blocks when
1182 	     * writing to a pipe, it will never wake up again, and it
1183 	     * eventually brings the whole system down around it.
1184 	     *
1185 	     * The 16-bit application is run as a normal process inside
1186 	     * of a hidden helper console app, and this helper may be run
1187 	     * as a detached process.  If any of the stdio handles is
1188 	     * a pipe, the helper application accumulates information
1189 	     * into temp files and forwards it to or from the DOS
1190 	     * application as appropriate.  This means that DOS apps
1191 	     * must receive EOF from a stdin pipe before they will actually
1192 	     * begin, and must finish generating stdout or stderr before
1193 	     * the data will be sent to the next stage of the pipe.
1194 	     *
1195 	     * The helper app should be located in the same directory as
1196 	     * the tcl dll.
1197 	     */
1198 
1199 	    if (createFlags != 0) {
1200 		startInfo.wShowWindow = SW_HIDE;
1201 		startInfo.dwFlags |= STARTF_USESHOWWINDOW;
1202 		createFlags = CREATE_NEW_CONSOLE;
1203 	    }
1204 
1205 	    {
1206 		Tcl_Obj *tclExePtr, *pipeDllPtr;
1207 		int i, fileExists;
1208 		char *start,*end;
1209 		Tcl_DString pipeDll;
1210 		Tcl_DStringInit(&pipeDll);
1211 		Tcl_DStringAppend(&pipeDll, TCL_PIPE_DLL, -1);
1212 		tclExePtr = Tcl_NewStringObj(TclpFindExecutable(""), -1);
1213 		start = Tcl_GetStringFromObj(tclExePtr, &i);
1214 		for (end = start + (i-1); end > start; end--) {
1215 		    if (*end == '/')
1216 		        break;
1217 		}
1218 		if (*end != '/')
1219 		    panic("no / in executable path name");
1220 		i = (end - start) + 1;
1221 		pipeDllPtr = Tcl_NewStringObj(start, i);
1222 		Tcl_AppendToObj(pipeDllPtr, Tcl_DStringValue(&pipeDll), -1);
1223 		Tcl_IncrRefCount(pipeDllPtr);
1224 		if (Tcl_FSConvertToPathType(interp, pipeDllPtr) != TCL_OK)
1225 		    panic("Tcl_FSConvertToPathType failed");
1226 		fileExists = (Tcl_FSAccess(pipeDllPtr, F_OK) == 0);
1227 		if (!fileExists) {
1228 		    panic("Tcl pipe dll \"%s\" not found",
1229 		        Tcl_DStringValue(&pipeDll));
1230 		}
1231 		Tcl_DStringAppend(&cmdLine, Tcl_DStringValue(&pipeDll), -1);
1232 		Tcl_DecrRefCount(tclExePtr);
1233 		Tcl_DecrRefCount(pipeDllPtr);
1234 		Tcl_DStringFree(&pipeDll);
1235 	    }
1236 	}
1237     }
1238 
1239     /*
1240      * cmdLine gets the full command line used to invoke the executable,
1241      * including the name of the executable itself.  The command line
1242      * arguments in argv[] are stored in cmdLine separated by spaces.
1243      * Special characters in individual arguments from argv[] must be
1244      * quoted when being stored in cmdLine.
1245      *
1246      * When calling any application, bear in mind that arguments that
1247      * specify a path name are not converted.  If an argument contains
1248      * forward slashes as path separators, it may or may not be
1249      * recognized as a path name, depending on the program.  In general,
1250      * most applications accept forward slashes only as option
1251      * delimiters and backslashes only as paths.
1252      *
1253      * Additionally, when calling a 16-bit dos or windows application,
1254      * all path names must use the short, cryptic, path format (e.g.,
1255      * using ab~1.def instead of "a b.default").
1256      */
1257 
1258     BuildCommandLine(execPath, argc, argv, &cmdLine);
1259 
1260     if ((*tclWinProcs->createProcessProc)(NULL,
1261 	    (TCHAR *) Tcl_DStringValue(&cmdLine), NULL, NULL, TRUE,
1262 	    (DWORD) createFlags, NULL, NULL, &startInfo, &procInfo) == 0) {
1263 	TclWinConvertError(GetLastError());
1264 	Tcl_AppendResult(interp, "couldn't execute \"", argv[0],
1265 		"\": ", Tcl_PosixError(interp), (char *) NULL);
1266 	goto end;
1267     }
1268 
1269     /*
1270      * This wait is used to force the OS to give some time to the DOS
1271      * process.
1272      */
1273 
1274     if (applType == APPL_DOS) {
1275 	WaitForSingleObject(procInfo.hProcess, 50);
1276     }
1277 
1278     /*
1279      * "When an application spawns a process repeatedly, a new thread
1280      * instance will be created for each process but the previous
1281      * instances may not be cleaned up.  This results in a significant
1282      * virtual memory loss each time the process is spawned.  If there
1283      * is a WaitForInputIdle() call between CreateProcess() and
1284      * CloseHandle(), the problem does not occur." PSS ID Number: Q124121
1285      */
1286 
1287     WaitForInputIdle(procInfo.hProcess, 5000);
1288     CloseHandle(procInfo.hThread);
1289 
1290     *pidPtr = (Tcl_Pid) procInfo.hProcess;
1291     if (*pidPtr != 0) {
1292 	TclWinAddProcess(procInfo.hProcess, procInfo.dwProcessId);
1293     }
1294     result = TCL_OK;
1295 
1296     end:
1297     Tcl_DStringFree(&cmdLine);
1298     if (startInfo.hStdInput != INVALID_HANDLE_VALUE) {
1299         CloseHandle(startInfo.hStdInput);
1300     }
1301     if (startInfo.hStdOutput != INVALID_HANDLE_VALUE) {
1302         CloseHandle(startInfo.hStdOutput);
1303     }
1304     if (startInfo.hStdError != INVALID_HANDLE_VALUE) {
1305 	CloseHandle(startInfo.hStdError);
1306     }
1307     return result;
1308 }
1309 
1310 
1311 /*
1312  *----------------------------------------------------------------------
1313  *
1314  * HasConsole --
1315  *
1316  *	Determines whether the current application is attached to a
1317  *	console.
1318  *
1319  * Results:
1320  *	Returns TRUE if this application has a console, else FALSE.
1321  *
1322  * Side effects:
1323  *	None.
1324  *
1325  *----------------------------------------------------------------------
1326  */
1327 
1328 static BOOL
HasConsole()1329 HasConsole()
1330 {
1331     HANDLE handle;
1332 
1333     handle = CreateFileA("CONOUT$", GENERIC_WRITE, FILE_SHARE_WRITE,
1334 	    NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1335 
1336     if (handle != INVALID_HANDLE_VALUE) {
1337         CloseHandle(handle);
1338 	return TRUE;
1339     } else {
1340         return FALSE;
1341     }
1342 }
1343 
1344 /*
1345  *--------------------------------------------------------------------
1346  *
1347  * ApplicationType --
1348  *
1349  *	Search for the specified program and identify if it refers to a DOS,
1350  *	Windows 3.X, or Win32 program.  Used to determine how to invoke
1351  *	a program, or if it can even be invoked.
1352  *
1353  *	It is possible to almost positively identify DOS and Windows
1354  *	applications that contain the appropriate magic numbers.  However,
1355  *	DOS .com files do not seem to contain a magic number; if the program
1356  *	name ends with .com and could not be identified as a Windows .com
1357  *	file, it will be assumed to be a DOS application, even if it was
1358  *	just random data.  If the program name does not end with .com, no
1359  *	such assumption is made.
1360  *
1361  *	The Win32 procedure GetBinaryType incorrectly identifies any
1362  *	junk file that ends with .exe as a dos executable and some
1363  *	executables that don't end with .exe as not executable.  Plus it
1364  *	doesn't exist under win95, so I won't feel bad about reimplementing
1365  *	functionality.
1366  *
1367  * Results:
1368  *	The return value is one of APPL_DOS, APPL_WIN3X, or APPL_WIN32
1369  *	if the filename referred to the corresponding application type.
1370  *	If the file name could not be found or did not refer to any known
1371  *	application type, APPL_NONE is returned and an error message is
1372  *	left in interp.  .bat files are identified as APPL_DOS.
1373  *
1374  * Side effects:
1375  *	None.
1376  *
1377  *----------------------------------------------------------------------
1378  */
1379 
1380 static int
ApplicationType(interp,originalName,fullName)1381 ApplicationType(interp, originalName, fullName)
1382     Tcl_Interp *interp;		/* Interp, for error message. */
1383     const char *originalName;	/* Name of the application to find. */
1384     char fullName[];		/* Filled with complete path to
1385 				 * application. */
1386 {
1387     int applType, i, nameLen, found;
1388     HANDLE hFile;
1389     TCHAR *rest;
1390     char *ext;
1391     char buf[2];
1392     DWORD attr, read;
1393     IMAGE_DOS_HEADER header;
1394     Tcl_DString nameBuf, ds;
1395     CONST TCHAR *nativeName;
1396     WCHAR nativeFullPath[MAX_PATH];
1397     static char extensions[][5] = {"", ".com", ".exe", ".bat"};
1398 
1399     /* Look for the program as an external program.  First try the name
1400      * as it is, then try adding .com, .exe, and .bat, in that order, to
1401      * the name, looking for an executable.
1402      *
1403      * Using the raw SearchPath() procedure doesn't do quite what is
1404      * necessary.  If the name of the executable already contains a '.'
1405      * character, it will not try appending the specified extension when
1406      * searching (in other words, SearchPath will not find the program
1407      * "a.b.exe" if the arguments specified "a.b" and ".exe").
1408      * So, first look for the file as it is named.  Then manually append
1409      * the extensions, looking for a match.
1410      */
1411 
1412     applType = APPL_NONE;
1413     Tcl_DStringInit(&nameBuf);
1414     Tcl_DStringAppend(&nameBuf, originalName, -1);
1415     nameLen = Tcl_DStringLength(&nameBuf);
1416 
1417     for (i = 0; i < (int) (sizeof(extensions) / sizeof(extensions[0])); i++) {
1418 	Tcl_DStringSetLength(&nameBuf, nameLen);
1419 	Tcl_DStringAppend(&nameBuf, extensions[i], -1);
1420         nativeName = Tcl_WinUtfToTChar(Tcl_DStringValue(&nameBuf),
1421 		Tcl_DStringLength(&nameBuf), &ds);
1422 	found = (*tclWinProcs->searchPathProc)(NULL, nativeName, NULL,
1423 		MAX_PATH, nativeFullPath, &rest);
1424 	Tcl_DStringFree(&ds);
1425 	if (found == 0) {
1426 	    continue;
1427 	}
1428 
1429 	/*
1430 	 * Ignore matches on directories or data files, return if identified
1431 	 * a known type.
1432 	 */
1433 
1434 	attr = (*tclWinProcs->getFileAttributesProc)((TCHAR *) nativeFullPath);
1435 	if ((attr == 0xffffffff) || (attr & FILE_ATTRIBUTE_DIRECTORY)) {
1436 	    continue;
1437 	}
1438 	strcpy(fullName, Tcl_WinTCharToUtf((TCHAR *) nativeFullPath, -1, &ds));
1439 	Tcl_DStringFree(&ds);
1440 
1441 	ext = strrchr(fullName, '.');
1442 	if ((ext != NULL) && (stricmp(ext, ".bat") == 0)) {
1443 	    applType = APPL_DOS;
1444 	    break;
1445 	}
1446 
1447 	hFile = (*tclWinProcs->createFileProc)((TCHAR *) nativeFullPath,
1448 		GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
1449 		FILE_ATTRIBUTE_NORMAL, NULL);
1450 	if (hFile == INVALID_HANDLE_VALUE) {
1451 	    continue;
1452 	}
1453 
1454 	header.e_magic = 0;
1455 	ReadFile(hFile, (void *) &header, sizeof(header), &read, NULL);
1456 	if (header.e_magic != IMAGE_DOS_SIGNATURE) {
1457 	    /*
1458 	     * Doesn't have the magic number for relocatable executables.  If
1459 	     * filename ends with .com, assume it's a DOS application anyhow.
1460 	     * Note that we didn't make this assumption at first, because some
1461 	     * supposed .com files are really 32-bit executables with all the
1462 	     * magic numbers and everything.
1463 	     */
1464 
1465 	    CloseHandle(hFile);
1466 	    if ((ext != NULL) && (stricmp(ext, ".com") == 0)) {
1467 		applType = APPL_DOS;
1468 		break;
1469 	    }
1470 	    continue;
1471 	}
1472 	if (header.e_lfarlc != sizeof(header)) {
1473 	    /*
1474 	     * All Windows 3.X and Win32 and some DOS programs have this value
1475 	     * set here.  If it doesn't, assume that since it already had the
1476 	     * other magic number it was a DOS application.
1477 	     */
1478 
1479 	    CloseHandle(hFile);
1480 	    applType = APPL_DOS;
1481 	    break;
1482 	}
1483 
1484 	/*
1485 	 * The DWORD at header.e_lfanew points to yet another magic number.
1486 	 */
1487 
1488 	buf[0] = '\0';
1489 	SetFilePointer(hFile, header.e_lfanew, NULL, FILE_BEGIN);
1490 	ReadFile(hFile, (void *) buf, 2, &read, NULL);
1491 	CloseHandle(hFile);
1492 
1493 	if ((buf[0] == 'N') && (buf[1] == 'E')) {
1494 	    applType = APPL_WIN3X;
1495 	} else if ((buf[0] == 'P') && (buf[1] == 'E')) {
1496 	    applType = APPL_WIN32;
1497 	} else {
1498 	    /*
1499 	     * Strictly speaking, there should be a test that there
1500 	     * is an 'L' and 'E' at buf[0..1], to identify the type as
1501 	     * DOS, but of course we ran into a DOS executable that
1502 	     * _doesn't_ have the magic number -- specifically, one
1503 	     * compiled using the Lahey Fortran90 compiler.
1504 	     */
1505 
1506 	    applType = APPL_DOS;
1507 	}
1508 	break;
1509     }
1510     Tcl_DStringFree(&nameBuf);
1511 
1512     if (applType == APPL_NONE) {
1513 	TclWinConvertError(GetLastError());
1514 	Tcl_AppendResult(interp, "couldn't execute \"", originalName,
1515 		"\": ", Tcl_PosixError(interp), (char *) NULL);
1516 	return APPL_NONE;
1517     }
1518 
1519     if ((applType == APPL_DOS) || (applType == APPL_WIN3X)) {
1520 	/*
1521 	 * Replace long path name of executable with short path name for
1522 	 * 16-bit applications.  Otherwise the application may not be able
1523 	 * to correctly parse its own command line to separate off the
1524 	 * application name from the arguments.
1525 	 */
1526 
1527 	(*tclWinProcs->getShortPathNameProc)((TCHAR *) nativeFullPath,
1528 		nativeFullPath, MAX_PATH);
1529 	strcpy(fullName, Tcl_WinTCharToUtf((TCHAR *) nativeFullPath, -1, &ds));
1530 	Tcl_DStringFree(&ds);
1531     }
1532     return applType;
1533 }
1534 
1535 /*
1536  *----------------------------------------------------------------------
1537  *
1538  * BuildCommandLine --
1539  *
1540  *	The command line arguments are stored in linePtr separated
1541  *	by spaces, in a form that CreateProcess() understands.  Special
1542  *	characters in individual arguments from argv[] must be quoted
1543  *	when being stored in cmdLine.
1544  *
1545  * Results:
1546  *	None.
1547  *
1548  * Side effects:
1549  *	None.
1550  *
1551  *----------------------------------------------------------------------
1552  */
1553 
1554 static void
BuildCommandLine(CONST char * executable,int argc,CONST char ** argv,Tcl_DString * linePtr)1555 BuildCommandLine(
1556     CONST char *executable,	/* Full path of executable (including
1557 				 * extension).  Replacement for argv[0]. */
1558     int argc,			/* Number of arguments. */
1559     CONST char **argv,		/* Argument strings in UTF. */
1560     Tcl_DString *linePtr)	/* Initialized Tcl_DString that receives the
1561 				 * command line (TCHAR). */
1562 {
1563     CONST char *arg, *start, *special;
1564     int quote, i;
1565     Tcl_DString ds;
1566 
1567     Tcl_DStringInit(&ds);
1568 
1569     /*
1570      * Prime the path.
1571      */
1572 
1573     Tcl_DStringAppend(&ds, Tcl_DStringValue(linePtr), -1);
1574 
1575     for (i = 0; i < argc; i++) {
1576 	if (i == 0) {
1577 	    arg = executable;
1578 	} else {
1579 	    arg = argv[i];
1580 	}
1581 
1582 	if(Tcl_DStringLength(&ds) > 0) Tcl_DStringAppend(&ds, " ", 1);
1583 
1584 	quote = 0;
1585 	if (arg[0] == '\0') {
1586 	    quote = 1;
1587 	} else {
1588 	    int count;
1589 	    Tcl_UniChar ch;
1590 	    for (start = arg; *start != '\0'; start += count) {
1591 	        count = Tcl_UtfToUniChar(start, &ch);
1592 		if (Tcl_UniCharIsSpace(ch)) { /* INTL: ISO space. */
1593 		    quote = 1;
1594 		    break;
1595 		}
1596 	    }
1597 	}
1598 	if (quote) {
1599 	    Tcl_DStringAppend(&ds, "\"", 1);
1600 	}
1601 
1602 	start = arg;
1603 	for (special = arg; ; ) {
1604 	    if ((*special == '\\') &&
1605 		    (special[1] == '\\' || special[1] == '"')) {
1606 		Tcl_DStringAppend(&ds, start, special - start);
1607 		start = special;
1608 		while (1) {
1609 		    special++;
1610 		    if (*special == '"') {
1611 			/*
1612 			 * N backslashes followed a quote -> insert
1613 			 * N * 2 + 1 backslashes then a quote.
1614 			 */
1615 
1616 			Tcl_DStringAppend(&ds, start, special - start);
1617 			break;
1618 		    }
1619 		    if (*special != '\\') {
1620 			break;
1621 		    }
1622 		}
1623 		Tcl_DStringAppend(&ds, start, special - start);
1624 		start = special;
1625 	    }
1626 	    if (*special == '"') {
1627 		Tcl_DStringAppend(&ds, start, special - start);
1628 		Tcl_DStringAppend(&ds, "\\\"", 2);
1629 		start = special + 1;
1630 	    }
1631 	    if (*special == '{') {
1632 		Tcl_DStringAppend(&ds, start, special - start);
1633 		Tcl_DStringAppend(&ds, "\\{", 2);
1634 		start = special + 1;
1635 	    }
1636 	    if (*special == '\0') {
1637 		break;
1638 	    }
1639 	    special++;
1640 	}
1641 	Tcl_DStringAppend(&ds, start, special - start);
1642 	if (quote) {
1643 	    Tcl_DStringAppend(&ds, "\"", 1);
1644 	}
1645     }
1646     Tcl_DStringFree(linePtr);
1647     Tcl_WinUtfToTChar(Tcl_DStringValue(&ds), Tcl_DStringLength(&ds), linePtr);
1648     Tcl_DStringFree(&ds);
1649 }
1650 
1651 /*
1652  *----------------------------------------------------------------------
1653  *
1654  * TclpCreateCommandChannel --
1655  *
1656  *	This function is called by Tcl_OpenCommandChannel to perform
1657  *	the platform specific channel initialization for a command
1658  *	channel.
1659  *
1660  * Results:
1661  *	Returns a new channel or NULL on failure.
1662  *
1663  * Side effects:
1664  *	Allocates a new channel.
1665  *
1666  *----------------------------------------------------------------------
1667  */
1668 
1669 Tcl_Channel
TclpCreateCommandChannel(TclFile readFile,TclFile writeFile,TclFile errorFile,int numPids,Tcl_Pid * pidPtr)1670 TclpCreateCommandChannel(
1671     TclFile readFile,		/* If non-null, gives the file for reading. */
1672     TclFile writeFile,		/* If non-null, gives the file for writing. */
1673     TclFile errorFile,		/* If non-null, gives the file where errors
1674 				 * can be read. */
1675     int numPids,		/* The number of pids in the pid array. */
1676     Tcl_Pid *pidPtr)		/* An array of process identifiers. */
1677 {
1678     char channelName[16 + TCL_INTEGER_SPACE];
1679     int channelId;
1680     DWORD id;
1681     PipeInfo *infoPtr = (PipeInfo *) ckalloc((unsigned) sizeof(PipeInfo));
1682 
1683     PipeInit();
1684 
1685     infoPtr->watchMask = 0;
1686     infoPtr->flags = 0;
1687     infoPtr->readFlags = 0;
1688     infoPtr->readFile = readFile;
1689     infoPtr->writeFile = writeFile;
1690     infoPtr->errorFile = errorFile;
1691     infoPtr->numPids = numPids;
1692     infoPtr->pidPtr = pidPtr;
1693     infoPtr->writeBuf = 0;
1694     infoPtr->writeBufLen = 0;
1695     infoPtr->writeError = 0;
1696 
1697     /*
1698      * Use one of the fds associated with the channel as the
1699      * channel id.
1700      */
1701 
1702     if (readFile) {
1703 	channelId = (int) ((WinFile*)readFile)->handle;
1704     } else if (writeFile) {
1705 	channelId = (int) ((WinFile*)writeFile)->handle;
1706     } else if (errorFile) {
1707 	channelId = (int) ((WinFile*)errorFile)->handle;
1708     } else {
1709 	channelId = 0;
1710     }
1711 
1712     infoPtr->validMask = 0;
1713 
1714     infoPtr->threadId = Tcl_GetCurrentThread();
1715 
1716     if (readFile != NULL) {
1717 	/*
1718 	 * Start the background reader thread.
1719 	 */
1720 
1721 	infoPtr->readable = CreateEvent(NULL, TRUE, TRUE, NULL);
1722 	infoPtr->startReader = CreateEvent(NULL, FALSE, FALSE, NULL);
1723 	infoPtr->stopReader = CreateEvent(NULL, TRUE, FALSE, NULL);
1724 	infoPtr->readThread = CreateThread(NULL, 256, PipeReaderThread,
1725 		infoPtr, 0, &id);
1726 	SetThreadPriority(infoPtr->readThread, THREAD_PRIORITY_HIGHEST);
1727         infoPtr->validMask |= TCL_READABLE;
1728     } else {
1729 	infoPtr->readThread = 0;
1730     }
1731     if (writeFile != NULL) {
1732 	/*
1733 	 * Start the background writer thread.
1734 	 */
1735 
1736 	infoPtr->writable = CreateEvent(NULL, TRUE, TRUE, NULL);
1737 	infoPtr->startWriter = CreateEvent(NULL, FALSE, FALSE, NULL);
1738 	infoPtr->stopWriter = CreateEvent(NULL, TRUE, FALSE, NULL);
1739 	infoPtr->writeThread = CreateThread(NULL, 256, PipeWriterThread,
1740 		infoPtr, 0, &id);
1741 	SetThreadPriority(infoPtr->readThread, THREAD_PRIORITY_HIGHEST);
1742         infoPtr->validMask |= TCL_WRITABLE;
1743     }
1744 
1745     /*
1746      * For backward compatibility with previous versions of Tcl, we
1747      * use "file%d" as the base name for pipes even though it would
1748      * be more natural to use "pipe%d".
1749      * Use the pointer to keep the channel names unique, in case
1750      * channels share handles (stdin/stdout).
1751      */
1752 
1753     wsprintfA(channelName, "file%lx", infoPtr);
1754     infoPtr->channel = Tcl_CreateChannel(&pipeChannelType, channelName,
1755             (ClientData) infoPtr, infoPtr->validMask);
1756 
1757     /*
1758      * Pipes have AUTO translation mode on Windows and ^Z eof char, which
1759      * means that a ^Z will be appended to them at close. This is needed
1760      * for Windows programs that expect a ^Z at EOF.
1761      */
1762 
1763     Tcl_SetChannelOption((Tcl_Interp *) NULL, infoPtr->channel,
1764 	    "-translation", "auto");
1765     Tcl_SetChannelOption((Tcl_Interp *) NULL, infoPtr->channel,
1766 	    "-eofchar", "\032 {}");
1767     return infoPtr->channel;
1768 }
1769 
1770 /*
1771  *----------------------------------------------------------------------
1772  *
1773  * TclGetAndDetachPids --
1774  *
1775  *	Stores a list of the command PIDs for a command channel in
1776  *	the interp's result.
1777  *
1778  * Results:
1779  *	None.
1780  *
1781  * Side effects:
1782  *	Modifies the interp's result.
1783  *
1784  *----------------------------------------------------------------------
1785  */
1786 
1787 void
TclGetAndDetachPids(Tcl_Interp * interp,Tcl_Channel chan)1788 TclGetAndDetachPids(
1789     Tcl_Interp *interp,
1790     Tcl_Channel chan)
1791 {
1792     PipeInfo *pipePtr;
1793     Tcl_ChannelType *chanTypePtr;
1794     int i;
1795     char buf[TCL_INTEGER_SPACE];
1796 
1797     /*
1798      * Punt if the channel is not a command channel.
1799      */
1800 
1801     chanTypePtr = Tcl_GetChannelType(chan);
1802     if (chanTypePtr != &pipeChannelType) {
1803         return;
1804     }
1805 
1806     pipePtr = (PipeInfo *) Tcl_GetChannelInstanceData(chan);
1807     for (i = 0; i < pipePtr->numPids; i++) {
1808         wsprintfA(buf, "%lu", TclpGetPid(pipePtr->pidPtr[i]));
1809         Tcl_AppendElement(interp, buf);
1810         Tcl_DetachPids(1, &(pipePtr->pidPtr[i]));
1811     }
1812     if (pipePtr->numPids > 0) {
1813         ckfree((char *) pipePtr->pidPtr);
1814         pipePtr->numPids = 0;
1815     }
1816 }
1817 
1818 /*
1819  *----------------------------------------------------------------------
1820  *
1821  * PipeBlockModeProc --
1822  *
1823  *	Set blocking or non-blocking mode on channel.
1824  *
1825  * Results:
1826  *	0 if successful, errno when failed.
1827  *
1828  * Side effects:
1829  *	Sets the device into blocking or non-blocking mode.
1830  *
1831  *----------------------------------------------------------------------
1832  */
1833 
1834 static int
PipeBlockModeProc(ClientData instanceData,int mode)1835 PipeBlockModeProc(
1836     ClientData instanceData,	/* Instance data for channel. */
1837     int mode)			/* TCL_MODE_BLOCKING or
1838                                  * TCL_MODE_NONBLOCKING. */
1839 {
1840     PipeInfo *infoPtr = (PipeInfo *) instanceData;
1841 
1842     /*
1843      * Pipes on Windows can not be switched between blocking and nonblocking,
1844      * hence we have to emulate the behavior. This is done in the input
1845      * function by checking against a bit in the state. We set or unset the
1846      * bit here to cause the input function to emulate the correct behavior.
1847      */
1848 
1849     if (mode == TCL_MODE_NONBLOCKING) {
1850 	infoPtr->flags |= PIPE_ASYNC;
1851     } else {
1852 	infoPtr->flags &= ~(PIPE_ASYNC);
1853     }
1854     return 0;
1855 }
1856 
1857 /*
1858  *----------------------------------------------------------------------
1859  *
1860  * PipeClose2Proc --
1861  *
1862  *	Closes a pipe based IO channel.
1863  *
1864  * Results:
1865  *	0 on success, errno otherwise.
1866  *
1867  * Side effects:
1868  *	Closes the physical channel.
1869  *
1870  *----------------------------------------------------------------------
1871  */
1872 
1873 static int
PipeClose2Proc(ClientData instanceData,Tcl_Interp * interp,int flags)1874 PipeClose2Proc(
1875     ClientData instanceData,	/* Pointer to PipeInfo structure. */
1876     Tcl_Interp *interp,		/* For error reporting. */
1877     int flags)			/* Flags that indicate which side to close. */
1878 {
1879     PipeInfo *pipePtr = (PipeInfo *) instanceData;
1880     Tcl_Channel errChan;
1881     int errorCode, result;
1882     PipeInfo *infoPtr, **nextPtrPtr;
1883     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
1884     DWORD exitCode;
1885 
1886     errorCode = 0;
1887     if ((!flags || (flags == TCL_CLOSE_READ))
1888 	    && (pipePtr->readFile != NULL)) {
1889 	/*
1890 	 * Clean up the background thread if necessary.  Note that this
1891 	 * must be done before we can close the file, since the
1892 	 * thread may be blocking trying to read from the pipe.
1893 	 */
1894 
1895 	if (pipePtr->readThread) {
1896 	    /*
1897 	     * The thread may already have closed on it's own.  Check it's
1898 	     * exit code.
1899 	     */
1900 
1901 	    GetExitCodeThread(pipePtr->readThread, &exitCode);
1902 
1903 	    if (exitCode == STILL_ACTIVE) {
1904 		/*
1905 		 * Set the stop event so that if the reader thread is blocked
1906 		 * in PipeReaderThread on WaitForMultipleEvents, it will exit
1907 		 * cleanly.
1908 		 */
1909 
1910 		SetEvent(pipePtr->stopReader);
1911 
1912 		/*
1913 		 * Wait at most 20 milliseconds for the reader thread to close.
1914 		 */
1915 
1916 		if (WaitForSingleObject(pipePtr->readThread, 20)
1917 			== WAIT_TIMEOUT) {
1918 		    /*
1919 		     * The thread must be blocked waiting for the pipe to
1920 		     * become readable in ReadFile().  There isn't a clean way
1921 		     * to exit the thread from this condition.  We should
1922 		     * terminate the child process instead to get the reader
1923 		     * thread to fall out of ReadFile with a FALSE.  (below) is
1924 		     * not the correct way to do this, but will stay here until
1925 		     * a better solution is found.
1926 		     *
1927 		     * Note that we need to guard against terminating the
1928 		     * thread while it is in the middle of Tcl_ThreadAlert
1929 		     * because it won't be able to release the notifier lock.
1930 		     */
1931 
1932 		    Tcl_MutexLock(&pipeMutex);
1933 
1934 		    /* BUG: this leaks memory */
1935 		    TerminateThread(pipePtr->readThread, 0);
1936 		    Tcl_MutexUnlock(&pipeMutex);
1937 		}
1938 	    }
1939 
1940 	    CloseHandle(pipePtr->readThread);
1941 	    CloseHandle(pipePtr->readable);
1942 	    CloseHandle(pipePtr->startReader);
1943 	    CloseHandle(pipePtr->stopReader);
1944 	    pipePtr->readThread = NULL;
1945 	}
1946 	if (TclpCloseFile(pipePtr->readFile) != 0) {
1947 	    errorCode = errno;
1948 	}
1949 	pipePtr->validMask &= ~TCL_READABLE;
1950 	pipePtr->readFile = NULL;
1951     }
1952     if ((!flags || (flags & TCL_CLOSE_WRITE))
1953 	    && (pipePtr->writeFile != NULL)) {
1954 
1955 	if (pipePtr->writeThread) {
1956 	    /*
1957 	     * Wait for the writer thread to finish the current buffer,
1958 	     * then terminate the thread and close the handles.  If the
1959 	     * channel is nonblocking, there should be no pending write
1960 	     * operations.
1961 	     */
1962 
1963 	    WaitForSingleObject(pipePtr->writable, INFINITE);
1964 
1965 	    /*
1966 	     * The thread may already have closed on it's own.  Check it's
1967 	     * exit code.
1968 	     */
1969 
1970 	    GetExitCodeThread(pipePtr->writeThread, &exitCode);
1971 
1972 	    if (exitCode == STILL_ACTIVE) {
1973 		/*
1974 		 * Set the stop event so that if the reader thread is blocked
1975 		 * in PipeReaderThread on WaitForMultipleEvents, it will exit
1976 		 * cleanly.
1977 		 */
1978 
1979 		SetEvent(pipePtr->stopWriter);
1980 
1981 		/*
1982 		 * Wait at most 20 milliseconds for the reader thread to close.
1983 		 */
1984 
1985 		if (WaitForSingleObject(pipePtr->writeThread, 20)
1986 			== WAIT_TIMEOUT) {
1987 		    /*
1988 		     * The thread must be blocked waiting for the pipe to
1989 		     * consume input in WriteFile().  There isn't a clean way
1990 		     * to exit the thread from this condition.  We should
1991 		     * terminate the child process instead to get the writer
1992 		     * thread to fall out of WriteFile with a FALSE.  (below) is
1993 		     * not the correct way to do this, but will stay here until
1994 		     * a better solution is found.
1995 		     *
1996 		     * Note that we need to guard against terminating the
1997 		     * thread while it is in the middle of Tcl_ThreadAlert
1998 		     * because it won't be able to release the notifier lock.
1999 		     */
2000 
2001 		    Tcl_MutexLock(&pipeMutex);
2002 
2003 		    /* BUG: this leaks memory */
2004 		    TerminateThread(pipePtr->writeThread, 0);
2005 		    Tcl_MutexUnlock(&pipeMutex);
2006 		}
2007 	    }
2008 
2009 	    CloseHandle(pipePtr->writeThread);
2010 	    CloseHandle(pipePtr->writable);
2011 	    CloseHandle(pipePtr->startWriter);
2012 	    CloseHandle(pipePtr->stopWriter);
2013 	    pipePtr->writeThread = NULL;
2014 	}
2015 	if (TclpCloseFile(pipePtr->writeFile) != 0) {
2016 	    if (errorCode == 0) {
2017 		errorCode = errno;
2018 	    }
2019 	}
2020 	pipePtr->validMask &= ~TCL_WRITABLE;
2021 	pipePtr->writeFile = NULL;
2022     }
2023 
2024     pipePtr->watchMask &= pipePtr->validMask;
2025 
2026     /*
2027      * Don't free the channel if any of the flags were set.
2028      */
2029 
2030     if (flags) {
2031 	return errorCode;
2032     }
2033 
2034     /*
2035      * Remove the file from the list of watched files.
2036      */
2037 
2038     for (nextPtrPtr = &(tsdPtr->firstPipePtr), infoPtr = *nextPtrPtr;
2039 	    infoPtr != NULL;
2040 	    nextPtrPtr = &infoPtr->nextPtr, infoPtr = *nextPtrPtr) {
2041 	if (infoPtr == (PipeInfo *)pipePtr) {
2042 	    *nextPtrPtr = infoPtr->nextPtr;
2043 	    break;
2044 	}
2045     }
2046 
2047     /*
2048      * Wrap the error file into a channel and give it to the cleanup
2049      * routine.
2050      */
2051 
2052     if (pipePtr->errorFile) {
2053 	WinFile *filePtr;
2054 
2055 	filePtr = (WinFile*)pipePtr->errorFile;
2056 	errChan = Tcl_MakeFileChannel((ClientData) filePtr->handle,
2057 		TCL_READABLE);
2058 	ckfree((char *) filePtr);
2059     } else {
2060         errChan = NULL;
2061     }
2062 
2063     result = TclCleanupChildren(interp, pipePtr->numPids, pipePtr->pidPtr,
2064             errChan);
2065 
2066     if (pipePtr->numPids > 0) {
2067         ckfree((char *) pipePtr->pidPtr);
2068     }
2069 
2070     if (pipePtr->writeBuf != NULL) {
2071 	ckfree(pipePtr->writeBuf);
2072     }
2073 
2074     ckfree((char*) pipePtr);
2075 
2076     if (errorCode == 0) {
2077         return result;
2078     }
2079     return errorCode;
2080 }
2081 
2082 /*
2083  *----------------------------------------------------------------------
2084  *
2085  * PipeInputProc --
2086  *
2087  *	Reads input from the IO channel into the buffer given. Returns
2088  *	count of how many bytes were actually read, and an error indication.
2089  *
2090  * Results:
2091  *	A count of how many bytes were read is returned and an error
2092  *	indication is returned in an output argument.
2093  *
2094  * Side effects:
2095  *	Reads input from the actual channel.
2096  *
2097  *----------------------------------------------------------------------
2098  */
2099 
2100 static int
PipeInputProc(ClientData instanceData,char * buf,int bufSize,int * errorCode)2101 PipeInputProc(
2102     ClientData instanceData,		/* Pipe state. */
2103     char *buf,				/* Where to store data read. */
2104     int bufSize,			/* How much space is available
2105                                          * in the buffer? */
2106     int *errorCode)			/* Where to store error code. */
2107 {
2108     PipeInfo *infoPtr = (PipeInfo *) instanceData;
2109     WinFile *filePtr = (WinFile*) infoPtr->readFile;
2110     DWORD count, bytesRead = 0;
2111     int result;
2112 
2113     *errorCode = 0;
2114     /*
2115      * Synchronize with the reader thread.
2116      */
2117 
2118     result = WaitForRead(infoPtr, (infoPtr->flags & PIPE_ASYNC) ? 0 : 1);
2119 
2120     /*
2121      * If an error occurred, return immediately.
2122      */
2123 
2124     if (result == -1) {
2125 	*errorCode = errno;
2126 	return -1;
2127     }
2128 
2129     if (infoPtr->readFlags & PIPE_EXTRABYTE) {
2130 	/*
2131 	 * The reader thread consumed 1 byte as a side effect of
2132 	 * waiting so we need to move it into the buffer.
2133 	 */
2134 
2135 	*buf = infoPtr->extraByte;
2136 	infoPtr->readFlags &= ~PIPE_EXTRABYTE;
2137 	buf++;
2138 	bufSize--;
2139 	bytesRead = 1;
2140 
2141 	/*
2142 	 * If further read attempts would block, return what we have.
2143 	 */
2144 
2145 	if (result == 0) {
2146 	    return bytesRead;
2147 	}
2148     }
2149 
2150     /*
2151      * Attempt to read bufSize bytes.  The read will return immediately
2152      * if there is any data available.  Otherwise it will block until
2153      * at least one byte is available or an EOF occurs.
2154      */
2155 
2156     if (ReadFile(filePtr->handle, (LPVOID) buf, (DWORD) bufSize, &count,
2157 	    (LPOVERLAPPED) NULL) == TRUE) {
2158 	return bytesRead + count;
2159     } else if (bytesRead) {
2160 	/*
2161 	 * Ignore errors if we have data to return.
2162 	 */
2163 
2164 	return bytesRead;
2165     }
2166 
2167     TclWinConvertError(GetLastError());
2168     if (errno == EPIPE) {
2169 	infoPtr->readFlags |= PIPE_EOF;
2170 	return 0;
2171     }
2172     *errorCode = errno;
2173     return -1;
2174 }
2175 
2176 /*
2177  *----------------------------------------------------------------------
2178  *
2179  * PipeOutputProc --
2180  *
2181  *	Writes the given output on the IO channel. Returns count of how
2182  *	many characters were actually written, and an error indication.
2183  *
2184  * Results:
2185  *	A count of how many characters were written is returned and an
2186  *	error indication is returned in an output argument.
2187  *
2188  * Side effects:
2189  *	Writes output on the actual channel.
2190  *
2191  *----------------------------------------------------------------------
2192  */
2193 
2194 static int
PipeOutputProc(ClientData instanceData,CONST char * buf,int toWrite,int * errorCode)2195 PipeOutputProc(
2196     ClientData instanceData,		/* Pipe state. */
2197     CONST char *buf,			/* The data buffer. */
2198     int toWrite,			/* How many bytes to write? */
2199     int *errorCode)			/* Where to store error code. */
2200 {
2201     PipeInfo *infoPtr = (PipeInfo *) instanceData;
2202     WinFile *filePtr = (WinFile*) infoPtr->writeFile;
2203     DWORD bytesWritten, timeout;
2204 
2205     *errorCode = 0;
2206     timeout = (infoPtr->flags & PIPE_ASYNC) ? 0 : INFINITE;
2207     if (WaitForSingleObject(infoPtr->writable, timeout) == WAIT_TIMEOUT) {
2208 	/*
2209 	 * The writer thread is blocked waiting for a write to complete
2210 	 * and the channel is in non-blocking mode.
2211 	 */
2212 
2213 	errno = EAGAIN;
2214 	goto error;
2215     }
2216 
2217     /*
2218      * Check for a background error on the last write.
2219      */
2220 
2221     if (infoPtr->writeError) {
2222 	TclWinConvertError(infoPtr->writeError);
2223 	infoPtr->writeError = 0;
2224 	goto error;
2225     }
2226 
2227     if (infoPtr->flags & PIPE_ASYNC) {
2228 	/*
2229 	 * The pipe is non-blocking, so copy the data into the output
2230 	 * buffer and restart the writer thread.
2231 	 */
2232 
2233 	if (toWrite > infoPtr->writeBufLen) {
2234 	    /*
2235 	     * Reallocate the buffer to be large enough to hold the data.
2236 	     */
2237 
2238 	    if (infoPtr->writeBuf) {
2239 		ckfree(infoPtr->writeBuf);
2240 	    }
2241 	    infoPtr->writeBufLen = toWrite;
2242 	    infoPtr->writeBuf = ckalloc((unsigned int) toWrite);
2243 	}
2244 	memcpy(infoPtr->writeBuf, buf, (size_t) toWrite);
2245 	infoPtr->toWrite = toWrite;
2246 	ResetEvent(infoPtr->writable);
2247 	SetEvent(infoPtr->startWriter);
2248 	bytesWritten = toWrite;
2249     } else {
2250 	/*
2251 	 * In the blocking case, just try to write the buffer directly.
2252 	 * This avoids an unnecessary copy.
2253 	 */
2254 
2255 	if (WriteFile(filePtr->handle, (LPVOID) buf, (DWORD) toWrite,
2256 		&bytesWritten, (LPOVERLAPPED) NULL) == FALSE) {
2257 	    TclWinConvertError(GetLastError());
2258 	    goto error;
2259 	}
2260     }
2261     return bytesWritten;
2262 
2263     error:
2264     *errorCode = errno;
2265     return -1;
2266 
2267 }
2268 
2269 /*
2270  *----------------------------------------------------------------------
2271  *
2272  * PipeEventProc --
2273  *
2274  *	This function is invoked by Tcl_ServiceEvent when a file event
2275  *	reaches the front of the event queue.  This procedure invokes
2276  *	Tcl_NotifyChannel on the pipe.
2277  *
2278  * Results:
2279  *	Returns 1 if the event was handled, meaning it should be removed
2280  *	from the queue.  Returns 0 if the event was not handled, meaning
2281  *	it should stay on the queue.  The only time the event isn't
2282  *	handled is if the TCL_FILE_EVENTS flag bit isn't set.
2283  *
2284  * Side effects:
2285  *	Whatever the notifier callback does.
2286  *
2287  *----------------------------------------------------------------------
2288  */
2289 
2290 static int
PipeEventProc(Tcl_Event * evPtr,int flags)2291 PipeEventProc(
2292     Tcl_Event *evPtr,		/* Event to service. */
2293     int flags)			/* Flags that indicate what events to
2294 				 * handle, such as TCL_FILE_EVENTS. */
2295 {
2296     PipeEvent *pipeEvPtr = (PipeEvent *)evPtr;
2297     PipeInfo *infoPtr;
2298     WinFile *filePtr;
2299     int mask;
2300     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
2301 
2302     if (!(flags & TCL_FILE_EVENTS)) {
2303 	return 0;
2304     }
2305 
2306     /*
2307      * Search through the list of watched pipes for the one whose handle
2308      * matches the event.  We do this rather than simply dereferencing
2309      * the handle in the event so that pipes can be deleted while the
2310      * event is in the queue.
2311      */
2312 
2313     for (infoPtr = tsdPtr->firstPipePtr; infoPtr != NULL;
2314 	    infoPtr = infoPtr->nextPtr) {
2315 	if (pipeEvPtr->infoPtr == infoPtr) {
2316 	    infoPtr->flags &= ~(PIPE_PENDING);
2317 	    break;
2318 	}
2319     }
2320 
2321     /*
2322      * Remove stale events.
2323      */
2324 
2325     if (!infoPtr) {
2326 	return 1;
2327     }
2328 
2329     /*
2330      * Check to see if the pipe is readable.  Note
2331      * that we can't tell if a pipe is writable, so we always report it
2332      * as being writable unless we have detected EOF.
2333      */
2334 
2335     filePtr = (WinFile*) ((PipeInfo*)infoPtr)->writeFile;
2336     mask = 0;
2337     if ((infoPtr->watchMask & TCL_WRITABLE) &&
2338 	    (WaitForSingleObject(infoPtr->writable, 0) != WAIT_TIMEOUT)) {
2339 	mask = TCL_WRITABLE;
2340     }
2341 
2342     filePtr = (WinFile*) ((PipeInfo*)infoPtr)->readFile;
2343     if ((infoPtr->watchMask & TCL_READABLE) &&
2344 	    (WaitForRead(infoPtr, 0) >= 0)) {
2345 	if (infoPtr->readFlags & PIPE_EOF) {
2346 	    mask = TCL_READABLE;
2347 	} else {
2348 	    mask |= TCL_READABLE;
2349 	}
2350     }
2351 
2352     /*
2353      * Inform the channel of the events.
2354      */
2355 
2356     Tcl_NotifyChannel(infoPtr->channel, infoPtr->watchMask & mask);
2357     return 1;
2358 }
2359 
2360 /*
2361  *----------------------------------------------------------------------
2362  *
2363  * PipeWatchProc --
2364  *
2365  *	Called by the notifier to set up to watch for events on this
2366  *	channel.
2367  *
2368  * Results:
2369  *	None.
2370  *
2371  * Side effects:
2372  *	None.
2373  *
2374  *----------------------------------------------------------------------
2375  */
2376 
2377 static void
PipeWatchProc(ClientData instanceData,int mask)2378 PipeWatchProc(
2379     ClientData instanceData,		/* Pipe state. */
2380     int mask)				/* What events to watch for, OR-ed
2381                                          * combination of TCL_READABLE,
2382                                          * TCL_WRITABLE and TCL_EXCEPTION. */
2383 {
2384     PipeInfo **nextPtrPtr, *ptr;
2385     PipeInfo *infoPtr = (PipeInfo *) instanceData;
2386     int oldMask = infoPtr->watchMask;
2387     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
2388 
2389     /*
2390      * Since most of the work is handled by the background threads,
2391      * we just need to update the watchMask and then force the notifier
2392      * to poll once.
2393      */
2394 
2395     infoPtr->watchMask = mask & infoPtr->validMask;
2396     if (infoPtr->watchMask) {
2397 	Tcl_Time blockTime = { 0, 0 };
2398 	if (!oldMask) {
2399 	    infoPtr->nextPtr = tsdPtr->firstPipePtr;
2400 	    tsdPtr->firstPipePtr = infoPtr;
2401 	}
2402 	Tcl_SetMaxBlockTime(&blockTime);
2403     } else {
2404 	if (oldMask) {
2405 	    /*
2406 	     * Remove the pipe from the list of watched pipes.
2407 	     */
2408 
2409 	    for (nextPtrPtr = &(tsdPtr->firstPipePtr), ptr = *nextPtrPtr;
2410 		 ptr != NULL;
2411 		 nextPtrPtr = &ptr->nextPtr, ptr = *nextPtrPtr) {
2412 		if (infoPtr == ptr) {
2413 		    *nextPtrPtr = ptr->nextPtr;
2414 		    break;
2415 		}
2416 	    }
2417 	}
2418     }
2419 }
2420 
2421 /*
2422  *----------------------------------------------------------------------
2423  *
2424  * PipeGetHandleProc --
2425  *
2426  *	Called from Tcl_GetChannelHandle to retrieve OS handles from
2427  *	inside a command pipeline based channel.
2428  *
2429  * Results:
2430  *	Returns TCL_OK with the fd in handlePtr, or TCL_ERROR if
2431  *	there is no handle for the specified direction.
2432  *
2433  * Side effects:
2434  *	None.
2435  *
2436  *----------------------------------------------------------------------
2437  */
2438 
2439 static int
PipeGetHandleProc(ClientData instanceData,int direction,ClientData * handlePtr)2440 PipeGetHandleProc(
2441     ClientData instanceData,	/* The pipe state. */
2442     int direction,		/* TCL_READABLE or TCL_WRITABLE */
2443     ClientData *handlePtr)	/* Where to store the handle.  */
2444 {
2445     PipeInfo *infoPtr = (PipeInfo *) instanceData;
2446     WinFile *filePtr;
2447 
2448     if (direction == TCL_READABLE && infoPtr->readFile) {
2449 	filePtr = (WinFile*) infoPtr->readFile;
2450 	*handlePtr = (ClientData) filePtr->handle;
2451 	return TCL_OK;
2452     }
2453     if (direction == TCL_WRITABLE && infoPtr->writeFile) {
2454 	filePtr = (WinFile*) infoPtr->writeFile;
2455 	*handlePtr = (ClientData) filePtr->handle;
2456 	return TCL_OK;
2457     }
2458     return TCL_ERROR;
2459 }
2460 
2461 /*
2462  *----------------------------------------------------------------------
2463  *
2464  * Tcl_WaitPid --
2465  *
2466  *	Emulates the waitpid system call.
2467  *
2468  * Results:
2469  *	Returns 0 if the process is still alive, -1 on an error, or
2470  *	the pid on a clean close.
2471  *
2472  * Side effects:
2473  *	Unless WNOHANG is set and the wait times out, the process
2474  *	information record will be deleted and the process handle
2475  *	will be closed.
2476  *
2477  *----------------------------------------------------------------------
2478  */
2479 
2480 Tcl_Pid
Tcl_WaitPid(Tcl_Pid pid,int * statPtr,int options)2481 Tcl_WaitPid(
2482     Tcl_Pid pid,
2483     int *statPtr,
2484     int options)
2485 {
2486     ProcInfo *infoPtr, **prevPtrPtr;
2487     DWORD flags;
2488     Tcl_Pid result;
2489     DWORD ret, exitCode;
2490 
2491     PipeInit();
2492 
2493     /*
2494      * If no pid is specified, do nothing.
2495      */
2496 
2497     if (pid == 0) {
2498 	*statPtr = 0;
2499 	return 0;
2500     }
2501 
2502     /*
2503      * Find the process on the process list.
2504      */
2505 
2506     Tcl_MutexLock(&pipeMutex);
2507     prevPtrPtr = &procList;
2508     for (infoPtr = procList; infoPtr != NULL;
2509 	    prevPtrPtr = &infoPtr->nextPtr, infoPtr = infoPtr->nextPtr) {
2510 	 if (infoPtr->hProcess == (HANDLE) pid) {
2511 	    break;
2512 	}
2513     }
2514     Tcl_MutexUnlock(&pipeMutex);
2515 
2516     /*
2517      * If the pid is not one of the processes we know about (we started it)
2518      * then do nothing.
2519      */
2520 
2521     if (infoPtr == NULL) {
2522         *statPtr = 0;
2523 	return 0;
2524     }
2525 
2526     /*
2527      * Officially "wait" for it to finish. We either poll (WNOHANG) or
2528      * wait for an infinite amount of time.
2529      */
2530 
2531     if (options & WNOHANG) {
2532 	flags = 0;
2533     } else {
2534 	flags = INFINITE;
2535     }
2536     ret = WaitForSingleObject(infoPtr->hProcess, flags);
2537     if (ret == WAIT_TIMEOUT) {
2538 	*statPtr = 0;
2539 	if (options & WNOHANG) {
2540 	    return 0;
2541 	} else {
2542 	    result = 0;
2543 	}
2544     } else if (ret == WAIT_OBJECT_0) {
2545 	GetExitCodeProcess(infoPtr->hProcess, &exitCode);
2546 	if (exitCode & 0xC0000000) {
2547 	    /*
2548 	     * A fatal exception occured.
2549 	     */
2550 	    switch (exitCode) {
2551 		case EXCEPTION_FLT_DENORMAL_OPERAND:
2552 		case EXCEPTION_FLT_DIVIDE_BY_ZERO:
2553 		case EXCEPTION_FLT_INEXACT_RESULT:
2554 		case EXCEPTION_FLT_INVALID_OPERATION:
2555 		case EXCEPTION_FLT_OVERFLOW:
2556 		case EXCEPTION_FLT_STACK_CHECK:
2557 		case EXCEPTION_FLT_UNDERFLOW:
2558 		case EXCEPTION_INT_DIVIDE_BY_ZERO:
2559 		case EXCEPTION_INT_OVERFLOW:
2560 		    *statPtr = SIGFPE;
2561 		    break;
2562 
2563 		case EXCEPTION_PRIV_INSTRUCTION:
2564 		case EXCEPTION_ILLEGAL_INSTRUCTION:
2565 		    *statPtr = SIGILL;
2566 		    break;
2567 
2568 		case EXCEPTION_ACCESS_VIOLATION:
2569 		case EXCEPTION_DATATYPE_MISALIGNMENT:
2570 		case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
2571 		case EXCEPTION_STACK_OVERFLOW:
2572 		case EXCEPTION_NONCONTINUABLE_EXCEPTION:
2573 		case EXCEPTION_INVALID_DISPOSITION:
2574 		case EXCEPTION_GUARD_PAGE:
2575 		case EXCEPTION_INVALID_HANDLE:
2576 		    *statPtr = SIGSEGV;
2577 		    break;
2578 
2579 		case CONTROL_C_EXIT:
2580 		    *statPtr = SIGINT;
2581 		    break;
2582 
2583 		default:
2584 		    *statPtr = SIGABRT;
2585 		    break;
2586 	    }
2587 	} else {
2588 	    /*
2589 	     * Non exception, normal, exit code.  Note that the exit code
2590 	     * is truncated to a byte range.
2591 	     */
2592 	    *statPtr = ((exitCode << 8) & 0xff00);
2593 	}
2594 	result = pid;
2595     } else {
2596 	errno = ECHILD;
2597         *statPtr = ECHILD;
2598 	result = (Tcl_Pid) -1;
2599     }
2600 
2601     /*
2602      * Remove the process from the process list and close the process handle.
2603      */
2604 
2605     CloseHandle(infoPtr->hProcess);
2606     *prevPtrPtr = infoPtr->nextPtr;
2607     ckfree((char*)infoPtr);
2608 
2609     return result;
2610 }
2611 
2612 /*
2613  *----------------------------------------------------------------------
2614  *
2615  * TclWinAddProcess --
2616  *
2617  *     Add a process to the process list so that we can use
2618  *     Tcl_WaitPid on the process.
2619  *
2620  * Results:
2621  *     None
2622  *
2623  * Side effects:
2624  *	Adds the specified process handle to the process list so
2625  *	Tcl_WaitPid knows about it.
2626  *
2627  *----------------------------------------------------------------------
2628  */
2629 
2630 void
TclWinAddProcess(hProcess,id)2631 TclWinAddProcess(hProcess, id)
2632     HANDLE hProcess;           /* Handle to process */
2633     DWORD id;                  /* Global process identifier */
2634 {
2635     ProcInfo *procPtr = (ProcInfo *) ckalloc(sizeof(ProcInfo));
2636 
2637     PipeInit();
2638 
2639     procPtr->hProcess = hProcess;
2640     procPtr->dwProcessId = id;
2641     Tcl_MutexLock(&pipeMutex);
2642     procPtr->nextPtr = procList;
2643     procList = procPtr;
2644     Tcl_MutexUnlock(&pipeMutex);
2645 }
2646 
2647 /*
2648  *----------------------------------------------------------------------
2649  *
2650  * Tcl_PidObjCmd --
2651  *
2652  *	This procedure is invoked to process the "pid" Tcl command.
2653  *	See the user documentation for details on what it does.
2654  *
2655  * Results:
2656  *	A standard Tcl result.
2657  *
2658  * Side effects:
2659  *	See the user documentation.
2660  *
2661  *----------------------------------------------------------------------
2662  */
2663 
2664 	/* ARGSUSED */
2665 int
Tcl_PidObjCmd(ClientData dummy,Tcl_Interp * interp,int objc,Tcl_Obj * CONST * objv)2666 Tcl_PidObjCmd(
2667     ClientData dummy,		/* Not used. */
2668     Tcl_Interp *interp,		/* Current interpreter. */
2669     int objc,			/* Number of arguments. */
2670     Tcl_Obj *CONST *objv)	/* Argument strings. */
2671 {
2672     Tcl_Channel chan;
2673     Tcl_ChannelType *chanTypePtr;
2674     PipeInfo *pipePtr;
2675     int i;
2676     Tcl_Obj *resultPtr;
2677     char buf[TCL_INTEGER_SPACE];
2678 
2679     if (objc > 2) {
2680 	Tcl_WrongNumArgs(interp, 1, objv, "?channelId?");
2681 	return TCL_ERROR;
2682     }
2683     if (objc == 1) {
2684 	resultPtr = Tcl_GetObjResult(interp);
2685 	wsprintfA(buf, "%lu", (unsigned long) getpid());
2686 	Tcl_SetStringObj(resultPtr, buf, -1);
2687     } else {
2688         chan = Tcl_GetChannel(interp, Tcl_GetStringFromObj(objv[1], NULL),
2689 		NULL);
2690         if (chan == (Tcl_Channel) NULL) {
2691 	    return TCL_ERROR;
2692 	}
2693 	chanTypePtr = Tcl_GetChannelType(chan);
2694 	if (chanTypePtr != &pipeChannelType) {
2695 	    return TCL_OK;
2696 	}
2697 
2698         pipePtr = (PipeInfo *) Tcl_GetChannelInstanceData(chan);
2699 	resultPtr = Tcl_GetObjResult(interp);
2700         for (i = 0; i < pipePtr->numPids; i++) {
2701 	    wsprintfA(buf, "%lu", TclpGetPid(pipePtr->pidPtr[i]));
2702 	    Tcl_ListObjAppendElement(/*interp*/ NULL, resultPtr,
2703 		    Tcl_NewStringObj(buf, -1));
2704 	}
2705     }
2706     return TCL_OK;
2707 }
2708 
2709 /*
2710  *----------------------------------------------------------------------
2711  *
2712  * WaitForRead --
2713  *
2714  *	Wait until some data is available, the pipe is at
2715  *	EOF or the reader thread is blocked waiting for data (if the
2716  *	channel is in non-blocking mode).
2717  *
2718  * Results:
2719  *	Returns 1 if pipe is readable.  Returns 0 if there is no data
2720  *	on the pipe, but there is buffered data.  Returns -1 if an
2721  *	error occurred.  If an error occurred, the threads may not
2722  *	be synchronized.
2723  *
2724  * Side effects:
2725  *	Updates the shared state flags and may consume 1 byte of data
2726  *	from the pipe.  If no error occurred, the reader thread is
2727  *	blocked waiting for a signal from the main thread.
2728  *
2729  *----------------------------------------------------------------------
2730  */
2731 
2732 static int
WaitForRead(PipeInfo * infoPtr,int blocking)2733 WaitForRead(
2734     PipeInfo *infoPtr,		/* Pipe state. */
2735     int blocking)		/* Indicates whether call should be
2736 				 * blocking or not. */
2737 {
2738     DWORD timeout, count;
2739     HANDLE *handle = ((WinFile *) infoPtr->readFile)->handle;
2740 
2741     while (1) {
2742 	/*
2743 	 * Synchronize with the reader thread.
2744 	 */
2745 
2746 	timeout = blocking ? INFINITE : 0;
2747 	if (WaitForSingleObject(infoPtr->readable, timeout) == WAIT_TIMEOUT) {
2748 	    /*
2749 	     * The reader thread is blocked waiting for data and the channel
2750 	     * is in non-blocking mode.
2751 	     */
2752 
2753 	    errno = EAGAIN;
2754 	    return -1;
2755 	}
2756 
2757 	/*
2758 	 * At this point, the two threads are synchronized, so it is safe
2759 	 * to access shared state.
2760 	 */
2761 
2762 
2763 	/*
2764 	 * If the pipe has hit EOF, it is always readable.
2765 	 */
2766 
2767 	if (infoPtr->readFlags & PIPE_EOF) {
2768 	    return 1;
2769 	}
2770 
2771 	/*
2772 	 * Check to see if there is any data sitting in the pipe.
2773 	 */
2774 
2775 	if (PeekNamedPipe(handle, (LPVOID) NULL, (DWORD) 0,
2776 		(LPDWORD) NULL, &count, (LPDWORD) NULL) != TRUE) {
2777 	    TclWinConvertError(GetLastError());
2778 	    /*
2779 	     * Check to see if the peek failed because of EOF.
2780 	     */
2781 
2782 	    if (errno == EPIPE) {
2783 		infoPtr->readFlags |= PIPE_EOF;
2784 		return 1;
2785 	    }
2786 
2787 	    /*
2788 	     * Ignore errors if there is data in the buffer.
2789 	     */
2790 
2791 	    if (infoPtr->readFlags & PIPE_EXTRABYTE) {
2792 		return 0;
2793 	    } else {
2794 		return -1;
2795 	    }
2796 	}
2797 
2798 	/*
2799 	 * We found some data in the pipe, so it must be readable.
2800 	 */
2801 
2802 	if (count > 0) {
2803 	    return 1;
2804 	}
2805 
2806 	/*
2807 	 * The pipe isn't readable, but there is some data sitting
2808 	 * in the buffer, so return immediately.
2809 	 */
2810 
2811 	if (infoPtr->readFlags & PIPE_EXTRABYTE) {
2812 	    return 0;
2813 	}
2814 
2815 	/*
2816 	 * There wasn't any data available, so reset the thread and
2817 	 * try again.
2818 	 */
2819 
2820 	ResetEvent(infoPtr->readable);
2821 	SetEvent(infoPtr->startReader);
2822     }
2823 }
2824 
2825 /*
2826  *----------------------------------------------------------------------
2827  *
2828  * PipeReaderThread --
2829  *
2830  *	This function runs in a separate thread and waits for input
2831  *	to become available on a pipe.
2832  *
2833  * Results:
2834  *	None.
2835  *
2836  * Side effects:
2837  *	Signals the main thread when input become available.  May
2838  *	cause the main thread to wake up by posting a message.  May
2839  *	consume one byte from the pipe for each wait operation.  Will
2840  *	cause a memory leak of ~4k, if forcefully terminated with
2841  *	TerminateThread().
2842  *
2843  *----------------------------------------------------------------------
2844  */
2845 
2846 static DWORD WINAPI
PipeReaderThread(LPVOID arg)2847 PipeReaderThread(LPVOID arg)
2848 {
2849     PipeInfo *infoPtr = (PipeInfo *)arg;
2850     HANDLE *handle = ((WinFile *) infoPtr->readFile)->handle;
2851     DWORD count, err;
2852     int done = 0;
2853     HANDLE wEvents[2];
2854     DWORD waitResult;
2855 
2856     wEvents[0] = infoPtr->stopReader;
2857     wEvents[1] = infoPtr->startReader;
2858 
2859     while (!done) {
2860 	/*
2861 	 * Wait for the main thread to signal before attempting to wait
2862 	 * on the pipe becoming readable.
2863 	 */
2864 
2865 	waitResult = WaitForMultipleObjects(2, wEvents, FALSE, INFINITE);
2866 
2867 	if (waitResult != (WAIT_OBJECT_0 + 1)) {
2868 	    /*
2869 	     * The start event was not signaled.  It might be the stop event
2870 	     * or an error, so exit.
2871 	     */
2872 
2873 	    break;
2874 	}
2875 
2876 	/*
2877 	 * Try waiting for 0 bytes.  This will block until some data is
2878 	 * available on NT, but will return immediately on Win 95.  So,
2879 	 * if no data is available after the first read, we block until
2880 	 * we can read a single byte off of the pipe.
2881 	 */
2882 
2883 	if ((ReadFile(handle, NULL, 0, &count, NULL) == FALSE)
2884 		|| (PeekNamedPipe(handle, NULL, 0, NULL, &count,
2885 			NULL) == FALSE)) {
2886 	    /*
2887 	     * The error is a result of an EOF condition, so set the
2888 	     * EOF bit before signalling the main thread.
2889 	     */
2890 
2891 	    err = GetLastError();
2892 	    if (err == ERROR_BROKEN_PIPE) {
2893 		infoPtr->readFlags |= PIPE_EOF;
2894 		done = 1;
2895 	    } else if (err == ERROR_INVALID_HANDLE) {
2896 		break;
2897 	    }
2898 	} else if (count == 0) {
2899 	    if (ReadFile(handle, &(infoPtr->extraByte), 1, &count, NULL)
2900 		    != FALSE) {
2901 		/*
2902 		 * One byte was consumed as a side effect of waiting
2903 		 * for the pipe to become readable.
2904 		 */
2905 
2906 		infoPtr->readFlags |= PIPE_EXTRABYTE;
2907 	    } else {
2908 		err = GetLastError();
2909 		if (err == ERROR_BROKEN_PIPE) {
2910 		    /*
2911 		     * The error is a result of an EOF condition, so set the
2912 		     * EOF bit before signalling the main thread.
2913 		     */
2914 
2915 		    infoPtr->readFlags |= PIPE_EOF;
2916 		    done = 1;
2917 		} else if (err == ERROR_INVALID_HANDLE) {
2918 		    break;
2919 		}
2920 	    }
2921 	}
2922 
2923 
2924 	/*
2925 	 * Signal the main thread by signalling the readable event and
2926 	 * then waking up the notifier thread.
2927 	 */
2928 
2929 	SetEvent(infoPtr->readable);
2930 
2931 	/*
2932 	 * Alert the foreground thread.  Note that we need to treat this like
2933 	 * a critical section so the foreground thread does not terminate
2934 	 * this thread while we are holding a mutex in the notifier code.
2935 	 */
2936 
2937 	Tcl_MutexLock(&pipeMutex);
2938 	Tcl_ThreadAlert(infoPtr->threadId);
2939 	Tcl_MutexUnlock(&pipeMutex);
2940     }
2941 
2942     return 0;
2943 }
2944 
2945 /*
2946  *----------------------------------------------------------------------
2947  *
2948  * PipeWriterThread --
2949  *
2950  *	This function runs in a separate thread and writes data
2951  *	onto a pipe.
2952  *
2953  * Results:
2954  *	Always returns 0.
2955  *
2956  * Side effects:
2957  *	Signals the main thread when an output operation is completed.
2958  *	May cause the main thread to wake up by posting a message.
2959  *
2960  *----------------------------------------------------------------------
2961  */
2962 
2963 static DWORD WINAPI
PipeWriterThread(LPVOID arg)2964 PipeWriterThread(LPVOID arg)
2965 {
2966 
2967     PipeInfo *infoPtr = (PipeInfo *)arg;
2968     HANDLE *handle = ((WinFile *) infoPtr->writeFile)->handle;
2969     DWORD count, toWrite;
2970     char *buf;
2971     int done = 0;
2972     HANDLE wEvents[2];
2973     DWORD waitResult;
2974 
2975     wEvents[0] = infoPtr->stopWriter;
2976     wEvents[1] = infoPtr->startWriter;
2977 
2978     while (!done) {
2979 	/*
2980 	 * Wait for the main thread to signal before attempting to write.
2981 	 */
2982 
2983 	waitResult = WaitForMultipleObjects(2, wEvents, FALSE, INFINITE);
2984 
2985 	if (waitResult != (WAIT_OBJECT_0 + 1)) {
2986 	    /*
2987 	     * The start event was not signaled.  It might be the stop event
2988 	     * or an error, so exit.
2989 	     */
2990 
2991 	    break;
2992 	}
2993 
2994 	buf = infoPtr->writeBuf;
2995 	toWrite = infoPtr->toWrite;
2996 
2997 	/*
2998 	 * Loop until all of the bytes are written or an error occurs.
2999 	 */
3000 
3001 	while (toWrite > 0) {
3002 	    if (WriteFile(handle, buf, toWrite, &count, NULL) == FALSE) {
3003 		infoPtr->writeError = GetLastError();
3004 		done = 1;
3005 		break;
3006 	    } else {
3007 		toWrite -= count;
3008 		buf += count;
3009 	    }
3010 	}
3011 
3012 	/*
3013 	 * Signal the main thread by signalling the writable event and
3014 	 * then waking up the notifier thread.
3015 	 */
3016 
3017 	SetEvent(infoPtr->writable);
3018 
3019 	/*
3020 	 * Alert the foreground thread.  Note that we need to treat this like
3021 	 * a critical section so the foreground thread does not terminate
3022 	 * this thread while we are holding a mutex in the notifier code.
3023 	 */
3024 
3025 	Tcl_MutexLock(&pipeMutex);
3026 	Tcl_ThreadAlert(infoPtr->threadId);
3027 	Tcl_MutexUnlock(&pipeMutex);
3028     }
3029 
3030     return 0;
3031 }
3032 
3033