dtpstree.cpp 22 KB

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