ps.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  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 SELINUX_O_PREFIX "label,"
  22. #define DEFAULT_O_STR (SELINUX_O_PREFIX "pid,user" IF_FEATURE_PS_TIME(",time") ",args")
  23. #else
  24. #define DEFAULT_O_STR ("pid,user" IF_FEATURE_PS_TIME(",time") ",args")
  25. #endif
  26. typedef struct {
  27. uint16_t width;
  28. char name6[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_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, 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. { 256 , "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 post_process(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. }
  343. #if ENABLE_SELINUX
  344. if (!is_selinux_enabled())
  345. need_flags &= ~PSSCAN_CONTEXT;
  346. #endif
  347. buffer = xmalloc(width + 1); /* for trailing \0 */
  348. }
  349. static void format_header(void)
  350. {
  351. int i;
  352. ps_out_t* op;
  353. char *p;
  354. if (!print_header)
  355. return;
  356. p = buffer;
  357. i = 0;
  358. if (out_cnt) {
  359. while (1) {
  360. op = &out[i];
  361. if (++i == out_cnt) /* do not pad last field */
  362. break;
  363. p += sprintf(p, "%-*s ", op->width, op->header);
  364. }
  365. strcpy(p, op->header);
  366. }
  367. printf("%.*s\n", terminal_width, buffer);
  368. }
  369. static void format_process(const procps_status_t *ps)
  370. {
  371. int i, len;
  372. char *p = buffer;
  373. i = 0;
  374. if (out_cnt) while (1) {
  375. out[i].f(p, out[i].width, ps);
  376. // POSIX: Any field need not be meaningful in all
  377. // implementations. In such a case a hyphen ( '-' )
  378. // should be output in place of the field value.
  379. if (!p[0]) {
  380. p[0] = '-';
  381. p[1] = '\0';
  382. }
  383. len = strlen(p);
  384. p += len;
  385. len = out[i].width - len + 1;
  386. if (++i == out_cnt) /* do not pad last field */
  387. break;
  388. p += sprintf(p, "%*s", len, "");
  389. }
  390. printf("%.*s\n", terminal_width, buffer);
  391. }
  392. int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  393. int ps_main(int argc UNUSED_PARAM, char **argv)
  394. {
  395. procps_status_t *p;
  396. llist_t* opt_o = NULL;
  397. IF_SELINUX(int opt;)
  398. // POSIX:
  399. // -a Write information for all processes associated with terminals
  400. // Implementations may omit session leaders from this list
  401. // -A Write information for all processes
  402. // -d Write information for all processes, except session leaders
  403. // -e Write information for all processes (equivalent to -A.)
  404. // -f Generate a full listing
  405. // -l Generate a long listing
  406. // -o col1,col2,col3=header
  407. // Select which columns to display
  408. /* We allow (and ignore) most of the above. FIXME */
  409. opt_complementary = "o::";
  410. IF_SELINUX(opt =) getopt32(argv, "Zo:aAdefl", &opt_o);
  411. if (opt_o) {
  412. do {
  413. parse_o(llist_pop(&opt_o));
  414. } while (opt_o);
  415. } else {
  416. /* Below: parse_o() needs char*, NOT const char*... */
  417. #if ENABLE_SELINUX
  418. if (!(opt & 1) || !is_selinux_enabled()) {
  419. /* no -Z or no SELinux: do not show LABEL */
  420. strcpy(default_o, DEFAULT_O_STR + sizeof(SELINUX_O_PREFIX)-1);
  421. } else
  422. #endif
  423. {
  424. strcpy(default_o, DEFAULT_O_STR);
  425. }
  426. parse_o(default_o);
  427. }
  428. post_process();
  429. /* Was INT_MAX, but some libc's go belly up with printf("%.*s")
  430. * and such large widths */
  431. terminal_width = MAX_WIDTH;
  432. if (isatty(1)) {
  433. get_terminal_width_height(0, &terminal_width, NULL);
  434. if (--terminal_width > MAX_WIDTH)
  435. terminal_width = MAX_WIDTH;
  436. }
  437. format_header();
  438. p = NULL;
  439. while ((p = procps_scan(p, need_flags))) {
  440. format_process(p);
  441. }
  442. return EXIT_SUCCESS;
  443. }
  444. #else /* !ENABLE_DESKTOP */
  445. int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  446. int ps_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  447. {
  448. procps_status_t *p = NULL;
  449. int len;
  450. IF_NOT_SELINUX(const) int use_selinux = 0;
  451. IF_SELINUX(int i;)
  452. #if !ENABLE_FEATURE_PS_WIDE
  453. enum { terminal_width = 79 };
  454. #else
  455. unsigned terminal_width;
  456. int w_count = 0;
  457. #endif
  458. #if ENABLE_FEATURE_PS_WIDE || ENABLE_SELINUX
  459. #if ENABLE_FEATURE_PS_WIDE
  460. opt_complementary = "-:ww";
  461. IF_SELINUX(i =) getopt32(argv, IF_SELINUX("Z") "w", &w_count);
  462. /* if w is given once, GNU ps sets the width to 132,
  463. * if w is given more than once, it is "unlimited"
  464. */
  465. if (w_count) {
  466. terminal_width = (w_count==1) ? 132 : MAX_WIDTH;
  467. } else {
  468. get_terminal_width_height(0, &terminal_width, NULL);
  469. /* Go one less... */
  470. if (--terminal_width > MAX_WIDTH)
  471. terminal_width = MAX_WIDTH;
  472. }
  473. #else /* only ENABLE_SELINUX */
  474. i = getopt32(argv, "Z");
  475. #endif
  476. #if ENABLE_SELINUX
  477. if ((i & 1) && is_selinux_enabled())
  478. use_selinux = PSSCAN_CONTEXT;
  479. #endif
  480. #endif /* ENABLE_FEATURE_PS_WIDE || ENABLE_SELINUX */
  481. if (use_selinux)
  482. puts(" PID CONTEXT STAT COMMAND");
  483. else
  484. puts(" PID USER VSZ STAT COMMAND");
  485. while ((p = procps_scan(p, 0
  486. | PSSCAN_PID
  487. | PSSCAN_UIDGID
  488. | PSSCAN_STATE
  489. | PSSCAN_VSZ
  490. | PSSCAN_COMM
  491. | use_selinux
  492. ))) {
  493. #if ENABLE_SELINUX
  494. if (use_selinux) {
  495. len = printf("%5u %-32.32s %s ",
  496. p->pid,
  497. p->context ? p->context : "unknown",
  498. p->state);
  499. } else
  500. #endif
  501. {
  502. const char *user = get_cached_username(p->uid);
  503. //if (p->vsz == 0)
  504. // len = printf("%5u %-8.8s %s ",
  505. // p->pid, user, p->state);
  506. //else
  507. {
  508. char buf6[6];
  509. smart_ulltoa5(p->vsz, buf6, " mgtpezy");
  510. buf6[5] = '\0';
  511. len = printf("%5u %-8.8s %s %s ",
  512. p->pid, user, buf6, p->state);
  513. }
  514. }
  515. {
  516. int sz = terminal_width - len;
  517. char buf[sz + 1];
  518. read_cmdline(buf, sz, p->pid, p->comm);
  519. puts(buf);
  520. }
  521. }
  522. if (ENABLE_FEATURE_CLEAN_UP)
  523. clear_username_cache();
  524. return EXIT_SUCCESS;
  525. }
  526. #endif /* ENABLE_DESKTOP */