Annotation of src/usr.bin/top/utils.c, Revision 1.18
1.18 ! otto 1: /* $OpenBSD: utils.c,v 1.17 2007/02/27 16:27:39 otto Exp $ */
1.1 downsj 2:
3: /*
4: * Top users/processes display for Unix
5: * Version 3
6: *
1.6 deraadt 7: * Copyright (c) 1984, 1989, William LeFebvre, Rice University
8: * Copyright (c) 1989, 1990, 1992, William LeFebvre, Northwestern University
1.1 downsj 9: *
1.6 deraadt 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.
1.1 downsj 29: */
30:
31: /*
32: * This file contains various handy utilities used by top.
33: */
34:
1.14 otto 35: #include <sys/param.h>
36: #include <sys/sysctl.h>
1.16 millert 37: #include <err.h>
1.2 downsj 38: #include <stdio.h>
39: #include <string.h>
40: #include <stdlib.h>
41:
1.1 downsj 42: #include "top.h"
1.14 otto 43: #include "machine.h"
1.13 deraadt 44: #include "utils.h"
1.1 downsj 45:
1.9 pvalchev 46: int
47: atoiwi(char *str)
1.1 downsj 48: {
1.12 deraadt 49: size_t len;
1.17 otto 50: const char *errstr;
51: int i;
1.1 downsj 52:
1.10 deraadt 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);
1.17 otto 59: }
60: i = (int)strtonum(str, 0, INT_MAX, &errstr);
61: if (errstr) {
1.10 deraadt 62: return (Invalid);
1.17 otto 63: } else
64: return (i);
1.1 downsj 65: }
1.10 deraadt 66: return (0);
1.1 downsj 67: }
68:
69: /*
1.11 millert 70: * itoa - convert integer (decimal) to ascii string.
1.1 downsj 71: */
1.9 pvalchev 72: char *
73: itoa(int val)
1.1 downsj 74: {
1.10 deraadt 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: */
1.11 millert 81: (void)snprintf(buffer, sizeof(buffer), "%d", val);
82: return (buffer);
1.1 downsj 83: }
84:
85: /*
1.11 millert 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.
1.1 downsj 88: */
1.9 pvalchev 89: char *
1.11 millert 90: format_uid(uid_t uid)
1.1 downsj 91: {
1.11 millert 92: static char buffer[16]; /* result is built here */
1.1 downsj 93:
1.11 millert 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);
1.1 downsj 100: }
101:
102: /*
1.10 deraadt 103: * digits(val) - return number of decimal digits in val. Only works for
104: * positive numbers. If val <= 0 then digits(val) == 0.
1.1 downsj 105: */
1.9 pvalchev 106: int
107: digits(int val)
1.1 downsj 108: {
1.10 deraadt 109: int cnt = 0;
1.1 downsj 110:
1.10 deraadt 111: while (val > 0) {
112: cnt++;
113: val /= 10;
114: }
115: return (cnt);
1.1 downsj 116: }
117:
118: /*
119: * string_index(string, array) - find string in array and return index
120: */
1.9 pvalchev 121: int
122: string_index(char *string, char **array)
1.1 downsj 123: {
1.10 deraadt 124: int i = 0;
1.1 downsj 125:
1.10 deraadt 126: while (*array != NULL) {
127: if (strcmp(string, *array) == 0)
128: return (i);
129: array++;
130: i++;
1.1 downsj 131: }
1.10 deraadt 132: return (-1);
1.1 downsj 133: }
134:
135: /*
136: * argparse(line, cntp) - parse arguments in string "line", separating them
1.10 deraadt 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.
1.1 downsj 140: */
1.9 pvalchev 141: char **
142: argparse(char *line, int *cntp)
1.1 downsj 143: {
1.10 deraadt 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;
1.1 downsj 160: }
161:
1.10 deraadt 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 */
1.16 millert 169: if ((argarray = malloc(cnt * sizeof(char *))) == NULL)
170: err(1, NULL);
1.10 deraadt 171:
172: /* allocate another array to hold the strings themselves */
1.16 millert 173: if ((args = malloc(length + 2)) == NULL)
174: err(1, NULL);
1.10 deraadt 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;
1.1 downsj 199: }
1.10 deraadt 200: *to++ = '\0';
201:
202: /* set cntp and return the allocated array */
203: *cntp = cnt;
204: return (argarray);
1.1 downsj 205: }
206:
207: /*
1.10 deraadt 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.
1.1 downsj 214: */
1.9 pvalchev 215: int
1.16 millert 216: percentages(int cnt, int64_t *out, int64_t *new, int64_t *old, int64_t *diffs)
1.1 downsj 217: {
1.16 millert 218: int64_t change, total_change, *dp, half_total;
1.10 deraadt 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 */
1.16 millert 229: change = (*new - *old);
1.10 deraadt 230: }
231: total_change += (*dp++ = change);
232: *old++ = *new++;
1.1 downsj 233: }
234:
1.10 deraadt 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);
1.1 downsj 246: }
247:
1.10 deraadt 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.
1.1 downsj 254: */
255:
1.10 deraadt 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 "???".
1.1 downsj 262: */
263:
1.9 pvalchev 264: char *
265: format_time(time_t seconds)
1.1 downsj 266: {
1.10 deraadt 267: static char result[10];
1.1 downsj 268:
1.10 deraadt 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);
1.1 downsj 291: }
292:
293: /*
294: * format_k(amt) - format a kilobyte memory value, returning a string
1.10 deraadt 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".
1.1 downsj 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
1.8 deraadt 306: * of the common uses of this function is in a large call to snprintf where
1.1 downsj 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:
1.9 pvalchev 318: char *
319: format_k(int amt)
1.1 downsj 320: {
1.10 deraadt 321: static char retarray[NUM_STRINGS][16];
1.12 deraadt 322: static int idx = 0;
1.11 millert 323: char *ret, tag = 'K';
1.10 deraadt 324:
1.12 deraadt 325: ret = retarray[idx];
326: idx = (idx + 1) % NUM_STRINGS;
1.10 deraadt 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: }
1.1 downsj 335: }
1.11 millert 336: snprintf(ret, sizeof(retarray[0]), "%d%c", amt, tag);
1.10 deraadt 337: return (ret);
1.14 otto 338: }
339:
340: int
341: find_pid(pid_t pid)
342: {
343: struct kinfo_proc2 *pbase, *cur;
1.15 pat 344: int nproc;
1.14 otto 345:
346: if ((pbase = getprocs(KERN_PROC_KTHREAD, 0, &nproc)) == NULL)
347: quit(23);
348:
1.15 pat 349: for (cur = pbase; cur < &pbase[nproc]; cur++)
1.14 otto 350: if (cur->p_pid == pid)
351: return 1;
352: return 0;
1.1 downsj 353: }