1/* Generic serial interface routines
2
3   Copyright (C) 1992-2023 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 "gdbcmd.h"
24#include "cli/cli-utils.h"
25
26/* Is serial being debugged?  */
27
28static unsigned int global_serial_debug_p;
29
30/* Serial I/O handlers.  */
31
32static std::vector<const struct serial_ops *> serial_ops_list;
33
34/* Pointer to list of scb's.  */
35
36static struct serial *scb_base;
37
38/* Non-NULL gives filename which contains a recording of the remote session,
39   suitable for playback by gdbserver.  */
40
41static std::string serial_logfile;
42static struct ui_file *serial_logfp = NULL;
43
44static const struct serial_ops *serial_interface_lookup (const char *);
45static void serial_logchar (struct ui_file *stream,
46			    int ch_type, int ch, int timeout);
47static const char logbase_hex[] = "hex";
48static const char logbase_octal[] = "octal";
49static const char logbase_ascii[] = "ascii";
50static const char *const logbase_enums[] =
51{logbase_hex, logbase_octal, logbase_ascii, NULL};
52static const char *serial_logbase = logbase_ascii;
53
54
55static int serial_current_type = 0;
56
57/* Log char CH of type CHTYPE, with TIMEOUT.  */
58
59/* Define bogus char to represent a BREAK.  Should be careful to choose a value
60   that can't be confused with a normal char, or an error code.  */
61#define SERIAL_BREAK 1235
62
63static void
64serial_logchar (struct ui_file *stream, int ch_type, int ch, int timeout)
65{
66  if (ch_type != serial_current_type)
67    {
68      gdb_printf (stream, "\n%c ", ch_type);
69      serial_current_type = ch_type;
70    }
71
72  if (serial_logbase != logbase_ascii)
73    gdb_putc (' ', stream);
74
75  switch (ch)
76    {
77    case SERIAL_TIMEOUT:
78      gdb_printf (stream, "<Timeout: %d seconds>", timeout);
79      return;
80    case SERIAL_ERROR:
81      gdb_printf (stream, "<Error: %s>", safe_strerror (errno));
82      return;
83    case SERIAL_EOF:
84      gdb_puts ("<Eof>", stream);
85      return;
86    case SERIAL_BREAK:
87      gdb_puts ("<Break>", stream);
88      return;
89    default:
90      if (serial_logbase == logbase_hex)
91	gdb_printf (stream, "%02x", ch & 0xff);
92      else if (serial_logbase == logbase_octal)
93	gdb_printf (stream, "%03o", ch & 0xff);
94      else
95	switch (ch)
96	  {
97	  case '\\':
98	    gdb_puts ("\\\\", stream);
99	    break;
100	  case '\b':
101	    gdb_puts ("\\b", stream);
102	    break;
103	  case '\f':
104	    gdb_puts ("\\f", stream);
105	    break;
106	  case '\n':
107	    gdb_puts ("\\n", stream);
108	    break;
109	  case '\r':
110	    gdb_puts ("\\r", stream);
111	    break;
112	  case '\t':
113	    gdb_puts ("\\t", stream);
114	    break;
115	  case '\v':
116	    gdb_puts ("\\v", stream);
117	    break;
118	  default:
119	    gdb_printf (stream,
120			isprint (ch) ? "%c" : "\\x%02x", ch & 0xFF);
121	    break;
122	  }
123    }
124}
125
126void
127serial_log_command (struct target_ops *self, const char *cmd)
128{
129  if (!serial_logfp)
130    return;
131
132  serial_current_type = 'c';
133
134  gdb_puts ("\nc ", serial_logfp);
135  gdb_puts (cmd, serial_logfp);
136
137  /* Make sure that the log file is as up-to-date as possible,
138     in case we are getting ready to dump core or something.  */
139  gdb_flush (serial_logfp);
140}
141
142
143static const struct serial_ops *
144serial_interface_lookup (const char *name)
145{
146  for (const serial_ops *ops : serial_ops_list)
147    if (strcmp (name, ops->name) == 0)
148      return ops;
149
150  return NULL;
151}
152
153void
154serial_add_interface (const struct serial_ops *optable)
155{
156  serial_ops_list.push_back (optable);
157}
158
159/* Return the open serial device for FD, if found, or NULL if FD is
160   not already opened.  */
161
162struct serial *
163serial_for_fd (int fd)
164{
165  struct serial *scb;
166
167  for (scb = scb_base; scb; scb = scb->next)
168    if (scb->fd == fd)
169      return scb;
170
171  return NULL;
172}
173
174/* Create a new serial for OPS.  */
175
176static struct serial *
177new_serial (const struct serial_ops *ops)
178{
179  struct serial *scb;
180
181  scb = XCNEW (struct serial);
182
183  scb->ops = ops;
184
185  scb->bufp = scb->buf;
186  scb->error_fd = -1;
187  scb->refcnt = 1;
188
189  return scb;
190}
191
192static struct serial *serial_open_ops_1 (const struct serial_ops *ops,
193					 const char *open_name);
194
195/* Open up a device or a network socket, depending upon the syntax of NAME.  */
196
197struct serial *
198serial_open (const char *name)
199{
200  const struct serial_ops *ops;
201  const char *open_name = name;
202
203  if (startswith (name, "|"))
204    ops = serial_interface_lookup ("pipe");
205  /* Check for a colon, suggesting an IP address/port pair.
206     Do this *after* checking for all the interesting prefixes.  We
207     don't want to constrain the syntax of what can follow them.  */
208  else if (strchr (name, ':'))
209    ops = serial_interface_lookup ("tcp");
210  else
211    {
212#ifndef USE_WIN32API
213      /* Check to see if name is a socket.  If it is, then treat it
214	 as such.  Otherwise assume that it's a character device.  */
215      struct stat sb;
216      if (stat (name, &sb) == 0 && (sb.st_mode & S_IFMT) == S_IFSOCK)
217	ops = serial_interface_lookup ("local");
218      else
219#endif
220	ops = serial_interface_lookup ("hardwire");
221    }
222
223  if (!ops)
224    return NULL;
225
226  return serial_open_ops_1 (ops, open_name);
227}
228
229/* Open up a serial for OPS, passing OPEN_NAME to the open method.  */
230
231static struct serial *
232serial_open_ops_1 (const struct serial_ops *ops, const char *open_name)
233{
234  struct serial *scb;
235
236  scb = new_serial (ops);
237
238  /* `...->open (...)' would get expanded by the open(2) syscall macro.  */
239  if ((*scb->ops->open) (scb, open_name))
240    {
241      xfree (scb);
242      return NULL;
243    }
244
245  scb->name = open_name != NULL ? xstrdup (open_name) : NULL;
246  scb->next = scb_base;
247  scb_base = scb;
248
249  if (!serial_logfile.empty ())
250    {
251      stdio_file_up file (new stdio_file ());
252
253      if (!file->open (serial_logfile.c_str (), "w"))
254	perror_with_name (serial_logfile.c_str ());
255
256      serial_logfp = file.release ();
257    }
258
259  return scb;
260}
261
262/* See serial.h.  */
263
264struct serial *
265serial_open_ops (const struct serial_ops *ops)
266{
267  return serial_open_ops_1 (ops, NULL);
268}
269
270/* Open a new serial stream using a file handle, using serial
271   interface ops OPS.  */
272
273static struct serial *
274serial_fdopen_ops (const int fd, const struct serial_ops *ops)
275{
276  struct serial *scb;
277
278  if (!ops)
279    {
280      ops = serial_interface_lookup ("terminal");
281      if (!ops)
282	ops = serial_interface_lookup ("hardwire");
283    }
284
285  if (!ops)
286    return NULL;
287
288  scb = new_serial (ops);
289
290  scb->name = NULL;
291  scb->next = scb_base;
292  scb_base = scb;
293
294  if ((ops->fdopen) != NULL)
295    (*ops->fdopen) (scb, fd);
296  else
297    scb->fd = fd;
298
299  return scb;
300}
301
302struct serial *
303serial_fdopen (const int fd)
304{
305  return serial_fdopen_ops (fd, NULL);
306}
307
308static void
309do_serial_close (struct serial *scb, int really_close)
310{
311  struct serial *tmp_scb;
312
313  if (serial_logfp)
314    {
315      gdb_puts ("\nEnd of log\n", serial_logfp);
316      serial_current_type = 0;
317
318      /* XXX - What if serial_logfp == gdb_stdout or gdb_stderr?  */
319      delete serial_logfp;
320      serial_logfp = NULL;
321    }
322
323  /* ensure that the FD has been taken out of async mode.  */
324  if (scb->async_handler != NULL)
325    serial_async (scb, NULL, NULL);
326
327  if (really_close)
328    scb->ops->close (scb);
329
330  xfree (scb->name);
331
332  /* For serial_is_open.  */
333  scb->bufp = NULL;
334
335  if (scb_base == scb)
336    scb_base = scb_base->next;
337  else
338    for (tmp_scb = scb_base; tmp_scb; tmp_scb = tmp_scb->next)
339      {
340	if (tmp_scb->next != scb)
341	  continue;
342
343	tmp_scb->next = tmp_scb->next->next;
344	break;
345      }
346
347  serial_unref (scb);
348}
349
350void
351serial_close (struct serial *scb)
352{
353  do_serial_close (scb, 1);
354}
355
356void
357serial_un_fdopen (struct serial *scb)
358{
359  do_serial_close (scb, 0);
360}
361
362int
363serial_is_open (struct serial *scb)
364{
365  return scb->bufp != NULL;
366}
367
368void
369serial_ref (struct serial *scb)
370{
371  scb->refcnt++;
372}
373
374void
375serial_unref (struct serial *scb)
376{
377  --scb->refcnt;
378  if (scb->refcnt == 0)
379    xfree (scb);
380}
381
382int
383serial_readchar (struct serial *scb, int timeout)
384{
385  int ch;
386
387  /* FIXME: cagney/1999-10-11: Don't enable this check until the ASYNC
388     code is finished.  */
389  if (0 && serial_is_async_p (scb) && timeout < 0)
390    internal_error (_("serial_readchar: blocking read in async mode"));
391
392  ch = scb->ops->readchar (scb, timeout);
393  if (serial_logfp != NULL)
394    {
395      serial_logchar (serial_logfp, 'r', ch, timeout);
396
397      /* Make sure that the log file is as up-to-date as possible,
398	 in case we are getting ready to dump core or something.  */
399      gdb_flush (serial_logfp);
400    }
401  if (serial_debug_p (scb))
402    {
403      gdb_printf (gdb_stdlog, "[");
404      serial_logchar (gdb_stdlog, 'r', ch, timeout);
405      gdb_printf (gdb_stdlog, "]");
406      gdb_flush (gdb_stdlog);
407    }
408
409  return (ch);
410}
411
412int
413serial_write (struct serial *scb, const void *buf, size_t count)
414{
415  if (serial_logfp != NULL)
416    {
417      const char *str = (const char *) buf;
418      size_t c;
419
420      for (c = 0; c < count; c++)
421	serial_logchar (serial_logfp, 'w', str[c] & 0xff, 0);
422
423      /* Make sure that the log file is as up-to-date as possible,
424	 in case we are getting ready to dump core or something.  */
425      gdb_flush (serial_logfp);
426    }
427  if (serial_debug_p (scb))
428    {
429      const char *str = (const char *) buf;
430      size_t c;
431
432      for (c = 0; c < count; c++)
433	{
434	  gdb_printf (gdb_stdlog, "[");
435	  serial_logchar (gdb_stdlog, 'w', str[c] & 0xff, 0);
436	  gdb_printf (gdb_stdlog, "]");
437	}
438      gdb_flush (gdb_stdlog);
439    }
440
441  return (scb->ops->write (scb, buf, count));
442}
443
444void
445serial_printf (struct serial *desc, const char *format, ...)
446{
447  va_list args;
448  va_start (args, format);
449
450  std::string buf = string_vprintf (format, args);
451  serial_write (desc, buf.c_str (), buf.length ());
452
453  va_end (args);
454}
455
456int
457serial_drain_output (struct serial *scb)
458{
459  return scb->ops->drain_output (scb);
460}
461
462int
463serial_flush_output (struct serial *scb)
464{
465  return scb->ops->flush_output (scb);
466}
467
468int
469serial_flush_input (struct serial *scb)
470{
471  return scb->ops->flush_input (scb);
472}
473
474int
475serial_send_break (struct serial *scb)
476{
477  if (serial_logfp != NULL)
478    serial_logchar (serial_logfp, 'w', SERIAL_BREAK, 0);
479
480  return (scb->ops->send_break (scb));
481}
482
483void
484serial_raw (struct serial *scb)
485{
486  scb->ops->go_raw (scb);
487}
488
489serial_ttystate
490serial_get_tty_state (struct serial *scb)
491{
492  return scb->ops->get_tty_state (scb);
493}
494
495serial_ttystate
496serial_copy_tty_state (struct serial *scb, serial_ttystate ttystate)
497{
498  return scb->ops->copy_tty_state (scb, ttystate);
499}
500
501int
502serial_set_tty_state (struct serial *scb, serial_ttystate ttystate)
503{
504  return scb->ops->set_tty_state (scb, ttystate);
505}
506
507void
508serial_print_tty_state (struct serial *scb,
509			serial_ttystate ttystate,
510			struct ui_file *stream)
511{
512  scb->ops->print_tty_state (scb, ttystate, stream);
513}
514
515int
516serial_setbaudrate (struct serial *scb, int rate)
517{
518  return scb->ops->setbaudrate (scb, rate);
519}
520
521int
522serial_setstopbits (struct serial *scb, int num)
523{
524  return scb->ops->setstopbits (scb, num);
525}
526
527/* See serial.h.  */
528
529int
530serial_setparity (struct serial *scb, int parity)
531{
532  return scb->ops->setparity (scb, parity);
533}
534
535int
536serial_can_async_p (struct serial *scb)
537{
538  return (scb->ops->async != NULL);
539}
540
541int
542serial_is_async_p (struct serial *scb)
543{
544  return (scb->ops->async != NULL) && (scb->async_handler != NULL);
545}
546
547void
548serial_async (struct serial *scb,
549	      serial_event_ftype *handler,
550	      void *context)
551{
552  int changed = ((scb->async_handler == NULL) != (handler == NULL));
553
554  scb->async_handler = handler;
555  scb->async_context = context;
556  /* Only change mode if there is a need.  */
557  if (changed)
558    scb->ops->async (scb, handler != NULL);
559}
560
561void
562serial_debug (struct serial *scb, int debug_p)
563{
564  scb->debug_p = debug_p;
565}
566
567int
568serial_debug_p (struct serial *scb)
569{
570  return scb->debug_p || global_serial_debug_p;
571}
572
573#ifdef USE_WIN32API
574void
575serial_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
576{
577  if (scb->ops->wait_handle)
578    scb->ops->wait_handle (scb, read, except);
579  else
580    {
581      *read = (HANDLE) _get_osfhandle (scb->fd);
582      *except = NULL;
583    }
584}
585
586void
587serial_done_wait_handle (struct serial *scb)
588{
589  if (scb->ops->done_wait_handle)
590    scb->ops->done_wait_handle (scb);
591}
592#endif
593
594int
595serial_pipe (struct serial *scbs[2])
596{
597  const struct serial_ops *ops;
598  int fildes[2];
599
600  ops = serial_interface_lookup ("pipe");
601  if (!ops)
602    {
603      errno = ENOSYS;
604      return -1;
605    }
606
607  if (gdb_pipe (fildes) == -1)
608    return -1;
609
610  scbs[0] = serial_fdopen_ops (fildes[0], ops);
611  scbs[1] = serial_fdopen_ops (fildes[1], ops);
612  return 0;
613}
614
615/* Serial set/show framework.  */
616
617static struct cmd_list_element *serial_set_cmdlist;
618static struct cmd_list_element *serial_show_cmdlist;
619
620/* See serial.h.  */
621
622int baud_rate = -1;
623
624static void
625serial_baud_show_cmd (struct ui_file *file, int from_tty,
626		      struct cmd_list_element *c, const char *value)
627{
628  gdb_printf (file, _("Baud rate for remote serial I/O is %s.\n"),
629	      value);
630}
631
632/* See serial.h.  */
633
634int serial_parity = GDBPARITY_NONE;
635
636static const char parity_none[] = "none";
637static const char parity_odd[] = "odd";
638static const char parity_even[] = "even";
639static const char *const parity_enums[] =
640  {parity_none, parity_odd, parity_even,  NULL};
641static const char *parity = parity_none;
642
643/* Set serial_parity value.  */
644
645static void
646set_parity (const char *ignore_args, int from_tty, struct cmd_list_element *c)
647{
648  if (parity == parity_odd)
649    serial_parity = GDBPARITY_ODD;
650  else if (parity == parity_even)
651    serial_parity = GDBPARITY_EVEN;
652  else
653    serial_parity = GDBPARITY_NONE;
654}
655
656void _initialize_serial ();
657void
658_initialize_serial ()
659{
660#if 0
661  add_com ("connect", class_obscure, connect_command, _("\
662Connect the terminal directly up to the command monitor.\n\
663Use <CR>~. or <CR>~^D to break out."));
664#endif /* 0 */
665
666  add_setshow_prefix_cmd ("serial", class_maintenance,
667			  _("Set default serial/parallel port configuration."),
668			  _("Show default serial/parallel port configuration."),
669			  &serial_set_cmdlist, &serial_show_cmdlist,
670			  &setlist, &showlist);
671
672  /* If target is open when baud changes, it doesn't take effect until
673     the next open (I think, not sure).  */
674  add_setshow_zinteger_cmd ("baud", no_class, &baud_rate, _("\
675Set baud rate for remote serial I/O."), _("\
676Show baud rate for remote serial I/O."), _("\
677This value is used to set the speed of the serial port when debugging\n\
678using remote targets."),
679			    NULL,
680			    serial_baud_show_cmd,
681			    &serial_set_cmdlist, &serial_show_cmdlist);
682
683  add_setshow_enum_cmd ("parity", no_class, parity_enums,
684			&parity, _("\
685Set parity for remote serial I/O."), _("\
686Show parity for remote serial I/O."), NULL,
687			set_parity,
688			NULL, /* FIXME: i18n: */
689			&serial_set_cmdlist, &serial_show_cmdlist);
690
691  add_setshow_filename_cmd ("remotelogfile", no_class, &serial_logfile, _("\
692Set filename for remote session recording."), _("\
693Show filename for remote session recording."), _("\
694This file is used to record the remote session for future playback\n\
695by gdbserver."),
696			    NULL,
697			    NULL, /* FIXME: i18n: */
698			    &setlist, &showlist);
699
700  add_setshow_enum_cmd ("remotelogbase", no_class, logbase_enums,
701			&serial_logbase, _("\
702Set numerical base for remote session logging."), _("\
703Show numerical base for remote session logging."), NULL,
704			NULL,
705			NULL, /* FIXME: i18n: */
706			&setlist, &showlist);
707
708  add_setshow_zuinteger_cmd ("serial", class_maintenance,
709			     &global_serial_debug_p, _("\
710Set serial debugging."), _("\
711Show serial debugging."), _("\
712When non-zero, serial port debugging is enabled."),
713			     NULL,
714			     NULL, /* FIXME: i18n: */
715			     &setdebuglist, &showdebuglist);
716}
717