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