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