ps.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini ps implementation(s) for busybox
  4. *
  5. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  6. * Fix for SELinux Support:(c)2007 Hiroshi Shinji <shiroshi@my.email.ne.jp>
  7. * (c)2007 Yuichi Nakamura <ynakam@hitachisoft.jp>
  8. *
  9. * Licensed under the GPL version 2, see the file LICENSE in this tarball.
  10. */
  11. #include "libbb.h"
  12. /* Absolute maximum on output line length */
  13. enum { MAX_WIDTH = 2*1024 };
  14. #if ENABLE_DESKTOP
  15. #include <sys/times.h> /* for times() */
  16. //#include <sys/sysinfo.h> /* for sysinfo() */
  17. #ifndef AT_CLKTCK
  18. #define AT_CLKTCK 17
  19. #endif
  20. #if ENABLE_SELINUX
  21. #define SELINIX_O_PREFIX "label,"
  22. #define DEFAULT_O_STR (SELINIX_O_PREFIX "pid,user" USE_FEATURE_PS_TIME(",time") ",args")
  23. #else
  24. #define DEFAULT_O_STR ("pid,user" USE_FEATURE_PS_TIME(",time") ",args")
  25. #endif
  26. typedef struct {
  27. uint16_t width;
  28. char name[6];
  29. const char *header;
  30. void (*f)(char *buf, int size, const procps_status_t *ps);
  31. int ps_flags;
  32. } ps_out_t;
  33. struct globals {
  34. ps_out_t* out;
  35. int out_cnt;
  36. int print_header;
  37. int need_flags;
  38. char *buffer;
  39. unsigned terminal_width;
  40. #if ENABLE_FEATURE_PS_TIME
  41. unsigned kernel_HZ;
  42. unsigned long long seconds_since_boot;
  43. #endif
  44. char default_o[sizeof(DEFAULT_O_STR)];
  45. };
  46. #define G (*(struct globals*)&bb_common_bufsiz1)
  47. #define out (G.out )
  48. #define out_cnt (G.out_cnt )
  49. #define print_header (G.print_header )
  50. #define need_flags (G.need_flags )
  51. #define buffer (G.buffer )
  52. #define terminal_width (G.terminal_width )
  53. #define kernel_HZ (G.kernel_HZ )
  54. #define seconds_since_boot (G.seconds_since_boot)
  55. #define default_o (G.default_o )
  56. #if ENABLE_FEATURE_PS_TIME
  57. /* for ELF executables, notes are pushed before environment and args */
  58. static ptrdiff_t find_elf_note(ptrdiff_t findme)
  59. {
  60. ptrdiff_t *ep = (ptrdiff_t *) environ;
  61. while (*ep++);
  62. while (*ep) {
  63. if (ep[0] == findme) {
  64. return ep[1];
  65. }
  66. ep += 2;
  67. }
  68. return -1;
  69. }
  70. #if ENABLE_FEATURE_PS_UNUSUAL_SYSTEMS
  71. static unsigned get_HZ_by_waiting(void)
  72. {
  73. struct timeval tv1, tv2;
  74. unsigned t1, t2, r, hz;
  75. unsigned cnt = cnt; /* for compiler */
  76. int diff;
  77. r = 0;
  78. /* Wait for times() to reach new tick */
  79. t1 = times(NULL);
  80. do {
  81. t2 = times(NULL);
  82. } while (t2 == t1);
  83. gettimeofday(&tv2, NULL);
  84. do {
  85. t1 = t2;
  86. tv1.tv_usec = tv2.tv_usec;
  87. /* Wait exactly one times() tick */
  88. do {
  89. t2 = times(NULL);
  90. } while (t2 == t1);
  91. gettimeofday(&tv2, NULL);
  92. /* Calculate ticks per sec, rounding up to even */
  93. diff = tv2.tv_usec - tv1.tv_usec;
  94. if (diff <= 0) diff += 1000000;
  95. hz = 1000000u / (unsigned)diff;
  96. hz = (hz+1) & ~1;
  97. /* Count how many same hz values we saw */
  98. if (r != hz) {
  99. r = hz;
  100. cnt = 0;
  101. }
  102. cnt++;
  103. } while (cnt < 3); /* exit if saw 3 same values */
  104. return r;
  105. }
  106. #else
  107. static inline unsigned get_HZ_by_waiting(void)
  108. {
  109. /* Better method? */
  110. return 100;
  111. }
  112. #endif
  113. static unsigned get_kernel_HZ(void)
  114. {
  115. //char buf[64];
  116. struct sysinfo info;
  117. if (kernel_HZ)
  118. return kernel_HZ;
  119. /* Works for ELF only, Linux 2.4.0+ */
  120. kernel_HZ = find_elf_note(AT_CLKTCK);
  121. if (kernel_HZ == (unsigned)-1)
  122. kernel_HZ = get_HZ_by_waiting();
  123. //if (open_read_close("/proc/uptime", buf, sizeof(buf) <= 0)
  124. // bb_perror_msg_and_die("cannot read %s", "/proc/uptime");
  125. //buf[sizeof(buf)-1] = '\0';
  126. ///sscanf(buf, "%llu", &seconds_since_boot);
  127. sysinfo(&info);
  128. seconds_since_boot = info.uptime;
  129. return kernel_HZ;
  130. }
  131. #endif
  132. /* Print value to buf, max size+1 chars (including trailing '\0') */
  133. static void func_user(char *buf, int size, const procps_status_t *ps)
  134. {
  135. #if 1
  136. safe_strncpy(buf, get_cached_username(ps->uid), size+1);
  137. #else
  138. /* "compatible" version, but it's larger */
  139. /* procps 2.18 shows numeric UID if name overflows the field */
  140. /* TODO: get_cached_username() returns numeric string if
  141. * user has no passwd record, we will display it
  142. * left-justified here; too long usernames are shown
  143. * as _right-justified_ IDs. Is it worth fixing? */
  144. const char *user = get_cached_username(ps->uid);
  145. if (strlen(user) <= size)
  146. safe_strncpy(buf, user, size+1);
  147. else
  148. sprintf(buf, "%*u", size, (unsigned)ps->uid);
  149. #endif
  150. }
  151. static void func_comm(char *buf, int size, const procps_status_t *ps)
  152. {
  153. safe_strncpy(buf, ps->comm, size+1);
  154. }
  155. static void func_args(char *buf, int size, const procps_status_t *ps)
  156. {
  157. read_cmdline(buf, size, ps->pid, ps->comm);
  158. }
  159. static void func_pid(char *buf, int size, const procps_status_t *ps)
  160. {
  161. sprintf(buf, "%*u", size, ps->pid);
  162. }
  163. static void func_ppid(char *buf, int size, const procps_status_t *ps)
  164. {
  165. sprintf(buf, "%*u", size, ps->ppid);
  166. }
  167. static void func_pgid(char *buf, int size, const procps_status_t *ps)
  168. {
  169. sprintf(buf, "%*u", size, ps->pgid);
  170. }
  171. static void put_lu(char *buf, int size, unsigned long u)
  172. {
  173. char buf4[5];
  174. /* see http://en.wikipedia.org/wiki/Tera */
  175. smart_ulltoa4(u, buf4, " mgtpezy");
  176. buf4[4] = '\0';
  177. sprintf(buf, "%.*s", size, buf4);
  178. }
  179. static void func_vsz(char *buf, int size, const procps_status_t *ps)
  180. {
  181. put_lu(buf, size, ps->vsz);
  182. }
  183. static void func_rss(char *buf, int size, const procps_status_t *ps)
  184. {
  185. put_lu(buf, size, ps->rss);
  186. }
  187. static void func_tty(char *buf, int size, const procps_status_t *ps)
  188. {
  189. buf[0] = '?';
  190. buf[1] = '\0';
  191. if (ps->tty_major) /* tty field of "0" means "no tty" */
  192. snprintf(buf, size+1, "%u,%u", ps->tty_major, ps->tty_minor);
  193. }
  194. #if ENABLE_FEATURE_PS_TIME
  195. static void func_etime(char *buf, int size, const procps_status_t *ps)
  196. {
  197. /* elapsed time [[dd-]hh:]mm:ss; here only mm:ss */
  198. unsigned long mm;
  199. unsigned ss;
  200. mm = ps->start_time / get_kernel_HZ();
  201. /* must be after get_kernel_HZ()! */
  202. mm = seconds_since_boot - mm;
  203. ss = mm % 60;
  204. mm /= 60;
  205. snprintf(buf, size+1, "%3lu:%02u", mm, ss);
  206. }
  207. static void func_time(char *buf, int size, const procps_status_t *ps)
  208. {
  209. /* cumulative time [[dd-]hh:]mm:ss; here only mm:ss */
  210. unsigned long mm;
  211. unsigned ss;
  212. mm = (ps->utime + ps->stime) / get_kernel_HZ();
  213. ss = mm % 60;
  214. mm /= 60;
  215. snprintf(buf, size+1, "%3lu:%02u", mm, ss);
  216. }
  217. #endif
  218. #if ENABLE_SELINUX
  219. static void func_label(char *buf, int size, const procps_status_t *ps)
  220. {
  221. safe_strncpy(buf, ps->context ? ps->context : "unknown", size+1);
  222. }
  223. #endif
  224. /*
  225. static void func_nice(char *buf, int size, const procps_status_t *ps)
  226. {
  227. ps->???
  228. }
  229. static void func_pcpu(char *buf, int size, const procps_status_t *ps)
  230. {
  231. }
  232. */
  233. static const ps_out_t out_spec[] = {
  234. // Mandated by POSIX:
  235. { 8 , "user" ,"USER" ,func_user ,PSSCAN_UIDGID },
  236. { 16 , "comm" ,"COMMAND",func_comm ,PSSCAN_COMM },
  237. { 256 , "args" ,"COMMAND",func_args ,PSSCAN_COMM },
  238. { 5 , "pid" ,"PID" ,func_pid ,PSSCAN_PID },
  239. { 5 , "ppid" ,"PPID" ,func_ppid ,PSSCAN_PPID },
  240. { 5 , "pgid" ,"PGID" ,func_pgid ,PSSCAN_PGID },
  241. #if ENABLE_FEATURE_PS_TIME
  242. { sizeof("ELAPSED")-1, "etime" ,"ELAPSED",func_etime ,PSSCAN_START_TIME },
  243. #endif
  244. // { sizeof("GROUP" )-1, "group" ,"GROUP" ,func_group ,PSSCAN_UIDGID },
  245. // { sizeof("NI" )-1, "nice" ,"NI" ,func_nice ,PSSCAN_ },
  246. // { sizeof("%CPU" )-1, "pcpu" ,"%CPU" ,func_pcpu ,PSSCAN_ },
  247. // { sizeof("RGROUP" )-1, "rgroup","RGROUP" ,func_rgroup,PSSCAN_UIDGID },
  248. // { sizeof("RUSER" )-1, "ruser" ,"RUSER" ,func_ruser ,PSSCAN_UIDGID },
  249. #if ENABLE_FEATURE_PS_TIME
  250. { 6 , "time" ,"TIME" ,func_time ,PSSCAN_STIME | PSSCAN_UTIME },
  251. #endif
  252. { 6 , "tty" ,"TT" ,func_tty ,PSSCAN_TTY },
  253. { 4 , "vsz" ,"VSZ" ,func_vsz ,PSSCAN_VSZ },
  254. // Not mandated by POSIX, but useful:
  255. { 4 , "rss" ,"RSS" ,func_rss ,PSSCAN_RSS },
  256. #if ENABLE_SELINUX
  257. { 35 , "label" ,"LABEL" ,func_label ,PSSCAN_CONTEXT },
  258. #endif
  259. };
  260. static ps_out_t* new_out_t(void)
  261. {
  262. int i = out_cnt++;
  263. out = xrealloc(out, out_cnt * sizeof(*out));
  264. return &out[i];
  265. }
  266. static const ps_out_t* find_out_spec(const char *name)
  267. {
  268. unsigned i;
  269. for (i = 0; i < ARRAY_SIZE(out_spec); i++) {
  270. if (!strcmp(name, out_spec[i].name))
  271. return &out_spec[i];
  272. }
  273. bb_error_msg_and_die("bad -o argument '%s'", name);
  274. }
  275. static void parse_o(char* opt)
  276. {
  277. ps_out_t* new;
  278. // POSIX: "-o is blank- or comma-separated list" (FIXME)
  279. char *comma, *equal;
  280. while (1) {
  281. comma = strchr(opt, ',');
  282. equal = strchr(opt, '=');
  283. if (comma && (!equal || equal > comma)) {
  284. *comma = '\0';
  285. *new_out_t() = *find_out_spec(opt);
  286. *comma = ',';
  287. opt = comma + 1;
  288. continue;
  289. }
  290. break;
  291. }
  292. // opt points to last spec in comma separated list.
  293. // This one can have =HEADER part.
  294. new = new_out_t();
  295. if (equal)
  296. *equal = '\0';
  297. *new = *find_out_spec(opt);
  298. if (equal) {
  299. *equal = '=';
  300. new->header = equal + 1;
  301. // POSIX: the field widths shall be ... at least as wide as
  302. // the header text (default or overridden value).
  303. // If the header text is null, such as -o user=,
  304. // the field width shall be at least as wide as the
  305. // default header text
  306. if (new->header[0]) {
  307. new->width = strlen(new->header);
  308. print_header = 1;
  309. }
  310. } else
  311. print_header = 1;
  312. }
  313. static void post_process(void)
  314. {
  315. int i;
  316. int width = 0;
  317. for (i = 0; i < out_cnt; i++) {
  318. need_flags |= out[i].ps_flags;
  319. if (out[i].header[0]) {
  320. print_header = 1;
  321. }
  322. width += out[i].width + 1; /* "FIELD " */
  323. }
  324. #if ENABLE_SELINUX
  325. if (!is_selinux_enabled())
  326. need_flags &= ~PSSCAN_CONTEXT;
  327. #endif
  328. buffer = xmalloc(width + 1); /* for trailing \0 */
  329. }
  330. static void format_header(void)
  331. {
  332. int i;
  333. ps_out_t* op;
  334. char *p;
  335. if (!print_header)
  336. return;
  337. p = buffer;
  338. i = 0;
  339. if (out_cnt) {
  340. while (1) {
  341. op = &out[i];
  342. if (++i == out_cnt) /* do not pad last field */
  343. break;
  344. p += sprintf(p, "%-*s ", op->width, op->header);
  345. }
  346. strcpy(p, op->header);
  347. }
  348. printf("%.*s\n", terminal_width, buffer);
  349. }
  350. static void format_process(const procps_status_t *ps)
  351. {
  352. int i, len;
  353. char *p = buffer;
  354. i = 0;
  355. if (out_cnt) while (1) {
  356. out[i].f(p, out[i].width, ps);
  357. // POSIX: Any field need not be meaningful in all
  358. // implementations. In such a case a hyphen ( '-' )
  359. // should be output in place of the field value.
  360. if (!p[0]) {
  361. p[0] = '-';
  362. p[1] = '\0';
  363. }
  364. len = strlen(p);
  365. p += len;
  366. len = out[i].width - len + 1;
  367. if (++i == out_cnt) /* do not pad last field */
  368. break;
  369. p += sprintf(p, "%*s", len, "");
  370. }
  371. printf("%.*s\n", terminal_width, buffer);
  372. }
  373. int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  374. int ps_main(int argc ATTRIBUTE_UNUSED, char **argv)
  375. {
  376. procps_status_t *p;
  377. llist_t* opt_o = NULL;
  378. USE_SELINUX(int opt;)
  379. // POSIX:
  380. // -a Write information for all processes associated with terminals
  381. // Implementations may omit session leaders from this list
  382. // -A Write information for all processes
  383. // -d Write information for all processes, except session leaders
  384. // -e Write information for all processes (equivalent to -A.)
  385. // -f Generate a full listing
  386. // -l Generate a long listing
  387. // -o col1,col2,col3=header
  388. // Select which columns to display
  389. /* We allow (and ignore) most of the above. FIXME */
  390. opt_complementary = "o::";
  391. USE_SELINUX(opt =) getopt32(argv, "Zo:aAdefl", &opt_o);
  392. if (opt_o) {
  393. do {
  394. parse_o(llist_pop(&opt_o));
  395. } while (opt_o);
  396. } else {
  397. /* Below: parse_o() needs char*, NOT const char*... */
  398. #if ENABLE_SELINUX
  399. if (!(opt & 1) || !is_selinux_enabled()) {
  400. /* no -Z or no SELinux: do not show LABEL */
  401. strcpy(default_o, DEFAULT_O_STR + sizeof(SELINIX_O_PREFIX)-1);
  402. } else
  403. #endif
  404. {
  405. strcpy(default_o, DEFAULT_O_STR);
  406. }
  407. parse_o(default_o);
  408. }
  409. post_process();
  410. /* Was INT_MAX, but some libc's go belly up with printf("%.*s")
  411. * and such large widths */
  412. terminal_width = MAX_WIDTH;
  413. if (isatty(1)) {
  414. get_terminal_width_height(0, &terminal_width, NULL);
  415. if (--terminal_width > MAX_WIDTH)
  416. terminal_width = MAX_WIDTH;
  417. }
  418. format_header();
  419. p = NULL;
  420. while ((p = procps_scan(p, need_flags))) {
  421. format_process(p);
  422. }
  423. return EXIT_SUCCESS;
  424. }
  425. #else /* !ENABLE_DESKTOP */
  426. int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  427. int ps_main(int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED)
  428. {
  429. procps_status_t *p = NULL;
  430. int len;
  431. SKIP_SELINUX(const) int use_selinux = 0;
  432. USE_SELINUX(int i;)
  433. #if !ENABLE_FEATURE_PS_WIDE
  434. enum { terminal_width = 79 };
  435. #else
  436. unsigned terminal_width;
  437. int w_count = 0;
  438. #endif
  439. #if ENABLE_FEATURE_PS_WIDE || ENABLE_SELINUX
  440. #if ENABLE_FEATURE_PS_WIDE
  441. opt_complementary = "-:ww";
  442. USE_SELINUX(i =) getopt32(argv, USE_SELINUX("Z") "w", &w_count);
  443. /* if w is given once, GNU ps sets the width to 132,
  444. * if w is given more than once, it is "unlimited"
  445. */
  446. if (w_count) {
  447. terminal_width = (w_count==1) ? 132 : MAX_WIDTH;
  448. } else {
  449. get_terminal_width_height(0, &terminal_width, NULL);
  450. /* Go one less... */
  451. if (--terminal_width > MAX_WIDTH)
  452. terminal_width = MAX_WIDTH;
  453. }
  454. #else /* only ENABLE_SELINUX */
  455. i = getopt32(argv, "Z");
  456. #endif
  457. #if ENABLE_SELINUX
  458. if ((i & 1) && is_selinux_enabled())
  459. use_selinux = PSSCAN_CONTEXT;
  460. #endif
  461. #endif /* ENABLE_FEATURE_PS_WIDE || ENABLE_SELINUX */
  462. if (use_selinux)
  463. puts(" PID CONTEXT STAT COMMAND");
  464. else
  465. puts(" PID USER VSZ STAT COMMAND");
  466. while ((p = procps_scan(p, 0
  467. | PSSCAN_PID
  468. | PSSCAN_UIDGID
  469. | PSSCAN_STATE
  470. | PSSCAN_VSZ
  471. | PSSCAN_COMM
  472. | use_selinux
  473. ))) {
  474. #if ENABLE_SELINUX
  475. if (use_selinux) {
  476. len = printf("%5u %-32.32s %s ",
  477. p->pid,
  478. p->context ? p->context : "unknown",
  479. p->state);
  480. } else
  481. #endif
  482. {
  483. const char *user = get_cached_username(p->uid);
  484. //if (p->vsz == 0)
  485. // len = printf("%5u %-8.8s %s ",
  486. // p->pid, user, p->state);
  487. //else
  488. {
  489. char buf6[6];
  490. smart_ulltoa5(p->vsz, buf6, " mgtpezy");
  491. buf6[5] = '\0';
  492. len = printf("%5u %-8.8s %s %s ",
  493. p->pid, user, buf6, p->state);
  494. }
  495. }
  496. {
  497. int sz = terminal_width - len;
  498. char buf[sz + 1];
  499. read_cmdline(buf, sz, p->pid, p->comm);
  500. puts(buf);
  501. }
  502. }
  503. if (ENABLE_FEATURE_CLEAN_UP)
  504. clear_username_cache();
  505. return EXIT_SUCCESS;
  506. }
  507. #endif /* ENABLE_DESKTOP */