]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/top/utils.c
top(1): Fix the prompt bug and core dump problem in o / p mode that occurred by r336028
[FreeBSD/FreeBSD.git] / usr.bin / top / utils.c
1 /*
2  *  This program may be freely redistributed,
3  *  but this entire comment MUST remain intact.
4  *
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
9  *
10  * $FreeBSD$
11  */
12
13 /*
14  *  This file contains various handy utilities used by top.
15  */
16
17 #include "top.h"
18 #include "utils.h"
19
20 #include <sys/param.h>
21 #include <sys/sysctl.h>
22 #include <sys/user.h>
23
24 #include <libutil.h>
25 #include <stdlib.h>
26 #include <stdio.h>
27 #include <string.h>
28 #include <fcntl.h>
29 #include <paths.h>
30 #include <kvm.h>
31
32 int
33 atoiwi(const char *str)
34 {
35     size_t len;
36
37     len = strlen(str);
38     if (len != 0)
39     {
40         if (strncmp(str, "infinity", len) == 0 ||
41             strncmp(str, "all",      len) == 0 ||
42             strncmp(str, "maximum",  len) == 0)
43         {
44             return(Infinity);
45         }
46         else if (str[0] == '-')
47         {
48             return(Invalid);
49         }
50         else
51         {
52                 return((int)strtol(str, NULL, 10));
53         }
54     }
55     return(0);
56 }
57
58 /*
59  *  itoa - convert integer (decimal) to ascii string for positive numbers
60  *         only (we don't bother with negative numbers since we know we
61  *         don't use them).
62  */
63
64                                 /*
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
68                                  * digits.
69                                  */
70 _Static_assert(sizeof(int) <= 4, "buffer too small for this sized int");
71
72 char *
73 itoa(unsigned int val)
74 {
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. */
79
80         sprintf(buffer, "%u", val);
81     return (buffer);
82 }
83
84 /*
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.
88  */
89
90 char *
91 itoa7(int val)
92 {
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. */
97
98         sprintf(buffer, "%6u", val);
99     return (buffer);
100 }
101
102 /*
103  *  digits(val) - return number of decimal digits in val.  Only works for
104  *      non-negative numbers.
105  */
106
107 int __pure2
108 digits(int val)
109 {
110     int cnt = 0;
111         if (val == 0) {
112                 return 1;
113         }
114
115     while (val > 0) {
116                 cnt++;
117                 val /= 10;
118     }
119     return(cnt);
120 }
121
122 /*
123  * string_index(string, array) - find string in array and return index
124  */
125
126 int
127 string_index(const char *string, const char * const *array)
128 {
129     size_t i = 0;
130
131     while (*array != NULL)
132     {
133         if (strcmp(string, *array) == 0)
134         {
135             return(i);
136         }
137         array++;
138         i++;
139     }
140     return(-1);
141 }
142
143 /*
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.
148  */
149
150 const char * const *
151 argparse(char *line, int *cntp)
152 {
153     const char **ap;
154     static const char *argv[1024] = {0};
155
156     *cntp = 1;
157     ap = &argv[1];
158     while ((*ap = strsep(&line, " ")) != NULL) {
159         if (**ap != '\0') {
160             (*cntp)++;
161             if (*cntp >= (int)nitems(argv)) {
162                 break;
163             }
164             ap++;
165         }
166     }
167     return (argv);
168 }
169
170 /*
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.
177  */
178
179 long
180 percentages(int cnt, int *out, long *new, long *old, long *diffs)
181 {
182     int i;
183     long change;
184     long total_change;
185     long *dp;
186     long half_total;
187
188     /* initialization */
189     total_change = 0;
190     dp = diffs;
191
192     /* calculate changes for each state and the overall change */
193     for (i = 0; i < cnt; i++)
194     {
195         if ((change = *new - *old) < 0)
196         {
197             /* this only happens when the counter wraps */
198             change = (int)
199                 ((unsigned long)*new-(unsigned long)*old);
200         }
201         total_change += (*dp++ = change);
202         *old++ = *new++;
203     }
204
205     /* avoid divide by zero potential */
206     if (total_change == 0)
207     {
208         total_change = 1;
209     }
210
211     /* calculate percentages based on overall change, rounding up */
212     half_total = total_change / 2l;
213
214         for (i = 0; i < cnt; i++)
215         {
216                 *out++ = (int)((*diffs++ * 1000 + half_total) / total_change);
217         }
218
219     /* return the total in case the caller wants to use it */
220     return(total_change);
221 }
222
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.
229  */
230
231 /* Explanation:
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 "???".
237  */
238
239 const char *
240 format_time(long seconds)
241 {
242         static char result[10];
243
244         /* sanity protection */
245         if (seconds < 0 || seconds > (99999l * 360l))
246         {
247                 strcpy(result, "   ???");
248         }
249         else if (seconds >= (1000l * 60l))
250         {
251                 /* alternate (slow) method displaying hours and tenths */
252                 sprintf(result, "%5.1fH", (double)seconds / (double)(60l * 60l));
253
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.
257                    */
258                 result[6] = '\0';
259         }
260         else
261         {
262                 /* standard method produces MMM:SS */
263                 sprintf(result, "%3ld:%02ld",
264                                 seconds / 60l, seconds % 60l);
265         }
266         return(result);
267 }
268
269 /*
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
274  */
275
276 /*
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!
288  */
289
290 #define NUM_STRINGS 8
291
292 char *
293 format_k(int64_t amt)
294 {
295     static char retarray[NUM_STRINGS][16];
296     static int index = 0;
297     char *ret;
298
299     ret = retarray[index];
300         index = (index + 1) % NUM_STRINGS;
301         humanize_number(ret, 5, amt * 1024, "", HN_AUTOSCALE, HN_NOSPACE);
302         return (ret);
303 }
304
305 int
306 find_pid(pid_t pid)
307 {
308         kvm_t *kd = NULL;
309         struct kinfo_proc *pbase = NULL;
310         int nproc;
311         int ret = 0;
312
313         kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, NULL);
314         if (kd == NULL) {
315                 fprintf(stderr, "top: kvm_open() failed.\n");
316                 quit(TOP_EX_SYS_ERROR);
317         }
318
319         pbase = kvm_getprocs(kd, KERN_PROC_PID, pid, &nproc);
320         if (pbase == NULL) {
321                 goto done;
322         }
323
324         if ((nproc == 1) && (pbase->ki_pid == pid)) {
325                 ret = 1;
326         }
327
328 done:
329         kvm_close(kd);
330         return ret;
331 }
332
333 /*
334  * utf8strvisx(dst,src,src_len) 
335  *      strvisx(dst,src,src_len,VIS_NL|VIS_CSTYLE) coresponding to UTF-8.
336  */
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", "\\^[", "\\^\\", "\\^]", "\\^^", "\\^_"
342 };
343
344 int
345 utf8strvisx(char *dst, const char *src, size_t src_len)
346 {
347         const signed char *src_p;
348         char *dst_p;
349         int i, j, olen, len;
350
351         src_p = src;
352         dst_p = dst;
353         i = olen = 0;
354         len = (int)src_len;
355         while (i < len) {
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]);
360                                 dst_p += j;
361                                 olen += j;
362                         } else if (127 == *src_p) {
363                                 strcpy(dst_p, "\\^?");
364                                 olen += 3;
365                         } else {
366                                 *dst_p++ = *src_p;
367                                 ++olen;
368                         }
369                         ++i;
370                         ++src_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; }
383                 } else {
384                         *dst_p++ = '?'; ++i; ++olen;
385                 }
386         }
387
388         return olen;
389 }