Coredump.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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(NonnullRefPtr<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(NonnullRefPtr<Process> process, NonnullRefPtr<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<NonnullRefPtr<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(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. return TRY(VirtualFileSystem::the().open(
  63. KLexicalPath::basename(output_path),
  64. O_CREAT | O_WRONLY | O_EXCL,
  65. S_IFREG, // We will enable reading from userspace when we finish generating the coredump file
  66. *dump_directory,
  67. UidAndGid { process.uid(), process.gid() }));
  68. }
  69. ErrorOr<void> Coredump::write_elf_header()
  70. {
  71. ElfW(Ehdr) elf_file_header;
  72. elf_file_header.e_ident[EI_MAG0] = 0x7f;
  73. elf_file_header.e_ident[EI_MAG1] = 'E';
  74. elf_file_header.e_ident[EI_MAG2] = 'L';
  75. elf_file_header.e_ident[EI_MAG3] = 'F';
  76. #if ARCH(I386)
  77. elf_file_header.e_ident[EI_CLASS] = ELFCLASS32;
  78. #else
  79. elf_file_header.e_ident[EI_CLASS] = ELFCLASS64;
  80. #endif
  81. elf_file_header.e_ident[EI_DATA] = ELFDATA2LSB;
  82. elf_file_header.e_ident[EI_VERSION] = EV_CURRENT;
  83. elf_file_header.e_ident[EI_OSABI] = 0; // ELFOSABI_NONE
  84. elf_file_header.e_ident[EI_ABIVERSION] = 0;
  85. elf_file_header.e_ident[EI_PAD + 1] = 0;
  86. elf_file_header.e_ident[EI_PAD + 2] = 0;
  87. elf_file_header.e_ident[EI_PAD + 3] = 0;
  88. elf_file_header.e_ident[EI_PAD + 4] = 0;
  89. elf_file_header.e_ident[EI_PAD + 5] = 0;
  90. elf_file_header.e_ident[EI_PAD + 6] = 0;
  91. elf_file_header.e_type = ET_CORE;
  92. #if ARCH(I386)
  93. elf_file_header.e_machine = EM_386;
  94. #else
  95. elf_file_header.e_machine = EM_X86_64;
  96. #endif
  97. elf_file_header.e_version = 1;
  98. elf_file_header.e_entry = 0;
  99. elf_file_header.e_phoff = sizeof(ElfW(Ehdr));
  100. elf_file_header.e_shoff = 0;
  101. elf_file_header.e_flags = 0;
  102. elf_file_header.e_ehsize = sizeof(ElfW(Ehdr));
  103. elf_file_header.e_shentsize = sizeof(ElfW(Shdr));
  104. elf_file_header.e_phentsize = sizeof(ElfW(Phdr));
  105. elf_file_header.e_phnum = m_num_program_headers;
  106. elf_file_header.e_shnum = 0;
  107. elf_file_header.e_shstrndx = SHN_UNDEF;
  108. TRY(m_description->write(UserOrKernelBuffer::for_kernel_buffer(reinterpret_cast<uint8_t*>(&elf_file_header)), sizeof(ElfW(Ehdr))));
  109. return {};
  110. }
  111. ErrorOr<void> Coredump::write_program_headers(size_t notes_size)
  112. {
  113. size_t offset = sizeof(ElfW(Ehdr)) + m_num_program_headers * sizeof(ElfW(Phdr));
  114. for (auto& region : m_process->address_space().regions()) {
  115. #if !INCLUDE_USERSPACE_HEAP_MEMORY_IN_COREDUMPS
  116. if (looks_like_userspace_heap_region(*region))
  117. continue;
  118. #endif
  119. if (region->access() == Memory::Region::Access::None)
  120. continue;
  121. ElfW(Phdr) phdr {};
  122. phdr.p_type = PT_LOAD;
  123. phdr.p_offset = offset;
  124. phdr.p_vaddr = region->vaddr().get();
  125. phdr.p_paddr = 0;
  126. phdr.p_filesz = region->page_count() * PAGE_SIZE;
  127. phdr.p_memsz = region->page_count() * PAGE_SIZE;
  128. phdr.p_align = 0;
  129. phdr.p_flags = region->is_readable() ? PF_R : 0;
  130. if (region->is_writable())
  131. phdr.p_flags |= PF_W;
  132. if (region->is_executable())
  133. phdr.p_flags |= PF_X;
  134. offset += phdr.p_filesz;
  135. [[maybe_unused]] auto rc = m_description->write(UserOrKernelBuffer::for_kernel_buffer(reinterpret_cast<uint8_t*>(&phdr)), sizeof(ElfW(Phdr)));
  136. }
  137. ElfW(Phdr) notes_pheader {};
  138. notes_pheader.p_type = PT_NOTE;
  139. notes_pheader.p_offset = offset;
  140. notes_pheader.p_vaddr = 0;
  141. notes_pheader.p_paddr = 0;
  142. notes_pheader.p_filesz = notes_size;
  143. notes_pheader.p_memsz = notes_size;
  144. notes_pheader.p_align = 0;
  145. notes_pheader.p_flags = 0;
  146. TRY(m_description->write(UserOrKernelBuffer::for_kernel_buffer(reinterpret_cast<uint8_t*>(&notes_pheader)), sizeof(ElfW(Phdr))));
  147. return {};
  148. }
  149. ErrorOr<void> Coredump::write_regions()
  150. {
  151. u8 zero_buffer[PAGE_SIZE] = {};
  152. for (auto& region : m_process->address_space().regions()) {
  153. VERIFY(!region->is_kernel());
  154. #if !INCLUDE_USERSPACE_HEAP_MEMORY_IN_COREDUMPS
  155. if (looks_like_userspace_heap_region(*region))
  156. continue;
  157. #endif
  158. if (region->access() == Memory::Region::Access::None)
  159. continue;
  160. region->set_readable(true);
  161. region->remap();
  162. for (size_t i = 0; i < region->page_count(); i++) {
  163. auto const* page = region->physical_page(i);
  164. auto src_buffer = [&]() -> ErrorOr<UserOrKernelBuffer> {
  165. if (page)
  166. return UserOrKernelBuffer::for_user_buffer(reinterpret_cast<uint8_t*>((region->vaddr().as_ptr() + (i * PAGE_SIZE))), PAGE_SIZE);
  167. // If the current page is not backed by a physical page, we zero it in the coredump file.
  168. return UserOrKernelBuffer::for_kernel_buffer(zero_buffer);
  169. }();
  170. TRY(m_description->write(src_buffer.value(), PAGE_SIZE));
  171. }
  172. }
  173. return {};
  174. }
  175. ErrorOr<void> Coredump::write_notes_segment(ReadonlyBytes notes_segment)
  176. {
  177. TRY(m_description->write(UserOrKernelBuffer::for_kernel_buffer(const_cast<u8*>(notes_segment.data())), notes_segment.size()));
  178. return {};
  179. }
  180. ErrorOr<void> Coredump::create_notes_process_data(auto& builder) const
  181. {
  182. ELF::Core::ProcessInfo info {};
  183. info.header.type = ELF::Core::NotesEntryHeader::Type::ProcessInfo;
  184. TRY(builder.append_bytes(ReadonlyBytes { (void*)&info, sizeof(info) }));
  185. {
  186. JsonObjectSerializer process_obj { builder };
  187. process_obj.add("pid"sv, m_process->pid().value());
  188. process_obj.add("termination_signal"sv, m_process->termination_signal());
  189. process_obj.add("executable_path"sv, m_process->executable() ? m_process->executable()->absolute_path() : String::empty());
  190. {
  191. auto arguments_array = process_obj.add_array("arguments"sv);
  192. for (auto const& argument : m_process->arguments())
  193. arguments_array.add(argument.view());
  194. }
  195. {
  196. auto environment_array = process_obj.add_array("environment"sv);
  197. for (auto const& variable : m_process->environment())
  198. environment_array.add(variable.view());
  199. }
  200. }
  201. TRY(builder.append('\0'));
  202. return {};
  203. }
  204. ErrorOr<void> Coredump::create_notes_threads_data(auto& builder) const
  205. {
  206. for (auto const& thread : m_process->threads_for_coredump({})) {
  207. ELF::Core::ThreadInfo info {};
  208. info.header.type = ELF::Core::NotesEntryHeader::Type::ThreadInfo;
  209. info.tid = thread.tid().value();
  210. if (thread.current_trap())
  211. copy_kernel_registers_into_ptrace_registers(info.regs, thread.get_register_dump_from_stack());
  212. TRY(builder.append_bytes(ReadonlyBytes { &info, sizeof(info) }));
  213. }
  214. return {};
  215. }
  216. ErrorOr<void> Coredump::create_notes_regions_data(auto& builder) const
  217. {
  218. size_t region_index = 0;
  219. for (auto const& region : m_process->address_space().regions()) {
  220. #if !INCLUDE_USERSPACE_HEAP_MEMORY_IN_COREDUMPS
  221. if (looks_like_userspace_heap_region(*region))
  222. continue;
  223. #endif
  224. if (region->access() == Memory::Region::Access::None)
  225. continue;
  226. ELF::Core::MemoryRegionInfo info {};
  227. info.header.type = ELF::Core::NotesEntryHeader::Type::MemoryRegionInfo;
  228. info.region_start = region->vaddr().get();
  229. info.region_end = region->vaddr().offset(region->size()).get();
  230. info.program_header_index = region_index++;
  231. TRY(builder.append_bytes(ReadonlyBytes { (void*)&info, sizeof(info) }));
  232. // NOTE: The region name *is* null-terminated, so the following is ok:
  233. auto name = region->name();
  234. if (name.is_empty())
  235. TRY(builder.append('\0'));
  236. else
  237. TRY(builder.append(name.characters_without_null_termination(), name.length() + 1));
  238. }
  239. return {};
  240. }
  241. ErrorOr<void> Coredump::create_notes_metadata_data(auto& builder) const
  242. {
  243. ELF::Core::Metadata metadata {};
  244. metadata.header.type = ELF::Core::NotesEntryHeader::Type::Metadata;
  245. TRY(builder.append_bytes(ReadonlyBytes { (void*)&metadata, sizeof(metadata) }));
  246. {
  247. JsonObjectSerializer metadata_obj { builder };
  248. m_process->for_each_coredump_property([&](auto& key, auto& value) {
  249. metadata_obj.add(key.view(), value.view());
  250. });
  251. }
  252. TRY(builder.append('\0'));
  253. return {};
  254. }
  255. ErrorOr<void> Coredump::create_notes_segment_data(auto& builder) const
  256. {
  257. TRY(create_notes_process_data(builder));
  258. TRY(create_notes_threads_data(builder));
  259. TRY(create_notes_regions_data(builder));
  260. TRY(create_notes_metadata_data(builder));
  261. ELF::Core::NotesEntryHeader null_entry {};
  262. null_entry.type = ELF::Core::NotesEntryHeader::Type::Null;
  263. TRY(builder.append(ReadonlyBytes { &null_entry, sizeof(null_entry) }));
  264. return {};
  265. }
  266. ErrorOr<void> Coredump::write()
  267. {
  268. SpinlockLocker lock(m_process->address_space().get_lock());
  269. ScopedAddressSpaceSwitcher switcher(m_process);
  270. auto builder = TRY(KBufferBuilder::try_create());
  271. TRY(create_notes_segment_data(builder));
  272. TRY(write_elf_header());
  273. TRY(write_program_headers(builder.bytes().size()));
  274. TRY(write_regions());
  275. TRY(write_notes_segment(builder.bytes()));
  276. return m_description->chmod(0600); // Make coredump file read/writable
  277. }
  278. }