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