Coredump.cpp 14 KB

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