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