2 * This program may be freely redistributed,
3 * but this entire comment MUST remain intact.
5 * Copyright (c) 2018, Daichi Goto
6 * Copyright (c) 2018, Eitan Adler
7 * Copyright (c) 1984, 1989, William LeFebvre, Rice University
8 * Copyright (c) 1989, 1990, 1992, William LeFebvre, Northwestern University
14 * This file contains various handy utilities used by top.
20 #include <sys/param.h>
21 #include <sys/sysctl.h>
33 atoiwi(const char *str)
40 if (strncmp(str, "infinity", len) == 0 ||
41 strncmp(str, "all", len) == 0 ||
42 strncmp(str, "maximum", len) == 0)
46 else if (str[0] == '-')
52 return((int)strtol(str, NULL, 10));
59 * itoa - convert integer (decimal) to ascii string for positive numbers
60 * only (we don't bother with negative numbers since we know we
65 * How do we know that 16 will suffice?
66 * Because the biggest number that we will
67 * ever convert will be 2^32-1, which is 10
70 _Static_assert(sizeof(int) <= 4, "buffer too small for this sized int");
73 itoa(unsigned int val)
75 static char buffer[16]; /* result is built here */
76 /* 16 is sufficient since the largest number
77 we will ever convert will be 2^32-1,
78 which is 10 digits. */
80 sprintf(buffer, "%u", val);
85 * itoa7(val) - like itoa, except the number is right justified in a 7
86 * character field. This code is a duplication of itoa instead of
87 * a front end to a more general routine for efficiency.
93 static char buffer[16]; /* result is built here */
94 /* 16 is sufficient since the largest number
95 we will ever convert will be 2^32-1,
96 which is 10 digits. */
98 sprintf(buffer, "%6u", val);
103 * digits(val) - return number of decimal digits in val. Only works for
104 * non-negative numbers.
123 * string_index(string, array) - find string in array and return index
127 string_index(const char *string, const char * const *array)
131 while (*array != NULL)
133 if (strcmp(string, *array) == 0)
144 * argparse(line, cntp) - parse arguments in string "line", separating them
145 * out into an argv-like array, and setting *cntp to the number of
146 * arguments encountered. This is a simple parser that doesn't understand
147 * squat about quotes.
151 argparse(char *line, int *cntp)
154 static const char *argv[1024] = {0};
158 while ((*ap = strsep(&line, " ")) != NULL) {
161 if (*cntp >= (int)nitems(argv)) {
171 * percentages(cnt, out, new, old, diffs) - calculate percentage change
172 * between array "old" and "new", putting the percentages i "out".
173 * "cnt" is size of each array and "diffs" is used for scratch space.
174 * The array "old" is updated on each call.
175 * The routine assumes modulo arithmetic. This function is especially
176 * useful on for calculating cpu state percentages.
180 percentages(int cnt, int *out, long *new, long *old, long *diffs)
192 /* calculate changes for each state and the overall change */
193 for (i = 0; i < cnt; i++)
195 if ((change = *new - *old) < 0)
197 /* this only happens when the counter wraps */
199 ((unsigned long)*new-(unsigned long)*old);
201 total_change += (*dp++ = change);
205 /* avoid divide by zero potential */
206 if (total_change == 0)
211 /* calculate percentages based on overall change, rounding up */
212 half_total = total_change / 2l;
214 for (i = 0; i < cnt; i++)
216 *out++ = (int)((*diffs++ * 1000 + half_total) / total_change);
219 /* return the total in case the caller wants to use it */
220 return(total_change);
223 /* format_time(seconds) - format number of seconds into a suitable
224 * display that will fit within 6 characters. Note that this
225 * routine builds its string in a static area. If it needs
226 * to be called more than once without overwriting previous data,
227 * then we will need to adopt a technique similar to the
228 * one used for format_k.
232 We want to keep the output within 6 characters. For low values we use
233 the format mm:ss. For values that exceed 999:59, we switch to a format
234 that displays hours and fractions: hhh.tH. For values that exceed
235 999.9, we use hhhh.t and drop the "H" designator. For values that
236 exceed 9999.9, we use "???".
240 format_time(long seconds)
242 static char result[10];
244 /* sanity protection */
245 if (seconds < 0 || seconds > (99999l * 360l))
247 strcpy(result, " ???");
249 else if (seconds >= (1000l * 60l))
251 /* alternate (slow) method displaying hours and tenths */
252 sprintf(result, "%5.1fH", (double)seconds / (double)(60l * 60l));
254 /* It is possible that the sprintf took more than 6 characters.
255 If so, then the "H" appears as result[6]. If not, then there
256 is a \0 in result[6]. Either way, it is safe to step on.
262 /* standard method produces MMM:SS */
263 sprintf(result, "%3ld:%02ld",
264 seconds / 60l, seconds % 60l);
270 * format_k(amt) - format a kilobyte memory value, returning a string
271 * suitable for display. Returns a pointer to a static
272 * area that changes each call. "amt" is converted to a fixed
273 * size humanize_number call
277 * Compromise time. We need to return a string, but we don't want the
278 * caller to have to worry about freeing a dynamically allocated string.
279 * Unfortunately, we can't just return a pointer to a static area as one
280 * of the common uses of this function is in a large call to sprintf where
281 * it might get invoked several times. Our compromise is to maintain an
282 * array of strings and cycle thru them with each invocation. We make the
283 * array large enough to handle the above mentioned case. The constant
284 * NUM_STRINGS defines the number of strings in this array: we can tolerate
285 * up to NUM_STRINGS calls before we start overwriting old information.
286 * Keeping NUM_STRINGS a power of two will allow an intelligent optimizer
287 * to convert the modulo operation into something quicker. What a hack!
290 #define NUM_STRINGS 8
293 format_k(int64_t amt)
295 static char retarray[NUM_STRINGS][16];
296 static int index = 0;
299 ret = retarray[index];
300 index = (index + 1) % NUM_STRINGS;
301 humanize_number(ret, 5, 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)) {
334 * utf8strvisx(dst,src,src_len)
335 * strvisx(dst,src,src_len,VIS_NL|VIS_CSTYLE) coresponding to UTF-8.
337 static const char *vis_encodes[] = {
338 "\\0", "\\^A", "\\^B", "\\^C", "\\^D", "\\^E", "\\^F", "\\a",
339 "\\b", "\t", "\\n", "\\v", "\\f", "\\r", "\\^N", "\\^O", "\\^P",
340 "\\^Q", "\\^R", "\\^S", "\\^T", "\\^U", "\\^V", "\\^W", "\\^X",
341 "\\^Y", "\\^Z", "\\^[", "\\^\\", "\\^]", "\\^^", "\\^_"
345 utf8strvisx(char *dst, const char *src, size_t src_len)
347 const signed char *src_p;
356 if (0x00 == (0x80 & *src_p)) {
357 if (0 <= *src_p && *src_p <= 31) {
358 j = strlen(vis_encodes[(int)*src_p]);
359 strcpy(dst_p, vis_encodes[(int)*src_p]);
362 } else if (127 == *src_p) {
363 strcpy(dst_p, "\\^?");
371 } else if (0xC0 == (0xE0 & *src_p)) {
372 *dst_p++ = *src_p++; ++i; ++olen;
373 if (i < len) { *dst_p++ = *src_p++; ++i; ++olen; }
374 } else if (0xE0 == (0xF0 & *src_p)) {
375 *dst_p++ = *src_p++; ++i; ++olen;
376 if (i < len) { *dst_p++ = *src_p++; ++i; ++olen; }
377 if (i < len) { *dst_p++ = *src_p++; ++i; ++olen; }
378 } else if (0xF0 == (0xF8 & *src_p)) {
379 *dst_p++ = *src_p++; ++i; ++olen;
380 if (i < len) { *dst_p++ = *src_p++; ++i; ++olen; }
381 if (i < len) { *dst_p++ = *src_p++; ++i; ++olen; }
382 if (i < len) { *dst_p++ = *src_p++; ++i; ++olen; }
384 *dst_p++ = '?'; ++i; ++olen;