procps.c 12 KB

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