xref: /titanic_41/usr/src/cmd/mdb/common/mdb/mdb_main.c (revision 5fbb41393be5d63f75952b1d72d4df2642d22557)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #include <sys/types.h>
27 #include <sys/mman.h>
28 #include <sys/priocntl.h>
29 #include <sys/rtpriocntl.h>
30 #include <sys/resource.h>
31 #include <sys/termios.h>
32 #include <sys/param.h>
33 #include <sys/regset.h>
34 #include <sys/frame.h>
35 #include <sys/stack.h>
36 #include <sys/reg.h>
37 
38 #include <libproc.h>
39 #include <libscf.h>
40 #include <alloca.h>
41 #include <unistd.h>
42 #include <string.h>
43 #include <stdlib.h>
44 #include <fcntl.h>
45 #include <dlfcn.h>
46 #include <libctf.h>
47 #include <errno.h>
48 #include <kvm.h>
49 
50 #include <mdb/mdb_lex.h>
51 #include <mdb/mdb_debug.h>
52 #include <mdb/mdb_signal.h>
53 #include <mdb/mdb_string.h>
54 #include <mdb/mdb_modapi.h>
55 #include <mdb/mdb_target.h>
56 #include <mdb/mdb_gelf.h>
57 #include <mdb/mdb_conf.h>
58 #include <mdb/mdb_err.h>
59 #include <mdb/mdb_io_impl.h>
60 #include <mdb/mdb_frame.h>
61 #include <mdb/mdb_set.h>
62 #include <kmdb/kmdb_kctl.h>
63 #include <mdb/mdb.h>
64 
65 #ifndef STACK_BIAS
66 #define	STACK_BIAS	0
67 #endif
68 
69 #if defined(__sparc)
70 #define	STACK_REGISTER	SP
71 #else
72 #define	STACK_REGISTER	REG_FP
73 #endif
74 
75 #ifdef _LP64
76 #define	MDB_DEF_IPATH	\
77 	"%r/usr/platform/%p/lib/adb/%i:" \
78 	"%r/usr/platform/%m/lib/adb/%i:" \
79 	"%r/usr/lib/adb/%i"
80 #define	MDB_DEF_LPATH	\
81 	"%r/usr/platform/%p/lib/mdb/%t/%i:" \
82 	"%r/usr/platform/%m/lib/mdb/%t/%i:" \
83 	"%r/usr/lib/mdb/%t/%i"
84 #else
85 #define	MDB_DEF_IPATH	\
86 	"%r/usr/platform/%p/lib/adb:" \
87 	"%r/usr/platform/%m/lib/adb:" \
88 	"%r/usr/lib/adb"
89 #define	MDB_DEF_LPATH	\
90 	"%r/usr/platform/%p/lib/mdb/%t:" \
91 	"%r/usr/platform/%m/lib/mdb/%t:" \
92 	"%r/usr/lib/mdb/%t"
93 #endif
94 
95 #define	MDB_DEF_PROMPT "> "
96 
97 /*
98  * Similar to the panic_* variables in the kernel, we keep some relevant
99  * information stored in a set of global _mdb_abort_* variables; in the
100  * event that the debugger dumps core, these will aid core dump analysis.
101  */
102 const char *volatile _mdb_abort_str;	/* reason for failure */
103 siginfo_t _mdb_abort_info;		/* signal info for fatal signal */
104 ucontext_t _mdb_abort_ctx;		/* context fatal signal interrupted */
105 int _mdb_abort_rcount;			/* number of times resume requested */
106 int _mdb_self_fd = -1;			/* fd for self as for valid_frame */
107 
108 static void
109 terminate(int status)
110 {
111 	(void) mdb_signal_blockall();
112 	mdb_destroy();
113 	exit(status);
114 }
115 
116 static void
117 print_frame(uintptr_t pc, int fnum)
118 {
119 	Dl_info dli;
120 
121 	if (dladdr((void *)pc, &dli)) {
122 		mdb_iob_printf(mdb.m_err, "    [%d] %s`%s+0x%lx()\n", fnum,
123 		    strbasename(dli.dli_fname), dli.dli_sname,
124 		    pc - (uintptr_t)dli.dli_saddr);
125 	} else
126 		mdb_iob_printf(mdb.m_err, "    [%d] %p()\n", fnum, pc);
127 }
128 
129 static int
130 valid_frame(struct frame *fr)
131 {
132 	static struct frame fake;
133 	uintptr_t addr = (uintptr_t)fr;
134 
135 	if (pread(_mdb_self_fd, &fake, sizeof (fake), addr) != sizeof (fake)) {
136 		mdb_iob_printf(mdb.m_err, "    invalid frame (%p)\n", fr);
137 		return (0);
138 	}
139 
140 	if (addr & (STACK_ALIGN - 1)) {
141 		mdb_iob_printf(mdb.m_err, "    mis-aligned frame (%p)\n", fr);
142 		return (0);
143 	}
144 
145 	return (1);
146 }
147 
148 /*ARGSUSED*/
149 static void
150 flt_handler(int sig, siginfo_t *sip, ucontext_t *ucp, void *data)
151 {
152 	static const struct rlimit rl = {
153 		(rlim_t)RLIM_INFINITY, (rlim_t)RLIM_INFINITY
154 	};
155 
156 	const mdb_idcmd_t *idcp = NULL;
157 
158 	if (mdb.m_frame != NULL && mdb.m_frame->f_cp != NULL)
159 		idcp = mdb.m_frame->f_cp->c_dcmd;
160 
161 	if (sip != NULL)
162 		bcopy(sip, &_mdb_abort_info, sizeof (_mdb_abort_info));
163 	if (ucp != NULL)
164 		bcopy(ucp, &_mdb_abort_ctx, sizeof (_mdb_abort_ctx));
165 
166 	_mdb_abort_info.si_signo = sig;
167 	(void) mdb_signal_sethandler(sig, SIG_DFL, NULL);
168 
169 	/*
170 	 * If there is no current dcmd, or the current dcmd comes from a
171 	 * builtin module, we don't allow resume and always core dump.
172 	 */
173 	if (idcp == NULL || idcp->idc_modp == NULL ||
174 	    idcp->idc_modp == &mdb.m_rmod || idcp->idc_modp->mod_hdl == NULL)
175 		goto dump;
176 
177 	if (mdb.m_term != NULL) {
178 		struct frame *fr = (struct frame *)
179 		    (ucp->uc_mcontext.gregs[STACK_REGISTER] + STACK_BIAS);
180 
181 		char signame[SIG2STR_MAX];
182 		int i = 1;
183 		char c;
184 
185 		if (sig2str(sig, signame) == -1) {
186 			mdb_iob_printf(mdb.m_err,
187 			    "\n*** %s: received signal %d at:\n",
188 			    mdb.m_pname, sig);
189 		} else {
190 			mdb_iob_printf(mdb.m_err,
191 			    "\n*** %s: received signal %s at:\n",
192 			    mdb.m_pname, signame);
193 		}
194 
195 		if (ucp->uc_mcontext.gregs[REG_PC] != 0)
196 			print_frame(ucp->uc_mcontext.gregs[REG_PC], i++);
197 
198 		while (fr != NULL && valid_frame(fr) && fr->fr_savpc != 0) {
199 			print_frame(fr->fr_savpc, i++);
200 			fr = (struct frame *)
201 			    ((uintptr_t)fr->fr_savfp + STACK_BIAS);
202 		}
203 
204 query:
205 		mdb_iob_printf(mdb.m_err, "\n%s: (c)ore dump, (q)uit, "
206 		    "(r)ecover, or (s)top for debugger [cqrs]? ", mdb.m_pname);
207 
208 		mdb_iob_flush(mdb.m_err);
209 
210 		for (;;) {
211 			if (IOP_READ(mdb.m_term, &c, sizeof (c)) != sizeof (c))
212 				goto dump;
213 
214 			switch (c) {
215 			case 'c':
216 			case 'C':
217 				(void) setrlimit(RLIMIT_CORE, &rl);
218 				mdb_iob_printf(mdb.m_err, "\n%s: attempting "
219 				    "to dump core ...\n", mdb.m_pname);
220 				goto dump;
221 
222 			case 'q':
223 			case 'Q':
224 				mdb_iob_discard(mdb.m_out);
225 				mdb_iob_nl(mdb.m_err);
226 				(void) mdb_signal_unblockall();
227 				terminate(1);
228 				/*NOTREACHED*/
229 
230 			case 'r':
231 			case 'R':
232 				mdb_iob_printf(mdb.m_err, "\n%s: unloading "
233 				    "module '%s' ...\n", mdb.m_pname,
234 				    idcp->idc_modp->mod_name);
235 
236 				(void) mdb_module_unload(
237 				    idcp->idc_modp->mod_name, 0);
238 
239 				(void) mdb_signal_sethandler(sig,
240 				    flt_handler, NULL);
241 
242 				_mdb_abort_rcount++;
243 				mdb.m_intr = 0;
244 				mdb.m_pend = 0;
245 
246 				(void) mdb_signal_unblockall();
247 				longjmp(mdb.m_frame->f_pcb, MDB_ERR_ABORT);
248 				/*NOTREACHED*/
249 
250 			case 's':
251 			case 'S':
252 				mdb_iob_printf(mdb.m_err, "\n%s: "
253 				    "attempting to stop pid %d ...\n",
254 				    mdb.m_pname, (int)getpid());
255 
256 				/*
257 				 * Stop ourself; if this fails or we are
258 				 * subsequently continued, ask again.
259 				 */
260 				(void) mdb_signal_raise(SIGSTOP);
261 				(void) mdb_signal_unblockall();
262 				goto query;
263 			}
264 		}
265 	}
266 
267 dump:
268 	if (SI_FROMUSER(sip)) {
269 		(void) mdb_signal_block(sig);
270 		(void) mdb_signal_raise(sig);
271 	}
272 
273 	(void) sigfillset(&ucp->uc_sigmask);
274 	(void) sigdelset(&ucp->uc_sigmask, sig);
275 
276 	if (_mdb_abort_str == NULL)
277 		_mdb_abort_str = "fatal signal received";
278 
279 	ucp->uc_flags |= UC_SIGMASK;
280 	(void) setcontext(ucp);
281 }
282 
283 /*ARGSUSED*/
284 static void
285 int_handler(int sig, siginfo_t *sip, ucontext_t *ucp, void *data)
286 {
287 	if (mdb.m_intr == 0)
288 		longjmp(mdb.m_frame->f_pcb, MDB_ERR_SIGINT);
289 	else
290 		mdb.m_pend++;
291 }
292 
293 static void
294 control_kmdb(int start)
295 {
296 	int fd;
297 
298 	if ((fd = open("/dev/kmdb", O_RDONLY)) < 0)
299 		die("failed to open /dev/kmdb");
300 
301 	if (start) {
302 		char *state = mdb_get_config();
303 
304 		if (ioctl(fd, KMDB_IOC_START, state) < 0)
305 			die("failed to start kmdb");
306 
307 		strfree(state);
308 	} else {
309 		if (ioctl(fd, KMDB_IOC_STOP) < 0)
310 			die("failed to stop kmdb");
311 	}
312 
313 	close(fd);
314 }
315 
316 static void
317 usage(int status)
318 {
319 	mdb_iob_printf(mdb.m_err, "Usage: %s [-fkmuwyAFKMSUW] [+/-o option] "
320 	    "[-p pid] [-s dist] [-I path] [-L path]\n\t[-P prompt] "
321 	    "[-R root] [-V dis-version] [object [core] | core | suffix]\n\n",
322 	    mdb.m_pname);
323 
324 	mdb_iob_puts(mdb.m_err,
325 	    "\t-f force raw file debugging mode\n"
326 	    "\t-k force kernel debugging mode\n"
327 	    "\t-m disable demand-loading of module symbols\n"
328 	    "\t-o set specified debugger option (+o to unset)\n"
329 	    "\t-p attach to specified process-id\n"
330 	    "\t-s set symbol matching distance\n"
331 	    "\t-u force user program debugging mode\n"
332 	    "\t-w enable write mode\n"
333 	    "\t-y send terminal initialization sequences for tty mode\n"
334 	    "\t-A disable automatic loading of mdb modules\n"
335 	    "\t-F enable forcible takeover mode\n"
336 	    "\t-K stop operating system and enter live kernel debugger\n"
337 	    "\t-M preload all module symbols\n"
338 	    "\t-I set initial path for macro files\n"
339 	    "\t-L set initial path for module libs\n"
340 	    "\t-P set command-line prompt\n"
341 	    "\t-R set root directory for pathname expansion\n"
342 	    "\t-S suppress processing of ~/.mdbrc file\n"
343 	    "\t-U unload live kernel debugger\n"
344 	    "\t-W enable I/O-mapped memory access (kernel only)\n"
345 	    "\t-V set disassembler version\n");
346 
347 	terminate(status);
348 }
349 
350 static char *
351 mdb_scf_console_term(void)
352 {
353 	scf_simple_prop_t *prop;
354 	char *term = NULL;
355 
356 	if ((prop = scf_simple_prop_get(NULL,
357 	    "svc:/system/console-login:default", "ttymon",
358 	    "terminal_type")) == NULL)
359 		return (NULL);
360 
361 	if (scf_simple_prop_type(prop) == SCF_TYPE_ASTRING &&
362 	    (term = scf_simple_prop_next_astring(prop)) != NULL)
363 		term = strdup(term);
364 
365 	scf_simple_prop_free(prop);
366 	return (term);
367 }
368 
369 /*
370  * Unpleasant hack: we might be debugging a hypervisor domain dump.
371  * Earlier versions use a non-ELF file.  Later versions are ELF, but are
372  * /always/ ELF64, so our standard ehdr check isn't good enough.  Since
373  * we don't want to know too much about the file format, we'll ask
374  * mdb_kb.
375  */
376 #ifdef __x86
377 static int
378 identify_xvm_file(const char *file, int *longmode)
379 {
380 	int (*identify)(const char *, int *);
381 
382 	if (mdb_module_load("mdb_kb", MDB_MOD_GLOBAL | MDB_MOD_SILENT) != 0)
383 		return (0);
384 
385 	identify = (int (*)())dlsym(RTLD_NEXT, "xkb_identify");
386 
387 	if (identify == NULL)
388 		return (0);
389 
390 	return (identify(file, longmode));
391 }
392 #else
393 /*ARGSUSED*/
394 static int
395 identify_xvm_file(const char *file, int *longmode)
396 {
397 	return (0);
398 }
399 #endif /* __x86 */
400 
401 int
402 main(int argc, char *argv[], char *envp[])
403 {
404 	mdb_tgt_ctor_f *tgt_ctor = NULL;
405 	const char **tgt_argv = alloca(argc * sizeof (char *));
406 	int tgt_argc = 0;
407 	mdb_tgt_t *tgt;
408 
409 	char object[MAXPATHLEN], execname[MAXPATHLEN];
410 	mdb_io_t *in_io, *out_io, *err_io, *null_io;
411 	struct termios tios;
412 	int status, c;
413 	char *p;
414 
415 	const char *Iflag = NULL, *Lflag = NULL, *Vflag = NULL, *pidarg = NULL;
416 	int fflag = 0, Kflag = 0, Rflag = 0, Sflag = 0, Oflag = 0, Uflag = 0;
417 
418 	int ttylike;
419 	int longmode = 0;
420 
421 	stack_t sigstack;
422 
423 	if (realpath(getexecname(), execname) == NULL) {
424 		(void) strncpy(execname, argv[0], MAXPATHLEN);
425 		execname[MAXPATHLEN - 1] = '\0';
426 	}
427 
428 	mdb_create(execname, argv[0]);
429 	bzero(tgt_argv, argc * sizeof (char *));
430 	argv[0] = (char *)mdb.m_pname;
431 	_mdb_self_fd = open("/proc/self/as", O_RDONLY);
432 
433 	mdb.m_env = envp;
434 
435 	out_io = mdb_fdio_create(STDOUT_FILENO);
436 	mdb.m_out = mdb_iob_create(out_io, MDB_IOB_WRONLY);
437 
438 	err_io = mdb_fdio_create(STDERR_FILENO);
439 	mdb.m_err = mdb_iob_create(err_io, MDB_IOB_WRONLY);
440 	mdb_iob_clrflags(mdb.m_err, MDB_IOB_AUTOWRAP);
441 
442 	null_io = mdb_nullio_create();
443 	mdb.m_null = mdb_iob_create(null_io, MDB_IOB_WRONLY);
444 
445 	in_io = mdb_fdio_create(STDIN_FILENO);
446 	if ((mdb.m_termtype = getenv("TERM")) != NULL) {
447 		mdb.m_termtype = strdup(mdb.m_termtype);
448 		mdb.m_flags |= MDB_FL_TERMGUESS;
449 	}
450 	mdb.m_term = NULL;
451 
452 	mdb_dmode(mdb_dstr2mode(getenv("MDB_DEBUG")));
453 	mdb.m_pgid = getpgrp();
454 
455 	if (getenv("_MDB_EXEC") != NULL)
456 		mdb.m_flags |= MDB_FL_EXEC;
457 
458 	/*
459 	 * Setup an alternate signal stack.  When tearing down pipelines in
460 	 * terminate(), we may have to destroy the stack of the context in
461 	 * which we are currently executing the signal handler.
462 	 */
463 	sigstack.ss_sp = mmap(NULL, SIGSTKSZ, PROT_READ | PROT_WRITE,
464 	    MAP_PRIVATE | MAP_ANON, -1, 0);
465 	if (sigstack.ss_sp == MAP_FAILED)
466 		die("could not allocate signal stack");
467 	sigstack.ss_size = SIGSTKSZ;
468 	sigstack.ss_flags = 0;
469 	if (sigaltstack(&sigstack, NULL) != 0)
470 		die("could not set signal stack");
471 
472 	(void) mdb_signal_sethandler(SIGPIPE, SIG_IGN, NULL);
473 	(void) mdb_signal_sethandler(SIGQUIT, SIG_IGN, NULL);
474 
475 	(void) mdb_signal_sethandler(SIGILL, flt_handler, NULL);
476 	(void) mdb_signal_sethandler(SIGTRAP, flt_handler, NULL);
477 	(void) mdb_signal_sethandler(SIGIOT, flt_handler, NULL);
478 	(void) mdb_signal_sethandler(SIGEMT, flt_handler, NULL);
479 	(void) mdb_signal_sethandler(SIGFPE, flt_handler, NULL);
480 	(void) mdb_signal_sethandler(SIGBUS, flt_handler, NULL);
481 	(void) mdb_signal_sethandler(SIGSEGV, flt_handler, NULL);
482 
483 	(void) mdb_signal_sethandler(SIGHUP, (mdb_signal_f *)terminate, NULL);
484 	(void) mdb_signal_sethandler(SIGTERM, (mdb_signal_f *)terminate, NULL);
485 
486 	for (mdb.m_rdvers = RD_VERSION; mdb.m_rdvers > 0; mdb.m_rdvers--) {
487 		if (rd_init(mdb.m_rdvers) == RD_OK)
488 			break;
489 	}
490 
491 	for (mdb.m_ctfvers = CTF_VERSION; mdb.m_ctfvers > 0; mdb.m_ctfvers--) {
492 		if (ctf_version(mdb.m_ctfvers) != -1)
493 			break;
494 	}
495 
496 	if ((p = getenv("HISTSIZE")) != NULL && strisnum(p)) {
497 		mdb.m_histlen = strtoi(p);
498 		if (mdb.m_histlen < 1)
499 			mdb.m_histlen = 1;
500 	}
501 
502 	while (optind < argc) {
503 		while ((c = getopt(argc, argv,
504 		    "fkmo:p:s:uwyACD:FI:KL:MOP:R:SUV:W")) != (int)EOF) {
505 			switch (c) {
506 			case 'f':
507 				fflag++;
508 				tgt_ctor = mdb_rawfile_tgt_create;
509 				break;
510 			case 'k':
511 				tgt_ctor = mdb_kvm_tgt_create;
512 				break;
513 			case 'm':
514 				mdb.m_tgtflags |= MDB_TGT_F_NOLOAD;
515 				mdb.m_tgtflags &= ~MDB_TGT_F_PRELOAD;
516 				break;
517 			case 'o':
518 				if (!mdb_set_options(optarg, TRUE))
519 					terminate(2);
520 				break;
521 			case 'p':
522 				tgt_ctor = mdb_proc_tgt_create;
523 				pidarg = optarg;
524 				break;
525 			case 's':
526 				if (!strisnum(optarg)) {
527 					warn("expected integer following -s\n");
528 					terminate(2);
529 				}
530 				mdb.m_symdist = (size_t)(uint_t)strtoi(optarg);
531 				break;
532 			case 'u':
533 				tgt_ctor = mdb_proc_tgt_create;
534 				break;
535 			case 'w':
536 				mdb.m_tgtflags |= MDB_TGT_F_RDWR;
537 				break;
538 			case 'y':
539 				mdb.m_flags |= MDB_FL_USECUP;
540 				break;
541 			case 'A':
542 				(void) mdb_set_options("nomods", TRUE);
543 				break;
544 			case 'C':
545 				(void) mdb_set_options("noctf", TRUE);
546 				break;
547 			case 'D':
548 				mdb_dmode(mdb_dstr2mode(optarg));
549 				break;
550 			case 'F':
551 				mdb.m_tgtflags |= MDB_TGT_F_FORCE;
552 				break;
553 			case 'I':
554 				Iflag = optarg;
555 				break;
556 			case 'L':
557 				Lflag = optarg;
558 				break;
559 			case 'K':
560 				Kflag++;
561 				break;
562 			case 'M':
563 				mdb.m_tgtflags |= MDB_TGT_F_PRELOAD;
564 				mdb.m_tgtflags &= ~MDB_TGT_F_NOLOAD;
565 				break;
566 			case 'O':
567 				Oflag++;
568 				break;
569 			case 'P':
570 				if (!mdb_set_prompt(optarg))
571 					terminate(2);
572 				break;
573 			case 'R':
574 				(void) strncpy(mdb.m_root, optarg, MAXPATHLEN);
575 				mdb.m_root[MAXPATHLEN - 1] = '\0';
576 				Rflag++;
577 				break;
578 			case 'S':
579 				Sflag++;
580 				break;
581 			case 'U':
582 				Uflag++;
583 				break;
584 			case 'V':
585 				Vflag = optarg;
586 				break;
587 			case 'W':
588 				mdb.m_tgtflags |= MDB_TGT_F_ALLOWIO;
589 				break;
590 			case '?':
591 				if (optopt == '?')
592 					usage(0);
593 				/* FALLTHROUGH */
594 			default:
595 				usage(2);
596 			}
597 		}
598 
599 		if (optind < argc) {
600 			const char *arg = argv[optind++];
601 
602 			if (arg[0] == '+' && strlen(arg) == 2) {
603 				if (arg[1] != 'o') {
604 					warn("illegal option -- %s\n", arg);
605 					terminate(2);
606 				}
607 				if (optind >= argc) {
608 					warn("option requires an argument -- "
609 					    "%s\n", arg);
610 					terminate(2);
611 				}
612 				if (!mdb_set_options(argv[optind++], FALSE))
613 					terminate(2);
614 			} else
615 				tgt_argv[tgt_argc++] = arg;
616 		}
617 	}
618 
619 	if (rd_ctl(RD_CTL_SET_HELPPATH, (void *)mdb.m_root) != RD_OK) {
620 		warn("cannot set librtld_db helper path to %s\n", mdb.m_root);
621 		terminate(2);
622 	}
623 
624 	if (mdb.m_debug & MDB_DBG_HELP)
625 		terminate(0); /* Quit here if we've printed out the tokens */
626 
627 
628 	if (Iflag != NULL && strchr(Iflag, ';') != NULL) {
629 		warn("macro path cannot contain semicolons\n");
630 		terminate(2);
631 	}
632 
633 	if (Lflag != NULL && strchr(Lflag, ';') != NULL) {
634 		warn("module path cannot contain semicolons\n");
635 		terminate(2);
636 	}
637 
638 	if (Kflag || Uflag) {
639 		char *nm;
640 
641 		if (tgt_ctor != NULL || Iflag != NULL) {
642 			warn("neither -f, -k, -p, -u, nor -I "
643 			    "may be used with -K\n");
644 			usage(2);
645 		}
646 
647 		if (Lflag != NULL)
648 			mdb_set_lpath(Lflag);
649 
650 		if ((nm = ttyname(STDIN_FILENO)) == NULL ||
651 		    strcmp(nm, "/dev/console") != 0) {
652 			/*
653 			 * Due to the consequences of typing mdb -K instead of
654 			 * mdb -k on a tty other than /dev/console, we require
655 			 * -F when starting kmdb from a tty other than
656 			 * /dev/console.
657 			 */
658 			if (!(mdb.m_tgtflags & MDB_TGT_F_FORCE)) {
659 				die("-F must also be supplied to start kmdb "
660 				    "from non-console tty\n");
661 			}
662 
663 			if (mdb.m_termtype == NULL || (mdb.m_flags &
664 			    MDB_FL_TERMGUESS)) {
665 				if (mdb.m_termtype != NULL)
666 					strfree(mdb.m_termtype);
667 
668 				if ((mdb.m_termtype = mdb_scf_console_term()) !=
669 				    NULL)
670 					mdb.m_flags |= MDB_FL_TERMGUESS;
671 			}
672 		} else {
673 			/*
674 			 * When on console, $TERM (if set) takes precedence over
675 			 * the SMF setting.
676 			 */
677 			if (mdb.m_termtype == NULL && (mdb.m_termtype =
678 			    mdb_scf_console_term()) != NULL)
679 				mdb.m_flags |= MDB_FL_TERMGUESS;
680 		}
681 
682 		control_kmdb(Kflag);
683 		terminate(0);
684 		/*NOTREACHED*/
685 	}
686 
687 	/*
688 	 * If standard input appears to have tty attributes, attempt to
689 	 * initialize a terminal i/o backend on top of stdin and stdout.
690 	 */
691 	ttylike = (IOP_CTL(in_io, TCGETS, &tios) == 0);
692 	if (ttylike) {
693 		if ((mdb.m_term = mdb_termio_create(mdb.m_termtype,
694 		    in_io, out_io)) == NULL) {
695 			if (!(mdb.m_flags & MDB_FL_EXEC)) {
696 				warn("term init failed: command-line editing "
697 				    "and prompt will not be available\n");
698 			}
699 		} else {
700 			in_io = mdb.m_term;
701 		}
702 	}
703 
704 	mdb.m_in = mdb_iob_create(in_io, MDB_IOB_RDONLY);
705 	if (mdb.m_term != NULL) {
706 		mdb_iob_setpager(mdb.m_out, mdb.m_term);
707 		if (mdb.m_flags & MDB_FL_PAGER)
708 			mdb_iob_setflags(mdb.m_out, MDB_IOB_PGENABLE);
709 		else
710 			mdb_iob_clrflags(mdb.m_out, MDB_IOB_PGENABLE);
711 	} else if (ttylike)
712 		mdb_iob_setflags(mdb.m_in, MDB_IOB_TTYLIKE);
713 	else
714 		mdb_iob_setbuf(mdb.m_in, mdb_alloc(1, UM_SLEEP), 1);
715 
716 	mdb_pservice_init();
717 	mdb_lex_reset();
718 
719 	if ((mdb.m_shell = getenv("SHELL")) == NULL)
720 		mdb.m_shell = "/bin/sh";
721 
722 	/*
723 	 * If the debugger state is to be inherited from a previous instance,
724 	 * restore it now prior to path evaluation so that %R is updated.
725 	 */
726 	if ((p = getenv(MDB_CONFIG_ENV_VAR)) != NULL) {
727 		mdb_set_config(p);
728 		(void) unsetenv(MDB_CONFIG_ENV_VAR);
729 	}
730 
731 	/*
732 	 * Path evaluation part 1: Create the initial module path to allow
733 	 * the target constructor to load a support module.  Then expand
734 	 * any command-line arguments that modify the paths.
735 	 */
736 	if (Iflag != NULL)
737 		mdb_set_ipath(Iflag);
738 	else
739 		mdb_set_ipath(MDB_DEF_IPATH);
740 
741 	if (Lflag != NULL)
742 		mdb_set_lpath(Lflag);
743 	else
744 		mdb_set_lpath(MDB_DEF_LPATH);
745 
746 	if (mdb_get_prompt() == NULL && !(mdb.m_flags & MDB_FL_ADB))
747 		(void) mdb_set_prompt(MDB_DEF_PROMPT);
748 
749 	if (tgt_ctor == mdb_kvm_tgt_create) {
750 		if (pidarg != NULL) {
751 			warn("-p and -k options are mutually exclusive\n");
752 			terminate(2);
753 		}
754 
755 		if (tgt_argc == 0)
756 			tgt_argv[tgt_argc++] = "/dev/ksyms";
757 		if (tgt_argc == 1 && strisnum(tgt_argv[0]) == 0) {
758 			if (mdb.m_tgtflags & MDB_TGT_F_ALLOWIO)
759 				tgt_argv[tgt_argc++] = "/dev/allkmem";
760 			else
761 				tgt_argv[tgt_argc++] = "/dev/kmem";
762 		}
763 	}
764 
765 	if (pidarg != NULL) {
766 		if (tgt_argc != 0) {
767 			warn("-p may not be used with other arguments\n");
768 			terminate(2);
769 		}
770 		if (proc_arg_psinfo(pidarg, PR_ARG_PIDS, NULL, &status) == -1) {
771 			die("cannot attach to %s: %s\n",
772 			    pidarg, Pgrab_error(status));
773 		}
774 		if (strchr(pidarg, '/') != NULL)
775 			(void) mdb_iob_snprintf(object, MAXPATHLEN,
776 			    "%s/object/a.out", pidarg);
777 		else
778 			(void) mdb_iob_snprintf(object, MAXPATHLEN,
779 			    "/proc/%s/object/a.out", pidarg);
780 		tgt_argv[tgt_argc++] = object;
781 		tgt_argv[tgt_argc++] = pidarg;
782 	}
783 
784 	/*
785 	 * Find the first argument that is not a special "-" token.  If one is
786 	 * found, we will examine this file and make some inferences below.
787 	 */
788 	for (c = 0; c < tgt_argc && strcmp(tgt_argv[c], "-") == 0; c++)
789 		continue;
790 
791 	if (c < tgt_argc) {
792 		Elf32_Ehdr ehdr;
793 		mdb_io_t *io;
794 
795 		/*
796 		 * If special "-" tokens preceded an argument, shift the entire
797 		 * argument list to the left to remove the leading "-" args.
798 		 */
799 		if (c > 0) {
800 			bcopy(&tgt_argv[c], tgt_argv,
801 			    sizeof (const char *) * (tgt_argc - c));
802 			tgt_argc -= c;
803 		}
804 
805 		/*
806 		 * If we just have an object file name, and that file doesn't
807 		 * exist, and it's a string of digits, infer it to be a
808 		 * sequence number referring to a pair of crash dump files.
809 		 */
810 		if (tgt_argc == 1 && access(tgt_argv[0], F_OK) == -1 &&
811 		    strisnum(tgt_argv[0])) {
812 
813 			size_t len = strlen(tgt_argv[0]) + 8;
814 			const char *object = tgt_argv[0];
815 
816 			tgt_argv[0] = mdb_alloc(len, UM_SLEEP);
817 			tgt_argv[1] = mdb_alloc(len, UM_SLEEP);
818 
819 			(void) strcpy((char *)tgt_argv[0], "unix.");
820 			(void) strcat((char *)tgt_argv[0], object);
821 			(void) strcpy((char *)tgt_argv[1], "vmcore.");
822 			(void) strcat((char *)tgt_argv[1], object);
823 
824 			tgt_argc = 2;
825 		}
826 
827 		/*
828 		 * We need to open the object file in order to determine its
829 		 * ELF class and potentially re-exec ourself.
830 		 */
831 		if ((io = mdb_fdio_create_path(NULL, tgt_argv[0],
832 		    O_RDONLY, 0)) == NULL)
833 			die("failed to open %s", tgt_argv[0]);
834 
835 		/*
836 		 * If the target is unknown or is not the rawfile target, do
837 		 * a gelf_check to determine if the file is an ELF file.  If
838 		 * it is not and the target is unknown, use the rawfile tgt.
839 		 * Otherwise an ELF-based target is needed, so we must abort.
840 		 */
841 		if (tgt_ctor != mdb_rawfile_tgt_create &&
842 		    mdb_gelf_check(io, &ehdr, ET_NONE) == -1) {
843 			if (tgt_ctor != NULL) {
844 				(void) mdb_gelf_check(io, &ehdr, ET_EXEC);
845 				mdb_io_destroy(io);
846 				terminate(1);
847 			} else
848 				tgt_ctor = mdb_rawfile_tgt_create;
849 		}
850 
851 		mdb_io_destroy(io);
852 
853 		if (identify_xvm_file(tgt_argv[0], &longmode) == 1 &&
854 		    !fflag) {
855 #ifdef _LP64
856 			if (!longmode)
857 				goto reexec;
858 #else
859 			if (longmode)
860 				goto reexec;
861 #endif
862 			tgt_ctor = mdb_kvm_tgt_create;
863 			goto tcreate;
864 		}
865 
866 		if (tgt_ctor == mdb_rawfile_tgt_create)
867 			goto tcreate; /* skip re-exec and just create target */
868 
869 		/*
870 		 * The object file turned out to be a user core file (ET_CORE),
871 		 * and no other arguments were specified, swap 0 and 1.  The
872 		 * proc target will infer the executable for us.
873 		 */
874 		if (ehdr.e_type == ET_CORE) {
875 			tgt_argv[tgt_argc++] = tgt_argv[0];
876 			tgt_argv[0] = NULL;
877 			tgt_ctor = mdb_proc_tgt_create;
878 		}
879 
880 		/*
881 		 * If tgt_argv[1] is filled in, open it up and determine if it
882 		 * is a vmcore file.  If it is, gelf_check will fail and we
883 		 * set tgt_ctor to 'kvm'; otherwise we use the default.
884 		 */
885 		if (tgt_argc > 1 && strcmp(tgt_argv[1], "-") != 0 &&
886 		    tgt_argv[0] != NULL && pidarg == NULL) {
887 			Elf32_Ehdr chdr;
888 
889 			if (access(tgt_argv[1], F_OK) == -1)
890 				die("failed to access %s", tgt_argv[1]);
891 
892 			if ((io = mdb_fdio_create_path(NULL, tgt_argv[1],
893 			    O_RDONLY, 0)) == NULL)
894 				die("failed to open %s", tgt_argv[1]);
895 
896 			if (mdb_gelf_check(io, &chdr, ET_NONE) == -1)
897 				tgt_ctor = mdb_kvm_tgt_create;
898 
899 			mdb_io_destroy(io);
900 		}
901 
902 		/*
903 		 * At this point, we've read the ELF header for either an
904 		 * object file or core into ehdr.  If the class does not match
905 		 * ours, attempt to exec the mdb of the appropriate class.
906 		 */
907 #ifdef _LP64
908 		if (ehdr.e_ident[EI_CLASS] == ELFCLASS32)
909 			goto reexec;
910 #else
911 		if (ehdr.e_ident[EI_CLASS] == ELFCLASS64)
912 			goto reexec;
913 #endif
914 	}
915 
916 tcreate:
917 	if (tgt_ctor == NULL)
918 		tgt_ctor = mdb_proc_tgt_create;
919 
920 	tgt = mdb_tgt_create(tgt_ctor, mdb.m_tgtflags, tgt_argc, tgt_argv);
921 
922 	if (tgt == NULL) {
923 		if (errno == EINVAL)
924 			usage(2); /* target can return EINVAL to get usage */
925 		if (errno == EMDB_TGT)
926 			terminate(1); /* target already printed error msg */
927 		die("failed to initialize target");
928 	}
929 
930 	mdb_tgt_activate(tgt);
931 
932 	mdb_create_loadable_disasms();
933 
934 	if (Vflag != NULL && mdb_dis_select(Vflag) == -1)
935 		warn("invalid disassembler mode -- %s\n", Vflag);
936 
937 
938 	if (Rflag && mdb.m_term != NULL)
939 		warn("Using proto area %s\n", mdb.m_root);
940 
941 	/*
942 	 * If the target was successfully constructed and -O was specified,
943 	 * we now attempt to enter piggy-mode for debugging jurassic problems.
944 	 */
945 	if (Oflag) {
946 		pcinfo_t pci;
947 
948 		(void) strcpy(pci.pc_clname, "RT");
949 
950 		if (priocntl(P_LWPID, P_MYID, PC_GETCID, (caddr_t)&pci) != -1) {
951 			pcparms_t pcp;
952 			rtparms_t *rtp = (rtparms_t *)pcp.pc_clparms;
953 
954 			rtp->rt_pri = 35;
955 			rtp->rt_tqsecs = 0;
956 			rtp->rt_tqnsecs = RT_TQDEF;
957 
958 			pcp.pc_cid = pci.pc_cid;
959 
960 			if (priocntl(P_LWPID, P_MYID, PC_SETPARMS,
961 			    (caddr_t)&pcp) == -1) {
962 				warn("failed to set RT parameters");
963 				Oflag = 0;
964 			}
965 		} else {
966 			warn("failed to get RT class id");
967 			Oflag = 0;
968 		}
969 
970 		if (mlockall(MCL_CURRENT | MCL_FUTURE) == -1) {
971 			warn("failed to lock address space");
972 			Oflag = 0;
973 		}
974 
975 		if (Oflag)
976 			mdb_printf("%s: oink, oink!\n", mdb.m_pname);
977 	}
978 
979 	/*
980 	 * Path evaluation part 2: Re-evaluate the path now that the target
981 	 * is ready (and thus we have access to the real platform string).
982 	 * Do this before reading ~/.mdbrc to allow path modifications prior
983 	 * to performing module auto-loading.
984 	 */
985 	mdb_set_ipath(mdb.m_ipathstr);
986 	mdb_set_lpath(mdb.m_lpathstr);
987 
988 	if (!Sflag && (p = getenv("HOME")) != NULL) {
989 		char rcpath[MAXPATHLEN];
990 		mdb_io_t *rc_io;
991 		int fd;
992 
993 		(void) mdb_iob_snprintf(rcpath, MAXPATHLEN, "%s/.mdbrc", p);
994 		fd = open64(rcpath, O_RDONLY);
995 
996 		if (fd >= 0 && (rc_io = mdb_fdio_create_named(fd, rcpath))) {
997 			mdb_iob_t *iob = mdb_iob_create(rc_io, MDB_IOB_RDONLY);
998 			mdb_iob_t *old = mdb.m_in;
999 
1000 			mdb.m_in = iob;
1001 			(void) mdb_run();
1002 			mdb.m_in = old;
1003 		}
1004 	}
1005 
1006 	if (!(mdb.m_flags & MDB_FL_NOMODS))
1007 		mdb_module_load_all(0);
1008 
1009 	(void) mdb_signal_sethandler(SIGINT, int_handler, NULL);
1010 	while ((status = mdb_run()) == MDB_ERR_ABORT ||
1011 	    status == MDB_ERR_OUTPUT) {
1012 		/*
1013 		 * If a write failed on stdout, give up.  A more informative
1014 		 * error message will already have been printed by mdb_run().
1015 		 */
1016 		if (status == MDB_ERR_OUTPUT &&
1017 		    mdb_iob_getflags(mdb.m_out) & MDB_IOB_ERR) {
1018 			mdb_warn("write to stdout failed, exiting\n");
1019 			break;
1020 		}
1021 		continue;
1022 	}
1023 
1024 	terminate((status == MDB_ERR_QUIT || status == 0) ? 0 : 1);
1025 	/*NOTREACHED*/
1026 	return (0);
1027 
1028 reexec:
1029 	if ((p = strrchr(execname, '/')) == NULL)
1030 		die("cannot determine absolute pathname\n");
1031 #ifdef _LP64
1032 #ifdef __sparc
1033 	(void) strcpy(p, "/../sparcv7/");
1034 #else
1035 	(void) strcpy(p, "/../i86/");
1036 #endif
1037 #else
1038 #ifdef __sparc
1039 	(void) strcpy(p, "/../sparcv9/");
1040 #else
1041 	(void) strcpy(p, "/../amd64/");
1042 #endif
1043 #endif
1044 	(void) strcat(p, mdb.m_pname);
1045 
1046 	if (mdb.m_term != NULL)
1047 		(void) IOP_CTL(in_io, TCSETSW, &tios);
1048 
1049 	(void) putenv("_MDB_EXEC=1");
1050 	(void) execv(execname, argv);
1051 
1052 	/*
1053 	 * If execv fails, suppress ENOEXEC.  Experience shows the most common
1054 	 * reason is that the machine is booted under a 32-bit kernel, in which
1055 	 * case it is clearer to only print the message below.
1056 	 */
1057 	if (errno != ENOEXEC)
1058 		warn("failed to exec %s", execname);
1059 #ifdef _LP64
1060 	die("64-bit %s cannot debug 32-bit program %s\n",
1061 	    mdb.m_pname, tgt_argv[0] ?
1062 	    tgt_argv[0] : tgt_argv[1]);
1063 #else
1064 	die("32-bit %s cannot debug 64-bit program %s\n",
1065 	    mdb.m_pname, tgt_argv[0] ?
1066 	    tgt_argv[0] : tgt_argv[1]);
1067 #endif
1068 
1069 	goto tcreate;
1070 }
1071