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