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