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