Merge from vendor branch GCC:
[dragonfly.git] / contrib / gdb-6.2.1 / gdb / ser-unix.c
1 /* Serial interface for local (hardwired) serial ports on Un*x like systems
2
3    Copyright 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
4    2003, 2004 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., 59 Temple Place - Suite 330,
21    Boston, MA 02111-1307, USA.  */
22
23 #include "defs.h"
24 #include "serial.h"
25 #include "ser-unix.h"
26
27 #include <fcntl.h>
28 #include <sys/types.h>
29 #include "terminal.h"
30 #include <sys/socket.h>
31 #include <sys/time.h>
32
33 #include "gdb_string.h"
34 #include "event-loop.h"
35
36 #ifdef HAVE_TERMIOS
37
38 struct hardwire_ttystate
39   {
40     struct termios termios;
41   };
42 #endif /* termios */
43
44 #ifdef HAVE_TERMIO
45
46 /* It is believed that all systems which have added job control to SVR3
47    (e.g. sco) have also added termios.  Even if not, trying to figure out
48    all the variations (TIOCGPGRP vs. TCGETPGRP, etc.) would be pretty
49    bewildering.  So we don't attempt it.  */
50
51 struct hardwire_ttystate
52   {
53     struct termio termio;
54   };
55 #endif /* termio */
56
57 #ifdef HAVE_SGTTY
58 struct hardwire_ttystate
59   {
60     struct sgttyb sgttyb;
61     struct tchars tc;
62     struct ltchars ltc;
63     /* Line discipline flags.  */
64     int lmode;
65   };
66 #endif /* sgtty */
67
68 static int hardwire_open (struct serial *scb, const char *name);
69 static void hardwire_raw (struct serial *scb);
70 static int wait_for (struct serial *scb, int timeout);
71 static int hardwire_readchar (struct serial *scb, int timeout);
72 static int do_hardwire_readchar (struct serial *scb, int timeout);
73 static int generic_readchar (struct serial *scb, int timeout,
74                              int (*do_readchar) (struct serial *scb,
75                                                  int timeout));
76 static int rate_to_code (int rate);
77 static int hardwire_setbaudrate (struct serial *scb, int rate);
78 static void hardwire_close (struct serial *scb);
79 static int get_tty_state (struct serial *scb,
80                           struct hardwire_ttystate * state);
81 static int set_tty_state (struct serial *scb,
82                           struct hardwire_ttystate * state);
83 static serial_ttystate hardwire_get_tty_state (struct serial *scb);
84 static int hardwire_set_tty_state (struct serial *scb, serial_ttystate state);
85 static int hardwire_noflush_set_tty_state (struct serial *, serial_ttystate,
86                                            serial_ttystate);
87 static void hardwire_print_tty_state (struct serial *, serial_ttystate,
88                                       struct ui_file *);
89 static int hardwire_drain_output (struct serial *);
90 static int hardwire_flush_output (struct serial *);
91 static int hardwire_flush_input (struct serial *);
92 static int hardwire_send_break (struct serial *);
93 static int hardwire_setstopbits (struct serial *, int);
94
95 static int do_unix_readchar (struct serial *scb, int timeout);
96 static timer_handler_func push_event;
97 static handler_func fd_event;
98 static void reschedule (struct serial *scb);
99
100 void _initialize_ser_hardwire (void);
101
102 /* Open up a real live device for serial I/O */
103
104 static int
105 hardwire_open (struct serial *scb, const char *name)
106 {
107   scb->fd = open (name, O_RDWR);
108   if (scb->fd < 0)
109     return -1;
110
111   return 0;
112 }
113
114 static int
115 get_tty_state (struct serial *scb, struct hardwire_ttystate *state)
116 {
117 #ifdef HAVE_TERMIOS
118   if (tcgetattr (scb->fd, &state->termios) < 0)
119     return -1;
120
121   return 0;
122 #endif
123
124 #ifdef HAVE_TERMIO
125   if (ioctl (scb->fd, TCGETA, &state->termio) < 0)
126     return -1;
127   return 0;
128 #endif
129
130 #ifdef HAVE_SGTTY
131   if (ioctl (scb->fd, TIOCGETP, &state->sgttyb) < 0)
132     return -1;
133   if (ioctl (scb->fd, TIOCGETC, &state->tc) < 0)
134     return -1;
135   if (ioctl (scb->fd, TIOCGLTC, &state->ltc) < 0)
136     return -1;
137   if (ioctl (scb->fd, TIOCLGET, &state->lmode) < 0)
138     return -1;
139
140   return 0;
141 #endif
142 }
143
144 static int
145 set_tty_state (struct serial *scb, struct hardwire_ttystate *state)
146 {
147 #ifdef HAVE_TERMIOS
148   if (tcsetattr (scb->fd, TCSANOW, &state->termios) < 0)
149     return -1;
150
151   return 0;
152 #endif
153
154 #ifdef HAVE_TERMIO
155   if (ioctl (scb->fd, TCSETA, &state->termio) < 0)
156     return -1;
157   return 0;
158 #endif
159
160 #ifdef HAVE_SGTTY
161   if (ioctl (scb->fd, TIOCSETN, &state->sgttyb) < 0)
162     return -1;
163   if (ioctl (scb->fd, TIOCSETC, &state->tc) < 0)
164     return -1;
165   if (ioctl (scb->fd, TIOCSLTC, &state->ltc) < 0)
166     return -1;
167   if (ioctl (scb->fd, TIOCLSET, &state->lmode) < 0)
168     return -1;
169
170   return 0;
171 #endif
172 }
173
174 static serial_ttystate
175 hardwire_get_tty_state (struct serial *scb)
176 {
177   struct hardwire_ttystate *state;
178
179   state = (struct hardwire_ttystate *) xmalloc (sizeof *state);
180
181   if (get_tty_state (scb, state))
182     return NULL;
183
184   return (serial_ttystate) state;
185 }
186
187 static int
188 hardwire_set_tty_state (struct serial *scb, serial_ttystate ttystate)
189 {
190   struct hardwire_ttystate *state;
191
192   state = (struct hardwire_ttystate *) ttystate;
193
194   return set_tty_state (scb, state);
195 }
196
197 static int
198 hardwire_noflush_set_tty_state (struct serial *scb,
199                                 serial_ttystate new_ttystate,
200                                 serial_ttystate old_ttystate)
201 {
202   struct hardwire_ttystate new_state;
203 #ifdef HAVE_SGTTY
204   struct hardwire_ttystate *state = (struct hardwire_ttystate *) old_ttystate;
205 #endif
206
207   new_state = *(struct hardwire_ttystate *) new_ttystate;
208
209   /* Don't change in or out of raw mode; we don't want to flush input.
210      termio and termios have no such restriction; for them flushing input
211      is separate from setting the attributes.  */
212
213 #ifdef HAVE_SGTTY
214   if (state->sgttyb.sg_flags & RAW)
215     new_state.sgttyb.sg_flags |= RAW;
216   else
217     new_state.sgttyb.sg_flags &= ~RAW;
218
219   /* I'm not sure whether this is necessary; the manpage just mentions
220      RAW not CBREAK.  */
221   if (state->sgttyb.sg_flags & CBREAK)
222     new_state.sgttyb.sg_flags |= CBREAK;
223   else
224     new_state.sgttyb.sg_flags &= ~CBREAK;
225 #endif
226
227   return set_tty_state (scb, &new_state);
228 }
229
230 static void
231 hardwire_print_tty_state (struct serial *scb,
232                           serial_ttystate ttystate,
233                           struct ui_file *stream)
234 {
235   struct hardwire_ttystate *state = (struct hardwire_ttystate *) ttystate;
236   int i;
237
238 #ifdef HAVE_TERMIOS
239   fprintf_filtered (stream, "c_iflag = 0x%x, c_oflag = 0x%x,\n",
240                     (int) state->termios.c_iflag,
241                     (int) state->termios.c_oflag);
242   fprintf_filtered (stream, "c_cflag = 0x%x, c_lflag = 0x%x\n",
243                     (int) state->termios.c_cflag,
244                     (int) state->termios.c_lflag);
245 #if 0
246   /* This not in POSIX, and is not really documented by those systems
247      which have it (at least not Sun).  */
248   fprintf_filtered (stream, "c_line = 0x%x.\n", state->termios.c_line);
249 #endif
250   fprintf_filtered (stream, "c_cc: ");
251   for (i = 0; i < NCCS; i += 1)
252     fprintf_filtered (stream, "0x%x ", state->termios.c_cc[i]);
253   fprintf_filtered (stream, "\n");
254 #endif
255
256 #ifdef HAVE_TERMIO
257   fprintf_filtered (stream, "c_iflag = 0x%x, c_oflag = 0x%x,\n",
258                     state->termio.c_iflag, state->termio.c_oflag);
259   fprintf_filtered (stream, "c_cflag = 0x%x, c_lflag = 0x%x, c_line = 0x%x.\n",
260                     state->termio.c_cflag, state->termio.c_lflag,
261                     state->termio.c_line);
262   fprintf_filtered (stream, "c_cc: ");
263   for (i = 0; i < NCC; i += 1)
264     fprintf_filtered (stream, "0x%x ", state->termio.c_cc[i]);
265   fprintf_filtered (stream, "\n");
266 #endif
267
268 #ifdef HAVE_SGTTY
269   fprintf_filtered (stream, "sgttyb.sg_flags = 0x%x.\n",
270                     state->sgttyb.sg_flags);
271
272   fprintf_filtered (stream, "tchars: ");
273   for (i = 0; i < (int) sizeof (struct tchars); i++)
274     fprintf_filtered (stream, "0x%x ", ((unsigned char *) &state->tc)[i]);
275   fprintf_filtered (stream, "\n");
276
277   fprintf_filtered (stream, "ltchars: ");
278   for (i = 0; i < (int) sizeof (struct ltchars); i++)
279     fprintf_filtered (stream, "0x%x ", ((unsigned char *) &state->ltc)[i]);
280   fprintf_filtered (stream, "\n");
281
282   fprintf_filtered (stream, "lmode:  0x%x\n", state->lmode);
283 #endif
284 }
285
286 /* Wait for the output to drain away, as opposed to flushing (discarding) it */
287
288 static int
289 hardwire_drain_output (struct serial *scb)
290 {
291 #ifdef HAVE_TERMIOS
292   return tcdrain (scb->fd);
293 #endif
294
295 #ifdef HAVE_TERMIO
296   return ioctl (scb->fd, TCSBRK, 1);
297 #endif
298
299 #ifdef HAVE_SGTTY
300   /* Get the current state and then restore it using TIOCSETP,
301      which should cause the output to drain and pending input
302      to be discarded. */
303   {
304     struct hardwire_ttystate state;
305     if (get_tty_state (scb, &state))
306       {
307         return (-1);
308       }
309     else
310       {
311         return (ioctl (scb->fd, TIOCSETP, &state.sgttyb));
312       }
313   }
314 #endif
315 }
316
317 static int
318 hardwire_flush_output (struct serial *scb)
319 {
320 #ifdef HAVE_TERMIOS
321   return tcflush (scb->fd, TCOFLUSH);
322 #endif
323
324 #ifdef HAVE_TERMIO
325   return ioctl (scb->fd, TCFLSH, 1);
326 #endif
327
328 #ifdef HAVE_SGTTY
329   /* This flushes both input and output, but we can't do better.  */
330   return ioctl (scb->fd, TIOCFLUSH, 0);
331 #endif
332 }
333
334 static int
335 hardwire_flush_input (struct serial *scb)
336 {
337   ser_unix_flush_input (scb);
338
339 #ifdef HAVE_TERMIOS
340   return tcflush (scb->fd, TCIFLUSH);
341 #endif
342
343 #ifdef HAVE_TERMIO
344   return ioctl (scb->fd, TCFLSH, 0);
345 #endif
346
347 #ifdef HAVE_SGTTY
348   /* This flushes both input and output, but we can't do better.  */
349   return ioctl (scb->fd, TIOCFLUSH, 0);
350 #endif
351 }
352
353 static int
354 hardwire_send_break (struct serial *scb)
355 {
356 #ifdef HAVE_TERMIOS
357   return tcsendbreak (scb->fd, 0);
358 #endif
359
360 #ifdef HAVE_TERMIO
361   return ioctl (scb->fd, TCSBRK, 0);
362 #endif
363
364 #ifdef HAVE_SGTTY
365   {
366     int status;
367     struct timeval timeout;
368
369     status = ioctl (scb->fd, TIOCSBRK, 0);
370
371     /* Can't use usleep; it doesn't exist in BSD 4.2.  */
372     /* Note that if this select() is interrupted by a signal it will not wait
373        the full length of time.  I think that is OK.  */
374     timeout.tv_sec = 0;
375     timeout.tv_usec = 250000;
376     select (0, 0, 0, 0, &timeout);
377     status = ioctl (scb->fd, TIOCCBRK, 0);
378     return status;
379   }
380 #endif
381 }
382
383 static void
384 hardwire_raw (struct serial *scb)
385 {
386   struct hardwire_ttystate state;
387
388   if (get_tty_state (scb, &state))
389     fprintf_unfiltered (gdb_stderr, "get_tty_state failed: %s\n", safe_strerror (errno));
390
391 #ifdef HAVE_TERMIOS
392   state.termios.c_iflag = 0;
393   state.termios.c_oflag = 0;
394   state.termios.c_lflag = 0;
395   state.termios.c_cflag &= ~(CSIZE | PARENB);
396   state.termios.c_cflag |= CLOCAL | CS8;
397   state.termios.c_cc[VMIN] = 0;
398   state.termios.c_cc[VTIME] = 0;
399 #endif
400
401 #ifdef HAVE_TERMIO
402   state.termio.c_iflag = 0;
403   state.termio.c_oflag = 0;
404   state.termio.c_lflag = 0;
405   state.termio.c_cflag &= ~(CSIZE | PARENB);
406   state.termio.c_cflag |= CLOCAL | CS8;
407   state.termio.c_cc[VMIN] = 0;
408   state.termio.c_cc[VTIME] = 0;
409 #endif
410
411 #ifdef HAVE_SGTTY
412   state.sgttyb.sg_flags |= RAW | ANYP;
413   state.sgttyb.sg_flags &= ~(CBREAK | ECHO);
414 #endif
415
416   scb->current_timeout = 0;
417
418   if (set_tty_state (scb, &state))
419     fprintf_unfiltered (gdb_stderr, "set_tty_state failed: %s\n", safe_strerror (errno));
420 }
421
422 /* Wait for input on scb, with timeout seconds.  Returns 0 on success,
423    otherwise SERIAL_TIMEOUT or SERIAL_ERROR.
424
425    For termio{s}, we actually just setup VTIME if necessary, and let the
426    timeout occur in the read() in hardwire_read().
427  */
428
429 /* FIXME: cagney/1999-09-16: Don't replace this with the equivalent
430    ser_unix*() until the old TERMIOS/SGTTY/... timer code has been
431    flushed. . */
432
433 /* NOTE: cagney/1999-09-30: Much of the code below is dead.  The only
434    possible values of the TIMEOUT parameter are ONE and ZERO.
435    Consequently all the code that tries to handle the possability of
436    an overflowed timer is unnecessary. */
437
438 static int
439 wait_for (struct serial *scb, int timeout)
440 {
441 #ifdef HAVE_SGTTY
442   while (1)
443     {
444       struct timeval tv;
445       fd_set readfds;
446       int numfds;
447
448       /* NOTE: Some OS's can scramble the READFDS when the select()
449          call fails (ex the kernel with Red Hat 5.2).  Initialize all
450          arguments before each call. */
451
452       tv.tv_sec = timeout;
453       tv.tv_usec = 0;
454
455       FD_ZERO (&readfds);
456       FD_SET (scb->fd, &readfds);
457
458       if (timeout >= 0)
459         numfds = select (scb->fd + 1, &readfds, 0, 0, &tv);
460       else
461         numfds = select (scb->fd + 1, &readfds, 0, 0, 0);
462
463       if (numfds <= 0)
464         if (numfds == 0)
465           return SERIAL_TIMEOUT;
466         else if (errno == EINTR)
467           continue;
468         else
469           return SERIAL_ERROR;  /* Got an error from select or poll */
470
471       return 0;
472     }
473 #endif /* HAVE_SGTTY */
474
475 #if defined HAVE_TERMIO || defined HAVE_TERMIOS
476   if (timeout == scb->current_timeout)
477     return 0;
478
479   scb->current_timeout = timeout;
480
481   {
482     struct hardwire_ttystate state;
483
484     if (get_tty_state (scb, &state))
485       fprintf_unfiltered (gdb_stderr, "get_tty_state failed: %s\n", safe_strerror (errno));
486
487 #ifdef HAVE_TERMIOS
488     if (timeout < 0)
489       {
490         /* No timeout.  */
491         state.termios.c_cc[VTIME] = 0;
492         state.termios.c_cc[VMIN] = 1;
493       }
494     else
495       {
496         state.termios.c_cc[VMIN] = 0;
497         state.termios.c_cc[VTIME] = timeout * 10;
498         if (state.termios.c_cc[VTIME] != timeout * 10)
499           {
500
501             /* If c_cc is an 8-bit signed character, we can't go 
502                bigger than this.  If it is always unsigned, we could use
503                25.  */
504
505             scb->current_timeout = 12;
506             state.termios.c_cc[VTIME] = scb->current_timeout * 10;
507             scb->timeout_remaining = timeout - scb->current_timeout;
508           }
509       }
510 #endif
511
512 #ifdef HAVE_TERMIO
513     if (timeout < 0)
514       {
515         /* No timeout.  */
516         state.termio.c_cc[VTIME] = 0;
517         state.termio.c_cc[VMIN] = 1;
518       }
519     else
520       {
521         state.termio.c_cc[VMIN] = 0;
522         state.termio.c_cc[VTIME] = timeout * 10;
523         if (state.termio.c_cc[VTIME] != timeout * 10)
524           {
525             /* If c_cc is an 8-bit signed character, we can't go 
526                bigger than this.  If it is always unsigned, we could use
527                25.  */
528
529             scb->current_timeout = 12;
530             state.termio.c_cc[VTIME] = scb->current_timeout * 10;
531             scb->timeout_remaining = timeout - scb->current_timeout;
532           }
533       }
534 #endif
535
536     if (set_tty_state (scb, &state))
537       fprintf_unfiltered (gdb_stderr, "set_tty_state failed: %s\n", safe_strerror (errno));
538
539     return 0;
540   }
541 #endif /* HAVE_TERMIO || HAVE_TERMIOS */
542 }
543
544 /* Read a character with user-specified timeout.  TIMEOUT is number of seconds
545    to wait, or -1 to wait forever.  Use timeout of 0 to effect a poll.  Returns
546    char if successful.  Returns SERIAL_TIMEOUT if timeout expired, EOF if line
547    dropped dead, or SERIAL_ERROR for any other error (see errno in that case).  */
548
549 /* FIXME: cagney/1999-09-16: Don't replace this with the equivalent
550    ser_unix*() until the old TERMIOS/SGTTY/... timer code has been
551    flushed. */
552
553 /* NOTE: cagney/1999-09-16: This function is not identical to
554    ser_unix_readchar() as part of replacing it with ser_unix*()
555    merging will be required - this code handles the case where read()
556    times out due to no data while ser_unix_readchar() doesn't expect
557    that. */
558
559 static int
560 do_hardwire_readchar (struct serial *scb, int timeout)
561 {
562   int status, delta;
563   int detach = 0;
564
565   if (timeout > 0)
566     timeout++;
567
568   /* We have to be able to keep the GUI alive here, so we break the original
569      timeout into steps of 1 second, running the "keep the GUI alive" hook 
570      each time through the loop.
571      Also, timeout = 0 means to poll, so we just set the delta to 0, so we
572      will only go through the loop once. */
573
574   delta = (timeout == 0 ? 0 : 1);
575   while (1)
576     {
577
578       /* N.B. The UI may destroy our world (for instance by calling
579          remote_stop,) in which case we want to get out of here as
580          quickly as possible.  It is not safe to touch scb, since
581          someone else might have freed it.  The
582          deprecated_ui_loop_hook signals that we should exit by
583          returning 1.  */
584
585       if (deprecated_ui_loop_hook)
586         detach = deprecated_ui_loop_hook (0);
587
588       if (detach)
589         return SERIAL_TIMEOUT;
590
591       scb->timeout_remaining = (timeout < 0 ? timeout : timeout - delta);
592       status = wait_for (scb, delta);
593
594       if (status < 0)
595         return status;
596
597       status = read (scb->fd, scb->buf, BUFSIZ);
598
599       if (status <= 0)
600         {
601           if (status == 0)
602             {
603               /* Zero characters means timeout (it could also be EOF, but
604                  we don't (yet at least) distinguish).  */
605               if (scb->timeout_remaining > 0)
606                 {
607                   timeout = scb->timeout_remaining;
608                   continue;
609                 }
610               else if (scb->timeout_remaining < 0)
611                 continue;
612               else
613                 return SERIAL_TIMEOUT;
614             }
615           else if (errno == EINTR)
616             continue;
617           else
618             return SERIAL_ERROR;        /* Got an error from read */
619         }
620
621       scb->bufcnt = status;
622       scb->bufcnt--;
623       scb->bufp = scb->buf;
624       return *scb->bufp++;
625     }
626 }
627
628 static int
629 hardwire_readchar (struct serial *scb, int timeout)
630 {
631   return generic_readchar (scb, timeout, do_hardwire_readchar);
632 }
633
634
635 #ifndef B19200
636 #define B19200 EXTA
637 #endif
638
639 #ifndef B38400
640 #define B38400 EXTB
641 #endif
642
643 /* Translate baud rates from integers to damn B_codes.  Unix should
644    have outgrown this crap years ago, but even POSIX wouldn't buck it.  */
645
646 static struct
647 {
648   int rate;
649   int code;
650 }
651 baudtab[] =
652 {
653   {
654     50, B50
655   }
656   ,
657   {
658     75, B75
659   }
660   ,
661   {
662     110, B110
663   }
664   ,
665   {
666     134, B134
667   }
668   ,
669   {
670     150, B150
671   }
672   ,
673   {
674     200, B200
675   }
676   ,
677   {
678     300, B300
679   }
680   ,
681   {
682     600, B600
683   }
684   ,
685   {
686     1200, B1200
687   }
688   ,
689   {
690     1800, B1800
691   }
692   ,
693   {
694     2400, B2400
695   }
696   ,
697   {
698     4800, B4800
699   }
700   ,
701   {
702     9600, B9600
703   }
704   ,
705   {
706     19200, B19200
707   }
708   ,
709   {
710     38400, B38400
711   }
712   ,
713 #ifdef B57600
714   {
715     57600, B57600
716   }
717   ,
718 #endif
719 #ifdef B115200
720   {
721     115200, B115200
722   }
723   ,
724 #endif
725 #ifdef B230400
726   {
727     230400, B230400
728   }
729   ,
730 #endif
731 #ifdef B460800
732   {
733     460800, B460800
734   }
735   ,
736 #endif
737   {
738     -1, -1
739   }
740   ,
741 };
742
743 static int
744 rate_to_code (int rate)
745 {
746   int i;
747
748   for (i = 0; baudtab[i].rate != -1; i++)
749     {
750       /* test for perfect macth. */
751       if (rate == baudtab[i].rate)
752         return baudtab[i].code;
753       else
754         {
755           /* check if it is in between valid values. */
756           if (rate < baudtab[i].rate)
757             {
758               if (i)
759                 {
760                   warning ("Invalid baud rate %d.  Closest values are %d and %d.",
761                             rate, baudtab[i - 1].rate, baudtab[i].rate);
762                 }
763               else
764                 {
765                   warning ("Invalid baud rate %d.  Minimum value is %d.",
766                             rate, baudtab[0].rate);
767                 }
768               return -1;
769             }
770         }
771     }
772  
773   /* The requested speed was too large. */
774   warning ("Invalid baud rate %d.  Maximum value is %d.",
775             rate, baudtab[i - 1].rate);
776   return -1;
777 }
778
779 static int
780 hardwire_setbaudrate (struct serial *scb, int rate)
781 {
782   struct hardwire_ttystate state;
783   int baud_code = rate_to_code (rate);
784   
785   if (baud_code < 0)
786     {
787       /* The baud rate was not valid.
788          A warning has already been issued. */
789       errno = EINVAL;
790       return -1;
791     }
792
793   if (get_tty_state (scb, &state))
794     return -1;
795
796 #ifdef HAVE_TERMIOS
797   cfsetospeed (&state.termios, baud_code);
798   cfsetispeed (&state.termios, baud_code);
799 #endif
800
801 #ifdef HAVE_TERMIO
802 #ifndef CIBAUD
803 #define CIBAUD CBAUD
804 #endif
805
806   state.termio.c_cflag &= ~(CBAUD | CIBAUD);
807   state.termio.c_cflag |= baud_code;
808 #endif
809
810 #ifdef HAVE_SGTTY
811   state.sgttyb.sg_ispeed = baud_code;
812   state.sgttyb.sg_ospeed = baud_code;
813 #endif
814
815   return set_tty_state (scb, &state);
816 }
817
818 static int
819 hardwire_setstopbits (struct serial *scb, int num)
820 {
821   struct hardwire_ttystate state;
822   int newbit;
823
824   if (get_tty_state (scb, &state))
825     return -1;
826
827   switch (num)
828     {
829     case SERIAL_1_STOPBITS:
830       newbit = 0;
831       break;
832     case SERIAL_1_AND_A_HALF_STOPBITS:
833     case SERIAL_2_STOPBITS:
834       newbit = 1;
835       break;
836     default:
837       return 1;
838     }
839
840 #ifdef HAVE_TERMIOS
841   if (!newbit)
842     state.termios.c_cflag &= ~CSTOPB;
843   else
844     state.termios.c_cflag |= CSTOPB;    /* two bits */
845 #endif
846
847 #ifdef HAVE_TERMIO
848   if (!newbit)
849     state.termio.c_cflag &= ~CSTOPB;
850   else
851     state.termio.c_cflag |= CSTOPB;     /* two bits */
852 #endif
853
854 #ifdef HAVE_SGTTY
855   return 0;                     /* sgtty doesn't support this */
856 #endif
857
858   return set_tty_state (scb, &state);
859 }
860
861 static void
862 hardwire_close (struct serial *scb)
863 {
864   if (scb->fd < 0)
865     return;
866
867   close (scb->fd);
868   scb->fd = -1;
869 }
870
871 \f
872 /* Generic operations used by all UNIX/FD based serial interfaces. */
873
874 serial_ttystate
875 ser_unix_nop_get_tty_state (struct serial *scb)
876 {
877   /* allocate a dummy */
878   return (serial_ttystate) XMALLOC (int);
879 }
880
881 int
882 ser_unix_nop_set_tty_state (struct serial *scb, serial_ttystate ttystate)
883 {
884   return 0;
885 }
886
887 void
888 ser_unix_nop_raw (struct serial *scb)
889 {
890   return;                       /* Always in raw mode */
891 }
892
893 /* Wait for input on scb, with timeout seconds.  Returns 0 on success,
894    otherwise SERIAL_TIMEOUT or SERIAL_ERROR. */
895
896 int
897 ser_unix_wait_for (struct serial *scb, int timeout)
898 {
899   while (1)
900     {
901       int numfds;
902       struct timeval tv;
903       fd_set readfds, exceptfds;
904
905       /* NOTE: Some OS's can scramble the READFDS when the select()
906          call fails (ex the kernel with Red Hat 5.2).  Initialize all
907          arguments before each call. */
908
909       tv.tv_sec = timeout;
910       tv.tv_usec = 0;
911
912       FD_ZERO (&readfds);
913       FD_ZERO (&exceptfds);
914       FD_SET (scb->fd, &readfds);
915       FD_SET (scb->fd, &exceptfds);
916
917       if (timeout >= 0)
918         numfds = select (scb->fd + 1, &readfds, 0, &exceptfds, &tv);
919       else
920         numfds = select (scb->fd + 1, &readfds, 0, &exceptfds, 0);
921
922       if (numfds <= 0)
923         {
924           if (numfds == 0)
925             return SERIAL_TIMEOUT;
926           else if (errno == EINTR)
927             continue;
928           else
929             return SERIAL_ERROR;        /* Got an error from select or poll */
930         }
931
932       return 0;
933     }
934 }
935
936 /* Read a character with user-specified timeout.  TIMEOUT is number of seconds
937    to wait, or -1 to wait forever.  Use timeout of 0 to effect a poll.  Returns
938    char if successful.  Returns -2 if timeout expired, EOF if line dropped
939    dead, or -3 for any other error (see errno in that case). */
940
941 static int
942 do_unix_readchar (struct serial *scb, int timeout)
943 {
944   int status;
945   int delta;
946
947   /* We have to be able to keep the GUI alive here, so we break the original
948      timeout into steps of 1 second, running the "keep the GUI alive" hook 
949      each time through the loop.
950
951      Also, timeout = 0 means to poll, so we just set the delta to 0, so we
952      will only go through the loop once. */
953
954   delta = (timeout == 0 ? 0 : 1);
955   while (1)
956     {
957
958       /* N.B. The UI may destroy our world (for instance by calling
959          remote_stop,) in which case we want to get out of here as
960          quickly as possible.  It is not safe to touch scb, since
961          someone else might have freed it.  The
962          deprecated_ui_loop_hook signals that we should exit by
963          returning 1.  */
964
965       if (deprecated_ui_loop_hook)
966         {
967           if (deprecated_ui_loop_hook (0))
968             return SERIAL_TIMEOUT;
969         }
970
971       status = ser_unix_wait_for (scb, delta);
972       if (timeout > 0)
973         timeout -= delta;
974
975       /* If we got a character or an error back from wait_for, then we can 
976          break from the loop before the timeout is completed. */
977
978       if (status != SERIAL_TIMEOUT)
979         {
980           break;
981         }
982
983       /* If we have exhausted the original timeout, then generate
984          a SERIAL_TIMEOUT, and pass it out of the loop. */
985
986       else if (timeout == 0)
987         {
988           status = SERIAL_TIMEOUT;
989           break;
990         }
991     }
992
993   if (status < 0)
994     return status;
995
996   while (1)
997     {
998       status = read (scb->fd, scb->buf, BUFSIZ);
999       if (status != -1 || errno != EINTR)
1000         break;
1001     }
1002
1003   if (status <= 0)
1004     {
1005       if (status == 0)
1006         return SERIAL_TIMEOUT;  /* 0 chars means timeout [may need to
1007                                    distinguish between EOF & timeouts
1008                                    someday] */
1009       else
1010         return SERIAL_ERROR;    /* Got an error from read */
1011     }
1012
1013   scb->bufcnt = status;
1014   scb->bufcnt--;
1015   scb->bufp = scb->buf;
1016   return *scb->bufp++;
1017 }
1018
1019 /* Perform operations common to both old and new readchar. */
1020
1021 /* Return the next character from the input FIFO.  If the FIFO is
1022    empty, call the SERIAL specific routine to try and read in more
1023    characters.
1024
1025    Initially data from the input FIFO is returned (fd_event()
1026    pre-reads the input into that FIFO.  Once that has been emptied,
1027    further data is obtained by polling the input FD using the device
1028    specific readchar() function.  Note: reschedule() is called after
1029    every read.  This is because there is no guarentee that the lower
1030    level fd_event() poll_event() code (which also calls reschedule())
1031    will be called. */
1032
1033 static int
1034 generic_readchar (struct serial *scb, int timeout,
1035                   int (do_readchar) (struct serial *scb, int timeout))
1036 {
1037   int ch;
1038   if (scb->bufcnt > 0)
1039     {
1040       ch = *scb->bufp;
1041       scb->bufcnt--;
1042       scb->bufp++;
1043     }
1044   else if (scb->bufcnt < 0)
1045     {
1046       /* Some errors/eof are are sticky. */
1047       ch = scb->bufcnt;
1048     }
1049   else
1050     {
1051       ch = do_readchar (scb, timeout);
1052       if (ch < 0)
1053         {
1054           switch ((enum serial_rc) ch)
1055             {
1056             case SERIAL_EOF:
1057             case SERIAL_ERROR:
1058               /* Make the error/eof stick. */
1059               scb->bufcnt = ch;
1060               break;
1061             case SERIAL_TIMEOUT:
1062               scb->bufcnt = 0;
1063               break;
1064             }
1065         }
1066     }
1067   reschedule (scb);
1068   return ch;
1069 }
1070
1071 int
1072 ser_unix_readchar (struct serial *scb, int timeout)
1073 {
1074   return generic_readchar (scb, timeout, do_unix_readchar);
1075 }
1076
1077 int
1078 ser_unix_nop_noflush_set_tty_state (struct serial *scb,
1079                                     serial_ttystate new_ttystate,
1080                                     serial_ttystate old_ttystate)
1081 {
1082   return 0;
1083 }
1084
1085 void
1086 ser_unix_nop_print_tty_state (struct serial *scb, 
1087                               serial_ttystate ttystate,
1088                               struct ui_file *stream)
1089 {
1090   /* Nothing to print.  */
1091   return;
1092 }
1093
1094 int
1095 ser_unix_nop_setbaudrate (struct serial *scb, int rate)
1096 {
1097   return 0;                     /* Never fails! */
1098 }
1099
1100 int
1101 ser_unix_nop_setstopbits (struct serial *scb, int num)
1102 {
1103   return 0;                     /* Never fails! */
1104 }
1105
1106 int
1107 ser_unix_write (struct serial *scb, const char *str, int len)
1108 {
1109   int cc;
1110
1111   while (len > 0)
1112     {
1113       cc = write (scb->fd, str, len);
1114
1115       if (cc < 0)
1116         return 1;
1117       len -= cc;
1118       str += cc;
1119     }
1120   return 0;
1121 }
1122
1123 int
1124 ser_unix_nop_flush_output (struct serial *scb)
1125 {
1126   return 0;
1127 }
1128
1129 int
1130 ser_unix_flush_input (struct serial *scb)
1131 {
1132   if (scb->bufcnt >= 0)
1133     {
1134       scb->bufcnt = 0;
1135       scb->bufp = scb->buf;
1136       return 0;
1137     }
1138   else
1139     return SERIAL_ERROR;
1140 }
1141
1142 int
1143 ser_unix_nop_send_break (struct serial *scb)
1144 {
1145   return 0;
1146 }
1147
1148 int
1149 ser_unix_nop_drain_output (struct serial *scb)
1150 {
1151   return 0;
1152 }
1153
1154
1155 \f
1156 /* Event handling for ASYNC serial code.
1157
1158    At any time the SERIAL device either: has an empty FIFO and is
1159    waiting on a FD event; or has a non-empty FIFO/error condition and
1160    is constantly scheduling timer events.
1161
1162    ASYNC only stops pestering its client when it is de-async'ed or it
1163    is told to go away. */
1164
1165 /* Value of scb->async_state: */
1166 enum {
1167   /* >= 0 (TIMER_SCHEDULED) */
1168   /* The ID of the currently scheduled timer event. This state is
1169      rarely encountered.  Timer events are one-off so as soon as the
1170      event is delivered the state is shanged to NOTHING_SCHEDULED. */
1171   FD_SCHEDULED = -1,
1172   /* The fd_event() handler is scheduled.  It is called when ever the
1173      file descriptor becomes ready. */
1174   NOTHING_SCHEDULED = -2
1175   /* Either no task is scheduled (just going into ASYNC mode) or a
1176      timer event has just gone off and the current state has been
1177      forced into nothing scheduled. */
1178 };
1179
1180 /* Identify and schedule the next ASYNC task based on scb->async_state
1181    and scb->buf* (the input FIFO).  A state machine is used to avoid
1182    the need to make redundant calls into the event-loop - the next
1183    scheduled task is only changed when needed. */
1184
1185 static void
1186 reschedule (struct serial *scb)
1187 {
1188   if (serial_is_async_p (scb))
1189     {
1190       int next_state;
1191       switch (scb->async_state)
1192         {
1193         case FD_SCHEDULED:
1194           if (scb->bufcnt == 0)
1195             next_state = FD_SCHEDULED;
1196           else
1197             {
1198               delete_file_handler (scb->fd);
1199               next_state = create_timer (0, push_event, scb);
1200             }
1201           break;
1202         case NOTHING_SCHEDULED:
1203           if (scb->bufcnt == 0)
1204             {
1205               add_file_handler (scb->fd, fd_event, scb);
1206               next_state = FD_SCHEDULED;
1207             }
1208           else
1209             {
1210               next_state = create_timer (0, push_event, scb);
1211             }
1212           break;
1213         default: /* TIMER SCHEDULED */
1214           if (scb->bufcnt == 0)
1215             {
1216               delete_timer (scb->async_state);
1217               add_file_handler (scb->fd, fd_event, scb);
1218               next_state = FD_SCHEDULED;
1219             }
1220           else
1221             next_state = scb->async_state;
1222           break;
1223         }
1224       if (serial_debug_p (scb))
1225         {
1226           switch (next_state)
1227             {
1228             case FD_SCHEDULED:
1229               if (scb->async_state != FD_SCHEDULED)
1230                 fprintf_unfiltered (gdb_stdlog, "[fd%d->fd-scheduled]\n",
1231                                     scb->fd);
1232               break;
1233             default: /* TIMER SCHEDULED */
1234               if (scb->async_state == FD_SCHEDULED)
1235                 fprintf_unfiltered (gdb_stdlog, "[fd%d->timer-scheduled]\n",
1236                                     scb->fd);
1237               break;
1238             }
1239         }
1240       scb->async_state = next_state;
1241     }
1242 }
1243
1244 /* FD_EVENT: This is scheduled when the input FIFO is empty (and there
1245    is no pending error).  As soon as data arrives, it is read into the
1246    input FIFO and the client notified.  The client should then drain
1247    the FIFO using readchar().  If the FIFO isn't immediatly emptied,
1248    push_event() is used to nag the client until it is. */
1249
1250 static void
1251 fd_event (int error, void *context)
1252 {
1253   struct serial *scb = context;
1254   if (error != 0)
1255     {
1256       scb->bufcnt = SERIAL_ERROR;
1257     }
1258   else if (scb->bufcnt == 0)
1259     {
1260       /* Prime the input FIFO.  The readchar() function is used to
1261          pull characters out of the buffer.  See also
1262          generic_readchar(). */
1263       int nr;
1264       do
1265         {
1266           nr = read (scb->fd, scb->buf, BUFSIZ);
1267         }
1268       while (nr == -1 && errno == EINTR);
1269       if (nr == 0)
1270         {
1271           scb->bufcnt = SERIAL_EOF;
1272         }
1273       else if (nr > 0)
1274         {
1275           scb->bufcnt = nr;
1276           scb->bufp = scb->buf;
1277         }
1278       else
1279         {
1280           scb->bufcnt = SERIAL_ERROR;
1281         }
1282     }
1283   scb->async_handler (scb, scb->async_context);
1284   reschedule (scb);
1285 }
1286
1287 /* PUSH_EVENT: The input FIFO is non-empty (or there is a pending
1288    error).  Nag the client until all the data has been read.  In the
1289    case of errors, the client will need to close or de-async the
1290    device before naging stops. */
1291
1292 static void
1293 push_event (void *context)
1294 {
1295   struct serial *scb = context;
1296   scb->async_state = NOTHING_SCHEDULED; /* Timers are one-off */
1297   scb->async_handler (scb, scb->async_context);
1298   /* re-schedule */
1299   reschedule (scb);
1300 }
1301
1302 /* Put the SERIAL device into/out-of ASYNC mode.  */
1303
1304 void
1305 ser_unix_async (struct serial *scb,
1306                 int async_p)
1307 {
1308   if (async_p)
1309     {
1310       /* Force a re-schedule. */
1311       scb->async_state = NOTHING_SCHEDULED;
1312       if (serial_debug_p (scb))
1313         fprintf_unfiltered (gdb_stdlog, "[fd%d->asynchronous]\n",
1314                             scb->fd);
1315       reschedule (scb);
1316     }
1317   else
1318     {
1319       if (serial_debug_p (scb))
1320         fprintf_unfiltered (gdb_stdlog, "[fd%d->synchronous]\n",
1321                             scb->fd);
1322       /* De-schedule whatever tasks are currently scheduled. */
1323       switch (scb->async_state)
1324         {
1325         case FD_SCHEDULED:
1326           delete_file_handler (scb->fd);
1327           break;
1328         case NOTHING_SCHEDULED:
1329           break;
1330         default: /* TIMER SCHEDULED */
1331           delete_timer (scb->async_state);
1332           break;
1333         }
1334     }
1335 }
1336
1337 void
1338 _initialize_ser_hardwire (void)
1339 {
1340   struct serial_ops *ops = XMALLOC (struct serial_ops);
1341   memset (ops, 0, sizeof (struct serial_ops));
1342   ops->name = "hardwire";
1343   ops->next = 0;
1344   ops->open = hardwire_open;
1345   ops->close = hardwire_close;
1346   /* FIXME: Don't replace this with the equivalent ser_unix*() until
1347      the old TERMIOS/SGTTY/... timer code has been flushed. cagney
1348      1999-09-16. */
1349   ops->readchar = hardwire_readchar;
1350   ops->write = ser_unix_write;
1351   ops->flush_output = hardwire_flush_output;
1352   ops->flush_input = hardwire_flush_input;
1353   ops->send_break = hardwire_send_break;
1354   ops->go_raw = hardwire_raw;
1355   ops->get_tty_state = hardwire_get_tty_state;
1356   ops->set_tty_state = hardwire_set_tty_state;
1357   ops->print_tty_state = hardwire_print_tty_state;
1358   ops->noflush_set_tty_state = hardwire_noflush_set_tty_state;
1359   ops->setbaudrate = hardwire_setbaudrate;
1360   ops->setstopbits = hardwire_setstopbits;
1361   ops->drain_output = hardwire_drain_output;
1362   ops->async = ser_unix_async;
1363   serial_add_interface (ops);
1364 }