dtpstree.cpp 24 KB

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