Debian Codegraph @

pTk/mTk/tclWin/tclWinChan.c

raw
1 /*
2 * tclWinChan.c
3 *
4 * Channel drivers for Windows channels based on files, command
5 * pipes and TCP sockets.
6 *
7 * Copyright (c) 1995-1997 Sun Microsystems, Inc.
8 *
9 * See the file "license.terms" for information on usage and redistribution
10 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
11 *
12 * RCS: @(#) $Id: tclWinChan.c,v 1.30 2003/01/26 05:59:38 mdejong Exp $
13 */
14
15 #include "tclWinInt.h"
16 #include "tclIO.h"
17
18 /*
19 * State flags used in the info structures below.
20 */
21
22 #define FILE_PENDING (1<<0) /* Message is pending in the queue. */
23 #define FILE_ASYNC (1<<1) /* Channel is non-blocking. */
24 #define FILE_APPEND (1<<2) /* File is in append mode. */
25
26 #define FILE_TYPE_SERIAL (FILE_TYPE_PIPE+1)
27 #define FILE_TYPE_CONSOLE (FILE_TYPE_PIPE+2)
28
29 /*
30 * The following structure contains per-instance data for a file based channel.
31 */
32
33 typedef struct FileInfo {
34 Tcl_Channel channel; /* Pointer to channel structure. */
35 int validMask; /* OR'ed combination of TCL_READABLE,
36 * TCL_WRITABLE, or TCL_EXCEPTION: indicates
37 * which operations are valid on the file. */
38 int watchMask; /* OR'ed combination of TCL_READABLE,
39 * TCL_WRITABLE, or TCL_EXCEPTION: indicates
40 * which events should be reported. */
41 int flags; /* State flags, see above for a list. */
42 HANDLE handle; /* Input/output file. */
43 struct FileInfo *nextPtr; /* Pointer to next registered file. */
44 int dirty; /* Boolean flag. Set if the OS may have data
45 * pending on the channel */
46 } FileInfo;
47
48 typedef struct ThreadSpecificData {
49 /*
50 * List of all file channels currently open.
51 */
52
53 FileInfo *firstFilePtr;
54 } ThreadSpecificData;
55
56 static Tcl_ThreadDataKey dataKey;
57
58 /*
59 * The following structure is what is added to the Tcl event queue when
60 * file events are generated.
61 */
62
63 typedef struct FileEvent {
64 Tcl_Event header; /* Information that is standard for
65 * all events. */
66 FileInfo *infoPtr; /* Pointer to file info structure. Note
67 * that we still have to verify that the
68 * file exists before dereferencing this
69 * pointer. */
70 } FileEvent;
71
72 /*
73 * Static routines for this file:
74 */
75
76 static int FileBlockProc _ANSI_ARGS_((ClientData instanceData,
77 int mode));
78 static void FileChannelExitHandler _ANSI_ARGS_((
79 ClientData clientData));
80 static void FileCheckProc _ANSI_ARGS_((ClientData clientData,
81 int flags));
82 static int FileCloseProc _ANSI_ARGS_((ClientData instanceData,
83 Tcl_Interp *interp));
84 static int FileEventProc _ANSI_ARGS_((Tcl_Event *evPtr,
85 int flags));
86 static int FileGetHandleProc _ANSI_ARGS_((ClientData instanceData,
87 int direction, ClientData *handlePtr));
88 static ThreadSpecificData *FileInit _ANSI_ARGS_((void));
89 static int FileInputProc _ANSI_ARGS_((ClientData instanceData,
90 char *buf, int toRead, int *errorCode));
91 static int FileOutputProc _ANSI_ARGS_((ClientData instanceData,
92 CONST char *buf, int toWrite, int *errorCode));
93 static int FileSeekProc _ANSI_ARGS_((ClientData instanceData,
94 long offset, int mode, int *errorCode));
95 static Tcl_WideInt FileWideSeekProc _ANSI_ARGS_((ClientData instanceData,
96 Tcl_WideInt offset, int mode, int *errorCode));
97 static void FileSetupProc _ANSI_ARGS_((ClientData clientData,
98 int flags));
99 static void FileWatchProc _ANSI_ARGS_((ClientData instanceData,
100 int mask));
101
102
103 /*
104 * This structure describes the channel type structure for file based IO.
105 */
106
107 static Tcl_ChannelType fileChannelType = {
108 "file", /* Type name. */
109 TCL_CHANNEL_VERSION_3, /* v3 channel */
110 FileCloseProc, /* Close proc. */
111 FileInputProc, /* Input proc. */
112 FileOutputProc, /* Output proc. */
113 FileSeekProc, /* Seek proc. */
114 NULL, /* Set option proc. */
115 NULL, /* Get option proc. */
116 FileWatchProc, /* Set up the notifier to watch the channel. */
117 FileGetHandleProc, /* Get an OS handle from channel. */
118 NULL, /* close2proc. */
119 FileBlockProc, /* Set blocking or non-blocking mode.*/
120 NULL, /* flush proc. */
121 NULL, /* handler proc. */
122 FileWideSeekProc, /* Wide seek proc. */
123 };
124
125 #if defined(HAVE_NO_SEH) && defined(TCL_MEM_DEBUG)
126 static void *INITIAL_ESP,
127 *INITIAL_EBP,
128 *INITIAL_HANDLER,
129 *RESTORED_ESP,
130 *RESTORED_EBP,
131 *RESTORED_HANDLER;
132 #endif /* HAVE_NO_SEH && TCL_MEM_DEBUG */
133
134
135 /*
136 *----------------------------------------------------------------------
137 *
138 * FileInit --
139 *
140 * This function creates the window used to simulate file events.
141 *
142 * Results:
143 * None.
144 *
145 * Side effects:
146 * Creates a new window and creates an exit handler.
147 *
148 *----------------------------------------------------------------------
149 */
150
151 static ThreadSpecificData *
152 FileInit()
153 {
154 ThreadSpecificData *tsdPtr =
155 (ThreadSpecificData *)TclThreadDataKeyGet(&dataKey);
156 if (tsdPtr == NULL) {
157 tsdPtr = TCL_TSD_INIT(&dataKey);
158 tsdPtr->firstFilePtr = NULL;
159 Tcl_CreateEventSource(FileSetupProc, FileCheckProc, NULL);
160 Tcl_CreateThreadExitHandler(FileChannelExitHandler, NULL);
161 }
162 return tsdPtr;
163 }
164
165 /*
166 *----------------------------------------------------------------------
167 *
168 * FileChannelExitHandler --
169 *
170 * This function is called to cleanup the channel driver before
171 * Tcl is unloaded.
172 *
173 * Results:
174 * None.
175 *
176 * Side effects:
177 * Destroys the communication window.
178 *
179 *----------------------------------------------------------------------
180 */
181
182 static void
183 FileChannelExitHandler(clientData)
184 ClientData clientData; /* Old window proc */
185 {
186 Tcl_DeleteEventSource(FileSetupProc, FileCheckProc, NULL);
187 }
188
189 /*
190 *----------------------------------------------------------------------
191 *
192 * FileSetupProc --
193 *
194 * This procedure is invoked before Tcl_DoOneEvent blocks waiting
195 * for an event.
196 *
197 * Results:
198 * None.
199 *
200 * Side effects:
201 * Adjusts the block time if needed.
202 *
203 *----------------------------------------------------------------------
204 */
205
206 void
207 FileSetupProc(data, flags)
208 ClientData data; /* Not used. */
209 int flags; /* Event flags as passed to Tcl_DoOneEvent. */
210 {
211 FileInfo *infoPtr;
212 Tcl_Time blockTime = { 0, 0 };
213 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
214
215 if (!(flags & TCL_FILE_EVENTS)) {
216 return;
217 }
218
219 /*
220 * Check to see if there is a ready file. If so, poll.
221 */
222
223 for (infoPtr = tsdPtr->firstFilePtr; infoPtr != NULL;
224 infoPtr = infoPtr->nextPtr) {
225 if (infoPtr->watchMask) {
226 Tcl_SetMaxBlockTime(&blockTime);
227 break;
228 }
229 }
230 }
231
232 /*
233 *----------------------------------------------------------------------
234 *
235 * FileCheckProc --
236 *
237 * This procedure is called by Tcl_DoOneEvent to check the file
238 * event source for events.
239 *
240 * Results:
241 * None.
242 *
243 * Side effects:
244 * May queue an event.
245 *
246 *----------------------------------------------------------------------
247 */
248
249 static void
250 FileCheckProc(data, flags)
251 ClientData data; /* Not used. */
252 int flags; /* Event flags as passed to Tcl_DoOneEvent. */
253 {
254 FileEvent *evPtr;
255 FileInfo *infoPtr;
256 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
257
258 if (!(flags & TCL_FILE_EVENTS)) {
259 return;
260 }
261
262 /*
263 * Queue events for any ready files that don't already have events
264 * queued (caused by persistent states that won't generate WinSock
265 * events).
266 */
267
268 for (infoPtr = tsdPtr->firstFilePtr; infoPtr != NULL;
269 infoPtr = infoPtr->nextPtr) {
270 if (infoPtr->watchMask && !(infoPtr->flags & FILE_PENDING)) {
271 infoPtr->flags |= FILE_PENDING;
272 evPtr = (FileEvent *) ckalloc(sizeof(FileEvent));
273 evPtr->header.proc = FileEventProc;
274 evPtr->infoPtr = infoPtr;
275 Tcl_QueueEvent((Tcl_Event *) evPtr, TCL_QUEUE_TAIL);
276 }
277 }
278 }
279
280 /*----------------------------------------------------------------------
281 *
282 * FileEventProc --
283 *
284 * This function is invoked by Tcl_ServiceEvent when a file event
285 * reaches the front of the event queue. This procedure invokes
286 * Tcl_NotifyChannel on the file.
287 *
288 * Results:
289 * Returns 1 if the event was handled, meaning it should be removed
290 * from the queue. Returns 0 if the event was not handled, meaning
291 * it should stay on the queue. The only time the event isn't
292 * handled is if the TCL_FILE_EVENTS flag bit isn't set.
293 *
294 * Side effects:
295 * Whatever the notifier callback does.
296 *
297 *----------------------------------------------------------------------
298 */
299
300 static int
301 FileEventProc(evPtr, flags)
302 Tcl_Event *evPtr; /* Event to service. */
303 int flags; /* Flags that indicate what events to
304 * handle, such as TCL_FILE_EVENTS. */
305 {
306 FileEvent *fileEvPtr = (FileEvent *)evPtr;
307 FileInfo *infoPtr;
308 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
309
310 if (!(flags & TCL_FILE_EVENTS)) {
311 return 0;
312 }
313
314 /*
315 * Search through the list of watched files for the one whose handle
316 * matches the event. We do this rather than simply dereferencing
317 * the handle in the event so that files can be deleted while the
318 * event is in the queue.
319 */
320
321 for (infoPtr = tsdPtr->firstFilePtr; infoPtr != NULL;
322 infoPtr = infoPtr->nextPtr) {
323 if (fileEvPtr->infoPtr == infoPtr) {
324 infoPtr->flags &= ~(FILE_PENDING);
325 Tcl_NotifyChannel(infoPtr->channel, infoPtr->watchMask);
326 break;
327 }
328 }
329 return 1;
330 }
331
332 /*
333 *----------------------------------------------------------------------
334 *
335 * FileBlockProc --
336 *
337 * Set blocking or non-blocking mode on channel.
338 *
339 * Results:
340 * 0 if successful, errno when failed.
341 *
342 * Side effects:
343 * Sets the device into blocking or non-blocking mode.
344 *
345 *----------------------------------------------------------------------
346 */
347
348 static int
349 FileBlockProc(instanceData, mode)
350 ClientData instanceData; /* Instance data for channel. */
351 int mode; /* TCL_MODE_BLOCKING or
352 * TCL_MODE_NONBLOCKING. */
353 {
354 FileInfo *infoPtr = (FileInfo *) instanceData;
355
356 /*
357 * Files on Windows can not be switched between blocking and nonblocking,
358 * hence we have to emulate the behavior. This is done in the input
359 * function by checking against a bit in the state. We set or unset the
360 * bit here to cause the input function to emulate the correct behavior.
361 */
362
363 if (mode == TCL_MODE_NONBLOCKING) {
364 infoPtr->flags |= FILE_ASYNC;
365 } else {
366 infoPtr->flags &= ~(FILE_ASYNC);
367 }
368 return 0;
369 }
370
371 /*
372 *----------------------------------------------------------------------
373 *
374 * FileCloseProc --
375 *
376 * Closes the IO channel.
377 *
378 * Results:
379 * 0 if successful, the value of errno if failed.
380 *
381 * Side effects:
382 * Closes the physical channel
383 *
384 *----------------------------------------------------------------------
385 */
386
387 static int
388 FileCloseProc(instanceData, interp)
389 ClientData instanceData; /* Pointer to FileInfo structure. */
390 Tcl_Interp *interp; /* Not used. */
391 {
392 FileInfo *fileInfoPtr = (FileInfo *) instanceData;
393 int errorCode = 0;
394
395 /*
396 * Remove the file from the watch list.
397 */
398
399 FileWatchProc(instanceData, 0);
400
401 /*
402 * Don't close the Win32 handle if the handle is a standard channel
403 * during the thread exit process. Otherwise, one thread may kill
404 * the stdio of another.
405 */
406
407 if (!TclInThreadExit()
408 || ((GetStdHandle(STD_INPUT_HANDLE) != fileInfoPtr->handle)
409 && (GetStdHandle(STD_OUTPUT_HANDLE) != fileInfoPtr->handle)
410 && (GetStdHandle(STD_ERROR_HANDLE) != fileInfoPtr->handle))) {
411 if (CloseHandle(fileInfoPtr->handle) == FALSE) {
412 TclWinConvertError(GetLastError());
413 errorCode = errno;
414 }
415 }
416
417 ckfree((char *)fileInfoPtr);
418 return errorCode;
419 }
420
421 /*
422 *----------------------------------------------------------------------
423 *
424 * FileSeekProc --
425 *
426 * Seeks on a file-based channel. Returns the new position.
427 *
428 * Results:
429 * -1 if failed, the new position if successful. If failed, it
430 * also sets *errorCodePtr to the error code.
431 *
432 * Side effects:
433 * Moves the location at which the channel will be accessed in
434 * future operations.
435 *
436 *----------------------------------------------------------------------
437 */
438
439 static int
440 FileSeekProc(instanceData, offset, mode, errorCodePtr)
441 ClientData instanceData; /* File state. */
442 long offset; /* Offset to seek to. */
443 int mode; /* Relative to where should we seek? */
444 int *errorCodePtr; /* To store error code. */
445 {
446 FileInfo *infoPtr = (FileInfo *) instanceData;
447 DWORD moveMethod;
448 DWORD newPos, newPosHigh;
449 DWORD oldPos, oldPosHigh;
450
451 *errorCodePtr = 0;
452 if (mode == SEEK_SET) {
453 moveMethod = FILE_BEGIN;
454 } else if (mode == SEEK_CUR) {
455 moveMethod = FILE_CURRENT;
456 } else {
457 moveMethod = FILE_END;
458 }
459
460 /*
461 * Save our current place in case we need to roll-back the seek.
462 */
463 oldPosHigh = (DWORD)0;
464 oldPos = SetFilePointer(infoPtr->handle, (LONG)0, &oldPosHigh,
465 FILE_CURRENT);
466 if (oldPos == INVALID_SET_FILE_POINTER) {
467 DWORD winError = GetLastError();
468 if (winError != NO_ERROR) {
469 TclWinConvertError(winError);
470 *errorCodePtr = errno;
471 return -1;
472 }
473 }
474
475 newPosHigh = (DWORD)(offset < 0 ? -1 : 0);
476 newPos = SetFilePointer(infoPtr->handle, (LONG) offset, &newPosHigh,
477 moveMethod);
478 if (newPos == INVALID_SET_FILE_POINTER) {
479 DWORD winError = GetLastError();
480 if (winError != NO_ERROR) {
481 TclWinConvertError(winError);
482 *errorCodePtr = errno;
483 return -1;
484 }
485 }
486
487 /*
488 * Check for expressability in our return type, and roll-back otherwise.
489 */
490 if (newPosHigh != 0) {
491 *errorCodePtr = EOVERFLOW;
492 SetFilePointer(infoPtr->handle, (LONG)oldPos, &oldPosHigh, FILE_BEGIN);
493 return -1;
494 }
495 return (int) newPos;
496 }
497
498 /*
499 *----------------------------------------------------------------------
500 *
501 * FileWideSeekProc --
502 *
503 * Seeks on a file-based channel. Returns the new position.
504 *
505 * Results:
506 * -1 if failed, the new position if successful. If failed, it
507 * also sets *errorCodePtr to the error code.
508 *
509 * Side effects:
510 * Moves the location at which the channel will be accessed in
511 * future operations.
512 *
513 *----------------------------------------------------------------------
514 */
515
516 static Tcl_WideInt
517 FileWideSeekProc(instanceData, offset, mode, errorCodePtr)
518 ClientData instanceData; /* File state. */
519 Tcl_WideInt offset; /* Offset to seek to. */
520 int mode; /* Relative to where should we seek? */
521 int *errorCodePtr; /* To store error code. */
522 {
523 FileInfo *infoPtr = (FileInfo *) instanceData;
524 DWORD moveMethod;
525 DWORD newPos, newPosHigh;
526
527 *errorCodePtr = 0;
528 if (mode == SEEK_SET) {
529 moveMethod = FILE_BEGIN;
530 } else if (mode == SEEK_CUR) {
531 moveMethod = FILE_CURRENT;
532 } else {
533 moveMethod = FILE_END;
534 }
535
536 newPosHigh = (DWORD)(offset >> 32);
537 newPos = SetFilePointer(infoPtr->handle, (LONG) offset, &newPosHigh,
538 moveMethod);
539 if (newPos == INVALID_SET_FILE_POINTER) {
540 DWORD winError = GetLastError();
541 if (winError != NO_ERROR) {
542 TclWinConvertError(winError);
543 *errorCodePtr = errno;
544 return -1;
545 }
546 }
547 return ((Tcl_WideInt) newPos) | (((Tcl_WideInt) newPosHigh) << 32);
548 }
549
550 /*
551 *----------------------------------------------------------------------
552 *
553 * FileInputProc --
554 *
555 * Reads input from the IO channel into the buffer given. Returns
556 * count of how many bytes were actually read, and an error indication.
557 *
558 * Results:
559 * A count of how many bytes were read is returned and an error
560 * indication is returned in an output argument.
561 *
562 * Side effects:
563 * Reads input from the actual channel.
564 *
565 *----------------------------------------------------------------------
566 */
567
568 static int
569 FileInputProc(instanceData, buf, bufSize, errorCode)
570 ClientData instanceData; /* File state. */
571 char *buf; /* Where to store data read. */
572 int bufSize; /* How much space is available
573 * in the buffer? */
574 int *errorCode; /* Where to store error code. */
575 {
576 FileInfo *infoPtr;
577 DWORD bytesRead;
578
579 *errorCode = 0;
580 infoPtr = (FileInfo *) instanceData;
581
582 /*
583 * Note that we will block on reads from a console buffer until a
584 * full line has been entered. The only way I know of to get
585 * around this is to write a console driver. We should probably
586 * do this at some point, but for now, we just block. The same
587 * problem exists for files being read over the network.
588 */
589
590 if (ReadFile(infoPtr->handle, (LPVOID) buf, (DWORD) bufSize, &bytesRead,
591 (LPOVERLAPPED) NULL) != FALSE) {
592 return bytesRead;
593 }
594
595 TclWinConvertError(GetLastError());
596 *errorCode = errno;
597 if (errno == EPIPE) {
598 return 0;
599 }
600 return -1;
601 }
602
603 /*
604 *----------------------------------------------------------------------
605 *
606 * FileOutputProc --
607 *
608 * Writes the given output on the IO channel. Returns count of how
609 * many characters were actually written, and an error indication.
610 *
611 * Results:
612 * A count of how many characters were written is returned and an
613 * error indication is returned in an output argument.
614 *
615 * Side effects:
616 * Writes output on the actual channel.
617 *
618 *----------------------------------------------------------------------
619 */
620
621 static int
622 FileOutputProc(instanceData, buf, toWrite, errorCode)
623 ClientData instanceData; /* File state. */
624 CONST char *buf; /* The data buffer. */
625 int toWrite; /* How many bytes to write? */
626 int *errorCode; /* Where to store error code. */
627 {
628 FileInfo *infoPtr = (FileInfo *) instanceData;
629 DWORD bytesWritten;
630
631 *errorCode = 0;
632
633 /*
634 * If we are writing to a file that was opened with O_APPEND, we need to
635 * seek to the end of the file before writing the current buffer.
636 */
637
638 if (infoPtr->flags & FILE_APPEND) {
639 SetFilePointer(infoPtr->handle, 0, NULL, FILE_END);
640 }
641
642 if (WriteFile(infoPtr->handle, (LPVOID) buf, (DWORD) toWrite, &bytesWritten,
643 (LPOVERLAPPED) NULL) == FALSE) {
644 TclWinConvertError(GetLastError());
645 *errorCode = errno;
646 return -1;
647 }
648 infoPtr->dirty = 1;
649 return bytesWritten;
650 }
651
652 /*
653 *----------------------------------------------------------------------
654 *
655 * FileWatchProc --
656 *
657 * Called by the notifier to set up to watch for events on this
658 * channel.
659 *
660 * Results:
661 * None.
662 *
663 * Side effects:
664 * None.
665 *
666 *----------------------------------------------------------------------
667 */
668
669 static void
670 FileWatchProc(instanceData, mask)
671 ClientData instanceData; /* File state. */
672 int mask; /* What events to watch for; OR-ed
673 * combination of TCL_READABLE,
674 * TCL_WRITABLE and TCL_EXCEPTION. */
675 {
676 FileInfo *infoPtr = (FileInfo *) instanceData;
677 Tcl_Time blockTime = { 0, 0 };
678
679 /*
680 * Since the file is always ready for events, we set the block time
681 * to zero so we will poll.
682 */
683
684 infoPtr->watchMask = mask & infoPtr->validMask;
685 if (infoPtr->watchMask) {
686 Tcl_SetMaxBlockTime(&blockTime);
687 }
688 }
689
690 /*
691 *----------------------------------------------------------------------
692 *
693 * FileGetHandleProc --
694 *
695 * Called from Tcl_GetChannelHandle to retrieve OS handles from
696 * a file based channel.
697 *
698 * Results:
699 * Returns TCL_OK with the fd in handlePtr, or TCL_ERROR if
700 * there is no handle for the specified direction.
701 *
702 * Side effects:
703 * None.
704 *
705 *----------------------------------------------------------------------
706 */
707
708 static int
709 FileGetHandleProc(instanceData, direction, handlePtr)
710 ClientData instanceData; /* The file state. */
711 int direction; /* TCL_READABLE or TCL_WRITABLE */
712 ClientData *handlePtr; /* Where to store the handle. */
713 {
714 FileInfo *infoPtr = (FileInfo *) instanceData;
715
716 if (direction & infoPtr->validMask) {
717 *handlePtr = (ClientData) infoPtr->handle;
718 return TCL_OK;
719 } else {
720 return TCL_ERROR;
721 }
722 }
723
724
725 /*
726 *----------------------------------------------------------------------
727 *
728 * TclpOpenFileChannel --
729 *
730 * Open an File based channel on Unix systems.
731 *
732 * Results:
733 * The new channel or NULL. If NULL, the output argument
734 * errorCodePtr is set to a POSIX error.
735 *
736 * Side effects:
737 * May open the channel and may cause creation of a file on the
738 * file system.
739 *
740 *----------------------------------------------------------------------
741 */
742
743 Tcl_Channel
744 TclpOpenFileChannel(interp, pathPtr, mode, permissions)
745 Tcl_Interp *interp; /* Interpreter for error reporting;
746 * can be NULL. */
747 Tcl_Obj *pathPtr; /* Name of file to open. */
748 int mode; /* POSIX mode. */
749 int permissions; /* If the open involves creating a
750 * file, with what modes to create
751 * it? */
752 {
753 Tcl_Channel channel = 0;
754 int channelPermissions;
755 DWORD accessMode, createMode, shareMode, flags, consoleParams, type;
756 CONST TCHAR *nativeName;
757 DCB dcb;
758 HANDLE handle;
759 char channelName[16 + TCL_INTEGER_SPACE];
760 TclFile readFile = NULL;
761 TclFile writeFile = NULL;
762
763 nativeName = (TCHAR*) Tcl_FSGetNativePath(pathPtr);
764 if (nativeName == NULL) {
765 return NULL;
766 }
767
768 switch (mode & (O_RDONLY | O_WRONLY | O_RDWR)) {
769 case O_RDONLY:
770 accessMode = GENERIC_READ;
771 channelPermissions = TCL_READABLE;
772 break;
773 case O_WRONLY:
774 accessMode = GENERIC_WRITE;
775 channelPermissions = TCL_WRITABLE;
776 break;
777 case O_RDWR:
778 accessMode = (GENERIC_READ | GENERIC_WRITE);
779 channelPermissions = (TCL_READABLE | TCL_WRITABLE);
780 break;
781 default:
782 panic("TclpOpenFileChannel: invalid mode value");
783 break;
784 }
785
786 /*
787 * Map the creation flags to the NT create mode.
788 */
789
790 switch (mode & (O_CREAT | O_EXCL | O_TRUNC)) {
791 case (O_CREAT | O_EXCL):
792 case (O_CREAT | O_EXCL | O_TRUNC):
793 createMode = CREATE_NEW;
794 break;
795 case (O_CREAT | O_TRUNC):
796 createMode = CREATE_ALWAYS;
797 break;
798 case O_CREAT:
799 createMode = OPEN_ALWAYS;
800 break;
801 case O_TRUNC:
802 case (O_TRUNC | O_EXCL):
803 createMode = TRUNCATE_EXISTING;
804 break;
805 default:
806 createMode = OPEN_EXISTING;
807 break;
808 }
809
810 /*
811 * If the file is being created, get the file attributes from the
812 * permissions argument, else use the existing file attributes.
813 */
814
815 if (mode & O_CREAT) {
816 if (permissions & S_IWRITE) {
817 flags = FILE_ATTRIBUTE_NORMAL;
818 } else {
819 flags = FILE_ATTRIBUTE_READONLY;
820 }
821 } else {
822 flags = (*tclWinProcs->getFileAttributesProc)(nativeName);
823 if (flags == 0xFFFFFFFF) {
824 flags = 0;
825 }
826 }
827
828 /*
829 * Set up the file sharing mode. We want to allow simultaneous access.
830 */
831
832 shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
833
834 /*
835 * Now we get to create the file.
836 */
837
838 handle = (*tclWinProcs->createFileProc)(nativeName, accessMode,
839 shareMode, NULL, createMode, flags, (HANDLE) NULL);
840
841 if (handle == INVALID_HANDLE_VALUE) {
842 DWORD err;
843 err = GetLastError();
844 if ((err & 0xffffL) == ERROR_OPEN_FAILED) {
845 err = (mode & O_CREAT) ? ERROR_FILE_EXISTS : ERROR_FILE_NOT_FOUND;
846 }
847 TclWinConvertError(err);
848 if (interp != (Tcl_Interp *) NULL) {
849 Tcl_AppendResult(interp, "couldn't open \"",
850 Tcl_GetString(pathPtr), "\": ",
851 Tcl_PosixError(interp), (char *) NULL);
852 }
853 return NULL;
854 }
855
856 type = GetFileType(handle);
857
858 /*
859 * If the file is a character device, we need to try to figure out
860 * whether it is a serial port, a console, or something else. We
861 * test for the console case first because this is more common.
862 */
863
864 if (type == FILE_TYPE_CHAR) {
865 if (GetConsoleMode(handle, &consoleParams)) {
866 type = FILE_TYPE_CONSOLE;
867 } else {
868 dcb.DCBlength = sizeof( DCB ) ;
869 if (GetCommState(handle, &dcb)) {
870 type = FILE_TYPE_SERIAL;
871 }
872
873 }
874 }
875
876 channel = NULL;
877
878 switch (type) {
879 case FILE_TYPE_SERIAL:
880 /*
881 * Reopen channel for OVERLAPPED operation
882 * Normally this shouldn't fail, because the channel exists
883 */
884 handle = TclWinSerialReopen(handle, nativeName, accessMode);
885 if (handle == INVALID_HANDLE_VALUE) {
886 TclWinConvertError(GetLastError());
887 if (interp != (Tcl_Interp *) NULL) {
888 Tcl_AppendResult(interp, "couldn't reopen serial \"",
889 Tcl_GetString(pathPtr), "\": ",
890 Tcl_PosixError(interp), (char *) NULL);
891 }
892 return NULL;
893 }
894 channel = TclWinOpenSerialChannel(handle, channelName,
895 channelPermissions);
896 break;
897 case FILE_TYPE_CONSOLE:
898 channel = TclWinOpenConsoleChannel(handle, channelName,
899 channelPermissions);
900 break;
901 case FILE_TYPE_PIPE:
902 if (channelPermissions & TCL_READABLE) {
903 readFile = TclWinMakeFile(handle);
904 }
905 if (channelPermissions & TCL_WRITABLE) {
906 writeFile = TclWinMakeFile(handle);
907 }
908 channel = TclpCreateCommandChannel(readFile, writeFile, NULL, 0, NULL);
909 break;
910 case FILE_TYPE_CHAR:
911 case FILE_TYPE_DISK:
912 case FILE_TYPE_UNKNOWN:
913 channel = TclWinOpenFileChannel(handle, channelName,
914 channelPermissions,
915 (mode & O_APPEND) ? FILE_APPEND : 0);
916 break;
917
918 default:
919 /*
920 * The handle is of an unknown type, probably /dev/nul equivalent
921 * or possibly a closed handle.
922 */
923
924 channel = NULL;
925 Tcl_AppendResult(interp, "couldn't open \"",
926 Tcl_GetString(pathPtr), "\": ",
927 "bad file type", (char *) NULL);
928 break;
929 }
930
931 return channel;
932 }
933
934 /*
935 *----------------------------------------------------------------------
936 *
937 * Tcl_MakeFileChannel --
938 *
939 * Creates a Tcl_Channel from an existing platform specific file
940 * handle.
941 *
942 * Results:
943 * The Tcl_Channel created around the preexisting file.
944 *
945 * Side effects:
946 * None.
947 *
948 *----------------------------------------------------------------------
949 */
950
951 Tcl_Channel
952 Tcl_MakeFileChannel(rawHandle, mode)
953 ClientData rawHandle; /* OS level handle */
954 int mode; /* ORed combination of TCL_READABLE and
955 * TCL_WRITABLE to indicate file mode. */
956 {
957 char channelName[16 + TCL_INTEGER_SPACE];
958 Tcl_Channel channel = NULL;
959 HANDLE handle = (HANDLE) rawHandle;
960 HANDLE dupedHandle;
961 DCB dcb;
962 DWORD consoleParams, type;
963 TclFile readFile = NULL;
964 TclFile writeFile = NULL;
965 BOOL result;
966
967 if (mode == 0) {
968 return NULL;
969 }
970
971 /*
972 * GetFileType() returns FILE_TYPE_UNKNOWN for invalid handles.
973 */
974
975 type = GetFileType(handle);
976
977 /*
978 * If the file is a character device, we need to try to figure out
979 * whether it is a serial port, a console, or something else. We
980 * test for the console case first because this is more common.
981 */
982
983 if (type == FILE_TYPE_CHAR) {
984 if (GetConsoleMode(handle, &consoleParams)) {
985 type = FILE_TYPE_CONSOLE;
986 } else {
987 dcb.DCBlength = sizeof( DCB ) ;
988 if (GetCommState(handle, &dcb)) {
989 type = FILE_TYPE_SERIAL;
990 }
991 }
992 }
993
994 switch (type)
995 {
996 case FILE_TYPE_SERIAL:
997 channel = TclWinOpenSerialChannel(handle, channelName, mode);
998 break;
999 case FILE_TYPE_CONSOLE:
1000 channel = TclWinOpenConsoleChannel(handle, channelName, mode);
1001 break;
1002 case FILE_TYPE_PIPE:
1003 if (mode & TCL_READABLE)
1004 {
1005 readFile = TclWinMakeFile(handle);
1006 }
1007 if (mode & TCL_WRITABLE)
1008 {
1009 writeFile = TclWinMakeFile(handle);
1010 }
1011 channel = TclpCreateCommandChannel(readFile, writeFile, NULL, 0, NULL);
1012 break;
1013
1014 case FILE_TYPE_DISK:
1015 case FILE_TYPE_CHAR:
1016 channel = TclWinOpenFileChannel(handle, channelName, mode, 0);
1017 break;
1018
1019 case FILE_TYPE_UNKNOWN:
1020 default:
1021 /*
1022 * The handle is of an unknown type. Test the validity of this OS
1023 * handle by duplicating it, then closing the dupe. The Win32 API
1024 * doesn't provide an IsValidHandle() function, so we have to emulate
1025 * it here. This test will not work on a console handle reliably,
1026 * which is why we can't test every handle that comes into this
1027 * function in this way.
1028 */
1029
1030 result = DuplicateHandle(GetCurrentProcess(), handle,
1031 GetCurrentProcess(), &dupedHandle, 0, FALSE,
1032 DUPLICATE_SAME_ACCESS);
1033
1034 if (result == 0) {
1035 /*
1036 * Unable to make a duplicate. It's definately invalid at this
1037 * point.
1038 */
1039
1040 return NULL;
1041 }
1042
1043 /*
1044 * Use structured exception handling (Win32 SEH) to protect the close
1045 * of this duped handle which might throw EXCEPTION_INVALID_HANDLE.
1046 */
1047
1048 #ifdef HAVE_NO_SEH
1049 # ifdef TCL_MEM_DEBUG
1050 __asm__ __volatile__ (
1051 "movl %%esp, %0" "\n\t"
1052 "movl %%ebp, %1" "\n\t"
1053 "movl %%fs:0, %2" "\n\t"
1054 : "=m"(INITIAL_ESP),
1055 "=m"(INITIAL_EBP),
1056 "=r"(INITIAL_HANDLER) );
1057 # endif /* TCL_MEM_DEBUG */
1058
1059 result = 0;
1060
1061 __asm__ __volatile__ (
1062 "pushl %ebp" "\n\t"
1063 "pushl $__except_makefilechannel_handler" "\n\t"
1064 "pushl %fs:0" "\n\t"
1065 "movl %esp, %fs:0");
1066 #else
1067 __try {
1068 #endif /* HAVE_NO_SEH */
1069 CloseHandle(dupedHandle);
1070 #ifdef HAVE_NO_SEH
1071 __asm__ __volatile__ (
1072 "jmp makefilechannel_pop" "\n"
1073 "makefilechannel_reentry:" "\n\t"
1074 "movl %%fs:0, %%eax" "\n\t"
1075 "movl 0x8(%%eax), %%esp" "\n\t"
1076 "movl 0x8(%%esp), %%ebp" "\n"
1077 "movl $1, %0" "\n"
1078 "makefilechannel_pop:" "\n\t"
1079 "movl (%%esp), %%eax" "\n\t"
1080 "movl %%eax, %%fs:0" "\n\t"
1081 "add $12, %%esp" "\n\t"
1082 : "=m"(result)
1083 :
1084 : "%eax");
1085
1086 # ifdef TCL_MEM_DEBUG
1087 __asm__ __volatile__ (
1088 "movl %%esp, %0" "\n\t"
1089 "movl %%ebp, %1" "\n\t"
1090 "movl %%fs:0, %2" "\n\t"
1091 : "=m"(RESTORED_ESP),
1092 "=m"(RESTORED_EBP),
1093 "=r"(RESTORED_HANDLER) );
1094
1095 if (INITIAL_ESP != RESTORED_ESP)
1096 panic("ESP restored incorrectly");
1097 if (INITIAL_EBP != RESTORED_EBP)
1098 panic("EBP restored incorrectly");
1099 if (INITIAL_HANDLER != RESTORED_HANDLER)
1100 panic("HANDLER restored incorrectly");
1101 # endif /* TCL_MEM_DEBUG */
1102
1103 if (result)
1104 return NULL;
1105 #else
1106 }
1107 __except (EXCEPTION_EXECUTE_HANDLER) {
1108 /*
1109 * Definately an invalid handle. So, therefore, the original
1110 * is invalid also.
1111 */
1112
1113 return NULL;
1114 }
1115 #endif /* HAVE_NO_SEH */
1116
1117 /* Fall through, the handle is valid. */
1118
1119 /*
1120 * Create the undefined channel, anyways, because we know the handle
1121 * is valid to something.
1122 */
1123
1124 channel = TclWinOpenFileChannel(handle, channelName, mode, 0);
1125 }
1126
1127 return channel;
1128 }
1129 #ifdef HAVE_NO_SEH
1130 static
1131 __attribute__ ((cdecl))
1132 EXCEPTION_DISPOSITION
1133 _except_makefilechannel_handler(
1134 struct _EXCEPTION_RECORD *ExceptionRecord,
1135 void *EstablisherFrame,
1136 struct _CONTEXT *ContextRecord,
1137 void *DispatcherContext)
1138 {
1139 __asm__ __volatile__ (
1140 "jmp makefilechannel_reentry");
1141 /* Nuke compiler warning about unused static function */
1142 _except_makefilechannel_handler(NULL, NULL, NULL, NULL);
1143 return 0; /* Function does not return */
1144 }
1145 #endif
1146
1147 /*
1148 *----------------------------------------------------------------------
1149 *
1150 * TclpGetDefaultStdChannel --
1151 *
1152 * Constructs a channel for the specified standard OS handle.
1153 *
1154 * Results:
1155 * Returns the specified default standard channel, or NULL.
1156 *
1157 * Side effects:
1158 * May cause the creation of a standard channel and the underlying
1159 * file.
1160 *
1161 *----------------------------------------------------------------------
1162 */
1163
1164 Tcl_Channel
1165 TclpGetDefaultStdChannel(type)
1166 int type; /* One of TCL_STDIN, TCL_STDOUT, TCL_STDERR. */
1167 {
1168 Tcl_Channel channel;
1169 HANDLE handle;
1170 int mode;
1171 char *bufMode;
1172 DWORD handleId; /* Standard handle to retrieve. */
1173
1174
1175 switch (type) {
1176 case TCL_STDIN:
1177 handleId = STD_INPUT_HANDLE;
1178 mode = TCL_READABLE;
1179 bufMode = "line";
1180 break;
1181 case TCL_STDOUT:
1182 handleId = STD_OUTPUT_HANDLE;
1183 mode = TCL_WRITABLE;
1184 bufMode = "line";
1185 break;
1186 case TCL_STDERR:
1187 handleId = STD_ERROR_HANDLE;
1188 mode = TCL_WRITABLE;
1189 bufMode = "none";
1190 break;
1191 default:
1192 panic("TclGetDefaultStdChannel: Unexpected channel type");
1193 break;
1194 }
1195
1196 handle = GetStdHandle(handleId);
1197
1198 /*
1199 * Note that we need to check for 0 because Windows may return 0 if this
1200 * is not a console mode application, even though this is not a valid
1201 * handle.
1202 */
1203
1204 if ((handle == INVALID_HANDLE_VALUE) || (handle == 0)) {
1205 return (Tcl_Channel) NULL;
1206 }
1207
1208 channel = Tcl_MakeFileChannel(handle, mode);
1209
1210 if (channel == NULL) {
1211 return (Tcl_Channel) NULL;
1212 }
1213
1214 /*
1215 * Set up the normal channel options for stdio handles.
1216 */
1217
1218 if ((Tcl_SetChannelOption((Tcl_Interp *) NULL, channel, "-translation",
1219 "auto") == TCL_ERROR)
1220 || (Tcl_SetChannelOption((Tcl_Interp *) NULL, channel, "-eofchar",
1221 "\032 {}") == TCL_ERROR)
1222 || (Tcl_SetChannelOption((Tcl_Interp *) NULL, channel,
1223 "-buffering", bufMode) == TCL_ERROR)) {
1224 Tcl_Close((Tcl_Interp *) NULL, channel);
1225 return (Tcl_Channel) NULL;
1226 }
1227 return channel;
1228 }
1229
1230
1231
1232 /*
1233 *----------------------------------------------------------------------
1234 *
1235 * TclWinOpenFileChannel --
1236 *
1237 * Constructs a File channel for the specified standard OS handle.
1238 * This is a helper function to break up the construction of
1239 * channels into File, Console, or Serial.
1240 *
1241 * Results:
1242 * Returns the new channel, or NULL.
1243 *
1244 * Side effects:
1245 * May open the channel and may cause creation of a file on the
1246 * file system.
1247 *
1248 *----------------------------------------------------------------------
1249 */
1250
1251 Tcl_Channel
1252 TclWinOpenFileChannel(handle, channelName, permissions, appendMode)
1253 HANDLE handle;
1254 char *channelName;
1255 int permissions;
1256 int appendMode;
1257 {
1258 FileInfo *infoPtr;
1259 ThreadSpecificData *tsdPtr;
1260
1261 tsdPtr = FileInit();
1262
1263 /*
1264 * See if a channel with this handle already exists.
1265 */
1266
1267 for (infoPtr = tsdPtr->firstFilePtr; infoPtr != NULL;
1268 infoPtr = infoPtr->nextPtr) {
1269 if (infoPtr->handle == (HANDLE) handle) {
1270 return (permissions == infoPtr->validMask) ? infoPtr->channel : NULL;
1271 }
1272 }
1273
1274 infoPtr = (FileInfo *) ckalloc((unsigned) sizeof(FileInfo));
1275 infoPtr->nextPtr = tsdPtr->firstFilePtr;
1276 tsdPtr->firstFilePtr = infoPtr;
1277 infoPtr->validMask = permissions;
1278 infoPtr->watchMask = 0;
1279 infoPtr->flags = appendMode;
1280 infoPtr->handle = handle;
1281 infoPtr->dirty = 0;
1282 wsprintfA(channelName, "file%lx", (int) infoPtr);
1283
1284 infoPtr->channel = Tcl_CreateChannel(&fileChannelType, channelName,
1285 (ClientData) infoPtr, permissions);
1286
1287 /*
1288 * Files have default translation of AUTO and ^Z eof char, which
1289 * means that a ^Z will be accepted as EOF when reading.
1290 */
1291
1292 Tcl_SetChannelOption(NULL, infoPtr->channel, "-translation", "auto");
1293 Tcl_SetChannelOption(NULL, infoPtr->channel, "-eofchar", "\032 {}");
1294
1295 return infoPtr->channel;
1296 }
1297
1298
1299 /*
1300 *----------------------------------------------------------------------
1301 *
1302 * TclWinFlushDirtyChannels --
1303 *
1304 * Flush all dirty channels to disk, so that requesting the
1305 * size of any file returns the correct value.
1306 *
1307 * Results:
1308 * None.
1309 *
1310 * Side effects:
1311 * Information is actually written to disk now, rather than
1312 * later. Don't call this too often, or there will be a
1313 * performance hit (i.e. only call when we need to ask for
1314 * the size of a file).
1315 *
1316 *----------------------------------------------------------------------
1317 */
1318
1319 void
1320 TclWinFlushDirtyChannels ()
1321 {
1322 FileInfo *infoPtr;
1323 ThreadSpecificData *tsdPtr;
1324
1325 tsdPtr = FileInit();
1326
1327 /*
1328 * Flush all channels which are dirty, i.e. may have data pending
1329 * in the OS
1330 */
1331
1332 for (infoPtr = tsdPtr->firstFilePtr;
1333 infoPtr != NULL;
1334 infoPtr = infoPtr->nextPtr) {
1335 if (infoPtr->dirty) {
1336 FlushFileBuffers(infoPtr->handle);
1337 infoPtr->dirty = 0;
1338 }
1339 }
1340 }
1341
1342 /*
1343 *----------------------------------------------------------------------
1344 *
1345 * TclpCutFileChannel --
1346 *
1347 * Remove any thread local refs to this channel. See
1348 * Tcl_CutChannel for more info.
1349 *
1350 * Results:
1351 * None.
1352 *
1353 * Side effects:
1354 * Changes thread local list of valid channels.
1355 *
1356 *----------------------------------------------------------------------
1357 */
1358
1359 void
1360 TclpCutFileChannel(chan)
1361 Tcl_Channel chan; /* The channel being removed. Must
1362 * not be referenced in any
1363 * interpreter. */
1364 {
1365 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
1366 Channel *chanPtr = (Channel *) chan;
1367 FileInfo *infoPtr;
1368 FileInfo **nextPtrPtr;
1369 int removed = 0;
1370
1371 if (chanPtr->typePtr != &fileChannelType)
1372 return;
1373
1374 infoPtr = (FileInfo *) chanPtr->instanceData;
1375
1376 for (nextPtrPtr = &(tsdPtr->firstFilePtr); (*nextPtrPtr) != NULL;
1377 nextPtrPtr = &((*nextPtrPtr)->nextPtr)) {
1378 if ((*nextPtrPtr) == infoPtr) {
1379 (*nextPtrPtr) = infoPtr->nextPtr;
1380 removed = 1;
1381 break;
1382 }
1383 }
1384
1385 /*
1386 * This could happen if the channel was created in one thread
1387 * and then moved to another without updating the thread
1388 * local data in each thread.
1389 */
1390
1391 if (!removed)
1392 panic("file info ptr not on thread channel list");
1393
1394 }
1395
1396 /*
1397 *----------------------------------------------------------------------
1398 *
1399 * TclpSpliceFileChannel --
1400 *
1401 * Insert thread local ref for this channel.
1402 * Tcl_SpliceChannel for more info.
1403 *
1404 * Results:
1405 * None.
1406 *
1407 * Side effects:
1408 * Changes thread local list of valid channels.
1409 *
1410 *----------------------------------------------------------------------
1411 */
1412
1413 void
1414 TclpSpliceFileChannel(chan)
1415 Tcl_Channel chan; /* The channel being removed. Must
1416 * not be referenced in any
1417 * interpreter. */
1418 {
1419 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
1420 Channel *chanPtr = (Channel *) chan;
1421 FileInfo *infoPtr;
1422
1423 if (chanPtr->typePtr != &fileChannelType)
1424 return;
1425
1426 infoPtr = (FileInfo *) chanPtr->instanceData;
1427
1428 infoPtr->nextPtr = tsdPtr->firstFilePtr;
1429 tsdPtr->firstFilePtr = infoPtr;
1430 }