2000-03-22 Elena Zannoni <ezannoni@kwikemart.cygnus.com>
[platform/upstream/binutils.git] / gdb / event-loop.c
1 /* Event loop machinery for GDB, the GNU debugger.
2    Copyright 1999 Free Software Foundation, Inc.
3    Written by Elena Zannoni <ezannoni@cygnus.com> of Cygnus Solutions.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 59 Temple Place - Suite 330,
20    Boston, MA 02111-1307, USA. */
21
22 #include "defs.h"
23 #include "top.h"
24 #include "event-loop.h"
25 #include "event-top.h"
26 #ifdef HAVE_POLL
27 #include <poll.h>
28 #endif
29 #include <sys/types.h>
30 #include <string.h>
31 #include <errno.h>
32 #include <setjmp.h>
33 #include <sys/time.h>
34
35 /* Type of the mask arguments to select. */
36
37 #ifndef HAVE_POLL
38 #ifdef NO_FD_SET
39 /* All this stuff below is not required if select is used as God(tm)
40    intended, with the FD_* macros.  Are there any implementations of
41    select which don't have FD_SET and other standard FD_* macros?  I
42    don't think there are, but if I'm wrong, we need to catch them.  */
43 #error FD_SET must be defined if select function is to be used!
44
45 #ifndef _AIX
46 typedef long fd_mask;
47 #endif
48 #if defined(_IBMR2)
49 #define SELECT_MASK void
50 #else
51 #define SELECT_MASK int
52 #endif /* !_IBMR2 */
53
54 /* Define "NBBY" (number of bits per byte) if it's not already defined. */
55
56 #ifndef NBBY
57 #define NBBY 8
58 #endif
59
60 /* Define the number of fd_masks in an fd_set */
61
62 #ifndef FD_SETSIZE
63 #ifdef OPEN_MAX
64 #define FD_SETSIZE OPEN_MAX
65 #else
66 #define FD_SETSIZE 256
67 #endif
68 #endif
69 #if !defined(howmany)
70 #define howmany(x, y) (((x)+((y)-1))/(y))
71 #endif
72 #ifndef NFDBITS
73 #define NFDBITS NBBY*sizeof(fd_mask)
74 #endif
75 #define MASK_SIZE howmany(FD_SETSIZE, NFDBITS)
76
77 #endif /* NO_FD_SET */
78 #endif /* !HAVE_POLL */
79
80
81 typedef struct gdb_event gdb_event;
82 typedef void (event_handler_func) (int);
83
84 /* Event for the GDB event system.  Events are queued by calling
85    async_queue_event and serviced later on by gdb_do_one_event. An
86    event can be, for instance, a file descriptor becoming ready to be
87    read. Servicing an event simply means that the procedure PROC will
88    be called.  We have 2 queues, one for file handlers that we listen
89    to in the event loop, and one for the file handlers+events that are
90    ready. The procedure PROC associated with each event is always the
91    same (handle_file_event).  Its duty is to invoke the handler
92    associated with the file descriptor whose state change generated
93    the event, plus doing other cleanups adn such. */
94
95 struct gdb_event
96   {
97     event_handler_func *proc;   /* Procedure to call to service this event. */
98     int fd;                     /* File descriptor that is ready. */
99     struct gdb_event *next_event;       /* Next in list of events or NULL. */
100   };
101
102 /* Information about each file descriptor we register with the event
103    loop. */
104
105 typedef struct file_handler
106   {
107     int fd;                     /* File descriptor. */
108     int mask;                   /* Events we want to monitor: POLLIN, etc. */
109     int ready_mask;             /* Events that have been seen since
110                                    the last time. */
111     handler_func *proc;         /* Procedure to call when fd is ready. */
112     gdb_client_data client_data;        /* Argument to pass to proc. */
113     int error;                  /* Was an error detected on this fd? */
114     struct file_handler *next_file;     /* Next registered file descriptor. */
115   }
116 file_handler;
117
118 /* PROC is a function to be invoked when the READY flag is set. This
119    happens when there has been a signal and the corresponding signal
120    handler has 'triggered' this async_signal_handler for
121    execution. The actual work to be done in response to a signal will
122    be carried out by PROC at a later time, within process_event. This
123    provides a deferred execution of signal handlers.
124    Async_init_signals takes care of setting up such an
125    asyn_signal_handler for each interesting signal. */
126 typedef struct async_signal_handler
127   {
128     int ready;                  /* If ready, call this handler from the main event loop, 
129                                    using invoke_async_handler. */
130     struct async_signal_handler *next_handler;  /* Ptr to next handler */
131     sig_handler_func *proc;     /* Function to call to do the work */
132     gdb_client_data client_data;        /* Argument to async_handler_func */
133   }
134 async_signal_handler;
135
136
137 /* Event queue:  
138    - the first event in the queue is the head of the queue. 
139    It will be the next to be serviced.
140    - the last event in the queue 
141
142    Events can be inserted at the front of the queue or at the end of
143    the queue.  Events will be extracted from the queue for processing
144    starting from the head.  Therefore, events inserted at the head of
145    the queue will be processed in a last in first out fashion, while
146    those inserted at the tail of the queue will be processed in a first
147    in first out manner.  All the fields are NULL if the queue is
148    empty. */
149
150 static struct
151   {
152     gdb_event *first_event;     /* First pending event */
153     gdb_event *last_event;      /* Last pending event */
154   }
155 event_queue;
156
157 /* Gdb_notifier is just a list of file descriptors gdb is interested in.
158    These are the input file descriptor, and the target file
159    descriptor. We have two flavors of the notifier, one for platforms
160    that have the POLL function, the other for those that don't, and
161    only support SELECT. Each of the elements in the gdb_notifier list is
162    basically a description of what kind of events gdb is interested
163    in, for each fd. */
164
165 /* As of 1999-04-30 only the input file descriptor is registered with the
166    event loop. */
167
168 /* Do we use poll or select ? */
169 #ifdef HAVE_POLL
170 #define USE_POLL 1
171 #else
172 #define USE_POLL 0
173 #endif /* HAVE_POLL */
174
175 static unsigned char use_poll = USE_POLL;
176
177 static struct
178   {
179     /* Ptr to head of file handler list. */
180     file_handler *first_file_handler;
181
182 #ifdef HAVE_POLL
183     /* Ptr to array of pollfd structures. */
184     struct pollfd *poll_fds;
185
186     /* Timeout in milliseconds for calls to poll(). */
187     int poll_timeout;
188 #endif
189
190     /* Masks to be used in the next call to select.
191        Bits are set in response to calls to create_file_handler. */
192     fd_set check_masks[3];
193
194     /* What file descriptors were found ready by select. */
195     fd_set ready_masks[3];
196
197     /* Number of file descriptors to monitor. (for poll) */
198     /* Number of valid bits (highest fd value + 1). (for select) */
199     int num_fds;
200
201     /* Time structure for calls to select(). */
202     struct timeval select_timeout;
203
204     /* Flag to tell whether the timeout should be used. */
205     int timeout_valid;
206   }
207 gdb_notifier;
208
209 /* Structure associated with a timer. PROC will be executed at the
210    first occasion after WHEN. */
211 struct gdb_timer
212   {
213     struct timeval when;
214     int timer_id;
215     struct gdb_timer *next;
216     timer_handler_func *proc;   /* Function to call to do the work */
217     gdb_client_data client_data;        /* Argument to async_handler_func */
218   }
219 gdb_timer;
220
221 /* List of currently active timers. It is sorted in order of
222    increasing timers. */
223 static struct
224   {
225     /* Pointer to first in timer list. */
226     struct gdb_timer *first_timer;
227
228     /* Id of the last timer created. */
229     int num_timers;
230   }
231 timer_list;
232
233 /* All the async_signal_handlers gdb is interested in are kept onto
234    this list. */
235 static struct
236   {
237     /* Pointer to first in handler list. */
238     async_signal_handler *first_handler;
239
240     /* Pointer to last in handler list. */
241     async_signal_handler *last_handler;
242   }
243 sighandler_list;
244
245 /* Is any of the handlers ready?  Check this variable using
246    check_async_ready. This is used by process_event, to determine
247    whether or not to invoke the invoke_async_signal_handler
248    function. */
249 static int async_handler_ready = 0;
250
251 static void create_file_handler (int fd, int mask, handler_func * proc, gdb_client_data client_data);
252 static void invoke_async_signal_handler (void);
253 static void handle_file_event (int event_file_desc);
254 static int gdb_wait_for_event (void);
255 static int gdb_do_one_event (void *data);
256 static int check_async_ready (void);
257 static void async_queue_event (gdb_event * event_ptr, queue_position position);
258 static gdb_event *create_file_event (int fd);
259 static int process_event (void);
260 static void handle_timer_event (int dummy);
261 static void poll_timers (void);
262 \f
263
264 /* Insert an event object into the gdb event queue at 
265    the specified position.
266    POSITION can be head or tail, with values TAIL, HEAD.
267    EVENT_PTR points to the event to be inserted into the queue.
268    The caller must allocate memory for the event. It is freed
269    after the event has ben handled.
270    Events in the queue will be processed head to tail, therefore,
271    events inserted at the head of the queue will be processed
272    as last in first out. Event appended at the tail of the queue
273    will be processed first in first out. */
274 static void
275 async_queue_event (gdb_event * event_ptr, queue_position position)
276 {
277   if (position == TAIL)
278     {
279       /* The event will become the new last_event. */
280
281       event_ptr->next_event = NULL;
282       if (event_queue.first_event == NULL)
283         event_queue.first_event = event_ptr;
284       else
285         event_queue.last_event->next_event = event_ptr;
286       event_queue.last_event = event_ptr;
287     }
288   else if (position == HEAD)
289     {
290       /* The event becomes the new first_event. */
291
292       event_ptr->next_event = event_queue.first_event;
293       if (event_queue.first_event == NULL)
294         event_queue.last_event = event_ptr;
295       event_queue.first_event = event_ptr;
296     }
297 }
298
299 /* Create a file event, to be enqueued in the event queue for
300    processing. The procedure associated to this event is always
301    handle_file_event, which will in turn invoke the one that was
302    associated to FD when it was registered with the event loop. */
303 static gdb_event *
304 create_file_event (int fd)
305 {
306   gdb_event *file_event_ptr;
307
308   file_event_ptr = (gdb_event *) xmalloc (sizeof (gdb_event));
309   file_event_ptr->proc = handle_file_event;
310   file_event_ptr->fd = fd;
311   return (file_event_ptr);
312 }
313
314 /* Process one event.
315    The event can be the next one to be serviced in the event queue,
316    or an asynchronous event handler can be invoked in response to
317    the reception of a signal.
318    If an event was processed (either way), 1 is returned otherwise
319    0 is returned.   
320    Scan the queue from head to tail, processing therefore the high
321    priority events first, by invoking the associated event handler
322    procedure. */
323 static int
324 process_event (void)
325 {
326   gdb_event *event_ptr, *prev_ptr;
327   event_handler_func *proc;
328   int fd;
329
330   /* First let's see if there are any asynchronous event handlers that
331      are ready. These would be the result of invoking any of the
332      signal handlers. */
333
334   if (check_async_ready ())
335     {
336       invoke_async_signal_handler ();
337       return 1;
338     }
339
340   /* Look in the event queue to find an event that is ready
341      to be processed. */
342
343   for (event_ptr = event_queue.first_event; event_ptr != NULL;
344        event_ptr = event_ptr->next_event)
345     {
346       /* Call the handler for the event. */
347
348       proc = event_ptr->proc;
349       fd = event_ptr->fd;
350
351       /* Let's get rid of the event from the event queue.  We need to
352          do this now because while processing the event, the proc
353          function could end up calling 'error' and therefore jump out
354          to the caller of this function, gdb_do_one_event. In that
355          case, we would have on the event queue an event wich has been
356          processed, but not deleted. */
357
358       if (event_queue.first_event == event_ptr)
359         {
360           event_queue.first_event = event_ptr->next_event;
361           if (event_ptr->next_event == NULL)
362             event_queue.last_event = NULL;
363         }
364       else
365         {
366           prev_ptr = event_queue.first_event;
367           while (prev_ptr->next_event != event_ptr)
368             prev_ptr = prev_ptr->next_event;
369
370           prev_ptr->next_event = event_ptr->next_event;
371           if (event_ptr->next_event == NULL)
372             event_queue.last_event = prev_ptr;
373         }
374       free ((char *) event_ptr);
375
376       /* Now call the procedure associated with the event. */
377       (*proc) (fd);
378       return 1;
379     }
380
381   /* this is the case if there are no event on the event queue. */
382   return 0;
383 }
384
385 /* Process one high level event.  If nothing is ready at this time,
386    wait for something to happen (via gdb_wait_for_event), then process
387    it.  Returns >0 if something was done otherwise returns <0 (this
388    can happen if there are no event sources to wait for).  If an error
389    occures catch_errors() which calls this function returns zero. */
390
391 static int
392 gdb_do_one_event (void *data)
393 {
394   /* Any events already waiting in the queue? */
395   if (process_event ())
396     {
397       return 1;
398     }
399   
400   /* Are any timers that are ready? If so, put an event on the queue. */
401   poll_timers ();
402   
403   /* Wait for a new event.  If gdb_wait_for_event returns -1,
404      we should get out because this means that there are no
405      event sources left. This will make the event loop stop,
406      and the application exit. */
407   
408   if (gdb_wait_for_event () < 0)
409     {
410       return -1;
411     }
412   
413   /* Handle any new events occurred while waiting. */
414   if (process_event ())
415     {
416       return 1;
417     }
418   
419   /* If gdb_wait_for_event has returned 1, it means that one
420      event has been handled. We break out of the loop. */
421   return 1;
422 }
423
424 /* Start up the event loop. This is the entry point to the event loop
425    from the command loop. */
426
427 void
428 start_event_loop (void)
429 {
430   /* Loop until there is nothing to do. This is the entry point to the
431      event loop engine. gdb_do_one_event, called via catch_errors()
432      will process one event for each invocation.  It blocks waits for
433      an event and then processes it.  >0 when an event is processed, 0
434      when catch_errors() caught an error and <0 when there are no
435      longer any event sources registered. */
436   while (1)
437     {
438       int result = catch_errors (gdb_do_one_event, 0, "", RETURN_MASK_ALL);
439       if (result < 0)
440         break;
441       if (result == 0)
442         {
443           /* FIXME: this should really be a call to a hook that is
444              interface specific, because interfaces can display the
445              prompt in their own way. */
446           display_gdb_prompt (0);
447           /* Maybe better to set a flag to be checked somewhere as to
448              whether display the prompt or not. */
449         }
450     }
451
452   /* We are done with the event loop. There are no more event sources
453      to listen to.  So we exit GDB. */
454   return;
455 }
456 \f
457
458 /* Wrapper function for create_file_handler, so that the caller
459    doesn't have to know implementation details about the use of poll
460    vs. select. */
461 void
462 add_file_handler (int fd, handler_func * proc, gdb_client_data client_data)
463 {
464 #ifdef HAVE_POLL
465   struct pollfd fds;
466 #endif
467
468   if (use_poll)
469     {
470 #ifdef HAVE_POLL
471       /* Check to see if poll () is usable. If not, we'll switch to
472          use select. This can happen on systems like
473          m68k-motorola-sys, `poll' cannot be used to wait for `stdin'.
474          On m68k-motorola-sysv, tty's are not stream-based and not
475          `poll'able.*/
476     fds.fd = fd;
477     fds.events = POLLIN;
478     if (poll (&fds, 1, 0) == 1 && (fds.revents & POLLNVAL))
479       use_poll = 0;
480 #else
481     internal_error ("event-loop.c : use_poll without HAVE_POLL");
482 #endif /* HAVE_POLL */
483     }
484   if (use_poll)
485     {
486 #ifdef HAVE_POLL
487       create_file_handler (fd, POLLIN, proc, client_data);
488 #else
489       internal_error ("event-loop.c : use_poll without HAVE_POLL");
490 #endif
491     }
492   else
493     create_file_handler (fd, GDB_READABLE | GDB_EXCEPTION, proc, client_data);
494 }
495
496 /* Add a file handler/descriptor to the list of descriptors we are
497    interested in.  
498    FD is the file descriptor for the file/stream to be listened to.  
499    For the poll case, MASK is a combination (OR) of
500    POLLIN, POLLRDNORM, POLLRDBAND, POLLPRI, POLLOUT, POLLWRNORM,
501    POLLWRBAND: these are the events we are interested in. If any of them 
502    occurs, proc should be called.
503    For the select case, MASK is a combination of READABLE, WRITABLE, EXCEPTION.
504    PROC is the procedure that will be called when an event occurs for
505    FD.  CLIENT_DATA is the argument to pass to PROC. */
506 static void
507 create_file_handler (int fd, int mask, handler_func * proc, gdb_client_data client_data)
508 {
509   file_handler *file_ptr;
510
511   /* Do we already have a file handler for this file? (We may be
512      changing its associated procedure). */
513   for (file_ptr = gdb_notifier.first_file_handler; file_ptr != NULL;
514        file_ptr = file_ptr->next_file)
515     {
516       if (file_ptr->fd == fd)
517         break;
518     }
519
520   /* It is a new file descriptor. Add it to the list. Otherwise, just
521      change the data associated with it. */
522   if (file_ptr == NULL)
523     {
524       file_ptr = (file_handler *) xmalloc (sizeof (file_handler));
525       file_ptr->fd = fd;
526       file_ptr->ready_mask = 0;
527       file_ptr->next_file = gdb_notifier.first_file_handler;
528       gdb_notifier.first_file_handler = file_ptr;
529     }
530   file_ptr->proc = proc;
531   file_ptr->client_data = client_data;
532   file_ptr->mask = mask;
533
534   if (use_poll)
535     {
536 #ifdef HAVE_POLL
537       gdb_notifier.num_fds++;
538       if (gdb_notifier.poll_fds)
539         gdb_notifier.poll_fds =
540           (struct pollfd *) realloc (gdb_notifier.poll_fds,
541                                (gdb_notifier.num_fds) * sizeof (struct pollfd));
542       else
543         gdb_notifier.poll_fds =
544           (struct pollfd *) xmalloc (sizeof (struct pollfd));
545       (gdb_notifier.poll_fds + gdb_notifier.num_fds - 1)->fd = fd;
546       (gdb_notifier.poll_fds + gdb_notifier.num_fds - 1)->events = mask;
547       (gdb_notifier.poll_fds + gdb_notifier.num_fds - 1)->revents = 0;
548 #else
549       internal_error ("event-loop.c : use_poll without HAVE_POLL");
550 #endif /* HAVE_POLL */
551     }
552   else
553     {
554       if (mask & GDB_READABLE)
555         FD_SET (fd, &gdb_notifier.check_masks[0]);
556       else
557         FD_CLR (fd, &gdb_notifier.check_masks[0]);
558
559       if (mask & GDB_WRITABLE)
560         FD_SET (fd, &gdb_notifier.check_masks[1]);
561       else
562         FD_CLR (fd, &gdb_notifier.check_masks[1]);
563
564       if (mask & GDB_EXCEPTION)
565         FD_SET (fd, &gdb_notifier.check_masks[2]);
566       else
567         FD_CLR (fd, &gdb_notifier.check_masks[2]);
568
569       if (gdb_notifier.num_fds <= fd)
570         gdb_notifier.num_fds = fd + 1;
571     }
572 }
573
574 /* Remove the file descriptor FD from the list of monitored fd's: 
575    i.e. we don't care anymore about events on the FD. */
576 void
577 delete_file_handler (int fd)
578 {
579   file_handler *file_ptr, *prev_ptr = NULL;
580   int i;
581 #ifdef HAVE_POLL
582   int j;
583   struct pollfd *new_poll_fds;
584 #endif
585
586   /* Find the entry for the given file. */
587
588   for (file_ptr = gdb_notifier.first_file_handler; file_ptr != NULL;
589        file_ptr = file_ptr->next_file)
590     {
591       if (file_ptr->fd == fd)
592         break;
593     }
594
595   if (file_ptr == NULL)
596     return;
597
598   if (use_poll)
599     {
600 #ifdef HAVE_POLL
601       /* Create a new poll_fds array by copying every fd's information but the
602          one we want to get rid of. */
603
604       new_poll_fds =
605         (struct pollfd *) xmalloc ((gdb_notifier.num_fds - 1) * sizeof (struct pollfd));
606
607       for (i = 0, j = 0; i < gdb_notifier.num_fds; i++)
608         {
609           if ((gdb_notifier.poll_fds + i)->fd != fd)
610             {
611               (new_poll_fds + j)->fd = (gdb_notifier.poll_fds + i)->fd;
612               (new_poll_fds + j)->events = (gdb_notifier.poll_fds + i)->events;
613               (new_poll_fds + j)->revents = (gdb_notifier.poll_fds + i)->revents;
614               j++;
615             }
616         }
617       free (gdb_notifier.poll_fds);
618       gdb_notifier.poll_fds = new_poll_fds;
619       gdb_notifier.num_fds--;
620 #else
621       internal_error ("event-loop.c : use_poll without HAVE_POLL");
622 #endif /* HAVE_POLL */
623     }
624   else
625     {
626       if (file_ptr->mask & GDB_READABLE)
627         FD_CLR (fd, &gdb_notifier.check_masks[0]);
628       if (file_ptr->mask & GDB_WRITABLE)
629         FD_CLR (fd, &gdb_notifier.check_masks[1]);
630       if (file_ptr->mask & GDB_EXCEPTION)
631         FD_CLR (fd, &gdb_notifier.check_masks[2]);
632
633       /* Find current max fd. */
634
635       if ((fd + 1) == gdb_notifier.num_fds)
636         {
637           gdb_notifier.num_fds--;
638           for (i = gdb_notifier.num_fds; i; i--)
639             {
640               if (FD_ISSET (i - 1, &gdb_notifier.check_masks[0])
641                   || FD_ISSET (i - 1, &gdb_notifier.check_masks[1])
642                   || FD_ISSET (i - 1, &gdb_notifier.check_masks[2]))
643                 break;
644             }
645           gdb_notifier.num_fds = i;
646         }
647     }
648
649   /* Deactivate the file descriptor, by clearing its mask, 
650      so that it will not fire again. */
651
652   file_ptr->mask = 0;
653
654   /* Get rid of the file handler in the file handler list. */
655   if (file_ptr == gdb_notifier.first_file_handler)
656     gdb_notifier.first_file_handler = file_ptr->next_file;
657   else
658     {
659       for (prev_ptr = gdb_notifier.first_file_handler;
660            prev_ptr->next_file != file_ptr;
661            prev_ptr = prev_ptr->next_file)
662         ;
663       prev_ptr->next_file = file_ptr->next_file;
664     }
665   free ((char *) file_ptr);
666 }
667
668 /* Handle the given event by calling the procedure associated to the
669    corresponding file handler.  Called by process_event indirectly,
670    through event_ptr->proc.  EVENT_FILE_DESC is file descriptor of the
671    event in the front of the event queue. */
672 static void
673 handle_file_event (int event_file_desc)
674 {
675   file_handler *file_ptr;
676   int mask;
677 #ifdef HAVE_POLL
678   int error_mask;
679   int error_mask_returned;
680 #endif
681
682   /* Search the file handler list to find one that matches the fd in
683      the event. */
684   for (file_ptr = gdb_notifier.first_file_handler; file_ptr != NULL;
685        file_ptr = file_ptr->next_file)
686     {
687       if (file_ptr->fd == event_file_desc)
688         {
689           /* With poll, the ready_mask could have any of three events
690              set to 1: POLLHUP, POLLERR, POLLNVAL. These events cannot
691              be used in the requested event mask (events), but they
692              can be returned in the return mask (revents). We need to
693              check for those event too, and add them to the mask which
694              will be passed to the handler. */
695
696           /* See if the desired events (mask) match the received
697              events (ready_mask). */
698
699           if (use_poll)
700             {
701 #ifdef HAVE_POLL
702               error_mask = POLLHUP | POLLERR | POLLNVAL;
703               mask = (file_ptr->ready_mask & file_ptr->mask) |
704                 (file_ptr->ready_mask & error_mask);
705               error_mask_returned = mask & error_mask;
706
707               if (error_mask_returned != 0)
708                 {
709                   /* Work in progress. We may need to tell somebody what
710                      kind of error we had. */
711                   if (error_mask_returned & POLLHUP)
712                     printf_unfiltered ("Hangup detected on fd %d\n", file_ptr->fd);
713                   if (error_mask_returned & POLLERR)
714                     printf_unfiltered ("Error detected on fd %d\n", file_ptr->fd);
715                   if (error_mask_returned & POLLNVAL)
716                     printf_unfiltered ("Invalid or non-`poll'able fd %d\n", file_ptr->fd);
717                   file_ptr->error = 1;
718                 }
719               else
720                 file_ptr->error = 0;
721 #else
722       internal_error ("event-loop.c : use_poll without HAVE_POLL");
723 #endif /* HAVE_POLL */
724             }
725           else
726             {
727               if (file_ptr->ready_mask & GDB_EXCEPTION)
728                 {
729                   printf_unfiltered ("Exception condition detected on fd %d\n", file_ptr->fd);
730                   file_ptr->error = 1;
731                 }
732               else
733                 file_ptr->error = 0;
734               mask = file_ptr->ready_mask & file_ptr->mask;
735             }
736
737           /* Clear the received events for next time around. */
738           file_ptr->ready_mask = 0;
739
740           /* If there was a match, then call the handler. */
741           if (mask != 0)
742             (*file_ptr->proc) (file_ptr->error, file_ptr->client_data);
743           break;
744         }
745     }
746 }
747
748 /* Called by gdb_do_one_event to wait for new events on the 
749    monitored file descriptors. Queue file events as they are 
750    detected by the poll. 
751    If there are no events, this function will block in the 
752    call to poll.
753    Return -1 if there are no files descriptors to monitor, 
754    otherwise return 0. */
755 static int
756 gdb_wait_for_event (void)
757 {
758   file_handler *file_ptr;
759   gdb_event *file_event_ptr;
760   int num_found = 0;
761   int i;
762
763   /* Make sure all output is done before getting another event. */
764   gdb_flush (gdb_stdout);
765   gdb_flush (gdb_stderr);
766
767   if (gdb_notifier.num_fds == 0)
768     return -1;
769
770   if (use_poll)
771     {
772 #ifdef HAVE_POLL
773       num_found =
774         poll (gdb_notifier.poll_fds,
775               (unsigned long) gdb_notifier.num_fds,
776               gdb_notifier.timeout_valid ? gdb_notifier.poll_timeout : -1);
777
778       /* Don't print anything if we get out of poll because of a
779          signal. */
780       if (num_found == -1 && errno != EINTR)
781         perror_with_name ("Poll");
782 #else
783       internal_error ("event-loop.c : use_poll without HAVE_POLL");
784 #endif /* HAVE_POLL */
785     }
786   else
787     {
788       gdb_notifier.ready_masks[0] = gdb_notifier.check_masks[0];
789       gdb_notifier.ready_masks[1] = gdb_notifier.check_masks[1];
790       gdb_notifier.ready_masks[2] = gdb_notifier.check_masks[2];
791       num_found = select (gdb_notifier.num_fds,
792                           & gdb_notifier.ready_masks[0],
793                           & gdb_notifier.ready_masks[1],
794                           & gdb_notifier.ready_masks[2],
795                           gdb_notifier.timeout_valid
796                           ? &gdb_notifier.select_timeout : NULL);
797
798       /* Clear the masks after an error from select. */
799       if (num_found == -1)
800         {
801           FD_ZERO (&gdb_notifier.ready_masks[0]);
802           FD_ZERO (&gdb_notifier.ready_masks[1]);
803           FD_ZERO (&gdb_notifier.ready_masks[2]);
804           /* Dont print anything is we got a signal, let gdb handle it. */
805           if (errno != EINTR)
806             perror_with_name ("Select");
807         }
808     }
809
810   /* Enqueue all detected file events. */
811
812   if (use_poll)
813     {
814 #ifdef HAVE_POLL
815       for (i = 0; (i < gdb_notifier.num_fds) && (num_found > 0); i++)
816         {
817           if ((gdb_notifier.poll_fds + i)->revents)
818             num_found--;
819           else
820             continue;
821
822           for (file_ptr = gdb_notifier.first_file_handler;
823                file_ptr != NULL;
824                file_ptr = file_ptr->next_file)
825             {
826               if (file_ptr->fd == (gdb_notifier.poll_fds + i)->fd)
827                 break;
828             }
829
830           if (file_ptr)
831             {
832               /* Enqueue an event only if this is still a new event for
833                  this fd. */
834               if (file_ptr->ready_mask == 0)
835                 {
836                   file_event_ptr = create_file_event (file_ptr->fd);
837                   async_queue_event (file_event_ptr, TAIL);
838                 }
839             }
840
841           file_ptr->ready_mask = (gdb_notifier.poll_fds + i)->revents;
842         }
843 #else
844       internal_error ("event-loop.c : use_poll without HAVE_POLL");
845 #endif /* HAVE_POLL */
846     }
847   else
848     {
849       for (file_ptr = gdb_notifier.first_file_handler;
850            (file_ptr != NULL) && (num_found > 0);
851            file_ptr = file_ptr->next_file)
852         {
853           int mask = 0;
854
855           if (FD_ISSET (file_ptr->fd, &gdb_notifier.ready_masks[0]))
856             mask |= GDB_READABLE;
857           if (FD_ISSET (file_ptr->fd, &gdb_notifier.ready_masks[1]))
858             mask |= GDB_WRITABLE;
859           if (FD_ISSET (file_ptr->fd, &gdb_notifier.ready_masks[2]))
860             mask |= GDB_EXCEPTION;
861
862           if (!mask)
863             continue;
864           else
865             num_found--;
866
867           /* Enqueue an event only if this is still a new event for
868              this fd. */
869
870           if (file_ptr->ready_mask == 0)
871             {
872               file_event_ptr = create_file_event (file_ptr->fd);
873               async_queue_event (file_event_ptr, TAIL);
874             }
875           file_ptr->ready_mask = mask;
876         }
877     }
878   return 0;
879 }
880 \f
881
882 /* Create an asynchronous handler, allocating memory for it. 
883    Return a pointer to the newly created handler.
884    This pointer will be used to invoke the handler by 
885    invoke_async_signal_handler.
886    PROC is the function to call with CLIENT_DATA argument 
887    whenever the handler is invoked. */
888 async_signal_handler *
889 create_async_signal_handler (sig_handler_func * proc, gdb_client_data client_data)
890 {
891   async_signal_handler *async_handler_ptr;
892
893   async_handler_ptr =
894     (async_signal_handler *) xmalloc (sizeof (async_signal_handler));
895   async_handler_ptr->ready = 0;
896   async_handler_ptr->next_handler = NULL;
897   async_handler_ptr->proc = proc;
898   async_handler_ptr->client_data = client_data;
899   if (sighandler_list.first_handler == NULL)
900     sighandler_list.first_handler = async_handler_ptr;
901   else
902     sighandler_list.last_handler->next_handler = async_handler_ptr;
903   sighandler_list.last_handler = async_handler_ptr;
904   return async_handler_ptr;
905 }
906
907 /* Mark the handler (ASYNC_HANDLER_PTR) as ready. This information will
908    be used when the handlers are invoked, after we have waited for
909    some event.  The caller of this function is the interrupt handler
910    associated with a signal. */
911 void
912 mark_async_signal_handler (async_signal_handler * async_handler_ptr)
913 {
914   ((async_signal_handler *) async_handler_ptr)->ready = 1;
915   async_handler_ready = 1;
916 }
917
918 /* Call all the handlers that are ready. */
919 static void
920 invoke_async_signal_handler (void)
921 {
922   async_signal_handler *async_handler_ptr;
923
924   if (async_handler_ready == 0)
925     return;
926   async_handler_ready = 0;
927
928   /* Invoke ready handlers. */
929
930   while (1)
931     {
932       for (async_handler_ptr = sighandler_list.first_handler;
933            async_handler_ptr != NULL;
934            async_handler_ptr = async_handler_ptr->next_handler)
935         {
936           if (async_handler_ptr->ready)
937             break;
938         }
939       if (async_handler_ptr == NULL)
940         break;
941       async_handler_ptr->ready = 0;
942       (*async_handler_ptr->proc) (async_handler_ptr->client_data);
943     }
944
945   return;
946 }
947
948 /* Delete an asynchronous handler (ASYNC_HANDLER_PTR). 
949    Free the space allocated for it.  */
950 void
951 delete_async_signal_handler (async_signal_handler ** async_handler_ptr)
952 {
953   async_signal_handler *prev_ptr;
954
955   if (sighandler_list.first_handler == (*async_handler_ptr))
956     {
957       sighandler_list.first_handler = (*async_handler_ptr)->next_handler;
958       if (sighandler_list.first_handler == NULL)
959         sighandler_list.last_handler = NULL;
960     }
961   else
962     {
963       prev_ptr = sighandler_list.first_handler;
964       while (prev_ptr->next_handler != (*async_handler_ptr) && prev_ptr)
965         prev_ptr = prev_ptr->next_handler;
966       prev_ptr->next_handler = (*async_handler_ptr)->next_handler;
967       if (sighandler_list.last_handler == (*async_handler_ptr))
968         sighandler_list.last_handler = prev_ptr;
969     }
970   free ((char *) (*async_handler_ptr));
971   (*async_handler_ptr) = NULL;
972 }
973
974 /* Is it necessary to call invoke_async_signal_handler? */
975 static int
976 check_async_ready (void)
977 {
978   return async_handler_ready;
979 }
980
981 /* Create a timer that will expire in MILLISECONDS from now. When the
982    timer is ready, PROC will be executed. At creation, the timer is
983    aded to the timers queue.  This queue is kept sorted in order of
984    increasing timers. Return a handle to the timer struct. */
985 int
986 create_timer (int milliseconds, timer_handler_func * proc, gdb_client_data client_data)
987 {
988   struct gdb_timer *timer_ptr, *timer_index, *prev_timer;
989   struct timeval time_now, delta;
990
991   /* compute seconds */
992   delta.tv_sec = milliseconds / 1000;
993   /* compute microseconds */
994   delta.tv_usec = (milliseconds % 1000) * 1000;
995
996   gettimeofday (&time_now, NULL);
997
998   timer_ptr = (struct gdb_timer *) xmalloc (sizeof (gdb_timer));
999   timer_ptr->when.tv_sec = time_now.tv_sec + delta.tv_sec;
1000   timer_ptr->when.tv_usec = time_now.tv_usec + delta.tv_usec;
1001   /* carry? */
1002   if (timer_ptr->when.tv_usec >= 1000000)
1003     {
1004       timer_ptr->when.tv_sec += 1;
1005       timer_ptr->when.tv_usec -= 1000000;
1006     }
1007   timer_ptr->proc = proc;
1008   timer_ptr->client_data = client_data;
1009   timer_list.num_timers++;
1010   timer_ptr->timer_id = timer_list.num_timers;
1011
1012   /* Now add the timer to the timer queue, making sure it is sorted in
1013      increasing order of expiration. */
1014
1015   for (timer_index = timer_list.first_timer;
1016        timer_index != NULL;
1017        timer_index = timer_index->next)
1018     {
1019       /* If the seconds field is greater or if it is the same, but the
1020          microsecond field is greater. */
1021       if ((timer_index->when.tv_sec > timer_ptr->when.tv_sec) ||
1022           ((timer_index->when.tv_sec == timer_ptr->when.tv_sec)
1023            && (timer_index->when.tv_usec > timer_ptr->when.tv_usec)))
1024         break;
1025     }
1026
1027   if (timer_index == timer_list.first_timer)
1028     {
1029       timer_ptr->next = timer_list.first_timer;
1030       timer_list.first_timer = timer_ptr;
1031
1032     }
1033   else
1034     {
1035       for (prev_timer = timer_list.first_timer;
1036            prev_timer->next != timer_index;
1037            prev_timer = prev_timer->next)
1038         ;
1039
1040       prev_timer->next = timer_ptr;
1041       timer_ptr->next = timer_index;
1042     }
1043
1044   gdb_notifier.timeout_valid = 0;
1045   return timer_ptr->timer_id;
1046 }
1047
1048 /* There is a chance that the creator of the timer wants to get rid of
1049    it before it expires. */
1050 void
1051 delete_timer (int id)
1052 {
1053   struct gdb_timer *timer_ptr, *prev_timer = NULL;
1054
1055   /* Find the entry for the given timer. */
1056
1057   for (timer_ptr = timer_list.first_timer; timer_ptr != NULL;
1058        timer_ptr = timer_ptr->next)
1059     {
1060       if (timer_ptr->timer_id == id)
1061         break;
1062     }
1063
1064   if (timer_ptr == NULL)
1065     return;
1066   /* Get rid of the timer in the timer list. */
1067   if (timer_ptr == timer_list.first_timer)
1068     timer_list.first_timer = timer_ptr->next;
1069   else
1070     {
1071       for (prev_timer = timer_list.first_timer;
1072            prev_timer->next != timer_ptr;
1073            prev_timer = prev_timer->next)
1074         ;
1075       prev_timer->next = timer_ptr->next;
1076     }
1077   free ((char *) timer_ptr);
1078
1079   gdb_notifier.timeout_valid = 0;
1080 }
1081
1082 /* When a timer event is put on the event queue, it will be handled by
1083    this function.  Just call the assiciated procedure and delete the
1084    timer event from the event queue. Repeat this for each timer that
1085    has expired. */
1086 static void
1087 handle_timer_event (int dummy)
1088 {
1089   struct timeval time_now;
1090   struct gdb_timer *timer_ptr, *saved_timer;
1091
1092   gettimeofday (&time_now, NULL);
1093   timer_ptr = timer_list.first_timer;
1094
1095   while (timer_ptr != NULL)
1096     {
1097       if ((timer_ptr->when.tv_sec > time_now.tv_sec) ||
1098           ((timer_ptr->when.tv_sec == time_now.tv_sec) &&
1099            (timer_ptr->when.tv_usec > time_now.tv_usec)))
1100         break;
1101
1102       /* Get rid of the timer from the beginning of the list. */
1103       timer_list.first_timer = timer_ptr->next;
1104       saved_timer = timer_ptr;
1105       timer_ptr = timer_ptr->next;
1106       /* Call the procedure associated with that timer. */
1107       (*saved_timer->proc) (saved_timer->client_data);
1108       free (saved_timer);
1109     }
1110
1111   gdb_notifier.timeout_valid = 0;
1112 }
1113
1114 /* Check whether any timers in the timers queue are ready. If at least
1115    one timer is ready, stick an event onto the event queue.  Even in
1116    case more than one timer is ready, one event is enough, because the
1117    handle_timer_event() will go through the timers list and call the
1118    procedures associated with all that have expired. Update the
1119    timeout for the select() or poll() as well. */
1120 static void
1121 poll_timers (void)
1122 {
1123   struct timeval time_now, delta;
1124   gdb_event *event_ptr;
1125
1126   if (timer_list.first_timer != NULL)
1127     {
1128       gettimeofday (&time_now, NULL);
1129       delta.tv_sec = timer_list.first_timer->when.tv_sec - time_now.tv_sec;
1130       delta.tv_usec = timer_list.first_timer->when.tv_usec - time_now.tv_usec;
1131       /* borrow? */
1132       if (delta.tv_usec < 0)
1133         {
1134           delta.tv_sec -= 1;
1135           delta.tv_usec += 1000000;
1136         }
1137
1138       /* Oops it expired already. Tell select / poll to return
1139          immediately. (Cannot simply test if delta.tv_sec is negative
1140          because time_t might be unsigned.)  */
1141       if (timer_list.first_timer->when.tv_sec < time_now.tv_sec
1142           || (timer_list.first_timer->when.tv_sec == time_now.tv_sec
1143               && timer_list.first_timer->when.tv_usec < time_now.tv_usec))
1144         {
1145           delta.tv_sec = 0;
1146           delta.tv_usec = 0;
1147         }
1148
1149       if (delta.tv_sec == 0 && delta.tv_usec == 0)
1150         {
1151           event_ptr = (gdb_event *) xmalloc (sizeof (gdb_event));
1152           event_ptr->proc = handle_timer_event;
1153           event_ptr->fd = timer_list.first_timer->timer_id;
1154           async_queue_event (event_ptr, TAIL);
1155         }
1156
1157       /* Now we need to update the timeout for select/ poll, because we
1158          don't want to sit there while this timer is expiring. */
1159       if (use_poll)
1160         {
1161 #ifdef HAVE_POLL
1162           gdb_notifier.poll_timeout = delta.tv_sec * 1000;
1163 #else
1164           internal_error ("event-loop.c : use_poll without HAVE_POLL");
1165 #endif /* HAVE_POLL */
1166         }
1167       else
1168         {
1169           gdb_notifier.select_timeout.tv_sec = delta.tv_sec;
1170           gdb_notifier.select_timeout.tv_usec = delta.tv_usec;
1171         }
1172       gdb_notifier.timeout_valid = 1;
1173     }
1174   else
1175     gdb_notifier.timeout_valid = 0;
1176 }