]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - lib/libkvm/kvm_proc.c
MFC r286886: Fixing typo as well as improving readability of a few comments.
[FreeBSD/stable/8.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  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 #if 0
35 #if defined(LIBC_SCCS) && !defined(lint)
36 static char sccsid[] = "@(#)kvm_proc.c  8.3 (Berkeley) 9/23/93";
37 #endif /* LIBC_SCCS and not lint */
38 #endif
39
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
42
43 /*
44  * Proc traversal interface for kvm.  ps and w are (probably) the exclusive
45  * users of this code, so we've factored it out into a separate module.
46  * Thus, we keep this grunge out of the other kvm applications (i.e.,
47  * most other applications are interested only in open/close/read/nlist).
48  */
49
50 #include <sys/param.h>
51 #define _WANT_UCRED     /* make ucred.h give us 'struct ucred' */
52 #include <sys/ucred.h>
53 #include <sys/queue.h>
54 #include <sys/_lock.h>
55 #include <sys/_mutex.h>
56 #include <sys/_task.h>
57 #include <sys/cpuset.h>
58 #include <sys/user.h>
59 #include <sys/proc.h>
60 #define _WANT_PRISON    /* make jail.h give us 'struct prison' */
61 #include <sys/jail.h>
62 #include <sys/exec.h>
63 #include <sys/stat.h>
64 #include <sys/sysent.h>
65 #include <sys/ioctl.h>
66 #include <sys/tty.h>
67 #include <sys/file.h>
68 #include <sys/conf.h>
69 #include <stdio.h>
70 #include <stdlib.h>
71 #include <unistd.h>
72 #include <nlist.h>
73 #include <kvm.h>
74
75 #include <vm/vm.h>
76 #include <vm/vm_param.h>
77
78 #include <sys/sysctl.h>
79
80 #include <limits.h>
81 #include <memory.h>
82 #include <paths.h>
83
84 #include "kvm_private.h"
85
86 #define KREAD(kd, addr, obj) \
87         (kvm_read(kd, addr, (char *)(obj), sizeof(*obj)) != sizeof(*obj))
88
89 static int ticks;
90 static int hz;
91
92 /*
93  * Read proc's from memory file into buffer bp, which has space to hold
94  * at most maxcnt procs.
95  */
96 static int
97 kvm_proclist(kd, what, arg, p, bp, maxcnt)
98         kvm_t *kd;
99         int what, arg;
100         struct proc *p;
101         struct kinfo_proc *bp;
102         int maxcnt;
103 {
104         int cnt = 0;
105         struct kinfo_proc kinfo_proc, *kp;
106         struct pgrp pgrp;
107         struct session sess;
108         struct cdev t_cdev;
109         struct tty tty;
110         struct vmspace vmspace;
111         struct sigacts sigacts;
112         struct pstats pstats;
113         struct ucred ucred;
114         struct prison pr;
115         struct thread mtd;
116         struct proc proc;
117         struct proc pproc;
118         struct timeval tv;
119         struct sysentvec sysent;
120         char svname[KI_EMULNAMELEN];
121
122         kp = &kinfo_proc;
123         kp->ki_structsize = sizeof(kinfo_proc);
124         /*
125          * Loop on the processes. this is completely broken because we need to be
126          * able to loop on the threads and merge the ones that are the same process some how.
127          */
128         for (; cnt < maxcnt && p != NULL; p = LIST_NEXT(&proc, p_list)) {
129                 memset(kp, 0, sizeof *kp);
130                 if (KREAD(kd, (u_long)p, &proc)) {
131                         _kvm_err(kd, kd->program, "can't read proc at %x", p);
132                         return (-1);
133                 }
134                 if (proc.p_state == PRS_NEW)
135                         continue;
136                 if (proc.p_state != PRS_ZOMBIE) {
137                         if (KREAD(kd, (u_long)TAILQ_FIRST(&proc.p_threads),
138                             &mtd)) {
139                                 _kvm_err(kd, kd->program,
140                                     "can't read thread at %x",
141                                     TAILQ_FIRST(&proc.p_threads));
142                                 return (-1);
143                         }
144                 }
145                 if (KREAD(kd, (u_long)proc.p_ucred, &ucred) == 0) {
146                         kp->ki_ruid = ucred.cr_ruid;
147                         kp->ki_svuid = ucred.cr_svuid;
148                         kp->ki_rgid = ucred.cr_rgid;
149                         kp->ki_svgid = ucred.cr_svgid;
150                         kp->ki_cr_flags = ucred.cr_flags;
151                         if (ucred.cr_ngroups > KI_NGROUPS) {
152                                 kp->ki_ngroups = KI_NGROUPS;
153                                 kp->ki_cr_flags |= KI_CRF_GRP_OVERFLOW;
154                         } else
155                                 kp->ki_ngroups = ucred.cr_ngroups;
156                         kvm_read(kd, (u_long)ucred.cr_groups, kp->ki_groups,
157                             kp->ki_ngroups * sizeof(gid_t));
158                         kp->ki_uid = ucred.cr_uid;
159                         if (ucred.cr_prison != NULL) {
160                                 if (KREAD(kd, (u_long)ucred.cr_prison, &pr)) {
161                                         _kvm_err(kd, kd->program,
162                                             "can't read prison at %x",
163                                             ucred.cr_prison);
164                                         return (-1);
165                                 }
166                                 kp->ki_jid = pr.pr_id;
167                         }
168                 }
169
170                 switch(what & ~KERN_PROC_INC_THREAD) {
171
172                 case KERN_PROC_GID:
173                         if (kp->ki_groups[0] != (gid_t)arg)
174                                 continue;
175                         break;
176
177                 case KERN_PROC_PID:
178                         if (proc.p_pid != (pid_t)arg)
179                                 continue;
180                         break;
181
182                 case KERN_PROC_RGID:
183                         if (kp->ki_rgid != (gid_t)arg)
184                                 continue;
185                         break;
186
187                 case KERN_PROC_UID:
188                         if (kp->ki_uid != (uid_t)arg)
189                                 continue;
190                         break;
191
192                 case KERN_PROC_RUID:
193                         if (kp->ki_ruid != (uid_t)arg)
194                                 continue;
195                         break;
196                 }
197                 /*
198                  * We're going to add another proc to the set.  If this
199                  * will overflow the buffer, assume the reason is because
200                  * nprocs (or the proc list) is corrupt and declare an error.
201                  */
202                 if (cnt >= maxcnt) {
203                         _kvm_err(kd, kd->program, "nprocs corrupt");
204                         return (-1);
205                 }
206                 /*
207                  * gather kinfo_proc
208                  */
209                 kp->ki_paddr = p;
210                 kp->ki_addr = 0;        /* XXX uarea */
211                 /* kp->ki_kstack = proc.p_thread.td_kstack; XXXKSE */
212                 kp->ki_args = proc.p_args;
213                 kp->ki_tracep = proc.p_tracevp;
214                 kp->ki_textvp = proc.p_textvp;
215                 kp->ki_fd = proc.p_fd;
216                 kp->ki_vmspace = proc.p_vmspace;
217                 if (proc.p_sigacts != NULL) {
218                         if (KREAD(kd, (u_long)proc.p_sigacts, &sigacts)) {
219                                 _kvm_err(kd, kd->program,
220                                     "can't read sigacts at %x", proc.p_sigacts);
221                                 return (-1);
222                         }
223                         kp->ki_sigignore = sigacts.ps_sigignore;
224                         kp->ki_sigcatch = sigacts.ps_sigcatch;
225                 }
226 #if 0
227                 if ((proc.p_flag & P_INMEM) && proc.p_stats != NULL) {
228                         if (KREAD(kd, (u_long)proc.p_stats, &pstats)) {
229                                 _kvm_err(kd, kd->program,
230                                     "can't read stats at %x", proc.p_stats);
231                                 return (-1);
232                         }
233                         kp->ki_start = pstats.p_start;
234
235                         /*
236                          * XXX: The times here are probably zero and need
237                          * to be calculated from the raw data in p_rux and
238                          * p_crux.
239                          */
240                         kp->ki_rusage = pstats.p_ru;
241                         kp->ki_childstime = pstats.p_cru.ru_stime;
242                         kp->ki_childutime = pstats.p_cru.ru_utime;
243                         /* Some callers want child-times in a single value */
244                         timeradd(&kp->ki_childstime, &kp->ki_childutime,
245                             &kp->ki_childtime);
246                 }
247 #endif
248                 if (proc.p_oppid)
249                         kp->ki_ppid = proc.p_oppid;
250                 else if (proc.p_pptr) {
251                         if (KREAD(kd, (u_long)proc.p_pptr, &pproc)) {
252                                 _kvm_err(kd, kd->program,
253                                     "can't read pproc at %x", proc.p_pptr);
254                                 return (-1);
255                         }
256                         kp->ki_ppid = pproc.p_pid;
257                 } else 
258                         kp->ki_ppid = 0;
259                 if (proc.p_pgrp == NULL)
260                         goto nopgrp;
261                 if (KREAD(kd, (u_long)proc.p_pgrp, &pgrp)) {
262                         _kvm_err(kd, kd->program, "can't read pgrp at %x",
263                                  proc.p_pgrp);
264                         return (-1);
265                 }
266                 kp->ki_pgid = pgrp.pg_id;
267                 kp->ki_jobc = pgrp.pg_jobc;
268                 if (KREAD(kd, (u_long)pgrp.pg_session, &sess)) {
269                         _kvm_err(kd, kd->program, "can't read session at %x",
270                                 pgrp.pg_session);
271                         return (-1);
272                 }
273                 kp->ki_sid = sess.s_sid;
274                 (void)memcpy(kp->ki_login, sess.s_login,
275                                                 sizeof(kp->ki_login));
276                 kp->ki_kiflag = sess.s_ttyvp ? KI_CTTY : 0;
277                 if (sess.s_leader == p)
278                         kp->ki_kiflag |= KI_SLEADER;
279                 if ((proc.p_flag & P_CONTROLT) && sess.s_ttyp != NULL) {
280                         if (KREAD(kd, (u_long)sess.s_ttyp, &tty)) {
281                                 _kvm_err(kd, kd->program,
282                                          "can't read tty at %x", sess.s_ttyp);
283                                 return (-1);
284                         }
285                         if (tty.t_dev != NULL) {
286                                 if (KREAD(kd, (u_long)tty.t_dev, &t_cdev)) {
287                                         _kvm_err(kd, kd->program,
288                                                  "can't read cdev at %x",
289                                                 tty.t_dev);
290                                         return (-1);
291                                 }
292 #if 0
293                                 kp->ki_tdev = t_cdev.si_udev;
294 #else
295                                 kp->ki_tdev = NODEV;
296 #endif
297                         }
298                         if (tty.t_pgrp != NULL) {
299                                 if (KREAD(kd, (u_long)tty.t_pgrp, &pgrp)) {
300                                         _kvm_err(kd, kd->program,
301                                                  "can't read tpgrp at %x",
302                                                 tty.t_pgrp);
303                                         return (-1);
304                                 }
305                                 kp->ki_tpgid = pgrp.pg_id;
306                         } else
307                                 kp->ki_tpgid = -1;
308                         if (tty.t_session != NULL) {
309                                 if (KREAD(kd, (u_long)tty.t_session, &sess)) {
310                                         _kvm_err(kd, kd->program,
311                                             "can't read session at %x",
312                                             tty.t_session);
313                                         return (-1);
314                                 }
315                                 kp->ki_tsid = sess.s_sid;
316                         }
317                 } else {
318 nopgrp:
319                         kp->ki_tdev = NODEV;
320                 }
321                 if ((proc.p_state != PRS_ZOMBIE) && mtd.td_wmesg)
322                         (void)kvm_read(kd, (u_long)mtd.td_wmesg,
323                             kp->ki_wmesg, WMESGLEN);
324
325                 (void)kvm_read(kd, (u_long)proc.p_vmspace,
326                     (char *)&vmspace, sizeof(vmspace));
327                 kp->ki_size = vmspace.vm_map.size;
328                 kp->ki_rssize = vmspace.vm_swrss; /* XXX */
329                 kp->ki_swrss = vmspace.vm_swrss;
330                 kp->ki_tsize = vmspace.vm_tsize;
331                 kp->ki_dsize = vmspace.vm_dsize;
332                 kp->ki_ssize = vmspace.vm_ssize;
333
334                 switch (what & ~KERN_PROC_INC_THREAD) {
335
336                 case KERN_PROC_PGRP:
337                         if (kp->ki_pgid != (pid_t)arg)
338                                 continue;
339                         break;
340
341                 case KERN_PROC_SESSION:
342                         if (kp->ki_sid != (pid_t)arg)
343                                 continue;
344                         break;
345
346                 case KERN_PROC_TTY:
347                         if ((proc.p_flag & P_CONTROLT) == 0 ||
348                              kp->ki_tdev != (dev_t)arg)
349                                 continue;
350                         break;
351                 }
352                 if (proc.p_comm[0] != 0)
353                         strlcpy(kp->ki_comm, proc.p_comm, MAXCOMLEN);
354                 (void)kvm_read(kd, (u_long)proc.p_sysent, (char *)&sysent,
355                     sizeof(sysent));
356                 (void)kvm_read(kd, (u_long)sysent.sv_name, (char *)&svname,
357                     sizeof(svname));
358                 if (svname[0] != 0)
359                         strlcpy(kp->ki_emul, svname, KI_EMULNAMELEN);
360                 if ((proc.p_state != PRS_ZOMBIE) &&
361                     (mtd.td_blocked != 0)) {
362                         kp->ki_kiflag |= KI_LOCKBLOCK;
363                         if (mtd.td_lockname)
364                                 (void)kvm_read(kd,
365                                     (u_long)mtd.td_lockname,
366                                     kp->ki_lockname, LOCKNAMELEN);
367                         kp->ki_lockname[LOCKNAMELEN] = 0;
368                 }
369                 /*
370                  * XXX: This is plain wrong, rux_runtime has nothing
371                  * to do with struct bintime, rux_runtime is just a 64-bit
372                  * integer counter of cputicks.  What we need here is a way
373                  * to convert cputicks to usecs.  The kernel does it in
374                  * kern/kern_tc.c, but the function can't be just copied.
375                  */
376                 bintime2timeval(&proc.p_rux.rux_runtime, &tv);
377                 kp->ki_runtime = (u_int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
378                 kp->ki_pid = proc.p_pid;
379                 kp->ki_siglist = proc.p_siglist;
380                 SIGSETOR(kp->ki_siglist, mtd.td_siglist);
381                 kp->ki_sigmask = mtd.td_sigmask;
382                 kp->ki_xstat = proc.p_xstat;
383                 kp->ki_acflag = proc.p_acflag;
384                 kp->ki_lock = proc.p_lock;
385                 if (proc.p_state != PRS_ZOMBIE) {
386                         kp->ki_swtime = (ticks - proc.p_swtick) / hz;
387                         kp->ki_flag = proc.p_flag;
388                         kp->ki_sflag = 0;
389                         kp->ki_nice = proc.p_nice;
390                         kp->ki_traceflag = proc.p_traceflag;
391                         if (proc.p_state == PRS_NORMAL) { 
392                                 if (TD_ON_RUNQ(&mtd) ||
393                                     TD_CAN_RUN(&mtd) ||
394                                     TD_IS_RUNNING(&mtd)) {
395                                         kp->ki_stat = SRUN;
396                                 } else if (mtd.td_state == 
397                                     TDS_INHIBITED) {
398                                         if (P_SHOULDSTOP(&proc)) {
399                                                 kp->ki_stat = SSTOP;
400                                         } else if (
401                                             TD_IS_SLEEPING(&mtd)) {
402                                                 kp->ki_stat = SSLEEP;
403                                         } else if (TD_ON_LOCK(&mtd)) {
404                                                 kp->ki_stat = SLOCK;
405                                         } else {
406                                                 kp->ki_stat = SWAIT;
407                                         }
408                                 }
409                         } else {
410                                 kp->ki_stat = SIDL;
411                         }
412                         /* Stuff from the thread */
413                         kp->ki_pri.pri_level = mtd.td_priority;
414                         kp->ki_pri.pri_native = mtd.td_base_pri;
415                         kp->ki_lastcpu = mtd.td_lastcpu;
416                         kp->ki_wchan = mtd.td_wchan;
417                         if (mtd.td_name[0] != 0)
418                                 strlcpy(kp->ki_ocomm, mtd.td_name, MAXCOMLEN);
419                         kp->ki_oncpu = mtd.td_oncpu;
420                         if (mtd.td_name[0] != '\0')
421                                 strlcpy(kp->ki_ocomm, mtd.td_name, sizeof(kp->ki_ocomm));
422                         kp->ki_pctcpu = 0;
423                         kp->ki_rqindex = 0;
424                 } else {
425                         kp->ki_stat = SZOMB;
426                 }
427                 bcopy(&kinfo_proc, bp, sizeof(kinfo_proc));
428                 ++bp;
429                 ++cnt;
430         }
431         return (cnt);
432 }
433
434 /*
435  * Build proc info array by reading in proc list from a crash dump.
436  * Return number of procs read.  maxcnt is the max we will read.
437  */
438 static int
439 kvm_deadprocs(kd, what, arg, a_allproc, a_zombproc, maxcnt)
440         kvm_t *kd;
441         int what, arg;
442         u_long a_allproc;
443         u_long a_zombproc;
444         int maxcnt;
445 {
446         struct kinfo_proc *bp = kd->procbase;
447         int acnt, zcnt;
448         struct proc *p;
449
450         if (KREAD(kd, a_allproc, &p)) {
451                 _kvm_err(kd, kd->program, "cannot read allproc");
452                 return (-1);
453         }
454         acnt = kvm_proclist(kd, what, arg, p, bp, maxcnt);
455         if (acnt < 0)
456                 return (acnt);
457
458         if (KREAD(kd, a_zombproc, &p)) {
459                 _kvm_err(kd, kd->program, "cannot read zombproc");
460                 return (-1);
461         }
462         zcnt = kvm_proclist(kd, what, arg, p, bp + acnt, maxcnt - acnt);
463         if (zcnt < 0)
464                 zcnt = 0;
465
466         return (acnt + zcnt);
467 }
468
469 struct kinfo_proc *
470 kvm_getprocs(kd, op, arg, cnt)
471         kvm_t *kd;
472         int op, arg;
473         int *cnt;
474 {
475         int mib[4], st, nprocs;
476         size_t size, osize;
477         int temp_op;
478
479         if (kd->procbase != 0) {
480                 free((void *)kd->procbase);
481                 /*
482                  * Clear this pointer in case this call fails.  Otherwise,
483                  * kvm_close() will free it again.
484                  */
485                 kd->procbase = 0;
486         }
487         if (ISALIVE(kd)) {
488                 size = 0;
489                 mib[0] = CTL_KERN;
490                 mib[1] = KERN_PROC;
491                 mib[2] = op;
492                 mib[3] = arg;
493                 temp_op = op & ~KERN_PROC_INC_THREAD;
494                 st = sysctl(mib,
495                     temp_op == KERN_PROC_ALL || temp_op == KERN_PROC_PROC ?
496                     3 : 4, NULL, &size, NULL, 0);
497                 if (st == -1) {
498                         _kvm_syserr(kd, kd->program, "kvm_getprocs");
499                         return (0);
500                 }
501                 /*
502                  * We can't continue with a size of 0 because we pass
503                  * it to realloc() (via _kvm_realloc()), and passing 0
504                  * to realloc() results in undefined behavior.
505                  */
506                 if (size == 0) {
507                         /*
508                          * XXX: We should probably return an invalid,
509                          * but non-NULL, pointer here so any client
510                          * program trying to dereference it will
511                          * crash.  However, _kvm_freeprocs() calls
512                          * free() on kd->procbase if it isn't NULL,
513                          * and free()'ing a junk pointer isn't good.
514                          * Then again, _kvm_freeprocs() isn't used
515                          * anywhere . . .
516                          */
517                         kd->procbase = _kvm_malloc(kd, 1);
518                         goto liveout;
519                 }
520                 do {
521                         size += size / 10;
522                         kd->procbase = (struct kinfo_proc *)
523                             _kvm_realloc(kd, kd->procbase, size);
524                         if (kd->procbase == 0)
525                                 return (0);
526                         osize = size;
527                         st = sysctl(mib, temp_op == KERN_PROC_ALL ||
528                             temp_op == KERN_PROC_PROC ? 3 : 4,
529                             kd->procbase, &size, NULL, 0);
530                 } while (st == -1 && errno == ENOMEM && size == osize);
531                 if (st == -1) {
532                         _kvm_syserr(kd, kd->program, "kvm_getprocs");
533                         return (0);
534                 }
535                 /*
536                  * We have to check the size again because sysctl()
537                  * may "round up" oldlenp if oldp is NULL; hence it
538                  * might've told us that there was data to get when
539                  * there really isn't any.
540                  */
541                 if (size > 0 &&
542                     kd->procbase->ki_structsize != sizeof(struct kinfo_proc)) {
543                         _kvm_err(kd, kd->program,
544                             "kinfo_proc size mismatch (expected %d, got %d)",
545                             sizeof(struct kinfo_proc),
546                             kd->procbase->ki_structsize);
547                         return (0);
548                 }
549 liveout:
550                 nprocs = size == 0 ? 0 : size / kd->procbase->ki_structsize;
551         } else {
552                 struct nlist nl[6], *p;
553
554                 nl[0].n_name = "_nprocs";
555                 nl[1].n_name = "_allproc";
556                 nl[2].n_name = "_zombproc";
557                 nl[3].n_name = "_ticks";
558                 nl[4].n_name = "_hz";
559                 nl[5].n_name = 0;
560
561                 if (kvm_nlist(kd, nl) != 0) {
562                         for (p = nl; p->n_type != 0; ++p)
563                                 ;
564                         _kvm_err(kd, kd->program,
565                                  "%s: no such symbol", p->n_name);
566                         return (0);
567                 }
568                 if (KREAD(kd, nl[0].n_value, &nprocs)) {
569                         _kvm_err(kd, kd->program, "can't read nprocs");
570                         return (0);
571                 }
572                 if (KREAD(kd, nl[3].n_value, &ticks)) {
573                         _kvm_err(kd, kd->program, "can't read ticks");
574                         return (0);
575                 }
576                 if (KREAD(kd, nl[4].n_value, &hz)) {
577                         _kvm_err(kd, kd->program, "can't read hz");
578                         return (0);
579                 }
580                 size = nprocs * sizeof(struct kinfo_proc);
581                 kd->procbase = (struct kinfo_proc *)_kvm_malloc(kd, size);
582                 if (kd->procbase == 0)
583                         return (0);
584
585                 nprocs = kvm_deadprocs(kd, op, arg, nl[1].n_value,
586                                       nl[2].n_value, nprocs);
587                 if (nprocs <= 0) {
588                         _kvm_freeprocs(kd);
589                         nprocs = 0;
590                 }
591 #ifdef notdef
592                 else {
593                         size = nprocs * sizeof(struct kinfo_proc);
594                         kd->procbase = realloc(kd->procbase, size);
595                 }
596 #endif
597         }
598         *cnt = nprocs;
599         return (kd->procbase);
600 }
601
602 void
603 _kvm_freeprocs(kd)
604         kvm_t *kd;
605 {
606         if (kd->procbase) {
607                 free(kd->procbase);
608                 kd->procbase = 0;
609         }
610 }
611
612 void *
613 _kvm_realloc(kd, p, n)
614         kvm_t *kd;
615         void *p;
616         size_t n;
617 {
618         void *np = (void *)realloc(p, n);
619
620         if (np == 0) {
621                 free(p);
622                 _kvm_err(kd, kd->program, "out of memory");
623         }
624         return (np);
625 }
626
627 #ifndef MAX
628 #define MAX(a, b) ((a) > (b) ? (a) : (b))
629 #endif
630
631 /*
632  * Read in an argument vector from the user address space of process kp.
633  * addr if the user-space base address of narg null-terminated contiguous
634  * strings.  This is used to read in both the command arguments and
635  * environment strings.  Read at most maxcnt characters of strings.
636  */
637 static char **
638 kvm_argv(kd, kp, addr, narg, maxcnt)
639         kvm_t *kd;
640         struct kinfo_proc *kp;
641         u_long addr;
642         int narg;
643         int maxcnt;
644 {
645         char *np, *cp, *ep, *ap;
646         u_long oaddr = -1;
647         int len, cc;
648         char **argv;
649
650         /*
651          * Check that there aren't an unreasonable number of agruments,
652          * and that the address is in user space.
653          */
654         if (narg > 512 || addr < VM_MIN_ADDRESS || addr >= VM_MAXUSER_ADDRESS)
655                 return (0);
656
657         /*
658          * kd->argv : work space for fetching the strings from the target 
659          *            process's space, and is converted for returning to caller
660          */
661         if (kd->argv == 0) {
662                 /*
663                  * Try to avoid reallocs.
664                  */
665                 kd->argc = MAX(narg + 1, 32);
666                 kd->argv = (char **)_kvm_malloc(kd, kd->argc *
667                                                 sizeof(*kd->argv));
668                 if (kd->argv == 0)
669                         return (0);
670         } else if (narg + 1 > kd->argc) {
671                 kd->argc = MAX(2 * kd->argc, narg + 1);
672                 kd->argv = (char **)_kvm_realloc(kd, kd->argv, kd->argc *
673                                                 sizeof(*kd->argv));
674                 if (kd->argv == 0)
675                         return (0);
676         }
677         /*
678          * kd->argspc : returned to user, this is where the kd->argv
679          *              arrays are left pointing to the collected strings.
680          */
681         if (kd->argspc == 0) {
682                 kd->argspc = (char *)_kvm_malloc(kd, PAGE_SIZE);
683                 if (kd->argspc == 0)
684                         return (0);
685                 kd->arglen = PAGE_SIZE;
686         }
687         /*
688          * kd->argbuf : used to pull in pages from the target process.
689          *              the strings are copied out of here.
690          */
691         if (kd->argbuf == 0) {
692                 kd->argbuf = (char *)_kvm_malloc(kd, PAGE_SIZE);
693                 if (kd->argbuf == 0)
694                         return (0);
695         }
696
697         /* Pull in the target process'es argv vector */
698         cc = sizeof(char *) * narg;
699         if (kvm_uread(kd, kp, addr, (char *)kd->argv, cc) != cc)
700                 return (0);
701         /*
702          * ap : saved start address of string we're working on in kd->argspc
703          * np : pointer to next place to write in kd->argspc
704          * len: length of data in kd->argspc
705          * argv: pointer to the argv vector that we are hunting around the
706          *       target process space for, and converting to addresses in
707          *       our address space (kd->argspc).
708          */
709         ap = np = kd->argspc;
710         argv = kd->argv;
711         len = 0;
712         /*
713          * Loop over pages, filling in the argument vector.
714          * Note that the argv strings could be pointing *anywhere* in
715          * the user address space and are no longer contiguous.
716          * Note that *argv is modified when we are going to fetch a string
717          * that crosses a page boundary.  We copy the next part of the string
718          * into to "np" and eventually convert the pointer.
719          */
720         while (argv < kd->argv + narg && *argv != 0) {
721
722                 /* get the address that the current argv string is on */
723                 addr = (u_long)*argv & ~(PAGE_SIZE - 1);
724
725                 /* is it the same page as the last one? */
726                 if (addr != oaddr) {
727                         if (kvm_uread(kd, kp, addr, kd->argbuf, PAGE_SIZE) !=
728                             PAGE_SIZE)
729                                 return (0);
730                         oaddr = addr;
731                 }
732
733                 /* offset within the page... kd->argbuf */
734                 addr = (u_long)*argv & (PAGE_SIZE - 1);
735
736                 /* cp = start of string, cc = count of chars in this chunk */
737                 cp = kd->argbuf + addr;
738                 cc = PAGE_SIZE - addr;
739
740                 /* dont get more than asked for by user process */
741                 if (maxcnt > 0 && cc > maxcnt - len)
742                         cc = maxcnt - len;
743
744                 /* pointer to end of string if we found it in this page */
745                 ep = memchr(cp, '\0', cc);
746                 if (ep != 0)
747                         cc = ep - cp + 1;
748                 /*
749                  * at this point, cc is the count of the chars that we are
750                  * going to retrieve this time. we may or may not have found
751                  * the end of it.  (ep points to the null if the end is known)
752                  */
753
754                 /* will we exceed the malloc/realloced buffer? */
755                 if (len + cc > kd->arglen) {
756                         int off;
757                         char **pp;
758                         char *op = kd->argspc;
759
760                         kd->arglen *= 2;
761                         kd->argspc = (char *)_kvm_realloc(kd, kd->argspc,
762                                                           kd->arglen);
763                         if (kd->argspc == 0)
764                                 return (0);
765                         /*
766                          * Adjust argv pointers in case realloc moved
767                          * the string space.
768                          */
769                         off = kd->argspc - op;
770                         for (pp = kd->argv; pp < argv; pp++)
771                                 *pp += off;
772                         ap += off;
773                         np += off;
774                 }
775                 /* np = where to put the next part of the string in kd->argspc*/
776                 /* np is kinda redundant.. could use "kd->argspc + len" */
777                 memcpy(np, cp, cc);
778                 np += cc;       /* inc counters */
779                 len += cc;
780
781                 /*
782                  * if end of string found, set the *argv pointer to the
783                  * saved beginning of string, and advance. argv points to
784                  * somewhere in kd->argv..  This is initially relative
785                  * to the target process, but when we close it off, we set
786                  * it to point in our address space.
787                  */
788                 if (ep != 0) {
789                         *argv++ = ap;
790                         ap = np;
791                 } else {
792                         /* update the address relative to the target process */
793                         *argv += cc;
794                 }
795
796                 if (maxcnt > 0 && len >= maxcnt) {
797                         /*
798                          * We're stopping prematurely.  Terminate the
799                          * current string.
800                          */
801                         if (ep == 0) {
802                                 *np = '\0';
803                                 *argv++ = ap;
804                         }
805                         break;
806                 }
807         }
808         /* Make sure argv is terminated. */
809         *argv = 0;
810         return (kd->argv);
811 }
812
813 static void
814 ps_str_a(p, addr, n)
815         struct ps_strings *p;
816         u_long *addr;
817         int *n;
818 {
819         *addr = (u_long)p->ps_argvstr;
820         *n = p->ps_nargvstr;
821 }
822
823 static void
824 ps_str_e(p, addr, n)
825         struct ps_strings *p;
826         u_long *addr;
827         int *n;
828 {
829         *addr = (u_long)p->ps_envstr;
830         *n = p->ps_nenvstr;
831 }
832
833 /*
834  * Determine if the proc indicated by p is still active.
835  * This test is not 100% foolproof in theory, but chances of
836  * being wrong are very low.
837  */
838 static int
839 proc_verify(curkp)
840         struct kinfo_proc *curkp;
841 {
842         struct kinfo_proc newkp;
843         int mib[4];
844         size_t len;
845
846         mib[0] = CTL_KERN;
847         mib[1] = KERN_PROC;
848         mib[2] = KERN_PROC_PID;
849         mib[3] = curkp->ki_pid;
850         len = sizeof(newkp);
851         if (sysctl(mib, 4, &newkp, &len, NULL, 0) == -1)
852                 return (0);
853         return (curkp->ki_pid == newkp.ki_pid &&
854             (newkp.ki_stat != SZOMB || curkp->ki_stat == SZOMB));
855 }
856
857 static char **
858 kvm_doargv(kd, kp, nchr, info)
859         kvm_t *kd;
860         struct kinfo_proc *kp;
861         int nchr;
862         void (*info)(struct ps_strings *, u_long *, int *);
863 {
864         char **ap;
865         u_long addr;
866         int cnt;
867         static struct ps_strings arginfo;
868         static u_long ps_strings;
869         size_t len;
870
871         if (ps_strings == 0) {
872                 len = sizeof(ps_strings);
873                 if (sysctlbyname("kern.ps_strings", &ps_strings, &len, NULL,
874                     0) == -1)
875                         ps_strings = PS_STRINGS;
876         }
877
878         /*
879          * Pointers are stored at the top of the user stack.
880          */
881         if (kp->ki_stat == SZOMB ||
882             kvm_uread(kd, kp, ps_strings, (char *)&arginfo,
883                       sizeof(arginfo)) != sizeof(arginfo))
884                 return (0);
885
886         (*info)(&arginfo, &addr, &cnt);
887         if (cnt == 0)
888                 return (0);
889         ap = kvm_argv(kd, kp, addr, cnt, nchr);
890         /*
891          * For live kernels, make sure this process didn't go away.
892          */
893         if (ap != 0 && ISALIVE(kd) && !proc_verify(kp))
894                 ap = 0;
895         return (ap);
896 }
897
898 /*
899  * Get the command args.  This code is now machine independent.
900  */
901 char **
902 kvm_getargv(kd, kp, nchr)
903         kvm_t *kd;
904         const struct kinfo_proc *kp;
905         int nchr;
906 {
907         int oid[4];
908         int i;
909         size_t bufsz;
910         static unsigned long buflen;
911         static char *buf, *p;
912         static char **bufp;
913         static int argc;
914
915         if (!ISALIVE(kd)) {
916                 _kvm_err(kd, kd->program,
917                     "cannot read user space from dead kernel");
918                 return (0);
919         }
920
921         if (!buflen) {
922                 bufsz = sizeof(buflen);
923                 i = sysctlbyname("kern.ps_arg_cache_limit", 
924                     &buflen, &bufsz, NULL, 0);
925                 if (i == -1) {
926                         buflen = 0;
927                 } else {
928                         buf = malloc(buflen);
929                         if (buf == NULL)
930                                 buflen = 0;
931                         argc = 32;
932                         bufp = malloc(sizeof(char *) * argc);
933                 }
934         }
935         if (buf != NULL) {
936                 oid[0] = CTL_KERN;
937                 oid[1] = KERN_PROC;
938                 oid[2] = KERN_PROC_ARGS;
939                 oid[3] = kp->ki_pid;
940                 bufsz = buflen;
941                 i = sysctl(oid, 4, buf, &bufsz, 0, 0);
942                 if (i == 0 && bufsz > 0) {
943                         i = 0;
944                         p = buf;
945                         do {
946                                 bufp[i++] = p;
947                                 p += strlen(p) + 1;
948                                 if (i >= argc) {
949                                         argc += argc;
950                                         bufp = realloc(bufp,
951                                             sizeof(char *) * argc);
952                                 }
953                         } while (p < buf + bufsz);
954                         bufp[i++] = 0;
955                         return (bufp);
956                 }
957         }
958         if (kp->ki_flag & P_SYSTEM)
959                 return (NULL);
960         return (kvm_doargv(kd, kp, nchr, ps_str_a));
961 }
962
963 char **
964 kvm_getenvv(kd, kp, nchr)
965         kvm_t *kd;
966         const struct kinfo_proc *kp;
967         int nchr;
968 {
969         return (kvm_doargv(kd, kp, nchr, ps_str_e));
970 }
971
972 /*
973  * Read from user space.  The user context is given by p.
974  */
975 ssize_t
976 kvm_uread(kd, kp, uva, buf, len)
977         kvm_t *kd;
978         struct kinfo_proc *kp;
979         u_long uva;
980         char *buf;
981         size_t len;
982 {
983         char *cp;
984         char procfile[MAXPATHLEN];
985         ssize_t amount;
986         int fd;
987
988         if (!ISALIVE(kd)) {
989                 _kvm_err(kd, kd->program,
990                     "cannot read user space from dead kernel");
991                 return (0);
992         }
993
994         sprintf(procfile, "/proc/%d/mem", kp->ki_pid);
995         fd = open(procfile, O_RDONLY, 0);
996         if (fd < 0) {
997                 _kvm_err(kd, kd->program, "cannot open %s", procfile);
998                 return (0);
999         }
1000
1001         cp = buf;
1002         while (len > 0) {
1003                 errno = 0;
1004                 if (lseek(fd, (off_t)uva, 0) == -1 && errno != 0) {
1005                         _kvm_err(kd, kd->program, "invalid address (%x) in %s",
1006                             uva, procfile);
1007                         break;
1008                 }
1009                 amount = read(fd, cp, len);
1010                 if (amount < 0) {
1011                         _kvm_syserr(kd, kd->program, "error reading %s",
1012                             procfile);
1013                         break;
1014                 }
1015                 if (amount == 0) {
1016                         _kvm_err(kd, kd->program, "EOF reading %s", procfile);
1017                         break;
1018                 }
1019                 cp += amount;
1020                 uva += amount;
1021                 len -= amount;
1022         }
1023
1024         close(fd);
1025         return ((ssize_t)(cp - buf));
1026 }