ps - Add a new option, -R, which sub-sorts by parent/child and indents
[dragonfly.git] / bin / ps / print.c
1 /*-
2  * Copyright (c) 1990, 1993, 1994
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
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  * @(#)print.c  8.6 (Berkeley) 4/16/94
34  * $FreeBSD: src/bin/ps/print.c,v 1.36.2.4 2002/11/30 13:00:14 tjr Exp $
35  * $DragonFly: src/bin/ps/print.c,v 1.34 2008/11/10 14:56:33 swildner Exp $
36  */
37
38 #include <sys/user.h>
39 #include <sys/param.h>
40 #include <sys/time.h>
41 #include <sys/resource.h>
42 #include <sys/stat.h>
43
44 #include <sys/ucred.h>
45 #include <sys/sysctl.h>
46 #include <sys/rtprio.h>
47 #include <vm/vm.h>
48
49 #include <err.h>
50 #include <langinfo.h>
51 #include <locale.h>
52 #include <math.h>
53 #include <nlist.h>
54 #include <pwd.h>
55 #include <stddef.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <unistd.h>
59 #include <string.h>
60 #include <vis.h>
61
62 #include "ps.h"
63
64 static const char *make_printable(const char *str);
65
66 void
67 printheader(void)
68 {
69         const VAR *v;
70         struct varent *vent;
71         int allempty;
72
73         allempty = 1;
74         STAILQ_FOREACH(vent, &var_head, link) {
75                 if (*vent->header != '\0') {
76                         allempty = 0;
77                         break;
78                 }
79         }
80         if (allempty)
81                 return;
82         STAILQ_FOREACH(vent, &var_head, link) {
83                 v = vent->var;
84                 if (v->flag & LJUST) {
85                         if (STAILQ_NEXT(vent, link) == NULL)    /* last one */
86                                 printf("%s", vent->header);
87                         else
88                                 printf("%-*s", vent->width, vent->header);
89                 } else
90                         printf("%*s", vent->width, vent->header);
91                 if (STAILQ_NEXT(vent, link) != NULL)
92                         putchar(' ');
93         }
94         putchar('\n');
95 }
96
97 void
98 command(const KINFO *k, const struct varent *vent)
99 {
100         int left;
101         int indent;
102         char *cp, *vis_env, *vis_args;
103
104         if (cflag) {
105                 /* Don't pad the last field. */
106                 if (STAILQ_NEXT(vent, link) == NULL)
107                         printf("%s", make_printable(KI_PROC(k, comm)));
108                 else
109                         printf("%-*s", vent->width, 
110                                 make_printable(KI_PROC(k, comm)));
111                 return;
112         }
113
114         if ((vis_args = malloc(strlen(k->ki_args) * 4 + 1)) == NULL)
115                 err(1, NULL);
116         strvis(vis_args, k->ki_args, VIS_TAB | VIS_NL | VIS_NOSLASH);
117         if (k->ki_env) {
118                 if ((vis_env = malloc(strlen(k->ki_env) * 4 + 1)) == NULL)
119                         err(1, NULL);
120                 strvis(vis_env, k->ki_env, VIS_TAB | VIS_NL | VIS_NOSLASH);
121         } else {
122                 vis_env = NULL;
123         }
124
125         indent = k->ki_indent;
126         if (indent < 0)
127                 indent = 0;
128
129         if (STAILQ_NEXT(vent, link) == NULL) {
130                 /* last field */
131                 if (termwidth == UNLIMITED) {
132                         if (vis_env)
133                                 printf("%s ", vis_env);
134                         while (indent) {
135                                 putchar(' ');
136                                 --indent;
137                         }
138                         printf("%s", vis_args);
139                 } else {
140                         left = termwidth - (totwidth - vent->width);
141                         if (left < 1) /* already wrapped, just use std width */
142                                 left = vent->width;
143                         while (indent && left > 1) {
144                                 putchar(' ');
145                                 --indent;
146                                 --left;
147                         }
148                         if ((cp = vis_env) != NULL) {
149                                 while (--left >= 0 && *cp)
150                                         putchar(*cp++);
151                                 if (--left >= 0)
152                                         putchar(' ');
153                         }
154                         for (cp = vis_args; --left >= 0 && *cp != '\0';)
155                                 putchar(*cp++);
156                 }
157         } else
158                 /* XXX env? */
159                 printf("%-*.*s", vent->width, vent->width, vis_args);
160         free(vis_args);
161         if (vis_env != NULL)
162                 free(vis_env);
163 }
164
165 void
166 ucomm(const KINFO *k, const struct varent *vent)
167 {
168         printf("%-*s", vent->width, make_printable(KI_PROC(k, comm)));
169 }
170
171 void
172 logname(const KINFO *k, const struct varent *vent)
173 {
174         const char *s = KI_PROC(k, login);
175
176         printf("%-*s", vent->width, *s != '\0' ? s : "-");
177 }
178
179 void
180 state(const KINFO *k, const struct varent *vent)
181 {
182         int flag;
183         char *cp;
184         char buf[16];
185
186         flag = KI_PROC(k, flags);
187         cp = buf;
188
189         switch (KI_PROC(k, stat)) {
190
191         case SSTOP:
192                 *cp = 'T';
193                 break;
194
195         case SACTIVE:
196                 switch (KI_LWP(k, stat)) {
197                 case LSSLEEP:
198                         if (KI_LWP(k, flags) & LWP_SINTR) {
199                                 /* interruptable wait short/long */
200                                 *cp = KI_LWP(k, slptime) >= MAXSLP ? 'I' : 'S';
201                         }
202                         else if (KI_LWP(k, tdflags) & TDF_SINTR)
203                                 *cp = 'S';      /* interruptable lwkt wait */
204                         else if (KI_PROC(k, paddr))
205                                 *cp = 'D';      /* uninterruptable wait */
206                         else
207                                 *cp = 'B';      /* uninterruptable lwkt wait */
208                         break;
209
210                 case LSRUN:
211                         *cp = 'R';
212                         if (KI_LWP(k, tdflags) & (TDF_RUNNING | TDF_RUNQ)) {
213                             ++cp;
214                             sprintf(cp, "%d", KI_LWP(k, cpuid));
215                             while (cp[1])
216                                 ++cp;
217                         }
218                         break;
219
220                 case LSSTOP:
221                         /* shouldn't happen anyways */
222                         *cp = 'T';
223                         break;
224                 }
225                 break;
226
227         case SZOMB:
228                 *cp = 'Z';
229                 break;
230
231         default:
232                 *cp = '?';
233         }
234
235         cp++;
236         if (flag & P_SWAPPEDOUT)
237                 *cp++ = 'W';
238         if (KI_PROC(k, nice) < NZERO)
239                 *cp++ = '<';
240         else if (KI_PROC(k, nice) > NZERO)
241                 *cp++ = 'N';
242         if (flag & P_TRACED)
243                 *cp++ = 'X';
244         if (flag & P_WEXIT && KI_PROC(k, stat) != SZOMB)
245                 *cp++ = 'E';
246         if (flag & P_PPWAIT)
247                 *cp++ = 'V';
248         if ((flag & P_SYSTEM) || KI_PROC(k, lock) > 0)
249                 *cp++ = 'L';
250         if (numcpus > 1 && KI_LWP(k, mpcount) == 0)
251                 *cp++ = 'M';
252         if (flag & P_JAILED)
253                 *cp++ = 'J';
254         if (KI_PROC(k, auxflags) & KI_SLEADER)
255                 *cp++ = 's';
256         if ((flag & P_CONTROLT) && KI_PROC(k, pgid) == KI_PROC(k, tpgid))
257                 *cp++ = '+';
258         *cp = '\0';
259         printf("%-*s", vent->width, buf);
260 }
261
262 /*
263  * Normalized priority (lower is better).  For pure threads
264  * output a negated LWKT priority (so lower still means better).
265  *
266  * XXX bsd4 scheduler specific.
267  */
268 void
269 pri(const KINFO *k, const struct varent *vent)
270 {
271         if (KI_LWP(k, pid) != -1)
272             printf("%*d", vent->width, KI_LWP(k, prio));
273         else
274             printf("%*d", vent->width, -(KI_LWP(k, tdprio)));
275 }
276
277 void
278 tdpri(const KINFO *k, const struct varent *vent)
279 {
280         char buf[32];
281         int val = KI_LWP(k, tdprio);
282
283         snprintf(buf, sizeof(buf), "%2d", val);
284         printf("%*s", vent->width, buf);
285 }
286
287 void
288 uname(const KINFO *k, const struct varent *vent)
289 {
290         printf("%-*s", vent->width,
291                user_from_uid(KI_PROC(k, uid), 0));
292 }
293
294 int
295 s_uname(const KINFO *k)
296 {
297         return (strlen(user_from_uid(KI_PROC(k, uid), 0)));
298 }
299
300 void
301 runame(const KINFO *k, const struct varent *vent)
302 {
303         printf("%-*s", vent->width,
304                user_from_uid(KI_PROC(k, ruid), 0));
305 }
306
307 int
308 s_runame(const KINFO *k)
309 {
310         return (strlen(user_from_uid(KI_PROC(k, ruid), 0)));
311 }
312
313 void
314 tdev(const KINFO *k, const struct varent *vent)
315 {
316         dev_t dev;
317         char buff[16];
318
319         dev = KI_PROC(k, tdev);
320         if (dev == NODEV)
321                 printf("%*s", vent->width, "??");
322         else {
323                 snprintf(buff, sizeof(buff), "%d/%d", major(dev), minor(dev));
324                 printf("%*s", vent->width, buff);
325         }
326 }
327
328 void
329 tname(const KINFO *k, const struct varent *vent)
330 {
331         dev_t dev;
332         const char *ttname;
333
334         dev = KI_PROC(k, tdev);
335         if (dev == NODEV || (ttname = devname(dev, S_IFCHR)) == NULL)
336                 printf("%*s ", vent->width-1, "??");
337         else {
338                 if (strncmp(ttname, "tty", 3) == 0 ||
339                     strncmp(ttname, "cua", 3) == 0)
340                         ttname += 3;
341                 if (strncmp(ttname, "pts/", 4) == 0)
342                         ttname += 4;
343                 printf("%*.*s%c", vent->width-1, vent->width-1, ttname,
344                         KI_PROC(k, auxflags) & KI_CTTY ? ' ' : '-');
345         }
346 }
347
348 void
349 longtname(const KINFO *k, const struct varent *vent)
350 {
351         dev_t dev;
352         const char *ttname;
353
354         dev = KI_PROC(k, tdev);
355         if (dev == NODEV || (ttname = devname(dev, S_IFCHR)) == NULL)
356                 printf("%-*s", vent->width, "??");
357         else
358                 printf("%-*s", vent->width, ttname);
359 }
360
361 void
362 started(const KINFO *k, const struct varent *vent)
363 {
364         static time_t now;
365         time_t then;
366         struct tm *tp;
367         char buf[100];
368         static int  use_ampm = -1;
369
370         if (use_ampm < 0)
371                 use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0');
372
373         then = KI_PROC(k, start).tv_sec;
374         if (then < btime.tv_sec) {
375                 then = btime.tv_sec;
376         }
377
378         tp = localtime(&then);
379         if (!now)
380                 time(&now);
381         if (now - then < 24 * 3600) {
382                 strftime(buf, sizeof(buf) - 1,
383                 use_ampm ? "%l:%M%p" : "%k:%M  ", tp);
384         } else if (now - then < 7 * 86400) {
385                 strftime(buf, sizeof(buf) - 1,
386                 use_ampm ? "%a%I%p" : "%a%H  ", tp);
387         } else
388                 strftime(buf, sizeof(buf) - 1, "%e%b%y", tp);
389         printf("%-*s", vent->width, buf);
390 }
391
392 void
393 lstarted(const KINFO *k, const struct varent *vent)
394 {
395         time_t then;
396         char buf[100];
397
398         then = KI_PROC(k, start).tv_sec;
399         strftime(buf, sizeof(buf) -1, "%c", localtime(&then));
400         printf("%-*s", vent->width, buf);
401 }
402
403 void
404 wchan(const KINFO *k, const struct varent *vent)
405 {
406         if (*KI_LWP(k, wmesg)) {
407                 printf("%-*.*s", vent->width, vent->width,
408                        KI_LWP(k, wmesg));
409         } else {
410                 printf("%-*s", vent->width, "-");
411         }
412 }
413
414 #ifndef pgtok
415 #define pgtok(a)        (((a)*getpagesize())/1024)
416 #endif
417
418 void
419 vsize(const KINFO *k, const struct varent *vent)
420 {
421         printf("%*ju", vent->width, (uintmax_t)(KI_PROC(k, vm_map_size)/1024));
422 }
423
424 void
425 rssize(const KINFO *k, const struct varent *vent)
426 {
427         /* XXX don't have info about shared */
428         printf("%*lu", vent->width, (u_long)pgtok(KI_PROC(k, vm_rssize)));
429 }
430
431 void
432 p_rssize(const KINFO *k, const struct varent *vent)     /* doesn't account for text */
433 {
434         printf("%*ld", vent->width, (long)pgtok(KI_PROC(k, vm_rssize)));
435 }
436
437 void
438 cputime(const KINFO *k, const struct varent *vent)
439 {
440         long secs;
441         long psecs;     /* "parts" of a second. first micro, then centi */
442         u_int64_t timeus;
443         char obuff[128];
444         static char decimal_point = '\0';
445
446         if (decimal_point == '\0')
447                 decimal_point = localeconv()->decimal_point[0];
448
449         /*
450          * This counts time spent handling interrupts.  We could
451          * fix this, but it is not 100% trivial (and interrupt
452          * time fractions only work on the sparc anyway).       XXX
453          */
454         timeus = KI_LWP(k, uticks) + KI_LWP(k, sticks) +
455                 KI_LWP(k, iticks);
456         secs = timeus / 1000000;
457         psecs = timeus % 1000000;
458         if (sumrusage) {
459                 secs += KI_PROC(k, cru).ru_utime.tv_sec +
460                         KI_PROC(k, cru).ru_stime.tv_sec;
461                 psecs += KI_PROC(k, cru).ru_utime.tv_usec +
462                         KI_PROC(k, cru).ru_stime.tv_usec;
463         }
464         /*
465          * round and scale to 100's
466          */
467         psecs = (psecs + 5000) / 10000;
468         secs += psecs / 100;
469         psecs = psecs % 100;
470 #if 1
471         if (secs >= 86400) {
472                 snprintf(obuff, sizeof(obuff), "%3ldd%02ld:%02ld",
473                         secs / 86400, secs / (60 * 60) % 24, secs / 60 % 60);
474         } else if (secs >= 100 * 60) {
475                 snprintf(obuff, sizeof(obuff), "%2ld:%02ld:%02ld",
476                         secs / 60 / 60, secs / 60 % 60, secs % 60);
477         } else
478 #endif
479         {
480                 snprintf(obuff, sizeof(obuff), "%3ld:%02ld%c%02ld",
481                          secs / 60, secs % 60,
482                          decimal_point, psecs);
483         }
484         printf("%*s", vent->width, obuff);
485 }
486
487 double
488 getpcpu(const KINFO *k)
489 {
490         static int failure;
491
492         if (!nlistread)
493                 failure = donlist();
494         if (failure)
495                 return (0.0);
496
497 #define fxtofl(fixpt)   ((double)(fixpt) / fscale)
498
499         /* XXX - I don't like this */
500         if (KI_PROC(k, swtime) == 0 || (KI_PROC(k, flags) & P_SWAPPEDOUT))
501                 return (0.0);
502         if (rawcpu)
503                 return (100.0 * fxtofl(KI_LWP(k, pctcpu)));
504         return (100.0 * fxtofl(KI_LWP(k, pctcpu)) /
505                 (1.0 - exp(KI_PROC(k, swtime) * log(fxtofl(ccpu)))));
506 }
507
508 void
509 pcpu(const KINFO *k, const struct varent *vent)
510 {
511         printf("%*.1f", vent->width, getpcpu(k));
512 }
513
514 void
515 pnice(const KINFO *k, const struct varent *vent)
516 {
517         int niceval;
518
519         switch (KI_LWP(k, rtprio).type) {
520         case RTP_PRIO_REALTIME:
521                 niceval = PRIO_MIN - 1 - RTP_PRIO_MAX + KI_LWP(k, rtprio).prio;
522                 break;
523         case RTP_PRIO_IDLE:
524                 niceval = PRIO_MAX + 1 + KI_LWP(k, rtprio).prio;
525                 break;
526         case RTP_PRIO_THREAD:
527                 niceval = PRIO_MIN - 1 - RTP_PRIO_MAX - KI_LWP(k, rtprio).prio;
528                 break;
529         default:
530                 niceval = KI_PROC(k, nice) - NZERO;
531                 break;
532         }
533         printf("%*d", vent->width, niceval);
534 }
535
536
537 double
538 getpmem(const KINFO *k)
539 {
540         static int failure;
541         double fracmem;
542         int szptudot;
543
544         if (!nlistread)
545                 failure = donlist();
546         if (failure)
547                 return (0.0);
548
549         if (KI_PROC(k, flags) & P_SWAPPEDOUT)
550                 return (0.0);
551         /* XXX want pmap ptpages, segtab, etc. (per architecture) */
552         szptudot = UPAGES;
553         /* XXX don't have info about shared */
554         fracmem = ((float)KI_PROC(k, vm_rssize) + szptudot)/mempages;
555         return (100.0 * fracmem);
556 }
557
558 void
559 pmem(const KINFO *k, const struct varent *vent)
560 {
561         printf("%*.1f", vent->width, getpmem(k));
562 }
563
564 void
565 pagein(const KINFO *k, const struct varent *vent)
566 {
567         printf("%*ld", vent->width, KI_LWP(k, ru).ru_majflt);
568 }
569
570 /* ARGSUSED */
571 void
572 maxrss(const KINFO *k __unused, const struct varent *vent)
573 {
574         printf("%*ld", vent->width, KI_PROC(k, ru).ru_maxrss);
575 }
576
577 void
578 tsize(const KINFO *k, const struct varent *vent)
579 {
580         printf("%*ld", vent->width, (long)pgtok(KI_PROC(k, vm_tsize)));
581 }
582
583 void
584 rtprior(const KINFO *k, const struct varent *vent)
585 {
586         struct rtprio *prtp;
587         char str[8];
588         unsigned prio, type;
589  
590         prtp = &KI_LWP(k, rtprio);
591         prio = prtp->prio;
592         type = prtp->type;
593         switch (type) {
594         case RTP_PRIO_REALTIME:
595                 snprintf(str, sizeof(str), "real:%u", prio);
596                 break;
597         case RTP_PRIO_NORMAL:
598                 strncpy(str, "normal", sizeof(str));
599                 break;
600         case RTP_PRIO_IDLE:
601                 snprintf(str, sizeof(str), "idle:%u", prio);
602                 break;
603         default:
604                 snprintf(str, sizeof(str), "%u:%u", type, prio);
605                 break;
606         }
607         str[sizeof(str) - 1] = '\0';
608         printf("%*s", vent->width, str);
609 }
610
611 /*
612  * Generic output routines.  Print fields from various prototype
613  * structures.
614  */
615 static void
616 printval(const char *bp, const struct varent *vent)
617 {
618         static char ofmt[32] = "%";
619         const char *fcp;
620         char *cp;
621
622         cp = ofmt + 1;
623         fcp = vent->var->fmt;
624         if (vent->var->flag & LJUST)
625                 *cp++ = '-';
626         *cp++ = '*';
627         while ((*cp++ = *fcp++));
628
629         switch (vent->var->type) {
630         case CHAR:
631                 printf(ofmt, vent->width, *(const char *)bp);
632                 break;
633         case UCHAR:
634                 printf(ofmt, vent->width, *(const u_char *)bp);
635                 break;
636         case SHORT:
637                 printf(ofmt, vent->width, *(const short *)bp);
638                 break;
639         case USHORT:
640                 printf(ofmt, vent->width, *(const u_short *)bp);
641                 break;
642         case INT:
643                 printf(ofmt, vent->width, *(const int *)bp);
644                 break;
645         case UINT:
646                 printf(ofmt, vent->width, *(const u_int *)bp);
647                 break;
648         case LONG:
649                 printf(ofmt, vent->width, *(const long *)bp);
650                 break;
651         case ULONG:
652                 printf(ofmt, vent->width, *(const u_long *)bp);
653                 break;
654         case KPTR:
655                 printf(ofmt, vent->width, *(const u_long *)bp);
656                 break;
657         default:
658                 errx(1, "unknown type %d", vent->var->type);
659         }
660 }
661
662 void
663 pvar(const KINFO *k, const struct varent *vent)
664 {
665         printval((char *)((char *)k->ki_proc + vent->var->off), vent);
666 }
667
668 void
669 lpest(const KINFO *k, const struct varent *vent)
670 {
671         int val;
672
673         val = *(int *)((char *)&k->ki_proc->kp_lwp + vent->var->off);
674         val = val / 128;
675         printval((char *)&val, vent);
676 }
677
678
679 void
680 lpvar(const KINFO *k, const struct varent *vent)
681 {
682         printval((char *)((char *)&k->ki_proc->kp_lwp + vent->var->off), vent);
683 }
684
685 void
686 rvar(const KINFO *k, const struct varent *vent)
687 {
688         printval(((const char *)&KI_LWP(k, ru) + vent->var->off), vent);
689 }
690
691 static const char *
692 make_printable(const char *str)
693 {
694     static char *cpy;
695     int len;
696
697     if (cpy)
698         free(cpy);
699     len = strlen(str);
700     if ((cpy = malloc(len * 4 + 1)) == NULL)
701         err(1, NULL);
702     strvis(cpy, str, VIS_TAB | VIS_NL | VIS_NOSLASH);
703     return(cpy);
704 }