xref: /dflybsd-src/contrib/gdb-7/gdb/ser-base.c (revision 0eb2eccd5a86ef7dd7492d2651de55c3589f23d7)
1 /* Generic serial interface functions.
2 
3    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, 2003,
4    2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
5 
6    This file is part of GDB.
7 
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12 
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17 
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
20 
21 #include "defs.h"
22 #include "serial.h"
23 #include "ser-base.h"
24 #include "event-loop.h"
25 
26 #include "gdb_select.h"
27 #include "gdb_string.h"
28 #include <sys/time.h>
29 #ifdef USE_WIN32API
30 #include <winsock2.h>
31 #endif
32 
33 
34 static timer_handler_func push_event;
35 static handler_func fd_event;
36 
37 /* Event handling for ASYNC serial code.
38 
39    At any time the SERIAL device either: has an empty FIFO and is
40    waiting on a FD event; or has a non-empty FIFO/error condition and
41    is constantly scheduling timer events.
42 
43    ASYNC only stops pestering its client when it is de-async'ed or it
44    is told to go away. */
45 
46 /* Value of scb->async_state: */
47 enum {
48   /* >= 0 (TIMER_SCHEDULED) */
49   /* The ID of the currently scheduled timer event. This state is
50      rarely encountered.  Timer events are one-off so as soon as the
51      event is delivered the state is shanged to NOTHING_SCHEDULED. */
52   FD_SCHEDULED = -1,
53   /* The fd_event() handler is scheduled.  It is called when ever the
54      file descriptor becomes ready. */
55   NOTHING_SCHEDULED = -2
56   /* Either no task is scheduled (just going into ASYNC mode) or a
57      timer event has just gone off and the current state has been
58      forced into nothing scheduled. */
59 };
60 
61 /* Identify and schedule the next ASYNC task based on scb->async_state
62    and scb->buf* (the input FIFO).  A state machine is used to avoid
63    the need to make redundant calls into the event-loop - the next
64    scheduled task is only changed when needed. */
65 
66 static void
67 reschedule (struct serial *scb)
68 {
69   if (serial_is_async_p (scb))
70     {
71       int next_state;
72 
73       switch (scb->async_state)
74 	{
75 	case FD_SCHEDULED:
76 	  if (scb->bufcnt == 0)
77 	    next_state = FD_SCHEDULED;
78 	  else
79 	    {
80 	      delete_file_handler (scb->fd);
81 	      next_state = create_timer (0, push_event, scb);
82 	    }
83 	  break;
84 	case NOTHING_SCHEDULED:
85 	  if (scb->bufcnt == 0)
86 	    {
87 	      add_file_handler (scb->fd, fd_event, scb);
88 	      next_state = FD_SCHEDULED;
89 	    }
90 	  else
91 	    {
92 	      next_state = create_timer (0, push_event, scb);
93 	    }
94 	  break;
95 	default: /* TIMER SCHEDULED */
96 	  if (scb->bufcnt == 0)
97 	    {
98 	      delete_timer (scb->async_state);
99 	      add_file_handler (scb->fd, fd_event, scb);
100 	      next_state = FD_SCHEDULED;
101 	    }
102 	  else
103 	    next_state = scb->async_state;
104 	  break;
105 	}
106       if (serial_debug_p (scb))
107 	{
108 	  switch (next_state)
109 	    {
110 	    case FD_SCHEDULED:
111 	      if (scb->async_state != FD_SCHEDULED)
112 		fprintf_unfiltered (gdb_stdlog, "[fd%d->fd-scheduled]\n",
113 				    scb->fd);
114 	      break;
115 	    default: /* TIMER SCHEDULED */
116 	      if (scb->async_state == FD_SCHEDULED)
117 		fprintf_unfiltered (gdb_stdlog, "[fd%d->timer-scheduled]\n",
118 				    scb->fd);
119 	      break;
120 	    }
121 	}
122       scb->async_state = next_state;
123     }
124 }
125 
126 /* FD_EVENT: This is scheduled when the input FIFO is empty (and there
127    is no pending error).  As soon as data arrives, it is read into the
128    input FIFO and the client notified.  The client should then drain
129    the FIFO using readchar().  If the FIFO isn't immediatly emptied,
130    push_event() is used to nag the client until it is. */
131 
132 static void
133 fd_event (int error, void *context)
134 {
135   struct serial *scb = context;
136   if (error != 0)
137     {
138       scb->bufcnt = SERIAL_ERROR;
139     }
140   else if (scb->bufcnt == 0)
141     {
142       /* Prime the input FIFO.  The readchar() function is used to
143          pull characters out of the buffer.  See also
144          generic_readchar(). */
145       int nr;
146       nr = scb->ops->read_prim (scb, BUFSIZ);
147       if (nr == 0)
148 	{
149 	  scb->bufcnt = SERIAL_EOF;
150 	}
151       else if (nr > 0)
152 	{
153 	  scb->bufcnt = nr;
154 	  scb->bufp = scb->buf;
155 	}
156       else
157 	{
158 	  scb->bufcnt = SERIAL_ERROR;
159 	}
160     }
161   scb->async_handler (scb, scb->async_context);
162   reschedule (scb);
163 }
164 
165 /* PUSH_EVENT: The input FIFO is non-empty (or there is a pending
166    error).  Nag the client until all the data has been read.  In the
167    case of errors, the client will need to close or de-async the
168    device before naging stops. */
169 
170 static void
171 push_event (void *context)
172 {
173   struct serial *scb = context;
174 
175   scb->async_state = NOTHING_SCHEDULED; /* Timers are one-off */
176   scb->async_handler (scb, scb->async_context);
177   /* re-schedule */
178   reschedule (scb);
179 }
180 
181 /* Wait for input on scb, with timeout seconds.  Returns 0 on success,
182    otherwise SERIAL_TIMEOUT or SERIAL_ERROR. */
183 
184 static int
185 ser_base_wait_for (struct serial *scb, int timeout)
186 {
187   while (1)
188     {
189       int numfds;
190       struct timeval tv;
191       fd_set readfds, exceptfds;
192 
193       /* NOTE: Some OS's can scramble the READFDS when the select()
194          call fails (ex the kernel with Red Hat 5.2).  Initialize all
195          arguments before each call. */
196 
197       tv.tv_sec = timeout;
198       tv.tv_usec = 0;
199 
200       FD_ZERO (&readfds);
201       FD_ZERO (&exceptfds);
202       FD_SET (scb->fd, &readfds);
203       FD_SET (scb->fd, &exceptfds);
204 
205       if (timeout >= 0)
206 	numfds = gdb_select (scb->fd + 1, &readfds, 0, &exceptfds, &tv);
207       else
208 	numfds = gdb_select (scb->fd + 1, &readfds, 0, &exceptfds, 0);
209 
210       if (numfds <= 0)
211 	{
212 	  if (numfds == 0)
213 	    return SERIAL_TIMEOUT;
214 	  else if (errno == EINTR)
215 	    continue;
216 	  else
217 	    return SERIAL_ERROR;	/* Got an error from select or poll */
218 	}
219 
220       return 0;
221     }
222 }
223 
224 /* Read a character with user-specified timeout.  TIMEOUT is number of seconds
225    to wait, or -1 to wait forever.  Use timeout of 0 to effect a poll.  Returns
226    char if successful.  Returns -2 if timeout expired, EOF if line dropped
227    dead, or -3 for any other error (see errno in that case). */
228 
229 static int
230 do_ser_base_readchar (struct serial *scb, int timeout)
231 {
232   int status;
233   int delta;
234 
235   /* We have to be able to keep the GUI alive here, so we break the
236      original timeout into steps of 1 second, running the "keep the
237      GUI alive" hook each time through the loop.
238 
239      Also, timeout = 0 means to poll, so we just set the delta to 0,
240      so we will only go through the loop once.  */
241 
242   delta = (timeout == 0 ? 0 : 1);
243   while (1)
244     {
245       /* N.B. The UI may destroy our world (for instance by calling
246          remote_stop,) in which case we want to get out of here as
247          quickly as possible.  It is not safe to touch scb, since
248          someone else might have freed it.  The
249          deprecated_ui_loop_hook signals that we should exit by
250          returning 1.  */
251 
252       if (deprecated_ui_loop_hook)
253 	{
254 	  if (deprecated_ui_loop_hook (0))
255 	    return SERIAL_TIMEOUT;
256 	}
257 
258       status = ser_base_wait_for (scb, delta);
259       if (timeout > 0)
260         timeout -= delta;
261 
262       /* If we got a character or an error back from wait_for, then we can
263          break from the loop before the timeout is completed. */
264       if (status != SERIAL_TIMEOUT)
265 	break;
266 
267       /* If we have exhausted the original timeout, then generate
268          a SERIAL_TIMEOUT, and pass it out of the loop. */
269       else if (timeout == 0)
270 	{
271 	  status = SERIAL_TIMEOUT;
272 	  break;
273 	}
274     }
275 
276   if (status < 0)
277     return status;
278 
279   status = scb->ops->read_prim (scb, BUFSIZ);
280 
281   if (status <= 0)
282     {
283       if (status == 0)
284         return SERIAL_EOF;
285       else
286 	/* Got an error from read.  */
287 	return SERIAL_ERROR;
288     }
289 
290   scb->bufcnt = status;
291   scb->bufcnt--;
292   scb->bufp = scb->buf;
293   return *scb->bufp++;
294 }
295 
296 /* Perform operations common to both old and new readchar. */
297 
298 /* Return the next character from the input FIFO.  If the FIFO is
299    empty, call the SERIAL specific routine to try and read in more
300    characters.
301 
302    Initially data from the input FIFO is returned (fd_event()
303    pre-reads the input into that FIFO.  Once that has been emptied,
304    further data is obtained by polling the input FD using the device
305    specific readchar() function.  Note: reschedule() is called after
306    every read.  This is because there is no guarentee that the lower
307    level fd_event() poll_event() code (which also calls reschedule())
308    will be called. */
309 
310 int
311 generic_readchar (struct serial *scb, int timeout,
312 		  int (do_readchar) (struct serial *scb, int timeout))
313 {
314   int ch;
315   if (scb->bufcnt > 0)
316     {
317       ch = *scb->bufp;
318       scb->bufcnt--;
319       scb->bufp++;
320     }
321   else if (scb->bufcnt < 0)
322     {
323       /* Some errors/eof are are sticky. */
324       ch = scb->bufcnt;
325     }
326   else
327     {
328       ch = do_readchar (scb, timeout);
329       if (ch < 0)
330 	{
331 	  switch ((enum serial_rc) ch)
332 	    {
333 	    case SERIAL_EOF:
334 	    case SERIAL_ERROR:
335 	      /* Make the error/eof stick. */
336 	      scb->bufcnt = ch;
337 	      break;
338 	    case SERIAL_TIMEOUT:
339 	      scb->bufcnt = 0;
340 	      break;
341 	    }
342 	}
343     }
344   /* Read any error output we might have.  */
345   if (scb->error_fd != -1)
346     {
347       ssize_t s;
348       char buf[81];
349 
350       for (;;)
351         {
352  	  char *current;
353  	  char *newline;
354 	  int to_read = 80;
355 
356 	  int num_bytes = -1;
357 	  if (scb->ops->avail)
358 	    num_bytes = (scb->ops->avail)(scb, scb->error_fd);
359 	  if (num_bytes != -1)
360 	    to_read = (num_bytes < to_read) ? num_bytes : to_read;
361 
362 	  if (to_read == 0)
363 	    break;
364 
365 	  s = read (scb->error_fd, &buf, to_read);
366 	  if (s == -1)
367 	    break;
368 	  if (s == 0)
369 	    {
370 	      /* EOF */
371 	      close (scb->error_fd);
372 	      scb->error_fd = -1;
373 	      break;
374 	    }
375 
376 	  /* In theory, embedded newlines are not a problem.
377 	     But for MI, we want each output line to have just
378 	     one newline for legibility.  So output things
379 	     in newline chunks.  */
380 	  buf[s] = '\0';
381 	  current = buf;
382 	  while ((newline = strstr (current, "\n")) != NULL)
383 	    {
384 	      *newline = '\0';
385 	      fputs_unfiltered (current, gdb_stderr);
386 	      fputs_unfiltered ("\n", gdb_stderr);
387 	      current = newline + 1;
388 	    }
389 	  fputs_unfiltered (current, gdb_stderr);
390 	}
391     }
392 
393   reschedule (scb);
394   return ch;
395 }
396 
397 int
398 ser_base_readchar (struct serial *scb, int timeout)
399 {
400   return generic_readchar (scb, timeout, do_ser_base_readchar);
401 }
402 
403 int
404 ser_base_write (struct serial *scb, const char *str, int len)
405 {
406   int cc;
407 
408   while (len > 0)
409     {
410       cc = scb->ops->write_prim (scb, str, len);
411 
412       if (cc < 0)
413 	return 1;
414       len -= cc;
415       str += cc;
416     }
417   return 0;
418 }
419 
420 int
421 ser_base_flush_output (struct serial *scb)
422 {
423   return 0;
424 }
425 
426 int
427 ser_base_flush_input (struct serial *scb)
428 {
429   if (scb->bufcnt >= 0)
430     {
431       scb->bufcnt = 0;
432       scb->bufp = scb->buf;
433       return 0;
434     }
435   else
436     return SERIAL_ERROR;
437 }
438 
439 int
440 ser_base_send_break (struct serial *scb)
441 {
442   return 0;
443 }
444 
445 int
446 ser_base_drain_output (struct serial *scb)
447 {
448   return 0;
449 }
450 
451 void
452 ser_base_raw (struct serial *scb)
453 {
454   return;			/* Always in raw mode */
455 }
456 
457 serial_ttystate
458 ser_base_get_tty_state (struct serial *scb)
459 {
460   /* allocate a dummy */
461   return (serial_ttystate) XMALLOC (int);
462 }
463 
464 int
465 ser_base_set_tty_state (struct serial *scb, serial_ttystate ttystate)
466 {
467   return 0;
468 }
469 
470 int
471 ser_base_noflush_set_tty_state (struct serial *scb,
472 				serial_ttystate new_ttystate,
473 				serial_ttystate old_ttystate)
474 {
475   return 0;
476 }
477 
478 void
479 ser_base_print_tty_state (struct serial *scb,
480 			  serial_ttystate ttystate,
481 			  struct ui_file *stream)
482 {
483   /* Nothing to print.  */
484   return;
485 }
486 
487 int
488 ser_base_setbaudrate (struct serial *scb, int rate)
489 {
490   return 0;			/* Never fails! */
491 }
492 
493 int
494 ser_base_setstopbits (struct serial *scb, int num)
495 {
496   return 0;			/* Never fails! */
497 }
498 
499 /* Put the SERIAL device into/out-of ASYNC mode.  */
500 
501 void
502 ser_base_async (struct serial *scb,
503 		int async_p)
504 {
505   if (async_p)
506     {
507       /* Force a re-schedule. */
508       scb->async_state = NOTHING_SCHEDULED;
509       if (serial_debug_p (scb))
510 	fprintf_unfiltered (gdb_stdlog, "[fd%d->asynchronous]\n",
511 			    scb->fd);
512       reschedule (scb);
513     }
514   else
515     {
516       if (serial_debug_p (scb))
517 	fprintf_unfiltered (gdb_stdlog, "[fd%d->synchronous]\n",
518 			    scb->fd);
519       /* De-schedule whatever tasks are currently scheduled. */
520       switch (scb->async_state)
521 	{
522 	case FD_SCHEDULED:
523 	  delete_file_handler (scb->fd);
524 	  break;
525 	case NOTHING_SCHEDULED:
526 	  break;
527 	default: /* TIMER SCHEDULED */
528 	  delete_timer (scb->async_state);
529 	  break;
530 	}
531     }
532 }
533