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