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