xref: /freebsd/usr.bin/top/utils.c (revision 5f72125339b1d14d1b04329ac561354f5e8133fe)
1 /*
2  *  This program may be freely redistributed,
3  *  but this entire comment MUST remain intact.
4  *
5  *  Copyright (c) 2018, Eitan Adler
6  *  Copyright (c) 1984, 1989, William LeFebvre, Rice University
7  *  Copyright (c) 1989, 1990, 1992, William LeFebvre, Northwestern University
8  */
9 
10 /*
11  *  This file contains various handy utilities used by top.
12  */
13 
14 #include "top.h"
15 #include "utils.h"
16 
17 #include <sys/param.h>
18 #include <sys/sysctl.h>
19 #include <sys/user.h>
20 
21 #include <libutil.h>
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <fcntl.h>
26 #include <paths.h>
27 #include <kvm.h>
28 
29 int
atoiwi(const char * str)30 atoiwi(const char *str)
31 {
32     size_t len;
33 
34     len = strlen(str);
35     if (len != 0)
36     {
37 	if (strncmp(str, "infinity", len) == 0 ||
38 	    strncmp(str, "all",      len) == 0 ||
39 	    strncmp(str, "maximum",  len) == 0)
40 	{
41 	    return(Infinity);
42 	}
43 	else if (str[0] == '-')
44 	{
45 	    return(Invalid);
46 	}
47 	else
48 	{
49 		return((int)strtol(str, NULL, 10));
50 	}
51     }
52     return(0);
53 }
54 
55 /*
56  *  itoa - convert integer (decimal) to ascii string for positive numbers
57  *  	   only (we don't bother with negative numbers since we know we
58  *	   don't use them).
59  */
60 
61 				/*
62 				 * How do we know that 16 will suffice?
63 				 * Because the biggest number that we will
64 				 * ever convert will be 2^32-1, which is 10
65 				 * digits.
66 				 */
67 _Static_assert(sizeof(int) <= 4, "buffer too small for this sized int");
68 
69 char *
itoa(unsigned int val)70 itoa(unsigned int val)
71 {
72     static char buffer[16];	/* result is built here */
73     				/* 16 is sufficient since the largest number
74 				   we will ever convert will be 2^32-1,
75 				   which is 10 digits. */
76 
77 	sprintf(buffer, "%u", val);
78     return (buffer);
79 }
80 
81 /*
82  *  itoa7(val) - like itoa, except the number is right justified in a 7
83  *	character field.  This code is a duplication of itoa instead of
84  *	a front end to a more general routine for efficiency.
85  */
86 
87 char *
itoa7(int val)88 itoa7(int val)
89 {
90     static char buffer[16];	/* result is built here */
91     				/* 16 is sufficient since the largest number
92 				   we will ever convert will be 2^32-1,
93 				   which is 10 digits. */
94 
95 	sprintf(buffer, "%6u", val);
96     return (buffer);
97 }
98 
99 /*
100  *  digits(val) - return number of decimal digits in val.  Only works for
101  *	non-negative numbers.
102  */
103 
104 int __pure2
digits(int val)105 digits(int val)
106 {
107     int cnt = 0;
108 	if (val == 0) {
109 		return 1;
110 	}
111 
112     while (val > 0) {
113 		cnt++;
114 		val /= 10;
115     }
116     return(cnt);
117 }
118 
119 /*
120  * argparse(line, cntp) - parse arguments in string "line", separating them
121  *	out into an argv-like array, and setting *cntp to the number of
122  *	arguments encountered.  This is a simple parser that doesn't understand
123  *	squat about quotes.
124  */
125 
126 const char **
argparse(char * line,int * cntp)127 argparse(char *line, int *cntp)
128 {
129     const char **ap;
130     static const char *argv[1024] = {0};
131 
132     *cntp = 1;
133     ap = &argv[1];
134     while ((*ap = strsep(&line, " ")) != NULL) {
135         if (**ap != '\0') {
136             (*cntp)++;
137             if (*cntp >= (int)nitems(argv)) {
138                 break;
139             }
140 	    ap++;
141         }
142     }
143     return (argv);
144 }
145 
146 /*
147  *  percentages(cnt, out, new, old, diffs) - calculate percentage change
148  *	between array "old" and "new", putting the percentages i "out".
149  *	"cnt" is size of each array and "diffs" is used for scratch space.
150  *	The array "old" is updated on each call.
151  *	The routine assumes modulo arithmetic.  This function is especially
152  *	useful on for calculating cpu state percentages.
153  */
154 
155 long
percentages(int cnt,int * out,long * new,long * old,long * diffs)156 percentages(int cnt, int *out, long *new, long *old, long *diffs)
157 {
158     int i;
159     long change;
160     long total_change;
161     long *dp;
162     long half_total;
163 
164     /* initialization */
165     total_change = 0;
166     dp = diffs;
167 
168     /* calculate changes for each state and the overall change */
169     for (i = 0; i < cnt; i++)
170     {
171 	if ((change = *new - *old) < 0)
172 	{
173 	    /* this only happens when the counter wraps */
174 	    change = (int)
175 		((unsigned long)*new-(unsigned long)*old);
176 	}
177 	total_change += (*dp++ = change);
178 	*old++ = *new++;
179     }
180 
181     /* avoid divide by zero potential */
182     if (total_change == 0)
183     {
184 	total_change = 1;
185     }
186 
187     /* calculate percentages based on overall change, rounding up */
188     half_total = total_change / 2l;
189 
190 	for (i = 0; i < cnt; i++)
191 	{
192 		*out++ = (int)((*diffs++ * 1000 + half_total) / total_change);
193 	}
194 
195     /* return the total in case the caller wants to use it */
196     return(total_change);
197 }
198 
199 /* format_time(seconds) - format number of seconds into a suitable
200  *		display that will fit within 6 characters.  Note that this
201  *		routine builds its string in a static area.  If it needs
202  *		to be called more than once without overwriting previous data,
203  *		then we will need to adopt a technique similar to the
204  *		one used for format_k.
205  */
206 
207 /* Explanation:
208    We want to keep the output within 6 characters.  For low values we use
209    the format mm:ss.  For values that exceed 999:59, we switch to a format
210    that displays hours and fractions:  hhh.tH.  For values that exceed
211    999.9, we use hhhh.t and drop the "H" designator.  For values that
212    exceed 9999.9, we use "???".
213  */
214 
215 const char *
format_time(long seconds)216 format_time(long seconds)
217 {
218 	static char result[10];
219 
220 	/* sanity protection */
221 	if (seconds < 0 || seconds > (99999l * 360l))
222 	{
223 		strcpy(result, "   ???");
224 	}
225 	else if (seconds >= (1000l * 60l))
226 	{
227 		/* alternate (slow) method displaying hours and tenths */
228 		sprintf(result, "%5.1fH", (double)seconds / (double)(60l * 60l));
229 
230 		/* It is possible that the sprintf took more than 6 characters.
231 		   If so, then the "H" appears as result[6].  If not, then there
232 		   is a \0 in result[6].  Either way, it is safe to step on.
233 		   */
234 		result[6] = '\0';
235 	}
236 	else
237 	{
238 		/* standard method produces MMM:SS */
239 		sprintf(result, "%3ld:%02ld",
240 				seconds / 60l, seconds % 60l);
241 	}
242 	return(result);
243 }
244 
245 /*
246  * format_k(amt) - format a kilobyte memory value, returning a string
247  *		suitable for display.  Returns a pointer to a static
248  *		area that changes each call.  "amt" is converted to a fixed
249  *		size humanize_number call
250  */
251 
252 /*
253  * Compromise time.  We need to return a string, but we don't want the
254  * caller to have to worry about freeing a dynamically allocated string.
255  * Unfortunately, we can't just return a pointer to a static area as one
256  * of the common uses of this function is in a large call to sprintf where
257  * it might get invoked several times.  Our compromise is to maintain an
258  * array of strings and cycle thru them with each invocation.  We make the
259  * array large enough to handle the above mentioned case.  The constant
260  * NUM_STRINGS defines the number of strings in this array:  we can tolerate
261  * up to NUM_STRINGS calls before we start overwriting old information.
262  * Keeping NUM_STRINGS a power of two will allow an intelligent optimizer
263  * to convert the modulo operation into something quicker.  What a hack!
264  */
265 
266 #define NUM_STRINGS 8
267 
268 char *
format_k(int64_t amt)269 format_k(int64_t amt)
270 {
271 	static char retarray[NUM_STRINGS][16];
272 	static int index_ = 0;
273 	char *ret;
274 
275 	ret = retarray[index_];
276 	index_ = (index_ + 1) % NUM_STRINGS;
277 	humanize_number(ret, 6, amt * 1024, "", HN_AUTOSCALE, HN_NOSPACE |
278 	    HN_B);
279 	return (ret);
280 }
281 
282 int
find_pid(pid_t pid)283 find_pid(pid_t pid)
284 {
285 	kvm_t *kd = NULL;
286 	struct kinfo_proc *pbase = NULL;
287 	int nproc;
288 	int ret = 0;
289 
290 	kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, NULL);
291 	if (kd == NULL) {
292 		fprintf(stderr, "top: kvm_open() failed.\n");
293 		quit(TOP_EX_SYS_ERROR);
294 	}
295 
296 	pbase = kvm_getprocs(kd, KERN_PROC_PID, pid, &nproc);
297 	if (pbase == NULL) {
298 		goto done;
299 	}
300 
301 	if ((nproc == 1) && (pbase->ki_pid == pid)) {
302 		ret = 1;
303 	}
304 
305 done:
306 	kvm_close(kd);
307 	return ret;
308 }
309