Debian Codegraph @

pTk/mTk/tclWin/tclWinConsole.c

raw
1 /*
2 * tclWinConsole.c --
3 *
4 * This file implements the Windows-specific console functions,
5 * and the "console" channel driver.
6 *
7 * Copyright (c) 1999 by Scriptics Corp.
8 *
9 * See the file "license.terms" for information on usage and redistribution
10 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
11 *
12 * RCS: @(#) $Id: tclWinConsole.c,v 1.11 2002/11/26 22:41:58 davygrvy Exp $
13 */
14
15 #include "tclWinInt.h"
16
17 #include <fcntl.h>
18 #include <io.h>
19 #include <sys/stat.h>
20
21 /*
22 * The following variable is used to tell whether this module has been
23 * initialized.
24 */
25
26 static int initialized = 0;
27
28 /*
29 * The consoleMutex locks around access to the initialized variable, and it is
30 * used to protect background threads from being terminated while they are
31 * using APIs that hold locks.
32 */
33
34 TCL_DECLARE_MUTEX(consoleMutex)
35
36 /*
37 * Bit masks used in the flags field of the ConsoleInfo structure below.
38 */
39
40 #define CONSOLE_PENDING (1<<0) /* Message is pending in the queue. */
41 #define CONSOLE_ASYNC (1<<1) /* Channel is non-blocking. */
42
43 /*
44 * Bit masks used in the sharedFlags field of the ConsoleInfo structure below.
45 */
46
47 #define CONSOLE_EOF (1<<2) /* Console has reached EOF. */
48 #define CONSOLE_BUFFERED (1<<3) /* data was read into a buffer by the reader
49 thread */
50
51 #define CONSOLE_BUFFER_SIZE (8*1024)
52 /*
53 * This structure describes per-instance data for a console based channel.
54 */
55
56 typedef struct ConsoleInfo {
57 HANDLE handle;
58 int type;
59 struct ConsoleInfo *nextPtr;/* Pointer to next registered console. */
60 Tcl_Channel channel; /* Pointer to channel structure. */
61 int validMask; /* OR'ed combination of TCL_READABLE,
62 * TCL_WRITABLE, or TCL_EXCEPTION: indicates
63 * which operations are valid on the file. */
64 int watchMask; /* OR'ed combination of TCL_READABLE,
65 * TCL_WRITABLE, or TCL_EXCEPTION: indicates
66 * which events should be reported. */
67 int flags; /* State flags, see above for a list. */
68 Tcl_ThreadId threadId; /* Thread to which events should be reported.
69 * This value is used by the reader/writer
70 * threads. */
71 HANDLE writeThread; /* Handle to writer thread. */
72 HANDLE readThread; /* Handle to reader thread. */
73 HANDLE writable; /* Manual-reset event to signal when the
74 * writer thread has finished waiting for
75 * the current buffer to be written. */
76 HANDLE readable; /* Manual-reset event to signal when the
77 * reader thread has finished waiting for
78 * input. */
79 HANDLE startWriter; /* Auto-reset event used by the main thread to
80 * signal when the writer thread should attempt
81 * to write to the console. */
82 HANDLE stopWriter; /* Auto-reset event used by the main thread to
83 * signal when the writer thread should exit.
84 */
85 HANDLE startReader; /* Auto-reset event used by the main thread to
86 * signal when the reader thread should attempt
87 * to read from the console. */
88 HANDLE stopReader; /* Auto-reset event used by the main thread to
89 * signal when the reader thread should exit.
90 */
91 DWORD writeError; /* An error caused by the last background
92 * write. Set to 0 if no error has been
93 * detected. This word is shared with the
94 * writer thread so access must be
95 * synchronized with the writable object.
96 */
97 char *writeBuf; /* Current background output buffer.
98 * Access is synchronized with the writable
99 * object. */
100 int writeBufLen; /* Size of write buffer. Access is
101 * synchronized with the writable
102 * object. */
103 int toWrite; /* Current amount to be written. Access is
104 * synchronized with the writable object. */
105 int readFlags; /* Flags that are shared with the reader
106 * thread. Access is synchronized with the
107 * readable object. */
108 int bytesRead; /* number of bytes in the buffer */
109 int offset; /* number of bytes read out of the buffer */
110 char buffer[CONSOLE_BUFFER_SIZE];
111 /* Data consumed by reader thread. */
112 } ConsoleInfo;
113
114 typedef struct ThreadSpecificData {
115 /*
116 * The following pointer refers to the head of the list of consoles
117 * that are being watched for file events.
118 */
119
120 ConsoleInfo *firstConsolePtr;
121 } ThreadSpecificData;
122
123 static Tcl_ThreadDataKey dataKey;
124
125 /*
126 * The following structure is what is added to the Tcl event queue when
127 * console events are generated.
128 */
129
130 typedef struct ConsoleEvent {
131 Tcl_Event header; /* Information that is standard for
132 * all events. */
133 ConsoleInfo *infoPtr; /* Pointer to console info structure. Note
134 * that we still have to verify that the
135 * console exists before dereferencing this
136 * pointer. */
137 } ConsoleEvent;
138
139 /*
140 * Declarations for functions used only in this file.
141 */
142
143 static int ConsoleBlockModeProc(ClientData instanceData, int mode);
144 static void ConsoleCheckProc(ClientData clientData, int flags);
145 static int ConsoleCloseProc(ClientData instanceData,
146 Tcl_Interp *interp);
147 static int ConsoleEventProc(Tcl_Event *evPtr, int flags);
148 static void ConsoleExitHandler(ClientData clientData);
149 static int ConsoleGetHandleProc(ClientData instanceData,
150 int direction, ClientData *handlePtr);
151 static ThreadSpecificData *ConsoleInit(void);
152 static int ConsoleInputProc(ClientData instanceData, char *buf,
153 int toRead, int *errorCode);
154 static int ConsoleOutputProc(ClientData instanceData,
155 CONST char *buf, int toWrite, int *errorCode);
156 static DWORD WINAPI ConsoleReaderThread(LPVOID arg);
157 static void ConsoleSetupProc(ClientData clientData, int flags);
158 static void ConsoleWatchProc(ClientData instanceData, int mask);
159 static DWORD WINAPI ConsoleWriterThread(LPVOID arg);
160 static void ProcExitHandler(ClientData clientData);
161 static int WaitForRead(ConsoleInfo *infoPtr, int blocking);
162
163 /*
164 * This structure describes the channel type structure for command console
165 * based IO.
166 */
167
168 static Tcl_ChannelType consoleChannelType = {
169 "console", /* Type name. */
170 TCL_CHANNEL_VERSION_2, /* v2 channel */
171 ConsoleCloseProc, /* Close proc. */
172 ConsoleInputProc, /* Input proc. */
173 ConsoleOutputProc, /* Output proc. */
174 NULL, /* Seek proc. */
175 NULL, /* Set option proc. */
176 NULL, /* Get option proc. */
177 ConsoleWatchProc, /* Set up notifier to watch the channel. */
178 ConsoleGetHandleProc, /* Get an OS handle from channel. */
179 NULL, /* close2proc. */
180 ConsoleBlockModeProc, /* Set blocking or non-blocking mode.*/
181 NULL, /* flush proc. */
182 NULL, /* handler proc. */
183 };
184
185 /*
186 *----------------------------------------------------------------------
187 *
188 * ConsoleInit --
189 *
190 * This function initializes the static variables for this file.
191 *
192 * Results:
193 * None.
194 *
195 * Side effects:
196 * Creates a new event source.
197 *
198 *----------------------------------------------------------------------
199 */
200
201 static ThreadSpecificData *
202 ConsoleInit()
203 {
204 ThreadSpecificData *tsdPtr;
205
206 /*
207 * Check the initialized flag first, then check again in the mutex.
208 * This is a speed enhancement.
209 */
210
211 if (!initialized) {
212 Tcl_MutexLock(&consoleMutex);
213 if (!initialized) {
214 initialized = 1;
215 Tcl_CreateExitHandler(ProcExitHandler, NULL);
216 }
217 Tcl_MutexUnlock(&consoleMutex);
218 }
219
220 tsdPtr = (ThreadSpecificData *)TclThreadDataKeyGet(&dataKey);
221 if (tsdPtr == NULL) {
222 tsdPtr = TCL_TSD_INIT(&dataKey);
223 tsdPtr->firstConsolePtr = NULL;
224 Tcl_CreateEventSource(ConsoleSetupProc, ConsoleCheckProc, NULL);
225 Tcl_CreateThreadExitHandler(ConsoleExitHandler, NULL);
226 }
227 return tsdPtr;
228 }
229
230 /*
231 *----------------------------------------------------------------------
232 *
233 * ConsoleExitHandler --
234 *
235 * This function is called to cleanup the console module before
236 * Tcl is unloaded.
237 *
238 * Results:
239 * None.
240 *
241 * Side effects:
242 * Removes the console event source.
243 *
244 *----------------------------------------------------------------------
245 */
246
247 static void
248 ConsoleExitHandler(
249 ClientData clientData) /* Old window proc */
250 {
251 Tcl_DeleteEventSource(ConsoleSetupProc, ConsoleCheckProc, NULL);
252 }
253
254 /*
255 *----------------------------------------------------------------------
256 *
257 * ProcExitHandler --
258 *
259 * This function is called to cleanup the process list before
260 * Tcl is unloaded.
261 *
262 * Results:
263 * None.
264 *
265 * Side effects:
266 * Resets the process list.
267 *
268 *----------------------------------------------------------------------
269 */
270
271 static void
272 ProcExitHandler(
273 ClientData clientData) /* Old window proc */
274 {
275 Tcl_MutexLock(&consoleMutex);
276 initialized = 0;
277 Tcl_MutexUnlock(&consoleMutex);
278 }
279
280 /*
281 *----------------------------------------------------------------------
282 *
283 * ConsoleSetupProc --
284 *
285 * This procedure is invoked before Tcl_DoOneEvent blocks waiting
286 * for an event.
287 *
288 * Results:
289 * None.
290 *
291 * Side effects:
292 * Adjusts the block time if needed.
293 *
294 *----------------------------------------------------------------------
295 */
296
297 void
298 ConsoleSetupProc(
299 ClientData data, /* Not used. */
300 int flags) /* Event flags as passed to Tcl_DoOneEvent. */
301 {
302 ConsoleInfo *infoPtr;
303 Tcl_Time blockTime = { 0, 0 };
304 int block = 1;
305 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
306
307 if (!(flags & TCL_FILE_EVENTS)) {
308 return;
309 }
310
311 /*
312 * Look to see if any events are already pending. If they are, poll.
313 */
314
315 for (infoPtr = tsdPtr->firstConsolePtr; infoPtr != NULL;
316 infoPtr = infoPtr->nextPtr) {
317 if (infoPtr->watchMask & TCL_WRITABLE) {
318 if (WaitForSingleObject(infoPtr->writable, 0) != WAIT_TIMEOUT) {
319 block = 0;
320 }
321 }
322 if (infoPtr->watchMask & TCL_READABLE) {
323 if (WaitForRead(infoPtr, 0) >= 0) {
324 block = 0;
325 }
326 }
327 }
328 if (!block) {
329 Tcl_SetMaxBlockTime(&blockTime);
330 }
331 }
332
333 /*
334 *----------------------------------------------------------------------
335 *
336 * ConsoleCheckProc --
337 *
338 * This procedure is called by Tcl_DoOneEvent to check the console
339 * event source for events.
340 *
341 * Results:
342 * None.
343 *
344 * Side effects:
345 * May queue an event.
346 *
347 *----------------------------------------------------------------------
348 */
349
350 static void
351 ConsoleCheckProc(
352 ClientData data, /* Not used. */
353 int flags) /* Event flags as passed to Tcl_DoOneEvent. */
354 {
355 ConsoleInfo *infoPtr;
356 ConsoleEvent *evPtr;
357 int needEvent;
358 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
359
360 if (!(flags & TCL_FILE_EVENTS)) {
361 return;
362 }
363
364 /*
365 * Queue events for any ready consoles that don't already have events
366 * queued.
367 */
368
369 for (infoPtr = tsdPtr->firstConsolePtr; infoPtr != NULL;
370 infoPtr = infoPtr->nextPtr) {
371 if (infoPtr->flags & CONSOLE_PENDING) {
372 continue;
373 }
374
375 /*
376 * Queue an event if the console is signaled for reading or writing.
377 */
378
379 needEvent = 0;
380 if (infoPtr->watchMask & TCL_WRITABLE) {
381 if (WaitForSingleObject(infoPtr->writable, 0) != WAIT_TIMEOUT) {
382 needEvent = 1;
383 }
384 }
385
386 if (infoPtr->watchMask & TCL_READABLE) {
387 if (WaitForRead(infoPtr, 0) >= 0) {
388 needEvent = 1;
389 }
390 }
391
392 if (needEvent) {
393 infoPtr->flags |= CONSOLE_PENDING;
394 evPtr = (ConsoleEvent *) ckalloc(sizeof(ConsoleEvent));
395 evPtr->header.proc = ConsoleEventProc;
396 evPtr->infoPtr = infoPtr;
397 Tcl_QueueEvent((Tcl_Event *) evPtr, TCL_QUEUE_TAIL);
398 }
399 }
400 }
401
402
403 /*
404 *----------------------------------------------------------------------
405 *
406 * ConsoleBlockModeProc --
407 *
408 * Set blocking or non-blocking mode on channel.
409 *
410 * Results:
411 * 0 if successful, errno when failed.
412 *
413 * Side effects:
414 * Sets the device into blocking or non-blocking mode.
415 *
416 *----------------------------------------------------------------------
417 */
418
419 static int
420 ConsoleBlockModeProc(
421 ClientData instanceData, /* Instance data for channel. */
422 int mode) /* TCL_MODE_BLOCKING or
423 * TCL_MODE_NONBLOCKING. */
424 {
425 ConsoleInfo *infoPtr = (ConsoleInfo *) instanceData;
426
427 /*
428 * Consoles on Windows can not be switched between blocking and nonblocking,
429 * hence we have to emulate the behavior. This is done in the input
430 * function by checking against a bit in the state. We set or unset the
431 * bit here to cause the input function to emulate the correct behavior.
432 */
433
434 if (mode == TCL_MODE_NONBLOCKING) {
435 infoPtr->flags |= CONSOLE_ASYNC;
436 } else {
437 infoPtr->flags &= ~(CONSOLE_ASYNC);
438 }
439 return 0;
440 }
441
442 /*
443 *----------------------------------------------------------------------
444 *
445 * ConsoleCloseProc --
446 *
447 * Closes a console based IO channel.
448 *
449 * Results:
450 * 0 on success, errno otherwise.
451 *
452 * Side effects:
453 * Closes the physical channel.
454 *
455 *----------------------------------------------------------------------
456 */
457
458 static int
459 ConsoleCloseProc(
460 ClientData instanceData, /* Pointer to ConsoleInfo structure. */
461 Tcl_Interp *interp) /* For error reporting. */
462 {
463 ConsoleInfo *consolePtr = (ConsoleInfo *) instanceData;
464 int errorCode;
465 ConsoleInfo *infoPtr, **nextPtrPtr;
466 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
467 DWORD exitCode;
468
469 errorCode = 0;
470
471 /*
472 * Clean up the background thread if necessary. Note that this
473 * must be done before we can close the file, since the
474 * thread may be blocking trying to read from the console.
475 */
476
477 if (consolePtr->readThread) {
478
479 /*
480 * The thread may already have closed on it's own. Check it's
481 * exit code.
482 */
483
484 GetExitCodeThread(consolePtr->readThread, &exitCode);
485
486 if (exitCode == STILL_ACTIVE) {
487
488 /*
489 * Set the stop event so that if the reader thread is blocked
490 * in ConsoleReaderThread on WaitForMultipleEvents, it will exit
491 * cleanly.
492 */
493
494 SetEvent(consolePtr->stopReader);
495
496 /*
497 * Wait at most 20 milliseconds for the reader thread to close.
498 */
499
500 if (WaitForSingleObject(consolePtr->readThread, 20)
501 == WAIT_TIMEOUT) {
502 /*
503 * Forcibly terminate the background thread as a last
504 * resort. Note that we need to guard against
505 * terminating the thread while it is in the middle of
506 * Tcl_ThreadAlert because it won't be able to release
507 * the notifier lock.
508 */
509
510 Tcl_MutexLock(&consoleMutex);
511
512 /* BUG: this leaks memory. */
513 TerminateThread(consolePtr->readThread, 0);
514 Tcl_MutexUnlock(&consoleMutex);
515 }
516 }
517
518 CloseHandle(consolePtr->readThread);
519 CloseHandle(consolePtr->readable);
520 CloseHandle(consolePtr->startReader);
521 CloseHandle(consolePtr->stopReader);
522 consolePtr->readThread = NULL;
523 }
524 consolePtr->validMask &= ~TCL_READABLE;
525
526 /*
527 * Wait for the writer thread to finish the current buffer, then
528 * terminate the thread and close the handles. If the channel is
529 * nonblocking, there should be no pending write operations.
530 */
531
532 if (consolePtr->writeThread) {
533 if (consolePtr->toWrite) {
534 /*
535 * We only need to wait if there is something to write.
536 * This may prevent infinite wait on exit. [python bug 216289]
537 */
538 WaitForSingleObject(consolePtr->writable, INFINITE);
539 }
540
541 /*
542 * The thread may already have closed on it's own. Check it's
543 * exit code.
544 */
545
546 GetExitCodeThread(consolePtr->writeThread, &exitCode);
547
548 if (exitCode == STILL_ACTIVE) {
549 /*
550 * Set the stop event so that if the reader thread is blocked
551 * in ConsoleWriterThread on WaitForMultipleEvents, it will
552 * exit cleanly.
553 */
554
555 SetEvent(consolePtr->stopWriter);
556
557 /*
558 * Wait at most 20 milliseconds for the writer thread to close.
559 */
560
561 if (WaitForSingleObject(consolePtr->writeThread, 20)
562 == WAIT_TIMEOUT) {
563 /*
564 * Forcibly terminate the background thread as a last
565 * resort. Note that we need to guard against
566 * terminating the thread while it is in the middle of
567 * Tcl_ThreadAlert because it won't be able to release
568 * the notifier lock.
569 */
570
571 Tcl_MutexLock(&consoleMutex);
572
573 /* BUG: this leaks memory. */
574 TerminateThread(consolePtr->writeThread, 0);
575 Tcl_MutexUnlock(&consoleMutex);
576 }
577 }
578
579 CloseHandle(consolePtr->writeThread);
580 CloseHandle(consolePtr->writable);
581 CloseHandle(consolePtr->startWriter);
582 CloseHandle(consolePtr->stopWriter);
583 consolePtr->writeThread = NULL;
584 }
585 consolePtr->validMask &= ~TCL_WRITABLE;
586
587
588 /*
589 * Don't close the Win32 handle if the handle is a standard channel
590 * during the thread exit process. Otherwise, one thread may kill
591 * the stdio of another.
592 */
593
594 if (!TclInThreadExit()
595 || ((GetStdHandle(STD_INPUT_HANDLE) != consolePtr->handle)
596 && (GetStdHandle(STD_OUTPUT_HANDLE) != consolePtr->handle)
597 && (GetStdHandle(STD_ERROR_HANDLE) != consolePtr->handle))) {
598 if (CloseHandle(consolePtr->handle) == FALSE) {
599 TclWinConvertError(GetLastError());
600 errorCode = errno;
601 }
602 }
603
604 consolePtr->watchMask &= consolePtr->validMask;
605
606 /*
607 * Remove the file from the list of watched files.
608 */
609
610 for (nextPtrPtr = &(tsdPtr->firstConsolePtr), infoPtr = *nextPtrPtr;
611 infoPtr != NULL;
612 nextPtrPtr = &infoPtr->nextPtr, infoPtr = *nextPtrPtr) {
613 if (infoPtr == (ConsoleInfo *)consolePtr) {
614 *nextPtrPtr = infoPtr->nextPtr;
615 break;
616 }
617 }
618 if (consolePtr->writeBuf != NULL) {
619 ckfree(consolePtr->writeBuf);
620 consolePtr->writeBuf = 0;
621 }
622 ckfree((char*) consolePtr);
623
624 return errorCode;
625 }
626
627 /*
628 *----------------------------------------------------------------------
629 *
630 * ConsoleInputProc --
631 *
632 * Reads input from the IO channel into the buffer given. Returns
633 * count of how many bytes were actually read, and an error indication.
634 *
635 * Results:
636 * A count of how many bytes were read is returned and an error
637 * indication is returned in an output argument.
638 *
639 * Side effects:
640 * Reads input from the actual channel.
641 *
642 *----------------------------------------------------------------------
643 */
644
645 static int
646 ConsoleInputProc(
647 ClientData instanceData, /* Console state. */
648 char *buf, /* Where to store data read. */
649 int bufSize, /* How much space is available
650 * in the buffer? */
651 int *errorCode) /* Where to store error code. */
652 {
653 ConsoleInfo *infoPtr = (ConsoleInfo *) instanceData;
654 DWORD count, bytesRead = 0;
655 int result;
656
657 *errorCode = 0;
658
659 /*
660 * Synchronize with the reader thread.
661 */
662
663 result = WaitForRead(infoPtr, (infoPtr->flags & CONSOLE_ASYNC) ? 0 : 1);
664
665 /*
666 * If an error occurred, return immediately.
667 */
668
669 if (result == -1) {
670 *errorCode = errno;
671 return -1;
672 }
673
674 if (infoPtr->readFlags & CONSOLE_BUFFERED) {
675 /*
676 * Data is stored in the buffer.
677 */
678
679 if (bufSize < (infoPtr->bytesRead - infoPtr->offset)) {
680 memcpy(buf, &infoPtr->buffer[infoPtr->offset], (size_t) bufSize);
681 bytesRead = bufSize;
682 infoPtr->offset += bufSize;
683 } else {
684 memcpy(buf, &infoPtr->buffer[infoPtr->offset], (size_t) bufSize);
685 bytesRead = infoPtr->bytesRead - infoPtr->offset;
686
687 /*
688 * Reset the buffer
689 */
690
691 infoPtr->readFlags &= ~CONSOLE_BUFFERED;
692 infoPtr->offset = 0;
693 }
694
695 return bytesRead;
696 }
697
698 /*
699 * Attempt to read bufSize bytes. The read will return immediately
700 * if there is any data available. Otherwise it will block until
701 * at least one byte is available or an EOF occurs.
702 */
703
704 if (ReadConsole(infoPtr->handle, (LPVOID) buf, (DWORD) bufSize, &count,
705 (LPOVERLAPPED) NULL) == TRUE) {
706 buf[count] = '\0';
707 return count;
708 }
709
710 return -1;
711 }
712
713 /*
714 *----------------------------------------------------------------------
715 *
716 * ConsoleOutputProc --
717 *
718 * Writes the given output on the IO channel. Returns count of how
719 * many characters were actually written, and an error indication.
720 *
721 * Results:
722 * A count of how many characters were written is returned and an
723 * error indication is returned in an output argument.
724 *
725 * Side effects:
726 * Writes output on the actual channel.
727 *
728 *----------------------------------------------------------------------
729 */
730
731 static int
732 ConsoleOutputProc(
733 ClientData instanceData, /* Console state. */
734 CONST char *buf, /* The data buffer. */
735 int toWrite, /* How many bytes to write? */
736 int *errorCode) /* Where to store error code. */
737 {
738 ConsoleInfo *infoPtr = (ConsoleInfo *) instanceData;
739 DWORD bytesWritten, timeout;
740
741 *errorCode = 0;
742 timeout = (infoPtr->flags & CONSOLE_ASYNC) ? 0 : INFINITE;
743 if (WaitForSingleObject(infoPtr->writable, timeout) == WAIT_TIMEOUT) {
744 /*
745 * The writer thread is blocked waiting for a write to complete
746 * and the channel is in non-blocking mode.
747 */
748
749 errno = EAGAIN;
750 goto error;
751 }
752
753 /*
754 * Check for a background error on the last write.
755 */
756
757 if (infoPtr->writeError) {
758 TclWinConvertError(infoPtr->writeError);
759 infoPtr->writeError = 0;
760 goto error;
761 }
762
763 if (infoPtr->flags & CONSOLE_ASYNC) {
764 /*
765 * The console is non-blocking, so copy the data into the output
766 * buffer and restart the writer thread.
767 */
768
769 if (toWrite > infoPtr->writeBufLen) {
770 /*
771 * Reallocate the buffer to be large enough to hold the data.
772 */
773
774 if (infoPtr->writeBuf) {
775 ckfree(infoPtr->writeBuf);
776 }
777 infoPtr->writeBufLen = toWrite;
778 infoPtr->writeBuf = ckalloc((unsigned int) toWrite);
779 }
780 memcpy(infoPtr->writeBuf, buf, (size_t) toWrite);
781 infoPtr->toWrite = toWrite;
782 ResetEvent(infoPtr->writable);
783 SetEvent(infoPtr->startWriter);
784 bytesWritten = toWrite;
785 } else {
786 /*
787 * In the blocking case, just try to write the buffer directly.
788 * This avoids an unnecessary copy.
789 */
790
791 if (WriteFile(infoPtr->handle, (LPVOID) buf, (DWORD) toWrite,
792 &bytesWritten, (LPOVERLAPPED) NULL) == FALSE) {
793 TclWinConvertError(GetLastError());
794 goto error;
795 }
796 }
797 return bytesWritten;
798
799 error:
800 *errorCode = errno;
801 return -1;
802
803 }
804
805 /*
806 *----------------------------------------------------------------------
807 *
808 * ConsoleEventProc --
809 *
810 * This function is invoked by Tcl_ServiceEvent when a file event
811 * reaches the front of the event queue. This procedure invokes
812 * Tcl_NotifyChannel on the console.
813 *
814 * Results:
815 * Returns 1 if the event was handled, meaning it should be removed
816 * from the queue. Returns 0 if the event was not handled, meaning
817 * it should stay on the queue. The only time the event isn't
818 * handled is if the TCL_FILE_EVENTS flag bit isn't set.
819 *
820 * Side effects:
821 * Whatever the notifier callback does.
822 *
823 *----------------------------------------------------------------------
824 */
825
826 static int
827 ConsoleEventProc(
828 Tcl_Event *evPtr, /* Event to service. */
829 int flags) /* Flags that indicate what events to
830 * handle, such as TCL_FILE_EVENTS. */
831 {
832 ConsoleEvent *consoleEvPtr = (ConsoleEvent *)evPtr;
833 ConsoleInfo *infoPtr;
834 int mask;
835 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
836
837 if (!(flags & TCL_FILE_EVENTS)) {
838 return 0;
839 }
840
841 /*
842 * Search through the list of watched consoles for the one whose handle
843 * matches the event. We do this rather than simply dereferencing
844 * the handle in the event so that consoles can be deleted while the
845 * event is in the queue.
846 */
847
848 for (infoPtr = tsdPtr->firstConsolePtr; infoPtr != NULL;
849 infoPtr = infoPtr->nextPtr) {
850 if (consoleEvPtr->infoPtr == infoPtr) {
851 infoPtr->flags &= ~(CONSOLE_PENDING);
852 break;
853 }
854 }
855
856 /*
857 * Remove stale events.
858 */
859
860 if (!infoPtr) {
861 return 1;
862 }
863
864 /*
865 * Check to see if the console is readable. Note
866 * that we can't tell if a console is writable, so we always report it
867 * as being writable unless we have detected EOF.
868 */
869
870 mask = 0;
871 if (infoPtr->watchMask & TCL_WRITABLE) {
872 if (WaitForSingleObject(infoPtr->writable, 0) != WAIT_TIMEOUT) {
873 mask = TCL_WRITABLE;
874 }
875 }
876
877 if (infoPtr->watchMask & TCL_READABLE) {
878 if (WaitForRead(infoPtr, 0) >= 0) {
879 if (infoPtr->readFlags & CONSOLE_EOF) {
880 mask = TCL_READABLE;
881 } else {
882 mask |= TCL_READABLE;
883 }
884 }
885 }
886
887 /*
888 * Inform the channel of the events.
889 */
890
891 Tcl_NotifyChannel(infoPtr->channel, infoPtr->watchMask & mask);
892 return 1;
893 }
894
895 /*
896 *----------------------------------------------------------------------
897 *
898 * ConsoleWatchProc --
899 *
900 * Called by the notifier to set up to watch for events on this
901 * channel.
902 *
903 * Results:
904 * None.
905 *
906 * Side effects:
907 * None.
908 *
909 *----------------------------------------------------------------------
910 */
911
912 static void
913 ConsoleWatchProc(
914 ClientData instanceData, /* Console state. */
915 int mask) /* What events to watch for, OR-ed
916 * combination of TCL_READABLE,
917 * TCL_WRITABLE and TCL_EXCEPTION. */
918 {
919 ConsoleInfo **nextPtrPtr, *ptr;
920 ConsoleInfo *infoPtr = (ConsoleInfo *) instanceData;
921 int oldMask = infoPtr->watchMask;
922 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
923
924 /*
925 * Since most of the work is handled by the background threads,
926 * we just need to update the watchMask and then force the notifier
927 * to poll once.
928 */
929
930 infoPtr->watchMask = mask & infoPtr->validMask;
931 if (infoPtr->watchMask) {
932 Tcl_Time blockTime = { 0, 0 };
933 if (!oldMask) {
934 infoPtr->nextPtr = tsdPtr->firstConsolePtr;
935 tsdPtr->firstConsolePtr = infoPtr;
936 }
937 Tcl_SetMaxBlockTime(&blockTime);
938 } else {
939 if (oldMask) {
940 /*
941 * Remove the console from the list of watched consoles.
942 */
943
944 for (nextPtrPtr = &(tsdPtr->firstConsolePtr), ptr = *nextPtrPtr;
945 ptr != NULL;
946 nextPtrPtr = &ptr->nextPtr, ptr = *nextPtrPtr) {
947 if (infoPtr == ptr) {
948 *nextPtrPtr = ptr->nextPtr;
949 break;
950 }
951 }
952 }
953 }
954 }
955
956 /*
957 *----------------------------------------------------------------------
958 *
959 * ConsoleGetHandleProc --
960 *
961 * Called from Tcl_GetChannelHandle to retrieve OS handles from
962 * inside a command consoleline based channel.
963 *
964 * Results:
965 * Returns TCL_OK with the fd in handlePtr, or TCL_ERROR if
966 * there is no handle for the specified direction.
967 *
968 * Side effects:
969 * None.
970 *
971 *----------------------------------------------------------------------
972 */
973
974 static int
975 ConsoleGetHandleProc(
976 ClientData instanceData, /* The console state. */
977 int direction, /* TCL_READABLE or TCL_WRITABLE */
978 ClientData *handlePtr) /* Where to store the handle. */
979 {
980 ConsoleInfo *infoPtr = (ConsoleInfo *) instanceData;
981
982 *handlePtr = (ClientData) infoPtr->handle;
983 return TCL_OK;
984 }
985
986 /*
987 *----------------------------------------------------------------------
988 *
989 * WaitForRead --
990 *
991 * Wait until some data is available, the console is at
992 * EOF or the reader thread is blocked waiting for data (if the
993 * channel is in non-blocking mode).
994 *
995 * Results:
996 * Returns 1 if console is readable. Returns 0 if there is no data
997 * on the console, but there is buffered data. Returns -1 if an
998 * error occurred. If an error occurred, the threads may not
999 * be synchronized.
1000 *
1001 * Side effects:
1002 * Updates the shared state flags. If no error occurred,
1003 * the reader thread is blocked waiting for a signal from the
1004 * main thread.
1005 *
1006 *----------------------------------------------------------------------
1007 */
1008
1009 static int
1010 WaitForRead(
1011 ConsoleInfo *infoPtr, /* Console state. */
1012 int blocking) /* Indicates whether call should be
1013 * blocking or not. */
1014 {
1015 DWORD timeout, count;
1016 HANDLE *handle = infoPtr->handle;
1017 INPUT_RECORD input;
1018
1019 while (1) {
1020 /*
1021 * Synchronize with the reader thread.
1022 */
1023
1024 timeout = blocking ? INFINITE : 0;
1025 if (WaitForSingleObject(infoPtr->readable, timeout) == WAIT_TIMEOUT) {
1026 /*
1027 * The reader thread is blocked waiting for data and the channel
1028 * is in non-blocking mode.
1029 */
1030 errno = EAGAIN;
1031 return -1;
1032 }
1033
1034 /*
1035 * At this point, the two threads are synchronized, so it is safe
1036 * to access shared state.
1037 */
1038
1039 /*
1040 * If the console has hit EOF, it is always readable.
1041 */
1042
1043 if (infoPtr->readFlags & CONSOLE_EOF) {
1044 return 1;
1045 }
1046
1047 if (PeekConsoleInput(handle, &input, 1, &count) == FALSE) {
1048 /*
1049 * Check to see if the peek failed because of EOF.
1050 */
1051
1052 TclWinConvertError(GetLastError());
1053
1054 if (errno == EOF) {
1055 infoPtr->readFlags |= CONSOLE_EOF;
1056 return 1;
1057 }
1058
1059 /*
1060 * Ignore errors if there is data in the buffer.
1061 */
1062
1063 if (infoPtr->readFlags & CONSOLE_BUFFERED) {
1064 return 0;
1065 } else {
1066 return -1;
1067 }
1068 }
1069
1070 /*
1071 * If there is data in the buffer, the console must be
1072 * readable (since it is a line-oriented device).
1073 */
1074
1075 if (infoPtr->readFlags & CONSOLE_BUFFERED) {
1076 return 1;
1077 }
1078
1079
1080 /*
1081 * There wasn't any data available, so reset the thread and
1082 * try again.
1083 */
1084
1085 ResetEvent(infoPtr->readable);
1086 SetEvent(infoPtr->startReader);
1087 }
1088 }
1089
1090 /*
1091 *----------------------------------------------------------------------
1092 *
1093 * ConsoleReaderThread --
1094 *
1095 * This function runs in a separate thread and waits for input
1096 * to become available on a console.
1097 *
1098 * Results:
1099 * None.
1100 *
1101 * Side effects:
1102 * Signals the main thread when input become available. May
1103 * cause the main thread to wake up by posting a message. May
1104 * one line from the console for each wait operation.
1105 *
1106 *----------------------------------------------------------------------
1107 */
1108
1109 static DWORD WINAPI
1110 ConsoleReaderThread(LPVOID arg)
1111 {
1112 ConsoleInfo *infoPtr = (ConsoleInfo *)arg;
1113 HANDLE *handle = infoPtr->handle;
1114 DWORD count, waitResult;
1115 HANDLE wEvents[2];
1116
1117 /* The first event takes precedence. */
1118 wEvents[0] = infoPtr->stopReader;
1119 wEvents[1] = infoPtr->startReader;
1120
1121 for (;;) {
1122 /*
1123 * Wait for the main thread to signal before attempting to wait.
1124 */
1125
1126 waitResult = WaitForMultipleObjects(2, wEvents, FALSE, INFINITE);
1127
1128 if (waitResult != (WAIT_OBJECT_0 + 1)) {
1129 /*
1130 * The start event was not signaled. It must be the stop event
1131 * or an error, so exit this thread.
1132 */
1133
1134 break;
1135 }
1136
1137 count = 0;
1138
1139 /*
1140 * Look for data on the console, but first ignore any events
1141 * that are not KEY_EVENTs
1142 */
1143 if (ReadConsoleA(handle, infoPtr->buffer, CONSOLE_BUFFER_SIZE,
1144 (LPDWORD) &infoPtr->bytesRead, NULL) != FALSE) {
1145 /*
1146 * Data was stored in the buffer.
1147 */
1148
1149 infoPtr->readFlags |= CONSOLE_BUFFERED;
1150 } else {
1151 DWORD err;
1152 err = GetLastError();
1153
1154 if (err == EOF) {
1155 infoPtr->readFlags = CONSOLE_EOF;
1156 }
1157 }
1158
1159 /*
1160 * Signal the main thread by signalling the readable event and
1161 * then waking up the notifier thread.
1162 */
1163
1164 SetEvent(infoPtr->readable);
1165
1166 /*
1167 * Alert the foreground thread. Note that we need to treat this like
1168 * a critical section so the foreground thread does not terminate
1169 * this thread while we are holding a mutex in the notifier code.
1170 */
1171
1172 Tcl_MutexLock(&consoleMutex);
1173 Tcl_ThreadAlert(infoPtr->threadId);
1174 Tcl_MutexUnlock(&consoleMutex);
1175 }
1176
1177 return 0;
1178 }
1179
1180 /*
1181 *----------------------------------------------------------------------
1182 *
1183 * ConsoleWriterThread --
1184 *
1185 * This function runs in a separate thread and writes data
1186 * onto a console.
1187 *
1188 * Results:
1189 * Always returns 0.
1190 *
1191 * Side effects:
1192 * Signals the main thread when an output operation is completed.
1193 * May cause the main thread to wake up by posting a message.
1194 *
1195 *----------------------------------------------------------------------
1196 */
1197
1198 static DWORD WINAPI
1199 ConsoleWriterThread(LPVOID arg)
1200 {
1201
1202 ConsoleInfo *infoPtr = (ConsoleInfo *)arg;
1203 HANDLE *handle = infoPtr->handle;
1204 DWORD count, toWrite, waitResult;
1205 char *buf;
1206 HANDLE wEvents[2];
1207
1208 /* The first event takes precedence. */
1209 wEvents[0] = infoPtr->stopWriter;
1210 wEvents[1] = infoPtr->startWriter;
1211
1212 for (;;) {
1213 /*
1214 * Wait for the main thread to signal before attempting to write.
1215 */
1216
1217 waitResult = WaitForMultipleObjects(2, wEvents, FALSE, INFINITE);
1218
1219 if (waitResult != (WAIT_OBJECT_0 + 1)) {
1220 /*
1221 * The start event was not signaled. It must be the stop event
1222 * or an error, so exit this thread.
1223 */
1224
1225 break;
1226 }
1227
1228 buf = infoPtr->writeBuf;
1229 toWrite = infoPtr->toWrite;
1230
1231 /*
1232 * Loop until all of the bytes are written or an error occurs.
1233 */
1234
1235 while (toWrite > 0) {
1236 if (WriteConsoleA(handle, buf, toWrite, &count, NULL) == FALSE) {
1237 infoPtr->writeError = GetLastError();
1238 break;
1239 } else {
1240 toWrite -= count;
1241 buf += count;
1242 }
1243 }
1244
1245 /*
1246 * Signal the main thread by signalling the writable event and
1247 * then waking up the notifier thread.
1248 */
1249
1250 SetEvent(infoPtr->writable);
1251
1252 /*
1253 * Alert the foreground thread. Note that we need to treat this like
1254 * a critical section so the foreground thread does not terminate
1255 * this thread while we are holding a mutex in the notifier code.
1256 */
1257
1258 Tcl_MutexLock(&consoleMutex);
1259 Tcl_ThreadAlert(infoPtr->threadId);
1260 Tcl_MutexUnlock(&consoleMutex);
1261 }
1262
1263 return 0;
1264 }
1265
1266
1267
1268 /*
1269 *----------------------------------------------------------------------
1270 *
1271 * TclWinOpenConsoleChannel --
1272 *
1273 * Constructs a Console channel for the specified standard OS handle.
1274 * This is a helper function to break up the construction of
1275 * channels into File, Console, or Serial.
1276 *
1277 * Results:
1278 * Returns the new channel, or NULL.
1279 *
1280 * Side effects:
1281 * May open the channel
1282 *
1283 *----------------------------------------------------------------------
1284 */
1285
1286 Tcl_Channel
1287 TclWinOpenConsoleChannel(handle, channelName, permissions)
1288 HANDLE handle;
1289 char *channelName;
1290 int permissions;
1291 {
1292 char encoding[4 + TCL_INTEGER_SPACE];
1293 ConsoleInfo *infoPtr;
1294 ThreadSpecificData *tsdPtr;
1295 DWORD id, modes;
1296
1297 tsdPtr = ConsoleInit();
1298
1299 /*
1300 * See if a channel with this handle already exists.
1301 */
1302
1303 infoPtr = (ConsoleInfo *) ckalloc((unsigned) sizeof(ConsoleInfo));
1304 memset(infoPtr, 0, sizeof(ConsoleInfo));
1305
1306 infoPtr->validMask = permissions;
1307 infoPtr->handle = handle;
1308
1309 wsprintfA(encoding, "cp%d", GetConsoleCP());
1310
1311 /*
1312 * Use the pointer for the name of the result channel.
1313 * This keeps the channel names unique, since some may share
1314 * handles (stdin/stdout/stderr for instance).
1315 */
1316
1317 wsprintfA(channelName, "file%lx", (int) infoPtr);
1318
1319 infoPtr->channel = Tcl_CreateChannel(&consoleChannelType, channelName,
1320 (ClientData) infoPtr, permissions);
1321
1322 infoPtr->threadId = Tcl_GetCurrentThread();
1323
1324 if (permissions & TCL_READABLE) {
1325 /*
1326 * Make sure the console input buffer is ready for only character
1327 * input notifications and the buffer is set for line buffering.
1328 * IOW, we only want to catch when complete lines are ready for
1329 * reading.
1330 */
1331 GetConsoleMode(infoPtr->handle, &modes);
1332 modes &= ~(ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT);
1333 modes |= ENABLE_LINE_INPUT;
1334 SetConsoleMode(infoPtr->handle, modes);
1335
1336 infoPtr->readable = CreateEvent(NULL, TRUE, TRUE, NULL);
1337 infoPtr->startReader = CreateEvent(NULL, FALSE, FALSE, NULL);
1338 infoPtr->stopReader = CreateEvent(NULL, FALSE, FALSE, NULL);
1339 infoPtr->readThread = CreateThread(NULL, 256, ConsoleReaderThread,
1340 infoPtr, 0, &id);
1341 SetThreadPriority(infoPtr->readThread, THREAD_PRIORITY_HIGHEST);
1342 }
1343
1344 if (permissions & TCL_WRITABLE) {
1345 infoPtr->writable = CreateEvent(NULL, TRUE, TRUE, NULL);
1346 infoPtr->startWriter = CreateEvent(NULL, FALSE, FALSE, NULL);
1347 infoPtr->stopWriter = CreateEvent(NULL, FALSE, FALSE, NULL);
1348 infoPtr->writeThread = CreateThread(NULL, 256, ConsoleWriterThread,
1349 infoPtr, 0, &id);
1350 SetThreadPriority(infoPtr->writeThread, THREAD_PRIORITY_HIGHEST);
1351 }
1352
1353 /*
1354 * Files have default translation of AUTO and ^Z eof char, which
1355 * means that a ^Z will be accepted as EOF when reading.
1356 */
1357
1358 Tcl_SetChannelOption(NULL, infoPtr->channel, "-translation", "auto");
1359 Tcl_SetChannelOption(NULL, infoPtr->channel, "-eofchar", "\032 {}");
1360 Tcl_SetChannelOption(NULL, infoPtr->channel, "-encoding", encoding);
1361
1362 return infoPtr->channel;
1363 }