main.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "IndividualSampleModel.h"
  7. #include "Profile.h"
  8. #include "TimelineContainer.h"
  9. #include "TimelineHeader.h"
  10. #include "TimelineTrack.h"
  11. #include "TimelineView.h"
  12. #include <LibCore/ArgsParser.h>
  13. #include <LibCore/ElapsedTimer.h>
  14. #include <LibCore/EventLoop.h>
  15. #include <LibCore/ProcessStatisticsReader.h>
  16. #include <LibCore/Timer.h>
  17. #include <LibDesktop/Launcher.h>
  18. #include <LibGUI/Action.h>
  19. #include <LibGUI/Application.h>
  20. #include <LibGUI/BoxLayout.h>
  21. #include <LibGUI/Button.h>
  22. #include <LibGUI/Label.h>
  23. #include <LibGUI/Menu.h>
  24. #include <LibGUI/Menubar.h>
  25. #include <LibGUI/MessageBox.h>
  26. #include <LibGUI/Model.h>
  27. #include <LibGUI/ProcessChooser.h>
  28. #include <LibGUI/Splitter.h>
  29. #include <LibGUI/Statusbar.h>
  30. #include <LibGUI/TabWidget.h>
  31. #include <LibGUI/TableView.h>
  32. #include <LibGUI/TreeView.h>
  33. #include <LibGUI/Window.h>
  34. #include <serenity.h>
  35. #include <string.h>
  36. using namespace Profiler;
  37. static bool generate_profile(pid_t& pid);
  38. int main(int argc, char** argv)
  39. {
  40. int pid = 0;
  41. const char* perfcore_file_arg = nullptr;
  42. Core::ArgsParser args_parser;
  43. args_parser.add_option(pid, "PID to profile", "pid", 'p', "PID");
  44. args_parser.add_positional_argument(perfcore_file_arg, "Path of perfcore file", "perfcore-file", Core::ArgsParser::Required::No);
  45. args_parser.parse(argc, argv);
  46. if (pid && perfcore_file_arg) {
  47. warnln("-p/--pid option and perfcore-file argument must not be used together!");
  48. return 1;
  49. }
  50. auto app = GUI::Application::construct(argc, argv);
  51. auto app_icon = GUI::Icon::default_icon("app-profiler");
  52. String perfcore_file;
  53. if (!perfcore_file_arg) {
  54. if (!generate_profile(pid))
  55. return 0;
  56. perfcore_file = String::formatted("/proc/{}/perf_events", pid);
  57. } else {
  58. perfcore_file = perfcore_file_arg;
  59. }
  60. auto profile_or_error = Profile::load_from_perfcore_file(perfcore_file);
  61. if (profile_or_error.is_error()) {
  62. GUI::MessageBox::show(nullptr, profile_or_error.error(), "Profiler", GUI::MessageBox::Type::Error);
  63. return 0;
  64. }
  65. auto& profile = profile_or_error.value();
  66. auto window = GUI::Window::construct();
  67. if (!Desktop::Launcher::add_allowed_handler_with_only_specific_urls(
  68. "/bin/Help",
  69. { URL::create_with_file_protocol("/usr/share/man/man1/Profiler.md") })
  70. || !Desktop::Launcher::seal_allowlist()) {
  71. warnln("Failed to set up allowed launch URLs");
  72. return 1;
  73. }
  74. window->set_title("Profiler");
  75. window->set_icon(app_icon.bitmap_for_size(16));
  76. window->resize(800, 600);
  77. auto& main_widget = window->set_main_widget<GUI::Widget>();
  78. main_widget.set_fill_with_background_color(true);
  79. main_widget.set_layout<GUI::VerticalBoxLayout>();
  80. auto timeline_header_container = GUI::Widget::construct();
  81. timeline_header_container->set_layout<GUI::VerticalBoxLayout>();
  82. timeline_header_container->set_fill_with_background_color(true);
  83. timeline_header_container->set_shrink_to_fit(true);
  84. auto timeline_view = TimelineView::construct();
  85. for (auto& process : profile->processes()) {
  86. bool matching_event_found = false;
  87. for (auto& event : profile->events()) {
  88. if (event.pid == process.pid && process.valid_at(event.timestamp)) {
  89. matching_event_found = true;
  90. break;
  91. }
  92. }
  93. if (!matching_event_found)
  94. continue;
  95. auto& timeline_header = timeline_header_container->add<TimelineHeader>(*profile, process);
  96. timeline_header.set_shrink_to_fit(true);
  97. timeline_header.on_selection_change = [&](bool selected) {
  98. if (selected) {
  99. auto end_valid = process.end_valid == 0 ? profile->last_timestamp() : process.end_valid;
  100. profile->set_process_filter(process.pid, process.start_valid, end_valid);
  101. } else
  102. profile->clear_process_filter();
  103. timeline_header_container->for_each_child_widget([](auto& other_timeline_header) {
  104. static_cast<TimelineHeader&>(other_timeline_header).update_selection();
  105. return IterationDecision::Continue;
  106. });
  107. };
  108. timeline_view->add<TimelineTrack>(*timeline_view, *profile, process);
  109. }
  110. auto& main_splitter = main_widget.add<GUI::VerticalSplitter>();
  111. [[maybe_unused]] auto& timeline_container = main_splitter.add<TimelineContainer>(*timeline_header_container, *timeline_view);
  112. auto& tab_widget = main_splitter.add<GUI::TabWidget>();
  113. auto& tree_tab = tab_widget.add_tab<GUI::Widget>("Call Tree");
  114. tree_tab.set_layout<GUI::VerticalBoxLayout>();
  115. tree_tab.layout()->set_margins({ 4, 4, 4, 4 });
  116. auto& bottom_splitter = tree_tab.add<GUI::VerticalSplitter>();
  117. auto& tree_view = bottom_splitter.add<GUI::TreeView>();
  118. tree_view.set_should_fill_selected_rows(true);
  119. tree_view.set_column_headers_visible(true);
  120. tree_view.set_model(profile->model());
  121. auto& disassembly_view = bottom_splitter.add<GUI::TableView>();
  122. tree_view.on_selection = [&](auto& index) {
  123. profile->set_disassembly_index(index);
  124. disassembly_view.set_model(profile->disassembly_model());
  125. };
  126. auto& samples_tab = tab_widget.add_tab<GUI::Widget>("Samples");
  127. samples_tab.set_layout<GUI::VerticalBoxLayout>();
  128. samples_tab.layout()->set_margins({ 4, 4, 4, 4 });
  129. auto& samples_splitter = samples_tab.add<GUI::HorizontalSplitter>();
  130. auto& samples_table_view = samples_splitter.add<GUI::TableView>();
  131. samples_table_view.set_model(profile->samples_model());
  132. auto& individual_sample_view = samples_splitter.add<GUI::TableView>();
  133. samples_table_view.on_selection = [&](const GUI::ModelIndex& index) {
  134. auto model = IndividualSampleModel::create(*profile, index.data(GUI::ModelRole::Custom).to_integer<size_t>());
  135. individual_sample_view.set_model(move(model));
  136. };
  137. const u64 start_of_trace = profile->first_timestamp();
  138. const u64 end_of_trace = start_of_trace + profile->length_in_ms();
  139. const auto clamp_timestamp = [start_of_trace, end_of_trace](u64 timestamp) -> u64 {
  140. return min(end_of_trace, max(timestamp, start_of_trace));
  141. };
  142. auto& statusbar = main_widget.add<GUI::Statusbar>();
  143. timeline_view->on_selection_change = [&] {
  144. auto& view = *timeline_view;
  145. StringBuilder builder;
  146. u64 normalized_start_time = clamp_timestamp(min(view.select_start_time(), view.select_end_time()));
  147. u64 normalized_end_time = clamp_timestamp(max(view.select_start_time(), view.select_end_time()));
  148. u64 normalized_hover_time = clamp_timestamp(view.hover_time());
  149. builder.appendff("Time: {} ms", normalized_hover_time - start_of_trace);
  150. if (normalized_start_time != normalized_end_time) {
  151. auto start = normalized_start_time - start_of_trace;
  152. auto end = normalized_end_time - start_of_trace;
  153. builder.appendff(", Selection: {} - {} ms", start, end);
  154. }
  155. statusbar.set_text(builder.to_string());
  156. };
  157. auto menubar = GUI::Menubar::construct();
  158. auto& file_menu = menubar->add_menu("&File");
  159. file_menu.add_action(GUI::CommonActions::make_quit_action([&](auto&) { app->quit(); }));
  160. auto& view_menu = menubar->add_menu("&View");
  161. auto invert_action = GUI::Action::create_checkable("&Invert Tree", { Mod_Ctrl, Key_I }, [&](auto& action) {
  162. profile->set_inverted(action.is_checked());
  163. });
  164. invert_action->set_checked(false);
  165. view_menu.add_action(invert_action);
  166. auto top_functions_action = GUI::Action::create_checkable("&Top Functions", { Mod_Ctrl, Key_T }, [&](auto& action) {
  167. profile->set_show_top_functions(action.is_checked());
  168. });
  169. top_functions_action->set_checked(false);
  170. view_menu.add_action(top_functions_action);
  171. auto percent_action = GUI::Action::create_checkable("Show &Percentages", { Mod_Ctrl, Key_P }, [&](auto& action) {
  172. profile->set_show_percentages(action.is_checked());
  173. tree_view.update();
  174. disassembly_view.update();
  175. });
  176. percent_action->set_checked(false);
  177. view_menu.add_action(percent_action);
  178. auto& help_menu = menubar->add_menu("&Help");
  179. help_menu.add_action(GUI::CommonActions::make_help_action([](auto&) {
  180. Desktop::Launcher::open(URL::create_with_file_protocol("/usr/share/man/man1/Profiler.md"), "/bin/Help");
  181. }));
  182. help_menu.add_action(GUI::CommonActions::make_about_action("Profiler", app_icon, window));
  183. window->set_menubar(move(menubar));
  184. window->show();
  185. return app->exec();
  186. }
  187. static bool prompt_to_stop_profiling(pid_t pid, const String& process_name)
  188. {
  189. auto window = GUI::Window::construct();
  190. window->set_title(String::formatted("Profiling {}({})", process_name, pid));
  191. window->resize(240, 100);
  192. window->set_icon(Gfx::Bitmap::load_from_file("/res/icons/16x16/app-profiler.png"));
  193. window->center_on_screen();
  194. auto& widget = window->set_main_widget<GUI::Widget>();
  195. widget.set_fill_with_background_color(true);
  196. auto& layout = widget.set_layout<GUI::VerticalBoxLayout>();
  197. layout.set_margins(GUI::Margins(0, 0, 0, 16));
  198. auto& timer_label = widget.add<GUI::Label>("...");
  199. Core::ElapsedTimer clock;
  200. clock.start();
  201. auto update_timer = Core::Timer::construct(100, [&] {
  202. timer_label.set_text(String::formatted("{:.1} seconds", clock.elapsed() / 1000.0f));
  203. });
  204. auto& stop_button = widget.add<GUI::Button>("Stop");
  205. stop_button.set_fixed_size(140, 22);
  206. stop_button.on_click = [&](auto) {
  207. GUI::Application::the()->quit();
  208. };
  209. window->show();
  210. return GUI::Application::the()->exec() == 0;
  211. }
  212. bool generate_profile(pid_t& pid)
  213. {
  214. if (!pid) {
  215. auto process_chooser = GUI::ProcessChooser::construct("Profiler", "Profile", Gfx::Bitmap::load_from_file("/res/icons/16x16/app-profiler.png"));
  216. if (process_chooser->exec() == GUI::Dialog::ExecCancel)
  217. return false;
  218. pid = process_chooser->pid();
  219. }
  220. String process_name;
  221. auto all_processes = Core::ProcessStatisticsReader::get_all();
  222. if (all_processes.has_value()) {
  223. if (auto it = all_processes.value().find(pid); it != all_processes.value().end())
  224. process_name = it->value.name;
  225. else
  226. process_name = "(unknown)";
  227. } else {
  228. process_name = "(unknown)";
  229. }
  230. if (profiling_enable(pid) < 0) {
  231. int saved_errno = errno;
  232. GUI::MessageBox::show(nullptr, String::formatted("Unable to profile process {}({}): {}", process_name, pid, strerror(saved_errno)), "Profiler", GUI::MessageBox::Type::Error);
  233. return false;
  234. }
  235. if (!prompt_to_stop_profiling(pid, process_name))
  236. return false;
  237. if (profiling_disable(pid) < 0) {
  238. return false;
  239. }
  240. return true;
  241. }