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