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