ps.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  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. #ifndef AT_CLKTCK
  17. #define AT_CLKTCK 17
  18. #endif
  19. #if ENABLE_SELINUX
  20. #define SELINUX_O_PREFIX "label,"
  21. #define DEFAULT_O_STR (SELINUX_O_PREFIX "pid,user" IF_FEATURE_PS_TIME(",time") ",args")
  22. #else
  23. #define DEFAULT_O_STR ("pid,user" IF_FEATURE_PS_TIME(",time") ",args")
  24. #endif
  25. typedef struct {
  26. uint16_t width;
  27. char name6[6];
  28. const char *header;
  29. void (*f)(char *buf, int size, const procps_status_t *ps);
  30. int ps_flags;
  31. } ps_out_t;
  32. struct globals {
  33. ps_out_t* out;
  34. int out_cnt;
  35. int print_header;
  36. int need_flags;
  37. char *buffer;
  38. unsigned terminal_width;
  39. #if ENABLE_FEATURE_PS_TIME
  40. unsigned kernel_HZ;
  41. unsigned long long seconds_since_boot;
  42. #endif
  43. char default_o[sizeof(DEFAULT_O_STR)];
  44. } FIX_ALIASING;
  45. #define G (*(struct globals*)&bb_common_bufsiz1)
  46. #define out (G.out )
  47. #define out_cnt (G.out_cnt )
  48. #define print_header (G.print_header )
  49. #define need_flags (G.need_flags )
  50. #define buffer (G.buffer )
  51. #define terminal_width (G.terminal_width )
  52. #define kernel_HZ (G.kernel_HZ )
  53. #define seconds_since_boot (G.seconds_since_boot)
  54. #define default_o (G.default_o )
  55. #define INIT_G() do { } while (0)
  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("can't 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_group(char *buf, int size, const procps_status_t *ps)
  152. {
  153. safe_strncpy(buf, get_cached_groupname(ps->gid), size+1);
  154. }
  155. static void func_comm(char *buf, int size, const procps_status_t *ps)
  156. {
  157. safe_strncpy(buf, ps->comm, size+1);
  158. }
  159. static void func_args(char *buf, int size, const procps_status_t *ps)
  160. {
  161. read_cmdline(buf, size+1, ps->pid, ps->comm);
  162. }
  163. static void func_pid(char *buf, int size, const procps_status_t *ps)
  164. {
  165. sprintf(buf, "%*u", size, ps->pid);
  166. }
  167. static void func_ppid(char *buf, int size, const procps_status_t *ps)
  168. {
  169. sprintf(buf, "%*u", size, ps->ppid);
  170. }
  171. static void func_pgid(char *buf, int size, const procps_status_t *ps)
  172. {
  173. sprintf(buf, "%*u", size, ps->pgid);
  174. }
  175. static void put_lu(char *buf, int size, unsigned long u)
  176. {
  177. char buf4[5];
  178. /* see http://en.wikipedia.org/wiki/Tera */
  179. smart_ulltoa4(u, buf4, " mgtpezy");
  180. buf4[4] = '\0';
  181. sprintf(buf, "%.*s", size, buf4);
  182. }
  183. static void func_vsz(char *buf, int size, const procps_status_t *ps)
  184. {
  185. put_lu(buf, size, ps->vsz);
  186. }
  187. static void func_rss(char *buf, int size, const procps_status_t *ps)
  188. {
  189. put_lu(buf, size, ps->rss);
  190. }
  191. static void func_tty(char *buf, int size, const procps_status_t *ps)
  192. {
  193. buf[0] = '?';
  194. buf[1] = '\0';
  195. if (ps->tty_major) /* tty field of "0" means "no tty" */
  196. snprintf(buf, size+1, "%u,%u", ps->tty_major, ps->tty_minor);
  197. }
  198. #if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
  199. static void func_rgroup(char *buf, int size, const procps_status_t *ps)
  200. {
  201. safe_strncpy(buf, get_cached_groupname(ps->rgid), size+1);
  202. }
  203. static void func_ruser(char *buf, int size, const procps_status_t *ps)
  204. {
  205. safe_strncpy(buf, get_cached_username(ps->ruid), size+1);
  206. }
  207. static void func_nice(char *buf, int size, const procps_status_t *ps)
  208. {
  209. sprintf(buf, "%*d", size, ps->niceness);
  210. }
  211. #endif /* FEATURE_PS_ADDITIONAL_COLUMNS */
  212. #if ENABLE_FEATURE_PS_TIME
  213. static void func_etime(char *buf, int size, const procps_status_t *ps)
  214. {
  215. /* elapsed time [[dd-]hh:]mm:ss; here only mm:ss */
  216. unsigned long mm;
  217. unsigned ss;
  218. mm = ps->start_time / get_kernel_HZ();
  219. /* must be after get_kernel_HZ()! */
  220. mm = seconds_since_boot - mm;
  221. ss = mm % 60;
  222. mm /= 60;
  223. snprintf(buf, size+1, "%3lu:%02u", mm, ss);
  224. }
  225. static void func_time(char *buf, int size, const procps_status_t *ps)
  226. {
  227. /* cumulative time [[dd-]hh:]mm:ss; here only mm:ss */
  228. unsigned long mm;
  229. unsigned ss;
  230. mm = (ps->utime + ps->stime) / get_kernel_HZ();
  231. ss = mm % 60;
  232. mm /= 60;
  233. snprintf(buf, size+1, "%3lu:%02u", mm, ss);
  234. }
  235. #endif
  236. #if ENABLE_SELINUX
  237. static void func_label(char *buf, int size, const procps_status_t *ps)
  238. {
  239. safe_strncpy(buf, ps->context ? ps->context : "unknown", size+1);
  240. }
  241. #endif
  242. /*
  243. static void func_nice(char *buf, int size, const procps_status_t *ps)
  244. {
  245. ps->???
  246. }
  247. static void func_pcpu(char *buf, int size, const procps_status_t *ps)
  248. {
  249. }
  250. */
  251. static const ps_out_t out_spec[] = {
  252. // Mandated by POSIX:
  253. { 8 , "user" ,"USER" ,func_user ,PSSCAN_UIDGID },
  254. { 8 , "group" ,"GROUP" ,func_group ,PSSCAN_UIDGID },
  255. { 16 , "comm" ,"COMMAND",func_comm ,PSSCAN_COMM },
  256. { MAX_WIDTH , "args" ,"COMMAND",func_args ,PSSCAN_COMM },
  257. { 5 , "pid" ,"PID" ,func_pid ,PSSCAN_PID },
  258. { 5 , "ppid" ,"PPID" ,func_ppid ,PSSCAN_PPID },
  259. { 5 , "pgid" ,"PGID" ,func_pgid ,PSSCAN_PGID },
  260. #if ENABLE_FEATURE_PS_TIME
  261. { sizeof("ELAPSED")-1, "etime" ,"ELAPSED",func_etime ,PSSCAN_START_TIME },
  262. #endif
  263. #if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
  264. { 5 , "nice" ,"NI" ,func_nice ,PSSCAN_NICE },
  265. { 8 , "rgroup","RGROUP" ,func_rgroup,PSSCAN_RUIDGID },
  266. { 8 , "ruser" ,"RUSER" ,func_ruser ,PSSCAN_RUIDGID },
  267. // { 5 , "pcpu" ,"%CPU" ,func_pcpu ,PSSCAN_ },
  268. #endif
  269. #if ENABLE_FEATURE_PS_TIME
  270. { 6 , "time" ,"TIME" ,func_time ,PSSCAN_STIME | PSSCAN_UTIME },
  271. #endif
  272. { 6 , "tty" ,"TT" ,func_tty ,PSSCAN_TTY },
  273. { 4 , "vsz" ,"VSZ" ,func_vsz ,PSSCAN_VSZ },
  274. // Not mandated by POSIX, but useful:
  275. { 4 , "rss" ,"RSS" ,func_rss ,PSSCAN_RSS },
  276. #if ENABLE_SELINUX
  277. { 35 , "label" ,"LABEL" ,func_label ,PSSCAN_CONTEXT },
  278. #endif
  279. };
  280. static ps_out_t* new_out_t(void)
  281. {
  282. out = xrealloc_vector(out, 2, out_cnt);
  283. return &out[out_cnt++];
  284. }
  285. static const ps_out_t* find_out_spec(const char *name)
  286. {
  287. unsigned i;
  288. for (i = 0; i < ARRAY_SIZE(out_spec); i++) {
  289. if (!strncmp(name, out_spec[i].name6, 6))
  290. return &out_spec[i];
  291. }
  292. bb_error_msg_and_die("bad -o argument '%s'", name);
  293. }
  294. static void parse_o(char* opt)
  295. {
  296. ps_out_t* new;
  297. // POSIX: "-o is blank- or comma-separated list" (FIXME)
  298. char *comma, *equal;
  299. while (1) {
  300. comma = strchr(opt, ',');
  301. equal = strchr(opt, '=');
  302. if (comma && (!equal || equal > comma)) {
  303. *comma = '\0';
  304. *new_out_t() = *find_out_spec(opt);
  305. *comma = ',';
  306. opt = comma + 1;
  307. continue;
  308. }
  309. break;
  310. }
  311. // opt points to last spec in comma separated list.
  312. // This one can have =HEADER part.
  313. new = new_out_t();
  314. if (equal)
  315. *equal = '\0';
  316. *new = *find_out_spec(opt);
  317. if (equal) {
  318. *equal = '=';
  319. new->header = equal + 1;
  320. // POSIX: the field widths shall be ... at least as wide as
  321. // the header text (default or overridden value).
  322. // If the header text is null, such as -o user=,
  323. // the field width shall be at least as wide as the
  324. // default header text
  325. if (new->header[0]) {
  326. new->width = strlen(new->header);
  327. print_header = 1;
  328. }
  329. } else
  330. print_header = 1;
  331. }
  332. static void alloc_line_buffer(void)
  333. {
  334. int i;
  335. int width = 0;
  336. for (i = 0; i < out_cnt; i++) {
  337. need_flags |= out[i].ps_flags;
  338. if (out[i].header[0]) {
  339. print_header = 1;
  340. }
  341. width += out[i].width + 1; /* "FIELD " */
  342. if ((int)(width - terminal_width) > 0) {
  343. /* The rest does not fit on the screen */
  344. //out[i].width -= (width - terminal_width - 1);
  345. out_cnt = i + 1;
  346. break;
  347. }
  348. }
  349. #if ENABLE_SELINUX
  350. if (!is_selinux_enabled())
  351. need_flags &= ~PSSCAN_CONTEXT;
  352. #endif
  353. buffer = xmalloc(width + 1); /* for trailing \0 */
  354. }
  355. static void format_header(void)
  356. {
  357. int i;
  358. ps_out_t* op;
  359. char *p;
  360. if (!print_header)
  361. return;
  362. p = buffer;
  363. i = 0;
  364. if (out_cnt) {
  365. while (1) {
  366. op = &out[i];
  367. if (++i == out_cnt) /* do not pad last field */
  368. break;
  369. p += sprintf(p, "%-*s ", op->width, op->header);
  370. }
  371. strcpy(p, op->header);
  372. }
  373. printf("%.*s\n", terminal_width, buffer);
  374. }
  375. static void format_process(const procps_status_t *ps)
  376. {
  377. int i, len;
  378. char *p = buffer;
  379. i = 0;
  380. if (out_cnt) while (1) {
  381. out[i].f(p, out[i].width, ps);
  382. // POSIX: Any field need not be meaningful in all
  383. // implementations. In such a case a hyphen ( '-' )
  384. // should be output in place of the field value.
  385. if (!p[0]) {
  386. p[0] = '-';
  387. p[1] = '\0';
  388. }
  389. len = strlen(p);
  390. p += len;
  391. len = out[i].width - len + 1;
  392. if (++i == out_cnt) /* do not pad last field */
  393. break;
  394. p += sprintf(p, "%*s", len, "");
  395. }
  396. printf("%.*s\n", terminal_width, buffer);
  397. }
  398. int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  399. int ps_main(int argc UNUSED_PARAM, char **argv)
  400. {
  401. procps_status_t *p;
  402. llist_t* opt_o = NULL;
  403. int opt;
  404. enum {
  405. OPT_Z = (1 << 0),
  406. OPT_o = (1 << 1),
  407. OPT_a = (1 << 2),
  408. OPT_A = (1 << 3),
  409. OPT_d = (1 << 4),
  410. OPT_e = (1 << 5),
  411. OPT_f = (1 << 6),
  412. OPT_l = (1 << 7),
  413. OPT_T = (1 << 8) * ENABLE_FEATURE_SHOW_THREADS,
  414. };
  415. INIT_G();
  416. // POSIX:
  417. // -a Write information for all processes associated with terminals
  418. // Implementations may omit session leaders from this list
  419. // -A Write information for all processes
  420. // -d Write information for all processes, except session leaders
  421. // -e Write information for all processes (equivalent to -A)
  422. // -f Generate a full listing
  423. // -l Generate a long listing
  424. // -o col1,col2,col3=header
  425. // Select which columns to display
  426. /* We allow (and ignore) most of the above. FIXME.
  427. * -T is picked for threads (POSIX hasn't it standardized).
  428. * procps v3.2.7 supports -T and shows tids as SPID column,
  429. * it also supports -L where it shows tids as LWP column.
  430. */
  431. opt_complementary = "o::";
  432. opt = getopt32(argv, "Zo:aAdefl"IF_FEATURE_SHOW_THREADS("T"), &opt_o);
  433. if (opt_o) {
  434. do {
  435. parse_o(llist_pop(&opt_o));
  436. } while (opt_o);
  437. } else {
  438. /* Below: parse_o() needs char*, NOT const char*... */
  439. #if ENABLE_SELINUX
  440. if (!(opt & OPT_Z) || !is_selinux_enabled()) {
  441. /* no -Z or no SELinux: do not show LABEL */
  442. strcpy(default_o, DEFAULT_O_STR + sizeof(SELINUX_O_PREFIX)-1);
  443. } else
  444. #endif
  445. {
  446. strcpy(default_o, DEFAULT_O_STR);
  447. }
  448. parse_o(default_o);
  449. }
  450. #if ENABLE_FEATURE_SHOW_THREADS
  451. if (opt & OPT_T)
  452. need_flags |= PSSCAN_TASKS;
  453. #endif
  454. /* Was INT_MAX, but some libc's go belly up with printf("%.*s")
  455. * and such large widths */
  456. terminal_width = MAX_WIDTH;
  457. if (isatty(1)) {
  458. get_terminal_width_height(0, &terminal_width, NULL);
  459. if (--terminal_width > MAX_WIDTH)
  460. terminal_width = MAX_WIDTH;
  461. }
  462. alloc_line_buffer();
  463. format_header();
  464. p = NULL;
  465. while ((p = procps_scan(p, need_flags)) != NULL) {
  466. format_process(p);
  467. }
  468. return EXIT_SUCCESS;
  469. }
  470. #else /* !ENABLE_DESKTOP */
  471. int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  472. int ps_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  473. {
  474. procps_status_t *p;
  475. int psscan_flags = PSSCAN_PID | PSSCAN_UIDGID
  476. | PSSCAN_STATE | PSSCAN_VSZ | PSSCAN_COMM;
  477. unsigned terminal_width IF_NOT_FEATURE_PS_WIDE(= 79);
  478. enum {
  479. OPT_Z = (1 << 0) * ENABLE_SELINUX,
  480. OPT_T = (1 << ENABLE_SELINUX) * ENABLE_FEATURE_SHOW_THREADS,
  481. };
  482. int opts = 0;
  483. /* If we support any options, parse argv */
  484. #if ENABLE_SELINUX || ENABLE_FEATURE_SHOW_THREADS || ENABLE_FEATURE_PS_WIDE
  485. # if ENABLE_FEATURE_PS_WIDE
  486. /* -w is a bit complicated */
  487. int w_count = 0;
  488. opt_complementary = "-:ww";
  489. opts = getopt32(argv, IF_SELINUX("Z")IF_FEATURE_SHOW_THREADS("T")"w", &w_count);
  490. /* if w is given once, GNU ps sets the width to 132,
  491. * if w is given more than once, it is "unlimited"
  492. */
  493. if (w_count) {
  494. terminal_width = (w_count == 1) ? 132 : MAX_WIDTH;
  495. } else {
  496. get_terminal_width_height(0, &terminal_width, NULL);
  497. /* Go one less... */
  498. if (--terminal_width > MAX_WIDTH)
  499. terminal_width = MAX_WIDTH;
  500. }
  501. # else
  502. /* -w is not supported, only -Z and/or -T */
  503. opt_complementary = "-";
  504. opts = getopt32(argv, IF_SELINUX("Z")IF_FEATURE_SHOW_THREADS("T"));
  505. # endif
  506. #endif
  507. #if ENABLE_SELINUX
  508. if ((opts & OPT_Z) && is_selinux_enabled()) {
  509. psscan_flags = PSSCAN_PID | PSSCAN_CONTEXT
  510. | PSSCAN_STATE | PSSCAN_COMM;
  511. puts(" PID CONTEXT STAT COMMAND");
  512. } else
  513. #endif
  514. {
  515. puts(" PID USER VSZ STAT COMMAND");
  516. }
  517. if (opts & OPT_T) {
  518. psscan_flags |= PSSCAN_TASKS;
  519. }
  520. p = NULL;
  521. while ((p = procps_scan(p, psscan_flags)) != NULL) {
  522. int len;
  523. #if ENABLE_SELINUX
  524. if (psscan_flags & PSSCAN_CONTEXT) {
  525. len = printf("%5u %-32.32s %s ",
  526. p->pid,
  527. p->context ? p->context : "unknown",
  528. p->state);
  529. } else
  530. #endif
  531. {
  532. const char *user = get_cached_username(p->uid);
  533. //if (p->vsz == 0)
  534. // len = printf("%5u %-8.8s %s ",
  535. // p->pid, user, p->state);
  536. //else
  537. {
  538. char buf6[6];
  539. smart_ulltoa5(p->vsz, buf6, " mgtpezy");
  540. buf6[5] = '\0';
  541. len = printf("%5u %-8.8s %s %s ",
  542. p->pid, user, buf6, p->state);
  543. }
  544. }
  545. {
  546. int sz = terminal_width - len;
  547. char buf[sz + 1];
  548. read_cmdline(buf, sz, p->pid, p->comm);
  549. puts(buf);
  550. }
  551. }
  552. if (ENABLE_FEATURE_CLEAN_UP)
  553. clear_username_cache();
  554. return EXIT_SUCCESS;
  555. }
  556. #endif /* !ENABLE_DESKTOP */