os/persistentdata/persistentstorage/sqlite3api/TEST/TCL/tcldistribution/unix/tclUnixNotfy.c
author sl@SLION-WIN7.fritz.box
Fri, 15 Jun 2012 03:10:57 +0200
changeset 0 bde4ae8d615e
permissions -rw-r--r--
First public contribution.
     1 /*
     2  * tclUnixNotify.c --
     3  *
     4  *	This file contains the implementation of the select-based
     5  *	Unix-specific notifier, which is the lowest-level part of the
     6  *	Tcl event loop.  This file works together with
     7  *	../generic/tclNotify.c.
     8  *
     9  * Copyright (c) 1995-1997 Sun Microsystems, Inc.
    10  * Portions Copyright (c) 2007-2008 Nokia Corporation and/or its subsidiaries. All rights reserved.  
    11  *
    12  * See the file "license.terms" for information on usage and redistribution
    13  * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
    14  *
    15  * RCS: @(#) $Id: tclUnixNotfy.c,v 1.11.2.16 2006/08/22 17:45:02 andreas_kupries Exp $
    16  */
    17 
    18 #include "tclInt.h"
    19 #include "tclPort.h"
    20 #if defined(__SYMBIAN32__) && defined(__WINSCW__)
    21 #include "tclSymbianGlobals.h"
    22 #define dataKey getdataKey(8)
    23 #endif 
    24 
    25 #ifndef HAVE_COREFOUNDATION /* Darwin/Mac OS X CoreFoundation notifier
    26                              * is in tclMacOSXNotify.c */
    27 #ifndef __SYMBIAN32__  // added to prevent link errors on armv5
    28 #include <signal.h> 
    29 #endif
    30 
    31 extern TclStubs tclStubs;
    32 extern Tcl_NotifierProcs tclOriginalNotifier;
    33 
    34 /*
    35  * This structure is used to keep track of the notifier info for a 
    36  * a registered file.
    37  */
    38 
    39 typedef struct FileHandler {
    40     int fd;
    41     int mask;			/* Mask of desired events: TCL_READABLE,
    42 				 * etc. */
    43     int readyMask;		/* Mask of events that have been seen since the
    44 				 * last time file handlers were invoked for
    45 				 * this file. */
    46     Tcl_FileProc *proc;		/* Procedure to call, in the style of
    47 				 * Tcl_CreateFileHandler. */
    48     ClientData clientData;	/* Argument to pass to proc. */
    49     struct FileHandler *nextPtr;/* Next in list of all files we care about. */
    50 } FileHandler;
    51 
    52 /*
    53  * The following structure is what is added to the Tcl event queue when
    54  * file handlers are ready to fire.
    55  */
    56 
    57 typedef struct FileHandlerEvent {
    58     Tcl_Event header;		/* Information that is standard for
    59 				 * all events. */
    60     int fd;			/* File descriptor that is ready.  Used
    61 				 * to find the FileHandler structure for
    62 				 * the file (can't point directly to the
    63 				 * FileHandler structure because it could
    64 				 * go away while the event is queued). */
    65 } FileHandlerEvent;
    66 
    67 /*
    68  *
    69  * The following structure contains a set of select() masks to track
    70  * readable, writable, and exceptional conditions.
    71  */
    72 
    73 typedef struct SelectMasks {
    74     fd_set readable;
    75     fd_set writable;
    76     fd_set exceptional;
    77 } SelectMasks;
    78 
    79 /*
    80  * The following static structure contains the state information for the
    81  * select based implementation of the Tcl notifier.  One of these structures
    82  * is created for each thread that is using the notifier.  
    83  */
    84 
    85 typedef struct ThreadSpecificData {
    86     FileHandler *firstFileHandlerPtr;
    87 				/* Pointer to head of file handler list. */
    88     
    89     SelectMasks checkMasks;	/* This structure is used to build up the masks
    90 				 * to be used in the next call to select.
    91 				 * Bits are set in response to calls to
    92 				 * Tcl_CreateFileHandler. */
    93     SelectMasks readyMasks;	/* This array reflects the readable/writable
    94 				 * conditions that were found to exist by the
    95 				 * last call to select. */
    96     int numFdBits;		/* Number of valid bits in checkMasks
    97 				 * (one more than highest fd for which
    98 				 * Tcl_WatchFile has been called). */
    99 #ifdef TCL_THREADS
   100     int onList;			/* True if it is in this list */
   101     unsigned int pollState;	/* pollState is used to implement a polling 
   102 				 * handshake between each thread and the
   103 				 * notifier thread. Bits defined below. */
   104     struct ThreadSpecificData *nextPtr, *prevPtr;
   105                                 /* All threads that are currently waiting on 
   106                                  * an event have their ThreadSpecificData
   107                                  * structure on a doubly-linked listed formed
   108                                  * from these pointers.  You must hold the
   109                                  * notifierMutex lock before accessing these
   110                                  * fields. */
   111     Tcl_Condition waitCV;     /* Any other thread alerts a notifier
   112 				 * that an event is ready to be processed
   113 				 * by signaling this condition variable. */
   114     int eventReady;           /* True if an event is ready to be processed.
   115                                * Used as condition flag together with
   116                                * waitCV above. */
   117 #endif
   118 } ThreadSpecificData;
   119 
   120 #if !defined(__SYMBIAN32__) || !defined(__WINSCW__)
   121 static Tcl_ThreadDataKey dataKey;
   122 #endif
   123 
   124 #ifdef TCL_THREADS
   125 /*
   126  * The following static indicates the number of threads that have
   127  * initialized notifiers.
   128  *
   129  * You must hold the notifierMutex lock before accessing this variable.
   130  */
   131 
   132 static int notifierCount = 0;
   133 
   134 /*
   135  * The following variable points to the head of a doubly-linked list of 
   136  * of ThreadSpecificData structures for all threads that are currently
   137  * waiting on an event.
   138  *
   139  * You must hold the notifierMutex lock before accessing this list.
   140  */
   141 
   142 static ThreadSpecificData *waitingListPtr = NULL;
   143 
   144 /*
   145  * The notifier thread spends all its time in select() waiting for a
   146  * file descriptor associated with one of the threads on the waitingListPtr
   147  * list to do something interesting.  But if the contents of the
   148  * waitingListPtr list ever changes, we need to wake up and restart
   149  * the select() system call.  You can wake up the notifier thread by
   150  * writing a single byte to the file descriptor defined below.  This
   151  * file descriptor is the input-end of a pipe and the notifier thread is
   152  * listening for data on the output-end of the same pipe.  Hence writing
   153  * to this file descriptor will cause the select() system call to return
   154  * and wake up the notifier thread.
   155  *
   156  * You must hold the notifierMutex lock before accessing this list.
   157  */
   158 
   159 static int triggerPipe = -1;
   160 
   161 /*
   162  * The notifierMutex locks access to all of the global notifier state. 
   163  */
   164 
   165 TCL_DECLARE_MUTEX(notifierMutex)
   166 
   167 /*
   168  * The notifier thread signals the notifierCV when it has finished
   169  * initializing the triggerPipe and right before the notifier
   170  * thread terminates.
   171  */
   172 
   173 static Tcl_Condition notifierCV;
   174 
   175 /*
   176  * The pollState bits
   177  *	POLL_WANT is set by each thread before it waits on its condition
   178  *		variable.  It is checked by the notifier before it does
   179  *		select.
   180  *	POLL_DONE is set by the notifier if it goes into select after
   181  *		seeing POLL_WANT.  The idea is to ensure it tries a select
   182  *		with the same bits the initial thread had set.
   183  */
   184 #define POLL_WANT	0x1
   185 #define POLL_DONE	0x2
   186 
   187 /*
   188  * This is the thread ID of the notifier thread that does select.
   189  */
   190 static Tcl_ThreadId notifierThread;
   191 
   192 #endif
   193 
   194 /*
   195  * Static routines defined in this file.
   196  */
   197 
   198 #ifdef TCL_THREADS
   199 static void	NotifierThreadProc _ANSI_ARGS_((ClientData clientData));
   200 #endif
   201 static int	FileHandlerEventProc _ANSI_ARGS_((Tcl_Event *evPtr,
   202 		    int flags));
   203 
   204 /*
   205  *----------------------------------------------------------------------
   206  *
   207  * Tcl_InitNotifier --
   208  *
   209  *	Initializes the platform specific notifier state.
   210  *
   211  * Results:
   212  *	Returns a handle to the notifier state for this thread..
   213  *
   214  * Side effects:
   215  *	None.
   216  *
   217  *----------------------------------------------------------------------
   218  */
   219 
   220 EXPORT_C ClientData
   221 Tcl_InitNotifier()
   222 {
   223     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
   224 
   225 #ifdef TCL_THREADS
   226     tsdPtr->eventReady = 0;
   227 
   228     /*
   229      * Start the Notifier thread if necessary.
   230      */
   231 
   232     Tcl_MutexLock(&notifierMutex);
   233     if (notifierCount == 0) {
   234 	if (TclpThreadCreate(&notifierThread, NotifierThreadProc, NULL,
   235 		     TCL_THREAD_STACK_DEFAULT, TCL_THREAD_JOINABLE) != TCL_OK) {
   236 	    panic("Tcl_InitNotifier: unable to start notifier thread");
   237 	}
   238     }
   239     notifierCount++;
   240 
   241     /*
   242      * Wait for the notifier pipe to be created.
   243      */
   244 
   245     while (triggerPipe < 0) {
   246 	Tcl_ConditionWait(&notifierCV, &notifierMutex, NULL);
   247     }
   248 
   249     Tcl_MutexUnlock(&notifierMutex);
   250 #endif
   251     return (ClientData) tsdPtr;
   252 }
   253 
   254 /*
   255  *----------------------------------------------------------------------
   256  *
   257  * Tcl_FinalizeNotifier --
   258  *
   259  *	This function is called to cleanup the notifier state before
   260  *	a thread is terminated.
   261  *
   262  * Results:
   263  *	None.
   264  *
   265  * Side effects:
   266  *	May terminate the background notifier thread if this is the
   267  *	last notifier instance.
   268  *
   269  *----------------------------------------------------------------------
   270  */
   271 
   272 EXPORT_C void
   273 Tcl_FinalizeNotifier(clientData)
   274     ClientData clientData;		/* Not used. */
   275 {
   276 #ifdef TCL_THREADS
   277     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
   278 
   279     Tcl_MutexLock(&notifierMutex);
   280     notifierCount--;
   281 
   282     /*
   283      * If this is the last thread to use the notifier, close the notifier
   284      * pipe and wait for the background thread to terminate.
   285      */
   286 
   287     if (notifierCount == 0) {
   288 	int result;
   289 	if (triggerPipe < 0) {
   290 	    panic("Tcl_FinalizeNotifier: notifier pipe not initialized");
   291 	}
   292 
   293 	/*
   294 	 * Send "q" message to the notifier thread so that it will
   295 	 * terminate.  The notifier will return from its call to select()
   296 	 * and notice that a "q" message has arrived, it will then close
   297 	 * its side of the pipe and terminate its thread.  Note the we can
   298 	 * not just close the pipe and check for EOF in the notifier
   299 	 * thread because if a background child process was created with
   300 	 * exec, select() would not register the EOF on the pipe until the
   301 	 * child processes had terminated. [Bug: 4139] [Bug: 1222872]
   302 	 */
   303 
   304 	write(triggerPipe, "q", 1);
   305 	close(triggerPipe);
   306 	while(triggerPipe >= 0) {
   307 	    Tcl_ConditionWait(&notifierCV, &notifierMutex, NULL);
   308 	}
   309 	result = Tcl_JoinThread(notifierThread, NULL);
   310 	if (result) {
   311 	    Tcl_Panic("Tcl_FinalizeNotifier: unable to join notifier thread");
   312 	}
   313     }
   314 
   315     /*
   316      * Clean up any synchronization objects in the thread local storage.
   317      */
   318 
   319     Tcl_ConditionFinalize(&(tsdPtr->waitCV));
   320 
   321     Tcl_MutexUnlock(&notifierMutex);
   322 #endif
   323 }
   324 
   325 /*
   326  *----------------------------------------------------------------------
   327  *
   328  * Tcl_AlertNotifier --
   329  *
   330  *	Wake up the specified notifier from any thread. This routine
   331  *	is called by the platform independent notifier code whenever
   332  *	the Tcl_ThreadAlert routine is called.  This routine is
   333  *	guaranteed not to be called on a given notifier after
   334  *	Tcl_FinalizeNotifier is called for that notifier.
   335  *
   336  * Results:
   337  *	None.
   338  *
   339  * Side effects:
   340  *	Signals the notifier condition variable for the specified
   341  *	notifier.
   342  *
   343  *----------------------------------------------------------------------
   344  */
   345 
   346 EXPORT_C void
   347 Tcl_AlertNotifier(clientData)
   348     ClientData clientData;
   349 {
   350 #ifdef TCL_THREADS
   351     ThreadSpecificData *tsdPtr = (ThreadSpecificData *) clientData;
   352     Tcl_MutexLock(&notifierMutex);
   353     tsdPtr->eventReady = 1;
   354     Tcl_ConditionNotify(&tsdPtr->waitCV);
   355     Tcl_MutexUnlock(&notifierMutex);
   356 #endif
   357 }
   358 
   359 /*
   360  *----------------------------------------------------------------------
   361  *
   362  * Tcl_SetTimer --
   363  *
   364  *	This procedure sets the current notifier timer value.  This
   365  *	interface is not implemented in this notifier because we are
   366  *	always running inside of Tcl_DoOneEvent.
   367  *
   368  * Results:
   369  *	None.
   370  *
   371  * Side effects:
   372  *	None.
   373  *
   374  *----------------------------------------------------------------------
   375  */
   376 
   377 EXPORT_C void
   378 Tcl_SetTimer(timePtr)
   379     Tcl_Time *timePtr;		/* Timeout value, may be NULL. */
   380 {
   381     /*
   382      * The interval timer doesn't do anything in this implementation,
   383      * because the only event loop is via Tcl_DoOneEvent, which passes
   384      * timeout values to Tcl_WaitForEvent.
   385      */
   386 
   387     if (tclStubs.tcl_SetTimer != tclOriginalNotifier.setTimerProc) {
   388 	tclStubs.tcl_SetTimer(timePtr);
   389     }
   390 }
   391 
   392 /*
   393  *----------------------------------------------------------------------
   394  *
   395  * Tcl_ServiceModeHook --
   396  *
   397  *	This function is invoked whenever the service mode changes.
   398  *
   399  * Results:
   400  *	None.
   401  *
   402  * Side effects:
   403  *	None.
   404  *
   405  *----------------------------------------------------------------------
   406  */
   407 
   408 EXPORT_C void
   409 Tcl_ServiceModeHook(mode)
   410     int mode;			/* Either TCL_SERVICE_ALL, or
   411 				 * TCL_SERVICE_NONE. */
   412 {
   413 }
   414 
   415 /*
   416  *----------------------------------------------------------------------
   417  *
   418  * Tcl_CreateFileHandler --
   419  *
   420  *	This procedure registers a file handler with the select notifier.
   421  *
   422  * Results:
   423  *	None.
   424  *
   425  * Side effects:
   426  *	Creates a new file handler structure.
   427  *
   428  *----------------------------------------------------------------------
   429  */
   430 
   431 EXPORT_C void
   432 Tcl_CreateFileHandler(fd, mask, proc, clientData)
   433     int fd;			/* Handle of stream to watch. */
   434     int mask;			/* OR'ed combination of TCL_READABLE,
   435 				 * TCL_WRITABLE, and TCL_EXCEPTION:
   436 				 * indicates conditions under which
   437 				 * proc should be called. */
   438     Tcl_FileProc *proc;		/* Procedure to call for each
   439 				 * selected event. */
   440     ClientData clientData;	/* Arbitrary data to pass to proc. */
   441 {
   442     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
   443     FileHandler *filePtr;
   444 
   445     if (tclStubs.tcl_CreateFileHandler != tclOriginalNotifier.createFileHandlerProc) {
   446 	tclStubs.tcl_CreateFileHandler(fd, mask, proc, clientData);
   447 	return;
   448     }
   449 
   450     for (filePtr = tsdPtr->firstFileHandlerPtr; filePtr != NULL;
   451 	 filePtr = filePtr->nextPtr) {
   452 	if (filePtr->fd == fd) {
   453 	    break;
   454 	}
   455     }
   456     if (filePtr == NULL) {
   457 	filePtr = (FileHandler*) ckalloc(sizeof(FileHandler));
   458 	filePtr->fd = fd;
   459 	filePtr->readyMask = 0;
   460 	filePtr->nextPtr = tsdPtr->firstFileHandlerPtr;
   461 	tsdPtr->firstFileHandlerPtr = filePtr;
   462     }
   463     filePtr->proc = proc;
   464     filePtr->clientData = clientData;
   465     filePtr->mask = mask;
   466 
   467     /*
   468      * Update the check masks for this file.
   469      */
   470 
   471     if ( mask & TCL_READABLE ) {
   472 	FD_SET( fd, &(tsdPtr->checkMasks.readable) );
   473     } else {
   474 	FD_CLR( fd, &(tsdPtr->checkMasks.readable) );
   475     }
   476     if ( mask & TCL_WRITABLE ) {
   477 	FD_SET( fd, &(tsdPtr->checkMasks.writable) );
   478     } else {
   479 	FD_CLR( fd, &(tsdPtr->checkMasks.writable) );
   480     }
   481     if ( mask & TCL_EXCEPTION ) {
   482 	FD_SET( fd, &(tsdPtr->checkMasks.exceptional) );
   483     } else {
   484 	FD_CLR( fd, &(tsdPtr->checkMasks.exceptional) );
   485     }
   486     if (tsdPtr->numFdBits <= fd) {
   487 	tsdPtr->numFdBits = fd+1;
   488     }
   489 }
   490 
   491 /*
   492  *----------------------------------------------------------------------
   493  *
   494  * Tcl_DeleteFileHandler --
   495  *
   496  *	Cancel a previously-arranged callback arrangement for
   497  *	a file.
   498  *
   499  * Results:
   500  *	None.
   501  *
   502  * Side effects:
   503  *	If a callback was previously registered on file, remove it.
   504  *
   505  *----------------------------------------------------------------------
   506  */
   507 
   508 EXPORT_C void
   509 Tcl_DeleteFileHandler(fd)
   510     int fd;		/* Stream id for which to remove callback procedure. */
   511 {
   512     FileHandler *filePtr, *prevPtr;
   513     int i;
   514     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
   515 
   516     if (tclStubs.tcl_DeleteFileHandler != tclOriginalNotifier.deleteFileHandlerProc) {
   517 	tclStubs.tcl_DeleteFileHandler(fd);
   518 	return;
   519     }
   520 
   521     /*
   522      * Find the entry for the given file (and return if there isn't one).
   523      */
   524 
   525     for (prevPtr = NULL, filePtr = tsdPtr->firstFileHandlerPtr; ;
   526 	 prevPtr = filePtr, filePtr = filePtr->nextPtr) {
   527 	if (filePtr == NULL) {
   528 	    return;
   529 	}
   530 	if (filePtr->fd == fd) {
   531 	    break;
   532 	}
   533     }
   534 
   535     /*
   536      * Update the check masks for this file.
   537      */
   538 
   539     if (filePtr->mask & TCL_READABLE) {
   540 	FD_CLR( fd, &(tsdPtr->checkMasks.readable) );
   541     }
   542     if (filePtr->mask & TCL_WRITABLE) {
   543 	FD_CLR( fd, &(tsdPtr->checkMasks.writable) );
   544     }
   545     if (filePtr->mask & TCL_EXCEPTION) {
   546 	FD_CLR( fd, &(tsdPtr->checkMasks.exceptional) );
   547     }
   548 
   549     /*
   550      * Find current max fd.
   551      */
   552 
   553     if (fd+1 == tsdPtr->numFdBits) {
   554 	tsdPtr->numFdBits = 0;
   555 	for (i = fd-1; i >= 0; i--) {
   556 	    if ( FD_ISSET( i, &(tsdPtr->checkMasks.readable) )
   557 		 || FD_ISSET( i, &(tsdPtr->checkMasks.writable) )
   558 		 || FD_ISSET( i, &(tsdPtr->checkMasks.exceptional ) ) ) {
   559 		tsdPtr->numFdBits = i+1;
   560 		break;
   561 	    }
   562 	}
   563     }
   564 
   565     /*
   566      * Clean up information in the callback record.
   567      */
   568 
   569     if (prevPtr == NULL) {
   570 	tsdPtr->firstFileHandlerPtr = filePtr->nextPtr;
   571     } else {
   572 	prevPtr->nextPtr = filePtr->nextPtr;
   573     }
   574     ckfree((char *) filePtr);
   575 }
   576 
   577 /*
   578  *----------------------------------------------------------------------
   579  *
   580  * FileHandlerEventProc --
   581  *
   582  *	This procedure is called by Tcl_ServiceEvent when a file event
   583  *	reaches the front of the event queue.  This procedure is
   584  *	responsible for actually handling the event by invoking the
   585  *	callback for the file handler.
   586  *
   587  * Results:
   588  *	Returns 1 if the event was handled, meaning it should be removed
   589  *	from the queue.  Returns 0 if the event was not handled, meaning
   590  *	it should stay on the queue.  The only time the event isn't
   591  *	handled is if the TCL_FILE_EVENTS flag bit isn't set.
   592  *
   593  * Side effects:
   594  *	Whatever the file handler's callback procedure does.
   595  *
   596  *----------------------------------------------------------------------
   597  */
   598 
   599 static int
   600 FileHandlerEventProc(evPtr, flags)
   601     Tcl_Event *evPtr;		/* Event to service. */
   602     int flags;			/* Flags that indicate what events to
   603 				 * handle, such as TCL_FILE_EVENTS. */
   604 {
   605     int mask;
   606     FileHandler *filePtr;
   607     FileHandlerEvent *fileEvPtr = (FileHandlerEvent *) evPtr;
   608     ThreadSpecificData *tsdPtr;
   609 
   610     if (!(flags & TCL_FILE_EVENTS)) {
   611 	return 0;
   612     }
   613 
   614     /*
   615      * Search through the file handlers to find the one whose handle matches
   616      * the event.  We do this rather than keeping a pointer to the file
   617      * handler directly in the event, so that the handler can be deleted
   618      * while the event is queued without leaving a dangling pointer.
   619      */
   620 
   621     tsdPtr = TCL_TSD_INIT(&dataKey);
   622     for (filePtr = tsdPtr->firstFileHandlerPtr; filePtr != NULL;
   623 	 filePtr = filePtr->nextPtr) {
   624 	if (filePtr->fd != fileEvPtr->fd) {
   625 	    continue;
   626 	}
   627 
   628 	/*
   629 	 * The code is tricky for two reasons:
   630 	 * 1. The file handler's desired events could have changed
   631 	 *    since the time when the event was queued, so AND the
   632 	 *    ready mask with the desired mask.
   633 	 * 2. The file could have been closed and re-opened since
   634 	 *    the time when the event was queued.  This is why the
   635 	 *    ready mask is stored in the file handler rather than
   636 	 *    the queued event:  it will be zeroed when a new
   637 	 *    file handler is created for the newly opened file.
   638 	 */
   639 
   640 	mask = filePtr->readyMask & filePtr->mask;
   641 	filePtr->readyMask = 0;
   642 	if (mask != 0) {
   643 	    (*filePtr->proc)(filePtr->clientData, mask);
   644 	}
   645 	break;
   646     }
   647     return 1;
   648 }
   649 
   650 /*
   651  *----------------------------------------------------------------------
   652  *
   653  * Tcl_WaitForEvent --
   654  *
   655  *	This function is called by Tcl_DoOneEvent to wait for new
   656  *	events on the message queue.  If the block time is 0, then
   657  *	Tcl_WaitForEvent just polls without blocking.
   658  *
   659  * Results:
   660  *	Returns -1 if the select would block forever, otherwise
   661  *	returns 0.
   662  *
   663  * Side effects:
   664  *	Queues file events that are detected by the select.
   665  *
   666  *----------------------------------------------------------------------
   667  */
   668 
   669 EXPORT_C int
   670 Tcl_WaitForEvent(timePtr)
   671     Tcl_Time *timePtr;		/* Maximum block time, or NULL. */
   672 {
   673     FileHandler *filePtr;
   674     FileHandlerEvent *fileEvPtr;
   675     int mask;
   676 #ifdef TCL_THREADS
   677     int waitForFiles;
   678 #else
   679     /* Impl. notes: timeout & timeoutPtr are used if, and only if
   680      * threads are not enabled. They are the arguments for the regular
   681      * select() used when the core is not thread-enabled. */
   682 
   683     struct timeval timeout, *timeoutPtr;
   684     int numFound;
   685 #endif
   686     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
   687 
   688     if (tclStubs.tcl_WaitForEvent != tclOriginalNotifier.waitForEventProc) {
   689 	return tclStubs.tcl_WaitForEvent(timePtr);
   690     }
   691 
   692 #ifndef TCL_THREADS
   693     /*
   694      * Set up the timeout structure.  Note that if there are no events to
   695      * check for, we return with a negative result rather than blocking
   696      * forever.
   697      */
   698 
   699     if (timePtr) {
   700 	timeout.tv_sec = timePtr->sec;
   701 	timeout.tv_usec = timePtr->usec;
   702 	timeoutPtr = &timeout;
   703     } else if (tsdPtr->numFdBits == 0) {
   704 	/*
   705 	 * If there are no threads, no timeout, and no fds registered,
   706 	 * then there are no events possible and we must avoid deadlock.
   707 	 * Note that this is not entirely correct because there might
   708 	 * be a signal that could interrupt the select call, but we
   709 	 * don't handle that case if we aren't using threads.
   710 	 */
   711 
   712 	return -1;
   713     } else {
   714 	timeoutPtr = NULL;
   715     }
   716 #endif
   717 
   718 #ifdef TCL_THREADS
   719     /*
   720      * Place this thread on the list of interested threads, signal the
   721      * notifier thread, and wait for a response or a timeout.
   722      */
   723 
   724     Tcl_MutexLock(&notifierMutex);
   725 
   726     waitForFiles = (tsdPtr->numFdBits > 0);
   727     if (timePtr != NULL && timePtr->sec == 0 && (timePtr->usec == 0
   728 #if defined(__APPLE__) && defined(__LP64__)
   729 	    /*
   730 	     * On 64-bit Darwin, pthread_cond_timedwait() appears to have a bug
   731 	     * that causes it to wait forever when passed an absolute time which
   732 	     * has already been exceeded by the system time; as a workaround,
   733 	     * when given a very brief timeout, just do a poll. [Bug 1457797]
   734 	     */
   735 	    || timePtr->usec < 10
   736 #endif
   737 	    )) {
   738 	/*
   739 	 * Cannot emulate a polling select with a polling condition variable.
   740 	 * Instead, pretend to wait for files and tell the notifier
   741 	 * thread what we are doing.  The notifier thread makes sure
   742 	 * it goes through select with its select mask in the same state
   743 	 * as ours currently is.  We block until that happens.
   744 	 */
   745 
   746 	waitForFiles = 1;
   747 	tsdPtr->pollState = POLL_WANT;
   748 	timePtr = NULL;
   749     } else {
   750 	tsdPtr->pollState = 0;
   751     }
   752 
   753     if (waitForFiles) {
   754         /*
   755          * Add the ThreadSpecificData structure of this thread to the list
   756          * of ThreadSpecificData structures of all threads that are waiting
   757          * on file events.
   758          */
   759 
   760 
   761         tsdPtr->nextPtr = waitingListPtr;
   762         if (waitingListPtr) {
   763             waitingListPtr->prevPtr = tsdPtr;
   764         }
   765         tsdPtr->prevPtr = 0;
   766         waitingListPtr = tsdPtr;
   767 	tsdPtr->onList = 1;
   768 	
   769 	write(triggerPipe, "", 1);
   770     }
   771 
   772     FD_ZERO( &(tsdPtr->readyMasks.readable) );
   773     FD_ZERO( &(tsdPtr->readyMasks.writable) );
   774     FD_ZERO( &(tsdPtr->readyMasks.exceptional) );
   775 
   776     if (!tsdPtr->eventReady) {
   777         Tcl_ConditionWait(&tsdPtr->waitCV, &notifierMutex, timePtr);
   778     }
   779     tsdPtr->eventReady = 0;
   780 
   781     if (waitForFiles && tsdPtr->onList) {
   782 	/*
   783 	 * Remove the ThreadSpecificData structure of this thread from the
   784 	 * waiting list.  Alert the notifier thread to recompute its select
   785 	 * masks - skipping this caused a hang when trying to close a pipe
   786 	 * which the notifier thread was still doing a select on.
   787 	 */
   788 
   789         if (tsdPtr->prevPtr) {
   790             tsdPtr->prevPtr->nextPtr = tsdPtr->nextPtr;
   791         } else {
   792             waitingListPtr = tsdPtr->nextPtr;
   793         }
   794         if (tsdPtr->nextPtr) {
   795             tsdPtr->nextPtr->prevPtr = tsdPtr->prevPtr;
   796         }
   797         tsdPtr->nextPtr = tsdPtr->prevPtr = NULL;
   798 	tsdPtr->onList = 0;
   799 	write(triggerPipe, "", 1);
   800     }
   801 
   802     
   803 #else
   804     tsdPtr->readyMasks = tsdPtr->checkMasks;
   805     numFound = select( tsdPtr->numFdBits,
   806 		       &(tsdPtr->readyMasks.readable),
   807 		       &(tsdPtr->readyMasks.writable),
   808 		       &(tsdPtr->readyMasks.exceptional),
   809 		       timeoutPtr );
   810 
   811     /*
   812      * Some systems don't clear the masks after an error, so
   813      * we have to do it here.
   814      */
   815 
   816     if (numFound == -1) {
   817 	FD_ZERO( &(tsdPtr->readyMasks.readable ) );
   818 	FD_ZERO( &(tsdPtr->readyMasks.writable ) );
   819 	FD_ZERO( &(tsdPtr->readyMasks.exceptional ) );
   820     }
   821 #endif
   822 
   823     /*
   824      * Queue all detected file events before returning.
   825      */
   826 
   827     for (filePtr = tsdPtr->firstFileHandlerPtr; (filePtr != NULL);
   828 	 filePtr = filePtr->nextPtr) {
   829 
   830 	mask = 0;
   831 	if ( FD_ISSET( filePtr->fd, &(tsdPtr->readyMasks.readable) ) ) {
   832 	    mask |= TCL_READABLE;
   833 	}
   834 	if ( FD_ISSET( filePtr->fd, &(tsdPtr->readyMasks.writable) ) ) {
   835 	    mask |= TCL_WRITABLE;
   836 	}
   837 	if ( FD_ISSET( filePtr->fd, &(tsdPtr->readyMasks.exceptional) ) ) {
   838 	    mask |= TCL_EXCEPTION;
   839 	}
   840 
   841 	if (!mask) {
   842 	    continue;
   843 	}
   844 
   845 	/*
   846 	 * Don't bother to queue an event if the mask was previously
   847 	 * non-zero since an event must still be on the queue.
   848 	 */
   849 
   850 	if (filePtr->readyMask == 0) {
   851 	    fileEvPtr = (FileHandlerEvent *) ckalloc(
   852 		sizeof(FileHandlerEvent));
   853 	    fileEvPtr->header.proc = FileHandlerEventProc;
   854 	    fileEvPtr->fd = filePtr->fd;
   855 	    Tcl_QueueEvent((Tcl_Event *) fileEvPtr, TCL_QUEUE_TAIL);
   856 	}
   857 	filePtr->readyMask = mask;
   858     }
   859 #ifdef TCL_THREADS
   860     Tcl_MutexUnlock(&notifierMutex);
   861 #endif
   862     return 0;
   863 }
   864 
   865 #ifdef TCL_THREADS
   866 /*
   867  *----------------------------------------------------------------------
   868  *
   869  * NotifierThreadProc --
   870  *
   871  *	This routine is the initial (and only) function executed by the
   872  *	special notifier thread.  Its job is to wait for file descriptors
   873  *	to become readable or writable or to have an exception condition
   874  *	and then to notify other threads who are interested in this
   875  *	information by signalling a condition variable.  Other threads
   876  *	can signal this notifier thread of a change in their interests
   877  *	by writing a single byte to a special pipe that the notifier
   878  *	thread is monitoring.
   879  *
   880  * Result:
   881  *	None.  Once started, this routine never exits.  It dies with
   882  *	the overall process.
   883  *
   884  * Side effects:
   885  *	The trigger pipe used to signal the notifier thread is created
   886  *	when the notifier thread first starts.
   887  *
   888  *----------------------------------------------------------------------
   889  */
   890 
   891 static void
   892 NotifierThreadProc(clientData)
   893     ClientData clientData;	/* Not used. */
   894 {
   895     ThreadSpecificData *tsdPtr;
   896     fd_set readableMask;
   897     fd_set writableMask;
   898     fd_set exceptionalMask;
   899     int fds[2];
   900     int i, status, numFdBits = 0, receivePipe;
   901     long found;
   902     struct timeval poll = {0., 0.}, *timePtr;
   903     char buf[2];
   904 
   905     if (pipe(fds) != 0) {
   906 	panic("NotifierThreadProc: could not create trigger pipe.");
   907     }
   908 
   909     receivePipe = fds[0];
   910 
   911 #ifndef USE_FIONBIO
   912     status = fcntl(receivePipe, F_GETFL);
   913     status |= O_NONBLOCK;
   914     if (fcntl(receivePipe, F_SETFL, status) < 0) {
   915 	panic("NotifierThreadProc: could not make receive pipe non blocking.");
   916     }
   917     status = fcntl(fds[1], F_GETFL);
   918     status |= O_NONBLOCK;
   919     if (fcntl(fds[1], F_SETFL, status) < 0) {
   920 	panic("NotifierThreadProc: could not make trigger pipe non blocking.");
   921     }
   922 #else
   923     if (ioctl(receivePipe, (int) FIONBIO, &status) < 0) {
   924 	panic("NotifierThreadProc: could not make receive pipe non blocking.");
   925     }
   926     if (ioctl(fds[1], (int) FIONBIO, &status) < 0) {
   927 	panic("NotifierThreadProc: could not make trigger pipe non blocking.");
   928     }
   929 #endif
   930 
   931     /*
   932      * Install the write end of the pipe into the global variable.
   933      */
   934 
   935     Tcl_MutexLock(&notifierMutex);
   936     triggerPipe = fds[1];
   937 
   938     /*
   939      * Signal any threads that are waiting.
   940      */
   941 
   942     Tcl_ConditionNotify(&notifierCV);
   943     Tcl_MutexUnlock(&notifierMutex);
   944 
   945     /*
   946      * Look for file events and report them to interested threads.
   947      */
   948 
   949     while (1) {
   950 
   951 	FD_ZERO( &readableMask );
   952 	FD_ZERO( &writableMask );
   953 	FD_ZERO( &exceptionalMask );
   954 
   955 	/*
   956 	 * Compute the logical OR of the select masks from all the
   957 	 * waiting notifiers.
   958 	 */
   959 
   960 	Tcl_MutexLock(&notifierMutex);
   961 	timePtr = NULL;
   962         for (tsdPtr = waitingListPtr; tsdPtr; tsdPtr = tsdPtr->nextPtr) {
   963 	    for ( i = tsdPtr->numFdBits-1; i >= 0; --i ) {
   964 		if ( FD_ISSET( i, &(tsdPtr->checkMasks.readable) ) ) {
   965 		    FD_SET( i, &readableMask );
   966 		}
   967 		if ( FD_ISSET( i, &(tsdPtr->checkMasks.writable) ) ) {
   968 		    FD_SET( i, &writableMask );
   969 		}
   970 		if ( FD_ISSET( i, &(tsdPtr->checkMasks.exceptional) ) ) {
   971 		    FD_SET( i, &exceptionalMask );
   972 		}
   973 	    }
   974 	    if ( tsdPtr->numFdBits > numFdBits ) {
   975 		numFdBits = tsdPtr->numFdBits;
   976 	    }
   977 	    if (tsdPtr->pollState & POLL_WANT) {
   978 		/*
   979 		 * Here we make sure we go through select() with the same
   980 		 * mask bits that were present when the thread tried to poll.
   981 		 */
   982 
   983 		tsdPtr->pollState |= POLL_DONE;
   984 		timePtr = &poll;
   985 	    }
   986 	}
   987 	Tcl_MutexUnlock(&notifierMutex);
   988 
   989 	/*
   990 	 * Set up the select mask to include the receive pipe.
   991 	 */
   992 
   993 	if ( receivePipe >= numFdBits ) {
   994 	    numFdBits = receivePipe + 1;
   995 	}
   996 	FD_SET( receivePipe, &readableMask );
   997 
   998 	if ( select( numFdBits, &readableMask, &writableMask,
   999 		     &exceptionalMask, timePtr) == -1 ) {
  1000 	    /*
  1001 	     * Try again immediately on an error.
  1002 	     */
  1003 
  1004 	    continue;
  1005         }
  1006 
  1007 	/*
  1008 	 * Alert any threads that are waiting on a ready file descriptor.
  1009 	 */
  1010 
  1011 	Tcl_MutexLock(&notifierMutex);
  1012         for (tsdPtr = waitingListPtr; tsdPtr; tsdPtr = tsdPtr->nextPtr) {
  1013 	    found = 0;
  1014 
  1015 	    for ( i = tsdPtr->numFdBits-1; i >= 0; --i ) {
  1016 		if ( FD_ISSET( i, &(tsdPtr->checkMasks.readable) )
  1017 		     && FD_ISSET( i, &readableMask ) ) {
  1018 		    FD_SET( i, &(tsdPtr->readyMasks.readable) );
  1019 		    found = 1;
  1020 		}
  1021 		if ( FD_ISSET( i, &(tsdPtr->checkMasks.writable) )
  1022 		     && FD_ISSET( i, &writableMask ) ) {
  1023 		    FD_SET( i, &(tsdPtr->readyMasks.writable) );
  1024 		    found = 1;
  1025 		}
  1026 		if ( FD_ISSET( i, &(tsdPtr->checkMasks.exceptional) )
  1027 		     && FD_ISSET( i, &exceptionalMask ) ) {
  1028 		    FD_SET( i, &(tsdPtr->readyMasks.exceptional) );
  1029 		    found = 1;
  1030 		}
  1031 	    }
  1032 
  1033             if (found || (tsdPtr->pollState & POLL_DONE)) {
  1034                 tsdPtr->eventReady = 1;
  1035 		if (tsdPtr->onList) {
  1036 		    /*
  1037 		     * Remove the ThreadSpecificData structure of this
  1038 		     * thread from the waiting list. This prevents us from
  1039 		     * continuously spining on select until the other
  1040 		     * threads runs and services the file event.
  1041 		     */
  1042 
  1043 		    if (tsdPtr->prevPtr) {
  1044 			tsdPtr->prevPtr->nextPtr = tsdPtr->nextPtr;
  1045 		    } else {
  1046 			waitingListPtr = tsdPtr->nextPtr;
  1047 		    }
  1048 		    if (tsdPtr->nextPtr) {
  1049 			tsdPtr->nextPtr->prevPtr = tsdPtr->prevPtr;
  1050 		    }
  1051 		    tsdPtr->nextPtr = tsdPtr->prevPtr = NULL;
  1052 		    tsdPtr->onList = 0;
  1053 		    tsdPtr->pollState = 0;
  1054 		}
  1055 		Tcl_ConditionNotify(&tsdPtr->waitCV);
  1056             }
  1057         }
  1058 	Tcl_MutexUnlock(&notifierMutex);
  1059 
  1060 	/*
  1061 	 * Consume the next byte from the notifier pipe if the pipe was
  1062 	 * readable.  Note that there may be multiple bytes pending, but
  1063 	 * to avoid a race condition we only read one at a time.
  1064 	 */
  1065 
  1066 	if ( FD_ISSET( receivePipe, &readableMask ) ) {
  1067 	    i = read(receivePipe, buf, 1);
  1068 
  1069 	    if ((i == 0) || ((i == 1) && (buf[0] == 'q'))) {
  1070 		/*
  1071 		 * Someone closed the write end of the pipe or sent us a
  1072 		 * Quit message [Bug: 4139] and then closed the write end
  1073 		 * of the pipe so we need to shut down the notifier thread.
  1074 		 */
  1075 
  1076 		break;
  1077 	    }
  1078 	}
  1079     }
  1080 
  1081     /*
  1082      * Clean up the read end of the pipe and signal any threads waiting on
  1083      * termination of the notifier thread.
  1084      */
  1085 
  1086     close(receivePipe);
  1087     Tcl_MutexLock(&notifierMutex);
  1088     triggerPipe = -1;
  1089     Tcl_ConditionNotify(&notifierCV);
  1090     Tcl_MutexUnlock(&notifierMutex);
  1091 
  1092     TclpThreadExit (0);
  1093 }
  1094 #endif
  1095 
  1096 #endif /* HAVE_COREFOUNDATION */