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