xref: /netbsd-src/external/gpl3/gdb/dist/gdbsupport/event-loop.cc (revision f8cf1a9151c7af1cb0bd8b09c13c66bca599c027)
1 /* Event loop machinery for GDB, the GNU debugger.
2    Copyright (C) 1999-2024 Free Software Foundation, Inc.
3    Written by Elena Zannoni <ezannoni@cygnus.com> of Cygnus Solutions.
4 
5    This file is part of GDB.
6 
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11 
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16 
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19 
20 #include "gdbsupport/event-loop.h"
21 
22 #include <chrono>
23 
24 #ifdef HAVE_POLL
25 #if defined (HAVE_POLL_H)
26 #include <poll.h>
27 #elif defined (HAVE_SYS_POLL_H)
28 #include <sys/poll.h>
29 #endif
30 #endif
31 
32 #include <sys/types.h>
33 #include "gdbsupport/gdb_sys_time.h"
34 #include "gdbsupport/gdb_select.h"
35 #include <optional>
36 #include "gdbsupport/scope-exit.h"
37 
38 /* See event-loop.h.  */
39 
40 debug_event_loop_kind debug_event_loop;
41 
42 /* Tell create_file_handler what events we are interested in.
43    This is used by the select version of the event loop.  */
44 
45 #define GDB_READABLE	(1<<1)
46 #define GDB_WRITABLE	(1<<2)
47 #define GDB_EXCEPTION	(1<<3)
48 
49 /* Information about each file descriptor we register with the event
50    loop.  */
51 
52 struct file_handler
53 {
54   /* File descriptor.  */
55   int fd;
56 
57   /* Events we want to monitor: POLLIN, etc.  */
58   int mask;
59 
60   /* Events that have been seen since the last time.  */
61   int ready_mask;
62 
63   /* Procedure to call when fd is ready.  */
64   handler_func *proc;
65 
66   /* Argument to pass to proc.  */
67   gdb_client_data client_data;
68 
69   /* User-friendly name of this handler.  */
70   std::string name;
71 
72   /* If set, this file descriptor is used for a user interface.  */
73   bool is_ui;
74 
75   /* Was an error detected on this fd?  */
76   int error;
77 
78   /* Next registered file descriptor.  */
79   struct file_handler *next_file;
80 };
81 
82 #ifdef HAVE_POLL
83 /* Do we use poll or select?  Some systems have poll, but then it's
84    not useable with all kinds of files.  We probe that whenever a new
85    file handler is added.  */
86 static bool use_poll = true;
87 #endif
88 
89 #ifdef USE_WIN32API
90 #include <windows.h>
91 #include <io.h>
92 #endif
93 
94 /* Gdb_notifier is just a list of file descriptors gdb is interested in.
95    These are the input file descriptor, and the target file
96    descriptor.  We have two flavors of the notifier, one for platforms
97    that have the POLL function, the other for those that don't, and
98    only support SELECT.  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     /* Next file handler to handle, for the select variant.  To level
108        the fairness across event sources, we serve file handlers in a
109        round-robin-like fashion.  The number and order of the polled
110        file handlers may change between invocations, but this is good
111        enough.  */
112     file_handler *next_file_handler;
113 
114 #ifdef HAVE_POLL
115     /* Descriptors to poll.  */
116     std::vector<struct pollfd> poll_fds;
117 
118     /* Next file descriptor to handle, for the poll variant.  To level
119        the fairness across event sources, we poll the file descriptors
120        in a round-robin-like fashion.  The number and order of the
121        polled file descriptors may change between invocations, but
122        this is good enough.  */
123     int next_poll_fds_index;
124 
125     /* Timeout in milliseconds for calls to poll().  */
126     int poll_timeout;
127 #endif
128 
129     /* Masks to be used in the next call to select.
130        Bits are set in response to calls to create_file_handler.  */
131     fd_set check_masks[3];
132 
133     /* What file descriptors were found ready by select.  */
134     fd_set ready_masks[3];
135 
136     /* Number of file descriptors to monitor (for poll).  */
137     /* Number of valid bits (highest fd value + 1) (for select).  */
138     int num_fds;
139 
140     /* Time structure for calls to select().  */
141     struct timeval select_timeout;
142 
143     /* Flag to tell whether the timeout should be used.  */
144     int timeout_valid;
145   }
146 gdb_notifier;
147 
148 /* Structure associated with a timer.  PROC will be executed at the
149    first occasion after WHEN.  */
150 struct gdb_timer
151   {
152     std::chrono::steady_clock::time_point when;
153     int timer_id;
154     struct gdb_timer *next;
155     timer_handler_func *proc;	    /* Function to call to do the work.  */
156     gdb_client_data client_data;    /* Argument to async_handler_func.  */
157   };
158 
159 /* List of currently active timers.  It is sorted in order of
160    increasing timers.  */
161 static struct
162   {
163     /* Pointer to first in timer list.  */
164     struct gdb_timer *first_timer;
165 
166     /* Id of the last timer created.  */
167     int num_timers;
168   }
169 timer_list;
170 
171 static void create_file_handler (int fd, int mask, handler_func *proc,
172 				 gdb_client_data client_data,
173 				 std::string &&name, bool is_ui);
174 static int gdb_wait_for_event (int);
175 static int update_wait_timeout (void);
176 static int poll_timers (void);
177 
178 /* Process one high level event.  If nothing is ready at this time,
179    wait at most MSTIMEOUT milliseconds for something to happen (via
180    gdb_wait_for_event), then process it.  Returns >0 if something was
181    done, <0 if there are no event sources to wait for, =0 if timeout occurred.
182    A timeout of 0 allows to serve an already pending event, but does not
183    wait if none found.
184    Setting the timeout to a negative value disables it.
185    The timeout is never used by gdb itself, it is however needed to
186    integrate gdb event handling within Insight's GUI event loop. */
187 
188 int
189 gdb_do_one_event (int mstimeout)
190 {
191   static int event_source_head = 0;
192   const int number_of_sources = 3;
193   int current = 0;
194 
195   /* First let's see if there are any asynchronous signal handlers
196      that are ready.  These would be the result of invoking any of the
197      signal handlers.  */
198   if (invoke_async_signal_handlers ())
199     return 1;
200 
201   /* To level the fairness across event sources, we poll them in a
202      round-robin fashion.  */
203   for (current = 0; current < number_of_sources; current++)
204     {
205       int res;
206 
207       switch (event_source_head)
208 	{
209 	case 0:
210 	  /* Are any timers that are ready?  */
211 	  res = poll_timers ();
212 	  break;
213 	case 1:
214 	  /* Are there events already waiting to be collected on the
215 	     monitored file descriptors?  */
216 	  res = gdb_wait_for_event (0);
217 	  break;
218 	case 2:
219 	  /* Are there any asynchronous event handlers ready?  */
220 	  res = check_async_event_handlers ();
221 	  break;
222 	default:
223 	  internal_error ("unexpected event_source_head %d",
224 			  event_source_head);
225 	}
226 
227       event_source_head++;
228       if (event_source_head == number_of_sources)
229 	event_source_head = 0;
230 
231       if (res > 0)
232 	return 1;
233     }
234 
235   if (mstimeout == 0)
236     return 0;	/* 0ms timeout: do not wait for an event. */
237 
238   /* Block waiting for a new event.  If gdb_wait_for_event returns -1,
239      we should get out because this means that there are no event
240      sources left.  This will make the event loop stop, and the
241      application exit.
242      If a timeout has been given, a new timer is set accordingly
243      to abort event wait.  It is deleted upon gdb_wait_for_event
244      termination and thus should never be triggered.
245      When the timeout is reached, events are not monitored again:
246      they already have been checked in the loop above. */
247 
248   std::optional<int> timer_id;
249 
250   SCOPE_EXIT
251     {
252       if (timer_id.has_value ())
253 	delete_timer (*timer_id);
254     };
255 
256   if (mstimeout > 0)
257     timer_id = create_timer (mstimeout,
258 			     [] (gdb_client_data arg)
259 			     {
260 			       ((std::optional<int> *) arg)->reset ();
261 			     },
262 			     &timer_id);
263   return gdb_wait_for_event (1);
264 }
265 
266 /* See event-loop.h  */
267 
268 void
269 add_file_handler (int fd, handler_func *proc, gdb_client_data client_data,
270 		  std::string &&name, bool is_ui)
271 {
272 #ifdef HAVE_POLL
273   if (use_poll)
274     {
275       struct pollfd fds;
276 
277       /* Check to see if poll () is usable.  If not, we'll switch to
278 	 use select.  This can happen on systems like
279 	 m68k-motorola-sys, `poll' cannot be used to wait for `stdin'.
280 	 On m68k-motorola-sysv, tty's are not stream-based and not
281 	 `poll'able.  */
282       fds.fd = fd;
283       fds.events = POLLIN;
284       if (poll (&fds, 1, 0) == 1 && (fds.revents & POLLNVAL))
285 	use_poll = false;
286     }
287   if (use_poll)
288     {
289       create_file_handler (fd, POLLIN, proc, client_data, std::move (name),
290 			   is_ui);
291     }
292   else
293 #endif /* HAVE_POLL */
294     create_file_handler (fd, GDB_READABLE | GDB_EXCEPTION,
295 			 proc, client_data, std::move (name), is_ui);
296 }
297 
298 /* Helper for add_file_handler.
299 
300    For the poll case, MASK is a combination (OR) of POLLIN,
301    POLLRDNORM, POLLRDBAND, POLLPRI, POLLOUT, POLLWRNORM, POLLWRBAND:
302    these are the events we are interested in.  If any of them occurs,
303    proc should be called.
304 
305    For the select case, MASK is a combination of READABLE, WRITABLE,
306    EXCEPTION.  PROC is the procedure that will be called when an event
307    occurs for FD.  CLIENT_DATA is the argument to pass to PROC.  */
308 
309 static void
310 create_file_handler (int fd, int mask, handler_func * proc,
311 		     gdb_client_data client_data, std::string &&name,
312 		     bool is_ui)
313 {
314   file_handler *file_ptr;
315 
316   /* Do we already have a file handler for this file?  (We may be
317      changing its associated procedure).  */
318   for (file_ptr = gdb_notifier.first_file_handler; file_ptr != NULL;
319        file_ptr = file_ptr->next_file)
320     {
321       if (file_ptr->fd == fd)
322 	break;
323     }
324 
325   /* It is a new file descriptor.  Add it to the list.  Otherwise, just
326      change the data associated with it.  */
327   if (file_ptr == NULL)
328     {
329       file_ptr = new file_handler;
330       file_ptr->fd = fd;
331       file_ptr->ready_mask = 0;
332       file_ptr->next_file = gdb_notifier.first_file_handler;
333       gdb_notifier.first_file_handler = file_ptr;
334 
335 #ifdef HAVE_POLL
336       if (use_poll)
337 	{
338 	  gdb_notifier.num_fds++;
339 	  struct pollfd new_fd;
340 	  new_fd.fd = fd;
341 	  new_fd.events = mask;
342 	  new_fd.revents = 0;
343 	  gdb_notifier.poll_fds.push_back (new_fd);
344 	}
345       else
346 #endif /* HAVE_POLL */
347 	{
348 	  if (mask & GDB_READABLE)
349 	    FD_SET (fd, &gdb_notifier.check_masks[0]);
350 	  else
351 	    FD_CLR (fd, &gdb_notifier.check_masks[0]);
352 
353 	  if (mask & GDB_WRITABLE)
354 	    FD_SET (fd, &gdb_notifier.check_masks[1]);
355 	  else
356 	    FD_CLR (fd, &gdb_notifier.check_masks[1]);
357 
358 	  if (mask & GDB_EXCEPTION)
359 	    FD_SET (fd, &gdb_notifier.check_masks[2]);
360 	  else
361 	    FD_CLR (fd, &gdb_notifier.check_masks[2]);
362 
363 	  if (gdb_notifier.num_fds <= fd)
364 	    gdb_notifier.num_fds = fd + 1;
365 	}
366     }
367 
368   file_ptr->proc = proc;
369   file_ptr->client_data = client_data;
370   file_ptr->mask = mask;
371   file_ptr->name = std::move (name);
372   file_ptr->is_ui = is_ui;
373 }
374 
375 /* Return the next file handler to handle, and advance to the next
376    file handler, wrapping around if the end of the list is
377    reached.  */
378 
379 static file_handler *
380 get_next_file_handler_to_handle_and_advance (void)
381 {
382   file_handler *curr_next;
383 
384   /* The first time around, this is still NULL.  */
385   if (gdb_notifier.next_file_handler == NULL)
386     gdb_notifier.next_file_handler = gdb_notifier.first_file_handler;
387 
388   curr_next = gdb_notifier.next_file_handler;
389   gdb_assert (curr_next != NULL);
390 
391   /* Advance.  */
392   gdb_notifier.next_file_handler = curr_next->next_file;
393   /* Wrap around, if necessary.  */
394   if (gdb_notifier.next_file_handler == NULL)
395     gdb_notifier.next_file_handler = gdb_notifier.first_file_handler;
396 
397   return curr_next;
398 }
399 
400 /* Remove the file descriptor FD from the list of monitored fd's:
401    i.e. we don't care anymore about events on the FD.  */
402 void
403 delete_file_handler (int fd)
404 {
405   file_handler *file_ptr, *prev_ptr = NULL;
406   int i;
407 
408   /* Find the entry for the given file.  */
409 
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 == fd)
414 	break;
415     }
416 
417   if (file_ptr == NULL)
418     return;
419 
420 #ifdef HAVE_POLL
421   if (use_poll)
422     {
423       auto iter = std::remove_if (gdb_notifier.poll_fds.begin (),
424 				  gdb_notifier.poll_fds.end (),
425 				  [=] (const pollfd &item)
426 				  {
427 				    return item.fd == fd;
428 				  });
429       gdb_notifier.poll_fds.erase (iter, gdb_notifier.poll_fds.end());
430       gdb_notifier.num_fds--;
431     }
432   else
433 #endif /* HAVE_POLL */
434     {
435       if (file_ptr->mask & GDB_READABLE)
436 	FD_CLR (fd, &gdb_notifier.check_masks[0]);
437       if (file_ptr->mask & GDB_WRITABLE)
438 	FD_CLR (fd, &gdb_notifier.check_masks[1]);
439       if (file_ptr->mask & GDB_EXCEPTION)
440 	FD_CLR (fd, &gdb_notifier.check_masks[2]);
441 
442       /* Find current max fd.  */
443 
444       if ((fd + 1) == gdb_notifier.num_fds)
445 	{
446 	  gdb_notifier.num_fds--;
447 	  for (i = gdb_notifier.num_fds; i; i--)
448 	    {
449 	      if (FD_ISSET (i - 1, &gdb_notifier.check_masks[0])
450 		  || FD_ISSET (i - 1, &gdb_notifier.check_masks[1])
451 		  || FD_ISSET (i - 1, &gdb_notifier.check_masks[2]))
452 		break;
453 	    }
454 	  gdb_notifier.num_fds = i;
455 	}
456     }
457 
458   /* Deactivate the file descriptor, by clearing its mask,
459      so that it will not fire again.  */
460 
461   file_ptr->mask = 0;
462 
463   /* If this file handler was going to be the next one to be handled,
464      advance to the next's next, if any.  */
465   if (gdb_notifier.next_file_handler == file_ptr)
466     {
467       if (file_ptr->next_file == NULL
468 	  && file_ptr == gdb_notifier.first_file_handler)
469 	gdb_notifier.next_file_handler = NULL;
470       else
471 	get_next_file_handler_to_handle_and_advance ();
472     }
473 
474   /* Get rid of the file handler in the file handler list.  */
475   if (file_ptr == gdb_notifier.first_file_handler)
476     gdb_notifier.first_file_handler = file_ptr->next_file;
477   else
478     {
479       for (prev_ptr = gdb_notifier.first_file_handler;
480 	   prev_ptr->next_file != file_ptr;
481 	   prev_ptr = prev_ptr->next_file)
482 	;
483       prev_ptr->next_file = file_ptr->next_file;
484     }
485 
486   delete file_ptr;
487 }
488 
489 /* Handle the given event by calling the procedure associated to the
490    corresponding file handler.  */
491 
492 static void
493 handle_file_event (file_handler *file_ptr, int ready_mask)
494 {
495   int mask;
496 
497   /* See if the desired events (mask) match the received events
498      (ready_mask).  */
499 
500 #ifdef HAVE_POLL
501   if (use_poll)
502     {
503       int error_mask;
504 
505       /* With poll, the ready_mask could have any of three events set
506 	 to 1: POLLHUP, POLLERR, POLLNVAL.  These events cannot be
507 	 used in the requested event mask (events), but they can be
508 	 returned in the return mask (revents).  We need to check for
509 	 those event too, and add them to the mask which will be
510 	 passed to the handler.  */
511 
512       /* POLLHUP means EOF, but can be combined with POLLIN to
513 	 signal more data to read.  */
514       error_mask = POLLHUP | POLLERR | POLLNVAL;
515       mask = ready_mask & (file_ptr->mask | error_mask);
516 
517       if ((mask & (POLLERR | POLLNVAL)) != 0)
518 	{
519 	  /* Work in progress.  We may need to tell somebody
520 	     what kind of error we had.  */
521 	  if (mask & POLLERR)
522 	    warning (_("Error detected on fd %d"), file_ptr->fd);
523 	  if (mask & POLLNVAL)
524 	    warning (_("Invalid or non-`poll'able fd %d"),
525 		     file_ptr->fd);
526 	  file_ptr->error = 1;
527 	}
528       else
529 	file_ptr->error = 0;
530     }
531   else
532 #endif /* HAVE_POLL */
533     {
534       if (ready_mask & GDB_EXCEPTION)
535 	{
536 	  warning (_("Exception condition detected on fd %d"),
537 		   file_ptr->fd);
538 	  file_ptr->error = 1;
539 	}
540       else
541 	file_ptr->error = 0;
542       mask = ready_mask & file_ptr->mask;
543     }
544 
545   /* If there was a match, then call the handler.  */
546   if (mask != 0)
547     {
548       event_loop_ui_debug_printf (file_ptr->is_ui,
549 				  "invoking fd file handler `%s`",
550 				  file_ptr->name.c_str ());
551       file_ptr->proc (file_ptr->error, file_ptr->client_data);
552     }
553 }
554 
555 /* Wait for new events on the monitored file descriptors.  Run the
556    event handler if the first descriptor that is detected by the poll.
557    If BLOCK and if there are no events, this function will block in
558    the call to poll.  Return 1 if an event was handled.  Return -1 if
559    there are no file descriptors to monitor.  Return 1 if an event was
560    handled, otherwise returns 0.  */
561 
562 static int
563 gdb_wait_for_event (int block)
564 {
565   file_handler *file_ptr;
566   int num_found = 0;
567 
568   /* Make sure all output is done before getting another event.  */
569   flush_streams ();
570 
571   if (gdb_notifier.num_fds == 0)
572     return -1;
573 
574   if (block)
575     update_wait_timeout ();
576 
577 #ifdef HAVE_POLL
578   if (use_poll)
579     {
580       int timeout;
581 
582       if (block)
583 	timeout = gdb_notifier.timeout_valid ? gdb_notifier.poll_timeout : -1;
584       else
585 	timeout = 0;
586 
587       num_found = poll (gdb_notifier.poll_fds.data (),
588 			(unsigned long) gdb_notifier.num_fds, timeout);
589 
590       /* Don't print anything if we get out of poll because of a
591 	 signal.  */
592       if (num_found == -1 && errno != EINTR)
593 	perror_with_name (("poll"));
594     }
595   else
596 #endif /* HAVE_POLL */
597     {
598       struct timeval select_timeout;
599       struct timeval *timeout_p;
600 
601       if (block)
602 	timeout_p = gdb_notifier.timeout_valid
603 	  ? &gdb_notifier.select_timeout : NULL;
604       else
605 	{
606 	  memset (&select_timeout, 0, sizeof (select_timeout));
607 	  timeout_p = &select_timeout;
608 	}
609 
610       gdb_notifier.ready_masks[0] = gdb_notifier.check_masks[0];
611       gdb_notifier.ready_masks[1] = gdb_notifier.check_masks[1];
612       gdb_notifier.ready_masks[2] = gdb_notifier.check_masks[2];
613       num_found = gdb_select (gdb_notifier.num_fds,
614 			      &gdb_notifier.ready_masks[0],
615 			      &gdb_notifier.ready_masks[1],
616 			      &gdb_notifier.ready_masks[2],
617 			      timeout_p);
618 
619       /* Clear the masks after an error from select.  */
620       if (num_found == -1)
621 	{
622 	  FD_ZERO (&gdb_notifier.ready_masks[0]);
623 	  FD_ZERO (&gdb_notifier.ready_masks[1]);
624 	  FD_ZERO (&gdb_notifier.ready_masks[2]);
625 
626 	  /* Dont print anything if we got a signal, let gdb handle
627 	     it.  */
628 	  if (errno != EINTR)
629 	    perror_with_name (("select"));
630 	}
631     }
632 
633   /* Avoid looking at poll_fds[i]->revents if no event fired.  */
634   if (num_found <= 0)
635     return 0;
636 
637   /* Run event handlers.  We always run just one handler and go back
638      to polling, in case a handler changes the notifier list.  Since
639      events for sources we haven't consumed yet wake poll/select
640      immediately, no event is lost.  */
641 
642   /* To level the fairness across event descriptors, we handle them in
643      a round-robin-like fashion.  The number and order of descriptors
644      may change between invocations, but this is good enough.  */
645 #ifdef HAVE_POLL
646   if (use_poll)
647     {
648       int i;
649       int mask;
650 
651       while (1)
652 	{
653 	  if (gdb_notifier.next_poll_fds_index >= gdb_notifier.num_fds)
654 	    gdb_notifier.next_poll_fds_index = 0;
655 	  i = gdb_notifier.next_poll_fds_index++;
656 
657 	  gdb_assert (i < gdb_notifier.num_fds);
658 	  if (gdb_notifier.poll_fds[i].revents)
659 	    break;
660 	}
661 
662       for (file_ptr = gdb_notifier.first_file_handler;
663 	   file_ptr != NULL;
664 	   file_ptr = file_ptr->next_file)
665 	{
666 	  if (file_ptr->fd == gdb_notifier.poll_fds[i].fd)
667 	    break;
668 	}
669       gdb_assert (file_ptr != NULL);
670 
671       mask = gdb_notifier.poll_fds[i].revents;
672       handle_file_event (file_ptr, mask);
673       return 1;
674     }
675   else
676 #endif /* HAVE_POLL */
677     {
678       /* See comment about even source fairness above.  */
679       int mask = 0;
680 
681       do
682 	{
683 	  file_ptr = get_next_file_handler_to_handle_and_advance ();
684 
685 	  if (FD_ISSET (file_ptr->fd, &gdb_notifier.ready_masks[0]))
686 	    mask |= GDB_READABLE;
687 	  if (FD_ISSET (file_ptr->fd, &gdb_notifier.ready_masks[1]))
688 	    mask |= GDB_WRITABLE;
689 	  if (FD_ISSET (file_ptr->fd, &gdb_notifier.ready_masks[2]))
690 	    mask |= GDB_EXCEPTION;
691 	}
692       while (mask == 0);
693 
694       handle_file_event (file_ptr, mask);
695       return 1;
696     }
697   return 0;
698 }
699 
700 /* Create a timer that will expire in MS milliseconds from now.  When
701    the timer is ready, PROC will be executed.  At creation, the timer
702    is added to the timers queue.  This queue is kept sorted in order
703    of increasing timers.  Return a handle to the timer struct.  */
704 
705 int
706 create_timer (int ms, timer_handler_func *proc,
707 	      gdb_client_data client_data)
708 {
709   using namespace std::chrono;
710   struct gdb_timer *timer_ptr, *timer_index, *prev_timer;
711 
712   steady_clock::time_point time_now = steady_clock::now ();
713 
714   timer_ptr = new gdb_timer ();
715   timer_ptr->when = time_now + milliseconds (ms);
716   timer_ptr->proc = proc;
717   timer_ptr->client_data = client_data;
718   timer_list.num_timers++;
719   timer_ptr->timer_id = timer_list.num_timers;
720 
721   /* Now add the timer to the timer queue, making sure it is sorted in
722      increasing order of expiration.  */
723 
724   for (timer_index = timer_list.first_timer;
725        timer_index != NULL;
726        timer_index = timer_index->next)
727     {
728       if (timer_index->when > timer_ptr->when)
729 	break;
730     }
731 
732   if (timer_index == timer_list.first_timer)
733     {
734       timer_ptr->next = timer_list.first_timer;
735       timer_list.first_timer = timer_ptr;
736 
737     }
738   else
739     {
740       for (prev_timer = timer_list.first_timer;
741 	   prev_timer->next != timer_index;
742 	   prev_timer = prev_timer->next)
743 	;
744 
745       prev_timer->next = timer_ptr;
746       timer_ptr->next = timer_index;
747     }
748 
749   gdb_notifier.timeout_valid = 0;
750   return timer_ptr->timer_id;
751 }
752 
753 /* There is a chance that the creator of the timer wants to get rid of
754    it before it expires.  */
755 void
756 delete_timer (int id)
757 {
758   struct gdb_timer *timer_ptr, *prev_timer = NULL;
759 
760   /* Find the entry for the given timer.  */
761 
762   for (timer_ptr = timer_list.first_timer; timer_ptr != NULL;
763        timer_ptr = timer_ptr->next)
764     {
765       if (timer_ptr->timer_id == id)
766 	break;
767     }
768 
769   if (timer_ptr == NULL)
770     return;
771   /* Get rid of the timer in the timer list.  */
772   if (timer_ptr == timer_list.first_timer)
773     timer_list.first_timer = timer_ptr->next;
774   else
775     {
776       for (prev_timer = timer_list.first_timer;
777 	   prev_timer->next != timer_ptr;
778 	   prev_timer = prev_timer->next)
779 	;
780       prev_timer->next = timer_ptr->next;
781     }
782   delete timer_ptr;
783 
784   gdb_notifier.timeout_valid = 0;
785 }
786 
787 /* Convert a std::chrono duration to a struct timeval.  */
788 
789 template<typename Duration>
790 static struct timeval
791 duration_cast_timeval (const Duration &d)
792 {
793   using namespace std::chrono;
794   seconds sec = duration_cast<seconds> (d);
795   microseconds msec = duration_cast<microseconds> (d - sec);
796 
797   struct timeval tv;
798   tv.tv_sec = sec.count ();
799   tv.tv_usec = msec.count ();
800   return tv;
801 }
802 
803 /* Update the timeout for the select() or poll().  Returns true if the
804    timer has already expired, false otherwise.  */
805 
806 static int
807 update_wait_timeout (void)
808 {
809   if (timer_list.first_timer != NULL)
810     {
811       using namespace std::chrono;
812       steady_clock::time_point time_now = steady_clock::now ();
813       struct timeval timeout;
814 
815       if (timer_list.first_timer->when < time_now)
816 	{
817 	  /* It expired already.  */
818 	  timeout.tv_sec = 0;
819 	  timeout.tv_usec = 0;
820 	}
821       else
822 	{
823 	  steady_clock::duration d = timer_list.first_timer->when - time_now;
824 	  timeout = duration_cast_timeval (d);
825 	}
826 
827       /* Update the timeout for select/ poll.  */
828 #ifdef HAVE_POLL
829       if (use_poll)
830 	gdb_notifier.poll_timeout = timeout.tv_sec * 1000;
831       else
832 #endif /* HAVE_POLL */
833 	{
834 	  gdb_notifier.select_timeout.tv_sec = timeout.tv_sec;
835 	  gdb_notifier.select_timeout.tv_usec = timeout.tv_usec;
836 	}
837       gdb_notifier.timeout_valid = 1;
838 
839       if (timer_list.first_timer->when < time_now)
840 	return 1;
841     }
842   else
843     gdb_notifier.timeout_valid = 0;
844 
845   return 0;
846 }
847 
848 /* Check whether a timer in the timers queue is ready.  If a timer is
849    ready, call its handler and return.  Update the timeout for the
850    select() or poll() as well.  Return 1 if an event was handled,
851    otherwise returns 0.*/
852 
853 static int
854 poll_timers (void)
855 {
856   if (update_wait_timeout ())
857     {
858       struct gdb_timer *timer_ptr = timer_list.first_timer;
859       timer_handler_func *proc = timer_ptr->proc;
860       gdb_client_data client_data = timer_ptr->client_data;
861 
862       /* Get rid of the timer from the beginning of the list.  */
863       timer_list.first_timer = timer_ptr->next;
864 
865       /* Delete the timer before calling the callback, not after, in
866 	 case the callback itself decides to try deleting the timer
867 	 too.  */
868       delete timer_ptr;
869 
870       /* Call the procedure associated with that timer.  */
871       (proc) (client_data);
872 
873       return 1;
874     }
875 
876   return 0;
877 }
878