nrelease - fix/improve livecd
[dragonfly.git] / lib / libkvm / kvm_proc.c
1 /*-
2  * Copyright (c) 1989, 1992, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software developed by the Computer Systems
6  * Engineering group at Lawrence Berkeley Laboratory under DARPA contract
7  * BG 91-66 and contributed to Berkeley.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * $FreeBSD: src/lib/libkvm/kvm_proc.c,v 1.25.2.3 2002/08/24 07:27:46 kris Exp $
34  *
35  * @(#)kvm_proc.c       8.3 (Berkeley) 9/23/93
36  */
37
38 /*
39  * Proc traversal interface for kvm.  ps and w are (probably) the exclusive
40  * users of this code, so we've factored it out into a separate module.
41  * Thus, we keep this grunge out of the other kvm applications (i.e.,
42  * most other applications are interested only in open/close/read/nlist).
43  */
44
45 #include <sys/user.h>   /* MUST BE FIRST */
46 #include <sys/conf.h>
47 #include <sys/param.h>
48 #include <sys/exec.h>
49 #include <sys/stat.h>
50 #include <sys/globaldata.h>
51 #include <sys/ioctl.h>
52 #include <sys/tty.h>
53 #include <sys/jail.h>
54 #include <fcntl.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <stddef.h>
58 #include <unistd.h>
59 #include <nlist.h>
60
61 #include <cpu/pmap.h>
62 #include <vm/vm.h>
63 #include <vm/vm_param.h>
64 #include <vm/swap_pager.h>
65
66 #include <sys/sysctl.h>
67
68 #include <limits.h>
69 #include <memory.h>
70 #include <paths.h>
71
72 #include "kvm.h"
73 #include "kvm_private.h"
74
75 dev_t   devid_from_dev(cdev_t dev);
76
77 #define KREAD(kd, addr, obj) \
78         (kvm_read(kd, addr, (char *)(obj), sizeof(*obj)) != sizeof(*obj))
79 #define KREADSTR(kd, addr) \
80         kvm_readstr(kd, (u_long)addr, NULL, NULL)
81
82 static struct kinfo_proc *
83 kinfo_resize_proc(kvm_t *kd, struct kinfo_proc *bp)
84 {
85         if (bp < kd->procend)
86                 return bp;
87
88         size_t pos = bp - kd->procend;
89         size_t size = kd->procend - kd->procbase;
90
91         if (size == 0)
92                 size = 8;
93         else
94                 size *= 2;
95         kd->procbase = _kvm_realloc(kd, kd->procbase, sizeof(*bp) * size);
96         if (kd->procbase == NULL)
97                 return NULL;
98         kd->procend = kd->procbase + size;
99         bp = kd->procbase + pos;
100         return bp;
101 }
102
103 /*
104  * note: this function is also used by /usr/src/sys/kern/kern_kinfo.c as
105  * compiled by userland.
106  */
107 dev_t
108 devid_from_dev(cdev_t dev)
109 {
110         if (dev == NULL)
111                 return NOUDEV;
112         if ((dev->si_umajor & 0xffffff00) ||
113             (dev->si_uminor & 0x0000ff00)) {
114                 return NOUDEV;
115         }
116         return((dev->si_umajor << 8) | dev->si_uminor);
117 }
118
119 /*
120  * Helper routine which traverses the left hand side of a red-black sub-tree.
121  */
122 static uintptr_t
123 kvm_lwptraverse(kvm_t *kd, struct lwp *lwp, uintptr_t lwppos)
124 {
125         for (;;) {
126                 if (KREAD(kd, lwppos, lwp)) {
127                         _kvm_err(kd, kd->program, "can't read lwp at %p",
128                                  (void *)lwppos);
129                         return ((uintptr_t)-1);
130                 }
131                 if (lwp->u.lwp_rbnode.rbe_left == NULL)
132                         break;
133                 lwppos = (uintptr_t)lwp->u.lwp_rbnode.rbe_left;
134         }
135         return(lwppos);
136 }
137
138 /*
139  * Iterate LWPs in a process.
140  *
141  * The first lwp in a red-black tree is a left-side traversal of the tree.
142  */
143 static uintptr_t
144 kvm_firstlwp(kvm_t *kd, struct lwp *lwp, struct proc *proc)
145 {
146         return(kvm_lwptraverse(kd, lwp, (uintptr_t)proc->p_lwp_tree.rbh_root));
147 }
148
149 /*
150  * If the current element is the left side of the parent the next element
151  * will be a left side traversal of the parent's right side.  If the parent
152  * has no right side the next element will be the parent.
153  *
154  * If the current element is the right side of the parent the next element
155  * is the parent.
156  *
157  * If the parent is NULL we are done.
158  */
159 static uintptr_t
160 kvm_nextlwp(kvm_t *kd, uintptr_t lwppos, struct lwp *lwp)
161 {
162         uintptr_t nextpos;
163
164         nextpos = (uintptr_t)lwp->u.lwp_rbnode.rbe_parent;
165         if (nextpos) {
166                 if (KREAD(kd, nextpos, lwp)) {
167                         _kvm_err(kd, kd->program, "can't read lwp at %p",
168                                  (void *)lwppos);
169                         return ((uintptr_t)-1);
170                 }
171                 if (lwppos == (uintptr_t)lwp->u.lwp_rbnode.rbe_left) {
172                         /*
173                          * If we had gone down the left side the next element
174                          * is a left hand traversal of the parent's right
175                          * side, or the parent itself if there is no right
176                          * side.
177                          */
178                         lwppos = (uintptr_t)lwp->u.lwp_rbnode.rbe_right;
179                         if (lwppos)
180                                 nextpos = kvm_lwptraverse(kd, lwp, lwppos);
181                 } else {
182                         /*
183                          * If we had gone down the right side the next
184                          * element is the parent.
185                          */
186                         /* nextpos = nextpos */
187                 }
188         }
189         return(nextpos);
190 }
191
192 /*
193  * Read proc's from memory file into buffer bp, which has space to hold
194  * at most maxcnt procs.
195  */
196 static int
197 kvm_proclist(kvm_t *kd, int what, int arg, struct proc *p,
198              struct kinfo_proc *bp)
199 {
200         struct pgrp pgrp;
201         struct pgrp tpgrp;
202         struct globaldata gdata;
203         struct session sess;
204         struct session tsess;
205         struct tty tty;
206         struct proc proc;
207         struct ucred ucred;
208         struct thread thread;
209         struct proc pproc;
210         struct cdev cdev;
211         struct vmspace vmspace;
212         struct prison prison;
213         struct sigacts sigacts;
214         struct lwp lwp;
215         uintptr_t lwppos;
216         int count;
217         char *wmesg;
218
219         count = 0;
220
221         for (; p != NULL; p = proc.p_list.le_next) {
222                 if (KREAD(kd, (u_long)p, &proc)) {
223                         _kvm_err(kd, kd->program, "can't read proc at %p", p);
224                         return (-1);
225                 }
226                 if (KREAD(kd, (u_long)proc.p_ucred, &ucred)) {
227                         _kvm_err(kd, kd->program, "can't read ucred at %p",
228                                  proc.p_ucred);
229                         return (-1);
230                 }
231                 proc.p_ucred = &ucred;
232
233                 switch(what & ~KERN_PROC_FLAGMASK) {
234
235                 case KERN_PROC_PID:
236                         if (proc.p_pid != (pid_t)arg)
237                                 continue;
238                         break;
239
240                 case KERN_PROC_UID:
241                         if (ucred.cr_uid != (uid_t)arg)
242                                 continue;
243                         break;
244
245                 case KERN_PROC_RUID:
246                         if (ucred.cr_ruid != (uid_t)arg)
247                                 continue;
248                         break;
249                 }
250
251                 if (KREAD(kd, (u_long)proc.p_pgrp, &pgrp)) {
252                         _kvm_err(kd, kd->program, "can't read pgrp at %p",
253                                  proc.p_pgrp);
254                         return (-1);
255                 }
256                 proc.p_pgrp = &pgrp;
257                 if (proc.p_pptr) {
258                   if (KREAD(kd, (u_long)proc.p_pptr, &pproc)) {
259                         _kvm_err(kd, kd->program, "can't read pproc at %p",
260                                  proc.p_pptr);
261                         return (-1);
262                   }
263                   proc.p_pptr = &pproc;
264                 }
265
266                 if (proc.p_sigacts) {
267                         if (KREAD(kd, (u_long)proc.p_sigacts, &sigacts)) {
268                                 _kvm_err(kd, kd->program,
269                                          "can't read sigacts at %p",
270                                          proc.p_sigacts);
271                                 return (-1);
272                         }
273                         proc.p_sigacts = &sigacts;
274                 }
275
276                 if (KREAD(kd, (u_long)pgrp.pg_session, &sess)) {
277                         _kvm_err(kd, kd->program, "can't read session at %p",
278                                 pgrp.pg_session);
279                         return (-1);
280                 }
281                 pgrp.pg_session = &sess;
282
283                 if ((proc.p_flags & P_CONTROLT) && sess.s_ttyp != NULL) {
284                         if (KREAD(kd, (u_long)sess.s_ttyp, &tty)) {
285                                 _kvm_err(kd, kd->program,
286                                          "can't read tty at %p", sess.s_ttyp);
287                                 return (-1);
288                         }
289                         sess.s_ttyp = &tty;
290                         if (tty.t_dev != NULL) {
291                                 if (KREAD(kd, (u_long)tty.t_dev, &cdev))
292                                         tty.t_dev = NULL;
293                                 else
294                                         tty.t_dev = &cdev;
295                         }
296                         if (tty.t_pgrp != NULL) {
297                                 if (KREAD(kd, (u_long)tty.t_pgrp, &tpgrp)) {
298                                         _kvm_err(kd, kd->program,
299                                                  "can't read tpgrp at %p",
300                                                 tty.t_pgrp);
301                                         return (-1);
302                                 }
303                                 tty.t_pgrp = &tpgrp;
304                         }
305                         if (tty.t_session != NULL) {
306                                 if (KREAD(kd, (u_long)tty.t_session, &tsess)) {
307                                         _kvm_err(kd, kd->program,
308                                                  "can't read tsess at %p",
309                                                 tty.t_session);
310                                         return (-1);
311                                 }
312                                 tty.t_session = &tsess;
313                         }
314                 }
315
316                 if (KREAD(kd, (u_long)proc.p_vmspace, &vmspace)) {
317                         _kvm_err(kd, kd->program, "can't read vmspace at %p",
318                                  proc.p_vmspace);
319                         return (-1);
320                 }
321                 proc.p_vmspace = &vmspace;
322
323                 if (ucred.cr_prison != NULL) {
324                         if (KREAD(kd, (u_long)ucred.cr_prison, &prison)) {
325                                 _kvm_err(kd, kd->program, "can't read prison at %p",
326                                          ucred.cr_prison);
327                                 return (-1);
328                         }
329                         ucred.cr_prison = &prison;
330                 }
331
332                 switch (what & ~KERN_PROC_FLAGMASK) {
333
334                 case KERN_PROC_PGRP:
335                         if (proc.p_pgrp->pg_id != (pid_t)arg)
336                                 continue;
337                         break;
338
339                 case KERN_PROC_TTY:
340                         if ((proc.p_flags & P_CONTROLT) == 0 ||
341                             devid_from_dev(proc.p_pgrp->pg_session->s_ttyp->t_dev)
342                                         != (dev_t)arg)
343                                 continue;
344                         break;
345                 }
346
347                 if ((bp = kinfo_resize_proc(kd, bp)) == NULL)
348                         return (-1);
349                 fill_kinfo_proc(&proc, bp);
350                 bp->kp_paddr = (uintptr_t)p;
351
352                 lwppos = kvm_firstlwp(kd, &lwp, &proc);
353                 if (lwppos == 0) {
354                         bp++;           /* Just export the proc then */
355                         count++;
356                 }
357                 while (lwppos && lwppos != (uintptr_t)-1) {
358                         if (p != lwp.lwp_proc) {
359                                 _kvm_err(kd, kd->program, "lwp has wrong parent");
360                                 return (-1);
361                         }
362                         lwp.lwp_proc = &proc;
363                         if (KREAD(kd, (u_long)lwp.lwp_thread, &thread)) {
364                                 _kvm_err(kd, kd->program, "can't read thread at %p",
365                                     lwp.lwp_thread);
366                                 return (-1);
367                         }
368                         lwp.lwp_thread = &thread;
369
370                         if (thread.td_gd) {
371                                 if (KREAD(kd, (u_long)thread.td_gd, &gdata)) {
372                                         _kvm_err(kd, kd->program, "can't read"
373                                                   " gd at %p",
374                                                   thread.td_gd);
375                                         return(-1);
376                                 }
377                                 thread.td_gd = &gdata;
378                         }
379                         if (thread.td_wmesg) {
380                                 wmesg = (void *)KREADSTR(kd, thread.td_wmesg);
381                                 if (wmesg == NULL) {
382                                         _kvm_err(kd, kd->program, "can't read"
383                                                   " wmesg %p",
384                                                   thread.td_wmesg);
385                                         return(-1);
386                                 }
387                                 thread.td_wmesg = wmesg;
388                         } else {
389                                 wmesg = NULL;
390                         }
391
392                         if ((bp = kinfo_resize_proc(kd, bp)) == NULL)
393                                 return (-1);
394                         fill_kinfo_proc(&proc, bp);
395                         fill_kinfo_lwp(&lwp, &bp->kp_lwp);
396                         bp->kp_paddr = (uintptr_t)p;
397                         bp++;
398                         count++;
399                         if (wmesg)
400                                 free(wmesg);
401                         if ((what & KERN_PROC_FLAG_LWP) == 0)
402                                 break;
403                         lwppos = kvm_nextlwp(kd, lwppos, &lwp);
404                 }
405                 if (lwppos == (uintptr_t)-1)
406                         return(-1);
407         }
408         return (count);
409 }
410
411 /*
412  * Build proc info array by reading in proc list from a crash dump.
413  * We reallocate kd->procbase as necessary.
414  */
415 static int
416 kvm_deadprocs(kvm_t *kd, int what, int arg, int allproc_hsize, long procglob)
417 {
418         struct kinfo_proc *bp;
419         struct proc *p;
420         struct proclist **pl;
421         int cnt, partcnt, n;
422         u_long nextoff;
423         u_long a_allproc;
424
425         cnt = partcnt = 0;
426         nextoff = 0;
427
428         /*
429          * Dynamically allocate space for all the elements of the
430          * allprocs array and KREAD() them.
431          */
432         pl = _kvm_malloc(kd, allproc_hsize * sizeof(struct proclist *));
433         for (n = 0; n < allproc_hsize; n++) {
434                 pl[n] = _kvm_malloc(kd, sizeof(struct proclist));
435                 a_allproc = procglob +
436                             sizeof(struct procglob) * n +
437                             offsetof(struct procglob, allproc);
438                 nextoff = a_allproc;
439                 if (KREAD(kd, (u_long)nextoff, pl[n])) {
440                         _kvm_err(kd, kd->program, "can't read proclist at 0x%lx",
441                                 a_allproc);
442                         return (-1);
443                 }
444
445                 /* Ignore empty proclists */
446                 if (LIST_EMPTY(pl[n]))
447                         continue;
448
449                 bp = kd->procbase + cnt;
450                 p = pl[n]->lh_first;
451                 partcnt = kvm_proclist(kd, what, arg, p, bp);
452                 if (partcnt < 0) {
453                         free(pl[n]);
454                         return (partcnt);
455                 }
456
457                 cnt += partcnt;
458                 free(pl[n]);
459         }
460
461         return (cnt);
462 }
463
464 struct kinfo_proc *
465 kvm_getprocs(kvm_t *kd, int op, int arg, int *cnt)
466 {
467         int mib[4], st, nprocs, allproc_hsize;
468         int miblen = ((op & ~KERN_PROC_FLAGMASK) == KERN_PROC_ALL) ? 3 : 4;
469         size_t size;
470
471         if (kd->procbase != NULL) {
472                 free(kd->procbase);
473                 kd->procbase = NULL;
474         }
475         if (kvm_ishost(kd)) {
476                 size = 0;
477                 mib[0] = CTL_KERN;
478                 mib[1] = KERN_PROC;
479                 mib[2] = op;
480                 mib[3] = arg;
481                 st = sysctl(mib, miblen, NULL, &size, NULL, 0);
482                 if (st == -1) {
483                         _kvm_syserr(kd, kd->program, "kvm_getprocs");
484                         return (0);
485                 }
486                 do {
487                         size += size / 10;
488                         kd->procbase = (struct kinfo_proc *)
489                             _kvm_realloc(kd, kd->procbase, size);
490                         if (kd->procbase == 0)
491                                 return (0);
492                         st = sysctl(mib, miblen, kd->procbase, &size, NULL, 0);
493                 } while (st == -1 && errno == ENOMEM);
494                 if (st == -1) {
495                         _kvm_syserr(kd, kd->program, "kvm_getprocs");
496                         return (0);
497                 }
498                 if (size % sizeof(struct kinfo_proc) != 0) {
499                         _kvm_err(kd, kd->program,
500                                 "proc size mismatch (%zd total, %zd chunks)",
501                                 size, sizeof(struct kinfo_proc));
502                         return (0);
503                 }
504                 nprocs = size / sizeof(struct kinfo_proc);
505         } else {
506                 struct nlist nl[4], *p;
507                 u_long procglob;
508
509                 nl[0].n_name = "_nprocs";
510                 nl[1].n_name = "_procglob";
511                 nl[2].n_name = "_allproc_hsize";
512                 nl[3].n_name = 0;
513
514                 if (kvm_nlist(kd, nl) != 0) {
515                         for (p = nl; p->n_type != 0; ++p)
516                                 ;
517                         _kvm_err(kd, kd->program,
518                                  "%s: no such symbol", p->n_name);
519                         return (0);
520                 }
521                 if (KREAD(kd, nl[0].n_value, &nprocs)) {
522                         _kvm_err(kd, kd->program, "can't read nprocs");
523                         return (0);
524                 }
525                 if (KREAD(kd, nl[2].n_value, &allproc_hsize)) {
526                         _kvm_err(kd, kd->program, "can't read allproc_hsize");
527                         return (0);
528                 }
529                 procglob = nl[1].n_value;
530                 nprocs = kvm_deadprocs(kd, op, arg, allproc_hsize, procglob);
531 #ifdef notdef
532                 size = nprocs * sizeof(struct kinfo_proc);
533                 (void)realloc(kd->procbase, size);
534 #endif
535         }
536         *cnt = nprocs;
537         return (kd->procbase);
538 }
539
540 void
541 _kvm_freeprocs(kvm_t *kd)
542 {
543         if (kd->procbase) {
544                 free(kd->procbase);
545                 kd->procbase = 0;
546         }
547 }
548
549 void *
550 _kvm_realloc(kvm_t *kd, void *p, size_t n)
551 {
552         void *np = (void *)realloc(p, n);
553
554         if (np == NULL) {
555                 free(p);
556                 _kvm_err(kd, kd->program, "out of memory");
557         }
558         return (np);
559 }
560
561 #ifndef MAX
562 #define MAX(a, b) ((a) > (b) ? (a) : (b))
563 #endif
564
565 /*
566  * Read in an argument vector from the user address space of process pid.
567  * addr if the user-space base address of narg null-terminated contiguous
568  * strings.  This is used to read in both the command arguments and
569  * environment strings.  Read at most maxcnt characters of strings.
570  */
571 static char **
572 kvm_argv(kvm_t *kd, pid_t pid, u_long addr, int narg, int maxcnt)
573 {
574         char *np, *cp, *ep, *ap;
575         u_long oaddr = -1;
576         u_long addr_min = VM_MIN_USER_ADDRESS;
577         u_long addr_max = VM_MAX_USER_ADDRESS;
578         int len, cc;
579         char **argv;
580
581         /*
582          * Check that there aren't an unreasonable number of agruments,
583          * and that the address is in user space.
584          */
585         if (narg > 512 || addr < addr_min || addr >= addr_max)
586                 return (0);
587
588         /*
589          * kd->argv : work space for fetching the strings from the target
590          *            process's space, and is converted for returning to caller
591          */
592         if (kd->argv == 0) {
593                 /*
594                  * Try to avoid reallocs.
595                  */
596                 kd->argc = MAX(narg + 1, 32);
597                 kd->argv = (char **)_kvm_malloc(kd, kd->argc *
598                                                 sizeof(*kd->argv));
599                 if (kd->argv == 0)
600                         return (0);
601         } else if (narg + 1 > kd->argc) {
602                 kd->argc = MAX(2 * kd->argc, narg + 1);
603                 kd->argv = (char **)_kvm_realloc(kd, kd->argv, kd->argc *
604                                                 sizeof(*kd->argv));
605                 if (kd->argv == 0)
606                         return (0);
607         }
608         /*
609          * kd->argspc : returned to user, this is where the kd->argv
610          *              arrays are left pointing to the collected strings.
611          */
612         if (kd->argspc == 0) {
613                 kd->argspc = (char *)_kvm_malloc(kd, PAGE_SIZE);
614                 if (kd->argspc == 0)
615                         return (0);
616                 kd->arglen = PAGE_SIZE;
617         }
618         /*
619          * kd->argbuf : used to pull in pages from the target process.
620          *              the strings are copied out of here.
621          */
622         if (kd->argbuf == 0) {
623                 kd->argbuf = (char *)_kvm_malloc(kd, PAGE_SIZE);
624                 if (kd->argbuf == 0)
625                         return (0);
626         }
627
628         /* Pull in the target process'es argv vector */
629         cc = sizeof(char *) * narg;
630         if (kvm_uread(kd, pid, addr, (char *)kd->argv, cc) != cc)
631                 return (0);
632         /*
633          * ap : saved start address of string we're working on in kd->argspc
634          * np : pointer to next place to write in kd->argspc
635          * len: length of data in kd->argspc
636          * argv: pointer to the argv vector that we are hunting around the
637          *       target process space for, and converting to addresses in
638          *       our address space (kd->argspc).
639          */
640         ap = np = kd->argspc;
641         argv = kd->argv;
642         len = 0;
643         /*
644          * Loop over pages, filling in the argument vector.
645          * Note that the argv strings could be pointing *anywhere* in
646          * the user address space and are no longer contiguous.
647          * Note that *argv is modified when we are going to fetch a string
648          * that crosses a page boundary.  We copy the next part of the string
649          * into to "np" and eventually convert the pointer.
650          */
651         while (argv < kd->argv + narg && *argv != NULL) {
652
653                 /* get the address that the current argv string is on */
654                 addr = rounddown2((u_long)*argv, PAGE_SIZE);
655
656                 /* is it the same page as the last one? */
657                 if (addr != oaddr) {
658                         if (kvm_uread(kd, pid, addr, kd->argbuf, PAGE_SIZE) !=
659                             PAGE_SIZE)
660                                 return (0);
661                         oaddr = addr;
662                 }
663
664                 /* offset within the page... kd->argbuf */
665                 addr = (u_long)*argv & (PAGE_SIZE - 1);
666
667                 /* cp = start of string, cc = count of chars in this chunk */
668                 cp = kd->argbuf + addr;
669                 cc = PAGE_SIZE - addr;
670
671                 /* dont get more than asked for by user process */
672                 if (maxcnt > 0 && cc > maxcnt - len)
673                         cc = maxcnt - len;
674
675                 /* pointer to end of string if we found it in this page */
676                 ep = memchr(cp, '\0', cc);
677                 if (ep != NULL)
678                         cc = ep - cp + 1;
679                 /*
680                  * at this point, cc is the count of the chars that we are
681                  * going to retrieve this time. we may or may not have found
682                  * the end of it.  (ep points to the null if the end is known)
683                  */
684
685                 /* will we exceed the malloc/realloced buffer? */
686                 if (len + cc > kd->arglen) {
687                         size_t off;
688                         char **pp;
689                         char *op = kd->argspc;
690
691                         kd->arglen *= 2;
692                         kd->argspc = (char *)_kvm_realloc(kd, kd->argspc,
693                                                           kd->arglen);
694                         if (kd->argspc == 0)
695                                 return (0);
696                         /*
697                          * Adjust argv pointers in case realloc moved
698                          * the string space.
699                          */
700                         off = kd->argspc - op;
701                         for (pp = kd->argv; pp < argv; pp++)
702                                 *pp += off;
703                         ap += off;
704                         np += off;
705                 }
706                 /* np = where to put the next part of the string in kd->argspc*/
707                 /* np is kinda redundant.. could use "kd->argspc + len" */
708                 memcpy(np, cp, cc);
709                 np += cc;       /* inc counters */
710                 len += cc;
711
712                 /*
713                  * if end of string found, set the *argv pointer to the
714                  * saved beginning of string, and advance. argv points to
715                  * somewhere in kd->argv..  This is initially relative
716                  * to the target process, but when we close it off, we set
717                  * it to point in our address space.
718                  */
719                 if (ep != NULL) {
720                         *argv++ = ap;
721                         ap = np;
722                 } else {
723                         /* update the address relative to the target process */
724                         *argv += cc;
725                 }
726
727                 if (maxcnt > 0 && len >= maxcnt) {
728                         /*
729                          * We're stopping prematurely.  Terminate the
730                          * current string.
731                          */
732                         if (ep == NULL) {
733                                 *np = '\0';
734                                 *argv++ = ap;
735                         }
736                         break;
737                 }
738         }
739         /* Make sure argv is terminated. */
740         *argv = NULL;
741         return (kd->argv);
742 }
743
744 static void
745 ps_str_a(struct ps_strings *p, u_long *addr, int *n)
746 {
747         *addr = (u_long)p->ps_argvstr;
748         *n = p->ps_nargvstr;
749 }
750
751 static void
752 ps_str_e(struct ps_strings *p, u_long *addr, int *n)
753 {
754         *addr = (u_long)p->ps_envstr;
755         *n = p->ps_nenvstr;
756 }
757
758 /*
759  * Determine if the proc indicated by p is still active.
760  * This test is not 100% foolproof in theory, but chances of
761  * being wrong are very low.
762  */
763 static int
764 proc_verify(const struct kinfo_proc *p)
765 {
766         struct kinfo_proc kp;
767         int mib[4];
768         size_t len;
769         int error;
770
771         mib[0] = CTL_KERN;
772         mib[1] = KERN_PROC;
773         mib[2] = KERN_PROC_PID;
774         mib[3] = p->kp_pid;
775
776         len = sizeof(kp);
777         error = sysctl(mib, 4, &kp, &len, NULL, 0);
778         if (error)
779                 return (0);
780
781         error = (p->kp_pid == kp.kp_pid &&
782             (kp.kp_stat != SZOMB || p->kp_stat == SZOMB));
783         return (error);
784 }
785
786 static char **
787 kvm_doargv(kvm_t *kd, const struct kinfo_proc *kp, int nchr,
788            void (*info)(struct ps_strings *, u_long *, int *))
789 {
790         char **ap;
791         u_long addr;
792         int cnt;
793         static struct ps_strings arginfo;
794         static u_long ps_strings;
795         size_t len;
796
797         if (ps_strings == 0) {
798                 len = sizeof(ps_strings);
799                 if (sysctlbyname("kern.ps_strings", &ps_strings, &len, NULL,
800                     0) == -1)
801                         ps_strings = PS_STRINGS;
802         }
803
804         /*
805          * Pointers are stored at the top of the user stack.
806          */
807         if (kp->kp_stat == SZOMB ||
808             kvm_uread(kd, kp->kp_pid, ps_strings, (char *)&arginfo,
809                       sizeof(arginfo)) != sizeof(arginfo))
810                 return (0);
811
812         (*info)(&arginfo, &addr, &cnt);
813         if (cnt == 0)
814                 return (0);
815         ap = kvm_argv(kd, kp->kp_pid, addr, cnt, nchr);
816         /*
817          * For live kernels, make sure this process didn't go away.
818          */
819         if (ap != NULL && (kvm_ishost(kd) || kvm_isvkernel(kd)) &&
820             !proc_verify(kp))
821                 ap = NULL;
822         return (ap);
823 }
824
825 /*
826  * Get the command args.  This code is now machine independent.
827  */
828 char **
829 kvm_getargv(kvm_t *kd, const struct kinfo_proc *kp, int nchr)
830 {
831         int oid[8];
832         int i;
833         size_t bufsz;
834         static unsigned long buflen;
835         static char *buf, *p;
836         static char **bufp;
837         static int argc;
838
839         if (!kvm_ishost(kd)) { /* XXX: vkernels */
840                 _kvm_err(kd, kd->program,
841                     "cannot read user space from dead kernel");
842                 return (0);
843         }
844
845         if (!buflen) {
846                 bufsz = sizeof(buflen);
847                 i = sysctlbyname("kern.ps_arg_cache_limit",
848                                  &buflen, &bufsz, NULL, 0);
849                 if (i == -1) {
850                         buflen = 0;
851                 } else {
852                         buf = malloc(buflen);
853                         if (buf == NULL)
854                                 buflen = 0;
855                         argc = 32;
856                         bufp = malloc(sizeof(char *) * argc);
857                 }
858         }
859         if (buf != NULL) {
860                 oid[0] = CTL_KERN;
861                 oid[1] = KERN_PROC;
862                 oid[2] = KERN_PROC_ARGS;
863                 oid[3] = kp->kp_pid;
864                 oid[4] = kp->kp_lwp.kl_tid;
865
866                 /*
867                  * sysctl can take a pid in 5.7 or earlier.  In late
868                  * 5.7 the sysctl can take a pid (4 args) or pid + tid
869                  * (5 args).
870                  */
871                 i = -1;
872                 if (kp->kp_lwp.kl_tid > 0) {
873                         bufsz = buflen;
874                         i = sysctl(oid, 5, buf, &bufsz, 0, 0);
875                 }
876                 if (i < 0) {
877                         bufsz = buflen;
878                         i = sysctl(oid, 4, buf, &bufsz, 0, 0);
879                 }
880
881                 if (i == 0 && bufsz > 0) {
882                         i = 0;
883                         p = buf;
884                         do {
885                                 bufp[i++] = p;
886                                 p += strlen(p) + 1;
887                                 if (i >= argc) {
888                                         argc += argc;
889                                         bufp = realloc(bufp,
890                                             sizeof(char *) * argc);
891                                 }
892                         } while (p < buf + bufsz);
893                         bufp[i++] = NULL;
894                         return (bufp);
895                 }
896         }
897         if (kp->kp_flags & P_SYSTEM)
898                 return (NULL);
899         return (kvm_doargv(kd, kp, nchr, ps_str_a));
900 }
901
902 char **
903 kvm_getenvv(kvm_t *kd, const struct kinfo_proc *kp, int nchr)
904 {
905         return (kvm_doargv(kd, kp, nchr, ps_str_e));
906 }
907
908 /*
909  * Read from user space.  The user context is given by pid.
910  */
911 ssize_t
912 kvm_uread(kvm_t *kd, pid_t pid, u_long uva, char *buf, size_t len)
913 {
914         char *cp;
915         char procfile[MAXPATHLEN];
916         ssize_t amount;
917         int fd;
918
919         if (!kvm_ishost(kd)) { /* XXX: vkernels */
920                 _kvm_err(kd, kd->program,
921                     "cannot read user space from dead kernel");
922                 return (0);
923         }
924
925         sprintf(procfile, "/proc/%d/mem", pid);
926         fd = open(procfile, O_RDONLY, 0);
927         if (fd < 0) {
928                 _kvm_err(kd, kd->program, "cannot open %s", procfile);
929                 close(fd);
930                 return (0);
931         }
932
933         cp = buf;
934         while (len > 0) {
935                 errno = 0;
936                 if (lseek(fd, (off_t)uva, 0) == -1 && errno != 0) {
937                         _kvm_err(kd, kd->program, "invalid address (%lx) in %s",
938                             uva, procfile);
939                         break;
940                 }
941                 amount = read(fd, cp, len);
942                 if (amount < 0) {
943                         _kvm_syserr(kd, kd->program, "error reading %s",
944                             procfile);
945                         break;
946                 }
947                 if (amount == 0) {
948                         _kvm_err(kd, kd->program, "EOF reading %s", procfile);
949                         break;
950                 }
951                 cp += amount;
952                 uva += amount;
953                 len -= amount;
954         }
955
956         close(fd);
957         return ((ssize_t)(cp - buf));
958 }