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