procps.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Utility routines.
  4. *
  5. * Copyright 1998 by Albert Cahalan; all rights reserved.
  6. * Copyright (C) 2002 by Vladimir Oleynik <dzo@simtreas.ru>
  7. * SELinux support: (c) 2007 by Yuichi Nakamura <ynakam@hitachisoft.jp>
  8. *
  9. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  10. */
  11. #include "libbb.h"
  12. typedef struct unsigned_to_name_map_t {
  13. long id;
  14. char name[USERNAME_MAX_SIZE];
  15. } unsigned_to_name_map_t;
  16. typedef struct cache_t {
  17. unsigned_to_name_map_t *cache;
  18. int size;
  19. } cache_t;
  20. static cache_t username, groupname;
  21. static void clear_cache(cache_t *cp)
  22. {
  23. free(cp->cache);
  24. cp->cache = NULL;
  25. cp->size = 0;
  26. }
  27. void FAST_FUNC clear_username_cache(void)
  28. {
  29. clear_cache(&username);
  30. clear_cache(&groupname);
  31. }
  32. #if 0 /* more generic, but we don't need that yet */
  33. /* Returns -N-1 if not found. */
  34. /* cp->cache[N] is allocated and must be filled in this case */
  35. static int get_cached(cache_t *cp, unsigned id)
  36. {
  37. int i;
  38. for (i = 0; i < cp->size; i++)
  39. if (cp->cache[i].id == id)
  40. return i;
  41. i = cp->size++;
  42. cp->cache = xrealloc_vector(cp->cache, 2, i);
  43. cp->cache[i++].id = id;
  44. return -i;
  45. }
  46. #endif
  47. static char* get_cached(cache_t *cp, long id,
  48. char* FAST_FUNC x2x_utoa(long id))
  49. {
  50. int i;
  51. for (i = 0; i < cp->size; i++)
  52. if (cp->cache[i].id == id)
  53. return cp->cache[i].name;
  54. i = cp->size++;
  55. cp->cache = xrealloc_vector(cp->cache, 2, i);
  56. cp->cache[i].id = id;
  57. /* Never fails. Generates numeric string if name isn't found */
  58. safe_strncpy(cp->cache[i].name, x2x_utoa(id), sizeof(cp->cache[i].name));
  59. return cp->cache[i].name;
  60. }
  61. const char* FAST_FUNC get_cached_username(uid_t uid)
  62. {
  63. return get_cached(&username, uid, uid2uname_utoa);
  64. }
  65. const char* FAST_FUNC get_cached_groupname(gid_t gid)
  66. {
  67. return get_cached(&groupname, gid, gid2group_utoa);
  68. }
  69. #define PROCPS_BUFSIZE 1024
  70. static int read_to_buf(const char *filename, void *buf)
  71. {
  72. int fd;
  73. /* open_read_close() would do two reads, checking for EOF.
  74. * When you have 10000 /proc/$NUM/stat to read, it isn't desirable */
  75. ssize_t ret = -1;
  76. fd = open(filename, O_RDONLY);
  77. if (fd >= 0) {
  78. ret = read(fd, buf, PROCPS_BUFSIZE-1);
  79. close(fd);
  80. }
  81. ((char *)buf)[ret > 0 ? ret : 0] = '\0';
  82. return ret;
  83. }
  84. static procps_status_t* FAST_FUNC alloc_procps_scan(void)
  85. {
  86. unsigned n = getpagesize();
  87. procps_status_t* sp = xzalloc(sizeof(procps_status_t));
  88. sp->dir = xopendir("/proc");
  89. while (1) {
  90. n >>= 1;
  91. if (!n) break;
  92. sp->shift_pages_to_bytes++;
  93. }
  94. sp->shift_pages_to_kb = sp->shift_pages_to_bytes - 10;
  95. return sp;
  96. }
  97. void FAST_FUNC free_procps_scan(procps_status_t* sp)
  98. {
  99. closedir(sp->dir);
  100. #if ENABLE_FEATURE_SHOW_THREADS
  101. if (sp->task_dir)
  102. closedir(sp->task_dir);
  103. #endif
  104. free(sp->argv0);
  105. free(sp->exe);
  106. IF_SELINUX(free(sp->context);)
  107. free(sp);
  108. }
  109. #if ENABLE_FEATURE_TOPMEM
  110. static unsigned long fast_strtoul_16(char **endptr)
  111. {
  112. unsigned char c;
  113. char *str = *endptr;
  114. unsigned long n = 0;
  115. while ((c = *str++) != ' ') {
  116. c = ((c|0x20) - '0');
  117. if (c > 9)
  118. // c = c + '0' - 'a' + 10:
  119. c = c - ('a' - '0' - 10);
  120. n = n*16 + c;
  121. }
  122. *endptr = str; /* We skip trailing space! */
  123. return n;
  124. }
  125. /* TOPMEM uses fast_strtoul_10, so... */
  126. # undef ENABLE_FEATURE_FAST_TOP
  127. # define ENABLE_FEATURE_FAST_TOP 1
  128. #endif
  129. #if ENABLE_FEATURE_FAST_TOP
  130. /* We cut a lot of corners here for speed */
  131. static unsigned long fast_strtoul_10(char **endptr)
  132. {
  133. char c;
  134. char *str = *endptr;
  135. unsigned long n = *str - '0';
  136. while ((c = *++str) != ' ')
  137. n = n*10 + (c - '0');
  138. *endptr = str + 1; /* We skip trailing space! */
  139. return n;
  140. }
  141. static long fast_strtol_10(char **endptr)
  142. {
  143. if (**endptr != '-')
  144. return fast_strtoul_10(endptr);
  145. (*endptr)++;
  146. return - (long)fast_strtoul_10(endptr);
  147. }
  148. static char *skip_fields(char *str, int count)
  149. {
  150. do {
  151. while (*str++ != ' ')
  152. continue;
  153. /* we found a space char, str points after it */
  154. } while (--count);
  155. return str;
  156. }
  157. #endif
  158. void BUG_comm_size(void);
  159. procps_status_t* FAST_FUNC procps_scan(procps_status_t* sp, int flags)
  160. {
  161. struct dirent *entry;
  162. char buf[PROCPS_BUFSIZE];
  163. char filename[sizeof("/proc//cmdline") + sizeof(int)*3];
  164. char *filename_tail;
  165. long tasknice;
  166. unsigned pid;
  167. int n;
  168. struct stat sb;
  169. if (!sp)
  170. sp = alloc_procps_scan();
  171. for (;;) {
  172. #if ENABLE_FEATURE_SHOW_THREADS
  173. if ((flags & PSSCAN_TASKS) && sp->task_dir) {
  174. entry = readdir(sp->task_dir);
  175. if (entry)
  176. goto got_entry;
  177. closedir(sp->task_dir);
  178. sp->task_dir = NULL;
  179. }
  180. #endif
  181. entry = readdir(sp->dir);
  182. if (entry == NULL) {
  183. free_procps_scan(sp);
  184. return NULL;
  185. }
  186. IF_FEATURE_SHOW_THREADS(got_entry:)
  187. pid = bb_strtou(entry->d_name, NULL, 10);
  188. if (errno)
  189. continue;
  190. #if ENABLE_FEATURE_SHOW_THREADS
  191. if ((flags & PSSCAN_TASKS) && !sp->task_dir) {
  192. /* We found another /proc/PID. Do not use it,
  193. * there will be /proc/PID/task/PID (same PID!),
  194. * so just go ahead and dive into /proc/PID/task. */
  195. char task_dir[sizeof("/proc/%u/task") + sizeof(int)*3];
  196. sprintf(task_dir, "/proc/%u/task", pid);
  197. sp->task_dir = xopendir(task_dir);
  198. continue;
  199. }
  200. #endif
  201. /* After this point we can:
  202. * "break": stop parsing, return the data
  203. * "continue": try next /proc/XXX
  204. */
  205. memset(&sp->vsz, 0, sizeof(*sp) - offsetof(procps_status_t, vsz));
  206. sp->pid = pid;
  207. if (!(flags & ~PSSCAN_PID))
  208. break; /* we needed only pid, we got it */
  209. #if ENABLE_SELINUX
  210. if (flags & PSSCAN_CONTEXT) {
  211. if (getpidcon(sp->pid, &sp->context) < 0)
  212. sp->context = NULL;
  213. }
  214. #endif
  215. filename_tail = filename + sprintf(filename, "/proc/%u/", pid);
  216. if (flags & PSSCAN_UIDGID) {
  217. if (stat(filename, &sb))
  218. continue; /* process probably exited */
  219. /* Effective UID/GID, not real */
  220. sp->uid = sb.st_uid;
  221. sp->gid = sb.st_gid;
  222. }
  223. if (flags & PSSCAN_STAT) {
  224. char *cp, *comm1;
  225. int tty;
  226. #if !ENABLE_FEATURE_FAST_TOP
  227. unsigned long vsz, rss;
  228. #endif
  229. /* see proc(5) for some details on this */
  230. strcpy(filename_tail, "stat");
  231. n = read_to_buf(filename, buf);
  232. if (n < 0)
  233. continue; /* process probably exited */
  234. cp = strrchr(buf, ')'); /* split into "PID (cmd" and "<rest>" */
  235. /*if (!cp || cp[1] != ' ')
  236. continue;*/
  237. cp[0] = '\0';
  238. if (sizeof(sp->comm) < 16)
  239. BUG_comm_size();
  240. comm1 = strchr(buf, '(');
  241. /*if (comm1)*/
  242. safe_strncpy(sp->comm, comm1 + 1, sizeof(sp->comm));
  243. #if !ENABLE_FEATURE_FAST_TOP
  244. n = sscanf(cp+2,
  245. "%c %u " /* state, ppid */
  246. "%u %u %d %*s " /* pgid, sid, tty, tpgid */
  247. "%*s %*s %*s %*s %*s " /* flags, min_flt, cmin_flt, maj_flt, cmaj_flt */
  248. "%lu %lu " /* utime, stime */
  249. "%*s %*s %*s " /* cutime, cstime, priority */
  250. "%ld " /* nice */
  251. "%*s %*s " /* timeout, it_real_value */
  252. "%lu " /* start_time */
  253. "%lu " /* vsize */
  254. "%lu " /* rss */
  255. # if ENABLE_FEATURE_TOP_SMP_PROCESS
  256. "%*s %*s %*s %*s %*s %*s " /*rss_rlim, start_code, end_code, start_stack, kstk_esp, kstk_eip */
  257. "%*s %*s %*s %*s " /*signal, blocked, sigignore, sigcatch */
  258. "%*s %*s %*s %*s " /*wchan, nswap, cnswap, exit_signal */
  259. "%d" /*cpu last seen on*/
  260. # endif
  261. ,
  262. sp->state, &sp->ppid,
  263. &sp->pgid, &sp->sid, &tty,
  264. &sp->utime, &sp->stime,
  265. &tasknice,
  266. &sp->start_time,
  267. &vsz,
  268. &rss
  269. # if ENABLE_FEATURE_TOP_SMP_PROCESS
  270. , &sp->last_seen_on_cpu
  271. # endif
  272. );
  273. if (n < 11)
  274. continue; /* bogus data, get next /proc/XXX */
  275. # if ENABLE_FEATURE_TOP_SMP_PROCESS
  276. if (n < 11+15)
  277. sp->last_seen_on_cpu = 0;
  278. # endif
  279. /* vsz is in bytes and we want kb */
  280. sp->vsz = vsz >> 10;
  281. /* vsz is in bytes but rss is in *PAGES*! Can you believe that? */
  282. sp->rss = rss << sp->shift_pages_to_kb;
  283. sp->tty_major = (tty >> 8) & 0xfff;
  284. sp->tty_minor = (tty & 0xff) | ((tty >> 12) & 0xfff00);
  285. #else
  286. /* This costs ~100 bytes more but makes top faster by 20%
  287. * If you run 10000 processes, this may be important for you */
  288. sp->state[0] = cp[2];
  289. cp += 4;
  290. sp->ppid = fast_strtoul_10(&cp);
  291. sp->pgid = fast_strtoul_10(&cp);
  292. sp->sid = fast_strtoul_10(&cp);
  293. tty = fast_strtoul_10(&cp);
  294. sp->tty_major = (tty >> 8) & 0xfff;
  295. sp->tty_minor = (tty & 0xff) | ((tty >> 12) & 0xfff00);
  296. cp = skip_fields(cp, 6); /* tpgid, flags, min_flt, cmin_flt, maj_flt, cmaj_flt */
  297. sp->utime = fast_strtoul_10(&cp);
  298. sp->stime = fast_strtoul_10(&cp);
  299. cp = skip_fields(cp, 3); /* cutime, cstime, priority */
  300. tasknice = fast_strtol_10(&cp);
  301. cp = skip_fields(cp, 2); /* timeout, it_real_value */
  302. sp->start_time = fast_strtoul_10(&cp);
  303. /* vsz is in bytes and we want kb */
  304. sp->vsz = fast_strtoul_10(&cp) >> 10;
  305. /* vsz is in bytes but rss is in *PAGES*! Can you believe that? */
  306. sp->rss = fast_strtoul_10(&cp) << sp->shift_pages_to_kb;
  307. # if ENABLE_FEATURE_TOP_SMP_PROCESS
  308. /* (6): rss_rlim, start_code, end_code, start_stack, kstk_esp, kstk_eip */
  309. /* (4): signal, blocked, sigignore, sigcatch */
  310. /* (4): wchan, nswap, cnswap, exit_signal */
  311. cp = skip_fields(cp, 14);
  312. //FIXME: is it safe to assume this field exists?
  313. sp->last_seen_on_cpu = fast_strtoul_10(&cp);
  314. # endif
  315. #endif /* end of !ENABLE_FEATURE_TOP_SMP_PROCESS */
  316. #if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
  317. sp->niceness = tasknice;
  318. #endif
  319. if (sp->vsz == 0 && sp->state[0] != 'Z')
  320. sp->state[1] = 'W';
  321. else
  322. sp->state[1] = ' ';
  323. if (tasknice < 0)
  324. sp->state[2] = '<';
  325. else if (tasknice) /* > 0 */
  326. sp->state[2] = 'N';
  327. else
  328. sp->state[2] = ' ';
  329. }
  330. #if ENABLE_FEATURE_TOPMEM
  331. if (flags & (PSSCAN_SMAPS)) {
  332. FILE *file;
  333. strcpy(filename_tail, "smaps");
  334. file = fopen_for_read(filename);
  335. if (file) {
  336. while (fgets(buf, sizeof(buf), file)) {
  337. unsigned long sz;
  338. char *tp;
  339. char w;
  340. #define SCAN(str, name) \
  341. if (strncmp(buf, str, sizeof(str)-1) == 0) { \
  342. tp = skip_whitespace(buf + sizeof(str)-1); \
  343. sp->name += fast_strtoul_10(&tp); \
  344. continue; \
  345. }
  346. SCAN("Shared_Clean:" , shared_clean );
  347. SCAN("Shared_Dirty:" , shared_dirty );
  348. SCAN("Private_Clean:", private_clean);
  349. SCAN("Private_Dirty:", private_dirty);
  350. #undef SCAN
  351. // f7d29000-f7d39000 rw-s ADR M:m OFS FILE
  352. tp = strchr(buf, '-');
  353. if (tp) {
  354. *tp = ' ';
  355. tp = buf;
  356. sz = fast_strtoul_16(&tp); /* start */
  357. sz = (fast_strtoul_16(&tp) - sz) >> 10; /* end - start */
  358. // tp -> "rw-s" string
  359. w = tp[1];
  360. // skipping "rw-s ADR M:m OFS "
  361. tp = skip_whitespace(skip_fields(tp, 4));
  362. // filter out /dev/something (something != zero)
  363. if (strncmp(tp, "/dev/", 5) != 0 || strcmp(tp, "/dev/zero\n") == 0) {
  364. if (w == 'w') {
  365. sp->mapped_rw += sz;
  366. } else if (w == '-') {
  367. sp->mapped_ro += sz;
  368. }
  369. }
  370. //else printf("DROPPING %s (%s)\n", buf, tp);
  371. if (strcmp(tp, "[stack]\n") == 0)
  372. sp->stack += sz;
  373. }
  374. }
  375. fclose(file);
  376. }
  377. }
  378. #endif /* TOPMEM */
  379. #if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
  380. if (flags & PSSCAN_RUIDGID) {
  381. FILE *file;
  382. strcpy(filename_tail, "status");
  383. file = fopen_for_read(filename);
  384. if (file) {
  385. while (fgets(buf, sizeof(buf), file)) {
  386. char *tp;
  387. #define SCAN_TWO(str, name, statement) \
  388. if (strncmp(buf, str, sizeof(str)-1) == 0) { \
  389. tp = skip_whitespace(buf + sizeof(str)-1); \
  390. sscanf(tp, "%u", &sp->name); \
  391. statement; \
  392. }
  393. SCAN_TWO("Uid:", ruid, continue);
  394. SCAN_TWO("Gid:", rgid, break);
  395. #undef SCAN_TWO
  396. }
  397. fclose(file);
  398. }
  399. }
  400. #endif /* PS_ADDITIONAL_COLUMNS */
  401. if (flags & PSSCAN_EXE) {
  402. strcpy(filename_tail, "exe");
  403. free(sp->exe);
  404. sp->exe = xmalloc_readlink(filename);
  405. }
  406. /* Note: if /proc/PID/cmdline is empty,
  407. * code below "breaks". Therefore it must be
  408. * the last code to parse /proc/PID/xxx data
  409. * (we used to have /proc/PID/exe parsing after it
  410. * and were getting stale sp->exe).
  411. */
  412. #if 0 /* PSSCAN_CMD is not used */
  413. if (flags & (PSSCAN_CMD|PSSCAN_ARGV0)) {
  414. free(sp->argv0);
  415. sp->argv0 = NULL;
  416. free(sp->cmd);
  417. sp->cmd = NULL;
  418. strcpy(filename_tail, "cmdline");
  419. /* TODO: to get rid of size limits, read into malloc buf,
  420. * then realloc it down to real size. */
  421. n = read_to_buf(filename, buf);
  422. if (n <= 0)
  423. break;
  424. if (flags & PSSCAN_ARGV0)
  425. sp->argv0 = xstrdup(buf);
  426. if (flags & PSSCAN_CMD) {
  427. do {
  428. n--;
  429. if ((unsigned char)(buf[n]) < ' ')
  430. buf[n] = ' ';
  431. } while (n);
  432. sp->cmd = xstrdup(buf);
  433. }
  434. }
  435. #else
  436. if (flags & (PSSCAN_ARGV0|PSSCAN_ARGVN)) {
  437. free(sp->argv0);
  438. sp->argv0 = NULL;
  439. strcpy(filename_tail, "cmdline");
  440. n = read_to_buf(filename, buf);
  441. if (n <= 0)
  442. break;
  443. if (flags & PSSCAN_ARGVN) {
  444. sp->argv_len = n;
  445. sp->argv0 = xmalloc(n + 1);
  446. memcpy(sp->argv0, buf, n + 1);
  447. /* sp->argv0[n] = '\0'; - buf has it */
  448. } else {
  449. sp->argv_len = 0;
  450. sp->argv0 = xstrdup(buf);
  451. }
  452. }
  453. #endif
  454. break;
  455. } /* for (;;) */
  456. return sp;
  457. }
  458. void FAST_FUNC read_cmdline(char *buf, int col, unsigned pid, const char *comm)
  459. {
  460. int sz;
  461. char filename[sizeof("/proc//cmdline") + sizeof(int)*3];
  462. sprintf(filename, "/proc/%u/cmdline", pid);
  463. sz = open_read_close(filename, buf, col - 1);
  464. if (sz > 0) {
  465. buf[sz] = '\0';
  466. while (--sz >= 0 && buf[sz] == '\0')
  467. continue;
  468. do {
  469. if ((unsigned char)(buf[sz]) < ' ')
  470. buf[sz] = ' ';
  471. } while (--sz >= 0);
  472. } else {
  473. snprintf(buf, col, "[%s]", comm);
  474. }
  475. }
  476. /* from kernel:
  477. // pid comm S ppid pgid sid tty_nr tty_pgrp flg
  478. sprintf(buffer,"%d (%s) %c %d %d %d %d %d %lu %lu \
  479. %lu %lu %lu %lu %lu %ld %ld %ld %ld %d 0 %llu %lu %ld %lu %lu %lu %lu %lu \
  480. %lu %lu %lu %lu %lu %lu %lu %lu %d %d %lu %lu %llu\n",
  481. task->pid,
  482. tcomm,
  483. state,
  484. ppid,
  485. pgid,
  486. sid,
  487. tty_nr,
  488. tty_pgrp,
  489. task->flags,
  490. min_flt,
  491. cmin_flt,
  492. maj_flt,
  493. cmaj_flt,
  494. cputime_to_clock_t(utime),
  495. cputime_to_clock_t(stime),
  496. cputime_to_clock_t(cutime),
  497. cputime_to_clock_t(cstime),
  498. priority,
  499. nice,
  500. num_threads,
  501. // 0,
  502. start_time,
  503. vsize,
  504. mm ? get_mm_rss(mm) : 0,
  505. rsslim,
  506. mm ? mm->start_code : 0,
  507. mm ? mm->end_code : 0,
  508. mm ? mm->start_stack : 0,
  509. esp,
  510. eip,
  511. the rest is some obsolete cruft
  512. */