CoreDump.cpp 11 KB

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