xref: /openbsd-src/usr.bin/top/utils.c (revision 11efff7f3ac2b3cfeff0c0cddc14294d9b3aca4f)
1 /* $OpenBSD: utils.c,v 1.15 2004/11/22 15:26:53 pat Exp $	 */
2 
3 /*
4  *  Top users/processes display for Unix
5  *  Version 3
6  *
7  * Copyright (c) 1984, 1989, William LeFebvre, Rice University
8  * Copyright (c) 1989, 1990, 1992, William LeFebvre, Northwestern University
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22  * IN NO EVENT SHALL THE AUTHOR OR HIS EMPLOYER BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30 
31 /*
32  *  This file contains various handy utilities used by top.
33  */
34 
35 #include <sys/param.h>
36 #include <sys/sysctl.h>
37 #include <stdio.h>
38 #include <string.h>
39 #include <stdlib.h>
40 #include <unistd.h>
41 
42 #include "top.h"
43 #include "machine.h"
44 #include "utils.h"
45 
46 int
47 atoiwi(char *str)
48 {
49 	size_t len;
50 
51 	len = strlen(str);
52 	if (len != 0) {
53 		if (strncmp(str, "infinity", len) == 0 ||
54 		    strncmp(str, "all", len) == 0 ||
55 		    strncmp(str, "maximum", len) == 0) {
56 			return (Infinity);
57 		} else if (str[0] == '-')
58 			return (Invalid);
59 		else
60 			return (atoi(str));
61 	}
62 	return (0);
63 }
64 
65 /*
66  * itoa - convert integer (decimal) to ascii string.
67  */
68 char *
69 itoa(int val)
70 {
71 	static char buffer[16];	/* result is built here */
72 
73 	/*
74 	 * 16 is sufficient since the largest number we will ever convert
75 	 * will be 2^32-1, which is 10 digits.
76 	 */
77 	(void)snprintf(buffer, sizeof(buffer), "%d", val);
78 	return (buffer);
79 }
80 
81 /*
82  * format_uid(uid) - like itoa, except for uid_t and the number is right
83  * justified in a 6 character field to match uname_field in top.c.
84  */
85 char *
86 format_uid(uid_t uid)
87 {
88 	static char buffer[16];	/* result is built here */
89 
90 	/*
91 	 * 16 is sufficient since the largest uid we will ever convert
92 	 * will be 2^32-1, which is 10 digits.
93 	 */
94 	(void)snprintf(buffer, sizeof(buffer), "%6u", uid);
95 	return (buffer);
96 }
97 
98 /*
99  * digits(val) - return number of decimal digits in val.  Only works for
100  * positive numbers.  If val <= 0 then digits(val) == 0.
101  */
102 int
103 digits(int val)
104 {
105 	int cnt = 0;
106 
107 	while (val > 0) {
108 		cnt++;
109 		val /= 10;
110 	}
111 	return (cnt);
112 }
113 
114 /*
115  * string_index(string, array) - find string in array and return index
116  */
117 int
118 string_index(char *string, char **array)
119 {
120 	int i = 0;
121 
122 	while (*array != NULL) {
123 		if (strcmp(string, *array) == 0)
124 			return (i);
125 		array++;
126 		i++;
127 	}
128 	return (-1);
129 }
130 
131 /*
132  * argparse(line, cntp) - parse arguments in string "line", separating them
133  * out into an argv-like array, and setting *cntp to the number of
134  * arguments encountered.  This is a simple parser that doesn't understand
135  * squat about quotes.
136  */
137 char **
138 argparse(char *line, int *cntp)
139 {
140 	char **argv, **argarray, *args, *from, *to;
141 	int cnt, ch, length, lastch;
142 
143 	/*
144 	 * unfortunately, the only real way to do this is to go thru the
145 	 * input string twice.
146 	 */
147 
148 	/* step thru the string counting the white space sections */
149 	from = line;
150 	lastch = cnt = length = 0;
151 	while ((ch = *from++) != '\0') {
152 		length++;
153 		if (ch == ' ' && lastch != ' ')
154 			cnt++;
155 		lastch = ch;
156 	}
157 
158 	/*
159 	 * add three to the count:  one for the initial "dummy" argument, one
160 	 * for the last argument and one for NULL
161 	 */
162 	cnt += 3;
163 
164 	/* allocate a char * array to hold the pointers */
165 	argarray = (char **) malloc(cnt * sizeof(char *));
166 
167 	/* allocate another array to hold the strings themselves */
168 	args = (char *) malloc(length + 2);
169 
170 	/* initialization for main loop */
171 	from = line;
172 	to = args;
173 	argv = argarray;
174 	lastch = '\0';
175 
176 	/* create a dummy argument to keep getopt happy */
177 	*argv++ = to;
178 	*to++ = '\0';
179 	cnt = 2;
180 
181 	/* now build argv while copying characters */
182 	*argv++ = to;
183 	while ((ch = *from++) != '\0') {
184 		if (ch != ' ') {
185 			if (lastch == ' ') {
186 				*to++ = '\0';
187 				*argv++ = to;
188 				cnt++;
189 			}
190 			*to++ = ch;
191 		}
192 		lastch = ch;
193 	}
194 	*to++ = '\0';
195 
196 	/* set cntp and return the allocated array */
197 	*cntp = cnt;
198 	return (argarray);
199 }
200 
201 /*
202  * percentages(cnt, out, new, old, diffs) - calculate percentage change
203  * between array "old" and "new", putting the percentages i "out".
204  * "cnt" is size of each array and "diffs" is used for scratch space.
205  * The array "old" is updated on each call.
206  * The routine assumes modulo arithmetic.  This function is especially
207  * useful on BSD mchines for calculating cpu state percentages.
208  */
209 int
210 percentages(int cnt, int *out, long *new, long *old, long *diffs)
211 {
212 	long change, total_change, *dp, half_total;
213 	int i;
214 
215 	/* initialization */
216 	total_change = 0;
217 	dp = diffs;
218 
219 	/* calculate changes for each state and the overall change */
220 	for (i = 0; i < cnt; i++) {
221 		if ((change = *new - *old) < 0) {
222 			/* this only happens when the counter wraps */
223 			change = ((unsigned int)*new - (unsigned int)*old);
224 		}
225 		total_change += (*dp++ = change);
226 		*old++ = *new++;
227 	}
228 
229 	/* avoid divide by zero potential */
230 	if (total_change == 0)
231 		total_change = 1;
232 
233 	/* calculate percentages based on overall change, rounding up */
234 	half_total = total_change / 2l;
235 	for (i = 0; i < cnt; i++)
236 		*out++ = ((*diffs++ * 1000 + half_total) / total_change);
237 
238 	/* return the total in case the caller wants to use it */
239 	return (total_change);
240 }
241 
242 /*
243  * format_time(seconds) - format number of seconds into a suitable display
244  * that will fit within 6 characters.  Note that this routine builds its
245  * string in a static area.  If it needs to be called more than once without
246  * overwriting previous data, then we will need to adopt a technique similar
247  * to the one used for format_k.
248  */
249 
250 /*
251  * Explanation: We want to keep the output within 6 characters.  For low
252  * values we use the format mm:ss.  For values that exceed 999:59, we switch
253  * to a format that displays hours and fractions:  hhh.tH.  For values that
254  * exceed 999.9, we use hhhh.t and drop the "H" designator.  For values that
255  * exceed 9999.9, we use "???".
256  */
257 
258 char *
259 format_time(time_t seconds)
260 {
261 	static char result[10];
262 
263 	/* sanity protection */
264 	if (seconds < 0 || seconds > (99999l * 360l)) {
265 		strlcpy(result, "   ???", sizeof result);
266 	} else if (seconds >= (1000l * 60l)) {
267 		/* alternate (slow) method displaying hours and tenths */
268 		snprintf(result, sizeof(result), "%5.1fH",
269 		    (double) seconds / (double) (60l * 60l));
270 
271 		/*
272 		 * It is possible that the snprintf took more than 6
273 		 * characters. If so, then the "H" appears as result[6].  If
274 		 * not, then there is a \0 in result[6].  Either way, it is
275 		 * safe to step on.
276 		 */
277 		result[6] = '\0';
278 	} else {
279 		/* standard method produces MMM:SS */
280 		/* we avoid printf as must as possible to make this quick */
281 		snprintf(result, sizeof(result), "%3d:%02d", seconds / 60,
282 		    seconds % 60);
283 	}
284 	return (result);
285 }
286 
287 /*
288  * format_k(amt) - format a kilobyte memory value, returning a string
289  * suitable for display.  Returns a pointer to a static
290  * area that changes each call.  "amt" is converted to a
291  * string with a trailing "K".  If "amt" is 10000 or greater,
292  * then it is formatted as megabytes (rounded) with a
293  * trailing "M".
294  */
295 
296 /*
297  * Compromise time.  We need to return a string, but we don't want the
298  * caller to have to worry about freeing a dynamically allocated string.
299  * Unfortunately, we can't just return a pointer to a static area as one
300  * of the common uses of this function is in a large call to snprintf where
301  * it might get invoked several times.  Our compromise is to maintain an
302  * array of strings and cycle thru them with each invocation.  We make the
303  * array large enough to handle the above mentioned case.  The constant
304  * NUM_STRINGS defines the number of strings in this array:  we can tolerate
305  * up to NUM_STRINGS calls before we start overwriting old information.
306  * Keeping NUM_STRINGS a power of two will allow an intelligent optimizer
307  * to convert the modulo operation into something quicker.  What a hack!
308  */
309 
310 #define NUM_STRINGS 8
311 
312 char *
313 format_k(int amt)
314 {
315 	static char retarray[NUM_STRINGS][16];
316 	static int  idx = 0;
317 	char *ret, tag = 'K';
318 
319 	ret = retarray[idx];
320 	idx = (idx + 1) % NUM_STRINGS;
321 
322 	if (amt >= 10000) {
323 		amt = (amt + 512) / 1024;
324 		tag = 'M';
325 		if (amt >= 10000) {
326 			amt = (amt + 512) / 1024;
327 			tag = 'G';
328 		}
329 	}
330 	snprintf(ret, sizeof(retarray[0]), "%d%c", amt, tag);
331 	return (ret);
332 }
333 
334 int
335 find_pid(pid_t pid)
336 {
337 	struct kinfo_proc2 *pbase, *cur;
338 	int nproc;
339 
340 	if ((pbase = getprocs(KERN_PROC_KTHREAD, 0, &nproc)) == NULL)
341 		quit(23);
342 
343 	for (cur = pbase; cur < &pbase[nproc]; cur++)
344 		if (cur->p_pid == pid)
345 			return 1;
346 	return 0;
347 }
348