1 /* exp_poll.c - This file contains UNIX specific procedures for
2  * poll-based notifier, which is the lowest-level part of the Tcl
3  * event loop.  This file works together with ../generic/tclNotify.c.
4  *
5  * Design and implementation of this program was paid for by U.S. tax
6  * dollars.  Therefore it is public domain.  However, the author and
7  * NIST would appreciate credit if this program or parts of it are
8  * used.
9  *
10  * Written by Don Libes, NIST, 2/6/90
11  * Rewritten by Don Libes, 2/96 for new Tcl notifier paradigm.
12  * Rewritten again by Don Libes, 8/97 for yet another Tcl notifier paradigm.
13  */
14 
15 #include "tclInt.h"
16 #include "tclPort.h"
17 #include <signal.h>
18 
19 #include <poll.h>
20 #include <sys/types.h>
21 
22 #ifdef HAVE_UNISTD_H
23 #  include <unistd.h>
24 #endif
25 
26 /* Some systems require that the poll array be non-empty so provide a
27  * 1-elt array for starters.  It will be ignored as soon as it grows
28  * larger.
29  */
30 
31 static struct pollfd initialFdArray;
32 static struct pollfd *fdArray = &initialFdArray;
33 static int fdsInUse = 0;	/* space in use */
34 static int fdsMaxSpace = 1;	/* space that has actually been allocated */
35 
36 /*
37  * tclUnixNotify.c --
38  *
39  *	This file contains the implementation of the select-based
40  *	Unix-specific notifier, which is the lowest-level part of the
41  *	Tcl event loop.  This file works together with
42  *	../generic/tclNotify.c.
43  *
44  * Copyright (c) 1995-1997 Sun Microsystems, Inc.
45  *
46  * See the file "license.terms" for information on usage and redistribution
47  * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
48  *
49  * SCCS: @(#) tclUnixNotfy.c 1.42 97/07/02 20:55:44
50  */
51 
52 /*
53  * This structure is used to keep track of the notifier info for a
54  * a registered file.
55  */
56 
57 typedef struct FileHandler {
58     int fd;
59     int mask;			/* Mask of desired events: TCL_READABLE,
60 				 * etc. */
61     int readyMask;		/* Mask of events that have been seen since the
62 				 * last time file handlers were invoked for
63 				 * this file. */
64     Tcl_FileProc *proc;		/* Procedure to call, in the style of
65 				 * Tcl_CreateFileHandler. */
66     ClientData clientData;	/* Argument to pass to proc. */
67     int pollArrayIndex;		/* index into poll array */
68     struct FileHandler *nextPtr;/* Next in list of all files we care about. */
69 } FileHandler;
70 
71 /*
72  * The following structure is what is added to the Tcl event queue when
73  * file handlers are ready to fire.
74  */
75 
76 typedef struct FileHandlerEvent {
77     Tcl_Event header;		/* Information that is standard for
78 				 * all events. */
79     int fd;			/* File descriptor that is ready.  Used
80 				 * to find the FileHandler structure for
81 				 * the file (can't point directly to the
82 				 * FileHandler structure because it could
83 				 * go away while the event is queued). */
84 } FileHandlerEvent;
85 
86 /*
87  * The following static structure contains the state information for the
88  * select based implementation of the Tcl notifier.
89  */
90 
91 static struct {
92     FileHandler *firstFileHandlerPtr;
93 				/* Pointer to head of file handler list. */
94     fd_mask checkMasks[3*MASK_SIZE];
95 				/* This array is used to build up the masks
96 				 * to be used in the next call to select.
97 				 * Bits are set in response to calls to
98 				 * Tcl_CreateFileHandler. */
99     fd_mask readyMasks[3*MASK_SIZE];
100 				/* This array reflects the readable/writable
101 				 * conditions that were found to exist by the
102 				 * last call to select. */
103     int numFdBits;		/* Number of valid bits in checkMasks
104 				 * (one more than highest fd for which
105 				 * Tcl_WatchFile has been called). */
106 } notifier;
107 
108 /*
109  * The following static indicates whether this module has been initialized.
110  */
111 
112 static int initialized = 0;
113 
114 /*
115  * Static routines defined in this file.
116  */
117 
118 static void		InitNotifier _ANSI_ARGS_((void));
119 static void		NotifierExitHandler _ANSI_ARGS_((
120 			    ClientData clientData));
121 static int		FileHandlerEventProc _ANSI_ARGS_((Tcl_Event *evPtr,
122 			    int flags));
123 
124 /*
125  *----------------------------------------------------------------------
126  *
127  * InitNotifier --
128  *
129  *	Initializes the notifier state.
130  *
131  * Results:
132  *	None.
133  *
134  * Side effects:
135  *	Creates a new exit handler.
136  *
137  *----------------------------------------------------------------------
138  */
139 
140 static void
InitNotifier()141 InitNotifier()
142 {
143     initialized = 1;
144     memset(&notifier, 0, sizeof(notifier));
145     Tcl_CreateExitHandler(NotifierExitHandler, NULL);
146 }
147 
148 /*
149  *----------------------------------------------------------------------
150  *
151  * NotifierExitHandler --
152  *
153  *	This function is called to cleanup the notifier state before
154  *	Tcl is unloaded.
155  *
156  * Results:
157  *	None.
158  *
159  * Side effects:
160  *	Destroys the notifier window.
161  *
162  *----------------------------------------------------------------------
163  */
164 
165 static void
NotifierExitHandler(clientData)166 NotifierExitHandler(clientData)
167     ClientData clientData;		/* Not used. */
168 {
169     initialized = 0;
170 }
171 
172 /*
173  *----------------------------------------------------------------------
174  *
175  * Tcl_SetTimer --
176  *
177  *	This procedure sets the current notifier timer value.  This
178  *	interface is not implemented in this notifier because we are
179  *	always running inside of Tcl_DoOneEvent.
180  *
181  * Results:
182  *	None.
183  *
184  * Side effects:
185  *	None.
186  *
187  *----------------------------------------------------------------------
188  */
189 
190 void
Tcl_SetTimer(timePtr)191 Tcl_SetTimer(timePtr)
192     Tcl_Time *timePtr;		/* Timeout value, may be NULL. */
193 {
194     /*
195      * The interval timer doesn't do anything in this implementation,
196      * because the only event loop is via Tcl_DoOneEvent, which passes
197      * timeout values to Tcl_WaitForEvent.
198      */
199 }
200 
201 /*
202  *----------------------------------------------------------------------
203  *
204  * Tcl_CreateFileHandler --
205  *
206  *	This procedure registers a file handler with the Xt notifier.
207  *
208  * Results:
209  *	None.
210  *
211  * Side effects:
212  *	Creates a new file handler structure and registers one or more
213  *	input procedures with Xt.
214  *
215  *----------------------------------------------------------------------
216  */
217 
218 void
Tcl_CreateFileHandler(fd,mask,proc,clientData)219 Tcl_CreateFileHandler(fd, mask, proc, clientData)
220     int fd;			/* Handle of stream to watch. */
221     int mask;			/* OR'ed combination of TCL_READABLE,
222 				 * TCL_WRITABLE, and TCL_EXCEPTION:
223 				 * indicates conditions under which
224 				 * proc should be called. */
225     Tcl_FileProc *proc;		/* Procedure to call for each
226 				 * selected event. */
227     ClientData clientData;	/* Arbitrary data to pass to proc. */
228 {
229     FileHandler *filePtr;
230     int index, bit;
231     int cur_fd_index;
232 
233     if (!initialized) {
234 	InitNotifier();
235     }
236 
237     for (filePtr = notifier.firstFileHandlerPtr; filePtr != NULL;
238 	    filePtr = filePtr->nextPtr) {
239 	if (filePtr->fd == fd) {
240 	    break;
241 	}
242     }
243     if (filePtr == NULL) {
244 	filePtr = (FileHandler*) ckalloc(sizeof(FileHandler)); /* MLK */
245 	filePtr->fd = fd;
246 	filePtr->readyMask = 0;
247 	filePtr->nextPtr = notifier.firstFileHandlerPtr;
248 	notifier.firstFileHandlerPtr = filePtr;
249     }
250     filePtr->proc = proc;
251     filePtr->clientData = clientData;
252     filePtr->pollArrayIndex = fdsInUse;
253     cur_fd_index = fdsInUse;
254 
255     fdsInUse++;
256     if (fdsInUse > fdsMaxSpace) {
257 	if (fdArray != &initialFdArray) ckfree((char *)fdArray);
258 	fdArray = (struct pollfd *)ckalloc(fdsInUse*sizeof(struct pollfd));
259 	fdsMaxSpace = fdsInUse;
260     }
261 
262     fdArray[cur_fd_index].fd = fd;
263 
264     /* I know that POLLIN/OUT is right.  But I have no idea if POLLPRI
265      * corresponds well to TCL_EXCEPTION.
266      */
267 
268     if (mask & TCL_READABLE) {
269         fdArray[cur_fd_index].events = POLLIN;
270     }
271     if (mask & TCL_WRITABLE) {
272         fdArray[cur_fd_index].events = POLLOUT;
273     }
274     if (mask & TCL_EXCEPTION) {
275         fdArray[cur_fd_index].events = POLLPRI;
276     }
277 }
278 
279 /*
280  *----------------------------------------------------------------------
281  *
282  * Tcl_DeleteFileHandler --
283  *
284  *	Cancel a previously-arranged callback arrangement for
285  *	a file.
286  *
287  * Results:
288  *	None.
289  *
290  * Side effects:
291  *	If a callback was previously registered on file, remove it.
292  *
293  *----------------------------------------------------------------------
294  */
295 
296 void
Tcl_DeleteFileHandler(fd)297 Tcl_DeleteFileHandler(fd)
298     int fd;		/* Stream id for which to remove callback procedure. */
299 {
300     FileHandler *filePtr, *prevPtr, *lastPtr;
301     int index, bit, mask, i;
302     int cur_fd_index;
303 
304     if (!initialized) {
305 	InitNotifier();
306     }
307 
308     /*
309      * Find the entry for the given file (and return if there
310      * isn't one).
311      */
312 
313     for (prevPtr = NULL, filePtr = notifier.firstFileHandlerPtr; ;
314 	    prevPtr = filePtr, filePtr = filePtr->nextPtr) {
315 	if (filePtr == NULL) {
316 	    return;
317 	}
318 	if (filePtr->fd == fd) {
319 	    break;
320 	}
321     }
322 
323     /*
324      * Clean up information in the callback record.
325      */
326 
327     if (prevPtr == NULL) {
328 	notifier.firstFileHandlerPtr = filePtr->nextPtr;
329     } else {
330 	prevPtr->nextPtr = filePtr->nextPtr;
331     }
332 
333     /* back to poll-specific code - DEL */
334 
335     cur_fd_index = filePtr->pollArrayIndex;
336     fdsInUse--;
337 
338     /* if this one is last, do nothing special */
339     /* else swap with one at end of array */
340 
341     if (cur_fd_index != fdsInUse) {
342 	int lastfd_in_array = fdArray[fdsInUse].fd;
343 	memcpy(&fdArray[cur_fd_index],&fdArray[fdsInUse],sizeof(struct pollfd));
344 
345 	/* update index to reflect new location in array */
346 	/* first find link corresponding to last element in array */
347 
348 	for (lastPtr = notifier.firstFileHandlerPtr; filePtr; lastPtr = lastPtr->nextPtr) {
349 	    if (lastPtr->fd == lastfd_in_array) {
350 		lastPtr->pollArrayIndex = cur_fd_index;
351 		break;
352 	    }
353 	}
354     }
355 
356     fdsInUse--;
357 
358     ckfree((char *) filePtr);
359 }
360 
361 /*
362  *----------------------------------------------------------------------
363  *
364  * FileHandlerEventProc --
365  *
366  *	This procedure is called by Tcl_ServiceEvent when a file event
367  *	reaches the front of the event queue.  This procedure is
368  *	responsible for actually handling the event by invoking the
369  *	callback for the file handler.
370  *
371  * Results:
372  *	Returns 1 if the event was handled, meaning it should be removed
373  *	from the queue.  Returns 0 if the event was not handled, meaning
374  *	it should stay on the queue.  The only time the event isn't
375  *	handled is if the TCL_FILE_EVENTS flag bit isn't set.
376  *
377  * Side effects:
378  *	Whatever the file handler's callback procedure does.
379  *
380  *----------------------------------------------------------------------
381  */
382 
383 static int
FileHandlerEventProc(evPtr,flags)384 FileHandlerEventProc(evPtr, flags)
385     Tcl_Event *evPtr;		/* Event to service. */
386     int flags;			/* Flags that indicate what events to
387 				 * handle, such as TCL_FILE_EVENTS. */
388 {
389     FileHandler *filePtr;
390     FileHandlerEvent *fileEvPtr = (FileHandlerEvent *) evPtr;
391     int mask;
392 
393     if (!(flags & TCL_FILE_EVENTS)) {
394 	return 0;
395     }
396 
397     /*
398      * Search through the file handlers to find the one whose handle matches
399      * the event.  We do this rather than keeping a pointer to the file
400      * handler directly in the event, so that the handler can be deleted
401      * while the event is queued without leaving a dangling pointer.
402      */
403 
404     for (filePtr = notifier.firstFileHandlerPtr; filePtr != NULL;
405 	    filePtr = filePtr->nextPtr) {
406 	if (filePtr->fd != fileEvPtr->fd) {
407 	    continue;
408 	}
409 
410 	/*
411 	 * The code is tricky for two reasons:
412 	 * 1. The file handler's desired events could have changed
413 	 *    since the time when the event was queued, so AND the
414 	 *    ready mask with the desired mask.
415 	 * 2. The file could have been closed and re-opened since
416 	 *    the time when the event was queued.  This is why the
417 	 *    ready mask is stored in the file handler rather than
418 	 *    the queued event:  it will be zeroed when a new
419 	 *    file handler is created for the newly opened file.
420 	 */
421 
422 	mask = filePtr->readyMask & filePtr->mask;
423 	filePtr->readyMask = 0;
424 	if (mask != 0) {
425 	    (*filePtr->proc)(filePtr->clientData, mask);
426 	}
427 	break;
428     }
429     return 1;
430 }
431 
432 /*
433  *----------------------------------------------------------------------
434  *
435  * Tcl_WaitForEvent --
436  *
437  *	This function is called by Tcl_DoOneEvent to wait for new
438  *	events on the message queue.  If the block time is 0, then
439  *	Tcl_WaitForEvent just polls without blocking.
440  *
441  * Results:
442  *	Returns -1 if the select would block forever, otherwise
443  *	returns 0.
444  *
445  * Side effects:
446  *	Queues file events that are detected by the select.
447  *
448  *----------------------------------------------------------------------
449  */
450 
451 int
Tcl_WaitForEvent(timePtr)452 Tcl_WaitForEvent(timePtr)
453     Tcl_Time *timePtr;		/* Maximum block time, or NULL. */
454 {
455     FileHandler *filePtr;
456     FileHandlerEvent *fileEvPtr;
457     int timeout;
458     struct timeval *timeoutPtr;
459 
460     int bit, index, mask, numFound;
461 
462     if (!initialized) {
463 	InitNotifier();
464     }
465 
466     /*
467      * Set up the timeout structure.  Note that if there are no events to
468      * check for, we return with a negative result rather than blocking
469      * forever.
470      */
471 
472     if (timePtr) {
473         timeout = timePtr->sec*1000 + timePtr->usec/1000;
474 
475     } else if (notifier.numFdBits == 0) {
476 	return -1;
477     } else {
478 	timeoutPtr = NULL;
479     }
480 
481     numFound = poll(fdArray,fdsInUse,timeout);
482 
483     /*
484      * Queue all detected file events before returning.
485      */
486 
487     for (filePtr = notifier.firstFileHandlerPtr;
488 	    (filePtr != NULL) && (numFound > 0);
489 	    filePtr = filePtr->nextPtr) {
490 	index = filePtr->pollArrayIndex;
491         mask = 0;
492 
493         if (fdArray[index].revents & POLLIN) {
494 	    mask |= TCL_READABLE;
495         }
496         if (fdArray[index].revents & POLLOUT) {
497 	    mask |= TCL_WRITABLE;
498         }
499         /* I have no idea if this is right ... */
500         if (fdArray[index].revents & (POLLPRI|POLLERR|POLLHUP|POLLNVAL)) {
501 	    mask |= TCL_EXCEPTION;
502         }
503 
504 	if (!mask) {
505 	    continue;
506 	} else {
507 	    numFound--;
508 	}
509 
510 	/*
511 	 * Don't bother to queue an event if the mask was previously
512 	 * non-zero since an event must still be on the queue.
513 	 */
514 
515 	if (filePtr->readyMask == 0) {
516 	    fileEvPtr = (FileHandlerEvent *) ckalloc(
517 		sizeof(FileHandlerEvent));
518 	    fileEvPtr->header.proc = FileHandlerEventProc;
519 	    fileEvPtr->fd = filePtr->fd;
520 	    Tcl_QueueEvent((Tcl_Event *) fileEvPtr, TCL_QUEUE_TAIL);
521 	}
522 	filePtr->readyMask = mask;
523     }
524     return 0;
525 }
526 
527