dtpstree.cpp 22 KB

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