dtpstree.cpp 24 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201
  1. // DT PS Tree
  2. //
  3. // Douglas Thrift
  4. //
  5. // dtpstree.cpp
  6. /* Copyright 2010 Douglas Thrift
  7. *
  8. * Licensed under the Apache License, Version 2.0 (the "License");
  9. * you may not use this file except in compliance with the License.
  10. * You may obtain a copy of the License at
  11. *
  12. * http://www.apache.org/licenses/LICENSE-2.0
  13. *
  14. * Unless required by applicable law or agreed to in writing, software
  15. * distributed under the License is distributed on an "AS IS" BASIS,
  16. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. * See the License for the specific language governing permissions and
  18. * limitations under the License.
  19. */
  20. #include <cerrno>
  21. #include <climits>
  22. #include <cstdarg>
  23. #include <cstdio>
  24. #include <cstdlib>
  25. #include <cstring>
  26. #include <iostream>
  27. #include <map>
  28. #include <set>
  29. #include <sstream>
  30. #include <string>
  31. #include <vector>
  32. #ifndef __GLIBC__
  33. #include <libgen.h>
  34. #endif
  35. #ifdef HAVE_TERMCAP_H
  36. #include <termcap.h>
  37. #elif defined(HAVE_NCURSES_TERM_H)
  38. #include <ncurses/ncurses.h>
  39. #include <ncurses/term.h>
  40. #elif defined(HAVE_TERM_H)
  41. #include <curses.h>
  42. #include <term.h>
  43. #endif
  44. #include <err.h>
  45. #include <fcntl.h>
  46. #include <getopt.h>
  47. #include <kvm.h>
  48. #include <paths.h>
  49. #include <pwd.h>
  50. #include <sys/param.h>
  51. #include <sys/sysctl.h>
  52. #include <sys/user.h>
  53. #include <sys/utsname.h>
  54. #include <unistd.h>
  55. #include <vis.h>
  56. #include "foreach.hpp"
  57. namespace kvm
  58. {
  59. #if HAVE_DECL_KERN_PROC_PROC
  60. const int All(KERN_PROC_PROC);
  61. #elif HAVE_DECL_KERN_PROC_KTHREAD
  62. const int All(KERN_PROC_KTHREAD);
  63. #else
  64. const int All(KERN_PROC_ALL);
  65. #endif
  66. template <typename Type>
  67. inline Type *getprocs(kvm_t *kd, int &count);
  68. template <typename Type>
  69. inline char **getargv(kvm_t *kd, const Type *proc);
  70. template <typename Type>
  71. inline pid_t pid(Type *proc);
  72. template <typename Type>
  73. inline pid_t ppid(Type *proc);
  74. template <typename Type>
  75. inline uid_t ruid(Type *proc);
  76. template <typename Type>
  77. inline char *comm(Type *proc);
  78. #ifndef HAVE_STRUCT_KINFO_PROC2
  79. typedef kinfo_proc Proc;
  80. const int Flags(O_RDONLY);
  81. template <>
  82. inline kinfo_proc *getprocs(kvm_t *kd, int &count)
  83. {
  84. return kvm_getprocs(kd, All, 0, &count);
  85. }
  86. template <>
  87. inline char **getargv(kvm_t *kd, const kinfo_proc *proc)
  88. {
  89. return kvm_getargv(kd, proc, 0);
  90. }
  91. #else
  92. typedef kinfo_proc2 Proc;
  93. const int Flags(KVM_NO_FILES);
  94. template <>
  95. inline kinfo_proc2 *getprocs(kvm_t *kd, int &count)
  96. {
  97. return kvm_getproc2(kd, All, 0, sizeof (kinfo_proc2), &count);
  98. }
  99. template <>
  100. inline char **getargv(kvm_t *kd, const kinfo_proc2 *proc)
  101. {
  102. return kvm_getargv2(kd, proc, 0);
  103. }
  104. #endif
  105. template <>
  106. inline pid_t pid(Proc *proc)
  107. {
  108. # ifdef HAVE_STRUCT_KINFO_PROCX_KI_PID
  109. return proc->ki_pid;
  110. # elif defined(HAVE_STRUCT_KINFO_PROCX_P_PID)
  111. return proc->p_pid;
  112. # endif
  113. }
  114. template <>
  115. inline pid_t ppid(Proc *proc)
  116. {
  117. # ifdef HAVE_STRUCT_KINFO_PROCX_KI_PPID
  118. return proc->ki_ppid;
  119. # elif defined(HAVE_STRUCT_KINFO_PROCX_P_PPID)
  120. return proc->p_ppid;
  121. # endif
  122. }
  123. template <>
  124. inline uid_t ruid(Proc *proc)
  125. {
  126. # ifdef HAVE_STRUCT_KINFO_PROCX_KI_RUID
  127. return proc->ki_ruid;
  128. # elif defined(HAVE_STRUCT_KINFO_PROCX_P_RUID)
  129. return proc->p_ruid;
  130. # endif
  131. }
  132. template <>
  133. inline char *comm(Proc *proc)
  134. {
  135. # ifdef HAVE_STRUCT_KINFO_PROCX_KI_COMM
  136. return proc->ki_comm;
  137. # elif defined(HAVE_STRUCT_KINFO_PROCX_P_COMM)
  138. return proc->p_comm;
  139. # endif
  140. }
  141. }
  142. enum Flags
  143. {
  144. Arguments = 0x0001,
  145. Ascii = 0x0002,
  146. NoCompact = 0x0004,
  147. Highlight = 0x0008,
  148. Vt100 = 0x0010,
  149. ShowKernel = 0x0020,
  150. Long = 0x0040,
  151. NumericSort = 0x0080,
  152. ShowPids = 0x0100,
  153. ShowTitles = 0x0200,
  154. UidChanges = 0x0400,
  155. Unicode = 0x0800,
  156. Pid = 0x1000,
  157. User = 0x2000
  158. };
  159. enum Escape { None, BoxDrawing, Bright };
  160. struct Segment
  161. {
  162. size_t width_;
  163. Escape escape_;
  164. char *string_;
  165. inline Segment(size_t width, Escape escape, char *string) : width_(width), escape_(escape), string_(string) {}
  166. };
  167. struct Branch
  168. {
  169. std::string indentation_;
  170. bool done_;
  171. inline Branch(size_t indentation) : indentation_(indentation, ' '), done_(false) {}
  172. };
  173. class Tree
  174. {
  175. const uint16_t &flags_;
  176. bool vt100_;
  177. wchar_t horizontal_, vertical_, upAndRight_, verticalAndRight_, downAndHorizontal_;
  178. size_t maxWidth_, width_;
  179. bool max_, suppress_;
  180. std::vector<Segment> segments_;
  181. std::vector<Branch> branches_;
  182. bool first_, last_;
  183. size_t duplicate_;
  184. public:
  185. Tree(const uint16_t &flags) : flags_(flags), vt100_(false), maxWidth_(0), width_(0), max_(false), suppress_(false), duplicate_(0)
  186. {
  187. bool tty(isatty(1));
  188. if (flags & Ascii)
  189. {
  190. ascii:
  191. horizontal_ = L'-';
  192. vertical_ = L'|';
  193. upAndRight_ = L'`';
  194. verticalAndRight_ = L'|';
  195. downAndHorizontal_ = L'+';
  196. }
  197. else if (flags & Unicode)
  198. {
  199. unicode:
  200. if (!std::setlocale(LC_CTYPE, ""))
  201. goto vt100;
  202. horizontal_ = L'\x2500';
  203. vertical_ = L'\x2502';
  204. upAndRight_ = L'\x2514';
  205. verticalAndRight_ = L'\x251c';
  206. downAndHorizontal_ = L'\x252c';
  207. wchar_t wides[] = { horizontal_, vertical_, upAndRight_, verticalAndRight_, downAndHorizontal_ };
  208. for (int index(0); index != sizeof (wides) / sizeof (*wides); ++index)
  209. {
  210. char buffer[MB_CUR_MAX];
  211. int size;
  212. if ((size = std::wctomb(buffer, wides[index])) == -1)
  213. goto vt100;
  214. wchar_t wide;
  215. if (std::mbtowc(&wide, buffer, size) == -1)
  216. goto vt100;
  217. if (wide != wides[index])
  218. goto vt100;
  219. }
  220. }
  221. else if (flags & Vt100)
  222. {
  223. vt100:
  224. vt100_ = true;
  225. horizontal_ = L'\x71';
  226. vertical_ = L'\x78';
  227. upAndRight_ = L'\x6d';
  228. verticalAndRight_ = L'\x74';
  229. downAndHorizontal_ = L'\x77';
  230. }
  231. else if (tty)
  232. goto unicode;
  233. else
  234. goto ascii;
  235. if (!(flags & Long) && tty)
  236. {
  237. # ifndef HAVE_TERMCAP_H
  238. int code;
  239. if (setupterm(NULL, 1, &code) == OK)
  240. {
  241. maxWidth_ = tigetnum(const_cast<char *>("cols"));
  242. if (tigetflag(const_cast<char *>("am")) && !tigetflag(const_cast<char *>("xenl")))
  243. suppress_ = true;
  244. }
  245. # else
  246. char buffer[1024], *term(std::getenv("TERM"));
  247. if (term != NULL && tgetent(buffer, term) == 1)
  248. {
  249. maxWidth_ = tgetnum("co");
  250. if (tgetflag("am") && !tgetflag("xn"))
  251. suppress_ = true;
  252. }
  253. # endif
  254. else
  255. maxWidth_ = 80;
  256. }
  257. }
  258. void print(const std::string &string, bool highlight, size_t duplicate)
  259. {
  260. Escape escape(vt100_ ? BoxDrawing : None);
  261. if (!first_ || flags_ & Arguments)
  262. {
  263. size_t last(branches_.size() - 1);
  264. _foreach (std::vector<Branch>, branch, branches_)
  265. {
  266. size_t width(branch->indentation_.size() + 2);
  267. if (_index == last)
  268. {
  269. wchar_t line;
  270. if (last_)
  271. {
  272. branch->done_ = true;
  273. line = upAndRight_;
  274. }
  275. else
  276. line = verticalAndRight_;
  277. print(width, escape, "%s%lc%lc", branch->indentation_.c_str(), line, horizontal_);
  278. }
  279. else
  280. print(width, escape, "%s%lc ", branch->indentation_.c_str(), branch->done_ ? ' ' : vertical_);
  281. }
  282. }
  283. else if (branches_.size())
  284. {
  285. wchar_t line;
  286. if (last_)
  287. {
  288. branches_.back().done_ = true;
  289. line = horizontal_;
  290. }
  291. else
  292. line = downAndHorizontal_;
  293. print(3, escape, "%lc%lc%lc", horizontal_, line, horizontal_);
  294. }
  295. size_t size(0);
  296. if (duplicate)
  297. {
  298. std::ostringstream string;
  299. string << duplicate << "*[";
  300. size = string.str().size();
  301. print(size, None, "%s", string.str().c_str());
  302. ++duplicate_;
  303. }
  304. print(string.size(), highlight ? Bright : None, "%s", string.c_str());
  305. branches_.push_back(Branch(!(flags_ & Arguments) ? size + string.size() + 1 : 2));
  306. }
  307. inline void printArg(const std::string &arg, bool last)
  308. {
  309. if (max_)
  310. return;
  311. size_t width(arg.size() + 1);
  312. width_ += width;
  313. char *string;
  314. if (maxWidth_ && !(flags_ & Long))
  315. if (width_ > maxWidth_ || !last && width_ + 3 >= maxWidth_)
  316. {
  317. width -= width_ - maxWidth_;
  318. width_ = maxWidth_;
  319. max_ = true;
  320. ssize_t size(static_cast<ssize_t>(width) - 4);
  321. asprintf(&string, " %s...", size > 0 ? arg.substr(0, size).c_str() : "");
  322. }
  323. else
  324. goto print;
  325. else
  326. print:
  327. asprintf(&string, " %s", arg.c_str());
  328. segments_.push_back(Segment(width, None, string));
  329. }
  330. inline void pop(bool children)
  331. {
  332. branches_.pop_back();
  333. if (!(flags_ & Arguments) && !children)
  334. done();
  335. }
  336. void done()
  337. {
  338. if (duplicate_)
  339. {
  340. print(duplicate_, None, "%s", std::string(duplicate_, ']').c_str());
  341. duplicate_ = 0;
  342. }
  343. size_t last(segments_.size() - 1);
  344. _foreach (std::vector<Segment>, segment, segments_)
  345. {
  346. const char *begin, *end;
  347. switch (segment->escape_)
  348. {
  349. case BoxDrawing:
  350. begin = !_index || (segment - 1)->escape_ != BoxDrawing ? "\033(0\017" : "";
  351. end = _index == last || (segment + 1)->escape_ != BoxDrawing ? "\033(B\017" : "";
  352. break;
  353. case Bright:
  354. begin = "\033[1m";
  355. end = "\033[22m";
  356. break;
  357. default:
  358. begin = end = ""; break;
  359. }
  360. std::printf("%s%s%s", begin, segment->string_, end);
  361. std::free(segment->string_);
  362. }
  363. segments_.clear();
  364. if (suppress_ && width_ == maxWidth_)
  365. std::fflush(stdout);
  366. else
  367. std::printf("\n");
  368. width_ = 0;
  369. max_ = false;
  370. }
  371. inline Tree &operator()(bool first, bool last)
  372. {
  373. first_ = first;
  374. last_ = last;
  375. return *this;
  376. }
  377. private:
  378. void print(size_t width, Escape escape, const char * format, ...)
  379. {
  380. if (max_)
  381. return;
  382. std::va_list args;
  383. va_start(args, format);
  384. char *string;
  385. vasprintf(&string, format, args);
  386. va_end(args);
  387. width_ += width;
  388. if (maxWidth_ && !(flags_ & Long))
  389. if (width_ > maxWidth_)
  390. {
  391. width -= width_ - maxWidth_;
  392. width_ = maxWidth_;
  393. max_ = true;
  394. bool previous = !width;
  395. if (previous)
  396. {
  397. std::free(string);
  398. const Segment &segment(segments_.back());
  399. width = segment.width_;
  400. string = segment.string_;
  401. }
  402. std::wstring wide(width - 1, '\0');
  403. std::mbstowcs(const_cast<wchar_t *>(wide.data()), string, wide.size());
  404. std::free(string);
  405. wide += L'+';
  406. size_t size(std::wcstombs(NULL, wide.c_str(), 0) + 1);
  407. string = static_cast<char *>(std::malloc(size));
  408. std::wcstombs(string, wide.c_str(), size);
  409. if (previous)
  410. {
  411. segments_.back().string_ = string;
  412. return;
  413. }
  414. }
  415. segments_.push_back(Segment(width, escape, string));
  416. }
  417. };
  418. template <typename Type>
  419. struct Proc
  420. {
  421. typedef std::map<pid_t, Proc<Type> *> PidMap;
  422. typedef std::multimap<std::string, Proc<Type> *> NameMap;
  423. private:
  424. const uint16_t &flags_;
  425. kvm_t *kd_;
  426. Type *proc_;
  427. mutable std::string name_, print_;
  428. Proc<Type> *parent_;
  429. PidMap childrenByPid_;
  430. NameMap childrenByName_;
  431. bool highlight_, root_;
  432. int8_t compact_;
  433. size_t duplicate_;
  434. public:
  435. inline Proc(const uint16_t &flags, kvm_t *kd, Type *proc) : flags_(flags), kd_(kd), proc_(proc), parent_(NULL), highlight_(false), root_(false), compact_(-1), duplicate_(0) {}
  436. inline const std::string &name() const
  437. {
  438. if (name_.empty())
  439. name_ = visual(kvm::comm(proc_));
  440. return name_;
  441. }
  442. inline pid_t parent() const { return kvm::ppid(proc_); }
  443. inline pid_t pid() const { return kvm::pid(proc_); }
  444. inline void child(Proc *proc)
  445. {
  446. if (proc == this)
  447. return;
  448. proc->parent_ = this;
  449. childrenByPid_[proc->pid()] = proc;
  450. childrenByName_.insert(typename NameMap::value_type(proc->name(), proc));
  451. }
  452. inline void highlight()
  453. {
  454. highlight_ = true;
  455. if (parent_)
  456. parent_->highlight();
  457. }
  458. inline bool compact()
  459. {
  460. if (compact_ == -1)
  461. compact_ = compact(childrenByName_);
  462. return compact_;
  463. }
  464. bool root(uid_t uid)
  465. {
  466. if (flags_ & User)
  467. {
  468. if (uid == this->uid())
  469. {
  470. Proc *parent(parent_);
  471. while (parent)
  472. {
  473. if (parent->uid() == uid)
  474. return false;
  475. parent = parent->parent_;
  476. }
  477. return root_ = true;
  478. }
  479. return false;
  480. }
  481. return root_ = !parent_;
  482. }
  483. inline void printByPid(Tree &tree) const
  484. {
  485. print(tree, childrenByPid_);
  486. }
  487. inline void printByName(Tree &tree) const
  488. {
  489. print(tree, childrenByName_);
  490. }
  491. static bool compact(NameMap &names)
  492. {
  493. Proc *previous(NULL);
  494. bool compact(true);
  495. _tforeach (NameMap, name, names)
  496. {
  497. Proc *proc(name->second);
  498. if (proc->duplicate_)
  499. continue;
  500. size_t duplicate(proc->compact());
  501. if (compact && duplicate && (!previous || proc->print() == previous->print()))
  502. previous = proc;
  503. else
  504. compact = false;
  505. size_t count(names.count(name->first));
  506. if (!duplicate || count == 1)
  507. continue;
  508. _forall(typename NameMap::iterator, n4me, (++name)--, names.upper_bound(name->first))
  509. {
  510. Proc *pr0c(n4me->second);
  511. if (pr0c->compact() && Proc::compact(proc, pr0c))
  512. duplicate += ++pr0c->duplicate_;
  513. }
  514. if (duplicate != 1)
  515. proc->duplicate_ = duplicate;
  516. }
  517. return compact;
  518. }
  519. private:
  520. inline std::string visual(const char *string) const
  521. {
  522. std::string visual(std::strlen(string) * 4 + 1, '\0');
  523. visual.resize(strvis(const_cast<char *>(visual.data()), string, VIS_TAB | VIS_NL | VIS_NOSLASH));
  524. return visual;
  525. }
  526. template <typename Map>
  527. void print(Tree &tree, const Map &children) const
  528. {
  529. if (duplicate_ == 1)
  530. return;
  531. print(tree);
  532. size_t size(children.size()), last(size - 1);
  533. _tforeach (const Map, child, children)
  534. {
  535. Proc<Type> *proc(child->second);
  536. bool l4st(_index + (proc->duplicate_ ? proc->duplicate_ - 1 : 0) == last);
  537. if (!l4st)
  538. {
  539. l4st = true;
  540. for (++child; child != _end; ++child)
  541. if (child->second->duplicate_ != 1)
  542. {
  543. l4st = false;
  544. break;
  545. }
  546. --child;
  547. }
  548. proc->print(tree(!_index, l4st), proc->template children<Map>());
  549. if (l4st)
  550. break;
  551. }
  552. tree.pop(size);
  553. }
  554. void print(Tree &tree) const
  555. {
  556. tree.print(print(), highlight_, duplicate_);
  557. if (flags_ & Arguments)
  558. {
  559. char **argv(kvm::getargv(kd_, proc_));
  560. if (argv && *argv)
  561. for (++argv; *argv; ++argv)
  562. tree.printArg(visual(*argv), !*(argv + 1));
  563. tree.done();
  564. }
  565. }
  566. const std::string &print() const
  567. {
  568. if (print_.empty())
  569. {
  570. std::ostringstream print;
  571. if (flags_ & ShowTitles)
  572. {
  573. char **argv(kvm::getargv(kd_, proc_));
  574. if (argv)
  575. print << visual(*argv);
  576. else
  577. print << name();
  578. }
  579. else
  580. print << name();
  581. bool p1d(flags_ & ShowPids), args(flags_ & Arguments);
  582. bool change(flags_ & UidChanges && (root_ ? !(flags_ & User) && uid() : parent_ && uid() != parent_->uid()));
  583. bool parens((p1d || change) && !args);
  584. if (parens)
  585. print << '(';
  586. if (p1d)
  587. {
  588. if (!parens)
  589. print << ',';
  590. print << pid();
  591. }
  592. if (change)
  593. {
  594. if (!parens || p1d)
  595. print << ',';
  596. passwd *user(getpwuid(uid()));
  597. print << user->pw_name;
  598. }
  599. if (parens)
  600. print << ')';
  601. print_ = print.str();
  602. }
  603. return print_;
  604. }
  605. inline uid_t uid() const { return kvm::ruid(proc_); }
  606. template <typename Map>
  607. inline const Map &children() const;
  608. inline bool hasChildren() const { return childrenByName_.size(); }
  609. inline Proc<Type> *child() const { return childrenByName_.begin()->second; }
  610. inline static bool compact(Proc<Type> *one, Proc<Type> *two)
  611. {
  612. if (one->print() != two->print())
  613. return false;
  614. if (one->hasChildren() != two->hasChildren())
  615. return false;
  616. if (one->hasChildren() && !compact(one->child(), two->child()))
  617. return false;
  618. if (two->highlight_)
  619. one->highlight_ = true;
  620. return true;
  621. }
  622. };
  623. template <> template <>
  624. inline const Proc<kvm::Proc>::PidMap &Proc<kvm::Proc>::children() const
  625. {
  626. return childrenByPid_;
  627. }
  628. template <> template <>
  629. inline const Proc<kvm::Proc>::NameMap &Proc<kvm::Proc>::children() const
  630. {
  631. return childrenByName_;
  632. }
  633. static void help(char *program, option options[], int code = 0)
  634. {
  635. std::printf("Usage: %s [options] [PID|USER]\n\nOptions:\n", basename(program));
  636. for (option *option(options); option->name; ++option)
  637. {
  638. std::string name(option->name);
  639. std::ostringstream arguments;
  640. switch (option->val)
  641. {
  642. case 'H':
  643. if (name != "highlight")
  644. continue;
  645. arguments << "-H[PID], --highlight[=PID]"; break;
  646. case 0:
  647. if (name == "pid")
  648. arguments << "PID, --pid=PID";
  649. else if (name == "user")
  650. arguments << "USER, --user=USER";
  651. else
  652. goto argument;
  653. break;
  654. case 'c':
  655. if (name != "no-compact")
  656. continue;
  657. default:
  658. arguments << '-' << static_cast<char>(option->val) << ", ";
  659. argument:
  660. arguments << "--" << name;
  661. }
  662. const char *description("");
  663. switch (option->val)
  664. {
  665. case 'a':
  666. description = "show command line arguments"; break;
  667. case 'A':
  668. description = "use ASCII line drawing characters"; break;
  669. case 'c':
  670. description = "don't compact identical subtrees"; break;
  671. case 'h':
  672. description = "show this help message and exit"; break;
  673. case 'H':
  674. description = "highlight the current process (or PID) and its\n ancestors"; break;
  675. case 'G':
  676. description = "use VT100 line drawing characters"; break;
  677. case 'k':
  678. description = "show kernel processes"; break;
  679. case 'l':
  680. description = "don't truncate long lines"; break;
  681. case 'n':
  682. description = "sort output by PID"; break;
  683. case 'p':
  684. description = "show PIDs; implies -c"; break;
  685. case 't':
  686. description = "show process titles"; break;
  687. case 'u':
  688. description = "show uid transitions"; break;
  689. case 'U':
  690. description = "use Unicode line drawing characters"; break;
  691. case 'V':
  692. description = "show version information and exit"; break;
  693. case 0:
  694. if (name == "pid")
  695. description = "show only the tree rooted at the process PID";
  696. else if (name == "user")
  697. description = "show only trees rooted at processes of USER";
  698. }
  699. std::printf(" %-27s %s\n", arguments.str().c_str(), description);
  700. }
  701. std::exit(code);
  702. }
  703. template <typename Type, long minimum, long maximum>
  704. static Type value(char *program, option options[], bool *success = NULL)
  705. {
  706. char *end;
  707. long value(std::strtol(optarg, &end, 0));
  708. errno = 0;
  709. if (optarg == end || *end != '\0')
  710. if (success)
  711. *success = false;
  712. else
  713. {
  714. warnx("Number is invalid: \"%s\"", optarg);
  715. help(program, options, 1);
  716. }
  717. else if (value < minimum || value == LONG_MIN && errno == ERANGE)
  718. {
  719. warnx("Number is too small: \"%s\"", optarg);
  720. help(program, options, 1);
  721. }
  722. else if (value > maximum || value == LONG_MAX && errno == ERANGE)
  723. {
  724. warnx("Number is too large: \"%s\"", optarg);
  725. help(program, options, 1);
  726. }
  727. else if (success)
  728. *success = true;
  729. return value;
  730. }
  731. static uint16_t options(int argc, char *argv[], pid_t &hpid, pid_t &pid, char *&user)
  732. {
  733. option options[] = {
  734. { "arguments", no_argument, NULL, 'a' },
  735. { "ascii", no_argument, NULL, 'A' },
  736. { "compact", no_argument, NULL, 'c' },
  737. { "no-compact", no_argument, NULL, 'c' },
  738. { "help", no_argument, NULL, 'h' },
  739. { "highlight", optional_argument, NULL, 'H' },
  740. { "highlight-all", no_argument, NULL, 'H' },
  741. { "highlight-pid", required_argument, NULL, 'H' },
  742. { "vt100", no_argument, NULL, 'G' },
  743. { "show-kernel", no_argument, NULL, 'k' },
  744. { "long", no_argument, NULL, 'l' },
  745. { "numeric-sort", no_argument, NULL, 'n' },
  746. { "show-pids", no_argument, NULL, 'p' },
  747. { "show-titles", no_argument, NULL, 't' },
  748. { "uid-changes", no_argument, NULL, 'u' },
  749. { "unicode", no_argument, NULL, 'U' },
  750. { "version", optional_argument, NULL, 'V' },
  751. { "pid", required_argument, NULL, 0 },
  752. { "user", required_argument, NULL, 0 },
  753. { NULL, 0, NULL, 0 }
  754. };
  755. int option, index;
  756. uint16_t flags(0);
  757. char *program(argv[0]);
  758. while ((option = getopt_long(argc, argv, "aAchH::GklnptuUV::", options, &index)) != -1)
  759. switch (option)
  760. {
  761. case 'a':
  762. flags |= Arguments | NoCompact; break;
  763. case 'A':
  764. flags |= Ascii;
  765. flags &= ~Vt100;
  766. flags &= ~Unicode;
  767. break;
  768. case 'c':
  769. flags |= NoCompact; break;
  770. case 'h':
  771. help(program, options);
  772. case 'H':
  773. hpid = optarg ? value<pid_t, 0, INT_MAX>(program, options) : getpid();
  774. flags |= Highlight;
  775. break;
  776. case 'G':
  777. flags |= Vt100;
  778. flags &= ~Ascii;
  779. flags &= ~Unicode;
  780. break;
  781. case 'k':
  782. flags |= ShowKernel; break;
  783. case 'l':
  784. flags |= Long; break;
  785. case 'n':
  786. flags |= NumericSort; break;
  787. case 'p':
  788. flags |= NoCompact | ShowPids; break;
  789. case 't':
  790. flags |= ShowTitles; break;
  791. case 'u':
  792. flags |= UidChanges; break;
  793. case 'U':
  794. flags |= Unicode;
  795. flags &= ~Ascii;
  796. flags &= ~Vt100;
  797. break;
  798. case 'V':
  799. {
  800. std::string version(optarg ? optarg : "");
  801. if (version == "s" || version == "short")
  802. std::printf(PACKAGE_TARNAME " " PACKAGE_VERSION "\n");
  803. else
  804. {
  805. utsname name;
  806. if (uname(&name))
  807. err(1, NULL);
  808. std::printf(PACKAGE_TARNAME " " PACKAGE_VERSION " - %s %s %s\n", name.sysname, name.release, name.machine);
  809. }
  810. if (version == "l" || version == "license")
  811. std::printf("\n"
  812. " Copyright 2010 Douglas Thrift\n\n"
  813. " Licensed under the Apache License, Version 2.0 (the \"License\");\n"
  814. " you may not use this file except in compliance with the License.\n"
  815. " You may obtain a copy of the License at\n\n"
  816. " http://www.apache.org/licenses/LICENSE-2.0\n\n"
  817. " Unless required by applicable law or agreed to in writing, software\n"
  818. " distributed under the License is distributed on an \"AS IS\" BASIS,\n"
  819. " WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n"
  820. " See the License for the specific language governing permissions and\n"
  821. " limitations under the License.\n");
  822. std::exit(0);
  823. }
  824. case 0:
  825. {
  826. std::string option(options[index].name);
  827. if (option == "pid")
  828. {
  829. pid = value<pid_t, 0, INT_MAX>(program, options);
  830. flags |= Pid;
  831. flags &= ~User;
  832. }
  833. else if (option == "user")
  834. {
  835. std::free(user);
  836. user = strdup(optarg);
  837. flags |= User;
  838. flags &= ~Pid;
  839. }
  840. }
  841. break;
  842. case '?':
  843. help(program, options, 1);
  844. }
  845. _forall (int, index, optind, argc)
  846. {
  847. bool success(false);
  848. optarg = argv[index];
  849. pid = value<pid_t, 0, INT_MAX>(program, options, &success);
  850. if (success)
  851. {
  852. flags |= Pid;
  853. flags &= ~User;
  854. }
  855. else
  856. {
  857. std::free(user);
  858. user = strdup(optarg);
  859. flags |= User;
  860. flags &= ~Pid;
  861. }
  862. }
  863. return flags;
  864. }
  865. template <typename Type, int Flags>
  866. static void tree(pid_t hpid, pid_t pid, uint16_t flags, uid_t uid)
  867. {
  868. char error[_POSIX2_LINE_MAX];
  869. kvm_t *kd(kvm_openfiles(NULL, _PATH_DEVNULL, NULL, Flags, error));
  870. if (!kd)
  871. errx(1, "%s", error);
  872. int count;
  873. Type *procs(kvm::getprocs<Type>(kd, count));
  874. if (!procs)
  875. errx(1, "%s", kvm_geterr(kd));
  876. typedef Type *Pointer;
  877. typename Proc<Type>::PidMap pids;
  878. _forall (Pointer, proc, procs, procs + count)
  879. if (flags & ShowKernel || kvm::ppid(proc) != 0 || kvm::pid(proc) == 1)
  880. pids[kvm::pid(proc)] = new Proc<Type>(flags, kd, proc);
  881. enum { PidSort, NameSort } sort(flags & NumericSort ? PidSort : NameSort);
  882. _tforeach (typename Proc<Type>::PidMap, pid, pids)
  883. {
  884. Proc<Type> *proc(pid->second);
  885. typename Proc<Type>::PidMap::iterator parent(pids.find(proc->parent()));
  886. if (parent != pids.end())
  887. parent->second->child(proc);
  888. }
  889. if (flags & Highlight)
  890. {
  891. typename Proc<Type>::PidMap::iterator pid(pids.find(hpid));
  892. if (pid != pids.end())
  893. pid->second->highlight();
  894. }
  895. Tree tree(flags);
  896. if (flags & Pid)
  897. {
  898. typename Proc<Type>::PidMap::iterator p1d(pids.find(pid));
  899. if (p1d != pids.end())
  900. {
  901. Proc<Type> *proc(p1d->second);
  902. if (!(flags & NoCompact))
  903. proc->compact();
  904. switch (sort)
  905. {
  906. case PidSort:
  907. proc->printByPid(tree);
  908. break;
  909. case NameSort:
  910. proc->printByName(tree);
  911. }
  912. }
  913. }
  914. else
  915. {
  916. typename Proc<Type>::NameMap names;
  917. _tforeach (typename Proc<Type>::PidMap, pid, pids)
  918. {
  919. Proc<Type> *proc(pid->second);
  920. if (proc->root(uid))
  921. names.insert(typename Proc<Type>::NameMap::value_type(proc->name(), proc));
  922. }
  923. if (!(flags & NoCompact))
  924. Proc<Type>::compact(names);
  925. switch (sort)
  926. {
  927. case PidSort:
  928. _tforeach (typename Proc<Type>::PidMap, pid, pids)
  929. {
  930. Proc<Type> *proc(pid->second);
  931. if (proc->root(uid))
  932. proc->printByPid(tree);
  933. }
  934. break;
  935. case NameSort:
  936. _tforeach (typename Proc<Type>::NameMap, name, names)
  937. name->second->printByName(tree);
  938. }
  939. }
  940. _tforeach (typename Proc<Type>::PidMap, pid, pids)
  941. delete pid->second;
  942. }
  943. int main(int argc, char *argv[])
  944. {
  945. pid_t hpid(0), pid(0);
  946. char *user(NULL);
  947. uint16_t flags(options(argc, argv, hpid, pid, user));
  948. uid_t uid(0);
  949. if (flags & User)
  950. {
  951. errno = 0;
  952. passwd *us3r(getpwnam(user));
  953. if (!us3r)
  954. errno ? err(1, NULL) : errx(1, "Unknown user: \"%s\"", user);
  955. uid = us3r->pw_uid;
  956. }
  957. tree<kvm::Proc, kvm::Flags>(hpid, pid, flags, uid);
  958. return 0;
  959. }
  960. // display a tree of processes