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