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