1 /* 2 * This program may be freely redistributed, 3 * but this entire comment MUST remain intact. 4 * 5 * Copyright (c) 1984, 1989, William LeFebvre, Rice University 6 * Copyright (c) 1989, 1990, 1992, William LeFebvre, Northwestern University 7 * 8 * $FreeBSD$ 9 */ 10 11 /* 12 * This file contains various handy utilities used by top. 13 */ 14 15 #include "top.h" 16 #include "utils.h" 17 18 #include <sys/param.h> 19 #include <sys/sysctl.h> 20 #include <sys/user.h> 21 22 #include <stdlib.h> 23 #include <stdio.h> 24 #include <string.h> 25 #include <fcntl.h> 26 #include <paths.h> 27 #include <kvm.h> 28 29 int 30 atoiwi(const char *str) 31 { 32 size_t len; 33 34 len = strlen(str); 35 if (len != 0) 36 { 37 if (strncmp(str, "infinity", len) == 0 || 38 strncmp(str, "all", len) == 0 || 39 strncmp(str, "maximum", len) == 0) 40 { 41 return(Infinity); 42 } 43 else if (str[0] == '-') 44 { 45 return(Invalid); 46 } 47 else 48 { 49 return(atoi(str)); 50 } 51 } 52 return(0); 53 } 54 55 /* 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). 59 */ 60 61 /* 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. 66 */ 67 _Static_assert(sizeof(int) <= 4, "buffer too small for this sized int"); 68 69 char * 70 itoa(unsigned int val) 71 { 72 char *ptr; 73 static char buffer[16]; /* result is built here */ 74 /* 16 is sufficient since the largest number 75 we will ever convert will be 2^32-1, 76 which is 10 digits. */ 77 78 ptr = buffer + sizeof(buffer); 79 *--ptr = '\0'; 80 if (val == 0) 81 { 82 *--ptr = '0'; 83 } 84 else while (val != 0) 85 { 86 *--ptr = (val % 10) + '0'; 87 val /= 10; 88 } 89 return(ptr); 90 } 91 92 /* 93 * itoa7(val) - like itoa, except the number is right justified in a 7 94 * character field. This code is a duplication of itoa instead of 95 * a front end to a more general routine for efficiency. 96 */ 97 98 char * 99 itoa7(int val) 100 { 101 char *ptr; 102 static char buffer[16]; /* result is built here */ 103 /* 16 is sufficient since the largest number 104 we will ever convert will be 2^32-1, 105 which is 10 digits. */ 106 107 ptr = buffer + sizeof(buffer); 108 *--ptr = '\0'; 109 if (val == 0) 110 { 111 *--ptr = '0'; 112 } 113 else while (val != 0) 114 { 115 *--ptr = (val % 10) + '0'; 116 val /= 10; 117 } 118 while (ptr > buffer + sizeof(buffer) - 7) 119 { 120 *--ptr = ' '; 121 } 122 return(ptr); 123 } 124 125 /* 126 * digits(val) - return number of decimal digits in val. Only works for 127 * positive numbers. If val <= 0 then digits(val) == 0. 128 */ 129 130 int 131 digits(int val) 132 { 133 int cnt = 0; 134 135 while (val > 0) 136 { 137 cnt++; 138 val /= 10; 139 } 140 return(cnt); 141 } 142 143 /* 144 * string_index(string, array) - find string in array and return index 145 */ 146 147 int 148 string_index(const char *string, const char * const *array) 149 { 150 size_t i = 0; 151 152 while (*array != NULL) 153 { 154 if (strcmp(string, *array) == 0) 155 { 156 return(i); 157 } 158 array++; 159 i++; 160 } 161 return(-1); 162 } 163 164 /* 165 * argparse(line, cntp) - parse arguments in string "line", separating them 166 * out into an argv-like array, and setting *cntp to the number of 167 * arguments encountered. This is a simple parser that doesn't understand 168 * squat about quotes. 169 */ 170 171 const char * const * 172 argparse(char *line, int *cntp) 173 { 174 const char **ap; 175 static const char *argv[1024] = {0}; 176 177 *cntp = 1; 178 ap = &argv[1]; 179 while ((*ap = strsep(&line, " ")) != NULL) { 180 if (**ap != '\0') { 181 (*cntp)++; 182 if (*cntp >= (int)nitems(argv)) { 183 break; 184 } 185 ap++; 186 } 187 } 188 return (argv); 189 } 190 191 /* 192 * percentages(cnt, out, new, old, diffs) - calculate percentage change 193 * between array "old" and "new", putting the percentages i "out". 194 * "cnt" is size of each array and "diffs" is used for scratch space. 195 * The array "old" is updated on each call. 196 * The routine assumes modulo arithmetic. This function is especially 197 * useful on for calculating cpu state percentages. 198 */ 199 200 long 201 percentages(int cnt, int *out, long *new, long *old, long *diffs) 202 { 203 int i; 204 long change; 205 long total_change; 206 long *dp; 207 long half_total; 208 209 /* initialization */ 210 total_change = 0; 211 dp = diffs; 212 213 /* calculate changes for each state and the overall change */ 214 for (i = 0; i < cnt; i++) 215 { 216 if ((change = *new - *old) < 0) 217 { 218 /* this only happens when the counter wraps */ 219 change = (int) 220 ((unsigned long)*new-(unsigned long)*old); 221 } 222 total_change += (*dp++ = change); 223 *old++ = *new++; 224 } 225 226 /* avoid divide by zero potential */ 227 if (total_change == 0) 228 { 229 total_change = 1; 230 } 231 232 /* calculate percentages based on overall change, rounding up */ 233 half_total = total_change / 2l; 234 235 /* Do not divide by 0. Causes Floating point exception */ 236 if(total_change) { 237 for (i = 0; i < cnt; i++) 238 { 239 *out++ = (int)((*diffs++ * 1000 + half_total) / total_change); 240 } 241 } 242 243 /* return the total in case the caller wants to use it */ 244 return(total_change); 245 } 246 247 /* format_time(seconds) - format number of seconds into a suitable 248 * display that will fit within 6 characters. Note that this 249 * routine builds its string in a static area. If it needs 250 * to be called more than once without overwriting previous data, 251 * then we will need to adopt a technique similar to the 252 * one used for format_k. 253 */ 254 255 /* Explanation: 256 We want to keep the output within 6 characters. For low values we use 257 the format mm:ss. For values that exceed 999:59, we switch to a format 258 that displays hours and fractions: hhh.tH. For values that exceed 259 999.9, we use hhhh.t and drop the "H" designator. For values that 260 exceed 9999.9, we use "???". 261 */ 262 263 char * 264 format_time(long seconds) 265 { 266 static char result[10]; 267 268 /* sanity protection */ 269 if (seconds < 0 || seconds > (99999l * 360l)) 270 { 271 strcpy(result, " ???"); 272 } 273 else if (seconds >= (1000l * 60l)) 274 { 275 /* alternate (slow) method displaying hours and tenths */ 276 sprintf(result, "%5.1fH", (double)seconds / (double)(60l * 60l)); 277 278 /* It is possible that the sprintf took more than 6 characters. 279 If so, then the "H" appears as result[6]. If not, then there 280 is a \0 in result[6]. Either way, it is safe to step on. 281 */ 282 result[6] = '\0'; 283 } 284 else 285 { 286 /* standard method produces MMM:SS */ 287 /* we avoid printf as must as possible to make this quick */ 288 sprintf(result, "%3ld:%02ld", 289 (long)(seconds / 60), (long)(seconds % 60)); 290 } 291 return(result); 292 } 293 294 /* 295 * format_k(amt) - format a kilobyte memory value, returning a string 296 * suitable for display. Returns a pointer to a static 297 * area that changes each call. "amt" is converted to a 298 * string with a trailing "K". If "amt" is 10000 or greater, 299 * then it is formatted as megabytes (rounded) with a 300 * trailing "M". 301 */ 302 303 /* 304 * Compromise time. We need to return a string, but we don't want the 305 * caller to have to worry about freeing a dynamically allocated string. 306 * Unfortunately, we can't just return a pointer to a static area as one 307 * of the common uses of this function is in a large call to sprintf where 308 * it might get invoked several times. Our compromise is to maintain an 309 * array of strings and cycle thru them with each invocation. We make the 310 * array large enough to handle the above mentioned case. The constant 311 * NUM_STRINGS defines the number of strings in this array: we can tolerate 312 * up to NUM_STRINGS calls before we start overwriting old information. 313 * Keeping NUM_STRINGS a power of two will allow an intelligent optimizer 314 * to convert the modulo operation into something quicker. What a hack! 315 */ 316 317 #define NUM_STRINGS 8 318 319 char * 320 format_k(int amt) 321 { 322 static char retarray[NUM_STRINGS][16]; 323 static int index = 0; 324 char *p; 325 char *ret; 326 char tag = 'K'; 327 328 p = ret = retarray[index]; 329 index = (index + 1) % NUM_STRINGS; 330 331 if (amt >= 10000) 332 { 333 amt = (amt + 512) / 1024; 334 tag = 'M'; 335 if (amt >= 10000) 336 { 337 amt = (amt + 512) / 1024; 338 tag = 'G'; 339 } 340 } 341 342 p = stpcpy(p, itoa(amt)); 343 *p++ = tag; 344 *p = '\0'; 345 346 return(ret); 347 } 348 349 char * 350 format_k2(unsigned long long amt) 351 { 352 static char retarray[NUM_STRINGS][16]; 353 static int index = 0; 354 char *p; 355 char *ret; 356 char tag = 'K'; 357 358 p = ret = retarray[index]; 359 index = (index + 1) % NUM_STRINGS; 360 361 if (amt >= 100000) 362 { 363 amt = (amt + 512) / 1024; 364 tag = 'M'; 365 if (amt >= 100000) 366 { 367 amt = (amt + 512) / 1024; 368 tag = 'G'; 369 } 370 } 371 372 p = stpcpy(p, itoa((int)amt)); 373 *p++ = tag; 374 *p = '\0'; 375 376 return(ret); 377 } 378 379 int 380 find_pid(pid_t pid) 381 { 382 kvm_t *kd = NULL; 383 struct kinfo_proc *pbase = NULL; 384 int nproc; 385 int ret = 0; 386 387 kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, NULL); 388 if (kd == NULL) { 389 fprintf(stderr, "top: kvm_open() failed.\n"); 390 quit(TOP_EX_SYS_ERROR); 391 } 392 393 pbase = kvm_getprocs(kd, KERN_PROC_PID, pid, &nproc); 394 if (pbase == NULL) { 395 goto done; 396 } 397 398 if ((nproc == 1) && (pbase->ki_pid == pid)) { 399 ret = 1; 400 } 401 402 done: 403 kvm_close(kd); 404 return ret; 405 } 406