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