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