procps.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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 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(cp->cache, cp->size * sizeof(*cp->cache));
  43. cp->cache[i++].id = id;
  44. return -i;
  45. }
  46. #endif
  47. typedef char* 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(cp->cache, cp->size * sizeof(*cp->cache));
  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* get_cached_username(uid_t uid)
  62. {
  63. return get_cached(&username, uid, bb_getpwuid);
  64. }
  65. const char* 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 *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 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 *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. /* "%lu %lu %lu %lu %lu %lu " rss_rlim, start_code, end_code, start_stack, kstk_esp, kstk_eip */
  221. /* "%u %u %u %u " signal, blocked, sigignore, sigcatch */
  222. /* "%lu %lu %lu" wchan, nswap, cnswap */
  223. ,
  224. sp->state, &sp->ppid,
  225. &sp->pgid, &sp->sid, &tty,
  226. &sp->utime, &sp->stime,
  227. &tasknice,
  228. &sp->start_time,
  229. &vsz,
  230. &rss);
  231. if (n != 11)
  232. break;
  233. /* vsz is in bytes and we want kb */
  234. sp->vsz = vsz >> 10;
  235. /* vsz is in bytes but rss is in *PAGES*! Can you believe that? */
  236. sp->rss = rss << sp->shift_pages_to_kb;
  237. sp->tty_major = (tty >> 8) & 0xfff;
  238. sp->tty_minor = (tty & 0xff) | ((tty >> 12) & 0xfff00);
  239. #else
  240. /* This costs ~100 bytes more but makes top faster by 20%
  241. * If you run 10000 processes, this may be important for you */
  242. sp->state[0] = cp[2];
  243. cp += 4;
  244. sp->ppid = fast_strtoul_10(&cp);
  245. sp->pgid = fast_strtoul_10(&cp);
  246. sp->sid = fast_strtoul_10(&cp);
  247. tty = fast_strtoul_10(&cp);
  248. sp->tty_major = (tty >> 8) & 0xfff;
  249. sp->tty_minor = (tty & 0xff) | ((tty >> 12) & 0xfff00);
  250. cp = skip_fields(cp, 6); /* tpgid, flags, min_flt, cmin_flt, maj_flt, cmaj_flt */
  251. sp->utime = fast_strtoul_10(&cp);
  252. sp->stime = fast_strtoul_10(&cp);
  253. cp = skip_fields(cp, 3); /* cutime, cstime, priority */
  254. tasknice = fast_strtoul_10(&cp);
  255. cp = skip_fields(cp, 2); /* timeout, it_real_value */
  256. sp->start_time = fast_strtoul_10(&cp);
  257. /* vsz is in bytes and we want kb */
  258. sp->vsz = fast_strtoul_10(&cp) >> 10;
  259. /* vsz is in bytes but rss is in *PAGES*! Can you believe that? */
  260. sp->rss = fast_strtoul_10(&cp) << sp->shift_pages_to_kb;
  261. #endif
  262. if (sp->vsz == 0 && sp->state[0] != 'Z')
  263. sp->state[1] = 'W';
  264. else
  265. sp->state[1] = ' ';
  266. if (tasknice < 0)
  267. sp->state[2] = '<';
  268. else if (tasknice) /* > 0 */
  269. sp->state[2] = 'N';
  270. else
  271. sp->state[2] = ' ';
  272. }
  273. #if ENABLE_FEATURE_TOPMEM
  274. if (flags & (PSSCAN_SMAPS)) {
  275. FILE *file;
  276. strcpy(filename_tail, "/smaps");
  277. file = fopen(filename, "r");
  278. if (!file)
  279. break;
  280. while (fgets(buf, sizeof(buf), file)) {
  281. unsigned long sz;
  282. char *tp;
  283. char w;
  284. #define SCAN(str, name) \
  285. if (strncmp(buf, str, sizeof(str)-1) == 0) { \
  286. tp = skip_whitespace(buf + sizeof(str)-1); \
  287. sp->name += fast_strtoul_10(&tp); \
  288. continue; \
  289. }
  290. SCAN("Shared_Clean:" , shared_clean );
  291. SCAN("Shared_Dirty:" , shared_dirty );
  292. SCAN("Private_Clean:", private_clean);
  293. SCAN("Private_Dirty:", private_dirty);
  294. #undef SCAN
  295. // f7d29000-f7d39000 rw-s ADR M:m OFS FILE
  296. tp = strchr(buf, '-');
  297. if (tp) {
  298. *tp = ' ';
  299. tp = buf;
  300. sz = fast_strtoul_16(&tp); /* start */
  301. sz = (fast_strtoul_16(&tp) - sz) >> 10; /* end - start */
  302. // tp -> "rw-s" string
  303. w = tp[1];
  304. // skipping "rw-s ADR M:m OFS "
  305. tp = skip_whitespace(skip_fields(tp, 4));
  306. // filter out /dev/something (something != zero)
  307. if (strncmp(tp, "/dev/", 5) != 0 || strcmp(tp, "/dev/zero\n") == 0) {
  308. if (w == 'w') {
  309. sp->mapped_rw += sz;
  310. } else if (w == '-') {
  311. sp->mapped_ro += sz;
  312. }
  313. }
  314. //else printf("DROPPING %s (%s)\n", buf, tp);
  315. if (strcmp(tp, "[stack]\n") == 0)
  316. sp->stack += sz;
  317. }
  318. }
  319. fclose(file);
  320. }
  321. #endif /* TOPMEM */
  322. #if 0 /* PSSCAN_CMD is not used */
  323. if (flags & (PSSCAN_CMD|PSSCAN_ARGV0)) {
  324. free(sp->argv0);
  325. sp->argv0 = NULL;
  326. free(sp->cmd);
  327. sp->cmd = NULL;
  328. strcpy(filename_tail, "/cmdline");
  329. /* TODO: to get rid of size limits, read into malloc buf,
  330. * then realloc it down to real size. */
  331. n = read_to_buf(filename, buf);
  332. if (n <= 0)
  333. break;
  334. if (flags & PSSCAN_ARGV0)
  335. sp->argv0 = xstrdup(buf);
  336. if (flags & PSSCAN_CMD) {
  337. do {
  338. n--;
  339. if ((unsigned char)(buf[n]) < ' ')
  340. buf[n] = ' ';
  341. } while (n);
  342. sp->cmd = xstrdup(buf);
  343. }
  344. }
  345. #else
  346. if (flags & (PSSCAN_ARGV0|PSSCAN_ARGVN)) {
  347. free(sp->argv0);
  348. sp->argv0 = NULL;
  349. strcpy(filename_tail, "/cmdline");
  350. n = read_to_buf(filename, buf);
  351. if (n <= 0)
  352. break;
  353. #if ENABLE_PGREP || ENABLE_PKILL
  354. if (flags & PSSCAN_ARGVN) {
  355. do {
  356. n--;
  357. if (buf[n] == '\0')
  358. buf[n] = ' ';
  359. } while (n);
  360. }
  361. #endif
  362. sp->argv0 = xstrdup(buf);
  363. }
  364. #endif
  365. break;
  366. }
  367. return sp;
  368. }
  369. void read_cmdline(char *buf, int col, unsigned pid, const char *comm)
  370. {
  371. ssize_t sz;
  372. char filename[sizeof("/proc//cmdline") + sizeof(int)*3];
  373. sprintf(filename, "/proc/%u/cmdline", pid);
  374. sz = open_read_close(filename, buf, col);
  375. if (sz > 0) {
  376. buf[sz] = '\0';
  377. while (--sz >= 0)
  378. if ((unsigned char)(buf[sz]) < ' ')
  379. buf[sz] = ' ';
  380. } else {
  381. snprintf(buf, col, "[%s]", comm);
  382. }
  383. }
  384. /* from kernel:
  385. // pid comm S ppid pgid sid tty_nr tty_pgrp flg
  386. sprintf(buffer,"%d (%s) %c %d %d %d %d %d %lu %lu \
  387. %lu %lu %lu %lu %lu %ld %ld %ld %ld %d 0 %llu %lu %ld %lu %lu %lu %lu %lu \
  388. %lu %lu %lu %lu %lu %lu %lu %lu %d %d %lu %lu %llu\n",
  389. task->pid,
  390. tcomm,
  391. state,
  392. ppid,
  393. pgid,
  394. sid,
  395. tty_nr,
  396. tty_pgrp,
  397. task->flags,
  398. min_flt,
  399. cmin_flt,
  400. maj_flt,
  401. cmaj_flt,
  402. cputime_to_clock_t(utime),
  403. cputime_to_clock_t(stime),
  404. cputime_to_clock_t(cutime),
  405. cputime_to_clock_t(cstime),
  406. priority,
  407. nice,
  408. num_threads,
  409. // 0,
  410. start_time,
  411. vsize,
  412. mm ? get_mm_rss(mm) : 0,
  413. rsslim,
  414. mm ? mm->start_code : 0,
  415. mm ? mm->end_code : 0,
  416. mm ? mm->start_stack : 0,
  417. esp,
  418. eip,
  419. the rest is some obsolete cruft
  420. */