bc447ea2e543c7f28dfd28e24bdcb832fd18193f
[dragonfly.git] / gnu / usr.bin / binutils / gdb / i386 / kvm-fbsd.c
1 /* Live and postmortem kernel debugging functions for FreeBSD.
2    Copyright 1996 Free Software Foundation, Inc.
3
4 This file is part of GDB.
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
19
20 /* $FreeBSD: src/gnu/usr.bin/binutils/gdb/i386/kvm-fbsd.c,v 1.17.4.3 2001/12/17 23:06:06 peter Exp $ */
21 /* $DragonFly: src/gnu/usr.bin/binutils/gdb/i386/Attic/kvm-fbsd.c,v 1.4 2003/08/27 03:21:48 dillon Exp $ */
22
23 #define _KERNEL_STRUCTURES
24
25 #include "defs.h"
26
27 #include <errno.h>
28 #include <signal.h>
29 #include <fcntl.h>
30 #include <paths.h>
31 #include <sys/sysctl.h>
32 #include <sys/param.h>
33 #include <sys/time.h>
34 #include <sys/proc.h>
35 #include <sys/user.h>
36 #include <sys/globaldata.h>
37 #include "frame.h"  /* required by inferior.h */
38 #include "inferior.h"
39 #include "symtab.h"
40 #include "symfile.h"
41 #include "objfiles.h"
42 #include "command.h"
43 #include "bfd.h"
44 #include "target.h"
45 #include "gdbcore.h"
46 #include <sys/stat.h>
47 #include <unistd.h>
48 #include <vm/vm.h>
49 #include <vm/vm_param.h>
50
51 #include <machine/vmparam.h>
52 #include <machine/pcb.h>
53 #include <machine/tss.h>
54 #include <machine/frame.h>
55 #include <machine/globaldata.h>
56
57 static void kcore_files_info PARAMS ((struct target_ops *));
58
59 static void kcore_close PARAMS ((int));
60
61 static void get_kcore_registers PARAMS ((int));
62
63 static int kcore_xfer_kmem PARAMS ((CORE_ADDR, char *, int, int, struct target_ops *));
64
65 static int xfer_umem PARAMS ((CORE_ADDR, char *, int, int));
66
67 static CORE_ADDR ksym_lookup PARAMS ((const char *));
68
69 static int read_pcb PARAMS ((int, CORE_ADDR));
70
71 static struct proc * curProc PARAMS ((void));
72
73 static int set_proc_context PARAMS ((CORE_ADDR paddr));
74
75 static void kcore_open PARAMS ((char *filename, int from_tty));
76
77 static void kcore_detach PARAMS ((char *args, int from_tty));
78
79 static void set_proc_cmd PARAMS ((char *arg, int from_tty));
80
81 static void set_cpu_cmd PARAMS ((char *arg, int from_tty));
82
83 static CORE_ADDR kvtophys PARAMS ((int, CORE_ADDR));
84
85 static int physrd PARAMS ((int, u_int, char*, int));
86
87 static int kvm_open PARAMS ((const char *efile, char *cfile, char *sfile,
88                              int perm, char *errout));
89
90 static int kvm_close PARAMS ((int fd));
91
92 static int kvm_write PARAMS ((int core_kd, CORE_ADDR memaddr,
93                               char *myaddr, int len));
94
95 static int kvm_read PARAMS ((int core_kd, CORE_ADDR memaddr,
96                              char *myaddr, int len));
97
98 static int kvm_uread PARAMS ((int core_kd, struct proc *p,
99                               CORE_ADDR memaddr, char *myaddr,
100                               int len));
101
102 static int kernel_core_file_hook PARAMS ((int fd, CORE_ADDR addr,
103                                           char *buf, int len));
104
105 static struct kinfo_proc * kvm_getprocs PARAMS ((int cfd, int op,
106                                                 CORE_ADDR proc, int *cnt));
107
108 extern struct target_ops kcore_ops;     /* Forward decl */
109
110 /* Non-zero means we are debugging a kernel core file */
111 int kernel_debugging = 0;
112 int kernel_writablecore = 0;
113
114 static char *core_file;
115 static int core_kd = -1;
116 static struct proc *cur_proc;
117 static CORE_ADDR kernel_start;
118
119 static int ncpus;
120 static int cpuid;
121 static CORE_ADDR prv_space;     /* per-cpu private space */
122 static int prv_space_size;
123 #define prv_start       (prv_space + cpuid * prv_space_size)
124
125 /*
126  * Read the "thing" at kernel address 'addr' into the space pointed to
127  * by point.  The length of the "thing" is determined by the type of p.
128  * Result is non-zero if transfer fails.
129  */
130 #define kvread(addr, p) \
131         (target_read_memory ((CORE_ADDR)(addr), (char *)(p), sizeof(*(p))))
132
133
134
135 /*
136  * The following is FreeBSD-specific hackery to decode special frames
137  * and elide the assembly-language stub.  This could be made faster by
138  * defining a frame_type field in the machine-dependent frame information,
139  * but we don't think that's too important right now.
140  */
141 enum frametype { tf_normal, tf_trap, tf_interrupt, tf_syscall };
142
143 CORE_ADDR
144 fbsd_kern_frame_saved_pc (fr)
145 struct frame_info *fr;
146 {
147        struct minimal_symbol *sym;
148        CORE_ADDR this_saved_pc;
149        enum frametype frametype;
150
151        this_saved_pc = read_memory_integer (fr->frame + 4, 4);
152        sym = lookup_minimal_symbol_by_pc (this_saved_pc);
153        frametype = tf_normal;
154        if (sym != NULL) {
155                if (strcmp (SYMBOL_NAME(sym), "calltrap") == 0)
156                        frametype = tf_trap;
157                else if (strncmp (SYMBOL_NAME(sym), "Xresume", 7) == 0)
158                        frametype = tf_interrupt;
159                else if (strcmp (SYMBOL_NAME(sym), "Xsyscall") == 0)
160                        frametype = tf_syscall;
161        }
162
163        switch (frametype) {
164        case tf_normal:
165                return (this_saved_pc);
166
167 #define oEIP   offsetof(struct trapframe, tf_eip)
168
169        case tf_trap:
170                return (read_memory_integer (fr->frame + 8 + oEIP, 4));
171
172        case tf_interrupt:
173                return (read_memory_integer (fr->frame + 16 + oEIP, 4));
174
175        case tf_syscall:
176                return (read_memory_integer (fr->frame + 8 + oEIP, 4));
177 #undef oEIP
178        }
179 }
180
181 static CORE_ADDR
182 ksym_lookup (name)
183 const char *name;
184 {
185         struct minimal_symbol *sym;
186
187         sym = lookup_minimal_symbol (name, NULL, NULL);
188         if (sym == NULL)
189                 error ("kernel symbol `%s' not found.", name);
190
191         return SYMBOL_VALUE_ADDRESS (sym);
192 }
193
194 static struct proc *
195 curProc ()
196 {
197     CORE_ADDR td_ptr_addr;
198     CORE_ADDR td_ptr;
199     CORE_ADDR p_ptr_addr;
200     CORE_ADDR p_ptr;
201
202     td_ptr_addr = prv_start + offsetof(struct mdglobaldata, mi.gd_curthread);
203     if (kvread(td_ptr_addr, &td_ptr) != 0)
204         error ("cannot read thread pointer at %08x\n", td_ptr_addr);
205     p_ptr_addr = td_ptr + offsetof(struct thread, td_proc);
206     if (kvread(p_ptr_addr, &p_ptr) != 0)
207         error ("cannot read proc pointer at %08x\n", p_ptr_addr);
208     return((void *)p_ptr);
209 }
210
211 /*
212  * Set the process context to that of the proc structure at
213  * system address paddr.
214  */
215 static int
216 set_proc_context (paddr)
217         CORE_ADDR paddr;
218 {
219   struct proc p;
220
221   if (paddr < kernel_start)
222     return (1);
223
224   cur_proc = (struct proc *)paddr;
225 #ifdef notyet
226   set_kernel_boundaries (cur_proc);
227 #endif
228
229   /* Fetch all registers from core file */
230   target_fetch_registers (-1);
231
232   /* Now, set up the frame cache, and print the top of stack */
233   flush_cached_frames ();
234   set_current_frame (create_new_frame (read_fp (), read_pc ()));
235   select_frame (get_current_frame (), 0);
236   return (0);
237 }
238
239 /* Discard all vestiges of any previous core file
240    and mark data and stack spaces as empty.  */
241
242 /* ARGSUSED */
243 static void
244 kcore_close (quitting)
245      int quitting;
246 {
247   inferior_pid = 0;     /* Avoid confusion from thread stuff */
248
249   if (core_kd)
250     {
251       kvm_close (core_kd);
252       free (core_file);
253       core_file = NULL;
254       core_kd = -1;
255     }
256 }
257
258 /* This routine opens and sets up the core file bfd */
259
260 static void
261 kcore_open (filename, from_tty)
262      char *filename;
263      int from_tty;
264 {
265   const char *p;
266   struct cleanup *old_chain;
267   char buf[256], *cp;
268   int ontop;
269   CORE_ADDR addr;
270   struct pcb pcb;
271
272   target_preopen (from_tty);
273
274   unpush_target (&kcore_ops);
275
276   if (!filename)
277     {
278       /*error (core_kd?*/
279       error ( (core_kd >= 0)?
280              "No core file specified.  (Use `detach' to stop debugging a core file.)"
281              : "No core file specified.");
282     }
283
284   filename = tilde_expand (filename);
285   if (filename[0] != '/')
286     {
287       cp = concat (current_directory, "/", filename, NULL);
288       free (filename);
289       filename = cp;
290     }
291
292   old_chain = make_cleanup (free, filename);
293
294   /*
295    * gdb doesn't really do anything if the exec-file couldn't
296    * be opened (in that case exec_bfd is NULL). Usually that's
297    * no big deal, but kvm_open needs the exec-file's name,
298    * which results in dereferencing a NULL pointer, a real NO-NO !
299    * So, check here if the open of the exec-file succeeded.
300    */
301   if (exec_bfd == NULL) /* the open failed */
302     error ("kgdb could not open the exec-file, please check the name you used !");
303
304   core_kd = kvm_open (exec_bfd->filename, filename, NULL,
305                       kernel_writablecore? O_RDWR : O_RDONLY, "kgdb: ");
306   if (core_kd < 0)
307     perror_with_name (filename);
308
309   /* Looks semi-reasonable. Toss the old core file and work on the new. */
310
311   discard_cleanups (old_chain); /* Don't free filename any more */
312   core_file = filename;
313   ontop = !push_target (&kcore_ops);
314
315   kernel_start = bfd_get_start_address (exec_bfd); /* XXX */
316
317   /* print out the panic string if there is one */
318   if (kvread (ksym_lookup ("panicstr"), &addr) == 0
319       && addr != 0
320       && target_read_memory (addr, buf, sizeof (buf)) == 0)
321     {
322       for (cp = buf; cp < &buf[sizeof (buf)] && *cp; cp++)
323         if (!isascii (*cp) || (!isprint (*cp) && !isspace (*cp)))
324           *cp = '?';
325       *cp = '\0';
326       if (buf[0] != '\0')
327         printf ("panicstr: %s\n", buf);
328     }
329
330   /* Print all the panic messages if possible. */
331   if (symfile_objfile != NULL)
332     {
333       printf ("panic messages:\n---\n");
334       snprintf (buf, sizeof buf,
335                 "/sbin/dmesg -N %s -M %s | \
336                  /usr/bin/awk '/^(panic:|Fatal trap) / { printing = 1 } \
337                                { if (printing) print $0 }'",
338                 symfile_objfile->name, filename);
339       fflush(stdout);
340       system (buf);
341       printf ("---\n");
342     }
343
344   if (!ontop)
345     {
346       warning ("you won't be able to access this core file until you terminate\n\
347 your %s; do ``info files''", target_longname);
348       return;
349     }
350
351   /* we may need this later */
352   cur_proc = (struct proc *)curProc ();
353   /* Now, set up the frame cache, and print the top of stack */
354   flush_cached_frames ();
355   set_current_frame (create_new_frame (read_fp (), read_pc ()));
356   select_frame (get_current_frame (), 0);
357   print_stack_frame (selected_frame, selected_frame_level, 1);
358 }
359
360 static void
361 kcore_detach (args, from_tty)
362      char *args;
363      int from_tty;
364 {
365   if (args)
366     error ("Too many arguments");
367   unpush_target (&kcore_ops);
368   reinit_frame_cache ();
369   if (from_tty)
370     printf_filtered ("No kernel core file now.\n");
371 }
372
373 /* Get the registers out of a core file.  This is the machine-
374    independent part.  Fetch_core_registers is the machine-dependent
375    part, typically implemented in the xm-file for each architecture.  */
376
377 /* We just get all the registers, so we don't use regno.  */
378 /* ARGSUSED */
379
380 #define PCB_ADDR(uptr)  ((char *)uptr + UPAGES * PAGE_SIZE - sizeof(struct pcb))
381
382 static void
383 get_kcore_registers (int regno)
384 {
385     struct user *uaddr;
386     struct thread *td;
387     void *pcb;
388
389     /* find the pcb for the current process */
390     if (cur_proc == NULL)
391         error ("cur_proc is NULL");
392     if (kvread(&cur_proc->p_thread, &td))
393         error ("cannot read cur_proc->p_thread at %p", cur_proc);
394     if (kvread(&td->td_pcb, &pcb))
395         error ("cannot read cur_proc->p_thread->td_pcb at %p", td);
396     if (read_pcb(core_kd, (CORE_ADDR)pcb) < 0)
397         error ("cannot read pcb at %p", pcb);
398 }
399
400 static void
401 kcore_files_info (t)
402      struct target_ops *t;
403 {
404   printf ("\t`%s'\n", core_file);
405 }
406
407 static CORE_ADDR
408 ksym_maxuseraddr()
409 {
410   static CORE_ADDR maxuseraddr;
411   struct minimal_symbol *sym;
412
413   if (maxuseraddr == 0)
414     {
415       sym = lookup_minimal_symbol ("PTmap", NULL, NULL);
416       if (sym == NULL) {
417         maxuseraddr = VM_MAXUSER_ADDRESS;
418       } else {
419         maxuseraddr = SYMBOL_VALUE_ADDRESS (sym);
420       }
421     }
422   return maxuseraddr;
423 }
424
425 static int
426 kcore_xfer_kmem (memaddr, myaddr, len, write, target)
427      CORE_ADDR memaddr;
428      char *myaddr;
429      int len;
430      int write;
431      struct target_ops *target;
432 {
433   int ns;
434   int nu;
435
436   if (memaddr >= ksym_maxuseraddr())
437     nu = 0;
438   else
439     {
440       nu = xfer_umem (memaddr, myaddr, len, write);
441       if (nu <= 0)
442         return (0);
443       if (nu == len)
444         return (nu);
445       memaddr += nu;
446       if (memaddr != ksym_maxuseraddr())
447         return (nu);
448       myaddr += nu;
449       len -= nu;
450     }
451
452   ns = (write ? kvm_write : kvm_read) (core_kd, memaddr, myaddr, len);
453   if (ns < 0)
454     ns = 0;
455
456   return (nu + ns);
457 }
458
459 static int
460 xfer_umem (memaddr, myaddr, len, write)
461      CORE_ADDR memaddr;
462      char *myaddr;
463      int len;
464      int write; /* ignored */
465 {
466   int n;
467   struct proc proc;
468
469   if (cur_proc == NULL || kvread (cur_proc, &proc))
470     error ("cannot read proc at %#x", cur_proc);
471   n = kvm_uread (core_kd, &proc, memaddr, myaddr, len) ;
472
473   if (n < 0)
474     return 0;
475   return n;
476 }
477
478 static CORE_ADDR
479 ksym_kernbase()
480 {
481   static CORE_ADDR kernbase;
482   struct minimal_symbol *sym;
483
484   if (kernbase == 0)
485     {
486       sym = lookup_minimal_symbol ("kernbase", NULL, NULL);
487       if (sym == NULL) {
488         kernbase = KERNBASE;
489       } else {
490         kernbase = SYMBOL_VALUE_ADDRESS (sym);
491       }
492     }
493   return kernbase;
494 }
495
496 #define KERNOFF         (ksym_kernbase())
497 #define INKERNEL(x)     ((x) >= KERNOFF)
498
499 static CORE_ADDR sbr;
500 static CORE_ADDR curpcb;
501 static int found_pcb;
502 static int devmem;
503 static int kfd;
504 static struct pcb pcb;
505
506 static void
507 set_proc_cmd (char *arg, int from_tty)
508 {
509     CORE_ADDR paddr;
510     struct kinfo_proc *kp;
511     int cnt = 0;
512
513     if (!arg)
514         error_no_arg ("proc address for new current process");
515     if (!kernel_debugging)
516         error ("not debugging kernel");
517
518     paddr = (CORE_ADDR)parse_and_eval_address (arg);
519     /* assume it's a proc pointer if it's in the kernel */
520     if (paddr >= kernel_start) {
521         if (set_proc_context(paddr))
522         error("invalid proc address");
523     } else {
524         kp = kvm_getprocs(core_kd, KERN_PROC_PID, paddr, &cnt);
525         if (!cnt)
526             error("invalid pid");
527         if (set_proc_context((CORE_ADDR)kp->kp_eproc.e_paddr))
528             error("invalid proc address");
529     }
530 }
531
532 static CORE_ADDR
533 findpcb(int cfd)
534 {
535     CORE_ADDR td_ptr_addr;
536     CORE_ADDR td_ptr;
537     CORE_ADDR pcb_ptr_addr;
538     CORE_ADDR pcb_ptr;
539
540     td_ptr_addr = prv_start + offsetof(struct mdglobaldata, mi.gd_curthread);
541     td_ptr_addr = kvtophys(cfd, td_ptr_addr);
542     physrd(cfd, td_ptr_addr, (char *)&td_ptr, sizeof(CORE_ADDR));
543     pcb_ptr_addr = td_ptr + offsetof(struct thread, td_pcb);
544     pcb_ptr_addr = kvtophys(cfd, pcb_ptr_addr);
545     physrd(cfd, pcb_ptr_addr, (char *)&pcb_ptr, sizeof(CORE_ADDR));
546     return(pcb_ptr);
547 }
548
549 static void
550 set_cpu_cmd (arg, from_tty)
551      char *arg;
552      int from_tty;
553 {
554   CORE_ADDR paddr;
555   struct kinfo_proc *kp;
556   int cpu, cfd;
557
558   if (!arg)
559     error_no_arg ("cpu number");
560   if (!kernel_debugging)
561     error ("not debugging kernel");
562   if (!ncpus)
563     error ("not debugging SMP kernel");
564
565   cpu = (int)parse_and_eval_address (arg);
566   if (cpu < 0 || cpu > ncpus)
567     error ("cpu number out of range");
568   cpuid = cpu;
569
570   cfd = core_kd;
571   curpcb = findpcb(cfd);
572
573   if (!devmem)
574     paddr = ksym_lookup ("dumppcb") - KERNOFF;
575   else
576     paddr = kvtophys (cfd, curpcb);
577   read_pcb (cfd, paddr);
578   printf ("initial pcb at %lx\n", (unsigned long)paddr);
579
580   if ((cur_proc = curProc()))
581     target_fetch_registers (-1);
582
583   /* Now, set up the frame cache, and print the top of stack */
584   flush_cached_frames ();
585   set_current_frame (create_new_frame (read_fp (), read_pc ()));
586   select_frame (get_current_frame (), 0);
587   print_stack_frame (selected_frame, selected_frame_level, 1);
588 }
589
590 /* substitutes for the stuff in libkvm which doesn't work */
591 /* most of this was taken from the old kgdb */
592
593 /* we don't need all this stuff, but the call should look the same */
594
595 static int
596 kvm_open (efile, cfile, sfile, perm, errout)
597      const char *efile;
598      char *cfile;
599      char *sfile;               /* makes this kvm_open more compatible to the one in libkvm */
600      int perm;
601      char *errout;              /* makes this kvm_open more compatible to the one in libkvm */
602 {
603   struct stat stb;
604   int cfd;
605   CORE_ADDR paddr;
606
607   if ((cfd = open (cfile, perm, 0)) < 0)
608     return (cfd);
609
610   fstat (cfd, &stb);
611   if ((stb.st_mode & S_IFMT) == S_IFCHR
612       && stb.st_rdev == makedev (2, 0))
613     {
614       devmem = 1;
615       kfd = open (_PATH_KMEM, perm, 0);
616     }
617
618   /*
619    * Both UP and SMP use CPU_prvspace.
620    */
621
622   physrd(cfd, ksym_lookup("ncpus") - KERNOFF, (char *)&ncpus, sizeof(ncpus));
623   prv_space = ksym_lookup("CPU_prvspace");
624   prv_space_size = (int)ksym_lookup("gd_idlestack_top");
625   printf("%d cpu%s [%08x,%d]\n", ncpus, (ncpus == 1 ? "" : "s"), prv_space, prv_space_size);
626   cpuid = 0;
627
628   physrd (cfd, ksym_lookup ("IdlePTD") - KERNOFF, (char*)&sbr, sizeof sbr);
629   printf ("IdlePTD at phsyical address 0x%08lx\n", (unsigned long)sbr);
630   curpcb = findpcb(cfd);
631
632   found_pcb = 1; /* for vtophys */
633   if (!devmem)
634     paddr = ksym_lookup ("dumppcb") - KERNOFF;
635   else
636     paddr = kvtophys (cfd, curpcb);
637   read_pcb (cfd, paddr);
638   printf ("initial pcb at physical address 0x%08lx\n", (unsigned long)paddr);
639
640   return (cfd);
641 }
642
643 static int
644 kvm_close (fd)
645      int fd;
646 {
647   return (close (fd));
648 }
649
650 static int
651 kvm_write (core_kd, memaddr, myaddr, len)
652      int core_kd;
653      CORE_ADDR memaddr;
654      char *myaddr;
655 {
656   int cc;
657
658   if (devmem)
659     {
660       if (kfd > 0)
661         {
662           /*
663            * Just like kvm_read, only we write.
664            */
665           errno = 0;
666           if (lseek (kfd, (off_t)memaddr, 0) < 0
667               && errno != 0)
668             {
669               error ("kvm_write:invalid address (%x)", memaddr);
670               return (0);
671             }
672           cc = write (kfd, myaddr, len);
673           if (cc < 0)
674             {
675               error ("kvm_write:write failed");
676               return (0);
677             }
678           else if (cc < len)
679             error ("kvm_write:short write");
680           return (cc);
681         }
682       else
683         return (0);
684     }
685   else
686     {
687       printf ("kvm_write not implemented for dead kernels\n");
688       return (0);
689     }
690   /* NOTREACHED */
691 }
692
693 static int
694 kvm_read (core_kd, memaddr, myaddr, len)
695      int core_kd;
696      CORE_ADDR memaddr;
697      char *myaddr;
698 {
699   return (kernel_core_file_hook (core_kd, memaddr, myaddr, len));
700 }
701
702 static int
703 kvm_uread (core_kd, p, memaddr, myaddr, len)
704      int core_kd;
705      register struct proc *p;
706      CORE_ADDR memaddr;
707      char *myaddr;
708      int len;
709 {
710   register char *cp;
711   char procfile[MAXPATHLEN];
712   ssize_t amount;
713   int fd;
714
715   if (devmem) 
716     {
717       sprintf (procfile, "/proc/%d/mem", p->p_pid);
718       fd = open (procfile, O_RDONLY, 0);
719       if (fd < 0)
720         {
721           error ("cannot open %s", procfile);
722           close (fd);
723           return (0);
724         }
725
726       cp = myaddr;
727       while (len > 0)
728         {
729           errno = 0;
730           if (lseek (fd, (off_t)memaddr, 0) == -1 && errno != 0)
731             {
732               error ("invalid address (%x) in %s", memaddr, procfile);
733               break;
734             }
735           amount = read (fd, cp, len);
736           if (amount < 0)
737             {
738               error ("error reading %s", procfile);
739               break;
740             }
741           if (amount == 0)
742             {
743               error ("EOF reading %s", procfile);
744               break;
745             }
746           cp += amount;
747           memaddr += amount;
748           len -= amount;
749         }
750
751       close (fd);
752       return ((ssize_t) (cp - myaddr));
753     }
754   else
755     return (kernel_core_file_hook (core_kd, memaddr, myaddr, len));
756 }
757
758 static struct kinfo_proc kp;
759
760 /*
761  * try to do what kvm_proclist in libkvm would do
762  */
763 static int
764 kvm_proclist (cfd, pid, p, cnt)
765 int cfd, pid, *cnt;
766 struct proc *p;
767 {
768   struct proc lp;
769
770   for (; p != NULL; p = lp.p_list.le_next) {
771       if (!kvm_read(cfd, (CORE_ADDR)p, (char *)&lp, sizeof (lp)))
772             return (0);
773        if (lp.p_pid != pid)
774            continue;
775        kp.kp_eproc.e_paddr = p;
776        *cnt = 1;
777        return (1);
778   }
779   *cnt = 0;
780   return (0);
781 }
782
783 /*
784  * try to do what kvm_deadprocs in libkvm would do
785  */
786 static struct kinfo_proc *
787 kvm_deadprocs (cfd, pid, cnt)
788 int cfd, pid, *cnt;
789 {
790   CORE_ADDR allproc, zombproc;
791   struct proc *p;
792
793   allproc = ksym_lookup("allproc");
794   if (kvm_read(cfd, allproc, (char *)&p, sizeof (p)) == 0)
795       return (NULL);
796   kvm_proclist (cfd, pid, p, cnt);
797   if (!*cnt) {
798       zombproc = ksym_lookup("zombproc");
799       if (kvm_read(cfd, zombproc, (char *)&p, sizeof (p)) == 0)
800            return (NULL);
801        kvm_proclist (cfd, pid, p, cnt);
802   }
803   return (&kp);
804 }
805
806 /*
807  * try to do what kvm_getprocs in libkvm would do
808  */
809 static struct kinfo_proc *
810 kvm_getprocs (cfd, op, proc, cnt)
811 int cfd, op, *cnt;
812 CORE_ADDR proc;
813 {
814   int mib[4], size;
815
816   *cnt = 0;
817   /* assume it's a pid */
818   if (devmem) { /* "live" kernel, use sysctl */
819       mib[0] = CTL_KERN;
820       mib[1] = KERN_PROC;
821       mib[2] = KERN_PROC_PID;
822       mib[3] = (int)proc;
823       size = sizeof (kp);
824       if (sysctl (mib, 4, &kp, &size, NULL, 0) < 0) {
825             perror("sysctl");
826             *cnt = 0;
827             return (NULL);
828       }
829       if (!size)
830             *cnt = 0;
831       else
832             *cnt = 1;
833       return (&kp);
834   } else
835       return (kvm_deadprocs (cfd, (int)proc, cnt));
836 }
837
838 static int
839 physrd (cfd, addr, dat, len)
840      int cfd;
841      u_int addr;
842      char *dat;
843      int len;
844 {
845   if (lseek (cfd, (off_t)addr, L_SET) == -1)
846     return (-1);
847   return (read (cfd, dat, len));
848 }
849
850 static CORE_ADDR
851 kvtophys (fd, addr)
852      int fd;
853      CORE_ADDR addr;
854 {
855   CORE_ADDR v;
856   unsigned int pte;
857   static CORE_ADDR PTD = -1;
858   CORE_ADDR current_ptd;
859
860   /*
861    * We may no longer have a linear system page table...
862    *
863    * Here's the scoop.  IdlePTD contains the physical address
864    * of a page table directory that always maps the kernel.
865    * IdlePTD is in memory that is mapped 1-to-1, so we can
866    * find it easily given its 'virtual' address from ksym_lookup().
867    * For hysterical reasons, the value of IdlePTD is stored in sbr.
868    *
869    * To look up a kernel address, we first convert it to a 1st-level
870    * address and look it up in IdlePTD.  This gives us the physical
871    * address of a page table page; we extract the 2nd-level part of
872    * VA and read the 2nd-level pte.  Finally, we add the offset part
873    * of the VA into the physical address from the pte and return it.
874    *
875    * User addresses are a little more complicated.  If we don't have
876    * a current PCB from read_pcb(), we use PTD, which is the (fixed)
877    * virtual address of the current ptd.  Since it's NOT in 1-to-1
878    * kernel space, we must look it up using IdlePTD.  If we do have
879    * a pcb, we get the ptd from pcb_ptd.
880    */
881
882   if (INKERNEL (addr))
883     current_ptd = sbr;
884   else if (found_pcb == 0)
885     {
886       if (PTD == -1)
887         PTD = kvtophys (fd, ksym_lookup ("PTD"));
888       current_ptd = PTD;
889     }
890   else
891     current_ptd = pcb.pcb_cr3;
892
893   /*
894    * Read the first-level page table (ptd).
895    */
896   v = current_ptd + ( (unsigned)addr >> PDRSHIFT) * sizeof pte;
897   if (physrd (fd, v, (char *)&pte, sizeof pte) < 0 || (pte&PG_V) == 0)
898     return (~0);
899
900   if (pte & PG_PS)
901     {
902       /*
903        * No second-level page table; ptd describes one 4MB page.
904        * (We assume that the kernel wouldn't set PG_PS without enabling
905        * it cr0, and that the kernel doesn't support 36-bit physical
906        * addresses).
907        */
908 #define PAGE4M_MASK     (NBPDR - 1)
909 #define PG_FRAME4M      (~PAGE4M_MASK)
910       addr = (pte & PG_FRAME4M) + (addr & PAGE4M_MASK);
911     }
912   else
913     {
914       /*
915        * Read the second-level page table.
916        */
917       v = (pte&PG_FRAME) + ((addr >> PAGE_SHIFT)&(NPTEPG-1)) * sizeof pte;
918       if (physrd (fd, v, (char *) &pte, sizeof (pte)) < 0 || (pte&PG_V) == 0)
919         return (~0);
920
921       addr = (pte & PG_FRAME) + (addr & PAGE_MASK);
922     }
923 #if 0
924   printf ("vtophys (%x) -> %x\n", oldaddr, addr);
925 #endif
926   return (addr);
927 }
928
929 static int
930 read_pcb (int fd, CORE_ADDR pcbaddr)
931 {
932     int i;
933     int noreg;
934     CORE_ADDR npcbaddr;
935
936     /* need this for the `proc' command to work */
937     /* this is a bad hack XXX */
938     if (INKERNEL(pcbaddr))
939         npcbaddr = kvtophys(fd, pcbaddr);
940     else
941         npcbaddr = pcbaddr;
942
943     if (physrd (fd, (CORE_ADDR)npcbaddr, (char *)&pcb, sizeof pcb) < 0) {
944         error ("cannot read pcb at %x\n", pcbaddr);
945         return (-1);
946     }
947     printf("PCB EIP=%08x ESP=%08x EBP=%08x\n", pcb.pcb_eip, pcb.pcb_esp, pcb.pcb_ebp);
948
949     /*
950      * get the register values out of the sys pcb and
951      * store them where `read_register' will find them.
952      */
953     /*
954      * XXX many registers aren't available.
955      * XXX for the non-core case, the registers are stale - they are for
956      *     the last context switch to the debugger.
957      * XXX gcc's register numbers aren't all #defined in tm-i386.h.
958      */
959     noreg = 0;
960     for (i = 0; i < 3; ++i)             /* eax,ecx,edx */
961         supply_register (i, (char *)&noreg);
962     supply_register (3, (char *)&pcb.pcb_ebx);
963     supply_register (SP_REGNUM, (char *)&pcb.pcb_esp);
964     supply_register (FP_REGNUM, (char *)&pcb.pcb_ebp);
965     supply_register (6, (char *)&pcb.pcb_esi);
966     supply_register (7, (char *)&pcb.pcb_edi);
967     supply_register (PC_REGNUM, (char *)&pcb.pcb_eip);
968     for (i = 9; i < 14; ++i)            /* eflags, cs, ss, ds, es, fs */
969         supply_register (i, (char *)&noreg);
970     supply_register (15, (char *)&pcb.pcb_gs);
971
972     /* XXX 80387 registers? */
973 }
974
975 /*
976  * read len bytes from kernel virtual address 'addr' into local
977  * buffer 'buf'.  Return numbert of bytes if read ok, 0 otherwise.  On read
978  * errors, portion of buffer not read is zeroed.
979  */
980
981 static int
982 kernel_core_file_hook (fd, addr, buf, len)
983      int fd;
984      CORE_ADDR addr;
985      char *buf;
986      int len;
987 {
988   int i;
989   CORE_ADDR paddr;
990   register char *cp;
991   int cc;
992
993   cp = buf;
994
995   while (len > 0)
996     {
997       paddr = kvtophys (fd, addr);
998       if (paddr == ~0)
999         {
1000           memset (buf, '\000', len);
1001           break;
1002         }
1003       /* we can't read across a page boundary */
1004       i = min (len, PAGE_SIZE - (addr & PAGE_MASK));
1005       if ( (cc = physrd (fd, paddr, cp, i)) <= 0)
1006         {
1007           memset (cp, '\000', len);
1008           return (cp - buf);
1009         }
1010       cp += cc;
1011       addr += cc;
1012       len -= cc;
1013     }
1014   return (cp - buf);
1015 }
1016
1017 static struct target_ops kcore_ops;
1018
1019 void
1020 _initialize_kcorelow()
1021 {
1022   kcore_ops.to_shortname = "kcore";
1023   kcore_ops.to_longname = "Kernel core dump file";
1024   kcore_ops.to_doc =
1025     "Use a core file as a target.  Specify the filename of the core file.";
1026   kcore_ops.to_open = kcore_open;
1027   kcore_ops.to_close = kcore_close;
1028   kcore_ops.to_attach = find_default_attach;
1029   kcore_ops.to_detach = kcore_detach;
1030   kcore_ops.to_fetch_registers = get_kcore_registers;
1031   kcore_ops.to_xfer_memory = kcore_xfer_kmem;
1032   kcore_ops.to_files_info = kcore_files_info;
1033   kcore_ops.to_create_inferior = find_default_create_inferior;
1034   kcore_ops.to_stratum = kcore_stratum;
1035   kcore_ops.to_has_memory = 1;
1036   kcore_ops.to_has_stack = 1;
1037   kcore_ops.to_has_registers = 1;
1038   kcore_ops.to_magic = OPS_MAGIC;
1039
1040   add_target (&kcore_ops);
1041   add_com ("proc", class_obscure, set_proc_cmd, "Set current process context");
1042   add_com ("cpu", class_obscure, set_cpu_cmd, "Set current cpu");
1043 }