main.cpp 16 KB

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