1/* Replay a remote debug session logfile for GDB.
2   Copyright (C) 1996-2023 Free Software Foundation, Inc.
3   Written by Fred Fish (fnf@cygnus.com) from pieces of gdbserver.
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 "gdbsupport/common-defs.h"
21
22#undef PACKAGE
23#undef PACKAGE_NAME
24#undef PACKAGE_VERSION
25#undef PACKAGE_STRING
26#undef PACKAGE_TARNAME
27
28#include <config.h>
29#include "gdbsupport/version.h"
30
31#if HAVE_SYS_FILE_H
32#include <sys/file.h>
33#endif
34#if HAVE_SIGNAL_H
35#include <signal.h>
36#endif
37#include <ctype.h>
38#if HAVE_FCNTL_H
39#include <fcntl.h>
40#endif
41#include <unistd.h>
42#ifdef HAVE_NETINET_IN_H
43#include <netinet/in.h>
44#endif
45#ifdef HAVE_SYS_SOCKET_H
46#include <sys/socket.h>
47#endif
48#if HAVE_NETDB_H
49#include <netdb.h>
50#endif
51#if HAVE_NETINET_TCP_H
52#include <netinet/tcp.h>
53#endif
54
55#if USE_WIN32API
56#include <ws2tcpip.h>
57#endif
58
59#include "gdbsupport/netstuff.h"
60#include "gdbsupport/rsp-low.h"
61
62#ifndef HAVE_SOCKLEN_T
63typedef int socklen_t;
64#endif
65
66/* Sort of a hack... */
67#define EOL (EOF - 1)
68
69static int remote_desc_in;
70static int remote_desc_out;
71
72static void
73sync_error (FILE *fp, const char *desc, int expect, int got)
74{
75  fprintf (stderr, "\n%s\n", desc);
76  fprintf (stderr, "At logfile offset %ld, expected '0x%x' got '0x%x'\n",
77	   ftell (fp), expect, got);
78  fflush (stderr);
79  exit (1);
80}
81
82static void
83remote_error (const char *desc)
84{
85  fprintf (stderr, "\n%s\n", desc);
86  fflush (stderr);
87  exit (1);
88}
89
90static void
91remote_close (void)
92{
93#ifdef USE_WIN32API
94  gdb_assert (remote_desc_in == remote_desc_out);
95  closesocket (remote_desc_in);
96#else
97  close (remote_desc_in);
98  if (remote_desc_in != remote_desc_out)
99    close (remote_desc_out);
100#endif
101}
102
103/* Open a connection to a remote debugger.
104   NAME is the filename used for communication.  */
105
106static void
107remote_open (const char *name)
108{
109#ifndef USE_WIN32API
110  if (strcmp (name, "-") == 0)
111    {
112      remote_desc_in = 0;
113      remote_desc_out = 1;
114      return;
115    }
116#endif
117
118  const char *last_colon = strrchr (name, ':');
119
120  if (last_colon == NULL)
121    {
122      fprintf (stderr, "%s: Must specify tcp connection as host:addr\n", name);
123      fflush (stderr);
124      exit (1);
125    }
126
127#ifdef USE_WIN32API
128  static int winsock_initialized;
129#endif
130  int tmp;
131  int tmp_desc;
132  struct addrinfo hint;
133  struct addrinfo *ainfo;
134
135  memset (&hint, 0, sizeof (hint));
136  /* Assume no prefix will be passed, therefore we should use
137     AF_UNSPEC.  */
138  hint.ai_family = AF_UNSPEC;
139  hint.ai_socktype = SOCK_STREAM;
140  hint.ai_protocol = IPPROTO_TCP;
141
142  parsed_connection_spec parsed = parse_connection_spec (name, &hint);
143
144  if (parsed.port_str.empty ())
145    error (_("Missing port on hostname '%s'"), name);
146
147#ifdef USE_WIN32API
148  if (!winsock_initialized)
149    {
150      WSADATA wsad;
151
152      WSAStartup (MAKEWORD (1, 0), &wsad);
153      winsock_initialized = 1;
154    }
155#endif
156
157  int r = getaddrinfo (parsed.host_str.c_str (), parsed.port_str.c_str (),
158		       &hint, &ainfo);
159
160  if (r != 0)
161    {
162      fprintf (stderr, "%s:%s: cannot resolve name: %s\n",
163	       parsed.host_str.c_str (), parsed.port_str.c_str (),
164	       gai_strerror (r));
165      fflush (stderr);
166      exit (1);
167    }
168
169  scoped_free_addrinfo free_ainfo (ainfo);
170
171  struct addrinfo *p;
172
173  for (p = ainfo; p != NULL; p = p->ai_next)
174    {
175      tmp_desc = socket (p->ai_family, p->ai_socktype, p->ai_protocol);
176
177      if (tmp_desc >= 0)
178	break;
179    }
180
181  if (p == NULL)
182    perror_with_name ("Cannot open socket");
183
184  /* Allow rapid reuse of this port. */
185  tmp = 1;
186  setsockopt (tmp_desc, SOL_SOCKET, SO_REUSEADDR, (char *) &tmp,
187	      sizeof (tmp));
188
189  switch (p->ai_family)
190    {
191    case AF_INET:
192      ((struct sockaddr_in *) p->ai_addr)->sin_addr.s_addr = INADDR_ANY;
193      break;
194    case AF_INET6:
195      ((struct sockaddr_in6 *) p->ai_addr)->sin6_addr = in6addr_any;
196      break;
197    default:
198      fprintf (stderr, "Invalid 'ai_family' %d\n", p->ai_family);
199      exit (1);
200    }
201
202  if (bind (tmp_desc, p->ai_addr, p->ai_addrlen) != 0)
203    perror_with_name ("Can't bind address");
204
205  if (p->ai_socktype == SOCK_DGRAM)
206    remote_desc_in = tmp_desc;
207  else
208    {
209      struct sockaddr_storage sockaddr;
210      socklen_t sockaddrsize = sizeof (sockaddr);
211      char orig_host[GDB_NI_MAX_ADDR], orig_port[GDB_NI_MAX_PORT];
212
213      if (listen (tmp_desc, 1) != 0)
214	perror_with_name ("Can't listen on socket");
215
216      remote_desc_in = accept (tmp_desc, (struct sockaddr *) &sockaddr,
217			       &sockaddrsize);
218
219      if (remote_desc_in == -1)
220	perror_with_name ("Accept failed");
221
222      /* Enable TCP keep alive process. */
223      tmp = 1;
224      setsockopt (tmp_desc, SOL_SOCKET, SO_KEEPALIVE,
225		  (char *) &tmp, sizeof (tmp));
226
227      /* Tell TCP not to delay small packets.  This greatly speeds up
228	 interactive response. */
229      tmp = 1;
230      setsockopt (remote_desc_in, IPPROTO_TCP, TCP_NODELAY,
231		  (char *) &tmp, sizeof (tmp));
232
233      if (getnameinfo ((struct sockaddr *) &sockaddr, sockaddrsize,
234		       orig_host, sizeof (orig_host),
235		       orig_port, sizeof (orig_port),
236		       NI_NUMERICHOST | NI_NUMERICSERV) == 0)
237	{
238	  fprintf (stderr, "Remote debugging from host %s, port %s\n",
239		   orig_host, orig_port);
240	  fflush (stderr);
241	}
242
243#ifndef USE_WIN32API
244      close (tmp_desc);		/* No longer need this */
245
246      signal (SIGPIPE, SIG_IGN);	/* If we don't do this, then
247					   gdbreplay simply exits when
248					   the remote side dies.  */
249#else
250      closesocket (tmp_desc);	/* No longer need this */
251#endif
252    }
253
254#if defined(F_SETFL) && defined (FASYNC)
255  fcntl (remote_desc_in, F_SETFL, FASYNC);
256#endif
257  remote_desc_out = remote_desc_in;
258
259  fprintf (stderr, "Replay logfile using %s\n", name);
260  fflush (stderr);
261}
262
263static int
264logchar (FILE *fp)
265{
266  int ch;
267  int ch2;
268
269  ch = fgetc (fp);
270  if (ch != '\r')
271    {
272      fputc (ch, stderr);
273      fflush (stderr);
274    }
275  switch (ch)
276    {
277      /* Treat \r\n as a newline.  */
278    case '\r':
279      ch = fgetc (fp);
280      if (ch == '\n')
281	ch = EOL;
282      else
283	{
284	  ungetc (ch, fp);
285	  ch = '\r';
286	}
287      fputc (ch == EOL ? '\n' : '\r', stderr);
288      fflush (stderr);
289      break;
290    case '\n':
291      ch = EOL;
292      break;
293    case '\\':
294      ch = fgetc (fp);
295      fputc (ch, stderr);
296      fflush (stderr);
297      switch (ch)
298	{
299	case '\\':
300	  break;
301	case 'b':
302	  ch = '\b';
303	  break;
304	case 'f':
305	  ch = '\f';
306	  break;
307	case 'n':
308	  ch = '\n';
309	  break;
310	case 'r':
311	  ch = '\r';
312	  break;
313	case 't':
314	  ch = '\t';
315	  break;
316	case 'v':
317	  ch = '\v';
318	  break;
319	case 'x':
320	  ch2 = fgetc (fp);
321	  fputc (ch2, stderr);
322	  fflush (stderr);
323	  ch = fromhex (ch2) << 4;
324	  ch2 = fgetc (fp);
325	  fputc (ch2, stderr);
326	  fflush (stderr);
327	  ch |= fromhex (ch2);
328	  break;
329	default:
330	  /* Treat any other char as just itself */
331	  break;
332	}
333    default:
334      break;
335    }
336  return (ch);
337}
338
339static int
340gdbchar (int desc)
341{
342  unsigned char fromgdb;
343
344  if (read (desc, &fromgdb, 1) != 1)
345    return -1;
346  else
347    return fromgdb;
348}
349
350/* Accept input from gdb and match with chars from fp (after skipping one
351   blank) up until a \n is read from fp (which is not matched) */
352
353static void
354expect (FILE *fp)
355{
356  int fromlog;
357  int fromgdb;
358
359  if ((fromlog = logchar (fp)) != ' ')
360    {
361      sync_error (fp, "Sync error during gdb read of leading blank", ' ',
362		  fromlog);
363    }
364  do
365    {
366      fromlog = logchar (fp);
367      if (fromlog == EOL)
368	break;
369      fromgdb = gdbchar (remote_desc_in);
370      if (fromgdb < 0)
371	remote_error ("Error during read from gdb");
372    }
373  while (fromlog == fromgdb);
374
375  if (fromlog != EOL)
376    {
377      sync_error (fp, "Sync error during read of gdb packet from log", fromlog,
378		  fromgdb);
379    }
380}
381
382/* Play data back to gdb from fp (after skipping leading blank) up until a
383   \n is read from fp (which is discarded and not sent to gdb). */
384
385static void
386play (FILE *fp)
387{
388  int fromlog;
389  char ch;
390
391  if ((fromlog = logchar (fp)) != ' ')
392    {
393      sync_error (fp, "Sync error skipping blank during write to gdb", ' ',
394		  fromlog);
395    }
396  while ((fromlog = logchar (fp)) != EOL)
397    {
398      ch = fromlog;
399      if (write (remote_desc_out, &ch, 1) != 1)
400	remote_error ("Error during write to gdb");
401    }
402}
403
404static void
405gdbreplay_version (void)
406{
407  printf ("GNU gdbreplay %s%s\n"
408	  "Copyright (C) 2023 Free Software Foundation, Inc.\n"
409	  "gdbreplay is free software, covered by "
410	  "the GNU General Public License.\n"
411	  "This gdbreplay was configured as \"%s\"\n",
412	  PKGVERSION, version, host_name);
413}
414
415static void
416gdbreplay_usage (FILE *stream)
417{
418  fprintf (stream, "Usage:\tgdbreplay LOGFILE HOST:PORT\n");
419  if (REPORT_BUGS_TO[0] && stream == stdout)
420    fprintf (stream, "Report bugs to \"%s\".\n", REPORT_BUGS_TO);
421}
422
423/* Main function.  This is called by the real "main" function,
424   wrapped in a TRY_CATCH that handles any uncaught exceptions.  */
425
426static void ATTRIBUTE_NORETURN
427captured_main (int argc, char *argv[])
428{
429  FILE *fp;
430  int ch;
431
432  if (argc >= 2 && strcmp (argv[1], "--version") == 0)
433    {
434      gdbreplay_version ();
435      exit (0);
436    }
437  if (argc >= 2 && strcmp (argv[1], "--help") == 0)
438    {
439      gdbreplay_usage (stdout);
440      exit (0);
441    }
442
443  if (argc < 3)
444    {
445      gdbreplay_usage (stderr);
446      exit (1);
447    }
448  fp = fopen (argv[1], "r");
449  if (fp == NULL)
450    {
451      perror_with_name (argv[1]);
452    }
453  remote_open (argv[2]);
454  while ((ch = logchar (fp)) != EOF)
455    {
456      switch (ch)
457	{
458	case 'w':
459	  /* data sent from gdb to gdbreplay, accept and match it */
460	  expect (fp);
461	  break;
462	case 'r':
463	  /* data sent from gdbreplay to gdb, play it */
464	  play (fp);
465	  break;
466	case 'c':
467	  /* Command executed by gdb */
468	  while ((ch = logchar (fp)) != EOL);
469	  break;
470	}
471    }
472  remote_close ();
473  exit (0);
474}
475
476int
477main (int argc, char *argv[])
478{
479  try
480    {
481      captured_main (argc, argv);
482    }
483  catch (const gdb_exception &exception)
484    {
485      if (exception.reason == RETURN_ERROR)
486	{
487	  fflush (stdout);
488	  fprintf (stderr, "%s\n", exception.what ());
489	}
490
491      exit (1);
492    }
493
494  gdb_assert_not_reached ("captured_main should never return");
495}
496