Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: downloads/tcl8.5.2/win/tclWinPipe.c @ 68

Last change on this file since 68 was 25, checked in by landauf, 16 years ago

added tcl to libs

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