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