* gdbreplay.c (remote_error): New.
[external/binutils.git] / gdb / gdbserver / gdbreplay.c
1 /* Replay a remote debug session logfile for GDB.
2    Copyright (C) 1996, 1998, 1999, 2000, 2002, 2003, 2005, 2006, 2007, 2008,
3    2009, 2010 Free Software Foundation, Inc.
4    Written by Fred Fish (fnf@cygnus.com) from pieces of gdbserver.
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 3 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, see <http://www.gnu.org/licenses/>.  */
20
21 #include "config.h"
22 #include <stdio.h>
23 #if HAVE_SYS_FILE_H
24 #include <sys/file.h>
25 #endif
26 #if HAVE_SIGNAL_H
27 #include <signal.h>
28 #endif
29 #include <ctype.h>
30 #if HAVE_FCNTL_H
31 #include <fcntl.h>
32 #endif
33 #if HAVE_ERRNO_H
34 #include <errno.h>
35 #endif
36 #ifdef HAVE_STDLIB_H
37 #include <stdlib.h>
38 #endif
39 #ifdef HAVE_STRING_H
40 #include <string.h>
41 #endif
42 #ifdef HAVE_UNISTD_H
43 #include <unistd.h>
44 #endif
45 #ifdef HAVE_NETINET_IN_H
46 #include <netinet/in.h>
47 #endif
48 #ifdef HAVE_SYS_SOCKET_H
49 #include <sys/socket.h>
50 #endif
51 #if HAVE_NETDB_H
52 #include <netdb.h>
53 #endif
54 #if HAVE_NETINET_TCP_H
55 #include <netinet/tcp.h>
56 #endif
57 #if HAVE_MALLOC_H
58 #include <malloc.h>
59 #endif
60
61 #if USE_WIN32API
62 #include <winsock2.h>
63 #endif
64
65 #ifndef HAVE_SOCKLEN_T
66 typedef int socklen_t;
67 #endif
68
69 /* Sort of a hack... */
70 #define EOL (EOF - 1)
71
72 /* Version information, from version.c.  */
73 extern const char version[];
74 extern const char host_name[];
75
76 static int remote_desc;
77
78 #ifdef __MINGW32CE__
79
80 #ifndef COUNTOF
81 #define COUNTOF(STR) (sizeof (STR) / sizeof ((STR)[0]))
82 #endif
83
84 #define errno (GetLastError ())
85
86 char *
87 strerror (DWORD error)
88 {
89   static char buf[1024];
90   WCHAR *msgbuf;
91   DWORD lasterr = GetLastError ();
92   DWORD chars = FormatMessageW (FORMAT_MESSAGE_FROM_SYSTEM
93                                 | FORMAT_MESSAGE_ALLOCATE_BUFFER,
94                                 NULL,
95                                 error,
96                                 0, /* Default language */
97                                 (LPVOID)&msgbuf,
98                                 0,
99                                 NULL);
100   if (chars != 0)
101     {
102       /* If there is an \r\n appended, zap it.  */
103       if (chars >= 2
104           && msgbuf[chars - 2] == '\r'
105           && msgbuf[chars - 1] == '\n')
106         {
107           chars -= 2;
108           msgbuf[chars] = 0;
109         }
110
111       if (chars > ((COUNTOF (buf)) - 1))
112         {
113           chars = COUNTOF (buf) - 1;
114           msgbuf [chars] = 0;
115         }
116
117       wcstombs (buf, msgbuf, chars + 1);
118       LocalFree (msgbuf);
119     }
120   else
121     sprintf (buf, "unknown win32 error (%ld)", error);
122
123   SetLastError (lasterr);
124   return buf;
125 }
126
127 #endif /* __MINGW32CE__ */
128
129 /* Print the system error message for errno, and also mention STRING
130    as the file name for which the error was encountered.
131    Then return to command level.  */
132
133 static void
134 perror_with_name (const char *string)
135 {
136 #ifndef STDC_HEADERS
137   extern int errno;
138 #endif
139   const char *err;
140   char *combined;
141
142   err = strerror (errno);
143   if (err == NULL)
144     err = "unknown error";
145
146   combined = (char *) alloca (strlen (err) + strlen (string) + 3);
147   strcpy (combined, string);
148   strcat (combined, ": ");
149   strcat (combined, err);
150   fprintf (stderr, "\n%s.\n", combined);
151   fflush (stderr);
152   exit (1);
153 }
154
155 static void
156 sync_error (FILE *fp, char *desc, int expect, int got)
157 {
158   fprintf (stderr, "\n%s\n", desc);
159   fprintf (stderr, "At logfile offset %ld, expected '0x%x' got '0x%x'\n",
160            ftell (fp), expect, got);
161   fflush (stderr);
162   exit (1);
163 }
164
165 static void
166 remote_error (const char *desc)
167 {
168   fprintf (stderr, "\n%s\n", desc);
169   fflush (stderr);
170   exit (1);
171 }
172
173 static void
174 remote_close (void)
175 {
176 #ifdef USE_WIN32API
177   closesocket (remote_desc);
178 #else
179   close (remote_desc);
180 #endif
181 }
182
183 /* Open a connection to a remote debugger.
184    NAME is the filename used for communication.  */
185
186 static void
187 remote_open (char *name)
188 {
189   if (!strchr (name, ':'))
190     {
191       fprintf (stderr, "%s: Must specify tcp connection as host:addr\n", name);
192       fflush (stderr);
193       exit (1);
194     }
195   else
196     {
197 #ifdef USE_WIN32API
198       static int winsock_initialized;
199 #endif
200       char *port_str;
201       int port;
202       struct sockaddr_in sockaddr;
203       socklen_t tmp;
204       int tmp_desc;
205
206       port_str = strchr (name, ':');
207
208       port = atoi (port_str + 1);
209
210 #ifdef USE_WIN32API
211       if (!winsock_initialized)
212         {
213           WSADATA wsad;
214
215           WSAStartup (MAKEWORD (1, 0), &wsad);
216           winsock_initialized = 1;
217         }
218 #endif
219
220       tmp_desc = socket (PF_INET, SOCK_STREAM, 0);
221       if (tmp_desc == -1)
222         perror_with_name ("Can't open socket");
223
224       /* Allow rapid reuse of this port. */
225       tmp = 1;
226       setsockopt (tmp_desc, SOL_SOCKET, SO_REUSEADDR, (char *) &tmp,
227                   sizeof (tmp));
228
229       sockaddr.sin_family = PF_INET;
230       sockaddr.sin_port = htons (port);
231       sockaddr.sin_addr.s_addr = INADDR_ANY;
232
233       if (bind (tmp_desc, (struct sockaddr *) &sockaddr, sizeof (sockaddr))
234           || listen (tmp_desc, 1))
235         perror_with_name ("Can't bind address");
236
237       tmp = sizeof (sockaddr);
238       remote_desc = accept (tmp_desc, (struct sockaddr *) &sockaddr, &tmp);
239       if (remote_desc == -1)
240         perror_with_name ("Accept failed");
241
242       /* Enable TCP keep alive process. */
243       tmp = 1;
244       setsockopt (tmp_desc, SOL_SOCKET, SO_KEEPALIVE, (char *) &tmp, sizeof (tmp));
245
246       /* Tell TCP not to delay small packets.  This greatly speeds up
247          interactive response. */
248       tmp = 1;
249       setsockopt (remote_desc, IPPROTO_TCP, TCP_NODELAY,
250                   (char *) &tmp, sizeof (tmp));
251
252 #ifndef USE_WIN32API
253       close (tmp_desc);         /* No longer need this */
254
255       signal (SIGPIPE, SIG_IGN);        /* If we don't do this, then gdbreplay simply
256                                            exits when the remote side dies.  */
257 #else
258       closesocket (tmp_desc);   /* No longer need this */
259 #endif
260     }
261
262 #if defined(F_SETFL) && defined (FASYNC)
263   fcntl (remote_desc, F_SETFL, FASYNC);
264 #endif
265
266   fprintf (stderr, "Replay logfile using %s\n", name);
267   fflush (stderr);
268 }
269
270 static int
271 tohex (int ch)
272 {
273   if (ch >= '0' && ch <= '9')
274     {
275       return (ch - '0');
276     }
277   if (ch >= 'A' && ch <= 'F')
278     {
279       return (ch - 'A' + 10);
280     }
281   if (ch >= 'a' && ch <= 'f')
282     {
283       return (ch - 'a' + 10);
284     }
285   fprintf (stderr, "\nInvalid hex digit '%c'\n", ch);
286   fflush (stderr);
287   exit (1);
288 }
289
290 static int
291 logchar (FILE *fp)
292 {
293   int ch;
294   int ch2;
295
296   ch = fgetc (fp);
297   fputc (ch, stdout);
298   fflush (stdout);
299   switch (ch)
300     {
301     case '\n':
302       ch = EOL;
303       break;
304     case '\\':
305       ch = fgetc (fp);
306       fputc (ch, stdout);
307       fflush (stdout);
308       switch (ch)
309         {
310         case '\\':
311           break;
312         case 'b':
313           ch = '\b';
314           break;
315         case 'f':
316           ch = '\f';
317           break;
318         case 'n':
319           ch = '\n';
320           break;
321         case 'r':
322           ch = '\r';
323           break;
324         case 't':
325           ch = '\t';
326           break;
327         case 'v':
328           ch = '\v';
329           break;
330         case 'x':
331           ch2 = fgetc (fp);
332           fputc (ch2, stdout);
333           fflush (stdout);
334           ch = tohex (ch2) << 4;
335           ch2 = fgetc (fp);
336           fputc (ch2, stdout);
337           fflush (stdout);
338           ch |= tohex (ch2);
339           break;
340         default:
341           /* Treat any other char as just itself */
342           break;
343         }
344     default:
345       break;
346     }
347   return (ch);
348 }
349
350 static int
351 gdbchar (int desc)
352 {
353   unsigned char fromgdb;
354
355   if (read (desc, &fromgdb, 1) != 1)
356     return -1;
357   else
358     return fromgdb;
359 }
360
361 /* Accept input from gdb and match with chars from fp (after skipping one
362    blank) up until a \n is read from fp (which is not matched) */
363
364 static void
365 expect (FILE *fp)
366 {
367   int fromlog;
368   int fromgdb;
369
370   if ((fromlog = logchar (fp)) != ' ')
371     {
372       sync_error (fp, "Sync error during gdb read of leading blank", ' ',
373                   fromlog);
374     }
375   do
376     {
377       fromlog = logchar (fp);
378       if (fromlog == EOL)
379         break;
380       fromgdb = gdbchar (remote_desc);
381       if (fromgdb < 0)
382         remote_error ("Error during read from gdb");
383     }
384   while (fromlog == fromgdb);
385
386   if (fromlog != EOL)
387     {
388       sync_error (fp, "Sync error during read of gdb packet from log", fromlog,
389                   fromgdb);
390     }
391 }
392
393 /* Play data back to gdb from fp (after skipping leading blank) up until a
394    \n is read from fp (which is discarded and not sent to gdb). */
395
396 static void
397 play (FILE *fp)
398 {
399   int fromlog;
400   char ch;
401
402   if ((fromlog = logchar (fp)) != ' ')
403     {
404       sync_error (fp, "Sync error skipping blank during write to gdb", ' ',
405                   fromlog);
406     }
407   while ((fromlog = logchar (fp)) != EOL)
408     {
409       ch = fromlog;
410       if (write (remote_desc, &ch, 1) != 1)
411         remote_error ("Error during write to gdb");
412     }
413 }
414
415 static void
416 gdbreplay_version (void)
417 {
418   printf ("GNU gdbreplay %s%s\n"
419           "Copyright (C) 2010 Free Software Foundation, Inc.\n"
420           "gdbreplay is free software, covered by the GNU General Public License.\n"
421           "This gdbreplay was configured as \"%s\"\n",
422           PKGVERSION, version, host_name);
423 }
424
425 static void
426 gdbreplay_usage (FILE *stream)
427 {
428   fprintf (stream, "Usage:\tgdbreplay <logfile> <host:port>\n");
429   if (REPORT_BUGS_TO[0] && stream == stdout)
430     fprintf (stream, "Report bugs to \"%s\".\n", REPORT_BUGS_TO);
431 }
432
433 int
434 main (int argc, char *argv[])
435 {
436   FILE *fp;
437   int ch;
438
439   if (argc >= 2 && strcmp (argv[1], "--version") == 0)
440     {
441       gdbreplay_version ();
442       exit (0);
443     }
444   if (argc >= 2 && strcmp (argv[1], "--help") == 0)
445     {
446       gdbreplay_usage (stdout);
447       exit (0);
448     }
449
450   if (argc < 3)
451     {
452       gdbreplay_usage (stderr);
453       exit (1);
454     }
455   fp = fopen (argv[1], "r");
456   if (fp == NULL)
457     {
458       perror_with_name (argv[1]);
459     }
460   remote_open (argv[2]);
461   while ((ch = logchar (fp)) != EOF)
462     {
463       switch (ch)
464         {
465         case 'w':
466           /* data sent from gdb to gdbreplay, accept and match it */
467           expect (fp);
468           break;
469         case 'r':
470           /* data sent from gdbreplay to gdb, play it */
471           play (fp);
472           break;
473         case 'c':
474           /* Command executed by gdb */
475           while ((ch = logchar (fp)) != EOL);
476           break;
477         }
478     }
479   remote_close ();
480   exit (0);
481 }