procps.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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. free(sp->argv0);
  101. IF_SELINUX(free(sp->context);)
  102. free(sp);
  103. }
  104. #if ENABLE_FEATURE_TOPMEM
  105. static unsigned long fast_strtoul_16(char **endptr)
  106. {
  107. unsigned char c;
  108. char *str = *endptr;
  109. unsigned long n = 0;
  110. while ((c = *str++) != ' ') {
  111. c = ((c|0x20) - '0');
  112. if (c > 9)
  113. // c = c + '0' - 'a' + 10:
  114. c = c - ('a' - '0' - 10);
  115. n = n*16 + c;
  116. }
  117. *endptr = str; /* We skip trailing space! */
  118. return n;
  119. }
  120. /* TOPMEM uses fast_strtoul_10, so... */
  121. #undef ENABLE_FEATURE_FAST_TOP
  122. #define ENABLE_FEATURE_FAST_TOP 1
  123. #endif
  124. #if ENABLE_FEATURE_FAST_TOP
  125. /* We cut a lot of corners here for speed */
  126. static unsigned long fast_strtoul_10(char **endptr)
  127. {
  128. char c;
  129. char *str = *endptr;
  130. unsigned long n = *str - '0';
  131. while ((c = *++str) != ' ')
  132. n = n*10 + (c - '0');
  133. *endptr = str + 1; /* We skip trailing space! */
  134. return n;
  135. }
  136. static long fast_strtol_10(char **endptr)
  137. {
  138. if (**endptr != '-')
  139. return fast_strtoul_10(endptr);
  140. (*endptr)++;
  141. return - (long)fast_strtoul_10(endptr);
  142. }
  143. static char *skip_fields(char *str, int count)
  144. {
  145. do {
  146. while (*str++ != ' ')
  147. continue;
  148. /* we found a space char, str points after it */
  149. } while (--count);
  150. return str;
  151. }
  152. #endif
  153. void BUG_comm_size(void);
  154. procps_status_t* FAST_FUNC procps_scan(procps_status_t* sp, int flags)
  155. {
  156. struct dirent *entry;
  157. char buf[PROCPS_BUFSIZE];
  158. char filename[sizeof("/proc//cmdline") + sizeof(int)*3];
  159. char *filename_tail;
  160. long tasknice;
  161. unsigned pid;
  162. int n;
  163. struct stat sb;
  164. if (!sp)
  165. sp = alloc_procps_scan();
  166. for (;;) {
  167. entry = readdir(sp->dir);
  168. if (entry == NULL) {
  169. free_procps_scan(sp);
  170. return NULL;
  171. }
  172. pid = bb_strtou(entry->d_name, NULL, 10);
  173. if (errno)
  174. continue;
  175. /* After this point we have to break, not continue
  176. * ("continue" would mean that current /proc/NNN
  177. * is not a valid process info) */
  178. memset(&sp->vsz, 0, sizeof(*sp) - offsetof(procps_status_t, vsz));
  179. sp->pid = pid;
  180. if (!(flags & ~PSSCAN_PID)) break;
  181. #if ENABLE_SELINUX
  182. if (flags & PSSCAN_CONTEXT) {
  183. if (getpidcon(sp->pid, &sp->context) < 0)
  184. sp->context = NULL;
  185. }
  186. #endif
  187. filename_tail = filename + sprintf(filename, "/proc/%d", pid);
  188. if (flags & PSSCAN_UIDGID) {
  189. if (stat(filename, &sb))
  190. break;
  191. /* Effective UID/GID, not real */
  192. sp->uid = sb.st_uid;
  193. sp->gid = sb.st_gid;
  194. }
  195. if (flags & PSSCAN_STAT) {
  196. char *cp, *comm1;
  197. int tty;
  198. #if !ENABLE_FEATURE_FAST_TOP
  199. unsigned long vsz, rss;
  200. #endif
  201. /* see proc(5) for some details on this */
  202. strcpy(filename_tail, "/stat");
  203. n = read_to_buf(filename, buf);
  204. if (n < 0)
  205. break;
  206. cp = strrchr(buf, ')'); /* split into "PID (cmd" and "<rest>" */
  207. /*if (!cp || cp[1] != ' ')
  208. break;*/
  209. cp[0] = '\0';
  210. if (sizeof(sp->comm) < 16)
  211. BUG_comm_size();
  212. comm1 = strchr(buf, '(');
  213. /*if (comm1)*/
  214. safe_strncpy(sp->comm, comm1 + 1, sizeof(sp->comm));
  215. #if !ENABLE_FEATURE_FAST_TOP
  216. n = sscanf(cp+2,
  217. "%c %u " /* state, ppid */
  218. "%u %u %d %*s " /* pgid, sid, tty, tpgid */
  219. "%*s %*s %*s %*s %*s " /* flags, min_flt, cmin_flt, maj_flt, cmaj_flt */
  220. "%lu %lu " /* utime, stime */
  221. "%*s %*s %*s " /* cutime, cstime, priority */
  222. "%ld " /* nice */
  223. "%*s %*s " /* timeout, it_real_value */
  224. "%lu " /* start_time */
  225. "%lu " /* vsize */
  226. "%lu " /* rss */
  227. #if ENABLE_FEATURE_TOP_SMP_PROCESS
  228. "%*s %*s %*s %*s %*s %*s " /*rss_rlim, start_code, end_code, start_stack, kstk_esp, kstk_eip */
  229. "%*s %*s %*s %*s " /*signal, blocked, sigignore, sigcatch */
  230. "%*s %*s %*s %*s " /*wchan, nswap, cnswap, exit_signal */
  231. "%d" /*cpu last seen on*/
  232. #endif
  233. ,
  234. sp->state, &sp->ppid,
  235. &sp->pgid, &sp->sid, &tty,
  236. &sp->utime, &sp->stime,
  237. &tasknice,
  238. &sp->start_time,
  239. &vsz,
  240. &rss
  241. #if ENABLE_FEATURE_TOP_SMP_PROCESS
  242. , &sp->last_seen_on_cpu
  243. #endif
  244. );
  245. if (n < 11)
  246. break;
  247. #if ENABLE_FEATURE_TOP_SMP_PROCESS
  248. if (n < 11+15)
  249. sp->last_seen_on_cpu = 0;
  250. #endif
  251. /* vsz is in bytes and we want kb */
  252. sp->vsz = vsz >> 10;
  253. /* vsz is in bytes but rss is in *PAGES*! Can you believe that? */
  254. sp->rss = rss << sp->shift_pages_to_kb;
  255. sp->tty_major = (tty >> 8) & 0xfff;
  256. sp->tty_minor = (tty & 0xff) | ((tty >> 12) & 0xfff00);
  257. #else
  258. /* This costs ~100 bytes more but makes top faster by 20%
  259. * If you run 10000 processes, this may be important for you */
  260. sp->state[0] = cp[2];
  261. cp += 4;
  262. sp->ppid = fast_strtoul_10(&cp);
  263. sp->pgid = fast_strtoul_10(&cp);
  264. sp->sid = fast_strtoul_10(&cp);
  265. tty = fast_strtoul_10(&cp);
  266. sp->tty_major = (tty >> 8) & 0xfff;
  267. sp->tty_minor = (tty & 0xff) | ((tty >> 12) & 0xfff00);
  268. cp = skip_fields(cp, 6); /* tpgid, flags, min_flt, cmin_flt, maj_flt, cmaj_flt */
  269. sp->utime = fast_strtoul_10(&cp);
  270. sp->stime = fast_strtoul_10(&cp);
  271. cp = skip_fields(cp, 3); /* cutime, cstime, priority */
  272. tasknice = fast_strtol_10(&cp);
  273. cp = skip_fields(cp, 2); /* timeout, it_real_value */
  274. sp->start_time = fast_strtoul_10(&cp);
  275. /* vsz is in bytes and we want kb */
  276. sp->vsz = fast_strtoul_10(&cp) >> 10;
  277. /* vsz is in bytes but rss is in *PAGES*! Can you believe that? */
  278. sp->rss = fast_strtoul_10(&cp) << sp->shift_pages_to_kb;
  279. #if ENABLE_FEATURE_TOP_SMP_PROCESS
  280. /* (6): rss_rlim, start_code, end_code, start_stack, kstk_esp, kstk_eip */
  281. /* (4): signal, blocked, sigignore, sigcatch */
  282. /* (4): wchan, nswap, cnswap, exit_signal */
  283. cp = skip_fields(cp, 14);
  284. //FIXME: is it safe to assume this field exists?
  285. sp->last_seen_on_cpu = fast_strtoul_10(&cp);
  286. #endif
  287. #endif /* end of !ENABLE_FEATURE_TOP_SMP_PROCESS */
  288. #if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
  289. sp->niceness = tasknice;
  290. #endif
  291. if (sp->vsz == 0 && sp->state[0] != 'Z')
  292. sp->state[1] = 'W';
  293. else
  294. sp->state[1] = ' ';
  295. if (tasknice < 0)
  296. sp->state[2] = '<';
  297. else if (tasknice) /* > 0 */
  298. sp->state[2] = 'N';
  299. else
  300. sp->state[2] = ' ';
  301. }
  302. #if ENABLE_FEATURE_TOPMEM
  303. if (flags & (PSSCAN_SMAPS)) {
  304. FILE *file;
  305. strcpy(filename_tail, "/smaps");
  306. file = fopen_for_read(filename);
  307. if (!file)
  308. break;
  309. while (fgets(buf, sizeof(buf), file)) {
  310. unsigned long sz;
  311. char *tp;
  312. char w;
  313. #define SCAN(str, name) \
  314. if (strncmp(buf, str, sizeof(str)-1) == 0) { \
  315. tp = skip_whitespace(buf + sizeof(str)-1); \
  316. sp->name += fast_strtoul_10(&tp); \
  317. continue; \
  318. }
  319. SCAN("Shared_Clean:" , shared_clean );
  320. SCAN("Shared_Dirty:" , shared_dirty );
  321. SCAN("Private_Clean:", private_clean);
  322. SCAN("Private_Dirty:", private_dirty);
  323. #undef SCAN
  324. // f7d29000-f7d39000 rw-s ADR M:m OFS FILE
  325. tp = strchr(buf, '-');
  326. if (tp) {
  327. *tp = ' ';
  328. tp = buf;
  329. sz = fast_strtoul_16(&tp); /* start */
  330. sz = (fast_strtoul_16(&tp) - sz) >> 10; /* end - start */
  331. // tp -> "rw-s" string
  332. w = tp[1];
  333. // skipping "rw-s ADR M:m OFS "
  334. tp = skip_whitespace(skip_fields(tp, 4));
  335. // filter out /dev/something (something != zero)
  336. if (strncmp(tp, "/dev/", 5) != 0 || strcmp(tp, "/dev/zero\n") == 0) {
  337. if (w == 'w') {
  338. sp->mapped_rw += sz;
  339. } else if (w == '-') {
  340. sp->mapped_ro += sz;
  341. }
  342. }
  343. //else printf("DROPPING %s (%s)\n", buf, tp);
  344. if (strcmp(tp, "[stack]\n") == 0)
  345. sp->stack += sz;
  346. }
  347. }
  348. fclose(file);
  349. }
  350. #endif /* TOPMEM */
  351. #if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
  352. if (flags & PSSCAN_RUIDGID) {
  353. FILE *file;
  354. strcpy(filename_tail, "/status");
  355. file = fopen_for_read(filename);
  356. if (!file)
  357. break;
  358. while (fgets(buf, sizeof(buf), file)) {
  359. char *tp;
  360. #define SCAN_TWO(str, name, statement) \
  361. if (strncmp(buf, str, sizeof(str)-1) == 0) { \
  362. tp = skip_whitespace(buf + sizeof(str)-1); \
  363. sscanf(tp, "%u", &sp->name); \
  364. statement; \
  365. }
  366. SCAN_TWO("Uid:", ruid, continue);
  367. SCAN_TWO("Gid:", rgid, break);
  368. #undef SCAN_TWO
  369. }
  370. fclose(file);
  371. }
  372. #endif /* PS_ADDITIONAL_COLUMNS */
  373. #if 0 /* PSSCAN_CMD is not used */
  374. if (flags & (PSSCAN_CMD|PSSCAN_ARGV0)) {
  375. free(sp->argv0);
  376. sp->argv0 = NULL;
  377. free(sp->cmd);
  378. sp->cmd = NULL;
  379. strcpy(filename_tail, "/cmdline");
  380. /* TODO: to get rid of size limits, read into malloc buf,
  381. * then realloc it down to real size. */
  382. n = read_to_buf(filename, buf);
  383. if (n <= 0)
  384. break;
  385. if (flags & PSSCAN_ARGV0)
  386. sp->argv0 = xstrdup(buf);
  387. if (flags & PSSCAN_CMD) {
  388. do {
  389. n--;
  390. if ((unsigned char)(buf[n]) < ' ')
  391. buf[n] = ' ';
  392. } while (n);
  393. sp->cmd = xstrdup(buf);
  394. }
  395. }
  396. #else
  397. if (flags & (PSSCAN_ARGV0|PSSCAN_ARGVN)) {
  398. free(sp->argv0);
  399. sp->argv0 = NULL;
  400. strcpy(filename_tail, "/cmdline");
  401. n = read_to_buf(filename, buf);
  402. if (n <= 0)
  403. break;
  404. if (flags & PSSCAN_ARGVN) {
  405. sp->argv_len = n;
  406. sp->argv0 = xmalloc(n + 1);
  407. memcpy(sp->argv0, buf, n + 1);
  408. /* sp->argv0[n] = '\0'; - buf has it */
  409. } else {
  410. sp->argv_len = 0;
  411. sp->argv0 = xstrdup(buf);
  412. }
  413. }
  414. #endif
  415. break;
  416. }
  417. return sp;
  418. }
  419. void FAST_FUNC read_cmdline(char *buf, int col, unsigned pid, const char *comm)
  420. {
  421. ssize_t sz;
  422. char filename[sizeof("/proc//cmdline") + sizeof(int)*3];
  423. sprintf(filename, "/proc/%u/cmdline", pid);
  424. sz = open_read_close(filename, buf, col);
  425. if (sz > 0) {
  426. buf[sz] = '\0';
  427. while (--sz >= 0)
  428. if ((unsigned char)(buf[sz]) < ' ')
  429. buf[sz] = ' ';
  430. } else {
  431. snprintf(buf, col, "[%s]", comm);
  432. }
  433. }
  434. /* from kernel:
  435. // pid comm S ppid pgid sid tty_nr tty_pgrp flg
  436. sprintf(buffer,"%d (%s) %c %d %d %d %d %d %lu %lu \
  437. %lu %lu %lu %lu %lu %ld %ld %ld %ld %d 0 %llu %lu %ld %lu %lu %lu %lu %lu \
  438. %lu %lu %lu %lu %lu %lu %lu %lu %d %d %lu %lu %llu\n",
  439. task->pid,
  440. tcomm,
  441. state,
  442. ppid,
  443. pgid,
  444. sid,
  445. tty_nr,
  446. tty_pgrp,
  447. task->flags,
  448. min_flt,
  449. cmin_flt,
  450. maj_flt,
  451. cmaj_flt,
  452. cputime_to_clock_t(utime),
  453. cputime_to_clock_t(stime),
  454. cputime_to_clock_t(cutime),
  455. cputime_to_clock_t(cstime),
  456. priority,
  457. nice,
  458. num_threads,
  459. // 0,
  460. start_time,
  461. vsize,
  462. mm ? get_mm_rss(mm) : 0,
  463. rsslim,
  464. mm ? mm->start_code : 0,
  465. mm ? mm->end_code : 0,
  466. mm ? mm->start_stack : 0,
  467. esp,
  468. eip,
  469. the rest is some obsolete cruft
  470. */