main.cpp 10 KB

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