xref: /freebsd/usr.bin/top/utils.c (revision ecbde90073aef9166e77cecf61bd80c15a707a53)
1 /*
2  *  This program may be freely redistributed,
3  *  but this entire comment MUST remain intact.
4  *
5  *  Copyright (c) 1984, 1989, William LeFebvre, Rice University
6  *  Copyright (c) 1989, 1990, 1992, William LeFebvre, Northwestern University
7  *
8  * $FreeBSD$
9  */
10 
11 /*
12  *  This file contains various handy utilities used by top.
13  */
14 
15 #include "top.h"
16 #include "utils.h"
17 
18 #include <sys/param.h>
19 #include <sys/sysctl.h>
20 #include <sys/user.h>
21 
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
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(atoi(str));
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 *
70 itoa(unsigned int val)
71 {
72     char *ptr;
73     static char buffer[16];	/* result is built here */
74     				/* 16 is sufficient since the largest number
75 				   we will ever convert will be 2^32-1,
76 				   which is 10 digits. */
77 
78     ptr = buffer + sizeof(buffer);
79     *--ptr = '\0';
80     if (val == 0)
81     {
82 	*--ptr = '0';
83     }
84     else while (val != 0)
85     {
86 	*--ptr = (val % 10) + '0';
87 	val /= 10;
88     }
89     return(ptr);
90 }
91 
92 /*
93  *  itoa7(val) - like itoa, except the number is right justified in a 7
94  *	character field.  This code is a duplication of itoa instead of
95  *	a front end to a more general routine for efficiency.
96  */
97 
98 char *
99 itoa7(int val)
100 {
101     char *ptr;
102     static char buffer[16];	/* result is built here */
103     				/* 16 is sufficient since the largest number
104 				   we will ever convert will be 2^32-1,
105 				   which is 10 digits. */
106 
107     ptr = buffer + sizeof(buffer);
108     *--ptr = '\0';
109     if (val == 0)
110     {
111 	*--ptr = '0';
112     }
113     else while (val != 0)
114     {
115 	*--ptr = (val % 10) + '0';
116 	val /= 10;
117     }
118     while (ptr > buffer + sizeof(buffer) - 7)
119     {
120 	*--ptr = ' ';
121     }
122     return(ptr);
123 }
124 
125 /*
126  *  digits(val) - return number of decimal digits in val.  Only works for
127  *	non-negative numbers.  If val <= 0 then digits(val) == 0.
128  */
129 
130 int __pure2
131 digits(int val)
132 {
133     int cnt = 0;
134 	if (val == 0) {
135 		return 1;
136 	}
137 
138     while (val > 0) {
139 		cnt++;
140 		val /= 10;
141     }
142     return(cnt);
143 }
144 
145 /*
146  * string_index(string, array) - find string in array and return index
147  */
148 
149 int
150 string_index(const char *string, const char * const *array)
151 {
152     size_t i = 0;
153 
154     while (*array != NULL)
155     {
156 	if (strcmp(string, *array) == 0)
157 	{
158 	    return(i);
159 	}
160 	array++;
161 	i++;
162     }
163     return(-1);
164 }
165 
166 /*
167  * argparse(line, cntp) - parse arguments in string "line", separating them
168  *	out into an argv-like array, and setting *cntp to the number of
169  *	arguments encountered.  This is a simple parser that doesn't understand
170  *	squat about quotes.
171  */
172 
173 const char * const *
174 argparse(char *line, int *cntp)
175 {
176     const char **ap;
177     static const char *argv[1024] = {0};
178 
179     *cntp = 1;
180     ap = &argv[1];
181     while ((*ap = strsep(&line, " ")) != NULL) {
182         if (**ap != '\0') {
183             (*cntp)++;
184             if (*cntp >= (int)nitems(argv)) {
185                 break;
186             }
187 	    ap++;
188         }
189     }
190     return (argv);
191 }
192 
193 /*
194  *  percentages(cnt, out, new, old, diffs) - calculate percentage change
195  *	between array "old" and "new", putting the percentages i "out".
196  *	"cnt" is size of each array and "diffs" is used for scratch space.
197  *	The array "old" is updated on each call.
198  *	The routine assumes modulo arithmetic.  This function is especially
199  *	useful on for calculating cpu state percentages.
200  */
201 
202 long
203 percentages(int cnt, int *out, long *new, long *old, long *diffs)
204 {
205     int i;
206     long change;
207     long total_change;
208     long *dp;
209     long half_total;
210 
211     /* initialization */
212     total_change = 0;
213     dp = diffs;
214 
215     /* calculate changes for each state and the overall change */
216     for (i = 0; i < cnt; i++)
217     {
218 	if ((change = *new - *old) < 0)
219 	{
220 	    /* this only happens when the counter wraps */
221 	    change = (int)
222 		((unsigned long)*new-(unsigned long)*old);
223 	}
224 	total_change += (*dp++ = change);
225 	*old++ = *new++;
226     }
227 
228     /* avoid divide by zero potential */
229     if (total_change == 0)
230     {
231 	total_change = 1;
232     }
233 
234     /* calculate percentages based on overall change, rounding up */
235     half_total = total_change / 2l;
236 
237     /* Do not divide by 0. Causes Floating point exception */
238     if(total_change) {
239         for (i = 0; i < cnt; i++)
240         {
241           *out++ = (int)((*diffs++ * 1000 + half_total) / total_change);
242         }
243     }
244 
245     /* return the total in case the caller wants to use it */
246     return(total_change);
247 }
248 
249 /* format_time(seconds) - format number of seconds into a suitable
250  *		display that will fit within 6 characters.  Note that this
251  *		routine builds its string in a static area.  If it needs
252  *		to be called more than once without overwriting previous data,
253  *		then we will need to adopt a technique similar to the
254  *		one used for format_k.
255  */
256 
257 /* Explanation:
258    We want to keep the output within 6 characters.  For low values we use
259    the format mm:ss.  For values that exceed 999:59, we switch to a format
260    that displays hours and fractions:  hhh.tH.  For values that exceed
261    999.9, we use hhhh.t and drop the "H" designator.  For values that
262    exceed 9999.9, we use "???".
263  */
264 
265 char *
266 format_time(long seconds)
267 {
268     static char result[10];
269 
270     /* sanity protection */
271     if (seconds < 0 || seconds > (99999l * 360l))
272     {
273 	strcpy(result, "   ???");
274     }
275     else if (seconds >= (1000l * 60l))
276     {
277 	/* alternate (slow) method displaying hours and tenths */
278 	sprintf(result, "%5.1fH", (double)seconds / (double)(60l * 60l));
279 
280 	/* It is possible that the sprintf took more than 6 characters.
281 	   If so, then the "H" appears as result[6].  If not, then there
282 	   is a \0 in result[6].  Either way, it is safe to step on.
283 	 */
284 	result[6] = '\0';
285     }
286     else
287     {
288 	/* standard method produces MMM:SS */
289 	/* we avoid printf as must as possible to make this quick */
290 	sprintf(result, "%3ld:%02ld",
291 	    (long)(seconds / 60), (long)(seconds % 60));
292     }
293     return(result);
294 }
295 
296 /*
297  * format_k(amt) - format a kilobyte memory value, returning a string
298  *		suitable for display.  Returns a pointer to a static
299  *		area that changes each call.  "amt" is converted to a
300  *		string with a trailing "K".  If "amt" is 10000 or greater,
301  *		then it is formatted as megabytes (rounded) with a
302  *		trailing "M".
303  */
304 
305 /*
306  * Compromise time.  We need to return a string, but we don't want the
307  * caller to have to worry about freeing a dynamically allocated string.
308  * Unfortunately, we can't just return a pointer to a static area as one
309  * of the common uses of this function is in a large call to sprintf where
310  * it might get invoked several times.  Our compromise is to maintain an
311  * array of strings and cycle thru them with each invocation.  We make the
312  * array large enough to handle the above mentioned case.  The constant
313  * NUM_STRINGS defines the number of strings in this array:  we can tolerate
314  * up to NUM_STRINGS calls before we start overwriting old information.
315  * Keeping NUM_STRINGS a power of two will allow an intelligent optimizer
316  * to convert the modulo operation into something quicker.  What a hack!
317  */
318 
319 #define NUM_STRINGS 8
320 
321 char *
322 format_k(int amt)
323 {
324     static char retarray[NUM_STRINGS][16];
325     static int index = 0;
326     char *p;
327     char *ret;
328     char tag = 'K';
329 
330     p = ret = retarray[index];
331     index = (index + 1) % NUM_STRINGS;
332 
333     if (amt >= 10000)
334     {
335 	amt = (amt + 512) / 1024;
336 	tag = 'M';
337 	if (amt >= 10000)
338 	{
339 	    amt = (amt + 512) / 1024;
340 	    tag = 'G';
341 	}
342     }
343 
344     p = stpcpy(p, itoa(amt));
345     *p++ = tag;
346     *p = '\0';
347 
348     return(ret);
349 }
350 
351 char *
352 format_k2(unsigned long long amt)
353 {
354     static char retarray[NUM_STRINGS][16];
355     static int index = 0;
356     char *p;
357     char *ret;
358     char tag = 'K';
359 
360     p = ret = retarray[index];
361     index = (index + 1) % NUM_STRINGS;
362 
363     if (amt >= 100000)
364     {
365 	amt = (amt + 512) / 1024;
366 	tag = 'M';
367 	if (amt >= 100000)
368 	{
369 	    amt = (amt + 512) / 1024;
370 	    tag = 'G';
371 	}
372     }
373 
374     p = stpcpy(p, itoa((int)amt));
375     *p++ = tag;
376     *p = '\0';
377 
378     return(ret);
379 }
380 
381 int
382 find_pid(pid_t pid)
383 {
384 	kvm_t *kd = NULL;
385 	struct kinfo_proc *pbase = NULL;
386 	int nproc;
387 	int ret = 0;
388 
389 	kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, NULL);
390 	if (kd == NULL) {
391 		fprintf(stderr, "top: kvm_open() failed.\n");
392 		quit(TOP_EX_SYS_ERROR);
393 	}
394 
395 	pbase = kvm_getprocs(kd, KERN_PROC_PID, pid, &nproc);
396 	if (pbase == NULL) {
397 		goto done;
398 	}
399 
400 	if ((nproc == 1) && (pbase->ki_pid == pid)) {
401 		ret = 1;
402 	}
403 
404 done:
405 	kvm_close(kd);
406 	return ret;
407 }
408