Coredump.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. /*
  2. * Copyright (c) 2019-2020, Jesse Buhagiar <jooster669@gmail.com>
  3. * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
  4. * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
  5. * Copyright (c) 2021, Andreas Kling <klingi@serenityos.org>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/ByteBuffer.h>
  10. #include <AK/JsonObjectSerializer.h>
  11. #include <Kernel/Coredump.h>
  12. #include <Kernel/FileSystem/Custody.h>
  13. #include <Kernel/FileSystem/OpenFileDescription.h>
  14. #include <Kernel/FileSystem/VirtualFileSystem.h>
  15. #include <Kernel/KLexicalPath.h>
  16. #include <Kernel/Locking/Spinlock.h>
  17. #include <Kernel/Memory/ScopedAddressSpaceSwitcher.h>
  18. #include <Kernel/Process.h>
  19. #include <Kernel/RTC.h>
  20. #include <LibC/elf.h>
  21. #include <LibELF/Core.h>
  22. #define INCLUDE_USERSPACE_HEAP_MEMORY_IN_COREDUMPS 0
  23. namespace Kernel {
  24. [[maybe_unused]] static bool looks_like_userspace_heap_region(Memory::Region const& region)
  25. {
  26. return region.name().starts_with("LibJS:"sv) || region.name().starts_with("malloc:"sv);
  27. }
  28. ErrorOr<NonnullOwnPtr<Coredump>> Coredump::try_create(NonnullLockRefPtr<Process> process, StringView output_path)
  29. {
  30. if (!process->is_dumpable()) {
  31. dbgln("Refusing to generate coredump for non-dumpable process {}", process->pid().value());
  32. return EPERM;
  33. }
  34. auto description = TRY(try_create_target_file(process, output_path));
  35. return adopt_nonnull_own_or_enomem(new (nothrow) Coredump(move(process), move(description)));
  36. }
  37. Coredump::Coredump(NonnullLockRefPtr<Process> process, NonnullLockRefPtr<OpenFileDescription> description)
  38. : m_process(move(process))
  39. , m_description(move(description))
  40. {
  41. m_num_program_headers = 0;
  42. for ([[maybe_unused]] auto& region : m_process->address_space().regions()) {
  43. #if !INCLUDE_USERSPACE_HEAP_MEMORY_IN_COREDUMPS
  44. if (looks_like_userspace_heap_region(region))
  45. continue;
  46. #endif
  47. if (region.access() == Memory::Region::Access::None)
  48. continue;
  49. ++m_num_program_headers;
  50. }
  51. ++m_num_program_headers; // +1 for NOTE segment
  52. }
  53. ErrorOr<NonnullLockRefPtr<OpenFileDescription>> Coredump::try_create_target_file(Process const& process, StringView output_path)
  54. {
  55. auto output_directory = KLexicalPath::dirname(output_path);
  56. auto dump_directory = TRY(VirtualFileSystem::the().open_directory(Process::current().credentials(), output_directory, VirtualFileSystem::the().root_custody()));
  57. auto dump_directory_metadata = dump_directory->inode().metadata();
  58. if (dump_directory_metadata.uid != 0 || dump_directory_metadata.gid != 0 || dump_directory_metadata.mode != 040777) {
  59. dbgln("Refusing to put coredump in sketchy directory '{}'", output_directory);
  60. return EINVAL;
  61. }
  62. auto process_credentials = process.credentials();
  63. return TRY(VirtualFileSystem::the().open(
  64. Process::current().credentials(),
  65. KLexicalPath::basename(output_path),
  66. O_CREAT | O_WRONLY | O_EXCL,
  67. S_IFREG, // We will enable reading from userspace when we finish generating the coredump file
  68. *dump_directory,
  69. UidAndGid { process_credentials->uid(), process_credentials->gid() }));
  70. }
  71. ErrorOr<void> Coredump::write_elf_header()
  72. {
  73. ElfW(Ehdr) elf_file_header;
  74. elf_file_header.e_ident[EI_MAG0] = 0x7f;
  75. elf_file_header.e_ident[EI_MAG1] = 'E';
  76. elf_file_header.e_ident[EI_MAG2] = 'L';
  77. elf_file_header.e_ident[EI_MAG3] = 'F';
  78. #if ARCH(I386)
  79. elf_file_header.e_ident[EI_CLASS] = ELFCLASS32;
  80. #elif ARCH(X86_64) || ARCH(AARCH64)
  81. elf_file_header.e_ident[EI_CLASS] = ELFCLASS64;
  82. #else
  83. # error Unknown architecture
  84. #endif
  85. elf_file_header.e_ident[EI_DATA] = ELFDATA2LSB;
  86. elf_file_header.e_ident[EI_VERSION] = EV_CURRENT;
  87. elf_file_header.e_ident[EI_OSABI] = 0; // ELFOSABI_NONE
  88. elf_file_header.e_ident[EI_ABIVERSION] = 0;
  89. elf_file_header.e_ident[EI_PAD + 1] = 0;
  90. elf_file_header.e_ident[EI_PAD + 2] = 0;
  91. elf_file_header.e_ident[EI_PAD + 3] = 0;
  92. elf_file_header.e_ident[EI_PAD + 4] = 0;
  93. elf_file_header.e_ident[EI_PAD + 5] = 0;
  94. elf_file_header.e_ident[EI_PAD + 6] = 0;
  95. elf_file_header.e_type = ET_CORE;
  96. #if ARCH(I386)
  97. elf_file_header.e_machine = EM_386;
  98. #elif ARCH(X86_64)
  99. elf_file_header.e_machine = EM_X86_64;
  100. #elif ARCH(AARCH64)
  101. elf_file_header.e_machine = EM_AARCH64;
  102. #else
  103. # error Unknown architecture
  104. #endif
  105. elf_file_header.e_version = 1;
  106. elf_file_header.e_entry = 0;
  107. elf_file_header.e_phoff = sizeof(ElfW(Ehdr));
  108. elf_file_header.e_shoff = 0;
  109. elf_file_header.e_flags = 0;
  110. elf_file_header.e_ehsize = sizeof(ElfW(Ehdr));
  111. elf_file_header.e_shentsize = sizeof(ElfW(Shdr));
  112. elf_file_header.e_phentsize = sizeof(ElfW(Phdr));
  113. elf_file_header.e_phnum = m_num_program_headers;
  114. elf_file_header.e_shnum = 0;
  115. elf_file_header.e_shstrndx = SHN_UNDEF;
  116. TRY(m_description->write(UserOrKernelBuffer::for_kernel_buffer(reinterpret_cast<uint8_t*>(&elf_file_header)), sizeof(ElfW(Ehdr))));
  117. return {};
  118. }
  119. ErrorOr<void> Coredump::write_program_headers(size_t notes_size)
  120. {
  121. size_t offset = sizeof(ElfW(Ehdr)) + m_num_program_headers * sizeof(ElfW(Phdr));
  122. for (auto& region : m_process->address_space().regions()) {
  123. #if !INCLUDE_USERSPACE_HEAP_MEMORY_IN_COREDUMPS
  124. if (looks_like_userspace_heap_region(region))
  125. continue;
  126. #endif
  127. if (region.access() == Memory::Region::Access::None)
  128. continue;
  129. ElfW(Phdr) phdr {};
  130. phdr.p_type = PT_LOAD;
  131. phdr.p_offset = offset;
  132. phdr.p_vaddr = region.vaddr().get();
  133. phdr.p_paddr = 0;
  134. phdr.p_filesz = region.page_count() * PAGE_SIZE;
  135. phdr.p_memsz = region.page_count() * PAGE_SIZE;
  136. phdr.p_align = 0;
  137. phdr.p_flags = region.is_readable() ? PF_R : 0;
  138. if (region.is_writable())
  139. phdr.p_flags |= PF_W;
  140. if (region.is_executable())
  141. phdr.p_flags |= PF_X;
  142. offset += phdr.p_filesz;
  143. [[maybe_unused]] auto rc = m_description->write(UserOrKernelBuffer::for_kernel_buffer(reinterpret_cast<uint8_t*>(&phdr)), sizeof(ElfW(Phdr)));
  144. }
  145. ElfW(Phdr) notes_pheader {};
  146. notes_pheader.p_type = PT_NOTE;
  147. notes_pheader.p_offset = offset;
  148. notes_pheader.p_vaddr = 0;
  149. notes_pheader.p_paddr = 0;
  150. notes_pheader.p_filesz = notes_size;
  151. notes_pheader.p_memsz = notes_size;
  152. notes_pheader.p_align = 0;
  153. notes_pheader.p_flags = 0;
  154. TRY(m_description->write(UserOrKernelBuffer::for_kernel_buffer(reinterpret_cast<uint8_t*>(&notes_pheader)), sizeof(ElfW(Phdr))));
  155. return {};
  156. }
  157. ErrorOr<void> Coredump::write_regions()
  158. {
  159. u8 zero_buffer[PAGE_SIZE] = {};
  160. for (auto& region : m_process->address_space().regions()) {
  161. VERIFY(!region.is_kernel());
  162. #if !INCLUDE_USERSPACE_HEAP_MEMORY_IN_COREDUMPS
  163. if (looks_like_userspace_heap_region(region))
  164. continue;
  165. #endif
  166. if (region.access() == Memory::Region::Access::None)
  167. continue;
  168. // If we crashed in the middle of mapping in Regions, they do not have a page directory yet, and will crash on a remap() call
  169. if (!region.is_mapped())
  170. continue;
  171. region.set_readable(true);
  172. region.remap();
  173. for (size_t i = 0; i < region.page_count(); i++) {
  174. auto page = region.physical_page(i);
  175. auto src_buffer = [&]() -> ErrorOr<UserOrKernelBuffer> {
  176. if (page)
  177. return UserOrKernelBuffer::for_user_buffer(reinterpret_cast<uint8_t*>((region.vaddr().as_ptr() + (i * PAGE_SIZE))), PAGE_SIZE);
  178. // If the current page is not backed by a physical page, we zero it in the coredump file.
  179. return UserOrKernelBuffer::for_kernel_buffer(zero_buffer);
  180. }();
  181. TRY(m_description->write(src_buffer.value(), PAGE_SIZE));
  182. }
  183. }
  184. return {};
  185. }
  186. ErrorOr<void> Coredump::write_notes_segment(ReadonlyBytes notes_segment)
  187. {
  188. TRY(m_description->write(UserOrKernelBuffer::for_kernel_buffer(const_cast<u8*>(notes_segment.data())), notes_segment.size()));
  189. return {};
  190. }
  191. ErrorOr<void> Coredump::create_notes_process_data(auto& builder) const
  192. {
  193. ELF::Core::ProcessInfo info {};
  194. info.header.type = ELF::Core::NotesEntryHeader::Type::ProcessInfo;
  195. TRY(builder.append_bytes(ReadonlyBytes { (void*)&info, sizeof(info) }));
  196. {
  197. auto process_obj = TRY(JsonObjectSerializer<>::try_create(builder));
  198. TRY(process_obj.add("pid"sv, m_process->pid().value()));
  199. TRY(process_obj.add("termination_signal"sv, m_process->termination_signal()));
  200. TRY(process_obj.add("executable_path"sv, m_process->executable() ? TRY(m_process->executable()->try_serialize_absolute_path())->view() : ""sv));
  201. {
  202. auto arguments_array = TRY(process_obj.add_array("arguments"sv));
  203. for (auto const& argument : m_process->arguments())
  204. TRY(arguments_array.add(argument.view()));
  205. TRY(arguments_array.finish());
  206. }
  207. {
  208. auto environment_array = TRY(process_obj.add_array("environment"sv));
  209. for (auto const& variable : m_process->environment())
  210. TRY(environment_array.add(variable.view()));
  211. TRY(environment_array.finish());
  212. }
  213. TRY(process_obj.finish());
  214. }
  215. TRY(builder.append('\0'));
  216. return {};
  217. }
  218. ErrorOr<void> Coredump::create_notes_threads_data(auto& builder) const
  219. {
  220. for (auto const& thread : m_process->threads_for_coredump({})) {
  221. ELF::Core::ThreadInfo info {};
  222. info.header.type = ELF::Core::NotesEntryHeader::Type::ThreadInfo;
  223. info.tid = thread.tid().value();
  224. if (thread.current_trap())
  225. copy_kernel_registers_into_ptrace_registers(info.regs, thread.get_register_dump_from_stack());
  226. TRY(builder.append_bytes(ReadonlyBytes { &info, sizeof(info) }));
  227. }
  228. return {};
  229. }
  230. ErrorOr<void> Coredump::create_notes_regions_data(auto& builder) const
  231. {
  232. size_t region_index = 0;
  233. for (auto const& region : m_process->address_space().regions()) {
  234. #if !INCLUDE_USERSPACE_HEAP_MEMORY_IN_COREDUMPS
  235. if (looks_like_userspace_heap_region(region))
  236. continue;
  237. #endif
  238. if (region.access() == Memory::Region::Access::None)
  239. continue;
  240. ELF::Core::MemoryRegionInfo info {};
  241. info.header.type = ELF::Core::NotesEntryHeader::Type::MemoryRegionInfo;
  242. info.region_start = region.vaddr().get();
  243. info.region_end = region.vaddr().offset(region.size()).get();
  244. info.program_header_index = region_index++;
  245. TRY(builder.append_bytes(ReadonlyBytes { (void*)&info, sizeof(info) }));
  246. // NOTE: The region name *is* null-terminated, so the following is ok:
  247. auto name = region.name();
  248. if (name.is_empty())
  249. TRY(builder.append('\0'));
  250. else
  251. TRY(builder.append(name.characters_without_null_termination(), name.length() + 1));
  252. }
  253. return {};
  254. }
  255. ErrorOr<void> Coredump::create_notes_metadata_data(auto& builder) const
  256. {
  257. ELF::Core::Metadata metadata {};
  258. metadata.header.type = ELF::Core::NotesEntryHeader::Type::Metadata;
  259. TRY(builder.append_bytes(ReadonlyBytes { (void*)&metadata, sizeof(metadata) }));
  260. {
  261. auto metadata_obj = TRY(JsonObjectSerializer<>::try_create(builder));
  262. TRY(m_process->for_each_coredump_property([&](auto& key, auto& value) -> ErrorOr<void> {
  263. TRY(metadata_obj.add(key.view(), value.view()));
  264. return {};
  265. }));
  266. TRY(metadata_obj.finish());
  267. }
  268. TRY(builder.append('\0'));
  269. return {};
  270. }
  271. ErrorOr<void> Coredump::create_notes_segment_data(auto& builder) const
  272. {
  273. TRY(create_notes_process_data(builder));
  274. TRY(create_notes_threads_data(builder));
  275. TRY(create_notes_regions_data(builder));
  276. TRY(create_notes_metadata_data(builder));
  277. ELF::Core::NotesEntryHeader null_entry {};
  278. null_entry.type = ELF::Core::NotesEntryHeader::Type::Null;
  279. TRY(builder.append(ReadonlyBytes { &null_entry, sizeof(null_entry) }));
  280. return {};
  281. }
  282. ErrorOr<void> Coredump::write()
  283. {
  284. SpinlockLocker lock(m_process->address_space().get_lock());
  285. ScopedAddressSpaceSwitcher switcher(m_process);
  286. auto builder = TRY(KBufferBuilder::try_create());
  287. TRY(create_notes_segment_data(builder));
  288. TRY(write_elf_header());
  289. TRY(write_program_headers(builder.bytes().size()));
  290. TRY(write_regions());
  291. TRY(write_notes_segment(builder.bytes()));
  292. return m_description->chmod(0600); // Make coredump file read/writable
  293. }
  294. }