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