Annotation of src/usr.bin/top/utils.c, Revision 1.15
1.15 ! pat 1: /* $OpenBSD: utils.c,v 1.14 2004/10/07 06:26:12 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.2 downsj 37: #include <stdio.h>
38: #include <string.h>
39: #include <stdlib.h>
40: #include <unistd.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.1 downsj 50:
1.10 deraadt 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));
1.1 downsj 61: }
1.10 deraadt 62: return (0);
1.1 downsj 63: }
64:
65: /*
1.11 millert 66: * itoa - convert integer (decimal) to ascii string.
1.1 downsj 67: */
1.9 pvalchev 68: char *
69: itoa(int val)
1.1 downsj 70: {
1.10 deraadt 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: */
1.11 millert 77: (void)snprintf(buffer, sizeof(buffer), "%d", val);
78: return (buffer);
1.1 downsj 79: }
80:
81: /*
1.11 millert 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.
1.1 downsj 84: */
1.9 pvalchev 85: char *
1.11 millert 86: format_uid(uid_t uid)
1.1 downsj 87: {
1.11 millert 88: static char buffer[16]; /* result is built here */
1.1 downsj 89:
1.11 millert 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);
1.1 downsj 96: }
97:
98: /*
1.10 deraadt 99: * digits(val) - return number of decimal digits in val. Only works for
100: * positive numbers. If val <= 0 then digits(val) == 0.
1.1 downsj 101: */
1.9 pvalchev 102: int
103: digits(int val)
1.1 downsj 104: {
1.10 deraadt 105: int cnt = 0;
1.1 downsj 106:
1.10 deraadt 107: while (val > 0) {
108: cnt++;
109: val /= 10;
110: }
111: return (cnt);
1.1 downsj 112: }
113:
114: /*
115: * string_index(string, array) - find string in array and return index
116: */
1.9 pvalchev 117: int
118: string_index(char *string, char **array)
1.1 downsj 119: {
1.10 deraadt 120: int i = 0;
1.1 downsj 121:
1.10 deraadt 122: while (*array != NULL) {
123: if (strcmp(string, *array) == 0)
124: return (i);
125: array++;
126: i++;
1.1 downsj 127: }
1.10 deraadt 128: return (-1);
1.1 downsj 129: }
130:
131: /*
132: * argparse(line, cntp) - parse arguments in string "line", separating them
1.10 deraadt 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.
1.1 downsj 136: */
1.9 pvalchev 137: char **
138: argparse(char *line, int *cntp)
1.1 downsj 139: {
1.10 deraadt 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;
1.1 downsj 156: }
157:
1.10 deraadt 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;
1.1 downsj 193: }
1.10 deraadt 194: *to++ = '\0';
195:
196: /* set cntp and return the allocated array */
197: *cntp = cnt;
198: return (argarray);
1.1 downsj 199: }
200:
201: /*
1.10 deraadt 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.
1.1 downsj 208: */
1.9 pvalchev 209: int
210: percentages(int cnt, int *out, long *new, long *old, long *diffs)
1.1 downsj 211: {
1.10 deraadt 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++;
1.1 downsj 227: }
228:
1.10 deraadt 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);
1.1 downsj 240: }
241:
1.10 deraadt 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.
1.1 downsj 248: */
249:
1.10 deraadt 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 "???".
1.1 downsj 256: */
257:
1.9 pvalchev 258: char *
259: format_time(time_t seconds)
1.1 downsj 260: {
1.10 deraadt 261: static char result[10];
1.1 downsj 262:
1.10 deraadt 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);
1.1 downsj 285: }
286:
287: /*
288: * format_k(amt) - format a kilobyte memory value, returning a string
1.10 deraadt 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".
1.1 downsj 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
1.8 deraadt 300: * of the common uses of this function is in a large call to snprintf where
1.1 downsj 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:
1.9 pvalchev 312: char *
313: format_k(int amt)
1.1 downsj 314: {
1.10 deraadt 315: static char retarray[NUM_STRINGS][16];
1.12 deraadt 316: static int idx = 0;
1.11 millert 317: char *ret, tag = 'K';
1.10 deraadt 318:
1.12 deraadt 319: ret = retarray[idx];
320: idx = (idx + 1) % NUM_STRINGS;
1.10 deraadt 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: }
1.1 downsj 329: }
1.11 millert 330: snprintf(ret, sizeof(retarray[0]), "%d%c", amt, tag);
1.10 deraadt 331: return (ret);
1.14 otto 332: }
333:
334: int
335: find_pid(pid_t pid)
336: {
337: struct kinfo_proc2 *pbase, *cur;
1.15 ! pat 338: int nproc;
1.14 otto 339:
340: if ((pbase = getprocs(KERN_PROC_KTHREAD, 0, &nproc)) == NULL)
341: quit(23);
342:
1.15 ! pat 343: for (cur = pbase; cur < &pbase[nproc]; cur++)
1.14 otto 344: if (cur->p_pid == pid)
345: return 1;
346: return 0;
1.1 downsj 347: }