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