-
Notifications
You must be signed in to change notification settings - Fork 13
/
top.c
3414 lines (3030 loc) · 110 KB
/
top.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* top.c - Source file: show Linux processes */
/*
* Copyright (c) 2002, by: James C. Warner
* All rights reserved. 8921 Hilloway Road
* Eden Prairie, Minnesota 55347 USA
*
* This file may be used subject to the terms and conditions of the
* GNU Library General Public License Version 2, or any later version
* at your option, as published by the Free Software Foundation.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* For their contributions to this program, the author wishes to thank:
* Albert D. Cahalan, <[email protected]>
* Craig Small, <[email protected]>
*
* Changes by Albert Cahalan, 2002-2004.
*/
#include <sys/ioctl.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <ctype.h>
#include <curses.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Foul POS defines all sorts of stuff...
#include <term.h>
#undef tab
#include <termios.h>
#include <time.h>
#include <unistd.h>
#include <values.h>
#include "proc/devname.h"
#include "proc/wchan.h"
#include "proc/procps.h"
#include "proc/readproc.h"
#include "proc/escape.h"
#include "proc/sig.h"
#include "proc/sysinfo.h"
#include "proc/version.h"
#include "proc/whattime.h"
#include "top.h"
/*###### Miscellaneous global stuff ####################################*/
/* The original and new terminal attributes */
static struct termios Savedtty,
Rawtty;
static int Ttychanged = 0;
/* Program name used in error messages and local 'rc' file name */
static char *Myname;
/* Name of user config file (dynamically constructed) and our
'Current' rcfile contents, initialized with defaults but may be
overridden with the local rcfile (old or new-style) values */
static char Rc_name [OURPATHSZ];
static RCF_t Rc = DEF_RCFILE;
/* The run-time acquired page size */
static unsigned Page_size;
static unsigned page_to_kb_shift;
/* SMP Irix/Solaris mode */
static int Cpu_tot;
static double pcpu_max_value; // usually 99.9, for %CPU display
/* assume no IO-wait stats, overridden if linux 2.5.41 */
static const char *States_fmts = STATES_line2x4;
/* Specific process id monitoring support */
static pid_t Monpids [MONPIDMAX] = { 0 };
static int Monpidsidx = 0;
/* A postponed error message */
static char Msg_delayed [SMLBUFSIZ];
static int Msg_awaiting = 0;
// This is the select() timeout. Clear it in sig handlers to avoid a race.
// (signal happens just as we are about to select() and thus does not
// break us out of the select(), causing us to delay until timeout)
static volatile struct timeval tv;
#define ZAP_TIMEOUT do{tv.tv_usec=0; tv.tv_sec=0;}while(0);
/* Configurable Display support ##################################*/
/* Current screen dimensions.
note: the number of processes displayed is tracked on a per window
basis (see the WIN_t). Max_lines is the total number of
screen rows after deducting summary information overhead. */
/* Current terminal screen size. */
static int Screen_cols, Screen_rows, Max_lines;
// set to 1 if writing to the last column would be troublesome
// (we don't distinguish the lowermost row from the other rows)
static int avoid_last_column;
/* This is really the number of lines needed to display the summary
information (0 - nn), but is used as the relative row where we
stick the cursor between frames. */
static int Msg_row;
/* Global/Non-windows mode stuff that is NOT persistent */
static int No_ksyms = -1, // set to '0' if ksym avail, '1' otherwise
PSDBopen = 0, // set to '1' if psdb opened (now postponed)
Batch = 0, // batch mode, collect no input, dumb output
Loops = -1, // number of iterations, -1 loops forever
Secure_mode = 0; // set if some functionality restricted
/* Some cap's stuff to reduce runtime calls --
to accomodate 'Batch' mode, they begin life as empty strings */
static char Cap_clr_eol [CAPBUFSIZ],
Cap_clr_eos [CAPBUFSIZ],
Cap_clr_scr [CAPBUFSIZ],
Cap_rmam [CAPBUFSIZ],
Cap_smam [CAPBUFSIZ],
Cap_curs_norm [CAPBUFSIZ],
Cap_curs_huge [CAPBUFSIZ],
Cap_home [CAPBUFSIZ],
Cap_norm [CAPBUFSIZ],
Cap_reverse [CAPBUFSIZ],
Caps_off [CAPBUFSIZ];
static int Cap_can_goto = 0;
/* Some optimization stuff, to reduce output demands...
The Pseudo_ guys are managed by wins_resize and frame_make. They
are exploited in a macro and represent 90% of our optimization.
The Stdout_buf is transparent to our code and regardless of whose
buffer is used, stdout is flushed at frame end or if interactive. */
static char *Pseudo_scrn;
static int Pseudo_row, Pseudo_cols, Pseudo_size;
#ifndef STDOUT_IOLBF
// less than stdout's normal buffer but with luck mostly '\n' anyway
static char Stdout_buf[2048];
#endif
/* ////////////////////////////////////////////////////////////// */
/* Special Section: multiple windows/field groups ---------------*/
/* The pointers to our four WIN_t's, and which of those is considered
the 'current' window (ie. which window is associated with any summ
info displayed and to which window commands are directed) */
static WIN_t Winstk [GROUPSMAX],
*Curwin;
/* Frame oriented stuff that can't remain local to any 1 function
and/or that would be too cumbersome managed as parms,
and/or that are simply more efficiently handled as globals
(first 2 persist beyond a single frame, changed infrequently) */
static int Frames_libflags; // PROC_FILLxxx flags (0 = need new)
//atic int Frames_maxcmdln; // the largest from the 4 windows
static unsigned Frame_maxtask; // last known number of active tasks
// ie. current 'size' of proc table
static unsigned Frame_running, // state categories for this frame
Frame_sleepin,
Frame_stopped,
Frame_zombied;
static float Frame_tscale; // so we can '*' vs. '/' WHEN 'pcpu'
static int Frame_srtflg, // the subject window's sort direction
Frame_ctimes, // the subject window's ctimes flag
Frame_cmdlin; // the subject window's cmdlin flag
/* ////////////////////////////////////////////////////////////// */
/*###### Sort callbacks ################################################*/
/*
* These happen to be coded in the same order as the enum 'pflag'
* values. Note that 2 of these routines serve double duty --
* 2 columns each.
*/
SCB_NUMx(P_PID, XXXID)
SCB_NUMx(P_PPD, ppid)
SCB_STRx(P_URR, ruser)
SCB_NUMx(P_UID, euid)
SCB_STRx(P_URE, euser)
SCB_STRx(P_GRP, egroup)
SCB_NUMx(P_TTY, tty)
SCB_NUMx(P_PRI, priority)
SCB_NUMx(P_NCE, nice)
SCB_NUMx(P_CPN, processor)
SCB_NUM1(P_CPU, pcpu)
// also serves P_TM2 !
static int sort_P_TME (const proc_t **P, const proc_t **Q)
{
if (Frame_ctimes) {
if ( ((*P)->cutime + (*P)->cstime + (*P)->utime + (*P)->stime)
< ((*Q)->cutime + (*Q)->cstime + (*Q)->utime + (*Q)->stime) )
return SORT_lt;
if ( ((*P)->cutime + (*P)->cstime + (*P)->utime + (*P)->stime)
> ((*Q)->cutime + (*Q)->cstime + (*Q)->utime + (*Q)->stime) )
return SORT_gt;
} else {
if ( ((*P)->utime + (*P)->stime) < ((*Q)->utime + (*Q)->stime))
return SORT_lt;
if ( ((*P)->utime + (*P)->stime) > ((*Q)->utime + (*Q)->stime))
return SORT_gt;
}
return SORT_eq;
}
SCB_NUM1(P_VRT, size)
SCB_NUM2(P_SWP, size, resident)
SCB_NUM1(P_RES, resident) // also serves P_MEM !
SCB_NUM1(P_COD, trs)
SCB_NUM1(P_DAT, drs)
SCB_NUM1(P_SHR, share)
SCB_NUM1(P_FLT, maj_flt)
SCB_NUM1(P_DRT, dt)
SCB_NUMx(P_STA, state)
static int sort_P_CMD (const proc_t **P, const proc_t **Q)
{
/* if a process doesn't have a cmdline, we'll consider it a kernel thread
-- since displayed tasks are given special treatment, we must too */
if (Frame_cmdlin && ((*P)->cmdline || (*Q)->cmdline)) {
if (!(*Q)->cmdline) return Frame_srtflg * -1;
if (!(*P)->cmdline) return Frame_srtflg;
return Frame_srtflg *
strncmp((*Q)->cmdline[0], (*P)->cmdline[0], (unsigned)Curwin->maxcmdln);
}
// this part also handles the compare if both are kernel threads
return Frame_srtflg * strcmp((*Q)->cmd, (*P)->cmd);
}
SCB_NUM1(P_WCH, wchan)
SCB_NUM1(P_FLG, flags)
/* ///////////////////////////////// special sort for prochlp() ! */
static int sort_HST_t (const HST_t *P, const HST_t *Q)
{
return P->pid - Q->pid;
}
/*###### Tiny useful routine(s) ########################################*/
/*
* This routine isolates ALL user INPUT and ensures that we
* wont be mixing I/O from stdio and low-level read() requests */
static int chin (int ech, char *buf, unsigned cnt)
{
int rc;
fflush(stdout);
if (!ech)
rc = read(STDIN_FILENO, buf, cnt);
else {
tcsetattr(STDIN_FILENO, TCSAFLUSH, &Savedtty);
rc = read(STDIN_FILENO, buf, cnt);
tcsetattr(STDIN_FILENO, TCSAFLUSH, &Rawtty);
}
// may be the beginning of a lengthy escape sequence
tcflush(STDIN_FILENO, TCIFLUSH);
return rc; // note: we do NOT produce a vaid 'string'
}
// This routine simply formats whatever the caller wants and
// returns a pointer to the resulting 'const char' string...
static const char *fmtmk (const char *fmts, ...) __attribute__((format(printf,1,2)));
static const char *fmtmk (const char *fmts, ...)
{
static char buf[BIGBUFSIZ]; // with help stuff, our buffer
va_list va; // requirements exceed 1k
va_start(va, fmts);
vsnprintf(buf, sizeof(buf), fmts, va);
va_end(va);
return (const char *)buf;
}
// This guy is just our way of avoiding the overhead of the standard
// strcat function (should the caller choose to participate)
static inline char *scat (char *restrict dst, const char *restrict src)
{
while (*dst) dst++;
while ((*(dst++) = *(src++)));
return --dst;
}
// Trim the rc file lines and any 'open_psdb_message' result which arrives
// with an inappropriate newline (thanks to 'sysmap_mmap')
static char *strim_0 (char *str)
{
static const char ws[] = "\b\e\f\n\r\t\v\x9b"; // 0x9b is an escape
char *p;
if ((p = strpbrk(str, ws))) *p = 0;
return str;
}
// This guy just facilitates Batch and protects against dumb ttys
// -- we'd 'inline' him but he's only called twice per frame,
// yet used in many other locations.
static const char *tg2 (int x, int y)
{
return Cap_can_goto ? tgoto(cursor_address, x, y) : "";
}
/*###### Exit/Interrput routines #######################################*/
// The usual program end -- called only by functions in this section.
static void bye_bye (FILE *fp, int eno, const char *str) NORETURN;
static void bye_bye (FILE *fp, int eno, const char *str)
{
if (!Batch)
tcsetattr(STDIN_FILENO, TCSAFLUSH, &Savedtty);
putp(tg2(0, Screen_rows));
putp(Cap_curs_norm);
putp(Cap_smam);
putp("\n");
fflush(stdout);
//#define ATEOJ_REPORT
#ifdef ATEOJ_REPORT
fprintf(fp,
"\n\tTerminal: %s"
"\n\t device = %s, ncurses = v%s"
"\n\t max_colors = %d, max_pairs = %d"
"\n\t Cap_can_goto = %s"
"\n\t Screen_cols = %d, Screen_rows = %d"
"\n\t Max_lines = %d, most recent Pseudo_size = %d"
"\n"
#ifdef PRETENDNOCAP
, "dumb"
#else
, termname()
#endif
, ttyname(STDOUT_FILENO), NCURSES_VERSION
, max_colors, max_pairs
, Cap_can_goto ? "yes" : "No!"
, Screen_cols, Screen_rows
, Max_lines, Pseudo_size
);
fprintf(fp,
#ifndef STDOUT_IOLBF
"\n\t Stdout_buf = %d, BUFSIZ = %u"
#endif
"\n\tWindows and Curwin->"
"\n\t sizeof(WIN_t) = %u, GROUPSMAX = %d"
"\n\t rc.winname = %s, grpname = %s"
"\n\t rc.winflags = %08x, maxpflgs = %d"
"\n\t rc.fieldscur = %s"
"\n\t winlines = %d, rc.maxtasks = %d, maxcmdln = %d"
"\n\t rc.sortindx = %d"
"\n"
#ifndef STDOUT_IOLBF
, sizeof(Stdout_buf), (unsigned)BUFSIZ
#endif
, sizeof(WIN_t), GROUPSMAX
, Curwin->rc.winname, Curwin->grpname
, Curwin->rc.winflags, Curwin->maxpflgs
, Curwin->rc.fieldscur
, Curwin->winlines, Curwin->rc.maxtasks, Curwin->maxcmdln
, Curwin->rc.sortindx
);
fprintf(fp,
"\n\tProgram"
"\n\t Linux version = %u.%u.%u, %s"
"\n\t Hertz = %u (%u bytes, %u-bit time)"
"\n\t Page_size = %d, Cpu_tot = %d, sizeof(proc_t) = %u"
"\n\t sizeof(CPU_t) = %u, sizeof(HST_t) = %u (%u HST_t's/Page)"
"\n"
, LINUX_VERSION_MAJOR(linux_version_code)
, LINUX_VERSION_MINOR(linux_version_code)
, LINUX_VERSION_PATCH(linux_version_code)
, procps_version
, (unsigned)Hertz, sizeof(Hertz), sizeof(Hertz) * 8
, Page_size, Cpu_tot, sizeof(proc_t)
, sizeof(CPU_t), sizeof(HST_t), Page_size / sizeof(HST_t)
);
#endif
if (str) fputs(str, fp);
exit(eno);
}
/*
* Normal end of execution.
* catches:
* SIGALRM, SIGHUP, SIGINT, SIGPIPE, SIGQUIT and SIGTERM */
// FIXME: can't do this shit in a signal handler
static void end_pgm (int sig) NORETURN;
static void end_pgm (int sig)
{
if(sig)
sig |= 0x80; // for a proper process exit code
bye_bye(stdout, sig, NULL);
}
/*
* Standard error handler to normalize the look of all err o/p */
static void std_err (const char *str) NORETURN;
static void std_err (const char *str)
{
static char buf[SMLBUFSIZ];
fflush(stdout);
/* we'll use our own buffer so callers can still use fmtmk() and, yes the
leading tab is not the standard convention, but the standard is wrong
-- OUR msg won't get lost in screen clutter, like so many others! */
snprintf(buf, sizeof(buf), "\t%s: %s\n", Myname, str);
if (!Ttychanged) {
fprintf(stderr, "%s\n", buf);
exit(1);
}
/* not to worry, he'll change our exit code to 1 due to 'buf' */
bye_bye(stderr, 1, buf);
}
/*
* Standard out handler */
static void std_out (const char *str) NORETURN;
static void std_out (const char *str)
{
static char buf[SMLBUFSIZ];
fflush(stdout);
/* we'll use our own buffer so callers can still use fmtmk() and, yes the
leading tab is not the standard convention, but the standard is wrong
-- OUR msg won't get lost in screen clutter, like so many others! */
snprintf(buf, sizeof(buf), "\t%s: %s\n", Myname, str);
if (!Ttychanged) {
fprintf(stdout, "%s\n", buf);
exit(0);
}
bye_bye(stdout, 0, buf);
}
/*
* Suspend ourself.
* catches:
* SIGTSTP, SIGTTIN and SIGTTOU */
// FIXME: can't do this shit in a signal handler!
static void suspend (int dont_care_sig)
{
(void)dont_care_sig;
/* reset terminal */
tcsetattr(STDIN_FILENO, TCSAFLUSH, &Savedtty);
putp(tg2(0, Screen_rows));
putp(Cap_curs_norm);
putp(Cap_smam);
putp("\n");
fflush(stdout);
raise(SIGSTOP);
/* later, after SIGCONT... */
ZAP_TIMEOUT
if (!Batch)
tcsetattr(STDIN_FILENO, TCSAFLUSH, &Rawtty);
putp(Cap_clr_scr);
putp(Cap_rmam);
}
/*###### Misc Color/Display support ####################################*/
/* macro to test if a basic (non-color) capability is valid
thanks: Floyd Davidson <[email protected]> */
#define tIF(s) s ? s : ""
#define CAPCOPY(dst,src) src && strcpy(dst,src)
/*
* Make the appropriate caps/color strings and set some
* lengths which are used to distinguish twix the displayed
* columns and an actual printed row!
* note: we avoid the use of background color so as to maximize
* compatibility with the user's xterm settings */
static void capsmk (WIN_t *q)
{
static int capsdone = 0;
// we must NOT disturb our 'empty' terminfo strings!
if (Batch) return;
// these are the unchangeable puppies, so we only do 'em once
if (!capsdone) {
CAPCOPY(Cap_clr_eol, clr_eol);
CAPCOPY(Cap_clr_eos, clr_eos);
CAPCOPY(Cap_clr_scr, clear_screen);
if (!eat_newline_glitch) { // we like the eat_newline_glitch
CAPCOPY(Cap_rmam, exit_am_mode);
CAPCOPY(Cap_smam, enter_am_mode);
if (!*Cap_rmam || !*Cap_smam) { // need both
*Cap_rmam = '\0';
*Cap_smam = '\0';
if (auto_right_margin) {
avoid_last_column = 1;
}
}
}
CAPCOPY(Cap_curs_huge, cursor_visible);
CAPCOPY(Cap_curs_norm, cursor_normal);
CAPCOPY(Cap_home, cursor_home);
CAPCOPY(Cap_norm, exit_attribute_mode);
CAPCOPY(Cap_reverse, enter_reverse_mode);
snprintf(Caps_off, sizeof(Caps_off), "%s%s", Cap_norm, tIF(orig_pair));
if (tgoto(cursor_address, 1, 1)) Cap_can_goto = 1;
capsdone = 1;
}
/* the key to NO run-time costs for configurable colors -- we spend a
little time with the user now setting up our terminfo strings, and
the job's done until he/she/it has a change-of-heart */
strcpy(q->cap_bold, CHKw(q, View_NOBOLD) ? Cap_norm : tIF(enter_bold_mode));
if (CHKw(q, Show_COLORS) && max_colors > 0) {
strcpy(q->capclr_sum, tparm(set_a_foreground, q->rc.summclr));
snprintf(q->capclr_msg, sizeof(q->capclr_msg), "%s%s"
, tparm(set_a_foreground, q->rc.msgsclr), Cap_reverse);
snprintf(q->capclr_pmt, sizeof(q->capclr_pmt), "%s%s"
, tparm(set_a_foreground, q->rc.msgsclr), q->cap_bold);
snprintf(q->capclr_hdr, sizeof(q->capclr_hdr), "%s%s"
, tparm(set_a_foreground, q->rc.headclr), Cap_reverse);
snprintf(q->capclr_rownorm, sizeof(q->capclr_rownorm), "%s%s"
, Caps_off, tparm(set_a_foreground, q->rc.taskclr));
} else {
q->capclr_sum[0] = '\0';
strcpy(q->capclr_msg, Cap_reverse);
strcpy(q->capclr_pmt, q->cap_bold);
strcpy(q->capclr_hdr, Cap_reverse);
strcpy(q->capclr_rownorm, Cap_norm);
}
// composite(s), so we do 'em outside and after the if
snprintf(q->capclr_rowhigh, sizeof(q->capclr_rowhigh), "%s%s"
, q->capclr_rownorm, CHKw(q, Show_HIBOLD) ? q->cap_bold : Cap_reverse);
q->len_rownorm = strlen(q->capclr_rownorm);
q->len_rowhigh = strlen(q->capclr_rowhigh);
#undef tIF
}
// Show an error, but not right now.
// Due to the postponed opening of ksym, using open_psdb_message,
// if P_WCH had been selected and the program is restarted, the
// message would otherwise be displayed prematurely.
static void msg_save (const char *fmts, ...) __attribute__((format(printf,1,2)));
static void msg_save (const char *fmts, ...)
{
char tmp[SMLBUFSIZ];
va_list va;
va_start(va, fmts);
vsnprintf(tmp, sizeof(tmp), fmts, va);
va_end(va);
/* we'll add some extra attention grabbers to whatever this is */
snprintf(Msg_delayed, sizeof(Msg_delayed), "\a*** %s ***", strim_0(tmp));
Msg_awaiting = 1;
}
/*
* Show an error message (caller may include a '\a' for sound) */
static void show_msg (const char *str)
{
PUTT("%s%s %s %s%s",
tg2(0, Msg_row),
Curwin->capclr_msg,
str,
Caps_off,
Cap_clr_eol
);
fflush(stdout);
sleep(MSG_SLEEP);
Msg_awaiting = 0;
}
/*
* Show an input prompt + larger cursor */
static void show_pmt (const char *str)
{
PUTT("%s%s%s: %s%s",
tg2(0, Msg_row),
Curwin->capclr_pmt,
str,
Cap_curs_huge,
Caps_off
);
fflush(stdout);
}
/*
* Show lines with specially formatted elements, but only output
* what will fit within the current screen width.
* Our special formatting consists of:
* "some text <_delimiter_> some more text <_delimiter_>...\n"
* Where <_delimiter_> is a single byte in the range of:
* \01 through \10 (in decimalizee, 1 - 8)
* and is used to select an 'attribute' from a capabilities table
* which is then applied to the *preceding* substring.
* Once recognized, the delimiter is replaced with a null character
* and viola, we've got a substring ready to output! Strings or
* substrings without delimiters will receive the Cap_norm attribute.
*
* Caution:
* This routine treats all non-delimiter bytes as displayable
* data subject to our screen width marching orders. If callers
* embed non-display data like tabs or terminfo strings in our
* glob, a line will truncate incorrectly at best. Worse case
* would be truncation of an embedded tty escape sequence.
*
* Tabs must always be avoided or our efforts are wasted and
* lines will wrap. To lessen but not eliminate the risk of
* terminfo string truncation, such non-display stuff should
* be placed at the beginning of a "short" line.
* (and as for tabs, gimme 1 more color then no worries, mate) */
static void show_special (int interact, const char *glob)
{ /* note: the following is for documentation only,
the real captab is now found in a group's WIN_t !
+------------------------------------------------------+
| char *captab[] = { : Cap's/Delim's |
| Cap_norm, Cap_norm, Cap_bold, = \00, \01, \02 |
| Sum_color, = \03 |
| Msg_color, Pmt_color, = \04, \05 |
| Hdr_color, = \06 |
| Row_color_high, = \07 |
| Row_color_norm }; = \10 [octal!] |
+------------------------------------------------------+ */
char lin[BIGBUFSIZ], row[ROWBUFSIZ], tmp[ROWBUFSIZ];
char *rp, *cap, *lin_end, *sub_beg, *sub_end;
int room;
/* handle multiple lines passed in a bunch */
while ((lin_end = strchr(glob, '\n'))) {
/* create a local copy we can extend and otherwise abuse */
size_t amt = lin_end - glob;
if(amt > sizeof lin - 1)
amt = sizeof lin - 1; // shit happens
memcpy(lin, glob, amt);
/* zero terminate this part and prepare to parse substrings */
lin[amt] = '\0';
room = Screen_cols;
sub_beg = sub_end = lin;
*(rp = row) = '\0';
while (*sub_beg) {
switch (*sub_end) {
case 0: /* no end delim, captab makes normal */
*(sub_end + 1) = '\0'; /* extend str end, then fall through */
case 1 ... 8:
cap = Curwin->captab[(int)*sub_end];
*sub_end = '\0';
snprintf(tmp, sizeof(tmp), "%s%.*s%s", cap, room, sub_beg, Caps_off);
amt = strlen(tmp);
if(rp - row + amt + 1 > sizeof row)
goto overflow; // shit happens
rp = scat(rp, tmp);
room -= (sub_end - sub_beg);
sub_beg = ++sub_end;
break;
default: /* nothin' special, just text */
++sub_end;
}
if (unlikely(0 >= room)) break; /* skip substrings that won't fit */
}
overflow:
if (interact) PUTT("%s%s\n", row, Cap_clr_eol);
else PUFF("%s%s\n", row, Cap_clr_eol);
glob = ++lin_end; /* point to next line (maybe) */
} /* end: while 'lines' */
/* If there's anything left in the glob (by virtue of no trailing '\n'),
it probably means caller wants to retain cursor position on this final
line. That, in turn, means we're interactive and so we'll just do our
'fit-to-screen' thingy... */
if (*glob) PUTT("%.*s", Screen_cols, glob);
}
/*###### Small Utility routines ########################################*/
// Get a string from the user
static char *ask4str (const char *prompt)
{
static char buf[GETBUFSIZ];
show_pmt(prompt);
memset(buf, '\0', sizeof(buf));
chin(1, buf, sizeof(buf) - 1);
putp(Cap_curs_norm);
return strim_0(buf);
}
// Get a float from the user
static float get_float (const char *prompt)
{
char *line;
float f;
if (!(*(line = ask4str(prompt)))) return -1;
// note: we're not allowing negative floats
if (strcspn(line, ",.1234567890")) {
show_msg("\aNot valid");
return -1;
}
sscanf(line, "%f", &f);
return f;
}
// Get an integer from the user
static int get_int (const char *prompt)
{
char *line;
int n;
if (!(*(line = ask4str(prompt)))) return -1;
// note: we've got to allow negative ints (renice)
if (strcspn(line, "-1234567890")) {
show_msg("\aNot valid");
return -1;
}
sscanf(line, "%d", &n);
return n;
}
/*
* Do some scaling stuff.
* We'll interpret 'num' as one of the following types and
* try to format it to fit 'width'.
* SK_no (0) it's a byte count
* SK_Kb (1) it's kilobytes
* SK_Mb (2) it's megabytes
* SK_Gb (3) it's gigabytes
* SK_Tb (4) it's terabytes */
static const char *scale_num (unsigned long num, const int width, const unsigned type)
{
/* kilobytes, megabytes, gigabytes, terabytes, duh! */
static double scale[] = { 1024.0, 1024.0*1024, 1024.0*1024*1024, 1024.0*1024*1024*1024, 0 };
/* kilo, mega, giga, tera, none */
#ifdef CASEUP_SCALE
static char nextup[] = { 'K', 'M', 'G', 'T', 0 };
#else
static char nextup[] = { 'k', 'm', 'g', 't', 0 };
#endif
static char buf[TNYBUFSIZ];
double *dp;
char *up;
/* try an unscaled version first... */
if (width >= snprintf(buf, sizeof(buf), "%lu", num)) return buf;
/* now try successively higher types until it fits */
for (up = nextup + type, dp = scale; *dp; ++dp, ++up) {
/* the most accurate version */
if (width >= snprintf(buf, sizeof(buf), "%.1f%c", num / *dp, *up))
return buf;
/* the integer version */
if (width >= snprintf(buf, sizeof(buf), "%ld%c", (unsigned long)(num / *dp), *up))
return buf;
}
/* well shoot, this outta' fit... */
return "?";
}
/*
* Do some scaling stuff.
* format 'tics' to fit 'width'. */
static const char *scale_tics (TIC_t tics, const int width)
{
#ifdef CASEUP_SCALE
#define HH "%uH"
#define DD "%uD"
#define WW "%uW"
#else
#define HH "%uh"
#define DD "%ud"
#define WW "%uw"
#endif
static char buf[TNYBUFSIZ];
unsigned long nt; // narrow time, for speed on 32-bit
unsigned cc; // centiseconds
unsigned nn; // multi-purpose whatever
nt = (tics * 100ull) / Hertz;
cc = nt % 100; // centiseconds past second
nt /= 100; // total seconds
nn = nt % 60; // seconds past the minute
nt /= 60; // total minutes
if (width >= snprintf(buf, sizeof(buf), "%lu:%02u.%02u", nt, nn, cc))
return buf;
if (width >= snprintf(buf, sizeof buf, "%lu:%02u", nt, nn))
return buf;
nn = nt % 60; // minutes past the hour
nt /= 60; // total hours
if (width >= snprintf(buf, sizeof buf, "%lu,%02u", nt, nn))
return buf;
nn = nt; // now also hours
if (width >= snprintf(buf, sizeof buf, HH, nn))
return buf;
nn /= 24; // now days
if (width >= snprintf(buf, sizeof buf, DD, nn))
return buf;
nn /= 7; // now weeks
if (width >= snprintf(buf, sizeof buf, WW, nn))
return buf;
// well shoot, this outta' fit...
return "?";
#undef HH
#undef DD
#undef WW
}
#include <pwd.h>
static int selection_type;
static uid_t selection_uid;
// FIXME: this is "temporary" code we hope
static int good_uid(const proc_t *restrict const pp){
switch(selection_type){
case 'p':
return 1;
case 0:
return 1;
case 'U':
if (pp->ruid == selection_uid) return 1;
if (pp->suid == selection_uid) return 1;
if (pp->fuid == selection_uid) return 1;
// FALLTHROUGH
case 'u':
if (pp->euid == selection_uid) return 1;
// FALLTHROUGH
default:
; // don't know what it is; find bugs fast
}
return 0;
}
// swiped from ps, and ought to be in libproc
static const char *parse_uid(const char *restrict const str, uid_t *restrict const ret){
struct passwd *passwd_data;
char *endp;
unsigned long num;
static const char uidrange[] = "User ID out of range.";
static const char uidexist[] = "User name does not exist.";
num = strtoul(str, &endp, 0);
if(*endp != '\0'){ /* hmmm, try as login name */
passwd_data = getpwnam(str);
if(!passwd_data) return uidexist;
num = passwd_data->pw_uid;
}
if(num > 0xfffffffeUL) return uidrange;
*ret = num;
return 0;
}
/*###### Library Alternatives ##########################################*/
/*
* Handle our own memory stuff without the risk of leaving the
* user's terminal in an ugly state should things go sour. */
static void *alloc_c (unsigned numb) MALLOC;
static void *alloc_c (unsigned numb)
{
void * p;
if (!numb) ++numb;
if (!(p = calloc(1, numb)))
std_err("failed memory allocate");
return p;
}
static void *alloc_r (void *q, unsigned numb) MALLOC;
static void *alloc_r (void *q, unsigned numb)
{
void *p;
if (!numb) ++numb;
if (!(p = realloc(q, numb)))
std_err("failed memory allocate");
return p;
}
/*
* This guy's modeled on libproc's 'five_cpu_numbers' function except
* we preserve all cpu data in our CPU_t array which is organized
* as follows:
* cpus[0] thru cpus[n] == tics for each separate cpu
* cpus[Cpu_tot] == tics from the 1st /proc/stat line */
static CPU_t *cpus_refresh (CPU_t *cpus)
{
static FILE *fp = NULL;
int i;
int num;
// enough for a /proc/stat CPU line (not the intr line)
char buf[SMLBUFSIZ];
/* by opening this file once, we'll avoid the hit on minor page faults
(sorry Linux, but you'll have to close it for us) */
if (!fp) {
if (!(fp = fopen("/proc/stat", "r")))
std_err(fmtmk("Failed /proc/stat open: %s", strerror(errno)));
/* note: we allocate one more CPU_t than Cpu_tot so that the last slot
can hold tics representing the /proc/stat cpu summary (the first
line read) -- that slot supports our View_CPUSUM toggle */
cpus = alloc_c((1 + Cpu_tot) * sizeof(CPU_t));
}
rewind(fp);
fflush(fp);
// first value the last slot with the cpu summary line
if (!fgets(buf, sizeof(buf), fp)) std_err("failed /proc/stat read");
cpus[Cpu_tot].x = 0; // FIXME: can't tell by kernel version number
cpus[Cpu_tot].y = 0; // FIXME: can't tell by kernel version number
cpus[Cpu_tot].z = 0; // FIXME: can't tell by kernel version number
num = sscanf(buf, "cpu %Lu %Lu %Lu %Lu %Lu %Lu %Lu %Lu",
&cpus[Cpu_tot].u,
&cpus[Cpu_tot].n,
&cpus[Cpu_tot].s,
&cpus[Cpu_tot].i,
&cpus[Cpu_tot].w,
&cpus[Cpu_tot].x,
&cpus[Cpu_tot].y,
&cpus[Cpu_tot].z
);
if (num < 4)
std_err("failed /proc/stat read");
// and just in case we're 2.2.xx compiled without SMP support...
if (Cpu_tot == 1) {
cpus[1].id = 0;
memcpy(cpus, &cpus[1], sizeof(CPU_t));
}
// now value each separate cpu's tics
for (i = 0; 1 < Cpu_tot && i < Cpu_tot; i++) {
if (!fgets(buf, sizeof(buf), fp)) std_err("failed /proc/stat read");
cpus[i].x = 0; // FIXME: can't tell by kernel version number
cpus[i].y = 0; // FIXME: can't tell by kernel version number
cpus[i].z = 0; // FIXME: can't tell by kernel version number
num = sscanf(buf, "cpu%u %Lu %Lu %Lu %Lu %Lu %Lu %Lu %Lu",
&cpus[i].id,
&cpus[i].u, &cpus[i].n, &cpus[i].s, &cpus[i].i, &cpus[i].w, &cpus[i].x, &cpus[i].y, &cpus[i].z
);
if (num < 4)
std_err("failed /proc/stat read");
}
return cpus;
}
/*
* Refresh procs *Helper* function to eliminate yet one more need
* to loop through our darn proc_t table. He's responsible for:
* 1) calculating the elapsed time since the previous frame
* 2) counting the number of tasks in each state (run, sleep, etc)
* 3) maintaining the HST_t's and priming the proc_t pcpu field
* 4) establishing the total number tasks for this frame */
static void prochlp (proc_t *this)
{
static HST_t *hist_sav = NULL;
static HST_t *hist_new = NULL;
static unsigned hist_siz = 0; // number of structs
static unsigned maxt_sav; // prior frame's max tasks
TIC_t tics;
if (unlikely(!this)) {
static struct timeval oldtimev;
struct timeval timev;