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