dtpstree.cpp 25 KB

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