main.cpp 17 KB

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