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