main.cpp 14 KB

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