main.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. /*
  2. * Copyright (c) 2020-2021, 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. #include <AK/LexicalPath.h>
  9. #include <AK/StringBuilder.h>
  10. #include <AK/Types.h>
  11. #include <AK/URL.h>
  12. #include <Applications/CrashReporter/CrashReporterWindowGML.h>
  13. #include <LibC/serenity.h>
  14. #include <LibC/spawn.h>
  15. #include <LibCore/ArgsParser.h>
  16. #include <LibCore/File.h>
  17. #include <LibCore/System.h>
  18. #include <LibCoredump/Backtrace.h>
  19. #include <LibCoredump/Reader.h>
  20. #include <LibDesktop/AppFile.h>
  21. #include <LibDesktop/Launcher.h>
  22. #include <LibELF/Core.h>
  23. #include <LibFileSystemAccessClient/Client.h>
  24. #include <LibGUI/Application.h>
  25. #include <LibGUI/BoxLayout.h>
  26. #include <LibGUI/Button.h>
  27. #include <LibGUI/FileIconProvider.h>
  28. #include <LibGUI/Icon.h>
  29. #include <LibGUI/ImageWidget.h>
  30. #include <LibGUI/Label.h>
  31. #include <LibGUI/LinkLabel.h>
  32. #include <LibGUI/MessageBox.h>
  33. #include <LibGUI/Process.h>
  34. #include <LibGUI/Progressbar.h>
  35. #include <LibGUI/TabWidget.h>
  36. #include <LibGUI/TextEditor.h>
  37. #include <LibGUI/Widget.h>
  38. #include <LibGUI/Window.h>
  39. #include <LibMain/Main.h>
  40. #include <LibThreading/BackgroundAction.h>
  41. #include <string.h>
  42. #include <unistd.h>
  43. struct TitleAndText {
  44. String title;
  45. String text;
  46. };
  47. struct ThreadBacktracesAndCpuRegisters {
  48. Vector<TitleAndText> thread_backtraces;
  49. Vector<TitleAndText> thread_cpu_registers;
  50. };
  51. static 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)
  52. {
  53. auto timer = Core::ElapsedTimer::start_new();
  54. Coredump::Backtrace backtrace(coredump, thread_info, move(on_progress));
  55. auto metadata = coredump.metadata();
  56. dbgln("Generating backtrace took {} ms", timer.elapsed());
  57. StringBuilder builder;
  58. auto prepend_metadata = [&](auto& key, StringView fmt) {
  59. auto maybe_value = metadata.get(key);
  60. if (!maybe_value.has_value() || maybe_value.value().is_empty())
  61. return;
  62. builder.appendff(fmt, maybe_value.value());
  63. builder.append('\n');
  64. builder.append('\n');
  65. };
  66. if (metadata.contains("assertion"))
  67. prepend_metadata("assertion", "ASSERTION FAILED: {}");
  68. else if (metadata.contains("pledge_violation"))
  69. prepend_metadata("pledge_violation", "Has not pledged {}");
  70. auto fault_address = metadata.get("fault_address");
  71. auto fault_type = metadata.get("fault_type");
  72. auto fault_access = metadata.get("fault_access");
  73. if (fault_address.has_value() && fault_type.has_value() && fault_access.has_value()) {
  74. builder.appendff("{} fault on {} at address {}\n\n", fault_type.value(), fault_access.value(), fault_address.value());
  75. }
  76. auto first_entry = true;
  77. for (auto& entry : backtrace.entries()) {
  78. if (first_entry)
  79. first_entry = false;
  80. else
  81. builder.append('\n');
  82. builder.append(entry.to_string());
  83. }
  84. dbgln("--- Backtrace for thread #{} (TID {}) ---", thread_index, thread_info.tid);
  85. for (auto& entry : backtrace.entries()) {
  86. dbgln("{}", entry.to_string(true));
  87. }
  88. return {
  89. String::formatted("Thread #{} (TID {})", thread_index, thread_info.tid),
  90. builder.build()
  91. };
  92. }
  93. static TitleAndText build_cpu_registers(const ELF::Core::ThreadInfo& thread_info, size_t thread_index)
  94. {
  95. auto& regs = thread_info.regs;
  96. StringBuilder builder;
  97. #if ARCH(I386)
  98. builder.appendff("eax={:p} ebx={:p} ecx={:p} edx={:p}\n", regs.eax, regs.ebx, regs.ecx, regs.edx);
  99. builder.appendff("ebp={:p} esp={:p} esi={:p} edi={:p}\n", regs.ebp, regs.esp, regs.esi, regs.edi);
  100. builder.appendff("eip={:p} eflags={:p}", regs.eip, regs.eflags);
  101. #else
  102. builder.appendff("rax={:p} rbx={:p} rcx={:p} rdx={:p}\n", regs.rax, regs.rbx, regs.rcx, regs.rdx);
  103. builder.appendff("rbp={:p} rsp={:p} rsi={:p} rdi={:p}\n", regs.rbp, regs.rsp, regs.rsi, regs.rdi);
  104. builder.appendff(" r8={:p} r9={:p} r10={:p} r11={:p}\n", regs.r8, regs.r9, regs.r10, regs.r11);
  105. builder.appendff("r12={:p} r13={:p} r14={:p} r15={:p}\n", regs.r12, regs.r13, regs.r14, regs.r15);
  106. builder.appendff("rip={:p} rflags={:p}", regs.rip, regs.rflags);
  107. #endif
  108. return {
  109. String::formatted("Thread #{} (TID {})", thread_index, thread_info.tid),
  110. builder.build()
  111. };
  112. }
  113. static void unlink_coredump(StringView const& coredump_path)
  114. {
  115. if (Core::File::remove(coredump_path, Core::File::RecursionMode::Disallowed, false).is_error())
  116. dbgln("Failed deleting coredump file");
  117. }
  118. ErrorOr<int> serenity_main(Main::Arguments arguments)
  119. {
  120. TRY(Core::System::pledge("stdio recvfd sendfd cpath rpath unix proc exec thread"));
  121. auto app = TRY(GUI::Application::try_create(arguments));
  122. String coredump_path {};
  123. bool unlink_on_exit = false;
  124. StringBuilder full_backtrace;
  125. Core::ArgsParser args_parser;
  126. args_parser.set_general_help("Show information from an application crash coredump.");
  127. args_parser.add_positional_argument(coredump_path, "Coredump path", "coredump-path");
  128. args_parser.add_option(unlink_on_exit, "Delete the coredump after its parsed", "unlink", 0);
  129. args_parser.parse(arguments);
  130. auto coredump = Coredump::Reader::create(coredump_path);
  131. if (!coredump) {
  132. warnln("Could not open coredump '{}'", coredump_path);
  133. return 1;
  134. }
  135. Vector<String> memory_regions;
  136. coredump->for_each_memory_region_info([&](auto& memory_region_info) {
  137. memory_regions.append(String::formatted("{:p} - {:p}: {}", memory_region_info.region_start, memory_region_info.region_end, memory_region_info.region_name));
  138. return IterationDecision::Continue;
  139. });
  140. auto executable_path = coredump->process_executable_path();
  141. auto crashed_process_arguments = coredump->process_arguments();
  142. auto environment = coredump->process_environment();
  143. auto pid = coredump->process_pid();
  144. auto termination_signal = coredump->process_termination_signal();
  145. auto app_icon = GUI::Icon::default_icon("app-crash-reporter");
  146. auto window = TRY(GUI::Window::try_create());
  147. window->set_title("Crash Reporter");
  148. window->set_icon(app_icon.bitmap_for_size(16));
  149. window->resize(460, 190);
  150. window->center_on_screen();
  151. window->on_close = [unlink_on_exit, &coredump_path]() {
  152. if (unlink_on_exit)
  153. unlink_coredump(coredump_path);
  154. };
  155. auto widget = TRY(window->try_set_main_widget<GUI::Widget>());
  156. widget->load_from_gml(crash_reporter_window_gml);
  157. auto& icon_image_widget = *widget->find_descendant_of_type_named<GUI::ImageWidget>("icon");
  158. icon_image_widget.set_bitmap(GUI::FileIconProvider::icon_for_executable(executable_path).bitmap_for_size(32));
  159. auto app_name = LexicalPath::basename(executable_path);
  160. auto af = Desktop::AppFile::get_for_app(app_name);
  161. if (af->is_valid())
  162. app_name = af->name();
  163. auto& description_label = *widget->find_descendant_of_type_named<GUI::Label>("description");
  164. description_label.set_text(String::formatted("\"{}\" (PID {}) has crashed - {} (signal {})", app_name, pid, strsignal(termination_signal), termination_signal));
  165. auto& executable_link_label = *widget->find_descendant_of_type_named<GUI::LinkLabel>("executable_link");
  166. executable_link_label.set_text(LexicalPath::canonicalized_path(executable_path));
  167. executable_link_label.on_click = [&] {
  168. LexicalPath path { executable_path };
  169. Desktop::Launcher::open(URL::create_with_file_protocol(path.dirname(), path.basename()));
  170. };
  171. auto& coredump_link_label = *widget->find_descendant_of_type_named<GUI::LinkLabel>("coredump_link");
  172. coredump_link_label.set_text(LexicalPath::canonicalized_path(coredump_path));
  173. coredump_link_label.on_click = [&] {
  174. LexicalPath path { coredump_path };
  175. Desktop::Launcher::open(URL::create_with_file_protocol(path.dirname(), path.basename()));
  176. };
  177. auto& arguments_label = *widget->find_descendant_of_type_named<GUI::Label>("arguments_label");
  178. arguments_label.set_text(String::join(" ", crashed_process_arguments));
  179. auto& progressbar = *widget->find_descendant_of_type_named<GUI::Progressbar>("progressbar");
  180. auto& tab_widget = *widget->find_descendant_of_type_named<GUI::TabWidget>("tab_widget");
  181. auto backtrace_tab = TRY(tab_widget.try_add_tab<GUI::Widget>("Backtrace"));
  182. (void)TRY(backtrace_tab->try_set_layout<GUI::VerticalBoxLayout>());
  183. backtrace_tab->layout()->set_margins(4);
  184. auto backtrace_label = TRY(backtrace_tab->try_add<GUI::Label>("A backtrace for each thread alive during the crash is listed below:"));
  185. backtrace_label->set_text_alignment(Gfx::TextAlignment::CenterLeft);
  186. backtrace_label->set_fixed_height(16);
  187. auto backtrace_tab_widget = TRY(backtrace_tab->try_add<GUI::TabWidget>());
  188. backtrace_tab_widget->set_tab_position(GUI::TabWidget::TabPosition::Bottom);
  189. auto cpu_registers_tab = TRY(tab_widget.try_add_tab<GUI::Widget>("CPU Registers"));
  190. cpu_registers_tab->set_layout<GUI::VerticalBoxLayout>();
  191. cpu_registers_tab->layout()->set_margins(4);
  192. 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:"));
  193. cpu_registers_label->set_text_alignment(Gfx::TextAlignment::CenterLeft);
  194. cpu_registers_label->set_fixed_height(16);
  195. auto cpu_registers_tab_widget = TRY(cpu_registers_tab->try_add<GUI::TabWidget>());
  196. cpu_registers_tab_widget->set_tab_position(GUI::TabWidget::TabPosition::Bottom);
  197. auto environment_tab = TRY(tab_widget.try_add_tab<GUI::Widget>("Environment"));
  198. (void)TRY(environment_tab->try_set_layout<GUI::VerticalBoxLayout>());
  199. environment_tab->layout()->set_margins(4);
  200. auto environment_text_editor = TRY(environment_tab->try_add<GUI::TextEditor>());
  201. environment_text_editor->set_text(String::join("\n", environment));
  202. environment_text_editor->set_mode(GUI::TextEditor::Mode::ReadOnly);
  203. environment_text_editor->set_should_hide_unnecessary_scrollbars(true);
  204. auto memory_regions_tab = TRY(tab_widget.try_add_tab<GUI::Widget>("Memory Regions"));
  205. (void)TRY(memory_regions_tab->try_set_layout<GUI::VerticalBoxLayout>());
  206. memory_regions_tab->layout()->set_margins(4);
  207. auto memory_regions_text_editor = TRY(memory_regions_tab->try_add<GUI::TextEditor>());
  208. memory_regions_text_editor->set_text(String::join("\n", memory_regions));
  209. memory_regions_text_editor->set_mode(GUI::TextEditor::Mode::ReadOnly);
  210. memory_regions_text_editor->set_should_hide_unnecessary_scrollbars(true);
  211. memory_regions_text_editor->set_visualize_trailing_whitespace(false);
  212. auto& close_button = *widget->find_descendant_of_type_named<GUI::Button>("close_button");
  213. close_button.on_click = [&](auto) {
  214. if (unlink_on_exit)
  215. unlink_coredump(coredump_path);
  216. app->quit();
  217. };
  218. auto& debug_button = *widget->find_descendant_of_type_named<GUI::Button>("debug_button");
  219. debug_button.set_icon(TRY(Gfx::Bitmap::try_load_from_file("/res/icons/16x16/app-hack-studio.png")));
  220. debug_button.on_click = [&](int) {
  221. GUI::Process::spawn_or_show_error(window, "/bin/HackStudio", Array { "-c", coredump_path.characters() });
  222. };
  223. auto& save_backtrace_button = *widget->find_descendant_of_type_named<GUI::Button>("save_backtrace_button");
  224. save_backtrace_button.set_icon(TRY(Gfx::Bitmap::try_load_from_file("/res/icons/16x16/save.png")));
  225. save_backtrace_button.on_click = [&](auto) {
  226. if (full_backtrace.is_empty()) {
  227. GUI::MessageBox::show(window, "Backtrace has not been generated yet. Please wait...", "Empty Backtrace", GUI::MessageBox::Type::Error);
  228. return;
  229. }
  230. LexicalPath lexical_path(String::formatted("{}_{}_backtrace.txt", pid, app_name));
  231. auto file_or_error = FileSystemAccessClient::Client::the().try_save_file(window, lexical_path.title(), lexical_path.extension());
  232. if (file_or_error.is_error())
  233. return;
  234. auto file = file_or_error.value();
  235. if (!file->write(full_backtrace.to_string()))
  236. GUI::MessageBox::show(window, String::formatted("Couldn't save file: {}.", file_or_error.error()), "Saving backtrace failed", GUI::MessageBox::Type::Error);
  237. };
  238. (void)Threading::BackgroundAction<ThreadBacktracesAndCpuRegisters>::construct(
  239. [&, coredump = move(coredump)](auto&) {
  240. ThreadBacktracesAndCpuRegisters results;
  241. size_t thread_index = 0;
  242. coredump->for_each_thread_info([&](auto& thread_info) {
  243. results.thread_backtraces.append(build_backtrace(*coredump, thread_info, thread_index, [&](size_t frame_index, size_t frame_count) {
  244. app->event_loop().deferred_invoke([&, frame_index, frame_count] {
  245. window->set_progress(100.0f * (float)(frame_index + 1) / (float)frame_count);
  246. progressbar.set_value(frame_index + 1);
  247. progressbar.set_max(frame_count);
  248. });
  249. }));
  250. results.thread_cpu_registers.append(build_cpu_registers(thread_info, thread_index));
  251. ++thread_index;
  252. return IterationDecision::Continue;
  253. });
  254. return results;
  255. },
  256. [&](auto results) {
  257. // FIXME: Make BackgroundAction propagate ErrorOr values so we can replace these MUSTs with TRYs.
  258. for (auto& backtrace : results.thread_backtraces) {
  259. auto container = MUST(backtrace_tab_widget->try_add_tab<GUI::Widget>(backtrace.title));
  260. (void)MUST(container->template try_set_layout<GUI::VerticalBoxLayout>());
  261. container->layout()->set_margins(4);
  262. auto backtrace_text_editor = MUST(container->template try_add<GUI::TextEditor>());
  263. backtrace_text_editor->set_text(backtrace.text);
  264. backtrace_text_editor->set_mode(GUI::TextEditor::Mode::ReadOnly);
  265. backtrace_text_editor->set_should_hide_unnecessary_scrollbars(true);
  266. full_backtrace.appendff("==== {} ====\n{}\n", backtrace.title, backtrace.text);
  267. }
  268. for (auto& cpu_registers : results.thread_cpu_registers) {
  269. auto container = MUST(cpu_registers_tab_widget->try_add_tab<GUI::Widget>(cpu_registers.title));
  270. (void)MUST(container->template try_set_layout<GUI::VerticalBoxLayout>());
  271. container->layout()->set_margins(4);
  272. auto cpu_registers_text_editor = MUST(container->template try_add<GUI::TextEditor>());
  273. cpu_registers_text_editor->set_text(cpu_registers.text);
  274. cpu_registers_text_editor->set_mode(GUI::TextEditor::Mode::ReadOnly);
  275. cpu_registers_text_editor->set_should_hide_unnecessary_scrollbars(true);
  276. }
  277. progressbar.set_visible(false);
  278. tab_widget.set_visible(true);
  279. window->resize(window->width(), max(340, window->height()));
  280. window->set_progress(0);
  281. });
  282. window->show();
  283. return app->exec();
  284. }