CoreDump.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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 <mail@linusgroh.de>
  5. * All rights reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. *
  10. * 1. Redistributions of source code must retain the above copyright notice, this
  11. * list of conditions and the following disclaimer.
  12. *
  13. * 2. Redistributions in binary form must reproduce the above copyright notice,
  14. * this list of conditions and the following disclaimer in the documentation
  15. * and/or other materials provided with the distribution.
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  18. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  19. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  20. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  21. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  22. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  23. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  24. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  25. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  26. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. */
  28. #include <AK/ByteBuffer.h>
  29. #include <AK/JsonArray.h>
  30. #include <AK/JsonObject.h>
  31. #include <Kernel/CoreDump.h>
  32. #include <Kernel/FileSystem/Custody.h>
  33. #include <Kernel/FileSystem/FileDescription.h>
  34. #include <Kernel/FileSystem/VirtualFileSystem.h>
  35. #include <Kernel/Process.h>
  36. #include <Kernel/RTC.h>
  37. #include <Kernel/SpinLock.h>
  38. #include <Kernel/VM/ProcessPagingScope.h>
  39. #include <LibELF/CoreDump.h>
  40. #include <LibELF/exec_elf.h>
  41. namespace Kernel {
  42. OwnPtr<CoreDump> CoreDump::create(NonnullRefPtr<Process> process, const String& output_path)
  43. {
  44. if (!process->is_dumpable()) {
  45. dbgln("Refusing to generate CoreDump for non-dumpable process {}", process->pid().value());
  46. return {};
  47. }
  48. auto fd = create_target_file(process, output_path);
  49. if (!fd)
  50. return {};
  51. return adopt_own(*new CoreDump(move(process), fd.release_nonnull()));
  52. }
  53. CoreDump::CoreDump(NonnullRefPtr<Process> process, NonnullRefPtr<FileDescription>&& fd)
  54. : m_process(move(process))
  55. , m_fd(move(fd))
  56. , m_num_program_headers(m_process->space().region_count() + 1) // +1 for NOTE segment
  57. {
  58. }
  59. CoreDump::~CoreDump()
  60. {
  61. }
  62. RefPtr<FileDescription> CoreDump::create_target_file(const Process& process, const String& output_path)
  63. {
  64. LexicalPath lexical_path(output_path);
  65. const auto& output_directory = lexical_path.dirname();
  66. auto dump_directory = VFS::the().open_directory(output_directory, VFS::the().root_custody());
  67. if (dump_directory.is_error()) {
  68. dbgln("Can't find directory '{}' for core dump", output_directory);
  69. return nullptr;
  70. }
  71. auto dump_directory_metadata = dump_directory.value()->inode().metadata();
  72. if (dump_directory_metadata.uid != 0 || dump_directory_metadata.gid != 0 || dump_directory_metadata.mode != 040755) {
  73. dbgln("Refusing to put core dump in sketchy directory '{}'", output_directory);
  74. return nullptr;
  75. }
  76. auto fd_or_error = VFS::the().open(
  77. lexical_path.basename(),
  78. O_CREAT | O_WRONLY | O_EXCL,
  79. S_IFREG, // We will enable reading from userspace when we finish generating the coredump file
  80. *dump_directory.value(),
  81. UidAndGid { process.uid(), process.gid() });
  82. if (fd_or_error.is_error()) {
  83. dbgln("Failed to open core dump '{}' for writing", output_path);
  84. return nullptr;
  85. }
  86. return fd_or_error.value();
  87. }
  88. KResult CoreDump::write_elf_header()
  89. {
  90. Elf32_Ehdr elf_file_header;
  91. elf_file_header.e_ident[EI_MAG0] = 0x7f;
  92. elf_file_header.e_ident[EI_MAG1] = 'E';
  93. elf_file_header.e_ident[EI_MAG2] = 'L';
  94. elf_file_header.e_ident[EI_MAG3] = 'F';
  95. elf_file_header.e_ident[EI_CLASS] = ELFCLASS32;
  96. elf_file_header.e_ident[EI_DATA] = ELFDATA2LSB;
  97. elf_file_header.e_ident[EI_VERSION] = EV_CURRENT;
  98. elf_file_header.e_ident[EI_OSABI] = 0; // ELFOSABI_NONE
  99. elf_file_header.e_ident[EI_ABIVERSION] = 0;
  100. elf_file_header.e_ident[EI_PAD + 1] = 0;
  101. elf_file_header.e_ident[EI_PAD + 2] = 0;
  102. elf_file_header.e_ident[EI_PAD + 3] = 0;
  103. elf_file_header.e_ident[EI_PAD + 4] = 0;
  104. elf_file_header.e_ident[EI_PAD + 5] = 0;
  105. elf_file_header.e_ident[EI_PAD + 6] = 0;
  106. elf_file_header.e_type = ET_CORE;
  107. elf_file_header.e_machine = EM_386;
  108. elf_file_header.e_version = 1;
  109. elf_file_header.e_entry = 0;
  110. elf_file_header.e_phoff = sizeof(Elf32_Ehdr);
  111. elf_file_header.e_shoff = 0;
  112. elf_file_header.e_flags = 0;
  113. elf_file_header.e_ehsize = sizeof(Elf32_Ehdr);
  114. elf_file_header.e_shentsize = sizeof(Elf32_Shdr);
  115. elf_file_header.e_phentsize = sizeof(Elf32_Phdr);
  116. elf_file_header.e_phnum = m_num_program_headers;
  117. elf_file_header.e_shnum = 0;
  118. elf_file_header.e_shstrndx = SHN_UNDEF;
  119. auto result = m_fd->write(UserOrKernelBuffer::for_kernel_buffer(reinterpret_cast<uint8_t*>(&elf_file_header)), sizeof(Elf32_Ehdr));
  120. if (result.is_error())
  121. return result.error();
  122. return KSuccess;
  123. }
  124. KResult CoreDump::write_program_headers(size_t notes_size)
  125. {
  126. size_t offset = sizeof(Elf32_Ehdr) + m_num_program_headers * sizeof(Elf32_Phdr);
  127. for (auto& region : m_process->space().regions()) {
  128. Elf32_Phdr phdr {};
  129. phdr.p_type = PT_LOAD;
  130. phdr.p_offset = offset;
  131. phdr.p_vaddr = region.vaddr().get();
  132. phdr.p_paddr = 0;
  133. phdr.p_filesz = region.page_count() * PAGE_SIZE;
  134. phdr.p_memsz = region.page_count() * PAGE_SIZE;
  135. phdr.p_align = 0;
  136. phdr.p_flags = region.is_readable() ? PF_R : 0;
  137. if (region.is_writable())
  138. phdr.p_flags |= PF_W;
  139. if (region.is_executable())
  140. phdr.p_flags |= PF_X;
  141. offset += phdr.p_filesz;
  142. [[maybe_unused]] auto rc = m_fd->write(UserOrKernelBuffer::for_kernel_buffer(reinterpret_cast<uint8_t*>(&phdr)), sizeof(Elf32_Phdr));
  143. }
  144. Elf32_Phdr notes_pheader {};
  145. notes_pheader.p_type = PT_NOTE;
  146. notes_pheader.p_offset = offset;
  147. notes_pheader.p_vaddr = 0;
  148. notes_pheader.p_paddr = 0;
  149. notes_pheader.p_filesz = notes_size;
  150. notes_pheader.p_memsz = notes_size;
  151. notes_pheader.p_align = 0;
  152. notes_pheader.p_flags = 0;
  153. auto result = m_fd->write(UserOrKernelBuffer::for_kernel_buffer(reinterpret_cast<uint8_t*>(&notes_pheader)), sizeof(Elf32_Phdr));
  154. if (result.is_error())
  155. return result.error();
  156. return KSuccess;
  157. }
  158. KResult CoreDump::write_regions()
  159. {
  160. for (auto& region : m_process->space().regions()) {
  161. if (region.is_kernel())
  162. continue;
  163. region.set_readable(true);
  164. region.remap();
  165. for (size_t i = 0; i < region.page_count(); i++) {
  166. auto* page = region.physical_page(i);
  167. uint8_t zero_buffer[PAGE_SIZE] = {};
  168. Optional<UserOrKernelBuffer> src_buffer;
  169. if (page) {
  170. src_buffer = UserOrKernelBuffer::for_user_buffer(reinterpret_cast<uint8_t*>((region.vaddr().as_ptr() + (i * PAGE_SIZE))), PAGE_SIZE);
  171. } else {
  172. // If the current page is not backed by a physical page, we zero it in the coredump file.
  173. // TODO: Do we want to include the contents of pages that have not been faulted-in in the coredump?
  174. // (A page may not be backed by a physical page because it has never been faulted in when the process ran).
  175. src_buffer = UserOrKernelBuffer::for_kernel_buffer(zero_buffer);
  176. }
  177. auto result = m_fd->write(src_buffer.value(), PAGE_SIZE);
  178. if (result.is_error())
  179. return result.error();
  180. }
  181. }
  182. return KSuccess;
  183. }
  184. KResult CoreDump::write_notes_segment(ByteBuffer& notes_segment)
  185. {
  186. auto result = m_fd->write(UserOrKernelBuffer::for_kernel_buffer(notes_segment.data()), notes_segment.size());
  187. if (result.is_error())
  188. return result.error();
  189. return KSuccess;
  190. }
  191. ByteBuffer CoreDump::create_notes_process_data() const
  192. {
  193. ByteBuffer process_data;
  194. ELF::Core::ProcessInfo info {};
  195. info.header.type = ELF::Core::NotesEntryHeader::Type::ProcessInfo;
  196. process_data.append((void*)&info, sizeof(info));
  197. JsonObject process_obj;
  198. process_obj.set("pid", m_process->pid().value());
  199. process_obj.set("termination_signal", m_process->termination_signal());
  200. process_obj.set("executable_path", m_process->executable() ? m_process->executable()->absolute_path() : String::empty());
  201. process_obj.set("arguments", JsonArray(m_process->arguments()));
  202. process_obj.set("environment", JsonArray(m_process->environment()));
  203. auto json_data = process_obj.to_string();
  204. process_data.append(json_data.characters(), json_data.length() + 1);
  205. return process_data;
  206. }
  207. ByteBuffer CoreDump::create_notes_threads_data() const
  208. {
  209. ByteBuffer threads_data;
  210. for (auto& thread : m_process->threads_for_coredump({})) {
  211. ByteBuffer entry_buff;
  212. ELF::Core::ThreadInfo info {};
  213. info.header.type = ELF::Core::NotesEntryHeader::Type::ThreadInfo;
  214. info.tid = thread.tid().value();
  215. copy_kernel_registers_into_ptrace_registers(info.regs, thread.get_register_dump_from_stack());
  216. entry_buff.append((void*)&info, sizeof(info));
  217. threads_data += entry_buff;
  218. }
  219. return threads_data;
  220. }
  221. ByteBuffer CoreDump::create_notes_regions_data() const
  222. {
  223. ByteBuffer regions_data;
  224. for (size_t region_index = 0; region_index < m_process->space().region_count(); ++region_index) {
  225. ByteBuffer memory_region_info_buffer;
  226. ELF::Core::MemoryRegionInfo info {};
  227. info.header.type = ELF::Core::NotesEntryHeader::Type::MemoryRegionInfo;
  228. auto& region = m_process->space().regions()[region_index];
  229. info.region_start = region.vaddr().get();
  230. info.region_end = region.vaddr().offset(region.size()).get();
  231. info.program_header_index = region_index;
  232. memory_region_info_buffer.append((void*)&info, sizeof(info));
  233. auto name = region.name();
  234. if (name.is_null())
  235. name = String::empty();
  236. memory_region_info_buffer.append(name.characters(), name.length() + 1);
  237. regions_data += memory_region_info_buffer;
  238. }
  239. return regions_data;
  240. }
  241. ByteBuffer CoreDump::create_notes_metadata_data() const
  242. {
  243. ByteBuffer metadata_data;
  244. ELF::Core::Metadata metadata {};
  245. metadata.header.type = ELF::Core::NotesEntryHeader::Type::Metadata;
  246. metadata_data.append((void*)&metadata, sizeof(metadata));
  247. JsonObject metadata_obj;
  248. for (auto& it : m_process->coredump_metadata())
  249. metadata_obj.set(it.key, it.value);
  250. auto json_data = metadata_obj.to_string();
  251. metadata_data.append(json_data.characters(), json_data.length() + 1);
  252. return metadata_data;
  253. }
  254. ByteBuffer CoreDump::create_notes_segment_data() const
  255. {
  256. ByteBuffer notes_buffer;
  257. notes_buffer += create_notes_process_data();
  258. notes_buffer += create_notes_threads_data();
  259. notes_buffer += create_notes_regions_data();
  260. notes_buffer += create_notes_metadata_data();
  261. ELF::Core::NotesEntryHeader null_entry {};
  262. null_entry.type = ELF::Core::NotesEntryHeader::Type::Null;
  263. notes_buffer.append(&null_entry, sizeof(null_entry));
  264. return notes_buffer;
  265. }
  266. KResult CoreDump::write()
  267. {
  268. ScopedSpinLock lock(m_process->space().get_lock());
  269. ProcessPagingScope scope(m_process);
  270. ByteBuffer notes_segment = create_notes_segment_data();
  271. auto result = write_elf_header();
  272. if (result.is_error())
  273. return result;
  274. result = write_program_headers(notes_segment.size());
  275. if (result.is_error())
  276. return result;
  277. result = write_regions();
  278. if (result.is_error())
  279. return result;
  280. result = write_notes_segment(notes_segment);
  281. if (result.is_error())
  282. return result;
  283. return m_fd->chmod(0400); // Make coredump file readable
  284. }
  285. }