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