ld/testsuite/
[external/binutils.git] / gdb / ser-base.c
1 /* Generic serial interface functions.
2
3    Copyright (C) 1992-1996, 1998-2001, 2003-2012 Free Software
4    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 /* Run the SCB's async handle, and reschedule, if the handler doesn't
127    close SCB.  */
128
129 static void
130 run_async_handler_and_reschedule (struct serial *scb)
131 {
132   int is_open;
133
134   /* Take a reference, so a serial_close call within the handler
135      doesn't make SCB a dangling pointer.  */
136   serial_ref (scb);
137
138   /* Run the handler.  */
139   scb->async_handler (scb, scb->async_context);
140
141   is_open = serial_is_open (scb);
142   serial_unref (scb);
143
144   /* Get ready for more, if not already closed.  */
145   if (is_open)
146     reschedule (scb);
147 }
148
149 /* FD_EVENT: This is scheduled when the input FIFO is empty (and there
150    is no pending error).  As soon as data arrives, it is read into the
151    input FIFO and the client notified.  The client should then drain
152    the FIFO using readchar().  If the FIFO isn't immediatly emptied,
153    push_event() is used to nag the client until it is.  */
154
155 static void
156 fd_event (int error, void *context)
157 {
158   struct serial *scb = context;
159   if (error != 0)
160     {
161       scb->bufcnt = SERIAL_ERROR;
162     }
163   else if (scb->bufcnt == 0)
164     {
165       /* Prime the input FIFO.  The readchar() function is used to
166          pull characters out of the buffer.  See also
167          generic_readchar().  */
168       int nr;
169       nr = scb->ops->read_prim (scb, BUFSIZ);
170       if (nr == 0)
171         {
172           scb->bufcnt = SERIAL_EOF;
173         }
174       else if (nr > 0)
175         {
176           scb->bufcnt = nr;
177           scb->bufp = scb->buf;
178         }
179       else
180         {
181           scb->bufcnt = SERIAL_ERROR;
182         }
183     }
184   run_async_handler_and_reschedule (scb);
185 }
186
187 /* PUSH_EVENT: The input FIFO is non-empty (or there is a pending
188    error).  Nag the client until all the data has been read.  In the
189    case of errors, the client will need to close or de-async the
190    device before naging stops.  */
191
192 static void
193 push_event (void *context)
194 {
195   struct serial *scb = context;
196
197   scb->async_state = NOTHING_SCHEDULED; /* Timers are one-off */
198   run_async_handler_and_reschedule (scb);
199 }
200
201 /* Wait for input on scb, with timeout seconds.  Returns 0 on success,
202    otherwise SERIAL_TIMEOUT or SERIAL_ERROR.  */
203
204 static int
205 ser_base_wait_for (struct serial *scb, int timeout)
206 {
207   while (1)
208     {
209       int numfds;
210       struct timeval tv;
211       fd_set readfds, exceptfds;
212
213       /* NOTE: Some OS's can scramble the READFDS when the select()
214          call fails (ex the kernel with Red Hat 5.2).  Initialize all
215          arguments before each call.  */
216
217       tv.tv_sec = timeout;
218       tv.tv_usec = 0;
219
220       FD_ZERO (&readfds);
221       FD_ZERO (&exceptfds);
222       FD_SET (scb->fd, &readfds);
223       FD_SET (scb->fd, &exceptfds);
224
225       if (timeout >= 0)
226         numfds = gdb_select (scb->fd + 1, &readfds, 0, &exceptfds, &tv);
227       else
228         numfds = gdb_select (scb->fd + 1, &readfds, 0, &exceptfds, 0);
229
230       if (numfds <= 0)
231         {
232           if (numfds == 0)
233             return SERIAL_TIMEOUT;
234           else if (errno == EINTR)
235             continue;
236           else
237             return SERIAL_ERROR;        /* Got an error from select or
238                                            poll.  */
239         }
240
241       return 0;
242     }
243 }
244
245 /* Read a character with user-specified timeout.  TIMEOUT is number of seconds
246    to wait, or -1 to wait forever.  Use timeout of 0 to effect a poll.  Returns
247    char if successful.  Returns -2 if timeout expired, EOF if line dropped
248    dead, or -3 for any other error (see errno in that case).  */
249
250 static int
251 do_ser_base_readchar (struct serial *scb, int timeout)
252 {
253   int status;
254   int delta;
255
256   /* We have to be able to keep the GUI alive here, so we break the
257      original timeout into steps of 1 second, running the "keep the
258      GUI alive" hook each time through the loop.
259
260      Also, timeout = 0 means to poll, so we just set the delta to 0,
261      so we will only go through the loop once.  */
262
263   delta = (timeout == 0 ? 0 : 1);
264   while (1)
265     {
266       /* N.B. The UI may destroy our world (for instance by calling
267          remote_stop,) in which case we want to get out of here as
268          quickly as possible.  It is not safe to touch scb, since
269          someone else might have freed it.  The
270          deprecated_ui_loop_hook signals that we should exit by
271          returning 1.  */
272
273       if (deprecated_ui_loop_hook)
274         {
275           if (deprecated_ui_loop_hook (0))
276             return SERIAL_TIMEOUT;
277         }
278
279       status = ser_base_wait_for (scb, delta);
280       if (timeout > 0)
281         timeout -= delta;
282
283       /* If we got a character or an error back from wait_for, then we can 
284          break from the loop before the timeout is completed.  */
285       if (status != SERIAL_TIMEOUT)
286         break;
287
288       /* If we have exhausted the original timeout, then generate
289          a SERIAL_TIMEOUT, and pass it out of the loop.  */
290       else if (timeout == 0)
291         {
292           status = SERIAL_TIMEOUT;
293           break;
294         }
295     }
296
297   if (status < 0)
298     return status;
299
300   status = scb->ops->read_prim (scb, BUFSIZ);
301
302   if (status <= 0)
303     {
304       if (status == 0)
305         return SERIAL_EOF;
306       else
307         /* Got an error from read.  */
308         return SERIAL_ERROR;    
309     }
310
311   scb->bufcnt = status;
312   scb->bufcnt--;
313   scb->bufp = scb->buf;
314   return *scb->bufp++;
315 }
316
317 /* Perform operations common to both old and new readchar.  */
318
319 /* Return the next character from the input FIFO.  If the FIFO is
320    empty, call the SERIAL specific routine to try and read in more
321    characters.
322
323    Initially data from the input FIFO is returned (fd_event()
324    pre-reads the input into that FIFO.  Once that has been emptied,
325    further data is obtained by polling the input FD using the device
326    specific readchar() function.  Note: reschedule() is called after
327    every read.  This is because there is no guarentee that the lower
328    level fd_event() poll_event() code (which also calls reschedule())
329    will be called.  */
330
331 int
332 generic_readchar (struct serial *scb, int timeout,
333                   int (do_readchar) (struct serial *scb, int timeout))
334 {
335   int ch;
336   if (scb->bufcnt > 0)
337     {
338       ch = *scb->bufp;
339       scb->bufcnt--;
340       scb->bufp++;
341     }
342   else if (scb->bufcnt < 0)
343     {
344       /* Some errors/eof are are sticky.  */
345       ch = scb->bufcnt;
346     }
347   else
348     {
349       ch = do_readchar (scb, timeout);
350       if (ch < 0)
351         {
352           switch ((enum serial_rc) ch)
353             {
354             case SERIAL_EOF:
355             case SERIAL_ERROR:
356               /* Make the error/eof stick.  */
357               scb->bufcnt = ch;
358               break;
359             case SERIAL_TIMEOUT:
360               scb->bufcnt = 0;
361               break;
362             }
363         }
364     }
365   /* Read any error output we might have.  */
366   if (scb->error_fd != -1)
367     {
368       ssize_t s;
369       char buf[81];
370
371       for (;;)
372         {
373           char *current;
374           char *newline;
375           int to_read = 80;
376
377           int num_bytes = -1;
378           if (scb->ops->avail)
379             num_bytes = (scb->ops->avail)(scb, scb->error_fd);
380           if (num_bytes != -1)
381             to_read = (num_bytes < to_read) ? num_bytes : to_read;
382
383           if (to_read == 0)
384             break;
385
386           s = read (scb->error_fd, &buf, to_read);
387           if (s == -1)
388             break;
389           if (s == 0)
390             {
391               /* EOF */
392               close (scb->error_fd);
393               scb->error_fd = -1;
394               break;
395             }
396
397           /* In theory, embedded newlines are not a problem.
398              But for MI, we want each output line to have just
399              one newline for legibility.  So output things
400              in newline chunks.  */
401           buf[s] = '\0';
402           current = buf;
403           while ((newline = strstr (current, "\n")) != NULL)
404             {
405               *newline = '\0';
406               fputs_unfiltered (current, gdb_stderr);
407               fputs_unfiltered ("\n", gdb_stderr);
408               current = newline + 1;
409             }
410           fputs_unfiltered (current, gdb_stderr);
411         }
412     }
413
414   reschedule (scb);
415   return ch;
416 }
417
418 int
419 ser_base_readchar (struct serial *scb, int timeout)
420 {
421   return generic_readchar (scb, timeout, do_ser_base_readchar);
422 }
423
424 int
425 ser_base_write (struct serial *scb, const char *str, int len)
426 {
427   int cc;
428
429   while (len > 0)
430     {
431       cc = scb->ops->write_prim (scb, str, len); 
432
433       if (cc < 0)
434         return 1;
435       len -= cc;
436       str += cc;
437     }
438   return 0;
439 }
440
441 int
442 ser_base_flush_output (struct serial *scb)
443 {
444   return 0;
445 }
446
447 int
448 ser_base_flush_input (struct serial *scb)
449 {
450   if (scb->bufcnt >= 0)
451     {
452       scb->bufcnt = 0;
453       scb->bufp = scb->buf;
454       return 0;
455     }
456   else
457     return SERIAL_ERROR;
458 }
459
460 int
461 ser_base_send_break (struct serial *scb)
462 {
463   return 0;
464 }
465
466 int
467 ser_base_drain_output (struct serial *scb)
468 {
469   return 0;
470 }
471
472 void
473 ser_base_raw (struct serial *scb)
474 {
475   return;                       /* Always in raw mode.  */
476 }
477
478 serial_ttystate
479 ser_base_get_tty_state (struct serial *scb)
480 {
481   /* Allocate a dummy.  */
482   return (serial_ttystate) XMALLOC (int);
483 }
484
485 serial_ttystate
486 ser_base_copy_tty_state (struct serial *scb, serial_ttystate ttystate)
487 {
488   /* Allocate another dummy.  */
489   return (serial_ttystate) XMALLOC (int);
490 }
491
492 int
493 ser_base_set_tty_state (struct serial *scb, serial_ttystate ttystate)
494 {
495   return 0;
496 }
497
498 int
499 ser_base_noflush_set_tty_state (struct serial *scb,
500                                 serial_ttystate new_ttystate,
501                                 serial_ttystate old_ttystate)
502 {
503   return 0;
504 }
505
506 void
507 ser_base_print_tty_state (struct serial *scb, 
508                           serial_ttystate ttystate,
509                           struct ui_file *stream)
510 {
511   /* Nothing to print.  */
512   return;
513 }
514
515 int
516 ser_base_setbaudrate (struct serial *scb, int rate)
517 {
518   return 0;                     /* Never fails!  */
519 }
520
521 int
522 ser_base_setstopbits (struct serial *scb, int num)
523 {
524   return 0;                     /* Never fails!  */
525 }
526
527 /* Put the SERIAL device into/out-of ASYNC mode.  */
528
529 void
530 ser_base_async (struct serial *scb,
531                 int async_p)
532 {
533   if (async_p)
534     {
535       /* Force a re-schedule.  */
536       scb->async_state = NOTHING_SCHEDULED;
537       if (serial_debug_p (scb))
538         fprintf_unfiltered (gdb_stdlog, "[fd%d->asynchronous]\n",
539                             scb->fd);
540       reschedule (scb);
541     }
542   else
543     {
544       if (serial_debug_p (scb))
545         fprintf_unfiltered (gdb_stdlog, "[fd%d->synchronous]\n",
546                             scb->fd);
547       /* De-schedule whatever tasks are currently scheduled.  */
548       switch (scb->async_state)
549         {
550         case FD_SCHEDULED:
551           delete_file_handler (scb->fd);
552           break;
553         case NOTHING_SCHEDULED:
554           break;
555         default: /* TIMER SCHEDULED */
556           delete_timer (scb->async_state);
557           break;
558         }
559     }
560 }