dtpstree.cpp 25 KB

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