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
13 * This file contains various handy utilities used by top.
19 #include <sys/param.h>
20 #include <sys/sysctl.h>
32 atoiwi(const char *str)
39 if (strncmp(str, "infinity", len) == 0 ||
40 strncmp(str, "all", len) == 0 ||
41 strncmp(str, "maximum", len) == 0)
45 else if (str[0] == '-')
51 return((int)strtol(str, NULL, 10));
58 * itoa - convert integer (decimal) to ascii string for positive numbers
59 * only (we don't bother with negative numbers since we know we
64 * How do we know that 16 will suffice?
65 * Because the biggest number that we will
66 * ever convert will be 2^32-1, which is 10
69 _Static_assert(sizeof(int) <= 4, "buffer too small for this sized int");
72 itoa(unsigned int val)
74 static char buffer[16]; /* result is built here */
75 /* 16 is sufficient since the largest number
76 we will ever convert will be 2^32-1,
77 which is 10 digits. */
79 sprintf(buffer, "%u", val);
84 * itoa7(val) - like itoa, except the number is right justified in a 7
85 * character field. This code is a duplication of itoa instead of
86 * a front end to a more general routine for efficiency.
92 static char buffer[16]; /* result is built here */
93 /* 16 is sufficient since the largest number
94 we will ever convert will be 2^32-1,
95 which is 10 digits. */
97 sprintf(buffer, "%6u", val);
102 * digits(val) - return number of decimal digits in val. Only works for
103 * non-negative numbers.
122 * string_index(string, array) - find string in array and return index
126 string_index(const char *string, const char * const *array)
130 while (*array != NULL)
132 if (strcmp(string, *array) == 0)
143 * argparse(line, cntp) - parse arguments in string "line", separating them
144 * out into an argv-like array, and setting *cntp to the number of
145 * arguments encountered. This is a simple parser that doesn't understand
146 * squat about quotes.
150 argparse(char *line, int *cntp)
153 static const char *argv[1024] = {0};
157 while ((*ap = strsep(&line, " ")) != NULL) {
160 if (*cntp >= (int)nitems(argv)) {
170 * percentages(cnt, out, new, old, diffs) - calculate percentage change
171 * between array "old" and "new", putting the percentages i "out".
172 * "cnt" is size of each array and "diffs" is used for scratch space.
173 * The array "old" is updated on each call.
174 * The routine assumes modulo arithmetic. This function is especially
175 * useful on for calculating cpu state percentages.
179 percentages(int cnt, int *out, long *new, long *old, long *diffs)
191 /* calculate changes for each state and the overall change */
192 for (i = 0; i < cnt; i++)
194 if ((change = *new - *old) < 0)
196 /* this only happens when the counter wraps */
198 ((unsigned long)*new-(unsigned long)*old);
200 total_change += (*dp++ = change);
204 /* avoid divide by zero potential */
205 if (total_change == 0)
210 /* calculate percentages based on overall change, rounding up */
211 half_total = total_change / 2l;
213 for (i = 0; i < cnt; i++)
215 *out++ = (int)((*diffs++ * 1000 + half_total) / total_change);
218 /* return the total in case the caller wants to use it */
219 return(total_change);
222 /* format_time(seconds) - format number of seconds into a suitable
223 * display that will fit within 6 characters. Note that this
224 * routine builds its string in a static area. If it needs
225 * to be called more than once without overwriting previous data,
226 * then we will need to adopt a technique similar to the
227 * one used for format_k.
231 We want to keep the output within 6 characters. For low values we use
232 the format mm:ss. For values that exceed 999:59, we switch to a format
233 that displays hours and fractions: hhh.tH. For values that exceed
234 999.9, we use hhhh.t and drop the "H" designator. For values that
235 exceed 9999.9, we use "???".
239 format_time(long seconds)
241 static char result[10];
243 /* sanity protection */
244 if (seconds < 0 || seconds > (99999l * 360l))
246 strcpy(result, " ???");
248 else if (seconds >= (1000l * 60l))
250 /* alternate (slow) method displaying hours and tenths */
251 sprintf(result, "%5.1fH", (double)seconds / (double)(60l * 60l));
253 /* It is possible that the sprintf took more than 6 characters.
254 If so, then the "H" appears as result[6]. If not, then there
255 is a \0 in result[6]. Either way, it is safe to step on.
261 /* standard method produces MMM:SS */
262 sprintf(result, "%3ld:%02ld",
263 seconds / 60l, seconds % 60l);
269 * format_k(amt) - format a kilobyte memory value, returning a string
270 * suitable for display. Returns a pointer to a static
271 * area that changes each call. "amt" is converted to a fixed
272 * size humanize_number call
276 * Compromise time. We need to return a string, but we don't want the
277 * caller to have to worry about freeing a dynamically allocated string.
278 * Unfortunately, we can't just return a pointer to a static area as one
279 * of the common uses of this function is in a large call to sprintf where
280 * it might get invoked several times. Our compromise is to maintain an
281 * array of strings and cycle thru them with each invocation. We make the
282 * array large enough to handle the above mentioned case. The constant
283 * NUM_STRINGS defines the number of strings in this array: we can tolerate
284 * up to NUM_STRINGS calls before we start overwriting old information.
285 * Keeping NUM_STRINGS a power of two will allow an intelligent optimizer
286 * to convert the modulo operation into something quicker. What a hack!
289 #define NUM_STRINGS 8
292 format_k(int64_t amt)
294 static char retarray[NUM_STRINGS][16];
295 static int index_ = 0;
298 ret = retarray[index_];
299 index_ = (index_ + 1) % NUM_STRINGS;
300 humanize_number(ret, 6, amt * 1024, "", HN_AUTOSCALE, HN_NOSPACE |
309 struct kinfo_proc *pbase = NULL;
313 kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, NULL);
315 fprintf(stderr, "top: kvm_open() failed.\n");
316 quit(TOP_EX_SYS_ERROR);
319 pbase = kvm_getprocs(kd, KERN_PROC_PID, pid, &nproc);
324 if ((nproc == 1) && (pbase->ki_pid == pid)) {