xref: /freebsd/usr.bin/top/utils.c (revision 4717628ed859513a3262ea68259d0605f39de0b3)
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
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 *
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 *
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
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  * string_index(string, array) - find string in array and return index
121  */
122 
123 int
124 string_index(const char *string, const char * const *array)
125 {
126     size_t i = 0;
127 
128     while (*array != NULL)
129     {
130 	if (strcmp(string, *array) == 0)
131 	{
132 	    return(i);
133 	}
134 	array++;
135 	i++;
136     }
137     return(-1);
138 }
139 
140 /*
141  * argparse(line, cntp) - parse arguments in string "line", separating them
142  *	out into an argv-like array, and setting *cntp to the number of
143  *	arguments encountered.  This is a simple parser that doesn't understand
144  *	squat about quotes.
145  */
146 
147 const char **
148 argparse(char *line, int *cntp)
149 {
150     const char **ap;
151     static const char *argv[1024] = {0};
152 
153     *cntp = 1;
154     ap = &argv[1];
155     while ((*ap = strsep(&line, " ")) != NULL) {
156         if (**ap != '\0') {
157             (*cntp)++;
158             if (*cntp >= (int)nitems(argv)) {
159                 break;
160             }
161 	    ap++;
162         }
163     }
164     return (argv);
165 }
166 
167 /*
168  *  percentages(cnt, out, new, old, diffs) - calculate percentage change
169  *	between array "old" and "new", putting the percentages i "out".
170  *	"cnt" is size of each array and "diffs" is used for scratch space.
171  *	The array "old" is updated on each call.
172  *	The routine assumes modulo arithmetic.  This function is especially
173  *	useful on for calculating cpu state percentages.
174  */
175 
176 long
177 percentages(int cnt, int *out, long *new, long *old, long *diffs)
178 {
179     int i;
180     long change;
181     long total_change;
182     long *dp;
183     long half_total;
184 
185     /* initialization */
186     total_change = 0;
187     dp = diffs;
188 
189     /* calculate changes for each state and the overall change */
190     for (i = 0; i < cnt; i++)
191     {
192 	if ((change = *new - *old) < 0)
193 	{
194 	    /* this only happens when the counter wraps */
195 	    change = (int)
196 		((unsigned long)*new-(unsigned long)*old);
197 	}
198 	total_change += (*dp++ = change);
199 	*old++ = *new++;
200     }
201 
202     /* avoid divide by zero potential */
203     if (total_change == 0)
204     {
205 	total_change = 1;
206     }
207 
208     /* calculate percentages based on overall change, rounding up */
209     half_total = total_change / 2l;
210 
211 	for (i = 0; i < cnt; i++)
212 	{
213 		*out++ = (int)((*diffs++ * 1000 + half_total) / total_change);
214 	}
215 
216     /* return the total in case the caller wants to use it */
217     return(total_change);
218 }
219 
220 /* format_time(seconds) - format number of seconds into a suitable
221  *		display that will fit within 6 characters.  Note that this
222  *		routine builds its string in a static area.  If it needs
223  *		to be called more than once without overwriting previous data,
224  *		then we will need to adopt a technique similar to the
225  *		one used for format_k.
226  */
227 
228 /* Explanation:
229    We want to keep the output within 6 characters.  For low values we use
230    the format mm:ss.  For values that exceed 999:59, we switch to a format
231    that displays hours and fractions:  hhh.tH.  For values that exceed
232    999.9, we use hhhh.t and drop the "H" designator.  For values that
233    exceed 9999.9, we use "???".
234  */
235 
236 const char *
237 format_time(long seconds)
238 {
239 	static char result[10];
240 
241 	/* sanity protection */
242 	if (seconds < 0 || seconds > (99999l * 360l))
243 	{
244 		strcpy(result, "   ???");
245 	}
246 	else if (seconds >= (1000l * 60l))
247 	{
248 		/* alternate (slow) method displaying hours and tenths */
249 		sprintf(result, "%5.1fH", (double)seconds / (double)(60l * 60l));
250 
251 		/* It is possible that the sprintf took more than 6 characters.
252 		   If so, then the "H" appears as result[6].  If not, then there
253 		   is a \0 in result[6].  Either way, it is safe to step on.
254 		   */
255 		result[6] = '\0';
256 	}
257 	else
258 	{
259 		/* standard method produces MMM:SS */
260 		sprintf(result, "%3ld:%02ld",
261 				seconds / 60l, seconds % 60l);
262 	}
263 	return(result);
264 }
265 
266 /*
267  * format_k(amt) - format a kilobyte memory value, returning a string
268  *		suitable for display.  Returns a pointer to a static
269  *		area that changes each call.  "amt" is converted to a fixed
270  *		size humanize_number call
271  */
272 
273 /*
274  * Compromise time.  We need to return a string, but we don't want the
275  * caller to have to worry about freeing a dynamically allocated string.
276  * Unfortunately, we can't just return a pointer to a static area as one
277  * of the common uses of this function is in a large call to sprintf where
278  * it might get invoked several times.  Our compromise is to maintain an
279  * array of strings and cycle thru them with each invocation.  We make the
280  * array large enough to handle the above mentioned case.  The constant
281  * NUM_STRINGS defines the number of strings in this array:  we can tolerate
282  * up to NUM_STRINGS calls before we start overwriting old information.
283  * Keeping NUM_STRINGS a power of two will allow an intelligent optimizer
284  * to convert the modulo operation into something quicker.  What a hack!
285  */
286 
287 #define NUM_STRINGS 8
288 
289 char *
290 format_k(int64_t amt)
291 {
292 	static char retarray[NUM_STRINGS][16];
293 	static int index_ = 0;
294 	char *ret;
295 
296 	ret = retarray[index_];
297 	index_ = (index_ + 1) % NUM_STRINGS;
298 	humanize_number(ret, 6, amt * 1024, "", HN_AUTOSCALE, HN_NOSPACE |
299 	    HN_B);
300 	return (ret);
301 }
302 
303 int
304 find_pid(pid_t pid)
305 {
306 	kvm_t *kd = NULL;
307 	struct kinfo_proc *pbase = NULL;
308 	int nproc;
309 	int ret = 0;
310 
311 	kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, NULL);
312 	if (kd == NULL) {
313 		fprintf(stderr, "top: kvm_open() failed.\n");
314 		quit(TOP_EX_SYS_ERROR);
315 	}
316 
317 	pbase = kvm_getprocs(kd, KERN_PROC_PID, pid, &nproc);
318 	if (pbase == NULL) {
319 		goto done;
320 	}
321 
322 	if ((nproc == 1) && (pbase->ki_pid == pid)) {
323 		ret = 1;
324 	}
325 
326 done:
327 	kvm_close(kd);
328 	return ret;
329 }
330