Rely on gnulib's unistd.h replacement.
[external/binutils.git] / gdb / gdbserver / event-loop.c
1 /* Event loop machinery for the remote server for GDB.
2    Copyright (C) 1999-2013 Free Software Foundation, Inc.
3
4    This file is part of GDB.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
18
19 /* Based on src/gdb/event-loop.c.  */
20
21 #include "server.h"
22 #include "queue.h"
23
24 #include <sys/types.h>
25 #include <string.h>
26 #include <sys/time.h>
27
28 #ifdef USE_WIN32API
29 #include <windows.h>
30 #include <io.h>
31 #endif
32
33 #ifdef HAVE_ERRNO_H
34 #include <errno.h>
35 #endif
36
37 #include <unistd.h>
38
39 typedef struct gdb_event gdb_event;
40 typedef int (event_handler_func) (gdb_fildes_t);
41
42 /* Tell create_file_handler what events we are interested in.  */
43
44 #define GDB_READABLE    (1<<1)
45 #define GDB_WRITABLE    (1<<2)
46 #define GDB_EXCEPTION   (1<<3)
47
48 /* Events are queued by calling 'QUEUE_enque (gdb_event_p, event_queue,
49    file_event_ptr)' and serviced later
50    on by do_one_event.  An event can be, for instance, a file
51    descriptor becoming ready to be read.  Servicing an event simply
52    means that the procedure PROC will be called.  We have 2 queues,
53    one for file handlers that we listen to in the event loop, and one
54    for the file handlers+events that are ready.  The procedure PROC
55    associated with each event is always the same (handle_file_event).
56    Its duty is to invoke the handler associated with the file
57    descriptor whose state change generated the event, plus doing other
58    cleanups and such.  */
59
60 typedef struct gdb_event
61   {
62     /* Procedure to call to service this event.  */
63     event_handler_func *proc;
64
65     /* File descriptor that is ready.  */
66     gdb_fildes_t fd;
67   } *gdb_event_p;
68
69 /* Information about each file descriptor we register with the event
70    loop.  */
71
72 typedef struct file_handler
73   {
74     /* File descriptor.  */
75     gdb_fildes_t fd;
76
77     /* Events we want to monitor.  */
78     int mask;
79
80     /* Events that have been seen since the last time.  */
81     int ready_mask;
82
83     /* Procedure to call when fd is ready.  */
84     handler_func *proc;
85
86     /* Argument to pass to proc.  */
87     gdb_client_data client_data;
88
89     /* Was an error detected on this fd?  */
90     int error;
91
92     /* Next registered file descriptor.  */
93     struct file_handler *next_file;
94   }
95 file_handler;
96
97 DECLARE_QUEUE_P(gdb_event_p);
98 static QUEUE(gdb_event_p) *event_queue = NULL;
99 DEFINE_QUEUE_P(gdb_event_p);
100
101 /* Gdb_notifier is just a list of file descriptors gdb is interested
102    in.  These are the input file descriptor, and the target file
103    descriptor.  Each of the elements in the gdb_notifier list is
104    basically a description of what kind of events gdb is interested
105    in, for each fd.  */
106
107 static struct
108   {
109     /* Ptr to head of file handler list.  */
110     file_handler *first_file_handler;
111
112     /* Masks to be used in the next call to select.  Bits are set in
113        response to calls to create_file_handler.  */
114     fd_set check_masks[3];
115
116     /* What file descriptors were found ready by select.  */
117     fd_set ready_masks[3];
118
119     /* Number of valid bits (highest fd value + 1). (for select) */
120     int num_fds;
121   }
122 gdb_notifier;
123
124 /* Callbacks are just routines that are executed before waiting for the
125    next event.  In GDB this is struct gdb_timer.  We don't need timers
126    so rather than copy all that complexity in gdbserver, we provide what
127    we need, but we do so in a way that if/when the day comes that we need
128    that complexity, it'll be easier to add - replace callbacks with timers
129    and use a delta of zero (which is all gdb currently uses timers for anyway).
130
131    PROC will be executed before gdbserver goes to sleep to wait for the
132    next event.  */
133
134 struct callback_event
135   {
136     int id;
137     callback_handler_func *proc;
138     gdb_client_data *data;
139     struct callback_event *next;
140   };
141
142 /* Table of registered callbacks.  */
143
144 static struct
145   {
146     struct callback_event *first;
147     struct callback_event *last;
148
149     /* Id of the last callback created.  */
150     int num_callbacks;
151   }
152 callback_list;
153
154 /* Free EVENT.  */
155
156 static void
157 gdb_event_xfree (struct gdb_event *event)
158 {
159   xfree (event);
160 }
161
162 void
163 initialize_event_loop (void)
164 {
165   event_queue = QUEUE_alloc (gdb_event_p, gdb_event_xfree);
166 }
167
168 /* Process one event.  If an event was processed, 1 is returned
169    otherwise 0 is returned.  Scan the queue from head to tail,
170    processing therefore the high priority events first, by invoking
171    the associated event handler procedure.  */
172
173 static int
174 process_event (void)
175 {
176   /* Let's get rid of the event from the event queue.  We need to
177      do this now because while processing the event, since the
178      proc function could end up jumping out to the caller of this
179      function.  In that case, we would have on the event queue an
180      event which has been processed, but not deleted.  */
181   if (!QUEUE_is_empty (gdb_event_p, event_queue))
182     {
183       gdb_event *event_ptr = QUEUE_deque (gdb_event_p, event_queue);
184       event_handler_func *proc = event_ptr->proc;
185       gdb_fildes_t fd = event_ptr->fd;
186
187       gdb_event_xfree (event_ptr);
188       /* Now call the procedure associated with the event.  */
189       if ((*proc) (fd))
190         return -1;
191       return 1;
192     }
193
194   /* This is the case if there are no event on the event queue.  */
195   return 0;
196 }
197
198 /* Append PROC to the callback list.
199    The result is the "id" of the callback that can be passed back to
200    delete_callback_event.  */
201
202 int
203 append_callback_event (callback_handler_func *proc, gdb_client_data data)
204 {
205   struct callback_event *event_ptr;
206
207   event_ptr = xmalloc (sizeof (*event_ptr));
208   event_ptr->id = callback_list.num_callbacks++;
209   event_ptr->proc = proc;
210   event_ptr->data = data;
211   event_ptr->next = NULL;
212   if (callback_list.first == NULL)
213     callback_list.first = event_ptr;
214   if (callback_list.last != NULL)
215     callback_list.last->next = event_ptr;
216   callback_list.last = event_ptr;
217   return event_ptr->id;
218 }
219
220 /* Delete callback ID.
221    It is not an error callback ID doesn't exist.  */
222
223 void
224 delete_callback_event (int id)
225 {
226   struct callback_event **p;
227
228   for (p = &callback_list.first; *p != NULL; p = &(*p)->next)
229     {
230       struct callback_event *event_ptr = *p;
231
232       if (event_ptr->id == id)
233         {
234           *p = event_ptr->next;
235           if (event_ptr == callback_list.last)
236             callback_list.last = NULL;
237           free (event_ptr);
238           break;
239         }
240     }
241 }
242
243 /* Run the next callback.
244    The result is 1 if a callback was called and event processing
245    should continue, -1 if the callback wants the event loop to exit,
246    and 0 if there are no more callbacks.  */
247
248 static int
249 process_callback (void)
250 {
251   struct callback_event *event_ptr;
252
253   event_ptr = callback_list.first;
254   if (event_ptr != NULL)
255     {
256       callback_handler_func *proc = event_ptr->proc;
257       gdb_client_data *data = event_ptr->data;
258
259       /* Remove the event before calling PROC,
260          more events may get added by PROC.  */
261       callback_list.first = event_ptr->next;
262       if (callback_list.first == NULL)
263         callback_list.last = NULL;
264       free  (event_ptr);
265       if ((*proc) (data))
266         return -1;
267       return 1;
268     }
269
270   return 0;
271 }
272
273 /* Add a file handler/descriptor to the list of descriptors we are
274    interested in.  FD is the file descriptor for the file/stream to be
275    listened to.  MASK is a combination of READABLE, WRITABLE,
276    EXCEPTION.  PROC is the procedure that will be called when an event
277    occurs for FD.  CLIENT_DATA is the argument to pass to PROC.  */
278
279 static void
280 create_file_handler (gdb_fildes_t fd, int mask, handler_func *proc,
281                      gdb_client_data client_data)
282 {
283   file_handler *file_ptr;
284
285   /* Do we already have a file handler for this file? (We may be
286      changing its associated procedure).  */
287   for (file_ptr = gdb_notifier.first_file_handler;
288        file_ptr != NULL;
289        file_ptr = file_ptr->next_file)
290     if (file_ptr->fd == fd)
291       break;
292
293   /* It is a new file descriptor.  Add it to the list.  Otherwise,
294      just change the data associated with it.  */
295   if (file_ptr == NULL)
296     {
297       file_ptr = xmalloc (sizeof (*file_ptr));
298       file_ptr->fd = fd;
299       file_ptr->ready_mask = 0;
300       file_ptr->next_file = gdb_notifier.first_file_handler;
301       gdb_notifier.first_file_handler = file_ptr;
302
303       if (mask & GDB_READABLE)
304         FD_SET (fd, &gdb_notifier.check_masks[0]);
305       else
306         FD_CLR (fd, &gdb_notifier.check_masks[0]);
307
308       if (mask & GDB_WRITABLE)
309         FD_SET (fd, &gdb_notifier.check_masks[1]);
310       else
311         FD_CLR (fd, &gdb_notifier.check_masks[1]);
312
313       if (mask & GDB_EXCEPTION)
314         FD_SET (fd, &gdb_notifier.check_masks[2]);
315       else
316         FD_CLR (fd, &gdb_notifier.check_masks[2]);
317
318       if (gdb_notifier.num_fds <= fd)
319         gdb_notifier.num_fds = fd + 1;
320     }
321
322   file_ptr->proc = proc;
323   file_ptr->client_data = client_data;
324   file_ptr->mask = mask;
325 }
326
327 /* Wrapper function for create_file_handler.  */
328
329 void
330 add_file_handler (gdb_fildes_t fd,
331                   handler_func *proc, gdb_client_data client_data)
332 {
333   create_file_handler (fd, GDB_READABLE | GDB_EXCEPTION, proc, client_data);
334 }
335
336 /* Remove the file descriptor FD from the list of monitored fd's:
337    i.e. we don't care anymore about events on the FD.  */
338
339 void
340 delete_file_handler (gdb_fildes_t fd)
341 {
342   file_handler *file_ptr, *prev_ptr = NULL;
343   int i;
344
345   /* Find the entry for the given file. */
346
347   for (file_ptr = gdb_notifier.first_file_handler;
348        file_ptr != NULL;
349        file_ptr = file_ptr->next_file)
350     if (file_ptr->fd == fd)
351       break;
352
353   if (file_ptr == NULL)
354     return;
355
356   if (file_ptr->mask & GDB_READABLE)
357     FD_CLR (fd, &gdb_notifier.check_masks[0]);
358   if (file_ptr->mask & GDB_WRITABLE)
359     FD_CLR (fd, &gdb_notifier.check_masks[1]);
360   if (file_ptr->mask & GDB_EXCEPTION)
361     FD_CLR (fd, &gdb_notifier.check_masks[2]);
362
363   /* Find current max fd.  */
364
365   if ((fd + 1) == gdb_notifier.num_fds)
366     {
367       gdb_notifier.num_fds--;
368       for (i = gdb_notifier.num_fds; i; i--)
369         {
370           if (FD_ISSET (i - 1, &gdb_notifier.check_masks[0])
371               || FD_ISSET (i - 1, &gdb_notifier.check_masks[1])
372               || FD_ISSET (i - 1, &gdb_notifier.check_masks[2]))
373             break;
374         }
375       gdb_notifier.num_fds = i;
376     }
377
378   /* Deactivate the file descriptor, by clearing its mask, so that it
379      will not fire again.  */
380
381   file_ptr->mask = 0;
382
383   /* Get rid of the file handler in the file handler list.  */
384   if (file_ptr == gdb_notifier.first_file_handler)
385     gdb_notifier.first_file_handler = file_ptr->next_file;
386   else
387     {
388       for (prev_ptr = gdb_notifier.first_file_handler;
389            prev_ptr->next_file != file_ptr;
390            prev_ptr = prev_ptr->next_file)
391         ;
392       prev_ptr->next_file = file_ptr->next_file;
393     }
394   free (file_ptr);
395 }
396
397 /* Handle the given event by calling the procedure associated to the
398    corresponding file handler.  Called by process_event indirectly,
399    through event_ptr->proc.  EVENT_FILE_DESC is file descriptor of the
400    event in the front of the event queue.  */
401
402 static int
403 handle_file_event (gdb_fildes_t event_file_desc)
404 {
405   file_handler *file_ptr;
406   int mask;
407
408   /* Search the file handler list to find one that matches the fd in
409      the event.  */
410   for (file_ptr = gdb_notifier.first_file_handler; file_ptr != NULL;
411        file_ptr = file_ptr->next_file)
412     {
413       if (file_ptr->fd == event_file_desc)
414         {
415           /* See if the desired events (mask) match the received
416              events (ready_mask).  */
417
418           if (file_ptr->ready_mask & GDB_EXCEPTION)
419             {
420               fprintf (stderr, "Exception condition detected on fd %s\n",
421                        pfildes (file_ptr->fd));
422               file_ptr->error = 1;
423             }
424           else
425             file_ptr->error = 0;
426           mask = file_ptr->ready_mask & file_ptr->mask;
427
428           /* Clear the received events for next time around.  */
429           file_ptr->ready_mask = 0;
430
431           /* If there was a match, then call the handler.  */
432           if (mask != 0)
433             {
434               if ((*file_ptr->proc) (file_ptr->error,
435                                      file_ptr->client_data) < 0)
436                 return -1;
437             }
438           break;
439         }
440     }
441
442   return 0;
443 }
444
445 /* Create a file event, to be enqueued in the event queue for
446    processing.  The procedure associated to this event is always
447    handle_file_event, which will in turn invoke the one that was
448    associated to FD when it was registered with the event loop.  */
449
450 static gdb_event *
451 create_file_event (gdb_fildes_t fd)
452 {
453   gdb_event *file_event_ptr;
454
455   file_event_ptr = xmalloc (sizeof (gdb_event));
456   file_event_ptr->proc = handle_file_event;
457   file_event_ptr->fd = fd;
458   return file_event_ptr;
459 }
460
461 /* Called by do_one_event to wait for new events on the monitored file
462    descriptors.  Queue file events as they are detected by the poll.
463    If there are no events, this function will block in the call to
464    select.  Return -1 if there are no files descriptors to monitor,
465    otherwise return 0.  */
466
467 static int
468 wait_for_event (void)
469 {
470   file_handler *file_ptr;
471   int num_found = 0;
472
473   /* Make sure all output is done before getting another event.  */
474   fflush (stdout);
475   fflush (stderr);
476
477   if (gdb_notifier.num_fds == 0)
478     return -1;
479
480   gdb_notifier.ready_masks[0] = gdb_notifier.check_masks[0];
481   gdb_notifier.ready_masks[1] = gdb_notifier.check_masks[1];
482   gdb_notifier.ready_masks[2] = gdb_notifier.check_masks[2];
483   num_found = select (gdb_notifier.num_fds,
484                       &gdb_notifier.ready_masks[0],
485                       &gdb_notifier.ready_masks[1],
486                       &gdb_notifier.ready_masks[2],
487                       NULL);
488
489   /* Clear the masks after an error from select.  */
490   if (num_found == -1)
491     {
492       FD_ZERO (&gdb_notifier.ready_masks[0]);
493       FD_ZERO (&gdb_notifier.ready_masks[1]);
494       FD_ZERO (&gdb_notifier.ready_masks[2]);
495 #ifdef EINTR
496       /* Dont print anything if we got a signal, let gdb handle
497          it.  */
498       if (errno != EINTR)
499         perror_with_name ("select");
500 #endif
501     }
502
503   /* Enqueue all detected file events.  */
504
505   for (file_ptr = gdb_notifier.first_file_handler;
506        file_ptr != NULL && num_found > 0;
507        file_ptr = file_ptr->next_file)
508     {
509       int mask = 0;
510
511       if (FD_ISSET (file_ptr->fd, &gdb_notifier.ready_masks[0]))
512         mask |= GDB_READABLE;
513       if (FD_ISSET (file_ptr->fd, &gdb_notifier.ready_masks[1]))
514         mask |= GDB_WRITABLE;
515       if (FD_ISSET (file_ptr->fd, &gdb_notifier.ready_masks[2]))
516         mask |= GDB_EXCEPTION;
517
518       if (!mask)
519         continue;
520       else
521         num_found--;
522
523       /* Enqueue an event only if this is still a new event for this
524          fd.  */
525
526       if (file_ptr->ready_mask == 0)
527         {
528           gdb_event *file_event_ptr = create_file_event (file_ptr->fd);
529
530           QUEUE_enque (gdb_event_p, event_queue, file_event_ptr);
531         }
532       file_ptr->ready_mask = mask;
533     }
534
535   return 0;
536 }
537
538 /* Start up the event loop.  This is the entry point to the event
539    loop.  */
540
541 void
542 start_event_loop (void)
543 {
544   /* Loop until there is nothing to do.  This is the entry point to
545      the event loop engine.  If nothing is ready at this time, wait
546      for something to happen (via wait_for_event), then process it.
547      Return when there are no longer event sources to wait for.  */
548
549   while (1)
550     {
551       /* Any events already waiting in the queue?  */
552       int res = process_event ();
553
554       /* Did the event handler want the event loop to stop?  */
555       if (res == -1)
556         return;
557
558       if (res)
559         continue;
560
561       /* Process any queued callbacks before we go to sleep.  */
562       res = process_callback ();
563
564       /* Did the callback want the event loop to stop?  */
565       if (res == -1)
566         return;
567
568       if (res)
569         continue;
570
571       /* Wait for a new event.  If wait_for_event returns -1, we
572          should get out because this means that there are no event
573          sources left.  This will make the event loop stop, and the
574          application exit.  */
575
576       if (wait_for_event () < 0)
577         return;
578     }
579
580   /* We are done with the event loop.  There are no more event sources
581      to listen to.  So we exit gdbserver.  */
582 }