diff options
author | Andreas Kling <kling@serenityos.org> | 2021-01-12 12:18:55 +0100 |
---|---|---|
committer | Andreas Kling <kling@serenityos.org> | 2021-01-12 12:18:55 +0100 |
commit | 4055b0329117c1a280080bbd638eb48bafe29638 (patch) | |
tree | ee229fbeca2708ce66a3a8b377eee8974c0f5c5e /Userland/DevTools/Profiler | |
parent | 13d7c09125f8eec703d0a43a9a87fc8aa08f7319 (diff) | |
download | serenity-4055b0329117c1a280080bbd638eb48bafe29638.zip |
DevTools: Move to Userland/DevTools/
Diffstat (limited to 'Userland/DevTools/Profiler')
-rw-r--r-- | Userland/DevTools/Profiler/CMakeLists.txt | 10 | ||||
-rw-r--r-- | Userland/DevTools/Profiler/DisassemblyModel.cpp | 202 | ||||
-rw-r--r-- | Userland/DevTools/Profiler/DisassemblyModel.h | 75 | ||||
-rw-r--r-- | Userland/DevTools/Profiler/Profile.cpp | 399 | ||||
-rw-r--r-- | Userland/DevTools/Profiler/Profile.h | 234 | ||||
-rw-r--r-- | Userland/DevTools/Profiler/ProfileModel.cpp | 147 | ||||
-rw-r--r-- | Userland/DevTools/Profiler/ProfileModel.h | 65 | ||||
-rw-r--r-- | Userland/DevTools/Profiler/ProfileTimelineWidget.cpp | 110 | ||||
-rw-r--r-- | Userland/DevTools/Profiler/ProfileTimelineWidget.h | 53 | ||||
-rw-r--r-- | Userland/DevTools/Profiler/main.cpp | 220 |
10 files changed, 1515 insertions, 0 deletions
diff --git a/Userland/DevTools/Profiler/CMakeLists.txt b/Userland/DevTools/Profiler/CMakeLists.txt new file mode 100644 index 0000000000..1cb7b95140 --- /dev/null +++ b/Userland/DevTools/Profiler/CMakeLists.txt @@ -0,0 +1,10 @@ +set(SOURCES + DisassemblyModel.cpp + main.cpp + Profile.cpp + ProfileModel.cpp + ProfileTimelineWidget.cpp +) + +serenity_app(Profiler ICON app-profiler) +target_link_libraries(Profiler LibGUI LibX86 LibCoreDump) diff --git a/Userland/DevTools/Profiler/DisassemblyModel.cpp b/Userland/DevTools/Profiler/DisassemblyModel.cpp new file mode 100644 index 0000000000..4195f103cd --- /dev/null +++ b/Userland/DevTools/Profiler/DisassemblyModel.cpp @@ -0,0 +1,202 @@ +/* + * Copyright (c) 2020, Andreas Kling <kling@serenityos.org> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "DisassemblyModel.h" +#include "Profile.h" +#include <AK/MappedFile.h> +#include <LibELF/Image.h> +#include <LibGUI/Painter.h> +#include <LibX86/Disassembler.h> +#include <LibX86/ELFSymbolProvider.h> +#include <ctype.h> +#include <stdio.h> + +static const Gfx::Bitmap& heat_gradient() +{ + static RefPtr<Gfx::Bitmap> bitmap; + if (!bitmap) { + bitmap = Gfx::Bitmap::create(Gfx::BitmapFormat::RGB32, { 101, 1 }); + GUI::Painter painter(*bitmap); + painter.fill_rect_with_gradient(Orientation::Horizontal, bitmap->rect(), Color::from_rgb(0xffc080), Color::from_rgb(0xff3000)); + } + return *bitmap; +} + +static Color color_for_percent(int percent) +{ + ASSERT(percent >= 0 && percent <= 100); + return heat_gradient().get_pixel(percent, 0); +} + +DisassemblyModel::DisassemblyModel(Profile& profile, ProfileNode& node) + : m_profile(profile) + , m_node(node) +{ + OwnPtr<ELF::Image> kernel_elf; + const ELF::Image* elf; + FlatPtr base_address = 0; + if (m_node.address() >= 0xc0000000) { + if (!m_kernel_file) { + auto file_or_error = MappedFile::map("/boot/Kernel"); + if (file_or_error.is_error()) + return; + m_kernel_file = file_or_error.release_value(); + } + kernel_elf = make<ELF::Image>((const u8*)m_kernel_file->data(), m_kernel_file->size()); + elf = kernel_elf.ptr(); + } else { + auto library_data = profile.libraries().library_containing(node.address()); + if (!library_data) { + dbgln("no library data"); + return; + } + elf = &library_data->elf; + base_address = library_data->base; + } + + ASSERT(elf != nullptr); + + auto symbol = elf->find_symbol(node.address() - base_address); + if (!symbol.has_value()) { + dbgln("DisassemblyModel: symbol not found"); + return; + } + ASSERT(symbol.has_value()); + + auto view = symbol.value().raw_data(); + + X86::ELFSymbolProvider symbol_provider(*elf); + X86::SimpleInstructionStream stream((const u8*)view.characters_without_null_termination(), view.length()); + X86::Disassembler disassembler(stream); + + size_t offset_into_symbol = 0; + for (;;) { + auto insn = disassembler.next(); + if (!insn.has_value()) + break; + FlatPtr address_in_profiled_program = symbol.value().value() + offset_into_symbol; + + auto disassembly = insn.value().to_string(address_in_profiled_program, &symbol_provider); + + StringView instruction_bytes = view.substring_view(offset_into_symbol, insn.value().length()); + size_t samples_at_this_instruction = m_node.events_per_address().get(address_in_profiled_program).value_or(0); + float percent = ((float)samples_at_this_instruction / (float)m_node.event_count()) * 100.0f; + + m_instructions.append({ insn.value(), disassembly, instruction_bytes, address_in_profiled_program, samples_at_this_instruction, percent }); + + offset_into_symbol += insn.value().length(); + } +} + +DisassemblyModel::~DisassemblyModel() +{ +} + +int DisassemblyModel::row_count(const GUI::ModelIndex&) const +{ + return m_instructions.size(); +} + +String DisassemblyModel::column_name(int column) const +{ + switch (column) { + case Column::SampleCount: + return m_profile.show_percentages() ? "% Samples" : "# Samples"; + case Column::Address: + return "Address"; + case Column::InstructionBytes: + return "Insn Bytes"; + case Column::Disassembly: + return "Disassembly"; + default: + ASSERT_NOT_REACHED(); + return {}; + } +} + +struct ColorPair { + Color background; + Color foreground; +}; + +static Optional<ColorPair> color_pair_for(const InstructionData& insn) +{ + if (insn.percent == 0) + return {}; + + Color background = color_for_percent(insn.percent); + Color foreground; + if (insn.percent > 50) + foreground = Color::White; + else + foreground = Color::Black; + return ColorPair { background, foreground }; +} + +GUI::Variant DisassemblyModel::data(const GUI::ModelIndex& index, GUI::ModelRole role) const +{ + auto& insn = m_instructions[index.row()]; + + if (role == GUI::ModelRole::BackgroundColor) { + auto colors = color_pair_for(insn); + if (!colors.has_value()) + return {}; + return colors.value().background; + } + + if (role == GUI::ModelRole::ForegroundColor) { + auto colors = color_pair_for(insn); + if (!colors.has_value()) + return {}; + return colors.value().foreground; + } + + if (role == GUI::ModelRole::Display) { + if (index.column() == Column::SampleCount) { + if (m_profile.show_percentages()) + return ((float)insn.event_count / (float)m_node.event_count()) * 100.0f; + return insn.event_count; + } + if (index.column() == Column::Address) + return String::formatted("{:p}", insn.address); + if (index.column() == Column::InstructionBytes) { + StringBuilder builder; + for (auto ch : insn.bytes) { + builder.appendff("{:02x} ", (u8)ch); + } + return builder.to_string(); + } + if (index.column() == Column::Disassembly) + return insn.disassembly; + return {}; + } + return {}; +} + +void DisassemblyModel::update() +{ + did_update(); +} diff --git a/Userland/DevTools/Profiler/DisassemblyModel.h b/Userland/DevTools/Profiler/DisassemblyModel.h new file mode 100644 index 0000000000..0d0e643292 --- /dev/null +++ b/Userland/DevTools/Profiler/DisassemblyModel.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2020, Andreas Kling <kling@serenityos.org> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include <LibGUI/Model.h> +#include <LibX86/Instruction.h> + +class Profile; +class ProfileNode; + +struct InstructionData { + X86::Instruction insn; + String disassembly; + StringView bytes; + FlatPtr address { 0 }; + u32 event_count { 0 }; + float percent { 0 }; +}; + +class DisassemblyModel final : public GUI::Model { +public: + static NonnullRefPtr<DisassemblyModel> create(Profile& profile, ProfileNode& node) + { + return adopt(*new DisassemblyModel(profile, node)); + } + + enum Column { + Address, + SampleCount, + InstructionBytes, + Disassembly, + __Count + }; + + virtual ~DisassemblyModel() override; + + virtual int row_count(const GUI::ModelIndex& = GUI::ModelIndex()) const override; + virtual int column_count(const GUI::ModelIndex& = GUI::ModelIndex()) const override { return Column::__Count; } + virtual String column_name(int) const override; + virtual GUI::Variant data(const GUI::ModelIndex&, GUI::ModelRole) const override; + virtual void update() override; + +private: + DisassemblyModel(Profile&, ProfileNode&); + + Profile& m_profile; + ProfileNode& m_node; + RefPtr<MappedFile> m_kernel_file; + + Vector<InstructionData> m_instructions; +}; diff --git a/Userland/DevTools/Profiler/Profile.cpp b/Userland/DevTools/Profiler/Profile.cpp new file mode 100644 index 0000000000..8e8e986841 --- /dev/null +++ b/Userland/DevTools/Profiler/Profile.cpp @@ -0,0 +1,399 @@ +/* + * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "Profile.h" +#include "DisassemblyModel.h" +#include "ProfileModel.h" +#include <AK/HashTable.h> +#include <AK/MappedFile.h> +#include <AK/QuickSort.h> +#include <AK/RefPtr.h> +#include <LibCore/File.h> +#include <LibELF/Image.h> +#include <stdio.h> +#include <sys/stat.h> + +static void sort_profile_nodes(Vector<NonnullRefPtr<ProfileNode>>& nodes) +{ + quick_sort(nodes.begin(), nodes.end(), [](auto& a, auto& b) { + return a->event_count() >= b->event_count(); + }); + + for (auto& child : nodes) + child->sort_children(); +} + +Profile::Profile(String executable_path, Vector<Event> events, NonnullOwnPtr<LibraryMetadata> library_metadata) + : m_executable_path(move(executable_path)) + , m_events(move(events)) + , m_library_metadata(move(library_metadata)) +{ + m_first_timestamp = m_events.first().timestamp; + m_last_timestamp = m_events.last().timestamp; + + m_model = ProfileModel::create(*this); + + for (auto& event : m_events) { + m_deepest_stack_depth = max((u32)event.frames.size(), m_deepest_stack_depth); + } + + rebuild_tree(); +} + +Profile::~Profile() +{ +} + +GUI::Model& Profile::model() +{ + return *m_model; +} + +void Profile::rebuild_tree() +{ + u32 filtered_event_count = 0; + Vector<NonnullRefPtr<ProfileNode>> roots; + + auto find_or_create_root = [&roots](const String& symbol, u32 address, u32 offset, u64 timestamp) -> ProfileNode& { + for (size_t i = 0; i < roots.size(); ++i) { + auto& root = roots[i]; + if (root->symbol() == symbol) { + return root; + } + } + auto new_root = ProfileNode::create(symbol, address, offset, timestamp); + roots.append(new_root); + return new_root; + }; + + HashTable<FlatPtr> live_allocations; + + for (auto& event : m_events) { + if (has_timestamp_filter_range()) { + auto timestamp = event.timestamp; + if (timestamp < m_timestamp_filter_range_start || timestamp > m_timestamp_filter_range_end) + continue; + } + + if (event.type == "malloc") + live_allocations.set(event.ptr); + else if (event.type == "free") + live_allocations.remove(event.ptr); + } + + for (size_t event_index = 0; event_index < m_events.size(); ++event_index) { + auto& event = m_events.at(event_index); + if (has_timestamp_filter_range()) { + auto timestamp = event.timestamp; + if (timestamp < m_timestamp_filter_range_start || timestamp > m_timestamp_filter_range_end) + continue; + } + + if (event.type == "malloc" && !live_allocations.contains(event.ptr)) + continue; + + if (event.type == "free") + continue; + + auto for_each_frame = [&]<typename Callback>(Callback callback) { + if (!m_inverted) { + for (size_t i = 0; i < event.frames.size(); ++i) { + if (callback(event.frames.at(i), i == event.frames.size() - 1) == IterationDecision::Break) + break; + } + } else { + for (ssize_t i = event.frames.size() - 1; i >= 0; --i) { + if (callback(event.frames.at(i), static_cast<size_t>(i) == event.frames.size() - 1) == IterationDecision::Break) + break; + } + } + }; + + if (!m_show_top_functions) { + ProfileNode* node = nullptr; + for_each_frame([&](const Frame& frame, bool is_innermost_frame) { + auto& symbol = frame.symbol; + auto& address = frame.address; + auto& offset = frame.offset; + + if (symbol.is_empty()) + return IterationDecision::Break; + + if (!node) + node = &find_or_create_root(symbol, address, offset, event.timestamp); + else + node = &node->find_or_create_child(symbol, address, offset, event.timestamp); + + node->increment_event_count(); + if (is_innermost_frame) { + node->add_event_address(address); + node->increment_self_count(); + } + return IterationDecision::Continue; + }); + } else { + for (size_t i = 0; i < event.frames.size(); ++i) { + ProfileNode* node = nullptr; + ProfileNode* root = nullptr; + for (size_t j = i; j < event.frames.size(); ++j) { + auto& frame = event.frames.at(j); + auto& symbol = frame.symbol; + auto& address = frame.address; + auto& offset = frame.offset; + if (symbol.is_empty()) + break; + + if (!node) { + node = &find_or_create_root(symbol, address, offset, event.timestamp); + root = node; + root->will_track_seen_events(m_events.size()); + } else { + node = &node->find_or_create_child(symbol, address, offset, event.timestamp); + } + + if (!root->has_seen_event(event_index)) { + root->did_see_event(event_index); + root->increment_event_count(); + } else if (node != root) { + node->increment_event_count(); + } + + if (j == event.frames.size() - 1) { + node->add_event_address(address); + node->increment_self_count(); + } + } + } + } + + ++filtered_event_count; + } + + sort_profile_nodes(roots); + + m_filtered_event_count = filtered_event_count; + m_roots = move(roots); + m_model->update(); +} + +Result<NonnullOwnPtr<Profile>, String> Profile::load_from_perfcore_file(const StringView& path) +{ + auto file = Core::File::construct(path); + if (!file->open(Core::IODevice::ReadOnly)) + return String::formatted("Unable to open {}, error: {}", path, file->error_string()); + + auto json = JsonValue::from_string(file->read_all()); + if (!json.has_value() || !json.value().is_object()) + return String { "Invalid perfcore format (not a JSON object)" }; + + auto& object = json.value().as_object(); + auto executable_path = object.get("executable").to_string(); + + auto pid = object.get("pid"); + if (!pid.is_u32()) + return String { "Invalid perfcore format (no process ID)" }; + + auto file_or_error = MappedFile::map("/boot/Kernel"); + OwnPtr<ELF::Image> kernel_elf; + if (!file_or_error.is_error()) + kernel_elf = make<ELF::Image>(file_or_error.value()->bytes()); + + auto events_value = object.get("events"); + if (!events_value.is_array()) + return String { "Malformed profile (events is not an array)" }; + + auto regions_value = object.get("regions"); + if (!regions_value.is_array() || regions_value.as_array().is_empty()) + return String { "Malformed profile (regions is not an array, or it is empty)" }; + + auto& perf_events = events_value.as_array(); + if (perf_events.is_empty()) + return String { "No events captured (targeted process was never on CPU)" }; + + auto library_metadata = make<LibraryMetadata>(regions_value.as_array()); + + Vector<Event> events; + + for (auto& perf_event_value : perf_events.values()) { + auto& perf_event = perf_event_value.as_object(); + + Event event; + + event.timestamp = perf_event.get("timestamp").to_number<u64>(); + event.type = perf_event.get("type").to_string(); + + if (event.type == "malloc") { + event.ptr = perf_event.get("ptr").to_number<FlatPtr>(); + event.size = perf_event.get("size").to_number<size_t>(); + } else if (event.type == "free") { + event.ptr = perf_event.get("ptr").to_number<FlatPtr>(); + } + + auto stack_array = perf_event.get("stack").as_array(); + for (ssize_t i = stack_array.values().size() - 1; i >= 0; --i) { + auto& frame = stack_array.at(i); + auto ptr = frame.to_number<u32>(); + u32 offset = 0; + String symbol; + + if (ptr >= 0xc0000000) { + if (kernel_elf) { + symbol = kernel_elf->symbolicate(ptr, &offset); + } else { + symbol = "??"; + } + } else { + symbol = library_metadata->symbolicate(ptr, offset); + } + + event.frames.append({ symbol, ptr, offset }); + } + + if (event.frames.size() < 2) + continue; + + FlatPtr innermost_frame_address = event.frames.at(1).address; + event.in_kernel = innermost_frame_address >= 0xc0000000; + + events.append(move(event)); + } + + return adopt_own(*new Profile(executable_path, move(events), move(library_metadata))); +} + +void ProfileNode::sort_children() +{ + sort_profile_nodes(m_children); +} + +void Profile::set_timestamp_filter_range(u64 start, u64 end) +{ + if (m_has_timestamp_filter_range && m_timestamp_filter_range_start == start && m_timestamp_filter_range_end == end) + return; + m_has_timestamp_filter_range = true; + + m_timestamp_filter_range_start = min(start, end); + m_timestamp_filter_range_end = max(start, end); + + rebuild_tree(); +} + +void Profile::clear_timestamp_filter_range() +{ + if (!m_has_timestamp_filter_range) + return; + m_has_timestamp_filter_range = false; + rebuild_tree(); +} + +void Profile::set_inverted(bool inverted) +{ + if (m_inverted == inverted) + return; + m_inverted = inverted; + rebuild_tree(); +} + +void Profile::set_show_top_functions(bool show) +{ + if (m_show_top_functions == show) + return; + m_show_top_functions = show; + rebuild_tree(); +} + +void Profile::set_show_percentages(bool show_percentages) +{ + if (m_show_percentages == show_percentages) + return; + m_show_percentages = show_percentages; +} + +void Profile::set_disassembly_index(const GUI::ModelIndex& index) +{ + if (m_disassembly_index == index) + return; + m_disassembly_index = index; + auto* node = static_cast<ProfileNode*>(index.internal_data()); + m_disassembly_model = DisassemblyModel::create(*this, *node); +} + +GUI::Model* Profile::disassembly_model() +{ + return m_disassembly_model; +} + +Profile::LibraryMetadata::LibraryMetadata(JsonArray regions) + : m_regions(move(regions)) +{ + for (auto& region_value : m_regions.values()) { + auto& region = region_value.as_object(); + auto base = region.get("base").as_u32(); + auto size = region.get("size").as_u32(); + auto name = region.get("name").as_string(); + + String path; + if (name.contains("Loader.so")) + path = "Loader.so"; + else if (!name.contains(":")) + continue; + else + path = name.substring(0, name.view().find_first_of(":").value()); + + if (name.contains(".so")) + path = String::formatted("/usr/lib/{}", path); + + auto file_or_error = MappedFile::map(path); + if (file_or_error.is_error()) { + m_libraries.set(name, {}); + continue; + } + auto elf = ELF::Image(file_or_error.value()->bytes()); + if (!elf.is_valid()) + continue; + auto library = make<Library>(base, size, name, file_or_error.release_value(), move(elf)); + m_libraries.set(name, move(library)); + } +} + +const Profile::LibraryMetadata::Library* Profile::LibraryMetadata::library_containing(FlatPtr ptr) const +{ + for (auto& it : m_libraries) { + if (!it.value) + continue; + auto& library = *it.value; + if (ptr >= library.base && ptr < (library.base + library.size)) + return &library; + } + return nullptr; +} + +String Profile::LibraryMetadata::symbolicate(FlatPtr ptr, u32& offset) const +{ + if (auto* library = library_containing(ptr)) + return String::formatted("[{}] {}", library->name, library->elf.symbolicate(ptr - library->base, &offset)); + return "??"; +} diff --git a/Userland/DevTools/Profiler/Profile.h b/Userland/DevTools/Profiler/Profile.h new file mode 100644 index 0000000000..0acf3e917f --- /dev/null +++ b/Userland/DevTools/Profiler/Profile.h @@ -0,0 +1,234 @@ +/* + * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include <AK/Bitmap.h> +#include <AK/JsonArray.h> +#include <AK/JsonObject.h> +#include <AK/JsonValue.h> +#include <AK/MappedFile.h> +#include <AK/NonnullRefPtrVector.h> +#include <AK/OwnPtr.h> +#include <AK/Result.h> +#include <LibELF/Image.h> +#include <LibGUI/Forward.h> +#include <LibGUI/ModelIndex.h> + +class ProfileModel; +class DisassemblyModel; + +class ProfileNode : public RefCounted<ProfileNode> { +public: + static NonnullRefPtr<ProfileNode> create(const String& symbol, u32 address, u32 offset, u64 timestamp) + { + return adopt(*new ProfileNode(symbol, address, offset, timestamp)); + } + + // These functions are only relevant for root nodes + void will_track_seen_events(size_t profile_event_count) + { + if (m_seen_events.size() != profile_event_count) + m_seen_events = Bitmap::create(profile_event_count, false); + } + bool has_seen_event(size_t event_index) const { return m_seen_events.get(event_index); } + void did_see_event(size_t event_index) { m_seen_events.set(event_index, true); } + + const String& symbol() const { return m_symbol; } + u32 address() const { return m_address; } + u32 offset() const { return m_offset; } + u64 timestamp() const { return m_timestamp; } + + u32 event_count() const { return m_event_count; } + u32 self_count() const { return m_self_count; } + + int child_count() const { return m_children.size(); } + const Vector<NonnullRefPtr<ProfileNode>>& children() const { return m_children; } + + void add_child(ProfileNode& child) + { + if (child.m_parent == this) + return; + ASSERT(!child.m_parent); + child.m_parent = this; + m_children.append(child); + } + + ProfileNode& find_or_create_child(const String& symbol, u32 address, u32 offset, u64 timestamp) + { + for (size_t i = 0; i < m_children.size(); ++i) { + auto& child = m_children[i]; + if (child->symbol() == symbol) { + return child; + } + } + auto new_child = ProfileNode::create(symbol, address, offset, timestamp); + add_child(new_child); + return new_child; + }; + + ProfileNode* parent() { return m_parent; } + const ProfileNode* parent() const { return m_parent; } + + void increment_event_count() { ++m_event_count; } + void increment_self_count() { ++m_self_count; } + + void sort_children(); + + const HashMap<FlatPtr, size_t>& events_per_address() const { return m_events_per_address; } + void add_event_address(FlatPtr address) + { + auto it = m_events_per_address.find(address); + if (it == m_events_per_address.end()) + m_events_per_address.set(address, 1); + else + m_events_per_address.set(address, it->value + 1); + } + +private: + explicit ProfileNode(const String& symbol, u32 address, u32 offset, u64 timestamp) + : m_symbol(symbol) + , m_address(address) + , m_offset(offset) + , m_timestamp(timestamp) + { + } + + ProfileNode* m_parent { nullptr }; + String m_symbol; + u32 m_address { 0 }; + u32 m_offset { 0 }; + u32 m_event_count { 0 }; + u32 m_self_count { 0 }; + u64 m_timestamp { 0 }; + Vector<NonnullRefPtr<ProfileNode>> m_children; + HashMap<FlatPtr, size_t> m_events_per_address; + Bitmap m_seen_events; +}; + +class Profile { +public: + static Result<NonnullOwnPtr<Profile>, String> load_from_perfcore_file(const StringView& path); + ~Profile(); + + GUI::Model& model(); + GUI::Model* disassembly_model(); + + void set_disassembly_index(const GUI::ModelIndex&); + + const Vector<NonnullRefPtr<ProfileNode>>& roots() const { return m_roots; } + + struct Frame { + String symbol; + u32 address { 0 }; + u32 offset { 0 }; + }; + + struct Event { + u64 timestamp { 0 }; + String type; + FlatPtr ptr { 0 }; + size_t size { 0 }; + bool in_kernel { false }; + Vector<Frame> frames; + }; + + u32 filtered_event_count() const { return m_filtered_event_count; } + + const Vector<Event>& events() const { return m_events; } + + u64 length_in_ms() const { return m_last_timestamp - m_first_timestamp; } + u64 first_timestamp() const { return m_first_timestamp; } + u64 last_timestamp() const { return m_last_timestamp; } + u32 deepest_stack_depth() const { return m_deepest_stack_depth; } + + void set_timestamp_filter_range(u64 start, u64 end); + void clear_timestamp_filter_range(); + bool has_timestamp_filter_range() const { return m_has_timestamp_filter_range; } + + bool is_inverted() const { return m_inverted; } + void set_inverted(bool); + + void set_show_top_functions(bool); + + bool show_percentages() const { return m_show_percentages; } + void set_show_percentages(bool); + + const String& executable_path() const { return m_executable_path; } + + class LibraryMetadata { + public: + LibraryMetadata(JsonArray regions); + + String symbolicate(FlatPtr ptr, u32& offset) const; + + struct Library { + FlatPtr base; + size_t size; + String name; + NonnullRefPtr<MappedFile> file; + ELF::Image elf; + }; + + const Library* library_containing(FlatPtr) const; + + private: + mutable HashMap<String, OwnPtr<Library>> m_libraries; + JsonArray m_regions; + }; + + const LibraryMetadata& libraries() const { return *m_library_metadata; } + +private: + Profile(String executable_path, Vector<Event>, NonnullOwnPtr<LibraryMetadata>); + + void rebuild_tree(); + + String m_executable_path; + + RefPtr<ProfileModel> m_model; + RefPtr<DisassemblyModel> m_disassembly_model; + + GUI::ModelIndex m_disassembly_index; + + Vector<NonnullRefPtr<ProfileNode>> m_roots; + u32 m_filtered_event_count { 0 }; + u64 m_first_timestamp { 0 }; + u64 m_last_timestamp { 0 }; + + Vector<Event> m_events; + + NonnullOwnPtr<LibraryMetadata> m_library_metadata; + + bool m_has_timestamp_filter_range { false }; + u64 m_timestamp_filter_range_start { 0 }; + u64 m_timestamp_filter_range_end { 0 }; + + u32 m_deepest_stack_depth { 0 }; + bool m_inverted { false }; + bool m_show_top_functions { false }; + bool m_show_percentages { false }; +}; diff --git a/Userland/DevTools/Profiler/ProfileModel.cpp b/Userland/DevTools/Profiler/ProfileModel.cpp new file mode 100644 index 0000000000..caf1819446 --- /dev/null +++ b/Userland/DevTools/Profiler/ProfileModel.cpp @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "ProfileModel.h" +#include "Profile.h" +#include <AK/StringBuilder.h> +#include <ctype.h> +#include <stdio.h> + +ProfileModel::ProfileModel(Profile& profile) + : m_profile(profile) +{ + m_user_frame_icon.set_bitmap_for_size(16, Gfx::Bitmap::load_from_file("/res/icons/16x16/inspector-object.png")); + m_kernel_frame_icon.set_bitmap_for_size(16, Gfx::Bitmap::load_from_file("/res/icons/16x16/inspector-object-red.png")); +} + +ProfileModel::~ProfileModel() +{ +} + +GUI::ModelIndex ProfileModel::index(int row, int column, const GUI::ModelIndex& parent) const +{ + if (!parent.is_valid()) { + if (m_profile.roots().is_empty()) + return {}; + return create_index(row, column, m_profile.roots().at(row).ptr()); + } + auto& remote_parent = *static_cast<ProfileNode*>(parent.internal_data()); + return create_index(row, column, remote_parent.children().at(row).ptr()); +} + +GUI::ModelIndex ProfileModel::parent_index(const GUI::ModelIndex& index) const +{ + if (!index.is_valid()) + return {}; + auto& node = *static_cast<ProfileNode*>(index.internal_data()); + if (!node.parent()) + return {}; + + // NOTE: If the parent has no parent, it's a root, so we have to look among the roots. + if (!node.parent()->parent()) { + for (size_t row = 0; row < m_profile.roots().size(); ++row) { + if (m_profile.roots()[row].ptr() == node.parent()) { + return create_index(row, index.column(), node.parent()); + } + } + ASSERT_NOT_REACHED(); + return {}; + } + + for (size_t row = 0; row < node.parent()->parent()->children().size(); ++row) { + if (node.parent()->parent()->children()[row].ptr() == node.parent()) + return create_index(row, index.column(), node.parent()); + } + + ASSERT_NOT_REACHED(); + return {}; +} + +int ProfileModel::row_count(const GUI::ModelIndex& index) const +{ + if (!index.is_valid()) + return m_profile.roots().size(); + auto& node = *static_cast<ProfileNode*>(index.internal_data()); + return node.children().size(); +} + +int ProfileModel::column_count(const GUI::ModelIndex&) const +{ + return Column::__Count; +} + +String ProfileModel::column_name(int column) const +{ + switch (column) { + case Column::SampleCount: + return m_profile.show_percentages() ? "% Samples" : "# Samples"; + case Column::SelfCount: + return m_profile.show_percentages() ? "% Self" : "# Self"; + case Column::StackFrame: + return "Stack Frame"; + default: + ASSERT_NOT_REACHED(); + return {}; + } +} + +GUI::Variant ProfileModel::data(const GUI::ModelIndex& index, GUI::ModelRole role) const +{ + auto* node = static_cast<ProfileNode*>(index.internal_data()); + if (role == GUI::ModelRole::TextAlignment) { + if (index.column() == Column::SampleCount || index.column() == Column::SelfCount) + return Gfx::TextAlignment::CenterRight; + } + if (role == GUI::ModelRole::Icon) { + if (index.column() == Column::StackFrame) { + if (node->address() >= 0xc0000000) + return m_kernel_frame_icon; + return m_user_frame_icon; + } + return {}; + } + if (role == GUI::ModelRole::Display) { + if (index.column() == Column::SampleCount) { + if (m_profile.show_percentages()) + return ((float)node->event_count() / (float)m_profile.filtered_event_count()) * 100.0f; + return node->event_count(); + } + if (index.column() == Column::SelfCount) { + if (m_profile.show_percentages()) + return ((float)node->self_count() / (float)m_profile.filtered_event_count()) * 100.0f; + return node->self_count(); + } + if (index.column() == Column::StackFrame) + return node->symbol(); + return {}; + } + return {}; +} + +void ProfileModel::update() +{ + did_update(Model::InvalidateAllIndexes); +} diff --git a/Userland/DevTools/Profiler/ProfileModel.h b/Userland/DevTools/Profiler/ProfileModel.h new file mode 100644 index 0000000000..9b61dd5137 --- /dev/null +++ b/Userland/DevTools/Profiler/ProfileModel.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include <LibGUI/Model.h> + +class Profile; + +class ProfileModel final : public GUI::Model { +public: + static NonnullRefPtr<ProfileModel> create(Profile& profile) + { + return adopt(*new ProfileModel(profile)); + } + + enum Column { + SampleCount, + SelfCount, + StackFrame, + __Count + }; + + virtual ~ProfileModel() override; + + virtual int row_count(const GUI::ModelIndex& = GUI::ModelIndex()) const override; + virtual int column_count(const GUI::ModelIndex& = GUI::ModelIndex()) const override; + virtual String column_name(int) const override; + virtual GUI::Variant data(const GUI::ModelIndex&, GUI::ModelRole) const override; + virtual GUI::ModelIndex index(int row, int column, const GUI::ModelIndex& parent = GUI::ModelIndex()) const override; + virtual GUI::ModelIndex parent_index(const GUI::ModelIndex&) const override; + virtual void update() override; + virtual int tree_column() const override { return Column::StackFrame; } + +private: + explicit ProfileModel(Profile&); + + Profile& m_profile; + + GUI::Icon m_user_frame_icon; + GUI::Icon m_kernel_frame_icon; +}; diff --git a/Userland/DevTools/Profiler/ProfileTimelineWidget.cpp b/Userland/DevTools/Profiler/ProfileTimelineWidget.cpp new file mode 100644 index 0000000000..7d4552d300 --- /dev/null +++ b/Userland/DevTools/Profiler/ProfileTimelineWidget.cpp @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "ProfileTimelineWidget.h" +#include "Profile.h" +#include <LibGUI/Painter.h> + +ProfileTimelineWidget::ProfileTimelineWidget(Profile& profile) + : m_profile(profile) +{ + set_fill_with_background_color(true); + set_fixed_height(80); +} + +ProfileTimelineWidget::~ProfileTimelineWidget() +{ +} + +void ProfileTimelineWidget::paint_event(GUI::PaintEvent& event) +{ + GUI::Frame::paint_event(event); + + GUI::Painter painter(*this); + painter.add_clip_rect(event.rect()); + + float column_width = (float)frame_inner_rect().width() / (float)m_profile.length_in_ms(); + float frame_height = (float)frame_inner_rect().height() / (float)m_profile.deepest_stack_depth(); + + for (auto& event : m_profile.events()) { + u64 t = event.timestamp - m_profile.first_timestamp(); + int x = (int)((float)t * column_width); + int cw = max(1, (int)column_width); + + int column_height = frame_inner_rect().height() - (int)((float)event.frames.size() * frame_height); + + bool in_kernel = event.in_kernel; + Color color = in_kernel ? Color::from_rgb(0xc25e5a) : Color::from_rgb(0x5a65c2); + for (int i = 0; i < cw; ++i) + painter.draw_line({ x + i, frame_thickness() + column_height }, { x + i, height() - frame_thickness() * 2 }, color); + } + + u64 normalized_start_time = min(m_select_start_time, m_select_end_time); + u64 normalized_end_time = max(m_select_start_time, m_select_end_time); + + int select_start_x = (int)((float)(normalized_start_time - m_profile.first_timestamp()) * column_width); + int select_end_x = (int)((float)(normalized_end_time - m_profile.first_timestamp()) * column_width); + painter.fill_rect({ select_start_x, frame_thickness(), select_end_x - select_start_x, height() - frame_thickness() * 2 }, Color(0, 0, 0, 60)); +} + +u64 ProfileTimelineWidget::timestamp_at_x(int x) const +{ + float column_width = (float)frame_inner_rect().width() / (float)m_profile.length_in_ms(); + float ms_into_profile = (float)x / column_width; + return m_profile.first_timestamp() + (u64)ms_into_profile; +} + +void ProfileTimelineWidget::mousedown_event(GUI::MouseEvent& event) +{ + if (event.button() != GUI::MouseButton::Left) + return; + + m_selecting = true; + m_select_start_time = timestamp_at_x(event.x()); + m_select_end_time = m_select_start_time; + m_profile.set_timestamp_filter_range(m_select_start_time, m_select_end_time); + update(); +} + +void ProfileTimelineWidget::mousemove_event(GUI::MouseEvent& event) +{ + if (!m_selecting) + return; + + m_select_end_time = timestamp_at_x(event.x()); + m_profile.set_timestamp_filter_range(m_select_start_time, m_select_end_time); + update(); +} + +void ProfileTimelineWidget::mouseup_event(GUI::MouseEvent& event) +{ + if (event.button() != GUI::MouseButton::Left) + return; + + m_selecting = false; + if (m_select_start_time == m_select_end_time) + m_profile.clear_timestamp_filter_range(); +} diff --git a/Userland/DevTools/Profiler/ProfileTimelineWidget.h b/Userland/DevTools/Profiler/ProfileTimelineWidget.h new file mode 100644 index 0000000000..056e07769e --- /dev/null +++ b/Userland/DevTools/Profiler/ProfileTimelineWidget.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include <LibGUI/Frame.h> + +class Profile; + +class ProfileTimelineWidget final : public GUI::Frame { + C_OBJECT(ProfileTimelineWidget) +public: + virtual ~ProfileTimelineWidget() override; + +private: + virtual void paint_event(GUI::PaintEvent&) override; + virtual void mousedown_event(GUI::MouseEvent&) override; + virtual void mousemove_event(GUI::MouseEvent&) override; + virtual void mouseup_event(GUI::MouseEvent&) override; + + explicit ProfileTimelineWidget(Profile&); + + u64 timestamp_at_x(int x) const; + + Profile& m_profile; + + bool m_selecting { false }; + u64 m_select_start_time { 0 }; + u64 m_select_end_time { 0 }; +}; diff --git a/Userland/DevTools/Profiler/main.cpp b/Userland/DevTools/Profiler/main.cpp new file mode 100644 index 0000000000..5f801936c0 --- /dev/null +++ b/Userland/DevTools/Profiler/main.cpp @@ -0,0 +1,220 @@ +/* + * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "Profile.h" +#include "ProfileTimelineWidget.h" +#include <LibCore/ArgsParser.h> +#include <LibCore/ElapsedTimer.h> +#include <LibCore/EventLoop.h> +#include <LibCore/ProcessStatisticsReader.h> +#include <LibCore/Timer.h> +#include <LibGUI/Action.h> +#include <LibGUI/Application.h> +#include <LibGUI/BoxLayout.h> +#include <LibGUI/Button.h> +#include <LibGUI/Desktop.h> +#include <LibGUI/Label.h> +#include <LibGUI/Menu.h> +#include <LibGUI/MenuBar.h> +#include <LibGUI/MessageBox.h> +#include <LibGUI/Model.h> +#include <LibGUI/ProcessChooser.h> +#include <LibGUI/Splitter.h> +#include <LibGUI/TableView.h> +#include <LibGUI/TreeView.h> +#include <LibGUI/Window.h> +#include <serenity.h> +#include <stdio.h> +#include <string.h> + +static bool generate_profile(pid_t& pid); + +int main(int argc, char** argv) +{ + Core::ArgsParser args_parser; + int pid = 0; + args_parser.add_option(pid, "PID to profile", "pid", 'p', "PID"); + args_parser.parse(argc, argv, false); + + auto app = GUI::Application::construct(argc, argv); + auto app_icon = GUI::Icon::default_icon("app-profiler"); + + String path; + if (argc != 2) { + if (!generate_profile(pid)) + return 0; + path = String::formatted("/proc/{}/perf_events", pid); + } else { + path = argv[1]; + } + + auto profile_or_error = Profile::load_from_perfcore_file(path); + if (profile_or_error.is_error()) { + GUI::MessageBox::show(nullptr, profile_or_error.error(), "Profiler", GUI::MessageBox::Type::Error); + return 0; + } + + auto& profile = profile_or_error.value(); + + auto window = GUI::Window::construct(); + window->set_title("Profiler"); + window->set_icon(app_icon.bitmap_for_size(16)); + window->resize(800, 600); + + auto& main_widget = window->set_main_widget<GUI::Widget>(); + main_widget.set_fill_with_background_color(true); + main_widget.set_layout<GUI::VerticalBoxLayout>(); + + main_widget.add<ProfileTimelineWidget>(*profile); + + auto& bottom_splitter = main_widget.add<GUI::VerticalSplitter>(); + + auto& tree_view = bottom_splitter.add<GUI::TreeView>(); + tree_view.set_should_fill_selected_rows(true); + tree_view.set_column_headers_visible(true); + tree_view.set_model(profile->model()); + + auto& disassembly_view = bottom_splitter.add<GUI::TableView>(); + + tree_view.on_selection = [&](auto& index) { + profile->set_disassembly_index(index); + disassembly_view.set_model(profile->disassembly_model()); + }; + + auto menubar = GUI::MenuBar::construct(); + auto& app_menu = menubar->add_menu("Profiler"); + app_menu.add_action(GUI::CommonActions::make_quit_action([&](auto&) { app->quit(); })); + + auto& view_menu = menubar->add_menu("View"); + + auto update_window_title = [&](auto title, bool is_checked) { + StringBuilder name; + name.append("Profiler"); + if (is_checked) { + name.append(" - "); + name.append(title); + } + window->set_title(name.to_string()); + }; + + auto invert_action = GUI::Action::create_checkable("Invert tree", { Mod_Ctrl, Key_I }, [&](auto& action) { + profile->set_inverted(action.is_checked()); + update_window_title("Invert tree", action.is_checked()); + }); + invert_action->set_checked(false); + view_menu.add_action(invert_action); + + auto top_functions_action = GUI::Action::create_checkable("Top functions", { Mod_Ctrl, Key_T }, [&](auto& action) { + profile->set_show_top_functions(action.is_checked()); + update_window_title("Top functions", action.is_checked()); + }); + top_functions_action->set_checked(false); + view_menu.add_action(top_functions_action); + + auto percent_action = GUI::Action::create_checkable("Show percentages", { Mod_Ctrl, Key_P }, [&](auto& action) { + profile->set_show_percentages(action.is_checked()); + tree_view.update(); + disassembly_view.update(); + update_window_title("Show percentages", action.is_checked()); + }); + percent_action->set_checked(false); + view_menu.add_action(percent_action); + + auto& help_menu = menubar->add_menu("Help"); + help_menu.add_action(GUI::CommonActions::make_about_action("Profiler", app_icon, window)); + + app->set_menubar(move(menubar)); + + window->show(); + return app->exec(); +} + +static bool prompt_to_stop_profiling(pid_t pid, const String& process_name) +{ + auto window = GUI::Window::construct(); + window->set_title(String::formatted("Profiling {}({})", process_name, pid)); + window->resize(240, 100); + window->set_icon(Gfx::Bitmap::load_from_file("/res/icons/16x16/app-profiler.png")); + window->center_on_screen(); + + auto& widget = window->set_main_widget<GUI::Widget>(); + widget.set_fill_with_background_color(true); + auto& layout = widget.set_layout<GUI::VerticalBoxLayout>(); + layout.set_margins(GUI::Margins(0, 0, 0, 16)); + + auto& timer_label = widget.add<GUI::Label>("..."); + Core::ElapsedTimer clock; + clock.start(); + auto update_timer = Core::Timer::construct(100, [&] { + timer_label.set_text(String::format("%.1f seconds", (float)clock.elapsed() / 1000.0f)); + }); + + auto& stop_button = widget.add<GUI::Button>("Stop"); + stop_button.set_fixed_size(140, 22); + stop_button.on_click = [&](auto) { + GUI::Application::the()->quit(); + }; + + window->show(); + return GUI::Application::the()->exec() == 0; +} + +bool generate_profile(pid_t& pid) +{ + if (!pid) { + auto process_chooser = GUI::ProcessChooser::construct("Profiler", "Profile", Gfx::Bitmap::load_from_file("/res/icons/16x16/app-profiler.png")); + if (process_chooser->exec() == GUI::Dialog::ExecCancel) + return false; + pid = process_chooser->pid(); + } + + String process_name; + + auto all_processes = Core::ProcessStatisticsReader::get_all(); + if (all_processes.has_value()) { + if (auto it = all_processes.value().find(pid); it != all_processes.value().end()) + process_name = it->value.name; + else + process_name = "(unknown)"; + } else { + process_name = "(unknown)"; + } + + if (profiling_enable(pid) < 0) { + int saved_errno = errno; + GUI::MessageBox::show(nullptr, String::formatted("Unable to profile process {}({}): {}", process_name, pid, strerror(saved_errno)), "Profiler", GUI::MessageBox::Type::Error); + return false; + } + + if (!prompt_to_stop_profiling(pid, process_name)) + return false; + + if (profiling_disable(pid) < 0) { + return false; + } + + return true; +} |