]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libkvm/kvm_proc.c
This commit was generated by cvs2svn to compensate for changes in r90067,
[FreeBSD/FreeBSD.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$
38  */
39
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
42
43 #if defined(LIBC_SCCS) && !defined(lint)
44 static char sccsid[] = "@(#)kvm_proc.c  8.3 (Berkeley) 9/23/93";
45 #endif /* LIBC_SCCS and not lint */
46
47 /*
48  * Proc traversal interface for kvm.  ps and w are (probably) the exclusive
49  * users of this code, so we've factored it out into a separate module.
50  * Thus, we keep this grunge out of the other kvm applications (i.e.,
51  * most other applications are interested only in open/close/read/nlist).
52  */
53
54 #include <sys/param.h>
55 #include <sys/user.h>
56 #include <sys/proc.h>
57 #include <sys/exec.h>
58 #include <sys/stat.h>
59 #include <sys/ioctl.h>
60 #include <sys/tty.h>
61 #include <sys/file.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <unistd.h>
65 #include <nlist.h>
66 #include <kvm.h>
67
68 #include <vm/vm.h>
69 #include <vm/vm_param.h>
70 #include <vm/swap_pager.h>
71
72 #include <sys/sysctl.h>
73
74 #include <limits.h>
75 #include <memory.h>
76 #include <paths.h>
77
78 #include "kvm_private.h"
79
80 #if used
81 static char *
82 kvm_readswap(kd, p, va, cnt)
83         kvm_t *kd;
84         const struct proc *p;
85         u_long va;
86         u_long *cnt;
87 {
88 #ifdef __FreeBSD__
89         /* XXX Stubbed out, our vm system is differnet */
90         _kvm_err(kd, kd->program, "kvm_readswap not implemented");
91         return(0);
92 #endif  /* __FreeBSD__ */
93 }
94 #endif
95
96 #define KREAD(kd, addr, obj) \
97         (kvm_read(kd, addr, (char *)(obj), sizeof(*obj)) != sizeof(*obj))
98
99 /*
100  * Read proc's from memory file into buffer bp, which has space to hold
101  * at most maxcnt procs.
102  */
103 static int
104 kvm_proclist(kd, what, arg, p, bp, maxcnt)
105         kvm_t *kd;
106         int what, arg;
107         struct proc *p;
108         struct kinfo_proc *bp;
109         int maxcnt;
110 {
111         register int cnt = 0;
112         struct kinfo_proc kinfo_proc, *kp;
113         struct pgrp pgrp;
114         struct session sess;
115         struct tty tty;
116         struct vmspace vmspace;
117         struct procsig procsig;
118         struct pstats pstats;
119         struct ucred ucred;
120         struct proc proc;
121         struct proc pproc;
122
123         kp = &kinfo_proc;
124         kp->ki_structsize = sizeof(kinfo_proc);
125         for (; cnt < maxcnt && p != NULL; p = LIST_NEXT(&proc, p_list)) {
126                 memset(kp, 0, sizeof *kp);
127                 if (KREAD(kd, (u_long)p, &proc)) {
128                         _kvm_err(kd, kd->program, "can't read proc at %x", p);
129                         return (-1);
130                 }
131                 if (KREAD(kd, (u_long)proc.p_ucred, &ucred) == 0) {
132                         kp->ki_ruid = ucred.cr_ruid;
133                         kp->ki_svuid = ucred.cr_svuid;
134                         kp->ki_rgid = ucred.cr_rgid;
135                         kp->ki_svgid = ucred.cr_svgid;
136                         kp->ki_ngroups = ucred.cr_ngroups;
137                         bcopy(ucred.cr_groups, kp->ki_groups,
138                             NGROUPS * sizeof(gid_t));
139                         kp->ki_uid = ucred.cr_uid;
140                 }
141
142                 switch(what) {
143
144                 case KERN_PROC_PID:
145                         if (proc.p_pid != (pid_t)arg)
146                                 continue;
147                         break;
148
149                 case KERN_PROC_UID:
150                         if (kp->ki_uid != (uid_t)arg)
151                                 continue;
152                         break;
153
154                 case KERN_PROC_RUID:
155                         if (kp->ki_ruid != (uid_t)arg)
156                                 continue;
157                         break;
158                 }
159                 /*
160                  * We're going to add another proc to the set.  If this
161                  * will overflow the buffer, assume the reason is because
162                  * nprocs (or the proc list) is corrupt and declare an error.
163                  */
164                 if (cnt >= maxcnt) {
165                         _kvm_err(kd, kd->program, "nprocs corrupt");
166                         return (-1);
167                 }
168                 /*
169                  * gather kinfo_proc
170                  */
171                 kp->ki_paddr = p;
172                 kp->ki_addr = proc.p_uarea;
173                 /* kp->ki_kstack = proc.p_thread.td_kstack; XXXKSE */
174                 kp->ki_args = proc.p_args;
175                 kp->ki_tracep = proc.p_tracep;
176                 kp->ki_textvp = proc.p_textvp;
177                 kp->ki_fd = proc.p_fd;
178                 kp->ki_vmspace = proc.p_vmspace;
179                 if (proc.p_procsig != NULL) {
180                         if (KREAD(kd, (u_long)proc.p_procsig, &procsig)) {
181                                 _kvm_err(kd, kd->program,
182                                     "can't read procsig at %x", proc.p_procsig);
183                                 return (-1);
184                         }
185                         kp->ki_sigignore = procsig.ps_sigignore;
186                         kp->ki_sigcatch = procsig.ps_sigcatch;
187                 }
188                 if ((proc.p_sflag & PS_INMEM) && proc.p_stats != NULL) {
189                         if (KREAD(kd, (u_long)proc.p_stats, &pstats)) {
190                                 _kvm_err(kd, kd->program,
191                                     "can't read stats at %x", proc.p_stats);
192                                 return (-1);
193                         }
194                         kp->ki_start = pstats.p_start;
195                         kp->ki_rusage = pstats.p_ru;
196                         kp->ki_childtime.tv_sec = pstats.p_cru.ru_utime.tv_sec +
197                             pstats.p_cru.ru_stime.tv_sec;
198                         kp->ki_childtime.tv_usec =
199                             pstats.p_cru.ru_utime.tv_usec +
200                             pstats.p_cru.ru_stime.tv_usec;
201                 }
202                 if (proc.p_oppid)
203                         kp->ki_ppid = proc.p_oppid;
204                 else if (proc.p_pptr) {
205                         if (KREAD(kd, (u_long)proc.p_pptr, &pproc)) {
206                                 _kvm_err(kd, kd->program,
207                                     "can't read pproc at %x", proc.p_pptr);
208                                 return (-1);
209                         }
210                         kp->ki_ppid = pproc.p_pid;
211                 } else 
212                         kp->ki_ppid = 0;
213                 if (proc.p_pgrp == NULL)
214                         goto nopgrp;
215                 if (KREAD(kd, (u_long)proc.p_pgrp, &pgrp)) {
216                         _kvm_err(kd, kd->program, "can't read pgrp at %x",
217                                  proc.p_pgrp);
218                         return (-1);
219                 }
220                 kp->ki_pgid = pgrp.pg_id;
221                 kp->ki_jobc = pgrp.pg_jobc;
222                 if (KREAD(kd, (u_long)pgrp.pg_session, &sess)) {
223                         _kvm_err(kd, kd->program, "can't read session at %x",
224                                 pgrp.pg_session);
225                         return (-1);
226                 }
227                 kp->ki_sid = sess.s_sid;
228                 (void)memcpy(kp->ki_login, sess.s_login,
229                                                 sizeof(kp->ki_login));
230                 kp->ki_kiflag = sess.s_ttyvp ? KI_CTTY : 0;
231                 if (sess.s_leader == p)
232                         kp->ki_kiflag |= KI_SLEADER;
233                 if ((proc.p_flag & P_CONTROLT) && sess.s_ttyp != NULL) {
234                         if (KREAD(kd, (u_long)sess.s_ttyp, &tty)) {
235                                 _kvm_err(kd, kd->program,
236                                          "can't read tty at %x", sess.s_ttyp);
237                                 return (-1);
238                         }
239                         kp->ki_tdev = tty.t_dev;
240                         if (tty.t_pgrp != NULL) {
241                                 if (KREAD(kd, (u_long)tty.t_pgrp, &pgrp)) {
242                                         _kvm_err(kd, kd->program,
243                                                  "can't read tpgrp at &x",
244                                                 tty.t_pgrp);
245                                         return (-1);
246                                 }
247                                 kp->ki_tpgid = pgrp.pg_id;
248                         } else
249                                 kp->ki_tpgid = -1;
250                         if (tty.t_session != NULL) {
251                                 if (KREAD(kd, (u_long)tty.t_session, &sess)) {
252                                         _kvm_err(kd, kd->program,
253                                             "can't read session at %x",
254                                             tty.t_session);
255                                         return (-1);
256                                 }
257                                 kp->ki_tsid = sess.s_sid;
258                         }
259                 } else {
260 nopgrp:
261                         kp->ki_tdev = NODEV;
262                 }
263                 if (proc.p_thread.td_wmesg)     /* XXXKSE */
264                         (void)kvm_read(kd, (u_long)proc.p_thread.td_wmesg,
265                             kp->ki_wmesg, WMESGLEN);
266
267 #ifdef sparc
268                 (void)kvm_read(kd, (u_long)&proc.p_vmspace->vm_rssize,
269                     (char *)&kp->ki_rssize,
270                     sizeof(kp->ki_rssize));
271                 (void)kvm_read(kd, (u_long)&proc.p_vmspace->vm_tsize,
272                     (char *)&kp->ki_tsize,
273                     3 * sizeof(kp->ki_rssize)); /* XXX */
274 #else
275                 (void)kvm_read(kd, (u_long)proc.p_vmspace,
276                     (char *)&vmspace, sizeof(vmspace));
277                 kp->ki_size = vmspace.vm_map.size;
278                 kp->ki_rssize = vmspace.vm_swrss; /* XXX */
279                 kp->ki_swrss = vmspace.vm_swrss;
280                 kp->ki_tsize = vmspace.vm_tsize;
281                 kp->ki_dsize = vmspace.vm_dsize;
282                 kp->ki_ssize = vmspace.vm_ssize;
283 #endif
284
285                 switch (what) {
286
287                 case KERN_PROC_PGRP:
288                         if (kp->ki_pgid != (pid_t)arg)
289                                 continue;
290                         break;
291
292                 case KERN_PROC_TTY:
293                         if ((proc.p_flag & P_CONTROLT) == 0 ||
294                              kp->ki_tdev != (dev_t)arg)
295                                 continue;
296                         break;
297                 }
298                 if (proc.p_comm[0] != 0) {
299                         strncpy(kp->ki_comm, proc.p_comm, MAXCOMLEN);
300                         kp->ki_comm[MAXCOMLEN] = 0;
301                 }
302                 if (proc.p_thread.td_blocked != 0) {    /* XXXKSE */
303                         kp->ki_kiflag |= KI_MTXBLOCK;
304                         if (proc.p_thread.td_mtxname)   /* XXXKSE */
305                                 (void)kvm_read(kd, (u_long)proc.p_thread.td_mtxname,
306                                     kp->ki_mtxname, MTXNAMELEN);
307                         kp->ki_mtxname[MTXNAMELEN] = 0;
308                 }
309                 kp->ki_runtime = proc.p_runtime;
310                 kp->ki_pid = proc.p_pid;
311                 kp->ki_siglist = proc.p_siglist;
312                 kp->ki_sigmask = proc.p_sigmask;
313                 kp->ki_xstat = proc.p_xstat;
314                 kp->ki_acflag = proc.p_acflag;
315                 kp->ki_pctcpu = proc.p_kse.ke_pctcpu;           /* XXXKSE */
316                 kp->ki_estcpu = proc.p_ksegrp.kg_estcpu;        /* XXXKSE */
317                 kp->ki_slptime = proc.p_kse.ke_slptime;         /* XXXKSE */
318                 kp->ki_swtime = proc.p_swtime;
319                 kp->ki_flag = proc.p_flag;
320                 kp->ki_sflag = proc.p_sflag;
321                 kp->ki_wchan = proc.p_thread.td_wchan;          /* XXXKSE */
322                 kp->ki_traceflag = proc.p_traceflag;
323                 kp->ki_stat = proc.p_stat;
324                 kp->ki_pri = proc.p_ksegrp.kg_pri;              /* XXXKSE */
325                 kp->ki_nice = proc.p_ksegrp.kg_nice;            /* XXXKSE */
326                 kp->ki_lock = proc.p_lock;
327                 kp->ki_rqindex = proc.p_kse.ke_rqindex;         /* XXXKSE */
328                 kp->ki_oncpu = proc.p_kse.ke_oncpu;             /* XXXKSE */
329                 kp->ki_lastcpu = proc.p_thread.td_lastcpu;      /* XXXKSE */
330                 bcopy(&kinfo_proc, bp, sizeof(kinfo_proc));
331                 ++bp;
332                 ++cnt;
333         }
334         return (cnt);
335 }
336
337 /*
338  * Build proc info array by reading in proc list from a crash dump.
339  * Return number of procs read.  maxcnt is the max we will read.
340  */
341 static int
342 kvm_deadprocs(kd, what, arg, a_allproc, a_zombproc, maxcnt)
343         kvm_t *kd;
344         int what, arg;
345         u_long a_allproc;
346         u_long a_zombproc;
347         int maxcnt;
348 {
349         register struct kinfo_proc *bp = kd->procbase;
350         register int acnt, zcnt;
351         struct proc *p;
352
353         if (KREAD(kd, a_allproc, &p)) {
354                 _kvm_err(kd, kd->program, "cannot read allproc");
355                 return (-1);
356         }
357         acnt = kvm_proclist(kd, what, arg, p, bp, maxcnt);
358         if (acnt < 0)
359                 return (acnt);
360
361         if (KREAD(kd, a_zombproc, &p)) {
362                 _kvm_err(kd, kd->program, "cannot read zombproc");
363                 return (-1);
364         }
365         zcnt = kvm_proclist(kd, what, arg, p, bp + acnt, maxcnt - acnt);
366         if (zcnt < 0)
367                 zcnt = 0;
368
369         return (acnt + zcnt);
370 }
371
372 struct kinfo_proc *
373 kvm_getprocs(kd, op, arg, cnt)
374         kvm_t *kd;
375         int op, arg;
376         int *cnt;
377 {
378         int mib[4], st, nprocs;
379         size_t size;
380
381         if (kd->procbase != 0) {
382                 free((void *)kd->procbase);
383                 /*
384                  * Clear this pointer in case this call fails.  Otherwise,
385                  * kvm_close() will free it again.
386                  */
387                 kd->procbase = 0;
388         }
389         if (ISALIVE(kd)) {
390                 size = 0;
391                 mib[0] = CTL_KERN;
392                 mib[1] = KERN_PROC;
393                 mib[2] = op;
394                 mib[3] = arg;
395                 st = sysctl(mib, op == KERN_PROC_ALL ? 3 : 4, NULL, &size, NULL, 0);
396                 if (st == -1) {
397                         _kvm_syserr(kd, kd->program, "kvm_getprocs");
398                         return (0);
399                 }
400                 do {
401                         size += size / 10;
402                         kd->procbase = (struct kinfo_proc *)
403                             _kvm_realloc(kd, kd->procbase, size);
404                         if (kd->procbase == 0)
405                                 return (0);
406                         st = sysctl(mib, op == KERN_PROC_ALL ? 3 : 4,
407                             kd->procbase, &size, NULL, 0);
408                 } while (st == -1 && errno == ENOMEM);
409                 if (st == -1) {
410                         _kvm_syserr(kd, kd->program, "kvm_getprocs");
411                         return (0);
412                 }
413                 if (size > 0 &&
414                     kd->procbase->ki_structsize != sizeof(struct kinfo_proc)) {
415                         _kvm_err(kd, kd->program,
416                             "kinfo_proc size mismatch (expected %d, got %d)",
417                             sizeof(struct kinfo_proc),
418                             kd->procbase->ki_structsize);
419                         return (0);
420                 }
421                 nprocs = size == 0 ? 0 : size / kd->procbase->ki_structsize;
422         } else {
423                 struct nlist nl[4], *p;
424
425                 nl[0].n_name = "_nprocs";
426                 nl[1].n_name = "_allproc";
427                 nl[2].n_name = "_zombproc";
428                 nl[3].n_name = 0;
429
430                 if (kvm_nlist(kd, nl) != 0) {
431                         for (p = nl; p->n_type != 0; ++p)
432                                 ;
433                         _kvm_err(kd, kd->program,
434                                  "%s: no such symbol", p->n_name);
435                         return (0);
436                 }
437                 if (KREAD(kd, nl[0].n_value, &nprocs)) {
438                         _kvm_err(kd, kd->program, "can't read nprocs");
439                         return (0);
440                 }
441                 size = nprocs * sizeof(struct kinfo_proc);
442                 kd->procbase = (struct kinfo_proc *)_kvm_malloc(kd, size);
443                 if (kd->procbase == 0)
444                         return (0);
445
446                 nprocs = kvm_deadprocs(kd, op, arg, nl[1].n_value,
447                                       nl[2].n_value, nprocs);
448 #ifdef notdef
449                 size = nprocs * sizeof(struct kinfo_proc);
450                 (void)realloc(kd->procbase, size);
451 #endif
452         }
453         *cnt = nprocs;
454         return (kd->procbase);
455 }
456
457 void
458 _kvm_freeprocs(kd)
459         kvm_t *kd;
460 {
461         if (kd->procbase) {
462                 free(kd->procbase);
463                 kd->procbase = 0;
464         }
465 }
466
467 void *
468 _kvm_realloc(kd, p, n)
469         kvm_t *kd;
470         void *p;
471         size_t n;
472 {
473         void *np = (void *)realloc(p, n);
474
475         if (np == 0) {
476                 free(p);
477                 _kvm_err(kd, kd->program, "out of memory");
478         }
479         return (np);
480 }
481
482 #ifndef MAX
483 #define MAX(a, b) ((a) > (b) ? (a) : (b))
484 #endif
485
486 /*
487  * Read in an argument vector from the user address space of process kp.
488  * addr if the user-space base address of narg null-terminated contiguous
489  * strings.  This is used to read in both the command arguments and
490  * environment strings.  Read at most maxcnt characters of strings.
491  */
492 static char **
493 kvm_argv(kd, kp, addr, narg, maxcnt)
494         kvm_t *kd;
495         struct kinfo_proc *kp;
496         register u_long addr;
497         register int narg;
498         register int maxcnt;
499 {
500         register char *np, *cp, *ep, *ap;
501         register u_long oaddr = -1;
502         register int len, cc;
503         register char **argv;
504
505         /*
506          * Check that there aren't an unreasonable number of agruments,
507          * and that the address is in user space.
508          */
509         if (narg > 512 || addr < VM_MIN_ADDRESS || addr >= VM_MAXUSER_ADDRESS)
510                 return (0);
511
512         /*
513          * kd->argv : work space for fetching the strings from the target 
514          *            process's space, and is converted for returning to caller
515          */
516         if (kd->argv == 0) {
517                 /*
518                  * Try to avoid reallocs.
519                  */
520                 kd->argc = MAX(narg + 1, 32);
521                 kd->argv = (char **)_kvm_malloc(kd, kd->argc *
522                                                 sizeof(*kd->argv));
523                 if (kd->argv == 0)
524                         return (0);
525         } else if (narg + 1 > kd->argc) {
526                 kd->argc = MAX(2 * kd->argc, narg + 1);
527                 kd->argv = (char **)_kvm_realloc(kd, kd->argv, kd->argc *
528                                                 sizeof(*kd->argv));
529                 if (kd->argv == 0)
530                         return (0);
531         }
532         /*
533          * kd->argspc : returned to user, this is where the kd->argv
534          *              arrays are left pointing to the collected strings.
535          */
536         if (kd->argspc == 0) {
537                 kd->argspc = (char *)_kvm_malloc(kd, PAGE_SIZE);
538                 if (kd->argspc == 0)
539                         return (0);
540                 kd->arglen = PAGE_SIZE;
541         }
542         /*
543          * kd->argbuf : used to pull in pages from the target process.
544          *              the strings are copied out of here.
545          */
546         if (kd->argbuf == 0) {
547                 kd->argbuf = (char *)_kvm_malloc(kd, PAGE_SIZE);
548                 if (kd->argbuf == 0)
549                         return (0);
550         }
551
552         /* Pull in the target process'es argv vector */
553         cc = sizeof(char *) * narg;
554         if (kvm_uread(kd, kp, addr, (char *)kd->argv, cc) != cc)
555                 return (0);
556         /*
557          * ap : saved start address of string we're working on in kd->argspc
558          * np : pointer to next place to write in kd->argspc
559          * len: length of data in kd->argspc
560          * argv: pointer to the argv vector that we are hunting around the
561          *       target process space for, and converting to addresses in
562          *       our address space (kd->argspc).
563          */
564         ap = np = kd->argspc;
565         argv = kd->argv;
566         len = 0;
567         /*
568          * Loop over pages, filling in the argument vector.
569          * Note that the argv strings could be pointing *anywhere* in
570          * the user address space and are no longer contiguous.
571          * Note that *argv is modified when we are going to fetch a string
572          * that crosses a page boundary.  We copy the next part of the string
573          * into to "np" and eventually convert the pointer.
574          */
575         while (argv < kd->argv + narg && *argv != 0) {
576
577                 /* get the address that the current argv string is on */
578                 addr = (u_long)*argv & ~(PAGE_SIZE - 1);
579
580                 /* is it the same page as the last one? */
581                 if (addr != oaddr) {
582                         if (kvm_uread(kd, kp, addr, kd->argbuf, PAGE_SIZE) !=
583                             PAGE_SIZE)
584                                 return (0);
585                         oaddr = addr;
586                 }
587
588                 /* offset within the page... kd->argbuf */
589                 addr = (u_long)*argv & (PAGE_SIZE - 1);
590
591                 /* cp = start of string, cc = count of chars in this chunk */
592                 cp = kd->argbuf + addr;
593                 cc = PAGE_SIZE - addr;
594
595                 /* dont get more than asked for by user process */
596                 if (maxcnt > 0 && cc > maxcnt - len)
597                         cc = maxcnt - len;
598
599                 /* pointer to end of string if we found it in this page */
600                 ep = memchr(cp, '\0', cc);
601                 if (ep != 0)
602                         cc = ep - cp + 1;
603                 /*
604                  * at this point, cc is the count of the chars that we are
605                  * going to retrieve this time. we may or may not have found
606                  * the end of it.  (ep points to the null if the end is known)
607                  */
608
609                 /* will we exceed the malloc/realloced buffer? */
610                 if (len + cc > kd->arglen) {
611                         register int off;
612                         register char **pp;
613                         register char *op = kd->argspc;
614
615                         kd->arglen *= 2;
616                         kd->argspc = (char *)_kvm_realloc(kd, kd->argspc,
617                                                           kd->arglen);
618                         if (kd->argspc == 0)
619                                 return (0);
620                         /*
621                          * Adjust argv pointers in case realloc moved
622                          * the string space.
623                          */
624                         off = kd->argspc - op;
625                         for (pp = kd->argv; pp < argv; pp++)
626                                 *pp += off;
627                         ap += off;
628                         np += off;
629                 }
630                 /* np = where to put the next part of the string in kd->argspc*/
631                 /* np is kinda redundant.. could use "kd->argspc + len" */
632                 memcpy(np, cp, cc);
633                 np += cc;       /* inc counters */
634                 len += cc;
635
636                 /*
637                  * if end of string found, set the *argv pointer to the
638                  * saved beginning of string, and advance. argv points to
639                  * somewhere in kd->argv..  This is initially relative
640                  * to the target process, but when we close it off, we set
641                  * it to point in our address space.
642                  */
643                 if (ep != 0) {
644                         *argv++ = ap;
645                         ap = np;
646                 } else {
647                         /* update the address relative to the target process */
648                         *argv += cc;
649                 }
650
651                 if (maxcnt > 0 && len >= maxcnt) {
652                         /*
653                          * We're stopping prematurely.  Terminate the
654                          * current string.
655                          */
656                         if (ep == 0) {
657                                 *np = '\0';
658                                 *argv++ = ap;
659                         }
660                         break;
661                 }
662         }
663         /* Make sure argv is terminated. */
664         *argv = 0;
665         return (kd->argv);
666 }
667
668 static void
669 ps_str_a(p, addr, n)
670         struct ps_strings *p;
671         u_long *addr;
672         int *n;
673 {
674         *addr = (u_long)p->ps_argvstr;
675         *n = p->ps_nargvstr;
676 }
677
678 static void
679 ps_str_e(p, addr, n)
680         struct ps_strings *p;
681         u_long *addr;
682         int *n;
683 {
684         *addr = (u_long)p->ps_envstr;
685         *n = p->ps_nenvstr;
686 }
687
688 /*
689  * Determine if the proc indicated by p is still active.
690  * This test is not 100% foolproof in theory, but chances of
691  * being wrong are very low.
692  */
693 static int
694 proc_verify(curkp)
695         struct kinfo_proc *curkp;
696 {
697         struct kinfo_proc newkp;
698         int mib[4];
699         size_t len;
700
701         mib[0] = CTL_KERN;
702         mib[1] = KERN_PROC;
703         mib[2] = KERN_PROC_PID;
704         mib[3] = curkp->ki_pid;
705         len = sizeof(newkp);
706         if (sysctl(mib, 4, &newkp, &len, NULL, 0) == -1)
707                 return (0);
708         return (curkp->ki_pid == newkp.ki_pid &&
709             (newkp.ki_stat != SZOMB || curkp->ki_stat == SZOMB));
710 }
711
712 static char **
713 kvm_doargv(kd, kp, nchr, info)
714         kvm_t *kd;
715         struct kinfo_proc *kp;
716         int nchr;
717         void (*info)(struct ps_strings *, u_long *, int *);
718 {
719         char **ap;
720         u_long addr;
721         int cnt;
722         static struct ps_strings arginfo;
723         static u_long ps_strings;
724         size_t len;
725
726         if (ps_strings == NULL) {
727                 len = sizeof(ps_strings);
728                 if (sysctlbyname("kern.ps_strings", &ps_strings, &len, NULL,
729                     0) == -1)
730                         ps_strings = PS_STRINGS;
731         }
732
733         /*
734          * Pointers are stored at the top of the user stack.
735          */
736         if (kp->ki_stat == SZOMB ||
737             kvm_uread(kd, kp, ps_strings, (char *)&arginfo,
738                       sizeof(arginfo)) != sizeof(arginfo))
739                 return (0);
740
741         (*info)(&arginfo, &addr, &cnt);
742         if (cnt == 0)
743                 return (0);
744         ap = kvm_argv(kd, kp, addr, cnt, nchr);
745         /*
746          * For live kernels, make sure this process didn't go away.
747          */
748         if (ap != 0 && ISALIVE(kd) && !proc_verify(kp))
749                 ap = 0;
750         return (ap);
751 }
752
753 /*
754  * Get the command args.  This code is now machine independent.
755  */
756 char **
757 kvm_getargv(kd, kp, nchr)
758         kvm_t *kd;
759         const struct kinfo_proc *kp;
760         int nchr;
761 {
762         int oid[4];
763         int i;
764         size_t bufsz;
765         static unsigned long buflen;
766         static char *buf, *p;
767         static char **bufp;
768         static int argc;
769
770         if (!ISALIVE(kd)) {
771                 _kvm_err(kd, kd->program,
772                     "cannot read user space from dead kernel");
773                 return (0);
774         }
775
776         if (!buflen) {
777                 bufsz = sizeof(buflen);
778                 i = sysctlbyname("kern.ps_arg_cache_limit", 
779                     &buflen, &bufsz, NULL, 0);
780                 if (i == -1) {
781                         buflen = 0;
782                 } else {
783                         buf = malloc(buflen);
784                         if (buf == NULL)
785                                 buflen = 0;
786                         argc = 32;
787                         bufp = malloc(sizeof(char *) * argc);
788                 }
789         }
790         if (buf != NULL) {
791                 oid[0] = CTL_KERN;
792                 oid[1] = KERN_PROC;
793                 oid[2] = KERN_PROC_ARGS;
794                 oid[3] = kp->ki_pid;
795                 bufsz = buflen;
796                 i = sysctl(oid, 4, buf, &bufsz, 0, 0);
797                 if (i == 0 && bufsz > 0) {
798                         i = 0;
799                         p = buf;
800                         do {
801                                 bufp[i++] = p;
802                                 p += strlen(p) + 1;
803                                 if (i >= argc) {
804                                         argc += argc;
805                                         bufp = realloc(bufp,
806                                             sizeof(char *) * argc);
807                                 }
808                         } while (p < buf + bufsz);
809                         bufp[i++] = 0;
810                         return (bufp);
811                 }
812         }
813         if (kp->ki_flag & P_SYSTEM)
814                 return (NULL);
815         return (kvm_doargv(kd, kp, nchr, ps_str_a));
816 }
817
818 char **
819 kvm_getenvv(kd, kp, nchr)
820         kvm_t *kd;
821         const struct kinfo_proc *kp;
822         int nchr;
823 {
824         return (kvm_doargv(kd, kp, nchr, ps_str_e));
825 }
826
827 /*
828  * Read from user space.  The user context is given by p.
829  */
830 ssize_t
831 kvm_uread(kd, kp, uva, buf, len)
832         kvm_t *kd;
833         struct kinfo_proc *kp;
834         register u_long uva;
835         register char *buf;
836         register size_t len;
837 {
838         register char *cp;
839         char procfile[MAXPATHLEN];
840         ssize_t amount;
841         int fd;
842
843         if (!ISALIVE(kd)) {
844                 _kvm_err(kd, kd->program,
845                     "cannot read user space from dead kernel");
846                 return (0);
847         }
848
849         sprintf(procfile, "/proc/%d/mem", kp->ki_pid);
850         fd = open(procfile, O_RDONLY, 0);
851         if (fd < 0) {
852                 _kvm_err(kd, kd->program, "cannot open %s", procfile);
853                 close(fd);
854                 return (0);
855         }
856
857         cp = buf;
858         while (len > 0) {
859                 errno = 0;
860                 if (lseek(fd, (off_t)uva, 0) == -1 && errno != 0) {
861                         _kvm_err(kd, kd->program, "invalid address (%x) in %s",
862                             uva, procfile);
863                         break;
864                 }
865                 amount = read(fd, cp, len);
866                 if (amount < 0) {
867                         _kvm_syserr(kd, kd->program, "error reading %s",
868                             procfile);
869                         break;
870                 }
871                 if (amount == 0) {
872                         _kvm_err(kd, kd->program, "EOF reading %s", procfile);
873                         break;
874                 }
875                 cp += amount;
876                 uva += amount;
877                 len -= amount;
878         }
879
880         close(fd);
881         return ((ssize_t)(cp - buf));
882 }