gdb - Local mods (compile)
[dragonfly.git] / gnu / usr.bin / gdb / kgdb / kgdb.c
1 /*
2  * Copyright (c) 2004 Marcel Moolenaar
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  *
26  * $FreeBSD: src/gnu/usr.bin/gdb/kgdb/main.c,v 1.16 2008/04/29 20:32:45 jhb Exp $
27  */
28
29 #include <sys/cdefs.h>
30
31 #include <sys/param.h>
32 #include <sys/stat.h>
33 #include <sys/types.h>
34 #include <sys/ioctl.h>
35 #include <sys/resource.h>
36 #include <sys/select.h>
37 #include <sys/time.h>
38 #include <sys/wait.h>
39 #include <errno.h>
40 #include <err.h>
41 #include <inttypes.h>
42 #include <kvm.h>
43 #include <limits.h>
44 #include <paths.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <unistd.h>
49
50 /* libgdb stuff. */
51 #include <defs.h>
52 #include <frame.h>
53 #include <frame-unwind.h>
54 #include <inferior.h>
55 #include <interps.h>
56 #include <cli-out.h>
57 #include <main.h>
58 #include <gdbcmd.h>
59 #include <objfiles.h>
60 #include <target.h>
61 #include <top.h>
62 #include <ui-file.h>
63 #include <bfd.h>
64 #include <gdbcore.h>
65 #include <exceptions.h>
66 #include <observer.h>
67 #include <arch-utils.h>
68
69 #include "kgdb.h"
70
71 static int dumpnr;
72 static int quiet;
73 static int verbose;
74
75 static char crashdir[PATH_MAX];
76 static char *kernel;
77 static char *remote;
78 static char *vmcore;
79 static struct ui_file *parse_gdberr;
80
81 static void
82 usage(void)
83 {
84
85         fprintf(stderr,
86             "usage: %s [-afqtvw] [-d crashdir] [-c core | -n dumpnr | -r device]\n"
87             "\t[kernel [core]]\n", getprogname());
88         exit(1);
89 }
90
91 static void
92 kernel_from_dumpnr(int nr)
93 {
94         char path[PATH_MAX];
95         FILE *info;
96         char *s;
97         struct stat st;
98         int l;
99
100         /*
101          * If there's a kernel image right here in the crash directory, then
102          * use it.  The kernel image is either called kern.<nr> or is in a
103          * subdirectory kern.<nr> and called kernel.  The latter allows us
104          * to collect the modules in the same place.
105          */
106         snprintf(path, sizeof(path), "%s/kern.%d", crashdir, nr);
107         if (stat(path, &st) == 0) {
108                 if (S_ISREG(st.st_mode)) {
109                         kernel = strdup(path);
110                         return;
111                 }
112                 if (S_ISDIR(st.st_mode)) {
113                         snprintf(path, sizeof(path), "%s/kern.%d/kernel",
114                             crashdir, nr);
115                         if (stat(path, &st) == 0 && S_ISREG(st.st_mode)) {
116                                 kernel = strdup(path);
117                                 return;
118                         }
119                 }
120         }
121
122         /*
123          * No kernel image here.  Parse the dump header.  The kernel object
124          * directory can be found there and we probably have the kernel
125          * image still in it.  The object directory may also have a kernel
126          * with debugging info (called kernel.debug).  If we have a debug
127          * kernel, use it.
128          */
129         snprintf(path, sizeof(path), "%s/info.%d", crashdir, nr);
130         info = fopen(path, "r");
131         if (info == NULL) {
132                 warn("%s", path);
133                 return;
134         }
135         while (fgets(path, sizeof(path), info) != NULL) {
136                 l = strlen(path);
137                 if (l > 0 && path[l - 1] == '\n')
138                         path[--l] = '\0';
139                 if (strncmp(path, "    ", 4) == 0) {
140                         s = strchr(path, ':');
141                         s = (s == NULL) ? path + 4 : s + 1;
142                         l = snprintf(path, sizeof(path), "%s/kernel.debug", s);
143                         if (stat(path, &st) == -1 || !S_ISREG(st.st_mode)) {
144                                 path[l - 6] = '\0';
145                                 if (stat(path, &st) == -1 ||
146                                     !S_ISREG(st.st_mode))
147                                         break;
148                         }
149                         kernel = strdup(path);
150                         break;
151                 }
152         }
153         fclose(info);
154 }
155
156 static void
157 kgdb_new_objfile(struct objfile *objfile)
158 {
159         static int once = 1;
160
161         if (once && objfile != NULL && objfile == symfile_objfile) {
162                 char *buf;
163
164                 /*
165                  * The initial kernel has just been loaded.  Start the
166                  * remote target if we have one or attach to the core.
167                  */
168                 once = 0;
169
170                 if (remote != NULL)
171                         asprintf(&buf, "target remote %s", remote);
172                 else if (vmcore != NULL)
173                         asprintf(&buf, "target kernel %s", vmcore);
174
175                 if (buf != NULL) {
176                         execute_command(buf, 0);
177                         free(buf);
178                 }
179         }
180 }
181
182 int
183 gdb_parse_exp_1 (const char **stringptr, struct block *block, int comma,
184                  struct expression **expression)
185 {
186   CORE_ADDR pc = 0;
187
188   TRY
189     {
190       *expression = parse_exp_1 (stringptr, pc ,block, comma);
191     }
192   CATCH (except, RETURN_MASK_ERROR)
193   {
194       return 0;
195   }
196   END_CATCH
197
198   return 1;
199 }
200
201 int
202 gdb_evaluate_expression (struct expression *exp, struct value **value)
203 {
204
205   TRY
206     {
207       *value = evaluate_expression(exp);
208     }
209   CATCH (except, RETURN_MASK_ERROR)
210   {
211       return 0;
212   }
213   END_CATCH
214
215   return 1;
216 }
217
218 /*
219  * Parse an expression and return its value.  If 'quiet' is true, then
220  * any error messages from the parser are masked.
221  */
222 CORE_ADDR
223 kgdb_parse_1(const char *exp, int quiet)
224 {
225         struct ui_file *old_stderr;
226         struct cleanup *old_chain;
227         struct expression *expr;
228         struct value *val;
229         const char *s;
230         CORE_ADDR n;
231
232         old_stderr = gdb_stderr;
233         if (quiet)
234                 gdb_stderr = parse_gdberr;
235         n = 0;
236         s = xstrdup(exp);
237         old_chain = make_cleanup(xfree, (char*)s);
238         if (gdb_parse_exp_1(&s, NULL, 0, &expr) && *s == '\0') {
239                 make_cleanup(free_current_contents, &expr);
240                 if (gdb_evaluate_expression(expr, &val))
241                     n = value_as_address(val);
242         }
243         do_cleanups(old_chain);
244         gdb_stderr = old_stderr;
245         return (n);
246 }
247
248 #define MSGBUF_SEQ_TO_POS(size, seq)    ((seq) % (size))
249
250 void
251 kgdb_dmesg(void)
252 {
253         CORE_ADDR bufp;
254         int size, rseq, wseq;
255         char c;
256
257         /*
258          * Display the unread portion of the message buffer. This gives the
259          * user a some initial data to work from.
260          */
261         if (quiet)
262                 return;
263         bufp = kgdb_parse("msgbufp->msg_ptr");
264         size = (int)kgdb_parse("msgbufp->msg_size");
265         if (bufp == 0 || size == 0)
266                 return;
267         rseq = (int)kgdb_parse("msgbufp->msg_bufr");
268         wseq = (int)kgdb_parse("msgbufp->msg_bufx");
269         rseq = MSGBUF_SEQ_TO_POS(size, rseq);
270         wseq = MSGBUF_SEQ_TO_POS(size, wseq);
271         if (rseq == wseq)
272                 return;
273
274         printf("\nUnread portion of the kernel message buffer:\n");
275         while (rseq < wseq) {
276                 read_memory(bufp + rseq, &c, 1);
277                 putchar(c);
278                 rseq++;
279                 if (rseq == size)
280                         rseq = 0;
281         }
282         if (c != '\n')
283                 putchar('\n');
284         putchar('\n');
285 }
286
287 static void
288 kgdb_init(char *argv0 __unused)
289 {
290
291         parse_gdberr = mem_fileopen();
292         set_prompt("(kgdb) ");
293         initialize_kgdb_target();
294         initialize_kld_target();
295         observer_attach_new_objfile(kgdb_new_objfile);
296 }
297
298 /*
299  * Remote targets can support any number of syntaxes and we want to
300  * support them all with one addition: we support specifying a device
301  * node for a serial device without the "/dev/" prefix.
302  *
303  * What we do is to stat(2) the existing remote target first.  If that
304  * fails, we try it with "/dev/" prepended.  If that succeeds we use
305  * the resulting path, otherwise we use the original target.  If
306  * either stat(2) succeeds make sure the file is either a character
307  * device or a FIFO.
308  */
309 static void
310 verify_remote(void)
311 {
312         char path[PATH_MAX];
313         struct stat st;
314
315         if (stat(remote, &st) != 0) {
316                 snprintf(path, sizeof(path), "/dev/%s", remote);
317                 if (stat(path, &st) != 0)
318                         return;
319                 free(remote);
320                 remote = strdup(path);
321         }
322         if (!S_ISCHR(st.st_mode) && !S_ISFIFO(st.st_mode))
323                 errx(1, "%s: not a special file, FIFO or socket", remote);
324 }
325
326 static void
327 add_arg(struct captured_main_args *args, char *arg)
328 {
329
330         args->argc++;
331         args->argv = reallocf(args->argv, (args->argc + 1) * sizeof(char *));
332         if (args->argv == NULL)
333                 err(1, "Out of memory building argument list");
334         args->argv[args->argc] = arg;
335 }
336
337 int
338 main(int argc, char *argv[])
339 {
340         char path[PATH_MAX];
341         struct stat st;
342         struct captured_main_args args;
343         char *s;
344         int a, ch;
345
346         dumpnr = -1;
347
348         strlcpy(crashdir, "/var/crash", sizeof(crashdir));
349         s = getenv("KGDB_CRASH_DIR");
350         if (s != NULL)
351                 strlcpy(crashdir, s, sizeof(crashdir));
352
353         /* Convert long options into short options. */
354         for (a = 1; a < argc; a++) {
355                 s = argv[a];
356                 if (s[0] == '-') {
357                         s++;
358                         /* Long options take either 1 or 2 dashes. */
359                         if (s[0] == '-')
360                                 s++;
361                         if (strcmp(s, "quiet") == 0)
362                                 argv[a] = "-q";
363                         else if (strcmp(s, "fullname") == 0)
364                                 argv[a] = "-f";
365                         else if (strcmp(s, "tui-mode") == 0)
366                                 argv[a] = "-t";
367                 }
368         }
369
370         quiet = 0;
371         memset (&args, 0, sizeof args);
372         args.interpreter_p = INTERP_CONSOLE;
373         args.argv = malloc(sizeof(char *));
374         args.argv[0] = argv[0];
375         add_arg(&args, "--kernel");
376
377         while ((ch = getopt(argc, argv, "ac:d:fn:qr:tvw")) != -1) {
378                 switch (ch) {
379                 case 'a':
380                         annotation_level++;
381                         break;
382                 case 'c':       /* use given core file. */
383                         if (vmcore != NULL) {
384                                 warnx("option %c: can only be specified once",
385                                     optopt);
386                                 usage();
387                                 /* NOTREACHED */
388                         }
389                         vmcore = strdup(optarg);
390                         break;
391                 case 'd':       /* lookup dumps in given directory. */
392                         strlcpy(crashdir, optarg, sizeof(crashdir));
393                         break;
394                 case 'f':
395                         annotation_level = 1;
396                         break;
397                 case 'n':       /* use dump with given number. */
398                         dumpnr = strtol(optarg, &s, 0);
399                         if (dumpnr < 0 || *s != '\0') {
400                                 warnx("option %c: invalid kernel dump number",
401                                     optopt);
402                                 usage();
403                                 /* NOTREACHED */
404                         }
405                         break;
406                 case 'q':
407                         quiet = 1;
408                         add_arg(&args, "-q");
409                         break;
410                 case 'r':       /* use given device for remote session. */
411                         if (remote != NULL) {
412                                 warnx("option %c: can only be specified once",
413                                     optopt);
414                                 usage();
415                                 /* NOTREACHED */
416                         }
417                         remote = strdup(optarg);
418                         break;
419                 case 't':
420                         args.interpreter_p = INTERP_TUI;
421                         add_arg(&args, "-tui");
422                         quiet = 1;
423                         add_arg(&args, "-q");
424                         break;
425                 case 'v':       /* increase verbosity. */
426                         verbose++;
427                         break;
428                 case 'w':       /* core file is writeable. */
429                         add_arg(&args, "--write");
430                         break;
431                 case '?':
432                 default:
433                         usage();
434                 }
435         }
436
437         if (((vmcore != NULL) ? 1 : 0) + ((dumpnr >= 0) ? 1 : 0) +
438             ((remote != NULL) ? 1 : 0) > 1) {
439                 warnx("options -c, -n and -r are mutually exclusive");
440                 usage();
441                 /* NOTREACHED */
442         }
443
444         if (verbose > 1)
445                 warnx("using %s as the crash directory", crashdir);
446
447         if (argc > optind)
448                 kernel = strdup(argv[optind++]);
449
450         if (argc > optind && (dumpnr >= 0 || remote != NULL)) {
451                 warnx("options -n and -r do not take a core file. Ignored");
452                 optind = argc;
453         }
454
455         if (dumpnr >= 0) {
456                 snprintf(path, sizeof(path), "%s/vmcore.%d", crashdir, dumpnr);
457                 if (stat(path, &st) == -1)
458                         err(1, "%s", path);
459                 if (!S_ISREG(st.st_mode))
460                         errx(1, "%s: not a regular file", path);
461                 vmcore = strdup(path);
462         } else if (remote != NULL) {
463                 verify_remote();
464         } else if (argc > optind) {
465                 if (vmcore == NULL)
466                         vmcore = strdup(argv[optind++]);
467                 if (argc > optind)
468                         warnx("multiple core files specified. Ignored");
469         } else if (vmcore == NULL && kernel == NULL) {
470                 vmcore = strdup(_PATH_MEM);
471                 kernel = strdup(getbootfile());
472         }
473
474         if (verbose) {
475                 if (vmcore != NULL)
476                         warnx("core file: %s", vmcore);
477                 if (remote != NULL)
478                         warnx("device file: %s", remote);
479                 if (kernel != NULL)
480                         warnx("kernel image: %s", kernel);
481         }
482
483         /* A remote target requires an explicit kernel argument. */
484         if (remote != NULL && kernel == NULL) {
485                 warnx("remote debugging requires a kernel");
486                 usage();
487                 /* NOTREACHED */
488         }
489
490         /* If we don't have a kernel image yet, try to find one. */
491         if (kernel == NULL) {
492                 if (dumpnr >= 0)
493                         kernel_from_dumpnr(dumpnr);
494
495                 if (kernel == NULL)
496                         errx(1, "couldn't find a suitable kernel image");
497                 if (verbose)
498                         warnx("kernel image: %s", kernel);
499         }
500         add_arg(&args, kernel);
501
502         /*
503         if (vmcore != NULL)
504                 add_arg(&args, vmcore);
505                 */
506
507         /* The libgdb code uses optind too. Reset it... */
508         optind = 0;
509
510         /* Terminate argv list. */
511         add_arg(&args, NULL);
512
513         kgdb_init(NULL);
514
515         return (gdb_main(&args));
516 }