utils.c 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. /*
  2. * This program may be freely redistributed,
  3. * but this entire comment MUST remain intact.
  4. *
  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. */
  9. /*
  10. * This file contains various handy utilities used by top.
  11. */
  12. #include "top.h"
  13. #include "utils.h"
  14. #include <sys/param.h>
  15. #include <sys/sysctl.h>
  16. #include <sys/user.h>
  17. #include <libutil.h>
  18. #include <stdlib.h>
  19. #include <stdio.h>
  20. #include <string.h>
  21. #include <fcntl.h>
  22. #include <paths.h>
  23. #include <kvm.h>
  24. int
  25. atoiwi(const char *str)
  26. {
  27. size_t len;
  28. len = strlen(str);
  29. if (len != 0)
  30. {
  31. if (strncmp(str, "infinity", len) == 0 ||
  32. strncmp(str, "all", len) == 0 ||
  33. strncmp(str, "maximum", len) == 0)
  34. {
  35. return(Infinity);
  36. }
  37. else if (str[0] == '-')
  38. {
  39. return(Invalid);
  40. }
  41. else
  42. {
  43. return((int)strtol(str, NULL, 10));
  44. }
  45. }
  46. return(0);
  47. }
  48. /*
  49. * itoa - convert integer (decimal) to ascii string for positive numbers
  50. * only (we don't bother with negative numbers since we know we
  51. * don't use them).
  52. */
  53. /*
  54. * How do we know that 16 will suffice?
  55. * Because the biggest number that we will
  56. * ever convert will be 2^32-1, which is 10
  57. * digits.
  58. */
  59. _Static_assert(sizeof(int) <= 4, "buffer too small for this sized int");
  60. char *
  61. itoa(unsigned int val)
  62. {
  63. static char buffer[16]; /* result is built here */
  64. /* 16 is sufficient since the largest number
  65. we will ever convert will be 2^32-1,
  66. which is 10 digits. */
  67. sprintf(buffer, "%u", val);
  68. return (buffer);
  69. }
  70. /*
  71. * itoa7(val) - like itoa, except the number is right justified in a 7
  72. * character field. This code is a duplication of itoa instead of
  73. * a front end to a more general routine for efficiency.
  74. */
  75. char *
  76. itoa7(int val)
  77. {
  78. static char buffer[16]; /* result is built here */
  79. /* 16 is sufficient since the largest number
  80. we will ever convert will be 2^32-1,
  81. which is 10 digits. */
  82. sprintf(buffer, "%6u", val);
  83. return (buffer);
  84. }
  85. /*
  86. * digits(val) - return number of decimal digits in val. Only works for
  87. * non-negative numbers.
  88. */
  89. int __pure2
  90. digits(int val)
  91. {
  92. int cnt = 0;
  93. if (val == 0) {
  94. return 1;
  95. }
  96. while (val > 0) {
  97. cnt++;
  98. val /= 10;
  99. }
  100. return(cnt);
  101. }
  102. /*
  103. * string_index(string, array) - find string in array and return index
  104. */
  105. int
  106. string_index(const char *string, const char * const *array)
  107. {
  108. size_t i = 0;
  109. while (*array != NULL)
  110. {
  111. if (strcmp(string, *array) == 0)
  112. {
  113. return(i);
  114. }
  115. array++;
  116. i++;
  117. }
  118. return(-1);
  119. }
  120. /*
  121. * argparse(line, cntp) - parse arguments in string "line", separating them
  122. * out into an argv-like array, and setting *cntp to the number of
  123. * arguments encountered. This is a simple parser that doesn't understand
  124. * squat about quotes.
  125. */
  126. const char **
  127. argparse(char *line, int *cntp)
  128. {
  129. const char **ap;
  130. static const char *argv[1024] = {0};
  131. *cntp = 1;
  132. ap = &argv[1];
  133. while ((*ap = strsep(&line, " ")) != NULL) {
  134. if (**ap != '\0') {
  135. (*cntp)++;
  136. if (*cntp >= (int)nitems(argv)) {
  137. break;
  138. }
  139. ap++;
  140. }
  141. }
  142. return (argv);
  143. }
  144. /*
  145. * percentages(cnt, out, new, old, diffs) - calculate percentage change
  146. * between array "old" and "new", putting the percentages i "out".
  147. * "cnt" is size of each array and "diffs" is used for scratch space.
  148. * The array "old" is updated on each call.
  149. * The routine assumes modulo arithmetic. This function is especially
  150. * useful on for calculating cpu state percentages.
  151. */
  152. long
  153. percentages(int cnt, int *out, long *new, long *old, long *diffs)
  154. {
  155. int i;
  156. long change;
  157. long total_change;
  158. long *dp;
  159. long half_total;
  160. /* initialization */
  161. total_change = 0;
  162. dp = diffs;
  163. /* calculate changes for each state and the overall change */
  164. for (i = 0; i < cnt; i++)
  165. {
  166. if ((change = *new - *old) < 0)
  167. {
  168. /* this only happens when the counter wraps */
  169. change = (int)
  170. ((unsigned long)*new-(unsigned long)*old);
  171. }
  172. total_change += (*dp++ = change);
  173. *old++ = *new++;
  174. }
  175. /* avoid divide by zero potential */
  176. if (total_change == 0)
  177. {
  178. total_change = 1;
  179. }
  180. /* calculate percentages based on overall change, rounding up */
  181. half_total = total_change / 2l;
  182. for (i = 0; i < cnt; i++)
  183. {
  184. *out++ = (int)((*diffs++ * 1000 + half_total) / total_change);
  185. }
  186. /* return the total in case the caller wants to use it */
  187. return(total_change);
  188. }
  189. /* format_time(seconds) - format number of seconds into a suitable
  190. * display that will fit within 6 characters. Note that this
  191. * routine builds its string in a static area. If it needs
  192. * to be called more than once without overwriting previous data,
  193. * then we will need to adopt a technique similar to the
  194. * one used for format_k.
  195. */
  196. /* Explanation:
  197. We want to keep the output within 6 characters. For low values we use
  198. the format mm:ss. For values that exceed 999:59, we switch to a format
  199. that displays hours and fractions: hhh.tH. For values that exceed
  200. 999.9, we use hhhh.t and drop the "H" designator. For values that
  201. exceed 9999.9, we use "???".
  202. */
  203. const char *
  204. format_time(long seconds)
  205. {
  206. static char result[10];
  207. /* sanity protection */
  208. if (seconds < 0 || seconds > (99999l * 360l))
  209. {
  210. strcpy(result, " ???");
  211. }
  212. else if (seconds >= (1000l * 60l))
  213. {
  214. /* alternate (slow) method displaying hours and tenths */
  215. sprintf(result, "%5.1fH", (double)seconds / (double)(60l * 60l));
  216. /* It is possible that the sprintf took more than 6 characters.
  217. If so, then the "H" appears as result[6]. If not, then there
  218. is a \0 in result[6]. Either way, it is safe to step on.
  219. */
  220. result[6] = '\0';
  221. }
  222. else
  223. {
  224. /* standard method produces MMM:SS */
  225. sprintf(result, "%3ld:%02ld",
  226. seconds / 60l, seconds % 60l);
  227. }
  228. return(result);
  229. }
  230. /*
  231. * format_k(amt) - format a kilobyte memory value, returning a string
  232. * suitable for display. Returns a pointer to a static
  233. * area that changes each call. "amt" is converted to a fixed
  234. * size humanize_number call
  235. */
  236. /*
  237. * Compromise time. We need to return a string, but we don't want the
  238. * caller to have to worry about freeing a dynamically allocated string.
  239. * Unfortunately, we can't just return a pointer to a static area as one
  240. * of the common uses of this function is in a large call to sprintf where
  241. * it might get invoked several times. Our compromise is to maintain an
  242. * array of strings and cycle thru them with each invocation. We make the
  243. * array large enough to handle the above mentioned case. The constant
  244. * NUM_STRINGS defines the number of strings in this array: we can tolerate
  245. * up to NUM_STRINGS calls before we start overwriting old information.
  246. * Keeping NUM_STRINGS a power of two will allow an intelligent optimizer
  247. * to convert the modulo operation into something quicker. What a hack!
  248. */
  249. #define NUM_STRINGS 8
  250. char *
  251. format_k(int64_t amt)
  252. {
  253. static char retarray[NUM_STRINGS][16];
  254. static int index_ = 0;
  255. char *ret;
  256. ret = retarray[index_];
  257. index_ = (index_ + 1) % NUM_STRINGS;
  258. humanize_number(ret, 6, amt * 1024, "", HN_AUTOSCALE, HN_NOSPACE |
  259. HN_B);
  260. return (ret);
  261. }
  262. int
  263. find_pid(pid_t pid)
  264. {
  265. kvm_t *kd = NULL;
  266. struct kinfo_proc *pbase = NULL;
  267. int nproc;
  268. int ret = 0;
  269. kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, NULL);
  270. if (kd == NULL) {
  271. fprintf(stderr, "top: kvm_open() failed.\n");
  272. quit(TOP_EX_SYS_ERROR);
  273. }
  274. pbase = kvm_getprocs(kd, KERN_PROC_PID, pid, &nproc);
  275. if (pbase == NULL) {
  276. goto done;
  277. }
  278. if ((nproc == 1) && (pbase->ki_pid == pid)) {
  279. ret = 1;
  280. }
  281. done:
  282. kvm_close(kd);
  283. return ret;
  284. }