2012-06-11 Pedro Alves <palves@redhat.com>
[platform/upstream/binutils.git] / gdb / serial.c
1 /* Generic serial interface routines
2
3    Copyright (C) 1992-2002, 2004-2012 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include <ctype.h>
22 #include "serial.h"
23 #include "gdb_string.h"
24 #include "gdbcmd.h"
25
26 extern void _initialize_serial (void);
27
28 /* Is serial being debugged?  */
29
30 static int global_serial_debug_p;
31
32 /* Linked list of serial I/O handlers.  */
33
34 static struct serial_ops *serial_ops_list = NULL;
35
36 /* This is the last serial stream opened.  Used by connect command.  */
37
38 static struct serial *last_serial_opened = NULL;
39
40 /* Pointer to list of scb's.  */
41
42 static struct serial *scb_base;
43
44 /* Non-NULL gives filename which contains a recording of the remote session,
45    suitable for playback by gdbserver.  */
46
47 static char *serial_logfile = NULL;
48 static struct ui_file *serial_logfp = NULL;
49
50 static struct serial_ops *serial_interface_lookup (const char *);
51 static void serial_logchar (struct ui_file *stream,
52                             int ch_type, int ch, int timeout);
53 static const char logbase_hex[] = "hex";
54 static const char logbase_octal[] = "octal";
55 static const char logbase_ascii[] = "ascii";
56 static const char *const logbase_enums[] =
57 {logbase_hex, logbase_octal, logbase_ascii, NULL};
58 static const char *serial_logbase = logbase_ascii;
59 \f
60
61 static int serial_current_type = 0;
62
63 /* Log char CH of type CHTYPE, with TIMEOUT.  */
64
65 /* Define bogus char to represent a BREAK.  Should be careful to choose a value
66    that can't be confused with a normal char, or an error code.  */
67 #define SERIAL_BREAK 1235
68
69 static void
70 serial_logchar (struct ui_file *stream, int ch_type, int ch, int timeout)
71 {
72   if (ch_type != serial_current_type)
73     {
74       fprintf_unfiltered (stream, "\n%c ", ch_type);
75       serial_current_type = ch_type;
76     }
77
78   if (serial_logbase != logbase_ascii)
79     fputc_unfiltered (' ', stream);
80
81   switch (ch)
82     {
83     case SERIAL_TIMEOUT:
84       fprintf_unfiltered (stream, "<Timeout: %d seconds>", timeout);
85       return;
86     case SERIAL_ERROR:
87       fprintf_unfiltered (stream, "<Error: %s>", safe_strerror (errno));
88       return;
89     case SERIAL_EOF:
90       fputs_unfiltered ("<Eof>", stream);
91       return;
92     case SERIAL_BREAK:
93       fputs_unfiltered ("<Break>", stream);
94       return;
95     default:
96       if (serial_logbase == logbase_hex)
97         fprintf_unfiltered (stream, "%02x", ch & 0xff);
98       else if (serial_logbase == logbase_octal)
99         fprintf_unfiltered (stream, "%03o", ch & 0xff);
100       else
101         switch (ch)
102           {
103           case '\\':
104             fputs_unfiltered ("\\\\", stream);
105             break;
106           case '\b':
107             fputs_unfiltered ("\\b", stream);
108             break;
109           case '\f':
110             fputs_unfiltered ("\\f", stream);
111             break;
112           case '\n':
113             fputs_unfiltered ("\\n", stream);
114             break;
115           case '\r':
116             fputs_unfiltered ("\\r", stream);
117             break;
118           case '\t':
119             fputs_unfiltered ("\\t", stream);
120             break;
121           case '\v':
122             fputs_unfiltered ("\\v", stream);
123             break;
124           default:
125             fprintf_unfiltered (stream,
126                                 isprint (ch) ? "%c" : "\\x%02x", ch & 0xFF);
127             break;
128           }
129     }
130 }
131
132 void
133 serial_log_command (const char *cmd)
134 {
135   if (!serial_logfp)
136     return;
137
138   serial_current_type = 'c';
139
140   fputs_unfiltered ("\nc ", serial_logfp);
141   fputs_unfiltered (cmd, serial_logfp);
142
143   /* Make sure that the log file is as up-to-date as possible,
144      in case we are getting ready to dump core or something.  */
145   gdb_flush (serial_logfp);
146 }
147
148 \f
149 static struct serial_ops *
150 serial_interface_lookup (const char *name)
151 {
152   struct serial_ops *ops;
153
154   for (ops = serial_ops_list; ops; ops = ops->next)
155     if (strcmp (name, ops->name) == 0)
156       return ops;
157
158   return NULL;
159 }
160
161 void
162 serial_add_interface (struct serial_ops *optable)
163 {
164   optable->next = serial_ops_list;
165   serial_ops_list = optable;
166 }
167
168 /* Open up a device or a network socket, depending upon the syntax of NAME.  */
169
170 struct serial *
171 serial_open (const char *name)
172 {
173   struct serial *scb;
174   struct serial_ops *ops;
175   const char *open_name = name;
176
177   for (scb = scb_base; scb; scb = scb->next)
178     if (scb->name && strcmp (scb->name, name) == 0)
179       {
180         scb->refcnt++;
181         return scb;
182       }
183
184   if (strcmp (name, "pc") == 0)
185     ops = serial_interface_lookup ("pc");
186   else if (strncmp (name, "lpt", 3) == 0)
187     ops = serial_interface_lookup ("parallel");
188   else if (strncmp (name, "|", 1) == 0)
189     {
190       ops = serial_interface_lookup ("pipe");
191       /* Discard ``|'' and any space before the command itself.  */
192       ++open_name;
193       while (isspace (*open_name))
194         ++open_name;
195     }
196   /* Check for a colon, suggesting an IP address/port pair.
197      Do this *after* checking for all the interesting prefixes.  We
198      don't want to constrain the syntax of what can follow them.  */
199   else if (strchr (name, ':'))
200     ops = serial_interface_lookup ("tcp");
201   else
202     ops = serial_interface_lookup ("hardwire");
203
204   if (!ops)
205     return NULL;
206
207   scb = XMALLOC (struct serial);
208
209   scb->ops = ops;
210
211   scb->bufcnt = 0;
212   scb->bufp = scb->buf;
213   scb->error_fd = -1;
214
215   /* `...->open (...)' would get expanded by the open(2) syscall macro.  */
216   if ((*scb->ops->open) (scb, open_name))
217     {
218       xfree (scb);
219       return NULL;
220     }
221
222   scb->name = xstrdup (name);
223   scb->next = scb_base;
224   scb->refcnt = 1;
225   scb->debug_p = 0;
226   scb->async_state = 0;
227   scb->async_handler = NULL;
228   scb->async_context = NULL;
229   scb_base = scb;
230
231   last_serial_opened = scb;
232
233   if (serial_logfile != NULL)
234     {
235       serial_logfp = gdb_fopen (serial_logfile, "w");
236       if (serial_logfp == NULL)
237         perror_with_name (serial_logfile);
238     }
239
240   return scb;
241 }
242
243 /* Return the open serial device for FD, if found, or NULL if FD
244    is not already opened.  */
245
246 struct serial *
247 serial_for_fd (int fd)
248 {
249   struct serial *scb;
250
251   for (scb = scb_base; scb; scb = scb->next)
252     if (scb->fd == fd)
253       return scb;
254
255   return NULL;
256 }
257
258 /* Open a new serial stream using a file handle, using serial
259    interface ops OPS.  */
260
261 static struct serial *
262 serial_fdopen_ops (const int fd, struct serial_ops *ops)
263 {
264   struct serial *scb;
265
266   scb = serial_for_fd (fd);
267   if (scb)
268     {
269       scb->refcnt++;
270       return scb;
271     }
272
273   if (!ops)
274     {
275       ops = serial_interface_lookup ("terminal");
276       if (!ops)
277         ops = serial_interface_lookup ("hardwire");
278     }
279
280   if (!ops)
281     return NULL;
282
283   scb = XCALLOC (1, struct serial);
284
285   scb->ops = ops;
286
287   scb->bufcnt = 0;
288   scb->bufp = scb->buf;
289   scb->error_fd = -1;
290
291   scb->name = NULL;
292   scb->next = scb_base;
293   scb->refcnt = 1;
294   scb->debug_p = 0;
295   scb->async_state = 0;
296   scb->async_handler = NULL;
297   scb->async_context = NULL;
298   scb_base = scb;
299
300   if ((ops->fdopen) != NULL)
301     (*ops->fdopen) (scb, fd);
302   else
303     scb->fd = fd;
304
305   last_serial_opened = scb;
306
307   return scb;
308 }
309
310 struct serial *
311 serial_fdopen (const int fd)
312 {
313   return serial_fdopen_ops (fd, NULL);
314 }
315
316 static void
317 do_serial_close (struct serial *scb, int really_close)
318 {
319   struct serial *tmp_scb;
320
321   last_serial_opened = NULL;
322
323   if (serial_logfp)
324     {
325       fputs_unfiltered ("\nEnd of log\n", serial_logfp);
326       serial_current_type = 0;
327
328       /* XXX - What if serial_logfp == gdb_stdout or gdb_stderr?  */
329       ui_file_delete (serial_logfp);
330       serial_logfp = NULL;
331     }
332
333   scb->refcnt--;
334   if (scb->refcnt > 0)
335     return;
336
337   /* ensure that the FD has been taken out of async mode.  */
338   if (scb->async_handler != NULL)
339     serial_async (scb, NULL, NULL);
340
341   if (really_close)
342     scb->ops->close (scb);
343
344   if (scb->name)
345     xfree (scb->name);
346
347   if (scb_base == scb)
348     scb_base = scb_base->next;
349   else
350     for (tmp_scb = scb_base; tmp_scb; tmp_scb = tmp_scb->next)
351       {
352         if (tmp_scb->next != scb)
353           continue;
354
355         tmp_scb->next = tmp_scb->next->next;
356         break;
357       }
358
359   xfree (scb);
360 }
361
362 void
363 serial_close (struct serial *scb)
364 {
365   do_serial_close (scb, 1);
366 }
367
368 void
369 serial_un_fdopen (struct serial *scb)
370 {
371   do_serial_close (scb, 0);
372 }
373
374 int
375 serial_readchar (struct serial *scb, int timeout)
376 {
377   int ch;
378
379   /* FIXME: cagney/1999-10-11: Don't enable this check until the ASYNC
380      code is finished.  */
381   if (0 && serial_is_async_p (scb) && timeout < 0)
382     internal_error (__FILE__, __LINE__,
383                     _("serial_readchar: blocking read in async mode"));
384
385   ch = scb->ops->readchar (scb, timeout);
386   if (serial_logfp != NULL)
387     {
388       serial_logchar (serial_logfp, 'r', ch, timeout);
389
390       /* Make sure that the log file is as up-to-date as possible,
391          in case we are getting ready to dump core or something.  */
392       gdb_flush (serial_logfp);
393     }
394   if (serial_debug_p (scb))
395     {
396       fprintf_unfiltered (gdb_stdlog, "[");
397       serial_logchar (gdb_stdlog, 'r', ch, timeout);
398       fprintf_unfiltered (gdb_stdlog, "]");
399       gdb_flush (gdb_stdlog);
400     }
401
402   return (ch);
403 }
404
405 int
406 serial_write (struct serial *scb, const char *str, int len)
407 {
408   if (serial_logfp != NULL)
409     {
410       int count;
411
412       for (count = 0; count < len; count++)
413         serial_logchar (serial_logfp, 'w', str[count] & 0xff, 0);
414
415       /* Make sure that the log file is as up-to-date as possible,
416          in case we are getting ready to dump core or something.  */
417       gdb_flush (serial_logfp);
418     }
419   if (serial_debug_p (scb))
420     {
421       int count;
422
423       for (count = 0; count < len; count++)
424         {
425           fprintf_unfiltered (gdb_stdlog, "[");
426           serial_logchar (gdb_stdlog, 'w', str[count] & 0xff, 0);
427           fprintf_unfiltered (gdb_stdlog, "]");
428         }
429       gdb_flush (gdb_stdlog);
430     }
431
432   return (scb->ops->write (scb, str, len));
433 }
434
435 void
436 serial_printf (struct serial *desc, const char *format,...)
437 {
438   va_list args;
439   char *buf;
440   va_start (args, format);
441
442   buf = xstrvprintf (format, args);
443   serial_write (desc, buf, strlen (buf));
444
445   xfree (buf);
446   va_end (args);
447 }
448
449 int
450 serial_drain_output (struct serial *scb)
451 {
452   return scb->ops->drain_output (scb);
453 }
454
455 int
456 serial_flush_output (struct serial *scb)
457 {
458   return scb->ops->flush_output (scb);
459 }
460
461 int
462 serial_flush_input (struct serial *scb)
463 {
464   return scb->ops->flush_input (scb);
465 }
466
467 int
468 serial_send_break (struct serial *scb)
469 {
470   if (serial_logfp != NULL)
471     serial_logchar (serial_logfp, 'w', SERIAL_BREAK, 0);
472
473   return (scb->ops->send_break (scb));
474 }
475
476 void
477 serial_raw (struct serial *scb)
478 {
479   scb->ops->go_raw (scb);
480 }
481
482 serial_ttystate
483 serial_get_tty_state (struct serial *scb)
484 {
485   return scb->ops->get_tty_state (scb);
486 }
487
488 serial_ttystate
489 serial_copy_tty_state (struct serial *scb, serial_ttystate ttystate)
490 {
491   return scb->ops->copy_tty_state (scb, ttystate);
492 }
493
494 int
495 serial_set_tty_state (struct serial *scb, serial_ttystate ttystate)
496 {
497   return scb->ops->set_tty_state (scb, ttystate);
498 }
499
500 void
501 serial_print_tty_state (struct serial *scb,
502                         serial_ttystate ttystate,
503                         struct ui_file *stream)
504 {
505   scb->ops->print_tty_state (scb, ttystate, stream);
506 }
507
508 int
509 serial_noflush_set_tty_state (struct serial *scb,
510                               serial_ttystate new_ttystate,
511                               serial_ttystate old_ttystate)
512 {
513   return scb->ops->noflush_set_tty_state (scb, new_ttystate, old_ttystate);
514 }
515
516 int
517 serial_setbaudrate (struct serial *scb, int rate)
518 {
519   return scb->ops->setbaudrate (scb, rate);
520 }
521
522 int
523 serial_setstopbits (struct serial *scb, int num)
524 {
525   return scb->ops->setstopbits (scb, num);
526 }
527
528 int
529 serial_can_async_p (struct serial *scb)
530 {
531   return (scb->ops->async != NULL);
532 }
533
534 int
535 serial_is_async_p (struct serial *scb)
536 {
537   return (scb->ops->async != NULL) && (scb->async_handler != NULL);
538 }
539
540 void
541 serial_async (struct serial *scb,
542               serial_event_ftype *handler,
543               void *context)
544 {
545   int changed = ((scb->async_handler == NULL) != (handler == NULL));
546
547   scb->async_handler = handler;
548   scb->async_context = context;
549   /* Only change mode if there is a need.  */
550   if (changed)
551     scb->ops->async (scb, handler != NULL);
552 }
553
554 int
555 deprecated_serial_fd (struct serial *scb)
556 {
557   /* FIXME: should this output a warning that deprecated code is being
558      called?  */
559   if (scb->fd < 0)
560     {
561       internal_error (__FILE__, __LINE__,
562                       _("serial: FD not valid"));
563     }
564   return scb->fd; /* sigh */
565 }
566
567 void
568 serial_debug (struct serial *scb, int debug_p)
569 {
570   scb->debug_p = debug_p;
571 }
572
573 int
574 serial_debug_p (struct serial *scb)
575 {
576   return scb->debug_p || global_serial_debug_p;
577 }
578
579 #ifdef USE_WIN32API
580 void
581 serial_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
582 {
583   if (scb->ops->wait_handle)
584     scb->ops->wait_handle (scb, read, except);
585   else
586     {
587       *read = (HANDLE) _get_osfhandle (scb->fd);
588       *except = NULL;
589     }
590 }
591
592 void
593 serial_done_wait_handle (struct serial *scb)
594 {
595   if (scb->ops->done_wait_handle)
596     scb->ops->done_wait_handle (scb);
597 }
598 #endif
599
600 int
601 serial_pipe (struct serial *scbs[2])
602 {
603   struct serial_ops *ops;
604   int fildes[2];
605
606   ops = serial_interface_lookup ("pipe");
607   if (!ops)
608     {
609       errno = ENOSYS;
610       return -1;
611     }
612
613   if (gdb_pipe (fildes) == -1)
614     return -1;
615
616   scbs[0] = serial_fdopen_ops (fildes[0], ops);
617   scbs[1] = serial_fdopen_ops (fildes[1], ops);
618   return 0;
619 }
620
621 #if 0
622 /* The connect command is #if 0 because I hadn't thought of an elegant
623    way to wait for I/O on two `struct serial *'s simultaneously.  Two
624    solutions came to mind:
625
626    1) Fork, and have have one fork handle the to user direction,
627    and have the other hand the to target direction.  This
628    obviously won't cut it for MSDOS.
629
630    2) Use something like select.  This assumes that stdin and
631    the target side can both be waited on via the same
632    mechanism.  This may not be true for DOS, if GDB is
633    talking to the target via a TCP socket.
634    -grossman, 8 Jun 93 */
635
636 /* Connect the user directly to the remote system.  This command acts just like
637    the 'cu' or 'tip' command.  Use <CR>~. or <CR>~^D to break out.  */
638
639 static struct serial *tty_desc; /* Controlling terminal */
640
641 static void
642 cleanup_tty (serial_ttystate ttystate)
643 {
644   printf_unfiltered ("\r\n[Exiting connect mode]\r\n");
645   serial_set_tty_state (tty_desc, ttystate);
646   xfree (ttystate);
647   serial_close (tty_desc);
648 }
649
650 static void
651 connect_command (char *args, int fromtty)
652 {
653   int c;
654   char cur_esc = 0;
655   serial_ttystate ttystate;
656   struct serial *port_desc;             /* TTY port */
657
658   dont_repeat ();
659
660   if (args)
661     fprintf_unfiltered (gdb_stderr,
662                         "This command takes no args.  "
663                         "They have been ignored.\n");
664
665   printf_unfiltered ("[Entering connect mode.  Use ~. or ~^D to escape]\n");
666
667   tty_desc = serial_fdopen (0);
668   port_desc = last_serial_opened;
669
670   ttystate = serial_get_tty_state (tty_desc);
671
672   serial_raw (tty_desc);
673   serial_raw (port_desc);
674
675   make_cleanup (cleanup_tty, ttystate);
676
677   while (1)
678     {
679       int mask;
680
681       mask = serial_wait_2 (tty_desc, port_desc, -1);
682
683       if (mask & 2)
684         {                       /* tty input */
685           char cx;
686
687           while (1)
688             {
689               c = serial_readchar (tty_desc, 0);
690
691               if (c == SERIAL_TIMEOUT)
692                 break;
693
694               if (c < 0)
695                 perror_with_name (_("connect"));
696
697               cx = c;
698               serial_write (port_desc, &cx, 1);
699
700               switch (cur_esc)
701                 {
702                 case 0:
703                   if (c == '\r')
704                     cur_esc = c;
705                   break;
706                 case '\r':
707                   if (c == '~')
708                     cur_esc = c;
709                   else
710                     cur_esc = 0;
711                   break;
712                 case '~':
713                   if (c == '.' || c == '\004')
714                     return;
715                   else
716                     cur_esc = 0;
717                 }
718             }
719         }
720
721       if (mask & 1)
722         {                       /* Port input */
723           char cx;
724
725           while (1)
726             {
727               c = serial_readchar (port_desc, 0);
728
729               if (c == SERIAL_TIMEOUT)
730                 break;
731
732               if (c < 0)
733                 perror_with_name (_("connect"));
734
735               cx = c;
736
737               serial_write (tty_desc, &cx, 1);
738             }
739         }
740     }
741 }
742 #endif /* 0 */
743
744 /* Serial set/show framework.  */
745
746 static struct cmd_list_element *serial_set_cmdlist;
747 static struct cmd_list_element *serial_show_cmdlist;
748
749 static void
750 serial_set_cmd (char *args, int from_tty)
751 {
752   printf_unfiltered ("\"set serial\" must be followed "
753                      "by the name of a command.\n");
754   help_list (serial_set_cmdlist, "set serial ", -1, gdb_stdout);
755 }
756
757 static void
758 serial_show_cmd (char *args, int from_tty)
759 {
760   cmd_show_list (serial_show_cmdlist, from_tty, "");
761 }
762
763
764 void
765 _initialize_serial (void)
766 {
767 #if 0
768   add_com ("connect", class_obscure, connect_command, _("\
769 Connect the terminal directly up to the command monitor.\n\
770 Use <CR>~. or <CR>~^D to break out."));
771 #endif /* 0 */
772
773   add_prefix_cmd ("serial", class_maintenance, serial_set_cmd, _("\
774 Set default serial/parallel port configuration."),
775                   &serial_set_cmdlist, "set serial ",
776                   0/*allow-unknown*/,
777                   &setlist);
778
779   add_prefix_cmd ("serial", class_maintenance, serial_show_cmd, _("\
780 Show default serial/parallel port configuration."),
781                   &serial_show_cmdlist, "show serial ",
782                   0/*allow-unknown*/,
783                   &showlist);
784
785   add_setshow_filename_cmd ("remotelogfile", no_class, &serial_logfile, _("\
786 Set filename for remote session recording."), _("\
787 Show filename for remote session recording."), _("\
788 This file is used to record the remote session for future playback\n\
789 by gdbserver."),
790                             NULL,
791                             NULL, /* FIXME: i18n: */
792                             &setlist, &showlist);
793
794   add_setshow_enum_cmd ("remotelogbase", no_class, logbase_enums,
795                         &serial_logbase, _("\
796 Set numerical base for remote session logging"), _("\
797 Show numerical base for remote session logging"), NULL,
798                         NULL,
799                         NULL, /* FIXME: i18n: */
800                         &setlist, &showlist);
801
802   add_setshow_zinteger_cmd ("serial", class_maintenance,
803                             &global_serial_debug_p, _("\
804 Set serial debugging."), _("\
805 Show serial debugging."), _("\
806 When non-zero, serial port debugging is enabled."),
807                             NULL,
808                             NULL, /* FIXME: i18n: */
809                             &setdebuglist, &showdebuglist);
810 }