ps.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  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" 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. out = xrealloc_vector(out, 2, out_cnt);
  263. return &out[out_cnt++];
  264. }
  265. static const ps_out_t* find_out_spec(const char *name)
  266. {
  267. unsigned i;
  268. for (i = 0; i < ARRAY_SIZE(out_spec); i++) {
  269. if (!strcmp(name, out_spec[i].name))
  270. return &out_spec[i];
  271. }
  272. bb_error_msg_and_die("bad -o argument '%s'", name);
  273. }
  274. static void parse_o(char* opt)
  275. {
  276. ps_out_t* new;
  277. // POSIX: "-o is blank- or comma-separated list" (FIXME)
  278. char *comma, *equal;
  279. while (1) {
  280. comma = strchr(opt, ',');
  281. equal = strchr(opt, '=');
  282. if (comma && (!equal || equal > comma)) {
  283. *comma = '\0';
  284. *new_out_t() = *find_out_spec(opt);
  285. *comma = ',';
  286. opt = comma + 1;
  287. continue;
  288. }
  289. break;
  290. }
  291. // opt points to last spec in comma separated list.
  292. // This one can have =HEADER part.
  293. new = new_out_t();
  294. if (equal)
  295. *equal = '\0';
  296. *new = *find_out_spec(opt);
  297. if (equal) {
  298. *equal = '=';
  299. new->header = equal + 1;
  300. // POSIX: the field widths shall be ... at least as wide as
  301. // the header text (default or overridden value).
  302. // If the header text is null, such as -o user=,
  303. // the field width shall be at least as wide as the
  304. // default header text
  305. if (new->header[0]) {
  306. new->width = strlen(new->header);
  307. print_header = 1;
  308. }
  309. } else
  310. print_header = 1;
  311. }
  312. static void post_process(void)
  313. {
  314. int i;
  315. int width = 0;
  316. for (i = 0; i < out_cnt; i++) {
  317. need_flags |= out[i].ps_flags;
  318. if (out[i].header[0]) {
  319. print_header = 1;
  320. }
  321. width += out[i].width + 1; /* "FIELD " */
  322. }
  323. #if ENABLE_SELINUX
  324. if (!is_selinux_enabled())
  325. need_flags &= ~PSSCAN_CONTEXT;
  326. #endif
  327. buffer = xmalloc(width + 1); /* for trailing \0 */
  328. }
  329. static void format_header(void)
  330. {
  331. int i;
  332. ps_out_t* op;
  333. char *p;
  334. if (!print_header)
  335. return;
  336. p = buffer;
  337. i = 0;
  338. if (out_cnt) {
  339. while (1) {
  340. op = &out[i];
  341. if (++i == out_cnt) /* do not pad last field */
  342. break;
  343. p += sprintf(p, "%-*s ", op->width, op->header);
  344. }
  345. strcpy(p, op->header);
  346. }
  347. printf("%.*s\n", terminal_width, buffer);
  348. }
  349. static void format_process(const procps_status_t *ps)
  350. {
  351. int i, len;
  352. char *p = buffer;
  353. i = 0;
  354. if (out_cnt) while (1) {
  355. out[i].f(p, out[i].width, ps);
  356. // POSIX: Any field need not be meaningful in all
  357. // implementations. In such a case a hyphen ( '-' )
  358. // should be output in place of the field value.
  359. if (!p[0]) {
  360. p[0] = '-';
  361. p[1] = '\0';
  362. }
  363. len = strlen(p);
  364. p += len;
  365. len = out[i].width - len + 1;
  366. if (++i == out_cnt) /* do not pad last field */
  367. break;
  368. p += sprintf(p, "%*s", len, "");
  369. }
  370. printf("%.*s\n", terminal_width, buffer);
  371. }
  372. int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  373. int ps_main(int argc UNUSED_PARAM, char **argv)
  374. {
  375. procps_status_t *p;
  376. llist_t* opt_o = NULL;
  377. USE_SELINUX(int opt;)
  378. // POSIX:
  379. // -a Write information for all processes associated with terminals
  380. // Implementations may omit session leaders from this list
  381. // -A Write information for all processes
  382. // -d Write information for all processes, except session leaders
  383. // -e Write information for all processes (equivalent to -A.)
  384. // -f Generate a full listing
  385. // -l Generate a long listing
  386. // -o col1,col2,col3=header
  387. // Select which columns to display
  388. /* We allow (and ignore) most of the above. FIXME */
  389. opt_complementary = "o::";
  390. USE_SELINUX(opt =) getopt32(argv, "Zo:aAdefl", &opt_o);
  391. if (opt_o) {
  392. do {
  393. parse_o(llist_pop(&opt_o));
  394. } while (opt_o);
  395. } else {
  396. /* Below: parse_o() needs char*, NOT const char*... */
  397. #if ENABLE_SELINUX
  398. if (!(opt & 1) || !is_selinux_enabled()) {
  399. /* no -Z or no SELinux: do not show LABEL */
  400. strcpy(default_o, DEFAULT_O_STR + sizeof(SELINUX_O_PREFIX)-1);
  401. } else
  402. #endif
  403. {
  404. strcpy(default_o, DEFAULT_O_STR);
  405. }
  406. parse_o(default_o);
  407. }
  408. post_process();
  409. /* Was INT_MAX, but some libc's go belly up with printf("%.*s")
  410. * and such large widths */
  411. terminal_width = MAX_WIDTH;
  412. if (isatty(1)) {
  413. get_terminal_width_height(0, &terminal_width, NULL);
  414. if (--terminal_width > MAX_WIDTH)
  415. terminal_width = MAX_WIDTH;
  416. }
  417. format_header();
  418. p = NULL;
  419. while ((p = procps_scan(p, need_flags))) {
  420. format_process(p);
  421. }
  422. return EXIT_SUCCESS;
  423. }
  424. #else /* !ENABLE_DESKTOP */
  425. int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  426. int ps_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  427. {
  428. procps_status_t *p = NULL;
  429. int len;
  430. SKIP_SELINUX(const) int use_selinux = 0;
  431. USE_SELINUX(int i;)
  432. #if !ENABLE_FEATURE_PS_WIDE
  433. enum { terminal_width = 79 };
  434. #else
  435. unsigned terminal_width;
  436. int w_count = 0;
  437. #endif
  438. #if ENABLE_FEATURE_PS_WIDE || ENABLE_SELINUX
  439. #if ENABLE_FEATURE_PS_WIDE
  440. opt_complementary = "-:ww";
  441. USE_SELINUX(i =) getopt32(argv, USE_SELINUX("Z") "w", &w_count);
  442. /* if w is given once, GNU ps sets the width to 132,
  443. * if w is given more than once, it is "unlimited"
  444. */
  445. if (w_count) {
  446. terminal_width = (w_count==1) ? 132 : MAX_WIDTH;
  447. } else {
  448. get_terminal_width_height(0, &terminal_width, NULL);
  449. /* Go one less... */
  450. if (--terminal_width > MAX_WIDTH)
  451. terminal_width = MAX_WIDTH;
  452. }
  453. #else /* only ENABLE_SELINUX */
  454. i = getopt32(argv, "Z");
  455. #endif
  456. #if ENABLE_SELINUX
  457. if ((i & 1) && is_selinux_enabled())
  458. use_selinux = PSSCAN_CONTEXT;
  459. #endif
  460. #endif /* ENABLE_FEATURE_PS_WIDE || ENABLE_SELINUX */
  461. if (use_selinux)
  462. puts(" PID CONTEXT STAT COMMAND");
  463. else
  464. puts(" PID USER VSZ STAT COMMAND");
  465. while ((p = procps_scan(p, 0
  466. | PSSCAN_PID
  467. | PSSCAN_UIDGID
  468. | PSSCAN_STATE
  469. | PSSCAN_VSZ
  470. | PSSCAN_COMM
  471. | use_selinux
  472. ))) {
  473. #if ENABLE_SELINUX
  474. if (use_selinux) {
  475. len = printf("%5u %-32.32s %s ",
  476. p->pid,
  477. p->context ? p->context : "unknown",
  478. p->state);
  479. } else
  480. #endif
  481. {
  482. const char *user = get_cached_username(p->uid);
  483. //if (p->vsz == 0)
  484. // len = printf("%5u %-8.8s %s ",
  485. // p->pid, user, p->state);
  486. //else
  487. {
  488. char buf6[6];
  489. smart_ulltoa5(p->vsz, buf6, " mgtpezy");
  490. buf6[5] = '\0';
  491. len = printf("%5u %-8.8s %s %s ",
  492. p->pid, user, buf6, p->state);
  493. }
  494. }
  495. {
  496. int sz = terminal_width - len;
  497. char buf[sz + 1];
  498. read_cmdline(buf, sz, p->pid, p->comm);
  499. puts(buf);
  500. }
  501. }
  502. if (ENABLE_FEATURE_CLEAN_UP)
  503. clear_username_cache();
  504. return EXIT_SUCCESS;
  505. }
  506. #endif /* ENABLE_DESKTOP */