OSDN Git Service

* gdb.texinfo (Target Description Format): Add version attribute
[pf3gnuchains/pf3gnuchains4x.git] / gdb / ser-base.c
1 /* Generic serial interface functions.
2
3    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, 2003,
4    2004, 2005, 2006, 2007 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 2 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, write to the Free Software
20    Foundation, Inc., 51 Franklin Street, Fifth Floor,
21    Boston, MA 02110-1301, USA.  */
22
23 #include "defs.h"
24 #include "serial.h"
25 #include "ser-base.h"
26 #include "event-loop.h"
27
28 #include "gdb_select.h"
29 #include "gdb_string.h"
30 #include <sys/time.h>
31 #ifdef USE_WIN32API
32 #include <winsock2.h>
33 #endif
34
35
36 static timer_handler_func push_event;
37 static handler_func fd_event;
38
39 /* Event handling for ASYNC serial code.
40
41    At any time the SERIAL device either: has an empty FIFO and is
42    waiting on a FD event; or has a non-empty FIFO/error condition and
43    is constantly scheduling timer events.
44
45    ASYNC only stops pestering its client when it is de-async'ed or it
46    is told to go away. */
47
48 /* Value of scb->async_state: */
49 enum {
50   /* >= 0 (TIMER_SCHEDULED) */
51   /* The ID of the currently scheduled timer event. This state is
52      rarely encountered.  Timer events are one-off so as soon as the
53      event is delivered the state is shanged to NOTHING_SCHEDULED. */
54   FD_SCHEDULED = -1,
55   /* The fd_event() handler is scheduled.  It is called when ever the
56      file descriptor becomes ready. */
57   NOTHING_SCHEDULED = -2
58   /* Either no task is scheduled (just going into ASYNC mode) or a
59      timer event has just gone off and the current state has been
60      forced into nothing scheduled. */
61 };
62
63 /* Identify and schedule the next ASYNC task based on scb->async_state
64    and scb->buf* (the input FIFO).  A state machine is used to avoid
65    the need to make redundant calls into the event-loop - the next
66    scheduled task is only changed when needed. */
67
68 void
69 reschedule (struct serial *scb)
70 {
71   if (serial_is_async_p (scb))
72     {
73       int next_state;
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 /* FD_EVENT: This is scheduled when the input FIFO is empty (and there
128    is no pending error).  As soon as data arrives, it is read into the
129    input FIFO and the client notified.  The client should then drain
130    the FIFO using readchar().  If the FIFO isn't immediatly emptied,
131    push_event() is used to nag the client until it is. */
132
133 static void
134 fd_event (int error, void *context)
135 {
136   struct serial *scb = context;
137   if (error != 0)
138     {
139       scb->bufcnt = SERIAL_ERROR;
140     }
141   else if (scb->bufcnt == 0)
142     {
143       /* Prime the input FIFO.  The readchar() function is used to
144          pull characters out of the buffer.  See also
145          generic_readchar(). */
146       int nr;
147       nr = scb->ops->read_prim (scb, BUFSIZ);
148       if (nr == 0)
149         {
150           scb->bufcnt = SERIAL_EOF;
151         }
152       else if (nr > 0)
153         {
154           scb->bufcnt = nr;
155           scb->bufp = scb->buf;
156         }
157       else
158         {
159           scb->bufcnt = SERIAL_ERROR;
160         }
161     }
162   scb->async_handler (scb, scb->async_context);
163   reschedule (scb);
164 }
165
166 /* PUSH_EVENT: The input FIFO is non-empty (or there is a pending
167    error).  Nag the client until all the data has been read.  In the
168    case of errors, the client will need to close or de-async the
169    device before naging stops. */
170
171 static void
172 push_event (void *context)
173 {
174   struct serial *scb = context;
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         /* 0 chars means timeout.  (We may need to distinguish between EOF
285            & timeouts someday.)  */
286         return SERIAL_TIMEOUT;  
287       else
288         /* Got an error from read.  */
289         return SERIAL_ERROR;    
290     }
291
292   scb->bufcnt = status;
293   scb->bufcnt--;
294   scb->bufp = scb->buf;
295   return *scb->bufp++;
296 }
297
298 /* Perform operations common to both old and new readchar. */
299
300 /* Return the next character from the input FIFO.  If the FIFO is
301    empty, call the SERIAL specific routine to try and read in more
302    characters.
303
304    Initially data from the input FIFO is returned (fd_event()
305    pre-reads the input into that FIFO.  Once that has been emptied,
306    further data is obtained by polling the input FD using the device
307    specific readchar() function.  Note: reschedule() is called after
308    every read.  This is because there is no guarentee that the lower
309    level fd_event() poll_event() code (which also calls reschedule())
310    will be called. */
311
312 int
313 generic_readchar (struct serial *scb, int timeout,
314                   int (do_readchar) (struct serial *scb, int timeout))
315 {
316   int ch;
317   if (scb->bufcnt > 0)
318     {
319       ch = *scb->bufp;
320       scb->bufcnt--;
321       scb->bufp++;
322     }
323   else if (scb->bufcnt < 0)
324     {
325       /* Some errors/eof are are sticky. */
326       ch = scb->bufcnt;
327     }
328   else
329     {
330       ch = do_readchar (scb, timeout);
331       if (ch < 0)
332         {
333           switch ((enum serial_rc) ch)
334             {
335             case SERIAL_EOF:
336             case SERIAL_ERROR:
337               /* Make the error/eof stick. */
338               scb->bufcnt = ch;
339               break;
340             case SERIAL_TIMEOUT:
341               scb->bufcnt = 0;
342               break;
343             }
344         }
345     }
346   /* Read any error output we might have.  */
347   if (scb->error_fd != -1)
348     {
349       ssize_t s;
350       char buf[81];
351
352       for (;;)
353         {
354           char *current;
355           char *newline;
356           int to_read = 80;
357
358           int num_bytes = -1;
359           if (scb->ops->avail)
360             num_bytes = (scb->ops->avail)(scb, scb->error_fd);
361           if (num_bytes != -1)
362             to_read = (num_bytes < to_read) ? num_bytes : to_read;
363
364           if (to_read == 0)
365             break;
366
367           s = read (scb->error_fd, &buf, to_read);
368           if (s == -1)
369             break;
370
371           /* In theory, embedded newlines are not a problem.
372              But for MI, we want each output line to have just
373              one newline for legibility.  So output things
374              in newline chunks.  */
375           buf[s] = '\0';
376           current = buf;
377           while ((newline = strstr (current, "\n")) != NULL)
378             {
379               *newline = '\0';
380               fputs_unfiltered (current, gdb_stderr);
381               fputs_unfiltered ("\n", gdb_stderr);
382               current = newline + 1;
383             }
384           fputs_unfiltered (current, gdb_stderr);
385         }
386     }
387
388   reschedule (scb);
389   return ch;
390 }
391
392 int
393 ser_base_readchar (struct serial *scb, int timeout)
394 {
395   return generic_readchar (scb, timeout, do_ser_base_readchar);
396 }
397
398 int
399 ser_base_write (struct serial *scb, const char *str, int len)
400 {
401   int cc;
402
403   while (len > 0)
404     {
405       cc = scb->ops->write_prim (scb, str, len); 
406
407       if (cc < 0)
408         return 1;
409       len -= cc;
410       str += cc;
411     }
412   return 0;
413 }
414
415 int
416 ser_base_flush_output (struct serial *scb)
417 {
418   return 0;
419 }
420
421 int
422 ser_base_flush_input (struct serial *scb)
423 {
424   if (scb->bufcnt >= 0)
425     {
426       scb->bufcnt = 0;
427       scb->bufp = scb->buf;
428       return 0;
429     }
430   else
431     return SERIAL_ERROR;
432 }
433
434 int
435 ser_base_send_break (struct serial *scb)
436 {
437   return 0;
438 }
439
440 int
441 ser_base_drain_output (struct serial *scb)
442 {
443   return 0;
444 }
445
446 void
447 ser_base_raw (struct serial *scb)
448 {
449   return;                       /* Always in raw mode */
450 }
451
452 serial_ttystate
453 ser_base_get_tty_state (struct serial *scb)
454 {
455   /* allocate a dummy */
456   return (serial_ttystate) XMALLOC (int);
457 }
458
459 int
460 ser_base_set_tty_state (struct serial *scb, serial_ttystate ttystate)
461 {
462   return 0;
463 }
464
465 int
466 ser_base_noflush_set_tty_state (struct serial *scb,
467                                 serial_ttystate new_ttystate,
468                                 serial_ttystate old_ttystate)
469 {
470   return 0;
471 }
472
473 void
474 ser_base_print_tty_state (struct serial *scb, 
475                           serial_ttystate ttystate,
476                           struct ui_file *stream)
477 {
478   /* Nothing to print.  */
479   return;
480 }
481
482 int
483 ser_base_setbaudrate (struct serial *scb, int rate)
484 {
485   return 0;                     /* Never fails! */
486 }
487
488 int
489 ser_base_setstopbits (struct serial *scb, int num)
490 {
491   return 0;                     /* Never fails! */
492 }
493
494 /* Put the SERIAL device into/out-of ASYNC mode.  */
495
496 void
497 ser_base_async (struct serial *scb,
498                 int async_p)
499 {
500   if (async_p)
501     {
502       /* Force a re-schedule. */
503       scb->async_state = NOTHING_SCHEDULED;
504       if (serial_debug_p (scb))
505         fprintf_unfiltered (gdb_stdlog, "[fd%d->asynchronous]\n",
506                             scb->fd);
507       reschedule (scb);
508     }
509   else
510     {
511       if (serial_debug_p (scb))
512         fprintf_unfiltered (gdb_stdlog, "[fd%d->synchronous]\n",
513                             scb->fd);
514       /* De-schedule whatever tasks are currently scheduled. */
515       switch (scb->async_state)
516         {
517         case FD_SCHEDULED:
518           delete_file_handler (scb->fd);
519           break;
520         case NOTHING_SCHEDULED:
521           break;
522         default: /* TIMER SCHEDULED */
523           delete_timer (scb->async_state);
524           break;
525         }
526     }
527 }