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