Serenity Operating System
at master 347 lines 16 kB view raw
1/* 2 * Copyright (c) 2020-2023, Linus Groh <linusg@serenityos.org> 3 * Copyright (c) 2021, Andreas Kling <kling@serenityos.org> 4 * Copyright (c) 2022, Ali Chraghi <chraghiali1@gmail.com> 5 * 6 * SPDX-License-Identifier: BSD-2-Clause 7 */ 8 9#include <AK/LexicalPath.h> 10#include <AK/StringBuilder.h> 11#include <AK/Types.h> 12#include <AK/URL.h> 13#include <Applications/CrashReporter/CrashReporterWindowGML.h> 14#include <LibCore/ArgsParser.h> 15#include <LibCore/DeprecatedFile.h> 16#include <LibCore/System.h> 17#include <LibCoredump/Backtrace.h> 18#include <LibCoredump/Reader.h> 19#include <LibDesktop/AppFile.h> 20#include <LibDesktop/Launcher.h> 21#include <LibELF/Core.h> 22#include <LibFileSystemAccessClient/Client.h> 23#include <LibGUI/Application.h> 24#include <LibGUI/BoxLayout.h> 25#include <LibGUI/Button.h> 26#include <LibGUI/FileIconProvider.h> 27#include <LibGUI/Icon.h> 28#include <LibGUI/ImageWidget.h> 29#include <LibGUI/Label.h> 30#include <LibGUI/LinkLabel.h> 31#include <LibGUI/MessageBox.h> 32#include <LibGUI/Process.h> 33#include <LibGUI/Progressbar.h> 34#include <LibGUI/TabWidget.h> 35#include <LibGUI/TextEditor.h> 36#include <LibGUI/Widget.h> 37#include <LibGUI/Window.h> 38#include <LibMain/Main.h> 39#include <LibThreading/BackgroundAction.h> 40#include <serenity.h> 41#include <spawn.h> 42#include <string.h> 43#include <unistd.h> 44 45struct TitleAndText { 46 DeprecatedString title; 47 DeprecatedString text; 48}; 49 50struct ThreadBacktracesAndCpuRegisters { 51 Vector<TitleAndText> thread_backtraces; 52 Vector<TitleAndText> thread_cpu_registers; 53}; 54 55static TitleAndText build_backtrace(Coredump::Reader const& coredump, ELF::Core::ThreadInfo const& thread_info, size_t thread_index, Function<void(size_t, size_t)> on_progress) 56{ 57 auto timer = Core::ElapsedTimer::start_new(); 58 Coredump::Backtrace backtrace(coredump, thread_info, move(on_progress)); 59 60 auto metadata = coredump.metadata(); 61 62 dbgln("Generating backtrace took {} ms", timer.elapsed()); 63 64 StringBuilder builder; 65 66 auto prepend_metadata = [&](auto& key, StringView fmt) { 67 auto maybe_value = metadata.get(key); 68 if (!maybe_value.has_value() || maybe_value.value().is_empty()) 69 return; 70 builder.appendff(fmt, maybe_value.value()); 71 builder.append('\n'); 72 builder.append('\n'); 73 }; 74 75 if (metadata.contains("assertion")) 76 prepend_metadata("assertion", "ASSERTION FAILED: {}"sv); 77 else if (metadata.contains("pledge_violation")) 78 prepend_metadata("pledge_violation", "Has not pledged {}"sv); 79 80 auto fault_address = metadata.get("fault_address"); 81 auto fault_type = metadata.get("fault_type"); 82 auto fault_access = metadata.get("fault_access"); 83 if (fault_address.has_value() && fault_type.has_value() && fault_access.has_value()) { 84 builder.appendff("{} fault on {} at address {}\n\n", fault_type.value(), fault_access.value(), fault_address.value()); 85 } 86 87 auto first_entry = true; 88 for (auto& entry : backtrace.entries()) { 89 if (first_entry) 90 first_entry = false; 91 else 92 builder.append('\n'); 93 builder.append(entry.to_deprecated_string()); 94 } 95 96 dbgln("--- Backtrace for thread #{} (TID {}) ---", thread_index, thread_info.tid); 97 for (auto& entry : backtrace.entries()) { 98 dbgln("{}", entry.to_deprecated_string(true)); 99 } 100 101 return { 102 DeprecatedString::formatted("Thread #{} (TID {})", thread_index, thread_info.tid), 103 builder.to_deprecated_string() 104 }; 105} 106 107static TitleAndText build_cpu_registers(const ELF::Core::ThreadInfo& thread_info, size_t thread_index) 108{ 109 auto& regs = thread_info.regs; 110 111 StringBuilder builder; 112 113#if ARCH(X86_64) 114 builder.appendff("rax={:p} rbx={:p} rcx={:p} rdx={:p}\n", regs.rax, regs.rbx, regs.rcx, regs.rdx); 115 builder.appendff("rbp={:p} rsp={:p} rsi={:p} rdi={:p}\n", regs.rbp, regs.rsp, regs.rsi, regs.rdi); 116 builder.appendff(" r8={:p} r9={:p} r10={:p} r11={:p}\n", regs.r8, regs.r9, regs.r10, regs.r11); 117 builder.appendff("r12={:p} r13={:p} r14={:p} r15={:p}\n", regs.r12, regs.r13, regs.r14, regs.r15); 118 builder.appendff("rip={:p} rflags={:p}", regs.rip, regs.rflags); 119#elif ARCH(AARCH64) 120 (void)regs; 121 TODO_AARCH64(); 122#else 123# error Unknown architecture 124#endif 125 126 return { 127 DeprecatedString::formatted("Thread #{} (TID {})", thread_index, thread_info.tid), 128 builder.to_deprecated_string() 129 }; 130} 131 132static void unlink_coredump(StringView coredump_path) 133{ 134 if (Core::DeprecatedFile::remove(coredump_path, Core::DeprecatedFile::RecursionMode::Disallowed).is_error()) 135 dbgln("Failed deleting coredump file"); 136} 137 138ErrorOr<int> serenity_main(Main::Arguments arguments) 139{ 140 TRY(Core::System::pledge("stdio recvfd sendfd cpath rpath unix proc exec thread")); 141 142 auto app = TRY(GUI::Application::try_create(arguments)); 143 144 DeprecatedString coredump_path {}; 145 bool unlink_on_exit = false; 146 StringBuilder full_backtrace; 147 148 Core::ArgsParser args_parser; 149 args_parser.set_general_help("Show information from an application crash coredump."); 150 args_parser.add_positional_argument(coredump_path, "Coredump path", "coredump-path"); 151 args_parser.add_option(unlink_on_exit, "Delete the coredump after its parsed", "unlink", 0); 152 args_parser.parse(arguments); 153 154 auto coredump = Coredump::Reader::create(coredump_path); 155 if (!coredump) { 156 warnln("Could not open coredump '{}'", coredump_path); 157 return 1; 158 } 159 160 Vector<DeprecatedString> memory_regions; 161 coredump->for_each_memory_region_info([&](auto& memory_region_info) { 162 memory_regions.append(DeprecatedString::formatted("{:p} - {:p}: {}", memory_region_info.region_start, memory_region_info.region_end, memory_region_info.region_name)); 163 return IterationDecision::Continue; 164 }); 165 166 auto executable_path = coredump->process_executable_path(); 167 auto crashed_process_arguments = coredump->process_arguments(); 168 auto environment = coredump->process_environment(); 169 auto pid = coredump->process_pid(); 170 auto termination_signal = coredump->process_termination_signal(); 171 172 auto app_icon = GUI::Icon::default_icon("app-crash-reporter"sv); 173 174 auto window = TRY(GUI::Window::try_create()); 175 window->set_title("Crash Reporter"); 176 window->set_icon(app_icon.bitmap_for_size(16)); 177 window->resize(460, 190); 178 window->center_on_screen(); 179 window->on_close = [unlink_on_exit, &coredump_path]() { 180 if (unlink_on_exit) 181 unlink_coredump(coredump_path); 182 }; 183 184 auto widget = TRY(window->set_main_widget<GUI::Widget>()); 185 TRY(widget->load_from_gml(crash_reporter_window_gml)); 186 187 auto& icon_image_widget = *widget->find_descendant_of_type_named<GUI::ImageWidget>("icon"); 188 icon_image_widget.set_bitmap(GUI::FileIconProvider::icon_for_executable(executable_path).bitmap_for_size(32)); 189 190 auto app_name = LexicalPath::basename(executable_path); 191 auto af = Desktop::AppFile::get_for_app(app_name); 192 if (af->is_valid()) 193 app_name = af->name(); 194 195 auto& description_label = *widget->find_descendant_of_type_named<GUI::Label>("description"); 196 description_label.set_text(DeprecatedString::formatted("\"{}\" (PID {}) has crashed - {} (signal {})", app_name, pid, strsignal(termination_signal), termination_signal)); 197 198 auto& executable_link_label = *widget->find_descendant_of_type_named<GUI::LinkLabel>("executable_link"); 199 executable_link_label.set_text(LexicalPath::canonicalized_path(executable_path)); 200 executable_link_label.on_click = [&] { 201 LexicalPath path { executable_path }; 202 Desktop::Launcher::open(URL::create_with_file_scheme(path.dirname(), path.basename())); 203 }; 204 205 auto& coredump_link_label = *widget->find_descendant_of_type_named<GUI::LinkLabel>("coredump_link"); 206 coredump_link_label.set_text(LexicalPath::canonicalized_path(coredump_path)); 207 coredump_link_label.on_click = [&] { 208 LexicalPath path { coredump_path }; 209 Desktop::Launcher::open(URL::create_with_file_scheme(path.dirname(), path.basename())); 210 }; 211 212 auto& arguments_label = *widget->find_descendant_of_type_named<GUI::Label>("arguments_label"); 213 arguments_label.set_text(DeprecatedString::join(' ', crashed_process_arguments)); 214 215 auto& progressbar = *widget->find_descendant_of_type_named<GUI::Progressbar>("progressbar"); 216 auto& tab_widget = *widget->find_descendant_of_type_named<GUI::TabWidget>("tab_widget"); 217 218 auto backtrace_tab = TRY(tab_widget.try_add_tab<GUI::Widget>("Backtrace")); 219 TRY(backtrace_tab->try_set_layout<GUI::VerticalBoxLayout>(4)); 220 221 auto backtrace_label = TRY(backtrace_tab->try_add<GUI::Label>("A backtrace for each thread alive during the crash is listed below:")); 222 backtrace_label->set_text_alignment(Gfx::TextAlignment::CenterLeft); 223 backtrace_label->set_fixed_height(16); 224 225 auto backtrace_tab_widget = TRY(backtrace_tab->try_add<GUI::TabWidget>()); 226 backtrace_tab_widget->set_tab_position(GUI::TabWidget::TabPosition::Bottom); 227 228 auto cpu_registers_tab = TRY(tab_widget.try_add_tab<GUI::Widget>("CPU Registers")); 229 cpu_registers_tab->set_layout<GUI::VerticalBoxLayout>(4); 230 231 auto cpu_registers_label = TRY(cpu_registers_tab->try_add<GUI::Label>("The CPU register state for each thread alive during the crash is listed below:")); 232 cpu_registers_label->set_text_alignment(Gfx::TextAlignment::CenterLeft); 233 cpu_registers_label->set_fixed_height(16); 234 235 auto cpu_registers_tab_widget = TRY(cpu_registers_tab->try_add<GUI::TabWidget>()); 236 cpu_registers_tab_widget->set_tab_position(GUI::TabWidget::TabPosition::Bottom); 237 238 auto environment_tab = TRY(tab_widget.try_add_tab<GUI::Widget>("Environment")); 239 TRY(environment_tab->try_set_layout<GUI::VerticalBoxLayout>(4)); 240 241 auto environment_text_editor = TRY(environment_tab->try_add<GUI::TextEditor>()); 242 environment_text_editor->set_text(DeprecatedString::join('\n', environment)); 243 environment_text_editor->set_mode(GUI::TextEditor::Mode::ReadOnly); 244 environment_text_editor->set_wrapping_mode(GUI::TextEditor::WrappingMode::NoWrap); 245 environment_text_editor->set_should_hide_unnecessary_scrollbars(true); 246 247 auto memory_regions_tab = TRY(tab_widget.try_add_tab<GUI::Widget>("Memory Regions")); 248 TRY(memory_regions_tab->try_set_layout<GUI::VerticalBoxLayout>(4)); 249 250 auto memory_regions_text_editor = TRY(memory_regions_tab->try_add<GUI::TextEditor>()); 251 memory_regions_text_editor->set_text(DeprecatedString::join('\n', memory_regions)); 252 memory_regions_text_editor->set_mode(GUI::TextEditor::Mode::ReadOnly); 253 memory_regions_text_editor->set_wrapping_mode(GUI::TextEditor::WrappingMode::NoWrap); 254 memory_regions_text_editor->set_should_hide_unnecessary_scrollbars(true); 255 memory_regions_text_editor->set_visualize_trailing_whitespace(false); 256 257 auto& close_button = *widget->find_descendant_of_type_named<GUI::Button>("close_button"); 258 close_button.on_click = [&](auto) { 259 window->close(); 260 }; 261 close_button.set_focus(true); 262 263 auto& debug_button = *widget->find_descendant_of_type_named<GUI::Button>("debug_button"); 264 debug_button.set_icon(TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/app-hack-studio.png"sv))); 265 debug_button.on_click = [&](int) { 266 GUI::Process::spawn_or_show_error(window, "/bin/HackStudio"sv, Array { "-c", coredump_path.characters() }); 267 }; 268 269 auto& save_backtrace_button = *widget->find_descendant_of_type_named<GUI::Button>("save_backtrace_button"); 270 save_backtrace_button.set_icon(TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/save.png"sv))); 271 save_backtrace_button.on_click = [&](auto) { 272 LexicalPath lexical_path(DeprecatedString::formatted("{}_{}_backtrace.txt", pid, app_name)); 273 auto file_or_error = FileSystemAccessClient::Client::the().save_file(window, lexical_path.title(), lexical_path.extension()); 274 if (file_or_error.is_error()) { 275 GUI::MessageBox::show(window, DeprecatedString::formatted("Communication failed with FileSystemAccessServer: {}.", file_or_error.release_error()), "Saving backtrace failed"sv, GUI::MessageBox::Type::Error); 276 return; 277 } 278 auto file = file_or_error.release_value().release_stream(); 279 280 auto byte_buffer_or_error = full_backtrace.to_byte_buffer(); 281 if (byte_buffer_or_error.is_error()) { 282 GUI::MessageBox::show(window, DeprecatedString::formatted("Couldn't create backtrace: {}.", byte_buffer_or_error.release_error()), "Saving backtrace failed"sv, GUI::MessageBox::Type::Error); 283 return; 284 } 285 auto byte_buffer = byte_buffer_or_error.release_value(); 286 287 if (auto result = file->write_until_depleted(byte_buffer); result.is_error()) 288 GUI::MessageBox::show(window, DeprecatedString::formatted("Couldn't save file: {}.", result.release_error()), "Saving backtrace failed"sv, GUI::MessageBox::Type::Error); 289 }; 290 save_backtrace_button.set_enabled(false); 291 292 (void)Threading::BackgroundAction<ThreadBacktracesAndCpuRegisters>::construct( 293 [&, coredump = move(coredump)](auto&) { 294 ThreadBacktracesAndCpuRegisters results; 295 size_t thread_index = 0; 296 coredump->for_each_thread_info([&](auto& thread_info) { 297 results.thread_backtraces.append(build_backtrace(*coredump, thread_info, thread_index, [&](size_t frame_index, size_t frame_count) { 298 app->event_loop().deferred_invoke([&, frame_index, frame_count] { 299 window->set_progress(100.0f * (float)(frame_index + 1) / (float)frame_count); 300 progressbar.set_value(frame_index + 1); 301 progressbar.set_max(frame_count); 302 }); 303 })); 304 results.thread_cpu_registers.append(build_cpu_registers(thread_info, thread_index)); 305 ++thread_index; 306 return IterationDecision::Continue; 307 }); 308 return results; 309 }, 310 [&](auto results) -> ErrorOr<void> { 311 for (auto& backtrace : results.thread_backtraces) { 312 auto container = TRY(backtrace_tab_widget->try_add_tab<GUI::Widget>(backtrace.title)); 313 TRY(container->template try_set_layout<GUI::VerticalBoxLayout>(4)); 314 auto backtrace_text_editor = TRY(container->template try_add<GUI::TextEditor>()); 315 backtrace_text_editor->set_text(backtrace.text); 316 backtrace_text_editor->set_mode(GUI::TextEditor::Mode::ReadOnly); 317 backtrace_text_editor->set_wrapping_mode(GUI::TextEditor::WrappingMode::NoWrap); 318 backtrace_text_editor->set_should_hide_unnecessary_scrollbars(true); 319 TRY(full_backtrace.try_appendff("==== {} ====\n{}\n", backtrace.title, backtrace.text)); 320 } 321 322 for (auto& cpu_registers : results.thread_cpu_registers) { 323 auto container = TRY(cpu_registers_tab_widget->try_add_tab<GUI::Widget>(cpu_registers.title)); 324 TRY(container->template try_set_layout<GUI::VerticalBoxLayout>(4)); 325 auto cpu_registers_text_editor = TRY(container->template try_add<GUI::TextEditor>()); 326 cpu_registers_text_editor->set_text(cpu_registers.text); 327 cpu_registers_text_editor->set_mode(GUI::TextEditor::Mode::ReadOnly); 328 cpu_registers_text_editor->set_wrapping_mode(GUI::TextEditor::WrappingMode::NoWrap); 329 cpu_registers_text_editor->set_should_hide_unnecessary_scrollbars(true); 330 } 331 332 progressbar.set_visible(false); 333 tab_widget.set_visible(true); 334 save_backtrace_button.set_enabled(true); 335 window->resize(window->width(), max(340, window->height())); 336 window->set_progress(0); 337 return {}; 338 }, 339 [window](Error error) { 340 dbgln("Error while parsing the coredump: {}", error); 341 window->close(); 342 }); 343 344 window->show(); 345 346 return app->exec(); 347}