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