Coredump.cpp 14 KB

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