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