xref: /openbsd-src/usr.bin/top/utils.c (revision 94fd4554194a14f126fba33b837cc68a1df42468)
1 /* $OpenBSD: utils.c,v 1.18 2007/04/04 19:22:46 otto 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 <err.h>
38 #include <stdio.h>
39 #include <string.h>
40 #include <stdlib.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 	const char *errstr;
51 	int i;
52 
53 	len = strlen(str);
54 	if (len != 0) {
55 		if (strncmp(str, "infinity", len) == 0 ||
56 		    strncmp(str, "all", len) == 0 ||
57 		    strncmp(str, "maximum", len) == 0) {
58 			return (Infinity);
59 		}
60 		i = (int)strtonum(str, 0, INT_MAX, &errstr);
61 		if (errstr) {
62 			return (Invalid);
63 		} else
64 			return (i);
65 	}
66 	return (0);
67 }
68 
69 /*
70  * itoa - convert integer (decimal) to ascii string.
71  */
72 char *
73 itoa(int val)
74 {
75 	static char buffer[16];	/* result is built here */
76 
77 	/*
78 	 * 16 is sufficient since the largest number we will ever convert
79 	 * will be 2^32-1, which is 10 digits.
80 	 */
81 	(void)snprintf(buffer, sizeof(buffer), "%d", val);
82 	return (buffer);
83 }
84 
85 /*
86  * format_uid(uid) - like itoa, except for uid_t and the number is right
87  * justified in a 6 character field to match uname_field in top.c.
88  */
89 char *
90 format_uid(uid_t uid)
91 {
92 	static char buffer[16];	/* result is built here */
93 
94 	/*
95 	 * 16 is sufficient since the largest uid we will ever convert
96 	 * will be 2^32-1, which is 10 digits.
97 	 */
98 	(void)snprintf(buffer, sizeof(buffer), "%6u", uid);
99 	return (buffer);
100 }
101 
102 /*
103  * digits(val) - return number of decimal digits in val.  Only works for
104  * positive numbers.  If val <= 0 then digits(val) == 0.
105  */
106 int
107 digits(int val)
108 {
109 	int cnt = 0;
110 
111 	while (val > 0) {
112 		cnt++;
113 		val /= 10;
114 	}
115 	return (cnt);
116 }
117 
118 /*
119  * string_index(string, array) - find string in array and return index
120  */
121 int
122 string_index(char *string, char **array)
123 {
124 	int i = 0;
125 
126 	while (*array != NULL) {
127 		if (strcmp(string, *array) == 0)
128 			return (i);
129 		array++;
130 		i++;
131 	}
132 	return (-1);
133 }
134 
135 /*
136  * argparse(line, cntp) - parse arguments in string "line", separating them
137  * out into an argv-like array, and setting *cntp to the number of
138  * arguments encountered.  This is a simple parser that doesn't understand
139  * squat about quotes.
140  */
141 char **
142 argparse(char *line, int *cntp)
143 {
144 	char **argv, **argarray, *args, *from, *to;
145 	int cnt, ch, length, lastch;
146 
147 	/*
148 	 * unfortunately, the only real way to do this is to go thru the
149 	 * input string twice.
150 	 */
151 
152 	/* step thru the string counting the white space sections */
153 	from = line;
154 	lastch = cnt = length = 0;
155 	while ((ch = *from++) != '\0') {
156 		length++;
157 		if (ch == ' ' && lastch != ' ')
158 			cnt++;
159 		lastch = ch;
160 	}
161 
162 	/*
163 	 * add three to the count:  one for the initial "dummy" argument, one
164 	 * for the last argument and one for NULL
165 	 */
166 	cnt += 3;
167 
168 	/* allocate a char * array to hold the pointers */
169 	if ((argarray = malloc(cnt * sizeof(char *))) == NULL)
170 		err(1, NULL);
171 
172 	/* allocate another array to hold the strings themselves */
173 	if ((args = malloc(length + 2)) == NULL)
174 		err(1, NULL);
175 
176 	/* initialization for main loop */
177 	from = line;
178 	to = args;
179 	argv = argarray;
180 	lastch = '\0';
181 
182 	/* create a dummy argument to keep getopt happy */
183 	*argv++ = to;
184 	*to++ = '\0';
185 	cnt = 2;
186 
187 	/* now build argv while copying characters */
188 	*argv++ = to;
189 	while ((ch = *from++) != '\0') {
190 		if (ch != ' ') {
191 			if (lastch == ' ') {
192 				*to++ = '\0';
193 				*argv++ = to;
194 				cnt++;
195 			}
196 			*to++ = ch;
197 		}
198 		lastch = ch;
199 	}
200 	*to++ = '\0';
201 
202 	/* set cntp and return the allocated array */
203 	*cntp = cnt;
204 	return (argarray);
205 }
206 
207 /*
208  * percentages(cnt, out, new, old, diffs) - calculate percentage change
209  * between array "old" and "new", putting the percentages i "out".
210  * "cnt" is size of each array and "diffs" is used for scratch space.
211  * The array "old" is updated on each call.
212  * The routine assumes modulo arithmetic.  This function is especially
213  * useful on BSD mchines for calculating cpu state percentages.
214  */
215 int
216 percentages(int cnt, int64_t *out, int64_t *new, int64_t *old, int64_t *diffs)
217 {
218 	int64_t change, total_change, *dp, half_total;
219 	int i;
220 
221 	/* initialization */
222 	total_change = 0;
223 	dp = diffs;
224 
225 	/* calculate changes for each state and the overall change */
226 	for (i = 0; i < cnt; i++) {
227 		if ((change = *new - *old) < 0) {
228 			/* this only happens when the counter wraps */
229 			change = (*new - *old);
230 		}
231 		total_change += (*dp++ = change);
232 		*old++ = *new++;
233 	}
234 
235 	/* avoid divide by zero potential */
236 	if (total_change == 0)
237 		total_change = 1;
238 
239 	/* calculate percentages based on overall change, rounding up */
240 	half_total = total_change / 2l;
241 	for (i = 0; i < cnt; i++)
242 		*out++ = ((*diffs++ * 1000 + half_total) / total_change);
243 
244 	/* return the total in case the caller wants to use it */
245 	return (total_change);
246 }
247 
248 /*
249  * format_time(seconds) - format number of seconds into a suitable display
250  * that will fit within 6 characters.  Note that this routine builds its
251  * string in a static area.  If it needs to be called more than once without
252  * overwriting previous data, then we will need to adopt a technique similar
253  * to the one used for format_k.
254  */
255 
256 /*
257  * Explanation: We want to keep the output within 6 characters.  For low
258  * values we use the format mm:ss.  For values that exceed 999:59, we switch
259  * to a format that displays hours and fractions:  hhh.tH.  For values that
260  * exceed 999.9, we use hhhh.t and drop the "H" designator.  For values that
261  * exceed 9999.9, we use "???".
262  */
263 
264 char *
265 format_time(time_t seconds)
266 {
267 	static char result[10];
268 
269 	/* sanity protection */
270 	if (seconds < 0 || seconds > (99999l * 360l)) {
271 		strlcpy(result, "   ???", sizeof result);
272 	} else if (seconds >= (1000l * 60l)) {
273 		/* alternate (slow) method displaying hours and tenths */
274 		snprintf(result, sizeof(result), "%5.1fH",
275 		    (double) seconds / (double) (60l * 60l));
276 
277 		/*
278 		 * It is possible that the snprintf took more than 6
279 		 * characters. If so, then the "H" appears as result[6].  If
280 		 * not, then there is a \0 in result[6].  Either way, it is
281 		 * safe to step on.
282 		 */
283 		result[6] = '\0';
284 	} else {
285 		/* standard method produces MMM:SS */
286 		/* we avoid printf as must as possible to make this quick */
287 		snprintf(result, sizeof(result), "%3d:%02d", seconds / 60,
288 		    seconds % 60);
289 	}
290 	return (result);
291 }
292 
293 /*
294  * format_k(amt) - format a kilobyte memory value, returning a string
295  * suitable for display.  Returns a pointer to a static
296  * area that changes each call.  "amt" is converted to a
297  * string with a trailing "K".  If "amt" is 10000 or greater,
298  * then it is formatted as megabytes (rounded) with a
299  * trailing "M".
300  */
301 
302 /*
303  * Compromise time.  We need to return a string, but we don't want the
304  * caller to have to worry about freeing a dynamically allocated string.
305  * Unfortunately, we can't just return a pointer to a static area as one
306  * of the common uses of this function is in a large call to snprintf where
307  * it might get invoked several times.  Our compromise is to maintain an
308  * array of strings and cycle thru them with each invocation.  We make the
309  * array large enough to handle the above mentioned case.  The constant
310  * NUM_STRINGS defines the number of strings in this array:  we can tolerate
311  * up to NUM_STRINGS calls before we start overwriting old information.
312  * Keeping NUM_STRINGS a power of two will allow an intelligent optimizer
313  * to convert the modulo operation into something quicker.  What a hack!
314  */
315 
316 #define NUM_STRINGS 8
317 
318 char *
319 format_k(int amt)
320 {
321 	static char retarray[NUM_STRINGS][16];
322 	static int  idx = 0;
323 	char *ret, tag = 'K';
324 
325 	ret = retarray[idx];
326 	idx = (idx + 1) % NUM_STRINGS;
327 
328 	if (amt >= 10000) {
329 		amt = (amt + 512) / 1024;
330 		tag = 'M';
331 		if (amt >= 10000) {
332 			amt = (amt + 512) / 1024;
333 			tag = 'G';
334 		}
335 	}
336 	snprintf(ret, sizeof(retarray[0]), "%d%c", amt, tag);
337 	return (ret);
338 }
339 
340 int
341 find_pid(pid_t pid)
342 {
343 	struct kinfo_proc2 *pbase, *cur;
344 	int nproc;
345 
346 	if ((pbase = getprocs(KERN_PROC_KTHREAD, 0, &nproc)) == NULL)
347 		quit(23);
348 
349 	for (cur = pbase; cur < &pbase[nproc]; cur++)
350 		if (cur->p_pid == pid)
351 			return 1;
352 	return 0;
353 }
354