dtpstree.cpp 19 KB

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