dtpstree.cpp 22 KB

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