Share fork_inferior et al with gdbserver
[external/binutils.git] / gdb / gdbserver / event-loop.c
1 /* Event loop machinery for the remote server for GDB.
2    Copyright (C) 1999-2017 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 "gdb_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 = XNEW (struct callback_event);
201
202   event_ptr->id = callback_list.num_callbacks++;
203   event_ptr->proc = proc;
204   event_ptr->data = data;
205   event_ptr->next = NULL;
206   if (callback_list.first == NULL)
207     callback_list.first = event_ptr;
208   if (callback_list.last != NULL)
209     callback_list.last->next = event_ptr;
210   callback_list.last = event_ptr;
211   return event_ptr->id;
212 }
213
214 /* Delete callback ID.
215    It is not an error callback ID doesn't exist.  */
216
217 void
218 delete_callback_event (int id)
219 {
220   struct callback_event **p;
221
222   for (p = &callback_list.first; *p != NULL; p = &(*p)->next)
223     {
224       struct callback_event *event_ptr = *p;
225
226       if (event_ptr->id == id)
227         {
228           *p = event_ptr->next;
229           if (event_ptr == callback_list.last)
230             callback_list.last = NULL;
231           free (event_ptr);
232           break;
233         }
234     }
235 }
236
237 /* Run the next callback.
238    The result is 1 if a callback was called and event processing
239    should continue, -1 if the callback wants the event loop to exit,
240    and 0 if there are no more callbacks.  */
241
242 static int
243 process_callback (void)
244 {
245   struct callback_event *event_ptr;
246
247   event_ptr = callback_list.first;
248   if (event_ptr != NULL)
249     {
250       callback_handler_func *proc = event_ptr->proc;
251       gdb_client_data data = event_ptr->data;
252
253       /* Remove the event before calling PROC,
254          more events may get added by PROC.  */
255       callback_list.first = event_ptr->next;
256       if (callback_list.first == NULL)
257         callback_list.last = NULL;
258       free  (event_ptr);
259       if ((*proc) (data))
260         return -1;
261       return 1;
262     }
263
264   return 0;
265 }
266
267 /* Add a file handler/descriptor to the list of descriptors we are
268    interested in.  FD is the file descriptor for the file/stream to be
269    listened to.  MASK is a combination of READABLE, WRITABLE,
270    EXCEPTION.  PROC is the procedure that will be called when an event
271    occurs for FD.  CLIENT_DATA is the argument to pass to PROC.  */
272
273 static void
274 create_file_handler (gdb_fildes_t fd, int mask, handler_func *proc,
275                      gdb_client_data client_data)
276 {
277   file_handler *file_ptr;
278
279   /* Do we already have a file handler for this file? (We may be
280      changing its associated procedure).  */
281   for (file_ptr = gdb_notifier.first_file_handler;
282        file_ptr != NULL;
283        file_ptr = file_ptr->next_file)
284     if (file_ptr->fd == fd)
285       break;
286
287   /* It is a new file descriptor.  Add it to the list.  Otherwise,
288      just change the data associated with it.  */
289   if (file_ptr == NULL)
290     {
291       file_ptr = XNEW (struct file_handler);
292       file_ptr->fd = fd;
293       file_ptr->ready_mask = 0;
294       file_ptr->next_file = gdb_notifier.first_file_handler;
295       gdb_notifier.first_file_handler = file_ptr;
296
297       if (mask & GDB_READABLE)
298         FD_SET (fd, &gdb_notifier.check_masks[0]);
299       else
300         FD_CLR (fd, &gdb_notifier.check_masks[0]);
301
302       if (mask & GDB_WRITABLE)
303         FD_SET (fd, &gdb_notifier.check_masks[1]);
304       else
305         FD_CLR (fd, &gdb_notifier.check_masks[1]);
306
307       if (mask & GDB_EXCEPTION)
308         FD_SET (fd, &gdb_notifier.check_masks[2]);
309       else
310         FD_CLR (fd, &gdb_notifier.check_masks[2]);
311
312       if (gdb_notifier.num_fds <= fd)
313         gdb_notifier.num_fds = fd + 1;
314     }
315
316   file_ptr->proc = proc;
317   file_ptr->client_data = client_data;
318   file_ptr->mask = mask;
319 }
320
321 /* Wrapper function for create_file_handler.  */
322
323 void
324 add_file_handler (gdb_fildes_t fd,
325                   handler_func *proc, gdb_client_data client_data)
326 {
327   create_file_handler (fd, GDB_READABLE | GDB_EXCEPTION, proc, client_data);
328 }
329
330 /* Remove the file descriptor FD from the list of monitored fd's:
331    i.e. we don't care anymore about events on the FD.  */
332
333 void
334 delete_file_handler (gdb_fildes_t fd)
335 {
336   file_handler *file_ptr, *prev_ptr = NULL;
337   int i;
338
339   /* Find the entry for the given file. */
340
341   for (file_ptr = gdb_notifier.first_file_handler;
342        file_ptr != NULL;
343        file_ptr = file_ptr->next_file)
344     if (file_ptr->fd == fd)
345       break;
346
347   if (file_ptr == NULL)
348     return;
349
350   if (file_ptr->mask & GDB_READABLE)
351     FD_CLR (fd, &gdb_notifier.check_masks[0]);
352   if (file_ptr->mask & GDB_WRITABLE)
353     FD_CLR (fd, &gdb_notifier.check_masks[1]);
354   if (file_ptr->mask & GDB_EXCEPTION)
355     FD_CLR (fd, &gdb_notifier.check_masks[2]);
356
357   /* Find current max fd.  */
358
359   if ((fd + 1) == gdb_notifier.num_fds)
360     {
361       gdb_notifier.num_fds--;
362       for (i = gdb_notifier.num_fds; i; i--)
363         {
364           if (FD_ISSET (i - 1, &gdb_notifier.check_masks[0])
365               || FD_ISSET (i - 1, &gdb_notifier.check_masks[1])
366               || FD_ISSET (i - 1, &gdb_notifier.check_masks[2]))
367             break;
368         }
369       gdb_notifier.num_fds = i;
370     }
371
372   /* Deactivate the file descriptor, by clearing its mask, so that it
373      will not fire again.  */
374
375   file_ptr->mask = 0;
376
377   /* Get rid of the file handler in the file handler list.  */
378   if (file_ptr == gdb_notifier.first_file_handler)
379     gdb_notifier.first_file_handler = file_ptr->next_file;
380   else
381     {
382       for (prev_ptr = gdb_notifier.first_file_handler;
383            prev_ptr->next_file != file_ptr;
384            prev_ptr = prev_ptr->next_file)
385         ;
386       prev_ptr->next_file = file_ptr->next_file;
387     }
388   free (file_ptr);
389 }
390
391 /* Handle the given event by calling the procedure associated to the
392    corresponding file handler.  Called by process_event indirectly,
393    through event_ptr->proc.  EVENT_FILE_DESC is file descriptor of the
394    event in the front of the event queue.  */
395
396 static int
397 handle_file_event (gdb_fildes_t event_file_desc)
398 {
399   file_handler *file_ptr;
400   int mask;
401
402   /* Search the file handler list to find one that matches the fd in
403      the event.  */
404   for (file_ptr = gdb_notifier.first_file_handler; file_ptr != NULL;
405        file_ptr = file_ptr->next_file)
406     {
407       if (file_ptr->fd == event_file_desc)
408         {
409           /* See if the desired events (mask) match the received
410              events (ready_mask).  */
411
412           if (file_ptr->ready_mask & GDB_EXCEPTION)
413             {
414               warning ("Exception condition detected on fd %s",
415                        pfildes (file_ptr->fd));
416               file_ptr->error = 1;
417             }
418           else
419             file_ptr->error = 0;
420           mask = file_ptr->ready_mask & file_ptr->mask;
421
422           /* Clear the received events for next time around.  */
423           file_ptr->ready_mask = 0;
424
425           /* If there was a match, then call the handler.  */
426           if (mask != 0)
427             {
428               if ((*file_ptr->proc) (file_ptr->error,
429                                      file_ptr->client_data) < 0)
430                 return -1;
431             }
432           break;
433         }
434     }
435
436   return 0;
437 }
438
439 /* Create a file event, to be enqueued in the event queue for
440    processing.  The procedure associated to this event is always
441    handle_file_event, which will in turn invoke the one that was
442    associated to FD when it was registered with the event loop.  */
443
444 static gdb_event *
445 create_file_event (gdb_fildes_t fd)
446 {
447   gdb_event *file_event_ptr;
448
449   file_event_ptr = XNEW (gdb_event);
450   file_event_ptr->proc = handle_file_event;
451   file_event_ptr->fd = fd;
452
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 }