dtrace: Address KMSAN warnings in dtrace_disx86
[freebsd/src.git] / usr.bin / top / utils.c
blobcde89a211b53b9b2d6435302a7c7bf8f0813d62c
1 /*
2 * This program may be freely redistributed,
3 * but this entire comment MUST remain intact.
5 * Copyright (c) 2018, Eitan Adler
6 * Copyright (c) 1984, 1989, William LeFebvre, Rice University
7 * Copyright (c) 1989, 1990, 1992, William LeFebvre, Northwestern University
8 */
11 * This file contains various handy utilities used by top.
14 #include "top.h"
15 #include "utils.h"
17 #include <sys/param.h>
18 #include <sys/sysctl.h>
19 #include <sys/user.h>
21 #include <libutil.h>
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <fcntl.h>
26 #include <paths.h>
27 #include <kvm.h>
29 int
30 atoiwi(const char *str)
32 size_t len;
34 len = strlen(str);
35 if (len != 0)
37 if (strncmp(str, "infinity", len) == 0 ||
38 strncmp(str, "all", len) == 0 ||
39 strncmp(str, "maximum", len) == 0)
41 return(Infinity);
43 else if (str[0] == '-')
45 return(Invalid);
47 else
49 return((int)strtol(str, NULL, 10));
52 return(0);
56 * itoa - convert integer (decimal) to ascii string for positive numbers
57 * only (we don't bother with negative numbers since we know we
58 * don't use them).
62 * How do we know that 16 will suffice?
63 * Because the biggest number that we will
64 * ever convert will be 2^32-1, which is 10
65 * digits.
67 _Static_assert(sizeof(int) <= 4, "buffer too small for this sized int");
69 char *
70 itoa(unsigned int val)
72 static char buffer[16]; /* result is built here */
73 /* 16 is sufficient since the largest number
74 we will ever convert will be 2^32-1,
75 which is 10 digits. */
77 sprintf(buffer, "%u", val);
78 return (buffer);
82 * itoa7(val) - like itoa, except the number is right justified in a 7
83 * character field. This code is a duplication of itoa instead of
84 * a front end to a more general routine for efficiency.
87 char *
88 itoa7(int val)
90 static char buffer[16]; /* result is built here */
91 /* 16 is sufficient since the largest number
92 we will ever convert will be 2^32-1,
93 which is 10 digits. */
95 sprintf(buffer, "%6u", val);
96 return (buffer);
100 * digits(val) - return number of decimal digits in val. Only works for
101 * non-negative numbers.
104 int __pure2
105 digits(int val)
107 int cnt = 0;
108 if (val == 0) {
109 return 1;
112 while (val > 0) {
113 cnt++;
114 val /= 10;
116 return(cnt);
120 * string_index(string, array) - find string in array and return index
124 string_index(const char *string, const char * const *array)
126 size_t i = 0;
128 while (*array != NULL)
130 if (strcmp(string, *array) == 0)
132 return(i);
134 array++;
135 i++;
137 return(-1);
141 * argparse(line, cntp) - parse arguments in string "line", separating them
142 * out into an argv-like array, and setting *cntp to the number of
143 * arguments encountered. This is a simple parser that doesn't understand
144 * squat about quotes.
147 const char **
148 argparse(char *line, int *cntp)
150 const char **ap;
151 static const char *argv[1024] = {0};
153 *cntp = 1;
154 ap = &argv[1];
155 while ((*ap = strsep(&line, " ")) != NULL) {
156 if (**ap != '\0') {
157 (*cntp)++;
158 if (*cntp >= (int)nitems(argv)) {
159 break;
161 ap++;
164 return (argv);
168 * percentages(cnt, out, new, old, diffs) - calculate percentage change
169 * between array "old" and "new", putting the percentages i "out".
170 * "cnt" is size of each array and "diffs" is used for scratch space.
171 * The array "old" is updated on each call.
172 * The routine assumes modulo arithmetic. This function is especially
173 * useful on for calculating cpu state percentages.
176 long
177 percentages(int cnt, int *out, long *new, long *old, long *diffs)
179 int i;
180 long change;
181 long total_change;
182 long *dp;
183 long half_total;
185 /* initialization */
186 total_change = 0;
187 dp = diffs;
189 /* calculate changes for each state and the overall change */
190 for (i = 0; i < cnt; i++)
192 if ((change = *new - *old) < 0)
194 /* this only happens when the counter wraps */
195 change = (int)
196 ((unsigned long)*new-(unsigned long)*old);
198 total_change += (*dp++ = change);
199 *old++ = *new++;
202 /* avoid divide by zero potential */
203 if (total_change == 0)
205 total_change = 1;
208 /* calculate percentages based on overall change, rounding up */
209 half_total = total_change / 2l;
211 for (i = 0; i < cnt; i++)
213 *out++ = (int)((*diffs++ * 1000 + half_total) / total_change);
216 /* return the total in case the caller wants to use it */
217 return(total_change);
220 /* format_time(seconds) - format number of seconds into a suitable
221 * display that will fit within 6 characters. Note that this
222 * routine builds its string in a static area. If it needs
223 * to be called more than once without overwriting previous data,
224 * then we will need to adopt a technique similar to the
225 * one used for format_k.
228 /* Explanation:
229 We want to keep the output within 6 characters. For low values we use
230 the format mm:ss. For values that exceed 999:59, we switch to a format
231 that displays hours and fractions: hhh.tH. For values that exceed
232 999.9, we use hhhh.t and drop the "H" designator. For values that
233 exceed 9999.9, we use "???".
236 const char *
237 format_time(long seconds)
239 static char result[10];
241 /* sanity protection */
242 if (seconds < 0 || seconds > (99999l * 360l))
244 strcpy(result, " ???");
246 else if (seconds >= (1000l * 60l))
248 /* alternate (slow) method displaying hours and tenths */
249 sprintf(result, "%5.1fH", (double)seconds / (double)(60l * 60l));
251 /* It is possible that the sprintf took more than 6 characters.
252 If so, then the "H" appears as result[6]. If not, then there
253 is a \0 in result[6]. Either way, it is safe to step on.
255 result[6] = '\0';
257 else
259 /* standard method produces MMM:SS */
260 sprintf(result, "%3ld:%02ld",
261 seconds / 60l, seconds % 60l);
263 return(result);
267 * format_k(amt) - format a kilobyte memory value, returning a string
268 * suitable for display. Returns a pointer to a static
269 * area that changes each call. "amt" is converted to a fixed
270 * size humanize_number call
274 * Compromise time. We need to return a string, but we don't want the
275 * caller to have to worry about freeing a dynamically allocated string.
276 * Unfortunately, we can't just return a pointer to a static area as one
277 * of the common uses of this function is in a large call to sprintf where
278 * it might get invoked several times. Our compromise is to maintain an
279 * array of strings and cycle thru them with each invocation. We make the
280 * array large enough to handle the above mentioned case. The constant
281 * NUM_STRINGS defines the number of strings in this array: we can tolerate
282 * up to NUM_STRINGS calls before we start overwriting old information.
283 * Keeping NUM_STRINGS a power of two will allow an intelligent optimizer
284 * to convert the modulo operation into something quicker. What a hack!
287 #define NUM_STRINGS 8
289 char *
290 format_k(int64_t amt)
292 static char retarray[NUM_STRINGS][16];
293 static int index_ = 0;
294 char *ret;
296 ret = retarray[index_];
297 index_ = (index_ + 1) % NUM_STRINGS;
298 humanize_number(ret, 6, amt * 1024, "", HN_AUTOSCALE, HN_NOSPACE |
299 HN_B);
300 return (ret);
304 find_pid(pid_t pid)
306 kvm_t *kd = NULL;
307 struct kinfo_proc *pbase = NULL;
308 int nproc;
309 int ret = 0;
311 kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, NULL);
312 if (kd == NULL) {
313 fprintf(stderr, "top: kvm_open() failed.\n");
314 quit(TOP_EX_SYS_ERROR);
317 pbase = kvm_getprocs(kd, KERN_PROC_PID, pid, &nproc);
318 if (pbase == NULL) {
319 goto done;
322 if ((nproc == 1) && (pbase->ki_pid == pid)) {
323 ret = 1;
326 done:
327 kvm_close(kd);
328 return ret;