Automatic date update in version.in
[binutils-gdb.git] / gdb / ser-base.c
blobccf38d2202b6142a5454687bd9efa12f5a23ba2f
1 /* Generic serial interface functions.
3 Copyright (C) 1992-2024 Free Software Foundation, Inc.
5 This file is part of GDB.
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.
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.
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/>. */
20 #include "serial.h"
21 #include "ser-base.h"
22 #include "gdbsupport/event-loop.h"
24 #include "gdbsupport/gdb_select.h"
25 #include "gdbsupport/gdb_sys_time.h"
26 #ifdef USE_WIN32API
27 #include <winsock2.h>
28 #endif
31 static timer_handler_func push_event;
32 static handler_func fd_event;
34 /* Event handling for ASYNC serial code.
36 At any time the SERIAL device either: has an empty FIFO and is
37 waiting on a FD event; or has a non-empty FIFO/error condition and
38 is constantly scheduling timer events.
40 ASYNC only stops pestering its client when it is de-async'ed or it
41 is told to go away. */
43 /* Value of scb->async_state: */
44 enum {
45 /* When >= 0, this contains the ID of the currently scheduled timer event.
46 This state is rarely encountered. Timer events are one-off so as soon as
47 the event is delivered the state is changed to NOTHING_SCHEDULED. */
49 /* The fd_event() handler is scheduled. It is called when ever the
50 file descriptor becomes ready. */
51 FD_SCHEDULED = -1,
53 /* Either no task is scheduled (just going into ASYNC mode) or a
54 timer event has just gone off and the current state has been
55 forced into nothing scheduled. */
56 NOTHING_SCHEDULED = -2
59 /* Identify and schedule the next ASYNC task based on scb->async_state
60 and scb->buf* (the input FIFO). A state machine is used to avoid
61 the need to make redundant calls into the event-loop - the next
62 scheduled task is only changed when needed. */
64 static void
65 reschedule (struct serial *scb)
67 if (serial_is_async_p (scb))
69 int next_state;
71 switch (scb->async_state)
73 case FD_SCHEDULED:
74 if (scb->bufcnt == 0)
75 next_state = FD_SCHEDULED;
76 else
78 delete_file_handler (scb->fd);
79 next_state = create_timer (0, push_event, scb);
81 break;
82 case NOTHING_SCHEDULED:
83 if (scb->bufcnt == 0)
85 add_file_handler (scb->fd, fd_event, scb, "serial");
86 next_state = FD_SCHEDULED;
88 else
90 next_state = create_timer (0, push_event, scb);
92 break;
93 default: /* TIMER SCHEDULED */
94 if (scb->bufcnt == 0)
96 delete_timer (scb->async_state);
97 add_file_handler (scb->fd, fd_event, scb, "serial");
98 next_state = FD_SCHEDULED;
100 else
101 next_state = scb->async_state;
102 break;
104 if (serial_debug_p (scb))
106 switch (next_state)
108 case FD_SCHEDULED:
109 if (scb->async_state != FD_SCHEDULED)
110 gdb_printf (gdb_stdlog, "[fd%d->fd-scheduled]\n",
111 scb->fd);
112 break;
113 default: /* TIMER SCHEDULED */
114 if (scb->async_state == FD_SCHEDULED)
115 gdb_printf (gdb_stdlog, "[fd%d->timer-scheduled]\n",
116 scb->fd);
117 break;
120 scb->async_state = next_state;
124 /* Run the SCB's async handle, and reschedule, if the handler doesn't
125 close SCB. */
127 static void
128 run_async_handler_and_reschedule (struct serial *scb)
130 int is_open;
132 /* Take a reference, so a serial_close call within the handler
133 doesn't make SCB a dangling pointer. */
134 serial_ref (scb);
136 /* Run the handler. */
137 scb->async_handler (scb, scb->async_context);
139 is_open = serial_is_open (scb);
140 serial_unref (scb);
142 /* Get ready for more, if not already closed. */
143 if (is_open)
144 reschedule (scb);
147 /* FD_EVENT: This is scheduled when the input FIFO is empty (and there
148 is no pending error). As soon as data arrives, it is read into the
149 input FIFO and the client notified. The client should then drain
150 the FIFO using readchar(). If the FIFO isn't immediatly emptied,
151 push_event() is used to nag the client until it is. */
153 static void
154 fd_event (int error, void *context)
156 struct serial *scb = (struct serial *) context;
157 if (error != 0)
159 scb->bufcnt = SERIAL_ERROR;
161 else if (scb->bufcnt == 0)
163 /* Prime the input FIFO. The readchar() function is used to
164 pull characters out of the buffer. See also
165 generic_readchar(). */
166 int nr;
170 nr = scb->ops->read_prim (scb, BUFSIZ);
172 while (nr < 0 && errno == EINTR);
174 if (nr == 0)
176 scb->bufcnt = SERIAL_EOF;
178 else if (nr > 0)
180 scb->bufcnt = nr;
181 scb->bufp = scb->buf;
183 else
185 scb->bufcnt = SERIAL_ERROR;
188 run_async_handler_and_reschedule (scb);
191 /* PUSH_EVENT: The input FIFO is non-empty (or there is a pending
192 error). Nag the client until all the data has been read. In the
193 case of errors, the client will need to close or de-async the
194 device before nagging stops. */
196 static void
197 push_event (void *context)
199 struct serial *scb = (struct serial *) context;
201 scb->async_state = NOTHING_SCHEDULED; /* Timers are one-off */
202 run_async_handler_and_reschedule (scb);
205 /* Wait for input on scb, with timeout seconds. Returns 0 on success,
206 otherwise SERIAL_TIMEOUT or SERIAL_ERROR. */
208 /* NOTE: Some of the code below is dead. The only possible values of
209 the TIMEOUT parameter are ONE and ZERO. OTOH, we should probably
210 get rid of the deprecated_ui_loop_hook call in do_ser_base_readchar
211 instead and support infinite time outs here. */
213 static int
214 ser_base_wait_for (struct serial *scb, int timeout)
216 while (1)
218 int numfds;
219 struct timeval tv;
220 fd_set readfds, exceptfds;
221 int nfds;
223 /* NOTE: Some OS's can scramble the READFDS when the select()
224 call fails (ex the kernel with Red Hat 5.2). Initialize all
225 arguments before each call. */
227 tv.tv_sec = timeout;
228 tv.tv_usec = 0;
230 FD_ZERO (&readfds);
231 FD_ZERO (&exceptfds);
232 FD_SET (scb->fd, &readfds);
233 FD_SET (scb->fd, &exceptfds);
235 QUIT;
237 nfds = scb->fd + 1;
238 if (timeout >= 0)
239 numfds = interruptible_select (nfds, &readfds, 0, &exceptfds, &tv);
240 else
241 numfds = interruptible_select (nfds, &readfds, 0, &exceptfds, 0);
243 if (numfds <= 0)
245 if (numfds == 0)
246 return SERIAL_TIMEOUT;
247 else if (errno == EINTR)
248 continue;
249 else
250 return SERIAL_ERROR; /* Got an error from select or
251 poll. */
254 return 0;
258 /* Read any error output we might have. */
260 static void
261 ser_base_read_error_fd (struct serial *scb, int close_fd)
263 if (scb->error_fd != -1)
265 ssize_t s;
266 char buf[GDB_MI_MSG_WIDTH + 1];
268 for (;;)
270 char *current;
271 char *newline;
272 int to_read = GDB_MI_MSG_WIDTH;
273 int num_bytes = -1;
275 if (scb->ops->avail)
276 num_bytes = (scb->ops->avail)(scb, scb->error_fd);
278 if (num_bytes != -1)
279 to_read = (num_bytes < to_read) ? num_bytes : to_read;
281 if (to_read == 0)
282 break;
284 s = read (scb->error_fd, &buf, to_read);
285 if ((s == -1) || (s == 0 && !close_fd))
286 break;
288 if (s == 0 && close_fd)
290 /* End of file. */
291 if (serial_is_async_p (scb))
292 delete_file_handler (scb->error_fd);
293 close (scb->error_fd);
294 scb->error_fd = -1;
295 break;
298 /* In theory, embedded newlines are not a problem.
299 But for MI, we want each output line to have just
300 one newline for legibility. So output things
301 in newline chunks. */
302 gdb_assert (s > 0 && s <= GDB_MI_MSG_WIDTH);
303 buf[s] = '\0';
304 current = buf;
305 while ((newline = strstr (current, "\n")) != NULL)
307 *newline = '\0';
308 gdb_puts (current, gdb_stderr);
309 gdb_puts ("\n", gdb_stderr);
310 current = newline + 1;
313 gdb_puts (current, gdb_stderr);
318 /* Event-loop callback for a serial's error_fd. Flushes any error
319 output we might have. */
321 static void
322 handle_error_fd (int error, gdb_client_data client_data)
324 serial *scb = (serial *) client_data;
326 ser_base_read_error_fd (scb, 0);
329 /* Read a character with user-specified timeout. TIMEOUT is number of
330 seconds to wait, or -1 to wait forever. Use timeout of 0 to effect
331 a poll. Returns char if successful. Returns SERIAL_TIMEOUT if
332 timeout expired, SERIAL_EOF if line dropped dead, or SERIAL_ERROR
333 for any other error (see errno in that case). */
335 static int
336 do_ser_base_readchar (struct serial *scb, int timeout)
338 int status;
339 int delta;
341 /* We have to be able to keep the GUI alive here, so we break the
342 original timeout into steps of 1 second, running the "keep the
343 GUI alive" hook each time through the loop.
345 Also, timeout = 0 means to poll, so we just set the delta to 0,
346 so we will only go through the loop once. */
348 delta = (timeout == 0 ? 0 : 1);
349 while (1)
351 /* N.B. The UI may destroy our world (for instance by calling
352 remote_stop,) in which case we want to get out of here as
353 quickly as possible. It is not safe to touch scb, since
354 someone else might have freed it. The
355 deprecated_ui_loop_hook signals that we should exit by
356 returning 1. */
358 if (deprecated_ui_loop_hook)
360 if (deprecated_ui_loop_hook (0))
361 return SERIAL_TIMEOUT;
364 status = ser_base_wait_for (scb, delta);
365 if (timeout > 0)
366 timeout -= delta;
368 /* If we got a character or an error back from wait_for, then we can
369 break from the loop before the timeout is completed. */
370 if (status != SERIAL_TIMEOUT)
371 break;
373 /* If we have exhausted the original timeout, then generate
374 a SERIAL_TIMEOUT, and pass it out of the loop. */
375 else if (timeout == 0)
377 status = SERIAL_TIMEOUT;
378 break;
381 /* We also need to check and consume the stderr because it could
382 come before the stdout for some stubs. If we just sit and wait
383 for stdout, we would hit a deadlock for that case. */
384 ser_base_read_error_fd (scb, 0);
387 if (status < 0)
388 return status;
392 status = scb->ops->read_prim (scb, BUFSIZ);
394 while (status < 0 && errno == EINTR);
396 if (status <= 0)
398 if (status == 0)
399 return SERIAL_EOF;
400 else
401 /* Got an error from read. */
402 return SERIAL_ERROR;
405 scb->bufcnt = status;
406 scb->bufcnt--;
407 scb->bufp = scb->buf;
408 return *scb->bufp++;
411 /* Perform operations common to both old and new readchar. */
413 /* Return the next character from the input FIFO. If the FIFO is
414 empty, call the SERIAL specific routine to try and read in more
415 characters.
417 Initially data from the input FIFO is returned (fd_event()
418 pre-reads the input into that FIFO. Once that has been emptied,
419 further data is obtained by polling the input FD using the device
420 specific readchar() function. Note: reschedule() is called after
421 every read. This is because there is no guarentee that the lower
422 level fd_event() poll_event() code (which also calls reschedule())
423 will be called. */
426 generic_readchar (struct serial *scb, int timeout,
427 int (do_readchar) (struct serial *scb, int timeout))
429 int ch;
430 if (scb->bufcnt > 0)
432 ch = *scb->bufp;
433 scb->bufcnt--;
434 scb->bufp++;
436 else if (scb->bufcnt < 0)
438 /* Some errors/eof are are sticky. */
439 ch = scb->bufcnt;
441 else
443 ch = do_readchar (scb, timeout);
444 if (ch < 0)
446 switch ((enum serial_rc) ch)
448 case SERIAL_EOF:
449 case SERIAL_ERROR:
450 /* Make the error/eof stick. */
451 scb->bufcnt = ch;
452 break;
453 case SERIAL_TIMEOUT:
454 scb->bufcnt = 0;
455 break;
460 /* Read any error output we might have. */
461 ser_base_read_error_fd (scb, 1);
463 reschedule (scb);
464 return ch;
468 ser_base_readchar (struct serial *scb, int timeout)
470 return generic_readchar (scb, timeout, do_ser_base_readchar);
473 void
474 ser_base_write (struct serial *scb, const void *buf, size_t count)
476 const char *str = (const char *) buf;
477 int cc;
479 while (count > 0)
481 QUIT;
483 cc = scb->ops->write_prim (scb, str, count);
485 if (cc < 0)
487 if (errno == EINTR)
488 continue;
489 perror_with_name ("error while writing");
491 count -= cc;
492 str += cc;
497 ser_base_flush_output (struct serial *scb)
499 return 0;
503 ser_base_flush_input (struct serial *scb)
505 if (scb->bufcnt >= 0)
507 scb->bufcnt = 0;
508 scb->bufp = scb->buf;
509 return 0;
511 else
512 return SERIAL_ERROR;
515 void
516 ser_base_send_break (struct serial *scb)
521 ser_base_drain_output (struct serial *scb)
523 return 0;
526 void
527 ser_base_raw (struct serial *scb)
529 return; /* Always in raw mode. */
532 serial_ttystate
533 ser_base_get_tty_state (struct serial *scb)
535 /* Allocate a dummy. */
536 return (serial_ttystate) XNEW (int);
539 serial_ttystate
540 ser_base_copy_tty_state (struct serial *scb, serial_ttystate ttystate)
542 /* Allocate another dummy. */
543 return (serial_ttystate) XNEW (int);
547 ser_base_set_tty_state (struct serial *scb, serial_ttystate ttystate)
549 return 0;
552 void
553 ser_base_print_tty_state (struct serial *scb,
554 serial_ttystate ttystate,
555 struct ui_file *stream)
557 /* Nothing to print. */
558 return;
561 void
562 ser_base_setbaudrate (struct serial *scb, int rate)
564 /* Never fails! */
568 ser_base_setstopbits (struct serial *scb, int num)
570 return 0; /* Never fails! */
573 /* Implement the "setparity" serial_ops callback. */
576 ser_base_setparity (struct serial *scb, int parity)
578 return 0; /* Never fails! */
581 /* Put the SERIAL device into/out-of ASYNC mode. */
583 void
584 ser_base_async (struct serial *scb,
585 int async_p)
587 if (async_p)
589 /* Force a re-schedule. */
590 scb->async_state = NOTHING_SCHEDULED;
591 if (serial_debug_p (scb))
592 gdb_printf (gdb_stdlog, "[fd%d->asynchronous]\n",
593 scb->fd);
594 reschedule (scb);
596 if (scb->error_fd != -1)
597 add_file_handler (scb->error_fd, handle_error_fd, scb, "serial-error");
599 else
601 if (serial_debug_p (scb))
602 gdb_printf (gdb_stdlog, "[fd%d->synchronous]\n",
603 scb->fd);
604 /* De-schedule whatever tasks are currently scheduled. */
605 switch (scb->async_state)
607 case FD_SCHEDULED:
608 delete_file_handler (scb->fd);
609 break;
610 case NOTHING_SCHEDULED:
611 break;
612 default: /* TIMER SCHEDULED */
613 delete_timer (scb->async_state);
614 break;
617 if (scb->error_fd != -1)
618 delete_file_handler (scb->error_fd);