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 
27 #include "defs.h"
28 #include "command.h"
29 #include "elf-bfd.h"
30 #include "filenames.h"
31 #include "gdbcore.h"
32 #include "gdbthread.h"
33 #include "gdbsupport/gdb_obstack.h"
34 #include "inferior.h"
35 #include "objfiles.h"
36 #include "osabi.h"
37 #include "process-stratum-target.h"
38 #include "solib.h"
39 #include "target.h"
40 #include "value.h"
41 #include "readline/tilde.h"
42 #include "gdbsupport/buildargv.h"
43 #include "gdbsupport/pathstuff.h"
44 #include "gdbsupport/gdb_tilde_expand.h"
45 
46 #include <sys/user.h>
47 #include <fcntl.h>
48 #include <kvm.h>
49 
50 #include "kgdb.h"
51 
52 static CORE_ADDR stoppcbs;
53 static LONGEST pcb_size;
54 
55 static std::string vmcore;
56 
57 struct fbsd_vmcore_ops
58 {
59   /* Supply registers for a pcb to a register cache.  */
60   void (*supply_pcb)(struct regcache *, CORE_ADDR) = nullptr;
61 
62   /* Return address of pcb for thread running on a CPU. */
63   CORE_ADDR (*cpu_pcb_addr)(u_int) = nullptr;
64 };
65 
66 /* Per-architecture data key.  */
67 static const registry<gdbarch>::key<struct fbsd_vmcore_ops> fbsd_vmcore_data;
68 
69 static struct fbsd_vmcore_ops *
70 get_fbsd_vmcore_ops (struct gdbarch *gdbarch)
71 {
72   struct fbsd_vmcore_ops *ops = fbsd_vmcore_data.get (gdbarch);
73   if (ops == nullptr)
74     ops = fbsd_vmcore_data.emplace (gdbarch);
75   return ops;
76 }
77 
78 /* Set the function that supplies registers from a pcb
79    for architecture GDBARCH to SUPPLY_PCB.  */
80 
81 void
82 fbsd_vmcore_set_supply_pcb (struct gdbarch *gdbarch,
83 			    void (*supply_pcb) (struct regcache *,
84 						CORE_ADDR))
85 {
86   struct fbsd_vmcore_ops *ops = get_fbsd_vmcore_ops (gdbarch);
87   ops->supply_pcb = supply_pcb;
88 }
89 
90 /* Set the function that returns the address of the pcb for a thread
91    running on a CPU for
92    architecture GDBARCH to CPU_PCB_ADDR.  */
93 
94 void
95 fbsd_vmcore_set_cpu_pcb_addr (struct gdbarch *gdbarch,
96 			      CORE_ADDR (*cpu_pcb_addr) (u_int))
97 {
98   struct fbsd_vmcore_ops *ops = get_fbsd_vmcore_ops (gdbarch);
99   ops->cpu_pcb_addr = cpu_pcb_addr;
100 }
101 
102 static CORE_ADDR kernstart;
103 static kvm_t *kvm;
104 int kgdb_quiet;
105 
106 static ptid_t
107 fbsd_vmcore_ptid(int tid)
108 {
109 	if (kvm == NULL)
110 		/*
111 		 * The remote target stores the 'tid' in the lwp
112 		 * field.
113 		 */
114 		return ptid_t(inferior_ptid.pid(), tid, 0);
115 
116 	/*
117 	 * This follows the model described in bsd-kvm.c except that
118 	 * in kernel tids are used as the tid of the ptid instead of a
119 	 * process ID.
120 	 */
121 	return ptid_t(1, 1, tid);
122 }
123 
124 #define	MSGBUF_SEQ_TO_POS(size, seq)	((seq) % (size))
125 
126 static void
127 kgdb_dmesg(void)
128 {
129 	CORE_ADDR bufp;
130 	int size, rseq, wseq;
131 	gdb_byte c;
132 
133 	/*
134 	 * Display the unread portion of the message buffer. This gives the
135 	 * user a some initial data to work from.
136 	 */
137 	if (kgdb_quiet)
138 		return;
139 	try {
140 		bufp = parse_and_eval_address("msgbufp->msg_ptr");
141 		size = parse_and_eval_long("msgbufp->msg_size");
142 		rseq = parse_and_eval_long("msgbufp->msg_rseq");
143 		wseq = parse_and_eval_long("msgbufp->msg_wseq");
144 	} catch (const gdb_exception_error &e) {
145 		return;
146 	}
147 	if (size == 0)
148 		return;
149 	rseq = MSGBUF_SEQ_TO_POS(size, rseq);
150 	wseq = MSGBUF_SEQ_TO_POS(size, wseq);
151 	if (rseq == wseq)
152 		return;
153 
154 	printf("\nUnread portion of the kernel message buffer:\n");
155 	while (rseq < wseq) {
156 		read_memory(bufp + rseq, &c, 1);
157 		putchar(c);
158 		rseq++;
159 		if (rseq == size)
160 			rseq = 0;
161 	}
162 	if (c != '\n')
163 		putchar('\n');
164 	putchar('\n');
165 }
166 
167 #define	KERNEL_INTERP		"/red/herring"
168 
169 enum gdb_osabi
170 fbsd_kernel_osabi_sniffer(bfd *abfd)
171 {
172 	asection *s;
173 	bfd_byte buf[sizeof(KERNEL_INTERP)];
174 	bfd_byte *bufp;
175 
176 	/* First, determine if this is a FreeBSD/ELF binary. */
177 	switch (elf_elfheader(abfd)->e_ident[EI_OSABI]) {
178 	case ELFOSABI_FREEBSD:
179 		break;
180 	case ELFOSABI_NONE: {
181 		enum gdb_osabi osabi = GDB_OSABI_UNKNOWN;
182 
183 		for (asection *sect : gdb_bfd_sections (abfd))
184 		  generic_elf_osabi_sniff_abi_tag_sections (abfd, sect, &osabi);
185 
186 		/*
187 		 * aarch64 and RISC-V kernels don't have the right
188 		 * note tag for kernels so just look for /red/herring
189 		 * anyway.
190 		 */
191 		if (osabi == GDB_OSABI_UNKNOWN &&
192 		    ((elf_elfheader(abfd)->e_machine == EM_AARCH64) ||
193 		    (elf_elfheader(abfd)->e_machine == EM_RISCV)))
194 			break;
195 		if (osabi != GDB_OSABI_FREEBSD)
196 			return (GDB_OSABI_UNKNOWN);
197 		break;
198 	}
199 	default:
200 		return (GDB_OSABI_UNKNOWN);
201 	}
202 
203 	/* FreeBSD ELF kernels have an interpreter path of "/red/herring". */
204 	bufp = buf;
205 	s = bfd_get_section_by_name(abfd, ".interp");
206 	if (s != NULL && bfd_section_size(s) == sizeof(buf) &&
207 	    bfd_get_full_section_contents(abfd, s, &bufp) &&
208 	    memcmp(buf, KERNEL_INTERP, sizeof(buf)) == 0)
209 		return (GDB_OSABI_FREEBSD_KERNEL);
210 
211 	return (GDB_OSABI_UNKNOWN);
212 }
213 
214 /* The FreeBSD libkvm target.  */
215 
216 static const target_info fbsd_kvm_target_info = {
217   "vmcore",
218   N_("Kernel core dump file"),
219   N_("Use a vmcore file as a target.\n\
220 If no filename is specified, /dev/mem is used to examine the running kernel.\n\
221 target vmcore [-w] [filename]")
222 };
223 
224 class fbsd_kvm_target final : public process_stratum_target
225 {
226 public:
227   fbsd_kvm_target () = default;
228 
229   const target_info &info () const override
230   { return fbsd_kvm_target_info; }
231 
232   void close () override;
233 
234   void fetch_registers (struct regcache *, int) override;
235   enum target_xfer_status xfer_partial (enum target_object object,
236 					const char *annex,
237 					gdb_byte *readbuf,
238 					const gdb_byte *writebuf,
239 					ULONGEST offset, ULONGEST len,
240 					ULONGEST *xfered_len) override;
241 
242   void files_info () override;
243   bool thread_alive (ptid_t ptid) override;
244   std::string pid_to_str (ptid_t) override;
245   const char *extra_thread_info (thread_info *) override;
246 
247   bool has_all_memory () override { return false; }
248   bool has_memory () override;
249   bool has_stack () override;
250   bool has_registers () override;
251   bool has_execution (inferior *inf) override { return false; }
252 };
253 
254 /* Target ops for libkvm interface.  */
255 static fbsd_kvm_target fbsd_kvm_ops;
256 
257 #ifdef HAVE_KVM_OPEN2
258 static int
259 kgdb_resolve_symbol(const char *name, kvaddr_t *kva)
260 {
261 	struct bound_minimal_symbol ms;
262 
263 	ms = lookup_minimal_symbol (name, NULL, NULL);
264 	if (ms.minsym == NULL)
265 		return (1);
266 	*kva = ms.value_address ();
267 	return (0);
268 }
269 #endif
270 
271 static void
272 fbsd_kvm_target_open (const char *args, int from_tty)
273 {
274 	struct fbsd_vmcore_ops *ops = get_fbsd_vmcore_ops (current_inferior ()->arch ());
275 	char kvm_err[_POSIX2_LINE_MAX];
276 	struct inferior *inf;
277 	struct cleanup *old_chain;
278 	struct kthr *kt;
279 	kvm_t *nkvm;
280 	const char *kernel;
281 	std::string filename;
282 	LONGEST osreldate;
283 	bool writeable;
284 
285 	if (ops == NULL || ops->supply_pcb == NULL || ops->cpu_pcb_addr == NULL)
286 		error ("ABI doesn't support a vmcore target");
287 
288 	target_preopen (from_tty);
289 	kernel = get_exec_file (0);
290 	if (kernel == NULL)
291 		error ("Can't open a vmcore without a kernel");
292 
293 	writeable = false;
294 	if (args != NULL) {
295 		gdb_argv built_argv (args);
296 
297 		for (char **argv = built_argv.get (); *argv != NULL; argv++) {
298 			if (**argv == '-') {
299 				if (strcmp (*argv, "-w") == 0)
300 					writeable = true;
301 				else
302 					error (_("Invalid argument"));
303 			} else {
304 				if (!filename.empty ())
305 					error (_("Invalid argument"));
306 
307 				filename = gdb_tilde_expand (*argv);
308 				if (!IS_ABSOLUTE_PATH (filename))
309 					filename = gdb_abspath (filename.c_str ());
310 			}
311 		}
312 	}
313 
314 #ifdef HAVE_KVM_OPEN2
315 	nkvm = kvm_open2(kernel, filename.c_str (),
316 	    writeable ? O_RDWR : O_RDONLY, kvm_err, kgdb_resolve_symbol);
317 #else
318 	nkvm = kvm_openfiles(kernel, filename.c_str (), NULL,
319 	    writeable ? O_RDWR : O_RDONLY, kvm_err);
320 #endif
321 	if (nkvm == NULL) {
322 		error ("Failed to open vmcore: %s", kvm_err);
323 	}
324 
325 	/* Don't free the filename now and close any previous vmcore. */
326 	current_inferior ()->unpush_target (&fbsd_kvm_ops);
327 
328 #ifdef HAVE_KVM_DISP
329 	/* Relocate kernel objfile if needed. */
330 	struct objfile *symfile_objfile =
331 	  current_program_space->symfile_object_file;
332 	if (symfile_objfile != nullptr &&
333 	    (bfd_get_file_flags(symfile_objfile->obfd.get ()) &
334 	      (EXEC_P | DYNAMIC)) != 0) {
335 		CORE_ADDR displacement = kvm_kerndisp(nkvm);
336 		if (displacement != 0) {
337 			section_offsets new_offsets (symfile_objfile->section_offsets.size (),
338 			    displacement);
339 			objfile_relocate(symfile_objfile, new_offsets);
340 		}
341 	}
342 #endif
343 
344 	kvm = nkvm;
345 	vmcore = std::move(filename);
346 	target_unpush_up unpusher;
347 	inf = current_inferior();
348 	inf->push_target (&fbsd_kvm_ops);
349 
350 	if (inf->pid == 0) {
351 		inferior_appeared(inf, 1);
352 		inf->fake_pid_p = 1;
353 	}
354 
355 	/*
356 	 * Determine the first address in KVA.  Newer kernels export
357 	 * VM_MAXUSER_ADDRESS and the first kernel address can be
358 	 * determined by adding one.  Older kernels do not provide a
359 	 * symbol that is valid on all platforms, but kernbase is close
360 	 * for most platforms.
361 	 */
362 	try {
363 		kernstart = parse_and_eval_address("vm_maxuser_address") + 1;
364 	} catch (const gdb_exception_error &e) {
365 		kernstart = kgdb_lookup("kernbase");
366 	}
367 
368 	osreldate = parse_and_eval_long("osreldate");
369 
370 	/*
371 	 * Look up symbols needed for stoppcbs handling, but don't
372 	 * fail if they aren't present.
373 	 */
374 	stoppcbs = kgdb_lookup("stoppcbs");
375 	if (osreldate >= 1400088) {
376 		/* stoppcbs is now a pointer rather than an array. */
377 		try {
378 			stoppcbs = read_memory_typed_address(stoppcbs,
379 			    builtin_type(current_inferior ()->arch())->builtin_data_ptr);
380 		} catch (const gdb_exception_error &e) {
381 			stoppcbs = 0;
382 		}
383 	}
384 
385 	try {
386 		pcb_size = parse_and_eval_long("pcb_size");
387 	} catch (const gdb_exception_error &e) {
388 		pcb_size = 0;
389 	}
390 
391 	if (pcb_size == 0) {
392 		try {
393 			pcb_size = parse_and_eval_long("sizeof(struct pcb)");
394 		} catch (const gdb_exception_error &e) {
395 #ifdef HAVE_KVM_OPEN2
396 			if (kvm_native(nkvm))
397 				pcb_size = sizeof(struct pcb);
398 			else
399 				pcb_size = 0;
400 #else
401 			pcb_size = sizeof(struct pcb);
402 #endif
403 		}
404 	}
405 
406 	kgdb_dmesg();
407 
408 	kt = kgdb_thr_init(ops->cpu_pcb_addr);
409 	thread_info *curthr = nullptr;
410 	while (kt != NULL) {
411 		thread_info *thr = add_thread_silent(&fbsd_kvm_ops,
412 		    fbsd_vmcore_ptid(kt->tid));
413 		if (kt == curkthr)
414 			curthr = thr;
415 		kt = kgdb_thr_next(kt);
416 	}
417 	switch_to_thread (curthr);
418 
419 	unpusher.release ();
420 
421 	post_create_inferior (from_tty);
422 
423 	target_fetch_registers (get_thread_regcache (curthr), -1);
424 
425 	reinit_frame_cache ();
426 	print_stack_frame (get_selected_frame (NULL), 0, SRC_AND_LOC, 1);
427 }
428 
429 void
430 fbsd_kvm_target::close()
431 {
432 
433 	if (kvm != NULL) {
434 		switch_to_no_thread ();
435 		exit_inferior (current_inferior ());
436 
437 		clear_solib (current_program_space);
438 		if (kvm_close(kvm) != 0)
439 			warning("cannot close \"%s\": %s", vmcore.c_str (),
440 			    kvm_geterr(kvm));
441 		kvm = NULL;
442 		vmcore.clear ();
443 	}
444 
445 }
446 
447 #if 0
448 static void
449 kgdb_trgt_detach(struct target_ops *ops, const char *args, int from_tty)
450 {
451 
452 	if (args)
453 		error ("Too many arguments");
454 	unpush_target(&kgdb_trgt_ops);
455 	reinit_frame_cache();
456 	if (from_tty)
457 		gdb_printf("No vmcore file now.\n");
458 }
459 #endif
460 
461 const char *
462 fbsd_kvm_target::extra_thread_info(thread_info *ti)
463 {
464 
465 	return (kgdb_thr_extra_thread_info(ti->ptid.tid()));
466 }
467 
468 bool
469 fbsd_kvm_target::has_memory ()
470 {
471   return (kvm != NULL);
472 }
473 
474 bool
475 fbsd_kvm_target::has_stack ()
476 {
477   return (kvm != NULL);
478 }
479 
480 bool
481 fbsd_kvm_target::has_registers ()
482 {
483   return (kvm != NULL);
484 }
485 
486 void
487 fbsd_kvm_target::files_info()
488 {
489 
490 	gdb_printf ("\t`%s', ", vmcore.c_str ());
491 	gdb_stdout->wrap_here (8);
492 	gdb_printf ("file type %s.\n", "FreeBSD kernel vmcore");
493 }
494 
495 std::string
496 fbsd_kvm_target::pid_to_str(ptid_t ptid)
497 {
498   return string_printf (_("Thread %ld"), ptid.tid ());
499 }
500 
501 bool
502 fbsd_kvm_target::thread_alive(ptid_t ptid)
503 {
504 	return (kgdb_thr_lookup_tid(ptid.tid()) != NULL);
505 }
506 
507 void
508 fbsd_kvm_target::fetch_registers(struct regcache *regcache, int regnum)
509 {
510 	struct fbsd_vmcore_ops *ops = get_fbsd_vmcore_ops (regcache->arch ());
511 	struct kthr *kt;
512 
513 	if (ops->supply_pcb == NULL)
514 		return;
515 	kt = kgdb_thr_lookup_tid(regcache->ptid().tid());
516 	if (kt == NULL)
517 		return;
518 	ops->supply_pcb(regcache, kt->pcb);
519 }
520 
521 enum target_xfer_status
522 fbsd_kvm_target::xfer_partial(enum target_object object,
523 		       const char *annex, gdb_byte *readbuf,
524 		       const gdb_byte *writebuf,
525 		       ULONGEST offset, ULONGEST len, ULONGEST *xfered_len)
526 {
527 	ssize_t nbytes;
528 
529 	gdb_assert(kvm != NULL);
530 	switch (object) {
531 	case TARGET_OBJECT_MEMORY:
532 		nbytes = len;
533 		if (readbuf != NULL)
534 #ifdef HAVE_KVM_OPEN2
535 			nbytes = kvm_read2(kvm, offset, readbuf, len);
536 #else
537 			nbytes = kvm_read(kvm, offset, readbuf, len);
538 #endif
539 		if (writebuf != NULL && len > 0)
540 			nbytes = kvm_write(kvm, offset, writebuf, len);
541 		if (nbytes < 0)
542 			return TARGET_XFER_E_IO;
543 		if (nbytes == 0)
544 			return TARGET_XFER_EOF;
545 		*xfered_len = nbytes;
546 		return TARGET_XFER_OK;
547 	default:
548 		return TARGET_XFER_E_IO;
549 	}
550 }
551 
552 static void
553 kgdb_switch_to_thread(const char *arg, int tid)
554 {
555   struct thread_info *tp = fbsd_kvm_ops.find_thread (fbsd_vmcore_ptid (tid));
556   if (tp == NULL)
557     error ("invalid tid");
558   thread_select (arg, tp);
559 }
560 
561 static void
562 kgdb_set_proc_cmd (const char *arg, int from_tty)
563 {
564 	CORE_ADDR addr;
565 	struct kthr *thr;
566 
567 	if (!arg)
568 		error_no_arg ("proc address for the new context");
569 
570 	if (kvm == NULL)
571 		error ("only supported for core file target");
572 
573 	addr = parse_and_eval_address (arg);
574 
575 	if (addr < kernstart) {
576 		thr = kgdb_thr_lookup_pid((int)addr);
577 		if (thr == NULL)
578 			error ("invalid pid");
579 	} else {
580 		thr = kgdb_thr_lookup_paddr(addr);
581 		if (thr == NULL)
582 			error("invalid proc address");
583 	}
584 	kgdb_switch_to_thread(arg, thr->tid);
585 }
586 
587 static void
588 kgdb_set_tid_cmd (const char *arg, int from_tty)
589 {
590 	CORE_ADDR addr;
591 	struct kthr *thr;
592 
593 	if (!arg)
594 		error_no_arg ("TID or thread address for the new context");
595 
596 	addr = (CORE_ADDR) parse_and_eval_address (arg);
597 
598 	if (kvm != NULL && addr >= kernstart) {
599 		thr = kgdb_thr_lookup_taddr(addr);
600 		if (thr == NULL)
601 			error("invalid thread address");
602 		addr = thr->tid;
603 	}
604 	kgdb_switch_to_thread(arg, addr);
605 }
606 
607 void _initialize_kgdb_target ();
608 void
609 _initialize_kgdb_target ()
610 {
611 
612 	add_target(fbsd_kvm_target_info, fbsd_kvm_target_open,
613 	    filename_completer);
614 
615 	add_com ("proc", class_obscure, kgdb_set_proc_cmd,
616 	   "Set current process context");
617 	add_com ("tid", class_obscure, kgdb_set_tid_cmd,
618 	   "Set current thread context");
619 }
620 
621 CORE_ADDR
622 kgdb_trgt_stop_pcb(u_int cpuid)
623 {
624 
625 	if (stoppcbs == 0 || pcb_size == 0)
626 		return 0;
627 
628 	return (stoppcbs + pcb_size * cpuid);
629 }
630