xref: /dragonfly/gnu/usr.bin/gdb/kgdb/kgdb.c (revision 28c26f7e)
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 <wrapper.h>
66 #include <observer.h>
67 
68 #include "kgdb.h"
69 
70 static int dumpnr;
71 static int quiet;
72 static int verbose;
73 
74 static char crashdir[PATH_MAX];
75 static char *kernel;
76 static char *remote;
77 static char *vmcore;
78 static struct ui_file *parse_gdberr;
79 
80 static void
81 usage(void)
82 {
83 
84 	fprintf(stderr,
85 	    "usage: %s [-afqv] [-d crashdir] [-c core | -n dumpnr | -r device]\n"
86 	    "\t[kernel [core]]\n", getprogname());
87 	exit(1);
88 }
89 
90 static void
91 kernel_from_dumpnr(int nr)
92 {
93 	char path[PATH_MAX];
94 	FILE *info;
95 	char *s;
96 	struct stat st;
97 	int l;
98 
99 	/*
100 	 * If there's a kernel image right here in the crash directory, then
101 	 * use it.  The kernel image is either called kernel.<nr> or is in a
102 	 * subdirectory kernel.<nr> and called kernel.  The latter allows us
103 	 * to collect the modules in the same place.
104 	 */
105 	snprintf(path, sizeof(path), "%s/kernel.%d", crashdir, nr);
106 	if (stat(path, &st) == 0) {
107 		if (S_ISREG(st.st_mode)) {
108 			kernel = strdup(path);
109 			return;
110 		}
111 		if (S_ISDIR(st.st_mode)) {
112 			snprintf(path, sizeof(path), "%s/kernel.%d/kernel",
113 			    crashdir, nr);
114 			if (stat(path, &st) == 0 && S_ISREG(st.st_mode)) {
115 				kernel = strdup(path);
116 				return;
117 			}
118 		}
119 	}
120 
121 	/*
122 	 * No kernel image here.  Parse the dump header.  The kernel object
123 	 * directory can be found there and we probably have the kernel
124 	 * image still in it.  The object directory may also have a kernel
125 	 * with debugging info (called kernel.debug).  If we have a debug
126 	 * kernel, use it.
127 	 */
128 	snprintf(path, sizeof(path), "%s/info.%d", crashdir, nr);
129 	info = fopen(path, "r");
130 	if (info == NULL) {
131 		warn(path);
132 		return;
133 	}
134 	while (fgets(path, sizeof(path), info) != NULL) {
135 		l = strlen(path);
136 		if (l > 0 && path[l - 1] == '\n')
137 			path[--l] = '\0';
138 		if (strncmp(path, "    ", 4) == 0) {
139 			s = strchr(path, ':');
140 			s = (s == NULL) ? path + 4 : s + 1;
141 			l = snprintf(path, sizeof(path), "%s/kernel.debug", s);
142 			if (stat(path, &st) == -1 || !S_ISREG(st.st_mode)) {
143 				path[l - 6] = '\0';
144 				if (stat(path, &st) == -1 ||
145 				    !S_ISREG(st.st_mode))
146 					break;
147 			}
148 			kernel = strdup(path);
149 			break;
150 		}
151 	}
152 	fclose(info);
153 }
154 
155 static void
156 kgdb_new_objfile(struct objfile *objfile)
157 {
158 	static int once = 1;
159 
160 	if (once && objfile != NULL && objfile == symfile_objfile) {
161 		char *buf;
162 
163 		/*
164 		 * The initial kernel has just been loaded.  Start the
165 		 * remote target if we have one or attach to the core.
166 		 */
167 		once = 0;
168 
169 		if (remote != NULL)
170 			asprintf(&buf, "target remote %s", remote);
171 		else if (vmcore != NULL)
172 			asprintf(&buf, "target kernel %s", vmcore);
173 
174 		if (buf != NULL) {
175 			execute_command(buf, 0);
176 			free(buf);
177 		}
178 	}
179 }
180 
181 /*
182  * Parse an expression and return its value.  If 'quiet' is true, then
183  * any error messages from the parser are masked.
184  */
185 CORE_ADDR
186 kgdb_parse_1(const char *exp, int quiet)
187 {
188 	struct ui_file *old_stderr;
189 	struct cleanup *old_chain;
190 	struct expression *expr;
191 	struct value *val;
192 	char *s;
193 	CORE_ADDR n;
194 
195 	old_stderr = gdb_stderr;
196 	if (quiet)
197 		gdb_stderr = parse_gdberr;
198 	n = 0;
199 	s = xstrdup(exp);
200 	old_chain = make_cleanup(xfree, s);
201 	if (gdb_parse_exp_1(&s, NULL, 0, &expr) && *s == '\0') {
202 		make_cleanup(free_current_contents, &expr);
203 		if (gdb_evaluate_expression(expr, &val))
204 		    n = value_as_address(val);
205 	}
206 	do_cleanups(old_chain);
207 	gdb_stderr = old_stderr;
208 	return (n);
209 }
210 
211 #define	MSGBUF_SEQ_TO_POS(size, seq)	((seq) % (size))
212 
213 void
214 kgdb_dmesg(void)
215 {
216 	CORE_ADDR bufp;
217 	int size, rseq, wseq;
218 	char c;
219 
220 	/*
221 	 * Display the unread portion of the message buffer. This gives the
222 	 * user a some initial data to work from.
223 	 */
224 	if (quiet)
225 		return;
226 	bufp = kgdb_parse("msgbufp->msg_ptr");
227 	size = (int)kgdb_parse("msgbufp->msg_size");
228 	rseq = (int)kgdb_parse("msgbufp->msg_bufr");
229 	wseq = (int)kgdb_parse("msgbufp->msg_bufx");
230 	rseq = MSGBUF_SEQ_TO_POS(size, rseq);
231 	wseq = MSGBUF_SEQ_TO_POS(size, wseq);
232 	if (bufp == 0 || size == 0 || rseq == wseq)
233 		return;
234 
235 	printf("\nUnread portion of the kernel message buffer:\n");
236 	while (rseq < wseq) {
237 		read_memory(bufp + rseq, &c, 1);
238 		putchar(c);
239 		rseq++;
240 		if (rseq == size)
241 			rseq = 0;
242 	}
243 	if (c != '\n')
244 		putchar('\n');
245 	putchar('\n');
246 }
247 
248 static void
249 kgdb_init(char *argv0 __unused)
250 {
251 
252 	parse_gdberr = mem_fileopen();
253 	set_prompt("(kgdb) ");
254 	initialize_kgdb_target();
255 	initialize_kld_target();
256 	observer_attach_new_objfile(kgdb_new_objfile);
257 }
258 
259 /*
260  * Remote targets can support any number of syntaxes and we want to
261  * support them all with one addition: we support specifying a device
262  * node for a serial device without the "/dev/" prefix.
263  *
264  * What we do is to stat(2) the existing remote target first.  If that
265  * fails, we try it with "/dev/" prepended.  If that succeeds we use
266  * the resulting path, otherwise we use the original target.  If
267  * either stat(2) succeeds make sure the file is either a character
268  * device or a FIFO.
269  */
270 static void
271 verify_remote(void)
272 {
273 	char path[PATH_MAX];
274 	struct stat st;
275 
276 	if (stat(remote, &st) != 0) {
277 		snprintf(path, sizeof(path), "/dev/%s", remote);
278 		if (stat(path, &st) != 0)
279 			return;
280 		free(remote);
281 		remote = strdup(path);
282 	}
283 	if (!S_ISCHR(st.st_mode) && !S_ISFIFO(st.st_mode))
284 		errx(1, "%s: not a special file, FIFO or socket", remote);
285 }
286 
287 static void
288 add_arg(struct captured_main_args *args, char *arg)
289 {
290 
291 	args->argc++;
292 	args->argv = reallocf(args->argv, (args->argc + 1) * sizeof(char *));
293 	if (args->argv == NULL)
294 		err(1, "Out of memory building argument list");
295 	args->argv[args->argc] = arg;
296 }
297 
298 int
299 main(int argc, char *argv[])
300 {
301 	char path[PATH_MAX];
302 	struct stat st;
303 	struct captured_main_args args;
304 	char *s;
305 	int a, ch;
306 
307 	dumpnr = -1;
308 
309 	strlcpy(crashdir, "/var/crash", sizeof(crashdir));
310 	s = getenv("KGDB_CRASH_DIR");
311 	if (s != NULL)
312 		strlcpy(crashdir, s, sizeof(crashdir));
313 
314 	/* Convert long options into short options. */
315 	for (a = 1; a < argc; a++) {
316 		s = argv[a];
317 		if (s[0] == '-') {
318 			s++;
319 			/* Long options take either 1 or 2 dashes. */
320 			if (s[0] == '-')
321 				s++;
322 			if (strcmp(s, "quiet") == 0)
323 				argv[a] = "-q";
324 			else if (strcmp(s, "fullname") == 0)
325 				argv[a] = "-f";
326 		}
327 	}
328 
329 	quiet = 0;
330 	memset (&args, 0, sizeof args);
331 	args.use_windows = 0;
332 	args.interpreter_p = INTERP_CONSOLE;
333 	args.argv = malloc(sizeof(char *));
334 	args.argv[0] = argv[0];
335 
336 	while ((ch = getopt(argc, argv, "ac:d:fn:qr:vw")) != -1) {
337 		switch (ch) {
338 		case 'a':
339 			annotation_level++;
340 			break;
341 		case 'c':	/* use given core file. */
342 			if (vmcore != NULL) {
343 				warnx("option %c: can only be specified once",
344 				    optopt);
345 				usage();
346 				/* NOTREACHED */
347 			}
348 			vmcore = strdup(optarg);
349 			break;
350 		case 'd':	/* lookup dumps in given directory. */
351 			strlcpy(crashdir, optarg, sizeof(crashdir));
352 			break;
353 		case 'f':
354 			annotation_level = 1;
355 			break;
356 		case 'n':	/* use dump with given number. */
357 			dumpnr = strtol(optarg, &s, 0);
358 			if (dumpnr < 0 || *s != '\0') {
359 				warnx("option %c: invalid kernel dump number",
360 				    optopt);
361 				usage();
362 				/* NOTREACHED */
363 			}
364 			break;
365 		case 'q':
366 			quiet = 1;
367 			add_arg(&args, "-q");
368 			break;
369 		case 'r':	/* use given device for remote session. */
370 			if (remote != NULL) {
371 				warnx("option %c: can only be specified once",
372 				    optopt);
373 				usage();
374 				/* NOTREACHED */
375 			}
376 			remote = strdup(optarg);
377 			break;
378 		case 'v':	/* increase verbosity. */
379 			verbose++;
380 			break;
381 		case 'w':	/* core file is writeable. */
382 			add_arg(&args, "--write");
383 			break;
384 		case '?':
385 		default:
386 			usage();
387 		}
388 	}
389 
390 	if (((vmcore != NULL) ? 1 : 0) + ((dumpnr >= 0) ? 1 : 0) +
391 	    ((remote != NULL) ? 1 : 0) > 1) {
392 		warnx("options -c, -n and -r are mutually exclusive");
393 		usage();
394 		/* NOTREACHED */
395 	}
396 
397 	if (verbose > 1)
398 		warnx("using %s as the crash directory", crashdir);
399 
400 	if (argc > optind)
401 		kernel = strdup(argv[optind++]);
402 
403 	if (argc > optind && (dumpnr >= 0 || remote != NULL)) {
404 		warnx("options -n and -r do not take a core file. Ignored");
405 		optind = argc;
406 	}
407 
408 	if (dumpnr >= 0) {
409 		snprintf(path, sizeof(path), "%s/vmcore.%d", crashdir, dumpnr);
410 		if (stat(path, &st) == -1)
411 			err(1, path);
412 		if (!S_ISREG(st.st_mode))
413 			errx(1, "%s: not a regular file", path);
414 		vmcore = strdup(path);
415 	} else if (remote != NULL) {
416 		verify_remote();
417 	} else if (argc > optind) {
418 		if (vmcore == NULL)
419 			vmcore = strdup(argv[optind++]);
420 		if (argc > optind)
421 			warnx("multiple core files specified. Ignored");
422 	} else if (vmcore == NULL && kernel == NULL) {
423 		vmcore = strdup(_PATH_MEM);
424 		kernel = strdup(getbootfile());
425 	}
426 
427 	if (verbose) {
428 		if (vmcore != NULL)
429 			warnx("core file: %s", vmcore);
430 		if (remote != NULL)
431 			warnx("device file: %s", remote);
432 		if (kernel != NULL)
433 			warnx("kernel image: %s", kernel);
434 	}
435 
436 	/* A remote target requires an explicit kernel argument. */
437 	if (remote != NULL && kernel == NULL) {
438 		warnx("remote debugging requires a kernel");
439 		usage();
440 		/* NOTREACHED */
441 	}
442 
443 	/* If we don't have a kernel image yet, try to find one. */
444 	if (kernel == NULL) {
445 		if (dumpnr >= 0)
446 			kernel_from_dumpnr(dumpnr);
447 
448 		if (kernel == NULL)
449 			errx(1, "couldn't find a suitable kernel image");
450 		if (verbose)
451 			warnx("kernel image: %s", kernel);
452 	}
453 	add_arg(&args, kernel);
454 
455 	/*
456 	if (vmcore != NULL)
457 		add_arg(&args, vmcore);
458 		*/
459 
460 	/* The libgdb code uses optind too. Reset it... */
461 	optind = 0;
462 
463 	/* Terminate argv list. */
464 	add_arg(&args, NULL);
465 
466 	deprecated_init_ui_hook = kgdb_init;
467 
468 	return (gdb_main(&args));
469 }
470