Debian Codegraph @

win/tclWinConsole.c

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