xref: /freebsd/usr.bin/top/utils.c (revision b2ca2e50b9aaccc15efaf970f9139310429abfe5)
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(char *line, int *cntp)
170 {
171     const char **ap;
172     static const char *argv[1024] = {0};
173 
174     *cntp = 1;
175     ap = &argv[1];
176     while ((*ap = strsep(&line, " ")) != NULL) {
177         if (**ap != '\0') {
178             (*cntp)++;
179             if (*cntp >= (int)nitems(argv)) {
180                 break;
181             }
182 	    ap++;
183         }
184     }
185     return argv;
186 }
187 
188 /*
189  *  percentages(cnt, out, new, old, diffs) - calculate percentage change
190  *	between array "old" and "new", putting the percentages i "out".
191  *	"cnt" is size of each array and "diffs" is used for scratch space.
192  *	The array "old" is updated on each call.
193  *	The routine assumes modulo arithmetic.  This function is especially
194  *	useful on for calculating cpu state percentages.
195  */
196 
197 long
198 percentages(int cnt, int *out, long *new, long *old, long *diffs)
199 {
200     int i;
201     long change;
202     long total_change;
203     long *dp;
204     long half_total;
205 
206     /* initialization */
207     total_change = 0;
208     dp = diffs;
209 
210     /* calculate changes for each state and the overall change */
211     for (i = 0; i < cnt; i++)
212     {
213 	if ((change = *new - *old) < 0)
214 	{
215 	    /* this only happens when the counter wraps */
216 	    change = (int)
217 		((unsigned long)*new-(unsigned long)*old);
218 	}
219 	total_change += (*dp++ = change);
220 	*old++ = *new++;
221     }
222 
223     /* avoid divide by zero potential */
224     if (total_change == 0)
225     {
226 	total_change = 1;
227     }
228 
229     /* calculate percentages based on overall change, rounding up */
230     half_total = total_change / 2l;
231 
232     /* Do not divide by 0. Causes Floating point exception */
233     if(total_change) {
234         for (i = 0; i < cnt; i++)
235         {
236           *out++ = (int)((*diffs++ * 1000 + half_total) / total_change);
237         }
238     }
239 
240     /* return the total in case the caller wants to use it */
241     return(total_change);
242 }
243 
244 /* format_time(seconds) - format number of seconds into a suitable
245  *		display that will fit within 6 characters.  Note that this
246  *		routine builds its string in a static area.  If it needs
247  *		to be called more than once without overwriting previous data,
248  *		then we will need to adopt a technique similar to the
249  *		one used for format_k.
250  */
251 
252 /* Explanation:
253    We want to keep the output within 6 characters.  For low values we use
254    the format mm:ss.  For values that exceed 999:59, we switch to a format
255    that displays hours and fractions:  hhh.tH.  For values that exceed
256    999.9, we use hhhh.t and drop the "H" designator.  For values that
257    exceed 9999.9, we use "???".
258  */
259 
260 char *
261 format_time(long seconds)
262 {
263     static char result[10];
264 
265     /* sanity protection */
266     if (seconds < 0 || seconds > (99999l * 360l))
267     {
268 	strcpy(result, "   ???");
269     }
270     else if (seconds >= (1000l * 60l))
271     {
272 	/* alternate (slow) method displaying hours and tenths */
273 	sprintf(result, "%5.1fH", (double)seconds / (double)(60l * 60l));
274 
275 	/* It is possible that the sprintf took more than 6 characters.
276 	   If so, then the "H" appears as result[6].  If not, then there
277 	   is a \0 in result[6].  Either way, it is safe to step on.
278 	 */
279 	result[6] = '\0';
280     }
281     else
282     {
283 	/* standard method produces MMM:SS */
284 	/* we avoid printf as must as possible to make this quick */
285 	sprintf(result, "%3ld:%02ld",
286 	    (long)(seconds / 60), (long)(seconds % 60));
287     }
288     return(result);
289 }
290 
291 /*
292  * format_k(amt) - format a kilobyte memory value, returning a string
293  *		suitable for display.  Returns a pointer to a static
294  *		area that changes each call.  "amt" is converted to a
295  *		string with a trailing "K".  If "amt" is 10000 or greater,
296  *		then it is formatted as megabytes (rounded) with a
297  *		trailing "M".
298  */
299 
300 /*
301  * Compromise time.  We need to return a string, but we don't want the
302  * caller to have to worry about freeing a dynamically allocated string.
303  * Unfortunately, we can't just return a pointer to a static area as one
304  * of the common uses of this function is in a large call to sprintf where
305  * it might get invoked several times.  Our compromise is to maintain an
306  * array of strings and cycle thru them with each invocation.  We make the
307  * array large enough to handle the above mentioned case.  The constant
308  * NUM_STRINGS defines the number of strings in this array:  we can tolerate
309  * up to NUM_STRINGS calls before we start overwriting old information.
310  * Keeping NUM_STRINGS a power of two will allow an intelligent optimizer
311  * to convert the modulo operation into something quicker.  What a hack!
312  */
313 
314 #define NUM_STRINGS 8
315 
316 char *format_k(int amt)
317 {
318     static char retarray[NUM_STRINGS][16];
319     static int index = 0;
320     char *p;
321     char *ret;
322     char tag = 'K';
323 
324     p = ret = retarray[index];
325     index = (index + 1) % NUM_STRINGS;
326 
327     if (amt >= 10000)
328     {
329 	amt = (amt + 512) / 1024;
330 	tag = 'M';
331 	if (amt >= 10000)
332 	{
333 	    amt = (amt + 512) / 1024;
334 	    tag = 'G';
335 	}
336     }
337 
338     p = stpcpy(p, itoa(amt));
339     *p++ = tag;
340     *p = '\0';
341 
342     return(ret);
343 }
344 
345 char *
346 format_k2(unsigned long long amt)
347 {
348     static char retarray[NUM_STRINGS][16];
349     static int index = 0;
350     char *p;
351     char *ret;
352     char tag = 'K';
353 
354     p = ret = retarray[index];
355     index = (index + 1) % NUM_STRINGS;
356 
357     if (amt >= 100000)
358     {
359 	amt = (amt + 512) / 1024;
360 	tag = 'M';
361 	if (amt >= 100000)
362 	{
363 	    amt = (amt + 512) / 1024;
364 	    tag = 'G';
365 	}
366     }
367 
368     p = stpcpy(p, itoa((int)amt));
369     *p++ = tag;
370     *p = '\0';
371 
372     return(ret);
373 }
374 
375 int
376 find_pid(pid_t pid)
377 {
378 	kvm_t *kd = NULL;
379 	struct kinfo_proc *pbase = NULL;
380 	int nproc;
381 	int ret = 0;
382 
383 	kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, NULL);
384 	if (kd == NULL) {
385 		fprintf(stderr, "top: kvm_open() failed.\n");
386 		quit(TOP_EX_SYS_ERROR);
387 	}
388 
389 	pbase = kvm_getprocs(kd, KERN_PROC_PID, pid, &nproc);
390 	if (pbase == NULL) {
391 		goto done;
392 	}
393 
394 	if ((nproc == 1) && (pbase->ki_pid == pid)) {
395 		ret = 1;
396 	}
397 
398 done:
399 	kvm_close(kd);
400 	return ret;
401 }
402