Debian Codegraph @

generic/bltWinPipe.c

raw symbols SCIP
1
2 /*
3 * bltWinPipe.c --
4 *
5 * Lifted from tclPipe.c and tclWinPipe.c in the Tcl
6 * distribution, this is the first step toward freedom from the
7 * tyranny of the former Tcl_CreatePipeline API.
8 *
9 * This file contains the generic portion of the command channel
10 * driver as well as various utility routines used in managing
11 * subprocesses.
12 *
13 * [It's not clear why we needed a whole new API for I/O. Channels
14 * are one of the few losing propositions in Tcl. While it's easy
15 * to see that one needs to handle the different platform I/O
16 * semantics in a coherent fashion, it's usually better to pick
17 * an API from one of platforms (hopefully a mature, well-known model)
18 * and crowbar the other platforms to follow that. At least then
19 * you're working from a known set of sematics. With Tcl Channels,
20 * no one's an expert and the interface is incomplete.]
21 *
22 * Copyright (c) 1997 by Sun Microsystems, Inc.
23 *
24 * See the file "license.terms" for information on usage and redistribution
25 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
26 *
27 */
28
29 /*
30 * Todo:
31 * Test on win95
32 * Does terminating bltwish kill child processes?
33 * Handle EOL translation more cleanly.
34 */
35
36 #include "bltInt.h"
37 #include "bltChain.h"
38 #include <fcntl.h>
39
40 #define PEEK_DEBUG 0
41 #define QUEUE_DEBUG 0
42 #define READER_DEBUG 0
43 #define ASYNC_DEBUG 0
44 #define KILL_DEBUG 0
45
46 typedef struct {
47 DWORD pid;
48 HANDLE hProcess;
49 } Process;
50
51 /*
52 * The following type identifies the various types of applications that
53 * run under windows. There is special case code for the various types.
54 */
55 typedef enum ApplicationTypes {
56 APPL_NONE, APPL_DOS, APPL_WIN3X, APPL_WIN32, APPL_INTERP
57 } ApplicationType;
58
59 #ifndef IMAGE_OS2_SIGNATURE
60 # define IMAGE_OS2_SIGNATURE (0x454E)
61 #endif
62 #ifndef IMAGE_VXD_SIGNATURE
63 # define IMAGE_VXD_SIGNATURE (0x454C)
64 #endif
65
66 #define PIPE_BUFSIZ (BUFSIZ*2) /* Size of pipe read buffer. */
67
68 #define PIPE_PENDING (1<<13) /* Message is pending in the queue. */
69 #define PIPE_EOF (1<<14) /* Pipe has reached EOF. */
70 #define PIPE_DELETED (1<<15) /* Indicates if the pipe has been deleted
71 * but its memory hasn't been freed yet. */
72
73 typedef struct {
74 int flags; /* State flags, see above for a list. */
75 HANDLE hPipe; /* Pipe handle */
76 HANDLE thread; /* Thread watching I/O on this pipe. */
77 HANDLE parent; /* Handle of main thread. */
78 DWORD parentId; /* Main thread ID. */
79 HWND hWindow; /* Notifier window in main thread. Used to
80 * goose the Tcl notifier system indicating
81 * that an event has occurred that it
82 * needs to process. */
83 HANDLE idleEvent; /* Signals that the pipe is idle (no one
84 * is reading/writing from it). */
85 HANDLE readyEvent; /* Signals that the pipe is ready for
86 * the next I/O operation. */
87
88 DWORD lastError; /* Error. */
89
90 char *buffer; /* Current background output buffer. */
91 size_t start, end; /* Pointers into the output buffer */
92 size_t size; /* Size of buffer. */
93
94 Tcl_FileProc *proc;
95 ClientData clientData;
96
97 } PipeHandler;
98
99
100 typedef struct {
101 Tcl_Event header; /* Information that is standard for
102 * all events. */
103
104 PipeHandler *pipePtr; /* Pointer to pipe handler structure.
105 * Note that we still have to verify
106 * that the pipe exists before
107 * dereferencing this pointer. */
108 } PipeEvent;
109
110 static int initialized = 0;
111 static Blt_Chain pipeChain;
112 static CRITICAL_SECTION pipeCriticalSection;
113
114 static DWORD WINAPI PipeWriterThread(void *clientData);
115 static DWORD WINAPI PipeReaderThread(void *clientData);
116
117 static Tcl_FreeProc DestroyPipe;
118
119 extern void Blt_MapPid(HANDLE hProcess, DWORD pid);
120 extern HINSTANCE TclWinGetTclInstance(void);
121 extern void TclWinConvertError(DWORD lastError);
122
123 /*
124 *----------------------------------------------------------------------
125 *
126 * NotifierWindowProc --
127 *
128 * This procedure is called to "goose" the Tcl notifier layer to
129 * service pending events. The notifier layer is built upon the
130 * Windows message system. It may need to be awakened if it's
131 * blocked waiting on messages, since synthetic events (i.e.
132 * data available on a pipe) won't do that. There may be events
133 * pending in the Tcl queue, but the Windows message system knows
134 * nothing about Tcl events and won't unblock until the next
135 * message arrives (whenever that may be).
136 *
137 * This callback is triggered by messages posted to the notifier
138 * window (we set up earlier) from the reader/writer pipe
139 * threads. It's purpose is to 1) unblock Windows (posting the
140 * message does that) and 2) call Tcl_ServiceAll from the main
141 * thread. It has to be called from the main thread, not
142 * directly from the pipe threads.
143 *
144 * Results:
145 * A standard Windows result.
146 *
147 * Side effects:
148 * Services any pending Tcl events.
149 *
150 *----------------------------------------------------------------------
151 */
152 static LRESULT CALLBACK
153 NotifierWindowProc(
154 HWND hWindow,
155 UINT message,
156 WPARAM wParam,
157 LPARAM lParam)
158 {
159 switch (message) {
160 case WM_USER:
161 case WM_TIMER:
162 break;
163
164 default:
165 return DefWindowProc(hWindow, message, wParam, lParam);
166 }
167
168 Tcl_ServiceAll(); /* Process all run-able events. */
169 return 0;
170 }
171
172 static void
173 WakeupNotifier(HWND hWindow)
174 {
175 PostMessage(hWindow, WM_USER, 0, 0);
176 }
177
178 /*
179 *----------------------------------------------------------------------
180 *
181 * GetNotifierWindow --
182 *
183 * Initializes the platform specific notifier state.
184 *
185 * Results:
186 * Returns a handle to the notifier state for this thread..
187 *
188 * Side effects:
189 * None.
190 *
191 *----------------------------------------------------------------------
192 */
193
194 static HWND
195 GetNotifierWindow(void)
196 {
197 static HWND hWindow = NULL;
198 /*
199 * Register Notifier window class if this is the first thread to
200 * use this module.
201 */
202 if (hWindow == NULL) {
203 WNDCLASS class;
204 HINSTANCE hInstance;
205
206 memset(&class, 0, sizeof(WNDCLASS));
207 hInstance = TclWinGetTclInstance();
208 class.hInstance = hInstance;
209 class.lpszClassName = "PipeNotifier";
210 class.lpfnWndProc = NotifierWindowProc;
211
212 if (!RegisterClassA(&class)) {
213 panic("Unable to register PipeNotifier window class");
214 }
215 /*
216 * Create a window for communication with the notifier.
217 */
218 hWindow = CreateWindowA("PipeNotifier", "PipeNotifier", WS_TILED,
219 0, 0, 0, 0, NULL, NULL, hInstance, NULL);
220 }
221 return hWindow;
222 }
223
224 /*
225 *----------------------------------------------------------------------
226 *
227 * PeekOnPipe --
228 *
229 * See if some data is available, the pipe is at EOF, or the
230 * reader thread is currently blocked waiting for data.
231 *
232 * Results:
233 * Return TRUE if data is available, FALSE if otherwise. Note
234 * that errors and EOF always return TRUE. We always make the
235 * condition available until the caller handles it by deleting
236 * the pipe event handler.
237 *
238 * On TRUE, the number of bytes returned indicates the following:
239 * 0 EOF.
240 * -1 An error has occured or the thread is currently
241 * blocked reading. In that last case, errno is set
242 * to EAGAIN.
243 * >0 Number of bytes of data in the buffer.
244 *
245 *----------------------------------------------------------------------
246 */
247 static int
248 PeekOnPipe(
249 PipeHandler *pipePtr, /* Pipe state. */
250 int *nAvailPtr)
251 {
252 int state;
253
254 *nAvailPtr = -1;
255 #if PEEK_DEBUG
256 PurifyPrintf("PEEK(%d): waiting for reader\n", pipePtr->hPipe);
257 #endif
258 state = WaitForSingleObject(pipePtr->readyEvent, 0);
259 #if PEEK_DEBUG
260 PurifyPrintf("PEEK(%d): state is %d\n", pipePtr->hPipe, state);
261 #endif
262 if (state == WAIT_TIMEOUT) {
263 #if PEEK_DEBUG
264 PurifyPrintf("PEEK(%d): try again, %d\n", pipePtr->hPipe, state);
265 #endif
266 errno = EAGAIN;
267 return FALSE; /* Reader thread is currently blocked. */
268 }
269 /*
270 * At this point the two threads are synchronized. So it's safe
271 * to access shared information.
272 */
273 if (state == WAIT_OBJECT_0) {
274 int nAvail;
275
276 nAvail = pipePtr->end - pipePtr->start;
277 #if PEEK_DEBUG
278 PurifyPrintf("PEEK(%d): Found %d bytes available\n",
279 pipePtr->hPipe, nAvail);
280 #endif
281 if ((nAvail <= 0) && !(pipePtr->flags & PIPE_EOF)) {
282 TclWinConvertError(pipePtr->lastError);
283 #if PEEK_DEBUG
284 PurifyPrintf("PEEK(%d): Error = %d\n",
285 pipePtr->hPipe, pipePtr->lastError);
286 #endif
287 nAvail = -1;
288 }
289 *nAvailPtr = nAvail;
290 }
291 #if PEEK_DEBUG
292 PurifyPrintf("PEEK(%d): Reseting events\n", pipePtr->hPipe);
293 #endif
294 return TRUE;
295 }
296
297 /*
298 *----------------------------------------------------------------------
299 *
300 * PipeEventProc --
301 *
302 * This function is invoked by Tcl_ServiceEvent when a file event
303 * reaches the front of the event queue. This procedure calls back
304 * the handler procedure designated for this pipe.
305 *
306 * Results:
307 * Returns 1 if the event was handled, meaning it should be removed
308 * from the queue. Returns 0 if the event was not handled, meaning
309 * it should stay on the queue. The only time the event isn't
310 * handled is if the TCL_FILE_EVENTS flag bit isn't set.
311 *
312 * Side effects:
313 * Whatever the pipe handler callback does.
314 *
315 *----------------------------------------------------------------------
316 */
317 static int
318 PipeEventProc(Tcl_Event * eventPtr, int flags)
319 {
320 PipeHandler *pipePtr;
321
322 if (!(flags & TCL_FILE_EVENTS)) {
323 return 0;
324 }
325 pipePtr = ((PipeEvent *) eventPtr)->pipePtr;
326 if ((pipePtr != NULL) && !(pipePtr->flags & PIPE_DELETED)) {
327 Tcl_Preserve(pipePtr);
328 if (pipePtr->proc != NULL) {
329 (*pipePtr->proc) (pipePtr->clientData, flags);
330 }
331 /* Allow more events again. */
332 pipePtr->flags &= ~PIPE_PENDING;
333 Tcl_Release(pipePtr);
334 }
335 return 1;
336 }
337
338 /*
339 *----------------------------------------------------------------------
340 *
341 * SetupHandlers --
342 *
343 * This procedure is invoked before Tcl_DoOneEvent blocks waiting
344 * for an event.
345 *
346 * Results:
347 * None.
348 *
349 * Side effects:
350 * Adjusts the block time if needed.
351 *
352 *----------------------------------------------------------------------
353 */
354 void
355 SetupHandlers(ClientData clientData, int flags)
356 {
357 Blt_Chain *chainPtr = (Blt_Chain *) clientData;
358 register PipeHandler *pipePtr;
359 Blt_ChainLink *linkPtr;
360 int dontBlock, nBytes;
361 Tcl_Time blockTime;
362
363 if (!(flags & TCL_FILE_EVENTS)) {
364 return;
365 }
366 /*
367 * Loop through the list of pipe handlers. Check if any I/O
368 * events are currently pending.
369 */
370 dontBlock = FALSE;
371 blockTime.sec = blockTime.usec = 0L;
372 #if QUEUE_DEBUG
373 PurifyPrintf("SetupHandlers: before loop\n");
374 #endif
375 for (linkPtr = Blt_ChainFirstLink(chainPtr); linkPtr != NULL;
376 linkPtr = Blt_ChainNextLink(linkPtr)) {
377 pipePtr = Blt_ChainGetValue(linkPtr);
378 if (pipePtr->flags & PIPE_DELETED) {
379 continue; /* Ignore pipes pending to be freed. */
380 }
381 if (pipePtr->flags & TCL_READABLE) {
382 if (PeekOnPipe(pipePtr, &nBytes)) {
383 dontBlock = TRUE;
384 }
385 }
386 if (pipePtr->flags & TCL_WRITABLE) {
387 if (WaitForSingleObject(pipePtr->readyEvent, 0) != WAIT_TIMEOUT) {
388 dontBlock = TRUE;
389 }
390 }
391 }
392 #if QUEUE_DEBUG
393 PurifyPrintf("SetupHandlers: after loop\n");
394 #endif
395 if (dontBlock) {
396 Tcl_SetMaxBlockTime(&blockTime);
397 }
398 }
399
400 /*
401 *----------------------------------------------------------------------
402 *
403 * CheckHandlers --
404 *
405 * This procedure is called by Tcl_DoOneEvent to check the pipe
406 * event source for events.
407 *
408 * Results:
409 * None.
410 *
411 * Side effects:
412 * May queue an event.
413 *
414 *----------------------------------------------------------------------
415 */
416 static void
417 CheckHandlers(ClientData clientData, int flags)
418 {
419 Blt_Chain *chainPtr = (Blt_Chain *) clientData;
420 PipeHandler *pipePtr;
421 Blt_ChainLink *linkPtr;
422 int queueEvent, nBytes;
423
424 if ((flags & TCL_FILE_EVENTS) == 0) {
425 return;
426 }
427 /* Queue events for any ready pipes that aren't already queued. */
428
429 for (linkPtr = Blt_ChainFirstLink(chainPtr); linkPtr != NULL;
430 linkPtr = Blt_ChainNextLink(linkPtr)) {
431 pipePtr = Blt_ChainGetValue(linkPtr);
432 if (pipePtr->flags & (PIPE_PENDING | PIPE_DELETED)) {
433 continue; /* If this pipe already is scheduled to
434 * service an event, wait for it to handle
435 * it. */
436 }
437 /* Queue an event if the pipe is signaled for reading or writing. */
438 queueEvent = FALSE;
439 if (pipePtr->flags & TCL_READABLE) {
440 if (PeekOnPipe(pipePtr, &nBytes)) {
441 queueEvent = TRUE;
442 }
443 }
444 if (pipePtr->flags & TCL_WRITABLE) {
445 if (WaitForSingleObject(pipePtr->readyEvent, 0) != WAIT_TIMEOUT) {
446 queueEvent = TRUE;
447 }
448 }
449 #if QUEUE_DEBUG
450 PurifyPrintf("Queue event is %d \n", queueEvent);
451 #endif
452 if (queueEvent) {
453 PipeEvent *eventPtr;
454
455 pipePtr->flags |= PIPE_PENDING;
456 eventPtr = Blt_Malloc(sizeof(PipeEvent));
457 assert(eventPtr);
458 eventPtr->header.proc = PipeEventProc;
459 eventPtr->pipePtr = pipePtr;
460 Tcl_QueueEvent((Tcl_Event *) eventPtr, TCL_QUEUE_TAIL);
461 }
462 }
463 }
464
465 static PipeHandler *
466 CreatePipeHandler(HANDLE hFile, int flags)
467 {
468 DWORD id;
469 PipeHandler *pipePtr;
470 LPTHREAD_START_ROUTINE threadProc;
471
472 pipePtr = Blt_Calloc(1, sizeof(PipeHandler));
473 assert(pipePtr);
474
475 pipePtr->hPipe = hFile;
476 pipePtr->flags = flags;
477 pipePtr->parentId = GetCurrentThreadId();
478 pipePtr->parent = GetCurrentThread();
479 pipePtr->hWindow = GetNotifierWindow();
480 pipePtr->readyEvent = CreateEvent(
481 NULL, /* Security attributes. */
482 TRUE, /* Manual reset event */
483 FALSE, /* Initially not signaled. */
484 NULL); /* Event object's name. */
485 pipePtr->idleEvent = CreateEvent(
486 NULL, /* Security attributes. */
487 FALSE, /* Auto reset event. */
488 TRUE, /* Initially signaled. */
489 NULL); /* Event object's name. */
490
491 if (flags & TCL_READABLE) {
492 threadProc = (LPTHREAD_START_ROUTINE) PipeReaderThread;
493 pipePtr->buffer = Blt_Calloc(1, PIPE_BUFSIZ);
494 pipePtr->size = PIPE_BUFSIZ;
495 } else {
496 threadProc = (LPTHREAD_START_ROUTINE) PipeWriterThread;
497 }
498
499 pipePtr->thread = CreateThread(
500 NULL, /* Security attributes */
501 8000, /* Initial stack size. */
502 threadProc, /* Starting address of thread routine */
503 (DWORD *) pipePtr, /* One-word of data passed to routine. */
504 0, /* Creation flags */
505 &id); /* (out) Will contain Id of new thread. */
506 return pipePtr;
507 }
508
509 static void
510 DestroyPipe(DestroyData data)
511 {
512 PipeHandler *pipePtr = (PipeHandler *)data;
513
514 if (pipePtr->buffer != NULL) {
515 Blt_Free(pipePtr->buffer);
516 }
517 Blt_Free(pipePtr);
518 }
519
520 static void
521 DeletePipeHandler(PipeHandler * pipePtr)
522 {
523 #if KILL_DEBUG
524 PurifyPrintf("DestroyPipeHandler(%d)\n", pipePtr->hPipe);
525 #endif
526 if ((pipePtr->flags & TCL_WRITABLE) &&
527 (pipePtr->hPipe != INVALID_HANDLE_VALUE)) {
528 /* Wait for the writer thread to finish with the current buffer */
529 WaitForSingleObject(pipePtr->idleEvent, INFINITE);
530 }
531 if (pipePtr->hPipe != INVALID_HANDLE_VALUE) {
532 CloseHandle(pipePtr->hPipe);
533 }
534 CloseHandle(pipePtr->readyEvent);
535 CloseHandle(pipePtr->idleEvent);
536 CloseHandle(pipePtr->thread);
537
538 pipePtr->idleEvent = pipePtr->readyEvent = INVALID_HANDLE_VALUE;
539 pipePtr->thread = pipePtr->hPipe = INVALID_HANDLE_VALUE;
540 pipePtr->flags |= PIPE_DELETED; /* Mark the pipe has deleted. */
541
542 Tcl_EventuallyFree(pipePtr, DestroyPipe);
543 }
544
545 /*
546 *----------------------------------------------------------------------
547 *
548 * PipeInit --
549 *
550 * This function initializes the static variables for this file.
551 *
552 * Results:
553 * None.
554 *
555 * Side effects:
556 * Creates a new event source.
557 *
558 *----------------------------------------------------------------------
559 */
560 static void
561 PipeInit(void)
562 {
563 initialized = TRUE;
564 InitializeCriticalSection(&pipeCriticalSection);
565 Blt_ChainInit(&pipeChain);
566 Tcl_CreateEventSource(SetupHandlers, CheckHandlers, &pipeChain);
567 }
568
569 static PipeHandler *
570 GetPipeHandler(HANDLE hPipe)
571 {
572 PipeHandler *pipePtr;
573 Blt_ChainLink *linkPtr;
574
575 for (linkPtr = Blt_ChainFirstLink(&pipeChain); linkPtr != NULL;
576 linkPtr = Blt_ChainNextLink(linkPtr)) {
577 pipePtr = Blt_ChainGetValue(linkPtr);
578 if ((pipePtr->hPipe == hPipe) && !(pipePtr->flags & PIPE_DELETED)){
579 return pipePtr;
580 }
581 }
582 return NULL;
583 }
584
585 /*
586 *----------------------------------------------------------------------
587 *
588 * Blt_PipeTeardown --
589 *
590 * This function releases any storage allocated for this file.
591 *
592 * Results:
593 * None.
594 *
595 * Side effects:
596 * Creates a new event source.
597 *
598 *----------------------------------------------------------------------
599 */
600 void
601 Blt_PipeTeardown(void)
602 {
603 Blt_ChainLink *linkPtr;
604 PipeHandler *pipePtr;
605
606 if (!initialized) {
607 return; /* Was never initialized. */
608 }
609 initialized = FALSE;
610 EnterCriticalSection(&pipeCriticalSection);
611 for (linkPtr = Blt_ChainFirstLink(&pipeChain); linkPtr != NULL;
612 linkPtr = Blt_ChainNextLink(linkPtr)) {
613 pipePtr = Blt_ChainGetValue(linkPtr);
614 if ((pipePtr != NULL) && !(pipePtr->flags & PIPE_DELETED)) {
615 DeletePipeHandler(pipePtr);
616 }
617 }
618 DestroyWindow(GetNotifierWindow());
619 UnregisterClassA("PipeNotifier", TclWinGetTclInstance());
620
621 Blt_ChainReset(&pipeChain);
622 LeaveCriticalSection(&pipeCriticalSection);
623 Tcl_DeleteEventSource(SetupHandlers, CheckHandlers, &pipeChain);
624 DeleteCriticalSection(&pipeCriticalSection);
625 }
626
627 /*
628 *----------------------------------------------------------------------
629 *
630 * PipeReaderThread --
631 *
632 * This function runs in a separate thread and waits for input
633 * to become available on a pipe.
634 *
635 * Results:
636 * None.
637 *
638 * Side effects:
639 * Signals the main thread when input become available. May
640 * cause the main thread to wake up by posting a message.
641 *
642 *----------------------------------------------------------------------
643 */
644 static DWORD WINAPI
645 PipeReaderThread(void *clientData)
646 {
647 PipeHandler *pipePtr = (PipeHandler *) clientData;
648 DWORD count;
649 BOOL result;
650
651 for (;;) {
652 if (pipePtr->flags & PIPE_DELETED) {
653 break;
654 }
655 /* Synchronize with the main thread so that we don't try to
656 * read from the pipe while it's copying to the buffer. */
657 #if READER_DEBUG
658 PurifyPrintf("READER(%d): waiting\n", pipePtr->hPipe);
659 #endif
660 WaitForSingleObject(pipePtr->idleEvent, INFINITE);
661 #if READER_DEBUG
662 PurifyPrintf("READER(%d): ok\n", pipePtr->hPipe);
663 #endif
664 /* Read from the pipe. The thread will block here until some
665 * data is read into its buffer. */
666 #if READER_DEBUG
667 PurifyPrintf("READER(%d): before read\n", pipePtr->hPipe);
668 #endif
669 assert(pipePtr->start == pipePtr->end);
670 result = ReadFile(
671 pipePtr->hPipe, /* Handle to anonymous pipe. */
672 pipePtr->buffer, /* Data buffer. */
673 pipePtr->size, /* Requested number of bytes (the size
674 * of the buffer) */
675 &count, /* (out) Number of bytes actually read. */
676 NULL); /* Overlapping I/O */
677
678 if (result) {
679 #if READER_DEBUG
680 PurifyPrintf("READER(%d): after read. status=%d, count=%d\n",
681 pipePtr->hPipe, result, count);
682 #endif
683 }
684 /*
685 * Reset counters to indicate that the buffer has been refreshed.
686 */
687 pipePtr->start = 0;
688 pipePtr->end = count;
689 if (count == 0) {
690 /* We've hit EOF or an error. */
691 pipePtr->lastError = GetLastError();
692 if ((pipePtr->lastError == ERROR_BROKEN_PIPE) ||
693 (pipePtr->lastError == ERROR_HANDLE_EOF)) {
694 pipePtr->flags |= PIPE_EOF;
695 }
696 #if READER_DEBUG
697 PurifyPrintf("READER(%d): error is %s\n",
698 pipePtr->hPipe, Blt_LastError());
699 #endif
700 }
701 WakeupNotifier(pipePtr->hWindow);
702 SetEvent(pipePtr->readyEvent);
703 if (count == 0) {
704 #if READER_DEBUG
705 PurifyPrintf("READER(%d): exiting\n", pipePtr->hPipe);
706 #endif
707 ExitThread(0);
708 }
709 }
710 /* NOTREACHED */
711 return 0;
712 }
713
714 /*
715 *----------------------------------------------------------------------
716 *
717 * PipeWriterThread --
718 *
719 * This function runs in a separate thread and writes data
720 * to the process' standard input pipe.
721 *
722 * Results:
723 * Always returns 0.
724 *
725 * Side effects:
726 * Signals the main thread when an output operation is completed.
727 * May cause the main thread to wake up by posting a message.
728 *
729 *----------------------------------------------------------------------
730 */
731 static DWORD WINAPI
732 PipeWriterThread(void *clientData)
733 {
734 PipeHandler *pipePtr = (PipeHandler *) clientData;
735 DWORD count, bytesLeft;
736 register char *ptr;
737
738 for (;;) {
739 if (pipePtr->flags & PIPE_DELETED) {
740 break;
741 }
742
743 /*
744 * Synchronize with the main thread so that we don't test the
745 * pipe until its done writing.
746 */
747
748 WaitForSingleObject(pipePtr->idleEvent, INFINITE);
749
750 ptr = pipePtr->buffer;
751 bytesLeft = pipePtr->end;
752
753 /* Loop until all of the bytes are written or an error occurs. */
754
755 while (bytesLeft > 0) {
756 if (!WriteFile(pipePtr->hPipe, ptr, bytesLeft, &count, NULL)) {
757 pipePtr->lastError = GetLastError();
758 break;
759 }
760 bytesLeft -= count;
761 ptr += count;
762 }
763
764 /* Tell the main thread that data can be written to the pipe.
765 * Remember to wake up the notifier thread. */
766
767 SetEvent(pipePtr->readyEvent);
768 WakeupNotifier(pipePtr->hWindow);
769 }
770 /* NOTREACHED */
771 return 0;
772 }
773
774 /*
775 *----------------------------------------------------------------------
776 *
777 * TempFileName --
778 *
779 * Gets a temporary file name and deals with the fact that the
780 * temporary file path provided by Windows may not actually exist
781 * if the TMP or TEMP environment variables refer to a
782 * non-existent directory.
783 *
784 * Results:
785 * 0 if error, non-zero otherwise. If non-zero is returned, the
786 * name buffer will be filled with a name that can be used to
787 * construct a temporary file.
788 *
789 * Side effects:
790 * None.
791 *
792 *----------------------------------------------------------------------
793 */
794
795 static int
796 TempFileName(char *name) /* (out) Buffer to hold name of
797 * temporary file. */
798 {
799 if ((GetTempPath(MAX_PATH, name) > 0) &&
800 (GetTempFileName(name, "TCL", 0, name))) {
801 return 1;
802 }
803 /* Bail out and use the current working directory. */
804 return GetTempFileName(".", "TCL", 0, name);
805 }
806
807 /*
808 *----------------------------------------------------------------------
809 *
810 * OpenRedirectFile --
811 *
812 * Open a file for use in a pipeline.
813 *
814 * Results:
815 * Returns a new handle or NULL on failure.
816 *
817 * Side effects:
818 * May cause a file to be created on the file system.
819 *
820 *----------------------------------------------------------------------
821 */
822 static HANDLE
823 OpenRedirectFile(
824 const char *path,
825 DWORD accessFlags,
826 DWORD createFlags)
827 {
828 HANDLE hFile;
829 DWORD attribFlags;
830 int useExisting;
831
832 attribFlags = 0;
833 useExisting = (createFlags & (TRUNCATE_EXISTING | OPEN_EXISTING));
834 if (useExisting) {
835 attribFlags = GetFileAttributes(path);
836 if (attribFlags == 0xFFFFFFFF) {
837 attribFlags = 0;
838 }
839 }
840 hFile = CreateFile(path,
841 accessFlags, /* Access mode flags */
842 FILE_SHARE_READ | FILE_SHARE_WRITE,
843 NULL, /* No security */
844 createFlags, /* Creation attributes */
845 attribFlags, /* File attribute flags */
846 NULL); /* Template file */
847
848 if (hFile == INVALID_HANDLE_VALUE) {
849 DWORD lastError;
850
851 lastError = GetLastError();
852 if ((lastError & 0xffffL) == ERROR_OPEN_FAILED) {
853 lastError = (useExisting)
854 ? ERROR_FILE_NOT_FOUND : ERROR_FILE_EXISTS;
855 }
856 TclWinConvertError(lastError);
857 return INVALID_HANDLE_VALUE;
858 }
859 /*
860 * Seek to the end of file if we are writing.
861 */
862 if (createFlags & GENERIC_WRITE) {
863 SetFilePointer(hFile, 0, NULL, FILE_END);
864 }
865 return hFile;
866 }
867
868 /*
869 *----------------------------------------------------------------------
870 *
871 * CreateTempFile --
872 *
873 * This function creates a temporary file initialized with an
874 * optional string, and returns a file handle with the file pointer
875 * at the beginning of the file.
876 *
877 * Results:
878 * A handle to a file.
879 *
880 * Side effects:
881 * None.
882 *
883 *----------------------------------------------------------------------
884 */
885 static HANDLE
886 CreateTempFile(const char *data) /* String to write into temp file, or
887 * NULL. */
888 {
889 char fileName[MAX_PATH + 1];
890 HANDLE hFile;
891 DWORD lastError;
892
893 if (!TempFileName(fileName)) {
894 return INVALID_HANDLE_VALUE;
895 }
896 hFile = CreateFile(
897 fileName, /* File path */
898 GENERIC_READ | GENERIC_WRITE, /* Access mode */
899 0, /* No sharing. */
900 NULL, /* Security attributes */
901 CREATE_ALWAYS, /* Overwrite any existing file */
902 FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE,
903 NULL); /* No template file */
904
905 if (hFile == INVALID_HANDLE_VALUE) {
906 goto error;
907 }
908 if (data != NULL) {
909 DWORD result, length;
910 const char *p;
911 const char *string;
912
913 string = data;
914 for (p = string; *p != '\0'; p++) {
915 if (*p == '\n') {
916 length = p - string;
917 if (length > 0) {
918 if (!WriteFile(hFile, string, length, &result, NULL)) {
919 goto error;
920 }
921 }
922 if (!WriteFile(hFile, "\r\n", 2, &result, NULL)) {
923 goto error;
924 }
925 string = p + 1;
926 }
927 }
928 length = p - string;
929 if (length > 0) {
930 if (!WriteFile(hFile, string, length, &result, NULL)) {
931 goto error;
932 }
933 }
934 if (SetFilePointer(hFile, 0, NULL, FILE_BEGIN) == (DWORD) - 1) {
935 goto error;
936 }
937 }
938 return hFile;
939
940 error:
941 lastError = GetLastError();
942 CloseHandle(hFile);
943 DeleteFile(fileName); /* Do I need this? Delete on close? */
944 TclWinConvertError(lastError);
945 return INVALID_HANDLE_VALUE;
946 }
947
948 /*
949 *----------------------------------------------------------------------
950 *
951 * HasConsole --
952 *
953 * Determines whether the current application is attached to a
954 * console.
955 *
956 * Results:
957 * Returns TRUE if this application has a console, else FALSE.
958 *
959 * Side effects:
960 * None.
961 *
962 *----------------------------------------------------------------------
963 */
964 static BOOL
965 HasConsole(void)
966 {
967 HANDLE hFile;
968
969 hFile = CreateFileA("CONOUT$", GENERIC_WRITE, FILE_SHARE_WRITE, NULL,
970 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
971 if (hFile == INVALID_HANDLE_VALUE) {
972 return FALSE;
973 }
974 CloseHandle(hFile);
975 return TRUE;
976 }
977
978 static ApplicationType
979 GetApplicationType(const char *file, char *cmdPrefix)
980 {
981 char *dot;
982 HANDLE hFile;
983 IMAGE_DOS_HEADER imageDosHeader;
984 ULONG signature;
985 BOOL result;
986 DWORD offset;
987 DWORD nBytes;
988 ApplicationType type;
989
990 dot = strrchr(file, '.');
991 if ((dot != NULL) && (strcasecmp(dot, ".bat") == 0)) {
992 return APPL_DOS;
993 }
994 /* Work a little harder. Open the binary and read the header */
995 hFile = CreateFileA(file, GENERIC_READ, FILE_SHARE_READ, NULL,
996 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
997 if (hFile == INVALID_HANDLE_VALUE) {
998 return APPL_NONE;
999 }
1000 type = APPL_NONE;
1001 result = ReadFile(hFile, &imageDosHeader, sizeof(IMAGE_DOS_HEADER),
1002 &nBytes, NULL);
1003 if ((!result) || (nBytes != sizeof(IMAGE_DOS_HEADER))) {
1004 goto done;
1005 }
1006 #if KILL_DEBUG
1007 PurifyPrintf("magic number is %x\n", imageDosHeader.e_magic);
1008 #endif
1009 if (imageDosHeader.e_magic == 0x2123) { /* #! */
1010 register char *p;
1011 register unsigned int i;
1012
1013 offset = SetFilePointer(hFile, 2, NULL, FILE_BEGIN);
1014 if (offset == (DWORD) - 1) {
1015 goto done;
1016 }
1017 result = ReadFile(hFile, cmdPrefix, MAX_PATH + 1, &nBytes, NULL);
1018 if ((!result) || (nBytes < 1)) {
1019 goto done;
1020 }
1021 for (p = cmdPrefix, i = 0; i < nBytes; i++, p++) {
1022 if ((*p == '\n') || (*p == '\r')) {
1023 break;
1024 }
1025 }
1026 *p = '\0';
1027 type = APPL_INTERP;
1028 goto done;
1029 }
1030 /*
1031 * Doesn't have the magic number for relocatable executables. If
1032 * filename ends with .com, assume it's a DOS application anyhow.
1033 * Note that we didn't make this assumption at first, because some
1034 * supposed .com files are really 32-bit executables with all the
1035 * magic numbers and everything.
1036 */
1037 if ((dot != NULL) && (strcmp(dot, ".com") == 0)) {
1038 #if KILL_DEBUG
1039 PurifyPrintf(".com\n");
1040 #endif
1041 type = APPL_DOS;
1042 goto done;
1043 }
1044 if (imageDosHeader.e_magic != IMAGE_DOS_SIGNATURE) {
1045 #if KILL_DEBUG
1046 PurifyPrintf("Application doesn't have correct sig?\n");
1047 #endif
1048 }
1049 if (imageDosHeader.e_lfarlc != sizeof(IMAGE_DOS_HEADER)) {
1050 /* This assumes that all 3.x and Win32 programs have their
1051 * file relocation table immediately following this header. */
1052 /*
1053 * All Windows 3.X and Win32 and some DOS programs have this value
1054 * set here. If it doesn't, assume that since it already had the
1055 * other magic number it was a DOS application.
1056 */
1057 #if KILL_DEBUG
1058 PurifyPrintf("wrong reloc table address\n");
1059 #endif
1060 type = APPL_DOS;
1061 goto done;
1062 }
1063 offset = SetFilePointer(hFile, imageDosHeader.e_lfanew, NULL, FILE_BEGIN);
1064 if (offset == (DWORD) - 1) {
1065 goto done;
1066 }
1067 result = ReadFile(hFile, &signature, sizeof(ULONG), &nBytes, NULL);
1068 if ((!result) || (nBytes != sizeof(ULONG))) {
1069 goto done;
1070 }
1071 #if KILL_DEBUG
1072 PurifyPrintf("signature is %x\n", signature);
1073 #endif
1074 switch (signature) {
1075 case IMAGE_NT_SIGNATURE:
1076 type = APPL_WIN32;
1077 break;
1078 case IMAGE_OS2_SIGNATURE:
1079 type = APPL_WIN3X;
1080 break;
1081 case IMAGE_VXD_SIGNATURE:
1082 type = APPL_WIN32;
1083 break;
1084 default:
1085 type = APPL_DOS;
1086 break;
1087 }
1088 done:
1089 CloseHandle(hFile);
1090 return type;
1091 }
1092
1093 /*
1094 *----------------------------------------------------------------------
1095 *
1096 * GetFullPath --
1097 *
1098 * Look for the program as an external program. First try the
1099 * name as it is, then try adding .com, .exe, and .bat, in that
1100 * order, to the name, looking for an executable.
1101 *
1102 * Using the raw SearchPath() procedure doesn't do quite what is
1103 * necessary. If the name of the executable already contains a
1104 * '.' character, it will not try appending the specified
1105 * extension when searching (in other words, SearchPath will
1106 * not find the program "a.b.exe" if the arguments specified
1107 * "a.b" and ".exe"). So, first look for the file as it is
1108 * named. Then manually append extensions, looking for a
1109 * match.
1110 *
1111 * Results:
1112 * Always returns TCL_OK.
1113 *
1114 * Side Effects:
1115 *
1116 *----------------------------------------------------------------------
1117 */
1118 static int
1119 GetFullPath(
1120 Tcl_Interp *interp, /* Interpreter to report errors to */
1121 const char *program, /* Name of program. */
1122 char *fullPath, /* (out) Returned full path. */
1123 char *cmdPrefix, /* (out) If program is a script, this contains
1124 * the name of the interpreter. */
1125 ApplicationType * typePtr)
1126 { /* (out) Type of program */
1127 TCHAR *rest;
1128 DWORD attr;
1129 int length;
1130 char cmd[MAX_PATH + 5];
1131 register char **p;
1132
1133 static char *dosExts[] =
1134 {
1135 "", ".com", ".exe", ".bat", NULL
1136 };
1137
1138 *typePtr = APPL_NONE;
1139
1140 length = strlen(program);
1141 strcpy(cmd, program);
1142 cmdPrefix[0] = '\0';
1143 for (p = dosExts; *p != NULL; p++) {
1144 cmd[length] = '\0'; /* Reset to original program name. */
1145 strcat(cmd, *p); /* Append the DOS extension to the
1146 * program name. */
1147
1148 if (!SearchPath(
1149 NULL, /* Use standard Windows search paths */
1150 cmd, /* Program name */
1151 NULL, /* Extension provided by program name. */
1152 MAX_PATH, /* Buffer size */
1153 fullPath, /* Buffer for absolute path of program */
1154 &rest)) {
1155 continue; /* Can't find program with that extension */
1156 }
1157 /*
1158 * Ignore matches on directories or data files.
1159 * Return when we identify a known program type.
1160 */
1161 attr = GetFileAttributesA(fullPath);
1162 if ((attr == (DWORD)-1) || (attr & FILE_ATTRIBUTE_DIRECTORY)) {
1163 continue;
1164 }
1165 *typePtr = GetApplicationType(fullPath, cmdPrefix);
1166 if (*typePtr != APPL_NONE) {
1167 break;
1168 }
1169 }
1170 if (*typePtr == APPL_NONE) {
1171 /*
1172 * Can't find the program. Check if it's an internal shell command
1173 * like "copy" or "dir" and let cmd.exe deal with it.
1174 */
1175 static char *shellCmds[] =
1176 {
1177 "copy", "del", "dir", "echo", "edit", "erase", "label",
1178 "md", "rd", "ren", "start", "time", "type", "ver", "vol", NULL
1179 };
1180
1181 for (p = shellCmds; *p != NULL; p++) {
1182 if (((*p)[0] == program[0]) && (strcmp(*p, program) == 0)) {
1183 break;
1184 }
1185 }
1186 if (*p == NULL) {
1187 Tcl_AppendResult(interp, "can't execute \"", program,
1188 "\": no such file or directory", (char *)NULL);
1189 return TCL_ERROR;
1190 }
1191 *typePtr = APPL_DOS;
1192 strcpy(fullPath, program);
1193 }
1194 if ((*typePtr == APPL_DOS) || (*typePtr == APPL_WIN3X)) {
1195
1196 /* For 16-bit applications, convert the long executable path
1197 * name to a short one. Otherwise the application may not be
1198 * able to correctly parse its own command line. */
1199
1200 GetShortPathName(fullPath, fullPath, MAX_PATH);
1201 }
1202 return TCL_OK;
1203 }
1204
1205 /*
1206 *----------------------------------------------------------------------
1207 *
1208 * ConcatCmdArgs --
1209 *
1210 * Concatonates command line arguments parsed from Tcl into a
1211 * single string. If an argument contain spaces, it is grouped
1212 * with surrounding double quotes. Must also escape any quotes we
1213 * find.
1214 *
1215 * Results:
1216 * Returns a malloc-ed string containing the concatonated command
1217 * line.
1218 *
1219 *----------------------------------------------------------------------
1220 */
1221 static char *
1222 ConcatCmdArgs(
1223 int argc,
1224 char **argv,
1225 Tcl_DString *resultPtr)
1226 {
1227 BOOL needQuote;
1228 register const char *s;
1229 register char *cp;
1230 char *string; /* Will contain the new command line */
1231 register int count;
1232 register int i;
1233
1234 /*
1235 * Pass 1. Compute how much space we need for an array to hold the entire
1236 * command line. Then allocate the string.
1237 */
1238 count = 0;
1239 for (i = 0; i < argc; i++) {
1240 needQuote = FALSE;
1241 if (*argv[i] == '\0') {
1242 needQuote = TRUE; /* Zero length args also need quotes. */
1243 }
1244 for (s = argv[i]; *s != '\0'; s++) {
1245 if (*s == '"') {
1246 register const char *bp;
1247
1248 count++; /* +1 Backslash needed to escape quote */
1249 for (bp = s - 1; (*bp == '\\') && (bp >= argv[i]); bp--) {
1250 count++; /* +? one for each preceding backslash */
1251 }
1252 } else if (isspace(*s)) {
1253 needQuote = TRUE;
1254 }
1255 count++; /* +1 Normal character */
1256 }
1257 if (needQuote) {
1258 count += 2; /* +2 Pair of quotes */
1259 }
1260 count++; /* +1 Space separating arguments */
1261 }
1262
1263 string = Blt_Malloc(count + 1);
1264 assert(string);
1265
1266 /*
1267 * Pass 2. Copy the arguments, quoting arguments with embedded spaces and
1268 * escaping all other quotes in the string.
1269 */
1270 cp = string;
1271 for (i = 0; i < argc; i++) {
1272 needQuote = FALSE;
1273
1274 if (*argv[i] == '\0') {
1275 needQuote = TRUE;
1276 }
1277 for (s = argv[i]; *s != '\0'; s++) {
1278 if (isspace(*s)) {
1279 needQuote = TRUE;
1280 }
1281 }
1282 if (needQuote) {
1283 *cp++ = '"';
1284 }
1285 for (s = argv[i]; *s; s++) {
1286 if (*s == '"') {
1287 register const char *bp;
1288
1289 for (bp = s - 1; (*bp == '\\') && (bp >= argv[i]); bp--) {
1290 *cp++ = '\\';
1291 }
1292 *cp++ = '\\';
1293 }
1294 *cp++ = *s;
1295 }
1296 if (needQuote) {
1297 *cp++ = '"';
1298 }
1299 *cp++ = ' ';
1300 }
1301 *cp = '\0';
1302 assert((cp - string) == count);
1303 Tcl_DStringAppend(resultPtr, string, count);
1304 Blt_Free(string);
1305 return Tcl_DStringValue(resultPtr);
1306 }
1307
1308 /*
1309 *----------------------------------------------------------------------
1310 *
1311 * StartProcess --
1312 *
1313 * Create a child process that has the specified files as its
1314 * standard input, output, and error.
1315 *
1316 * The complete Windows search path is searched to find the specified
1317 * executable. If an executable by the given name is not found,
1318 * automatically tries appending ".com", ".exe", and ".bat" to the
1319 * executable name.
1320 *
1321 * Results:
1322 * The return value is TCL_ERROR and an error message is left in
1323 * the interp's result if there was a problem creating the child
1324 * process. Otherwise, the return value is TCL_OK and *pidPtr is
1325 * filled with the process id of the child process.
1326 *
1327 * Side effects:
1328 * A process is created.
1329 *
1330 *----------------------------------------------------------------------
1331 */
1332 static int
1333 StartProcess(
1334 Tcl_Interp *interp, /* Interpreter to report errors that
1335 * occurred when creating the child process.
1336 * Error messages from the child process
1337 * itself are sent to errorFile. */
1338 int argc, /* Number of arguments. */
1339 char **argv, /* Command line arguments. */
1340 HANDLE hStdin, /* File handle to use as input (stdin) for the
1341 * child process. If handle is -1, no
1342 * standard input. */
1343 HANDLE hStdout, /* File handle to receive output (stdout)
1344 * from the child process. If -1, output
1345 * is discarded. */
1346 HANDLE hStderr, /* File handle to receive errors (stderr)
1347 * from the child process. If -1, stderr
1348 * will be discarded. Can be the same handle
1349 * as hStdOut */
1350 HANDLE *hProcessPtr, /* (out) Handle of child process. */
1351 DWORD *pidPtr) /* (out) Id of child process. */
1352 {
1353 int result, createFlags;
1354 ApplicationType applType;
1355 Tcl_DString dString; /* Complete command line */
1356 char *command;
1357 BOOL hasConsole;
1358 #ifdef notdef
1359 DWORD idleResult;
1360 #endif
1361 STARTUPINFOA si;
1362 PROCESS_INFORMATION pi;
1363 SECURITY_ATTRIBUTES securityAttrs;
1364 HANDLE hProcess, hPipe;
1365 char progPath[MAX_PATH];
1366 char cmdPrefix[MAX_PATH];
1367
1368 *hProcessPtr = INVALID_HANDLE_VALUE;
1369 GetFullPath(interp, argv[0], progPath, cmdPrefix, &applType);
1370 #if KILL_DEBUG
1371 PurifyPrintf("Application type is %d\n", (int)applType);
1372 #endif
1373 if (applType == APPL_NONE) {
1374 return TCL_ERROR;
1375 }
1376 result = TCL_ERROR;
1377
1378 hProcess = GetCurrentProcess();
1379
1380 ZeroMemory(&si, sizeof(STARTUPINFOA));
1381 si.cb = sizeof(STARTUPINFOA);
1382
1383 /*
1384 * The flag STARTF_USESTDHANDLES must be set to pass handles to
1385 * the child process. Using SetStdHandle and/or dup2 works only
1386 * when a console mode parent process is spawning an attached
1387 * console mode child process.
1388 */
1389
1390 si.dwFlags = STARTF_USESTDHANDLES;
1391 si.hStdInput = si.hStdOutput = si.hStdError = INVALID_HANDLE_VALUE;
1392
1393 securityAttrs.nLength = sizeof(SECURITY_ATTRIBUTES);
1394 securityAttrs.lpSecurityDescriptor = NULL;
1395 securityAttrs.bInheritHandle = TRUE;
1396
1397 /*
1398 * Duplicate all the handles to be passed off as stdin, stdout and
1399 * stderr of the child process. The duplicate handles are set to
1400 * be inheritable, so the child process can use them.
1401 */
1402 if (hStdin == INVALID_HANDLE_VALUE) {
1403 /*
1404 * If handle was not set, stdin should return immediate EOF.
1405 * Under Windows95, some applications (both 16 and 32 bit!)
1406 * can't read from the NUL device; they read from console
1407 * instead. When running tk, this is fatal because the child
1408 * process would hang forever waiting for EOF from the unmapped
1409 * console window used by the helper application.
1410 *
1411 * Fortunately, the helper application detects a closed pipe
1412 * as an immediate EOF and can pass that information to the
1413 * child process.
1414 */
1415 if (CreatePipe(&si.hStdInput, &hPipe, &securityAttrs, 0)) {
1416 CloseHandle(hPipe);
1417 }
1418 } else {
1419 DuplicateHandle(hProcess, hStdin, hProcess, &si.hStdInput, 0, TRUE,
1420 DUPLICATE_SAME_ACCESS);
1421 }
1422
1423 if (si.hStdInput == INVALID_HANDLE_VALUE) {
1424 Tcl_AppendResult(interp, "can't duplicate input handle: ",
1425 Blt_LastError(), (char *)NULL);
1426 goto closeHandles;
1427 }
1428 if (hStdout == INVALID_HANDLE_VALUE) {
1429 /*
1430 * If handle was not set, output should be sent to an infinitely
1431 * deep sink. Under Windows 95, some 16 bit applications cannot
1432 * have stdout redirected to NUL; they send their output to
1433 * the console instead. Some applications, like "more" or "dir /p",
1434 * when outputting multiple pages to the console, also then try and
1435 * read from the console to go the next page. When running tk, this
1436 * is fatal because the child process would hang forever waiting
1437 * for input from the unmapped console window used by the helper
1438 * application.
1439 *
1440 * Fortunately, the helper application will detect a closed pipe
1441 * as a sink.
1442 */
1443 if ((Blt_GetPlatformId() == VER_PLATFORM_WIN32_WINDOWS)
1444 && (applType == APPL_DOS)) {
1445 if (CreatePipe(&hPipe, &si.hStdOutput, &securityAttrs, 0)) {
1446 CloseHandle(hPipe);
1447 }
1448 } else {
1449 si.hStdOutput = CreateFileA("NUL:", GENERIC_WRITE, 0,
1450 &securityAttrs, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1451 }
1452 } else {
1453 DuplicateHandle(hProcess, hStdout, hProcess, &si.hStdOutput, 0, TRUE,
1454 DUPLICATE_SAME_ACCESS);
1455 }
1456 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
1457 Tcl_AppendResult(interp, "can't duplicate output handle: ",
1458 Blt_LastError(), (char *)NULL);
1459 goto closeHandles;
1460 }
1461 if (hStderr == INVALID_HANDLE_VALUE) {
1462 /*
1463 * If handle was not set, errors should be sent to an infinitely
1464 * deep sink.
1465 */
1466 si.hStdError = CreateFileA("NUL:", GENERIC_WRITE, 0,
1467 &securityAttrs, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1468 } else {
1469 DuplicateHandle(hProcess, hStderr, hProcess, &si.hStdError, 0, TRUE,
1470 DUPLICATE_SAME_ACCESS);
1471 }
1472 if (si.hStdError == INVALID_HANDLE_VALUE) {
1473 Tcl_AppendResult(interp, "can't duplicate error handle: ",
1474 Blt_LastError(), (char *)NULL);
1475 goto closeHandles;
1476 }
1477 Tcl_DStringInit(&dString);
1478 createFlags = 0;
1479 hasConsole = HasConsole();
1480 if (!hasConsole) {
1481 createFlags |= DETACHED_PROCESS;
1482 }
1483 /*
1484 * If we do not have a console window, then we must run DOS and
1485 * WIN32 console mode applications as detached processes. This tells
1486 * the loader that the child application should not inherit the
1487 * console, and that it should not create a new console window for
1488 * the child application. The child application should get its stdio
1489 * from the redirection handles provided by this application, and run
1490 * in the background.
1491 *
1492 * If we are starting a GUI process, they don't automatically get a
1493 * console, so it doesn't matter if they are started as foreground or
1494 * detached processes. The GUI window will still pop up to the
1495 * foreground.
1496 */
1497 if (applType == APPL_DOS) {
1498 if (Blt_GetPlatformId() == VER_PLATFORM_WIN32_NT) {
1499 /*
1500 * Under NT, 16-bit DOS applications will not run unless they
1501 * can be attached to a console. If we are running without a
1502 * console, run the 16-bit program as an normal process inside
1503 * of a hidden console application, and then run that hidden
1504 * console as a detached process.
1505 */
1506 si.wShowWindow = SW_HIDE;
1507 si.dwFlags |= STARTF_USESHOWWINDOW;
1508 createFlags = CREATE_NEW_CONSOLE;
1509 Tcl_DStringAppend(&dString, "cmd.exe /c ", -1);
1510 } else {
1511 /*
1512 * Under Windows 95, 16-bit DOS applications do not work well
1513 * with pipes:
1514 *
1515 * 1. EOF on a pipe between a detached 16-bit DOS application
1516 * and another application is not seen at the other
1517 * end of the pipe, so the listening process blocks forever on
1518 * reads. This inablity to detect EOF happens when either a
1519 * 16-bit app or the 32-bit app is the listener.
1520 *
1521 * 2. If a 16-bit DOS application (detached or not) blocks when
1522 * writing to a pipe, it will never wake up again, and it
1523 * eventually brings the whole system down around it.
1524 *
1525 * The 16-bit application is run as a normal process
1526 * inside of a hidden helper console app, and this helper
1527 * may be run as a detached process. If a stdio handle is
1528 * a pipe, the helper application accumulates information
1529 * into temp files and forwards it to or from the DOS
1530 * application as appropriate. This means that DOS apps
1531 * must receive EOF from a stdin pipe before they will
1532 * actually begin, and must finish generating stdout or
1533 * stderr before the data will be sent to the next stage
1534 * of the pipe.
1535 *
1536 * The helper app should be located in the same directory
1537 * as the tcl dll.
1538 */
1539 if (!hasConsole) {
1540 si.wShowWindow = SW_HIDE;
1541 si.dwFlags |= STARTF_USESHOWWINDOW;
1542 createFlags = CREATE_NEW_CONSOLE;
1543 }
1544 Tcl_DStringAppend(&dString, "tclpip" STRINGIFY(TCL_MAJOR_VERSION)
1545 STRINGIFY(TCL_MINOR_VERSION) ".dll ", -1);
1546 }
1547 } else if (applType == APPL_INTERP) {
1548 Tcl_DStringAppend(&dString, cmdPrefix, -1);
1549 Tcl_DStringAppend(&dString, " ", -1);
1550 }
1551 argv[0] = progPath;
1552
1553 command = ConcatCmdArgs(argc, argv, &dString);
1554 #if KILL_DEBUG
1555 PurifyPrintf("command is %s\n", command);
1556 #endif
1557 result = CreateProcess(
1558 NULL, /* Module name. */
1559 (TCHAR *)command, /* Command line */
1560 NULL, /* Process security */
1561 NULL, /* Thread security */
1562 TRUE, /* Inherit handles */
1563 createFlags, /* Creation flags */
1564 NULL, /* Environment */
1565 NULL, /* Current working directory */
1566 &si, /* Initialization for process: includes
1567 * standard handles, appearance and location
1568 * of window */
1569 &pi); /* (out) Information about newly
1570 created process */
1571 Tcl_DStringFree(&dString);
1572
1573 if (!result) {
1574 Tcl_AppendResult(interp, "can't execute \"", argv[0], "\": ",
1575 Blt_LastError(), (char *)NULL);
1576 goto closeHandles;
1577 }
1578 #if KILL_DEBUG
1579 PurifyPrintf("Starting process with handle of %d\n", pi.hProcess);
1580 PurifyPrintf("Starting process with id of %d\n", pi.dwProcessId);
1581 #endif
1582 if (applType == APPL_DOS) {
1583 /* Force the OS to give some time to the DOS process. */
1584 WaitForSingleObject(hProcess, 50);
1585 }
1586 #ifdef notdef /* FIXME: I don't think this actually
1587 * ever worked. WaitForInputIdle
1588 * usually fails with "Access is
1589 * denied" (maybe the process handle
1590 * isn't valid yet?). When you add a
1591 * delay, WaitForInputIdle will time
1592 * out instead. */
1593 /*
1594 * PSS ID Number: Q124121
1595 *
1596 * "When an application spawns a process repeatedly, a new
1597 * thread instance will be created for each process but the
1598 * previous instances may not be cleaned up. This results in
1599 * a significant virtual memory loss each time the process is
1600 * spawned. If there is a WaitForInputIdle() call between
1601 * CreateProcess() and CloseHandle(), the problem does not
1602 * occur." */
1603 idleResult = WaitForInputIdle(pi.hProcess, 1000);
1604 if (idleResult == (DWORD) - 1) {
1605 #if KILL_DEBUG
1606 PurifyPrintf("wait failed on %d: %s\n", pi.hProcess, Blt_LastError());
1607 #endif
1608 }
1609 #endif
1610 CloseHandle(pi.hThread);
1611
1612 *hProcessPtr = pi.hProcess;
1613
1614 /*
1615 * Add the entry to mapping table. Its purpose is to translate
1616 * process handles to process ids. Most things we do with the
1617 * Win32 API take handles, but we still want to present process
1618 * ids to the user. */
1619 *pidPtr = pi.dwProcessId;
1620 result = TCL_OK;
1621
1622 closeHandles:
1623 if (si.hStdInput != INVALID_HANDLE_VALUE) {
1624 CloseHandle(si.hStdInput);
1625 }
1626 if (si.hStdOutput != INVALID_HANDLE_VALUE) {
1627 CloseHandle(si.hStdOutput);
1628 }
1629 if (si.hStdError != INVALID_HANDLE_VALUE) {
1630 CloseHandle(si.hStdError);
1631 }
1632 return result;
1633 }
1634
1635 /*
1636 *----------------------------------------------------------------------
1637 *
1638 * FileForRedirect --
1639 *
1640 * This procedure does much of the work of parsing redirection
1641 * operators. It handles "@" if specified and allowed, and a file
1642 * name, and opens the file if necessary.
1643 *
1644 * Results:
1645 * The return value is the descriptor number for the file. If an
1646 * error occurs then NULL is returned and an error message is left
1647 * in interp->result. Several arguments are side-effected; see
1648 * the argument list below for details.
1649 *
1650 * Side effects:
1651 * None.
1652 *
1653 *----------------------------------------------------------------------
1654 */
1655 static HANDLE
1656 FileForRedirect(
1657 Tcl_Interp *interp, /* Intepreter to use for error reporting. */
1658 char *spec, /* Points to character just after
1659 * redirection character. */
1660 BOOL atOK, /* Non-zero means that '@' notation can be
1661 * used to specify a channel, zero means that
1662 * it isn't. */
1663 char *arg, /* Pointer to entire argument containing
1664 * spec: used for error reporting. */
1665 char *nextArg, /* Next argument in argc/argv array, if needed
1666 * for file name or channel name. May be
1667 * NULL. */
1668 DWORD accessFlags, /* Flags to use for opening file or to
1669 * specify mode for channel. */
1670 DWORD createFlags, /* Flags to use for opening file or to
1671 * specify mode for channel. */
1672 int *skipPtr, /* Filled with 1 if redirection target was
1673 * in spec, 2 if it was in nextArg. */
1674 int *closePtr) /* Filled with one if the caller should
1675 * close the file when done with it, zero
1676 * otherwise. */
1677 {
1678 int writing = (accessFlags & GENERIC_WRITE);
1679 Tcl_Channel chan;
1680 HANDLE hFile;
1681
1682 *skipPtr = 1;
1683 *closePtr = FALSE;
1684 if ((atOK) && (*spec == '@')) {
1685 spec++;
1686 if (*spec == '\0') {
1687 spec = nextArg;
1688 if (spec == NULL) {
1689 goto badLastArg;
1690 }
1691 *skipPtr = 2;
1692 }
1693 if (*spec == '1' && spec[1] == 0) {
1694 spec = "stdout";
1695 }
1696 chan = Tcl_GetChannel(interp, spec, NULL);
1697 if (chan == NULL) {
1698 return INVALID_HANDLE_VALUE;
1699 }
1700 if (Tcl_GetChannelHandle(chan, (writing) ? TCL_WRITABLE : TCL_READABLE,
1701 (ClientData *)&hFile) != TCL_OK) {
1702 hFile = INVALID_HANDLE_VALUE;
1703 }
1704 if (hFile == INVALID_HANDLE_VALUE) {
1705 Tcl_AppendResult(interp, "channel \"", Tcl_GetChannelName(chan),
1706 "\" wasn't opened for ",
1707 ((writing) ? "writing" : "reading"), (char *)NULL);
1708 return INVALID_HANDLE_VALUE;
1709 }
1710 if (writing) {
1711 /*
1712 * Be sure to flush output to the file, so that anything
1713 * written by the child appears after stuff we've already
1714 * written.
1715 */
1716 Tcl_Flush(chan);
1717 }
1718 } else {
1719 char *name;
1720 Tcl_DString dString;
1721
1722 if (*spec == '\0') {
1723 spec = nextArg;
1724 if (spec == NULL) {
1725 goto badLastArg;
1726 }
1727 *skipPtr = 2;
1728 }
1729 name = Tcl_TranslateFileName(interp, spec, &dString);
1730 if (name != NULL) {
1731 hFile = OpenRedirectFile(name, accessFlags, createFlags);
1732 } else {
1733 hFile = INVALID_HANDLE_VALUE;
1734 }
1735 Tcl_DStringFree(&dString);
1736
1737 if (hFile == INVALID_HANDLE_VALUE) {
1738 Tcl_AppendResult(interp, "can't ", (writing) ? "write" : "read",
1739 " file \"", spec, "\": ", Tcl_PosixError(interp),
1740 (char *)NULL);
1741 return INVALID_HANDLE_VALUE;
1742 }
1743 *closePtr = TRUE;
1744 }
1745 return hFile;
1746
1747 badLastArg:
1748 Tcl_AppendResult(interp, "can't specify \"", arg,
1749 "\" as last word in command", (char *)NULL);
1750 return INVALID_HANDLE_VALUE;
1751 }
1752
1753 /*
1754 *----------------------------------------------------------------------
1755 *
1756 * Blt_CreatePipeline --
1757 *
1758 * Given an argc/argv array, instantiate a pipeline of processes
1759 * as described by the argv.
1760 *
1761 * Results:
1762 * The return value is a count of the number of new processes
1763 * created, or -1 if an error occurred while creating the pipeline.
1764 * *pidArrayPtr is filled in with the address of a dynamically
1765 * allocated array giving the ids of all of the processes. It
1766 * is up to the caller to free this array when it isn't needed
1767 * anymore. If inPipePtr is non-NULL, *inPipePtr is filled in
1768 * with the file id for the input pipe for the pipeline (if any):
1769 * the caller must eventually close this file. If outPipePtr
1770 * isn't NULL, then *outPipePtr is filled in with the file id
1771 * for the output pipe from the pipeline: the caller must close
1772 * this file. If errPipePtr isn't NULL, then *errPipePtr is filled
1773 * with a file id that may be used to read error output after the
1774 * pipeline completes.
1775 *
1776 * Side effects:
1777 * Processes and pipes are created.
1778 *
1779 *----------------------------------------------------------------------
1780 */
1781 int
1782 Blt_CreatePipeline(
1783 Tcl_Interp *interp, /* Interpreter to use for error reporting. */
1784 int argc, /* Number of entries in argv. */
1785 char **argv, /* Array of strings describing commands in
1786 * pipeline plus I/O redirection with <,
1787 * <<, >, etc. Argv[argc] must be NULL. */
1788 Process **procArrPtr, /* *procArrPtr gets filled in with
1789 * address of array of pids for processes
1790 * in pipeline (first pid is first process
1791 * in pipeline). */
1792 int *inPipePtr, /* If non-NULL, input to the pipeline comes
1793 * from a pipe (unless overridden by
1794 * redirection in the command). The file
1795 * id with which to write to this pipe is
1796 * stored at *inPipePtr. NULL means command
1797 * specified its own input source. */
1798 int *outPipePtr, /* If non-NULL, output to the pipeline goes
1799 * to a pipe, unless overriden by redirection
1800 * in the command. The file id with which to
1801 * read frome this pipe is stored at
1802 * *outPipePtr. NULL means command specified
1803 * its own output sink. */
1804 int *errPipePtr) /* If non-NULL, all stderr output from the
1805 * pipeline will go to a temporary file
1806 * created here, and a descriptor to read
1807 * the file will be left at *errPipePtr.
1808 * The file will be removed already, so
1809 * closing this descriptor will be the end
1810 * of the file. If this is NULL, then
1811 * all stderr output goes to our stderr.
1812 * If the pipeline specifies redirection
1813 * then the file will still be created
1814 * but it will never get any data. */
1815 {
1816 Process *procArr = NULL; /* Points to malloc-ed array holding all
1817 * the handles of child processes. */
1818 int nPids; /* Actual number of processes that exist
1819 * at *procArr right now. */
1820 int cmdCount; /* Count of number of distinct commands
1821 * found in argc/argv. */
1822 char *inputLiteral = NULL; /* If non-null, then this points to a
1823 * string containing input data (specified
1824 * via <<) to be piped to the first process
1825 * in the pipeline. */
1826 HANDLE hStdin; /* If != -1, gives file to use as input for
1827 * first process in pipeline (specified via <
1828 * or <@). */
1829 BOOL closeStdin; /* If non-zero, then hStdin should be
1830 * closed when cleaning up. */
1831 HANDLE hStdout; /* Writable file for output from last command
1832 * in pipeline (could be file or pipe). NULL
1833 * means use stdout. */
1834 BOOL closeStdout; /* If non-zero, then hStdout should be
1835 * closed when cleaning up. */
1836 HANDLE hStderr; /* Writable file for error output from all
1837 * commands in pipeline. NULL means use
1838 * stderr. */
1839 BOOL closeStderr; /* If non-zero, then hStderr should be
1840 * closed when cleaning up. */
1841
1842 HANDLE hInPipe, hOutPipe, hErrPipe;
1843 char *p;
1844 int skip, lastBar, lastArg, i, j, flags;
1845 int pid;
1846 BOOL atOK, errorToOutput;
1847 Tcl_DString dString;
1848 HANDLE hPipe;
1849 HANDLE thisInput, thisOutput, thisError;
1850
1851 if (inPipePtr != NULL) {
1852 *inPipePtr = -1;
1853 }
1854 if (outPipePtr != NULL) {
1855 *outPipePtr = -1;
1856 }
1857 if (errPipePtr != NULL) {
1858 *errPipePtr = -1;
1859 }
1860 Tcl_DStringInit(&dString);
1861
1862 hStdin = hStdout = hStderr = INVALID_HANDLE_VALUE;
1863 hPipe = thisInput = thisOutput = INVALID_HANDLE_VALUE;
1864 hInPipe = hOutPipe = hErrPipe = INVALID_HANDLE_VALUE;
1865 closeStdin = closeStdout = closeStderr = FALSE;
1866 nPids = 0;
1867
1868 /*
1869 * First, scan through all the arguments to figure out the structure
1870 * of the pipeline. Process all of the input and output redirection
1871 * arguments and remove them from the argument list in the pipeline.
1872 * Count the number of distinct processes (it's the number of "|"
1873 * arguments plus one) but don't remove the "|" arguments because
1874 * they'll be used in the second pass to seperate the individual
1875 * child processes. Cannot start the child processes in this pass
1876 * because the redirection symbols may appear anywhere in the
1877 * command line -- e.g., the '<' that specifies the input to the
1878 * entire pipe may appear at the very end of the argument list.
1879 */
1880
1881 lastBar = -1;
1882 cmdCount = 1;
1883 for (i = 0; i < argc; i++) {
1884 skip = 0;
1885 p = argv[i];
1886 switch (*p++) {
1887 case '|':
1888 if (*p == '&') {
1889 p++;
1890 }
1891 if (*p == '\0') {
1892 if ((i == (lastBar + 1)) || (i == (argc - 1))) {
1893 Tcl_AppendResult(interp,
1894 "illegal use of | or |& in command",
1895 (char *)NULL);
1896 goto error;
1897 }
1898 }
1899 lastBar = i;
1900 cmdCount++;
1901 break;
1902
1903 case '<':
1904 if (closeStdin) {
1905 closeStdin = FALSE;
1906 CloseHandle(hStdin);
1907 }
1908 if (*p == '<') {
1909 hStdin = INVALID_HANDLE_VALUE;
1910 inputLiteral = p + 1;
1911 skip = 1;
1912 if (*inputLiteral == '\0') {
1913 inputLiteral = argv[i + 1];
1914 if (inputLiteral == NULL) {
1915 Tcl_AppendResult(interp, "can't specify \"", argv[i],
1916 "\" as last word in command", (char *)NULL);
1917 goto error;
1918 }
1919 skip = 2;
1920 }
1921 } else {
1922 inputLiteral = NULL;
1923 hStdin = FileForRedirect(interp, p, TRUE, argv[i], argv[i + 1],
1924 GENERIC_READ, OPEN_EXISTING, &skip, &closeStdin);
1925 if (hStdin == INVALID_HANDLE_VALUE) {
1926 goto error;
1927 }
1928 }
1929 break;
1930
1931 case '>':
1932 atOK = 1;
1933 flags = CREATE_ALWAYS;
1934 errorToOutput = FALSE;
1935 if (*p == '>') {
1936 p++;
1937 atOK = 0;
1938 flags = OPEN_ALWAYS;
1939 }
1940 if (*p == '&') {
1941 if (closeStderr) {
1942 closeStderr = FALSE;
1943 CloseHandle(hStderr);
1944 }
1945 errorToOutput = TRUE;
1946 p++;
1947 }
1948 if (closeStdout) {
1949 closeStdout = FALSE;
1950 CloseHandle(hStdout);
1951 }
1952 hStdout = FileForRedirect(interp, p, atOK, argv[i], argv[i + 1],
1953 GENERIC_WRITE, flags, &skip, &closeStdout);
1954 if (hStdout == INVALID_HANDLE_VALUE) {
1955 goto error;
1956 }
1957 if (errorToOutput) {
1958 closeStderr = FALSE;
1959 hStderr = hStdout;
1960 }
1961 break;
1962
1963 case '2':
1964 if (*p != '>') {
1965 break;
1966 }
1967 p++;
1968 atOK = TRUE;
1969 flags = CREATE_ALWAYS;
1970 if (*p == '>') {
1971 p++;
1972 atOK = FALSE;
1973 flags = OPEN_ALWAYS;
1974 }
1975 if (closeStderr) {
1976 closeStderr = FALSE;
1977 CloseHandle(hStderr);
1978 }
1979 hStderr = FileForRedirect(interp, p, atOK, argv[i], argv[i + 1],
1980 GENERIC_WRITE, flags, &skip, &closeStderr);
1981 if (hStderr == INVALID_HANDLE_VALUE) {
1982 goto error;
1983 }
1984 break;
1985 }
1986
1987 if (skip != 0) {
1988 for (j = i + skip; j < argc; j++) {
1989 argv[j - skip] = argv[j];
1990 }
1991 argc -= skip;
1992 i -= 1;
1993 }
1994 }
1995
1996 if (hStdin == INVALID_HANDLE_VALUE) {
1997 if (inputLiteral != NULL) {
1998 /*
1999 * The input for the first process is immediate data coming from
2000 * Tcl. Create a temporary file for it and put the data into the
2001 * file.
2002 */
2003 hStdin = CreateTempFile(inputLiteral);
2004 if (hStdin == INVALID_HANDLE_VALUE) {
2005 Tcl_AppendResult(interp,
2006 "can't create input file for command: ",
2007 Tcl_PosixError(interp), (char *)NULL);
2008 goto error;
2009 }
2010 closeStdin = TRUE;
2011 } else if (inPipePtr != NULL) {
2012 /*
2013 * The input for the first process in the pipeline is to
2014 * come from a pipe that can be written from by the caller.
2015 */
2016
2017 if (!CreatePipe(&hStdin, &hInPipe, NULL, 0)) {
2018 Tcl_AppendResult(interp,
2019 "can't create input pipe for command: ",
2020 Tcl_PosixError(interp), (char *)NULL);
2021 goto error;
2022 }
2023 closeStdin = TRUE;
2024 } else {
2025 /*
2026 * The input for the first process comes from stdin.
2027 */
2028 }
2029 }
2030 if (hStdout == INVALID_HANDLE_VALUE) {
2031 if (outPipePtr != NULL) {
2032 /*
2033 * Output from the last process in the pipeline is to go to a
2034 * pipe that can be read by the caller.
2035 */
2036
2037 if (!CreatePipe(&hOutPipe, &hStdout, NULL, 0)) {
2038 Tcl_AppendResult(interp,
2039 "can't create output pipe for command: ",
2040 Tcl_PosixError(interp), (char *)NULL);
2041 goto error;
2042 }
2043 closeStdout = TRUE;
2044 } else {
2045 /*
2046 * The output for the last process goes to stdout.
2047 */
2048 }
2049 }
2050 if (hStderr == INVALID_HANDLE_VALUE) {
2051 if (errPipePtr != NULL) {
2052 /*
2053 * Stderr from the last process in the pipeline is to go to a
2054 * pipe that can be read by the caller.
2055 */
2056 if (CreatePipe(&hErrPipe, &hStderr, NULL, 0) == 0) {
2057 Tcl_AppendResult(interp,
2058 "can't create error pipe for command: ",
2059 Tcl_PosixError(interp), (char *)NULL);
2060 goto error;
2061 }
2062 closeStderr = TRUE;
2063 } else {
2064 /*
2065 * Errors from the pipeline go to stderr.
2066 */
2067 }
2068 }
2069
2070 /*
2071 * Scan through the argc array, creating a process for each
2072 * group of arguments between the "|" characters.
2073 */
2074
2075 Tcl_ReapDetachedProcs();
2076 procArr = Blt_Malloc((unsigned)((cmdCount + 1) * sizeof(Process)));
2077 assert(procArr);
2078 thisInput = hStdin;
2079 if (argc == 0) {
2080 Tcl_AppendResult(interp, "invalid null command", (char *)NULL);
2081 goto error;
2082 }
2083 #ifdef notdef
2084 lastArg = 0; /* Suppress compiler warning */
2085 #endif
2086 for (i = 0; i < argc; i = lastArg + 1) {
2087 BOOL joinThisError;
2088 HANDLE hProcess;
2089
2090 /* Convert the program name into native form. */
2091 argv[i] = Tcl_TranslateFileName(interp, argv[i], &dString);
2092 if (argv[i] == NULL) {
2093 goto error;
2094 }
2095 /* Find the end of the current segment of the pipeline. */
2096 joinThisError = FALSE;
2097 for (lastArg = i; lastArg < argc; lastArg++) {
2098 if (argv[lastArg][0] == '|') {
2099 if (argv[lastArg][1] == '\0') {
2100 break;
2101 }
2102 if ((argv[lastArg][1] == '&') && (argv[lastArg][2] == '\0')) {
2103 joinThisError = TRUE;
2104 break;
2105 }
2106 }
2107 }
2108 argv[lastArg] = NULL;
2109 if ((lastArg - i) == 0) {
2110 Tcl_AppendResult(interp, "invalid null command", (char *)NULL);
2111 goto error;
2112 }
2113
2114 /*
2115 * If this is the last segment, use the specified output handle.
2116 * Otherwise create an intermediate pipe. hPipe will become the
2117 * input for the next segment of the pipe.
2118 */
2119 if (lastArg == argc) {
2120 thisOutput = hStdout;
2121 } else {
2122 if (CreatePipe(&hPipe, &thisOutput, NULL, 0) == 0) {
2123 Tcl_AppendResult(interp, "can't create pipe: ",
2124 Tcl_PosixError(interp), (char *)NULL);
2125 goto error;
2126 }
2127 }
2128
2129 if (joinThisError) {
2130 thisError = thisOutput;
2131 } else {
2132 thisError = hStderr;
2133 }
2134
2135 if (StartProcess(interp, lastArg - i, argv + i, thisInput, thisOutput,
2136 thisError, &hProcess, (DWORD *)&pid) != TCL_OK) {
2137 goto error;
2138 }
2139 Tcl_DStringFree(&dString);
2140
2141 procArr[nPids].hProcess = hProcess;
2142 procArr[nPids].pid = pid;
2143 nPids++;
2144
2145 /*
2146 * Close off our copies of file descriptors that were set up for
2147 * this child, then set up the input for the next child.
2148 */
2149
2150 if ((thisInput != INVALID_HANDLE_VALUE) && (thisInput != hStdin)) {
2151 CloseHandle(thisInput);
2152 }
2153 thisInput = hPipe;
2154 hPipe = INVALID_HANDLE_VALUE;
2155
2156 if ((thisOutput != INVALID_HANDLE_VALUE) && (thisOutput != hStdout)) {
2157 CloseHandle(thisOutput);
2158 }
2159 thisOutput = INVALID_HANDLE_VALUE;
2160 }
2161
2162 *procArrPtr = (Process *)procArr;
2163
2164 if (inPipePtr != NULL) {
2165 *inPipePtr = (int)hInPipe;
2166 }
2167 if (outPipePtr != NULL) {
2168 *outPipePtr = (int)hOutPipe;
2169 }
2170 if (errPipePtr != NULL) {
2171 *errPipePtr = (int)hErrPipe;
2172 }
2173 /*
2174 * All done. Cleanup open files lying around and then return.
2175 */
2176 cleanup:
2177 Tcl_DStringFree(&dString);
2178
2179 if (closeStdin) {
2180 CloseHandle(hStdin);
2181 }
2182 if (closeStdout) {
2183 CloseHandle(hStdout);
2184 }
2185 if (closeStderr) {
2186 CloseHandle(hStderr);
2187 }
2188 return nPids;
2189
2190 /*
2191 * An error occurred. There could have been extra files open, such
2192 * as pipes between children. Clean them all up. Detach any child
2193 * processes that have been created.
2194 */
2195 error:
2196 if (hPipe != INVALID_HANDLE_VALUE) {
2197 CloseHandle(hPipe);
2198 }
2199 if ((thisOutput != INVALID_HANDLE_VALUE) && (thisOutput != hStdout)) {
2200 CloseHandle(thisOutput);
2201 }
2202 if ((thisInput != INVALID_HANDLE_VALUE) && (thisInput != hStdin)) {
2203 CloseHandle(thisInput);
2204 }
2205 if (hInPipe != INVALID_HANDLE_VALUE) {
2206 CloseHandle(hInPipe);
2207 }
2208 if (hOutPipe != INVALID_HANDLE_VALUE) {
2209 CloseHandle(hOutPipe);
2210 }
2211 if (hErrPipe != INVALID_HANDLE_VALUE) {
2212 CloseHandle(hErrPipe);
2213 }
2214 if (procArr != NULL) {
2215 for (i = 0; i < nPids; i++) {
2216 if (procArr[i].hProcess != INVALID_HANDLE_VALUE) {
2217 /* It's Ok to use Tcl_DetachPids, since for WIN32 it's really
2218 * using process handles, not process ids. */
2219 Tcl_DetachPids(1, (Tcl_Pid *)&(procArr[i].pid));
2220 }
2221 }
2222 Blt_Free(procArr);
2223 }
2224 nPids = -1;
2225 goto cleanup;
2226 }
2227
2228 /*
2229 *----------------------------------------------------------------------
2230 *
2231 * Blt_CreateFileHandler --
2232 *
2233 * Limited emulation Tcl_CreateFileHandler for Win32. Works
2234 * with pipes. Don't know if anything else will (such as sockets).
2235 *
2236 * Results:
2237 * None.
2238 *
2239 * Side Effects:
2240 * Registers procedure and data to call back when data
2241 * is available on the pipe.
2242 *
2243 *----------------------------------------------------------------------
2244 */
2245 void
2246 Blt_CreateFileHandler(
2247 int fd, /* Descriptor or handle of file */
2248 int flags, /* TCL_READABLE or TCL_WRITABLE */
2249 Tcl_FileProc *proc,
2250 ClientData clientData)
2251 {
2252 PipeHandler *pipePtr;
2253
2254 if (!initialized) {
2255 PipeInit();
2256 }
2257 if ((flags != TCL_READABLE) && (flags != TCL_WRITABLE)) {
2258 return; /* Only one of the flags can be set. */
2259 }
2260 pipePtr = CreatePipeHandler((HANDLE) fd, flags);
2261 pipePtr->proc = proc;
2262 pipePtr->clientData = clientData;
2263
2264 /* Add the handler to the list of managed pipes. */
2265 EnterCriticalSection(&pipeCriticalSection);
2266 Blt_ChainAppend(&pipeChain, pipePtr);
2267 LeaveCriticalSection(&pipeCriticalSection);
2268 }
2269
2270 /*
2271 *----------------------------------------------------------------------
2272 *
2273 * Blt_DeleteFileHandler --
2274 *
2275 * Win32 emulation Tcl_DeleteFileHandler. Cleans up resources
2276 * used.
2277 *
2278 * Results:
2279 * None.
2280 *
2281 *----------------------------------------------------------------------
2282 */
2283 void
2284 Blt_DeleteFileHandler(int fd) /* Descriptor or handle of file */
2285 {
2286 PipeHandler *pipePtr;
2287 Blt_ChainLink *linkPtr;
2288 HANDLE hPipe;
2289
2290 if (!initialized) {
2291 PipeInit();
2292 }
2293 #if KILL_DEBUG
2294 PurifyPrintf("Blt_DeleteFileHandler(%d)\n", fd);
2295 #endif
2296 hPipe = (HANDLE) fd;
2297 EnterCriticalSection(&pipeCriticalSection);
2298
2299 for (linkPtr = Blt_ChainFirstLink(&pipeChain); linkPtr != NULL;
2300 linkPtr = Blt_ChainNextLink(linkPtr)) {
2301 pipePtr = Blt_ChainGetValue(linkPtr);
2302 if ((pipePtr->hPipe == hPipe) && !(pipePtr->flags & PIPE_DELETED)) {
2303 Blt_ChainDeleteLink(&pipeChain, linkPtr);
2304 DeletePipeHandler(pipePtr);
2305 break;
2306 }
2307 }
2308 LeaveCriticalSection(&pipeCriticalSection);
2309 #if KILL_DEBUG
2310 PurifyPrintf("Blt_DeleteFileHandler: done\n");
2311 #endif
2312 }
2313
2314 /*
2315 *----------------------------------------------------------------------
2316 *
2317 * Blt_AsyncRead --
2318 *
2319 * Reads input from the pipe into the given buffer.
2320 *
2321 * Results:
2322 * Returns the number of bytes read.
2323 *
2324 *----------------------------------------------------------------------
2325 */
2326 int
2327 Blt_AsyncRead(
2328 int f,
2329 char *buffer,
2330 unsigned int size)
2331 {
2332 register PipeHandler *pipePtr;
2333 unsigned int count;
2334 int nBytes;
2335
2336 #if ASYNC_DEBUG
2337 PurifyPrintf("Blt_AsyncRead(f=%d)\n", f);
2338 #endif
2339 pipePtr = GetPipeHandler((HANDLE) f);
2340 if ((pipePtr == NULL) || (pipePtr->flags & PIPE_DELETED)) {
2341 errno = EBADF;
2342 #if ASYNC_DEBUG
2343 PurifyPrintf("Blt_AsyncRead: bad file\n");
2344 #endif
2345 return -1;
2346 }
2347 if (!PeekOnPipe(pipePtr, &nBytes)) {
2348 #if ASYNC_DEBUG
2349 PurifyPrintf("Blt_AsyncRead: pipe is drained (nBytes=%d).\n", nBytes);
2350 #endif
2351 return -1; /* No data available. */
2352 }
2353 /*
2354 * nBytes is 0 EOF found.
2355 * -1 Error occured.
2356 * 1+ Number of bytes available.
2357 */
2358 if (nBytes == -1) {
2359 #if ASYNC_DEBUG
2360 PurifyPrintf("Blt_AsyncRead: Error\n");
2361 #endif
2362 return -1;
2363 }
2364 if (nBytes == 0) {
2365 #if ASYNC_DEBUG
2366 PurifyPrintf("Blt_AsyncRead: EOF\n");
2367 #endif
2368 return 0;
2369 }
2370 count = pipePtr->end - pipePtr->start;
2371 #if ASYNC_DEBUG
2372 PurifyPrintf("Blt_AsyncRead: nBytes is %d, %d\n", nBytes, count);
2373 #endif
2374 assert(count == (unsigned int)nBytes);
2375 if (size > count) {
2376 size = count; /* Reset request to what's available. */
2377 }
2378 memcpy(buffer, pipePtr->buffer + pipePtr->start, size);
2379 pipePtr->start += size;
2380 if (pipePtr->start == pipePtr->end) {
2381 #if ASYNC_DEBUG
2382 PurifyPrintf("Blt_AsyncRead: signaling idle\n");
2383 #endif
2384 ResetEvent(pipePtr->readyEvent);
2385 SetEvent(pipePtr->idleEvent);
2386 }
2387 return size;
2388 }
2389
2390 /*
2391 *----------------------------------------------------------------------
2392 *
2393 * Blt_AsyncWrite --
2394 *
2395 * Writes output to the pipe from the given buffer.
2396 *
2397 * Results:
2398 * Returns the number of bytes written.
2399 *
2400 *----------------------------------------------------------------------
2401 */
2402 int
2403 Blt_AsyncWrite(
2404 int f,
2405 char *buffer,
2406 unsigned int size)
2407 {
2408 register PipeHandler *pipePtr;
2409
2410 pipePtr = GetPipeHandler((HANDLE) f);
2411 if ((pipePtr == NULL) || (pipePtr->flags & PIPE_DELETED)) {
2412 errno = EBADF;
2413 return -1;
2414 }
2415 if (WaitForSingleObject(pipePtr->readyEvent, 0) == WAIT_TIMEOUT) {
2416 /*
2417 * Writer thread is currently blocked waiting for a write to
2418 * complete.
2419 */
2420 errno = EAGAIN;
2421 return -1;
2422 }
2423 /* Check for a background error on the last write. */
2424 if (pipePtr->lastError) {
2425 TclWinConvertError(pipePtr->lastError);
2426 pipePtr->lastError = 0;
2427 return -1;
2428 }
2429 /* Reallocate the buffer to be large enough to hold the data. */
2430 if (size > pipePtr->size) {
2431 char *ptr;
2432
2433 ptr = Blt_Malloc(size);
2434 assert(ptr);
2435 Blt_Free(pipePtr->buffer);
2436 pipePtr->buffer = ptr;
2437 }
2438 memcpy(pipePtr->buffer, buffer, size);
2439 pipePtr->end = pipePtr->size = size;
2440 ResetEvent(pipePtr->readyEvent);
2441 SetEvent(pipePtr->idleEvent);
2442 return size;
2443 }