Process.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Singleton.h>
  7. #include <AK/StdLibExtras.h>
  8. #include <AK/Time.h>
  9. #include <AK/Types.h>
  10. #include <Kernel/API/Syscall.h>
  11. #include <Kernel/Arch/x86/InterruptDisabler.h>
  12. #include <Kernel/Coredump.h>
  13. #include <Kernel/Debug.h>
  14. #include <Kernel/Devices/DeviceManagement.h>
  15. #ifdef ENABLE_KERNEL_COVERAGE_COLLECTION
  16. # include <Kernel/Devices/KCOVDevice.h>
  17. #endif
  18. #include <Kernel/API/POSIX/errno.h>
  19. #include <Kernel/Devices/NullDevice.h>
  20. #include <Kernel/FileSystem/Custody.h>
  21. #include <Kernel/FileSystem/OpenFileDescription.h>
  22. #include <Kernel/FileSystem/VirtualFileSystem.h>
  23. #include <Kernel/KBufferBuilder.h>
  24. #include <Kernel/KSyms.h>
  25. #include <Kernel/Memory/AnonymousVMObject.h>
  26. #include <Kernel/Memory/PageDirectory.h>
  27. #include <Kernel/Memory/SharedInodeVMObject.h>
  28. #include <Kernel/PerformanceEventBuffer.h>
  29. #include <Kernel/PerformanceManager.h>
  30. #include <Kernel/Process.h>
  31. #include <Kernel/Sections.h>
  32. #include <Kernel/StdLib.h>
  33. #include <Kernel/TTY/TTY.h>
  34. #include <Kernel/Thread.h>
  35. #include <Kernel/ThreadTracer.h>
  36. #include <LibC/limits.h>
  37. namespace Kernel {
  38. static void create_signal_trampoline();
  39. RecursiveSpinlock g_profiling_lock;
  40. static Atomic<pid_t> next_pid;
  41. static Singleton<SpinlockProtected<Process::List>> s_all_instances;
  42. READONLY_AFTER_INIT Memory::Region* g_signal_trampoline_region;
  43. static Singleton<MutexProtected<String>> s_hostname;
  44. MutexProtected<String>& hostname()
  45. {
  46. return *s_hostname;
  47. }
  48. SpinlockProtected<Process::List>& Process::all_instances()
  49. {
  50. return *s_all_instances;
  51. }
  52. ProcessID Process::allocate_pid()
  53. {
  54. // Overflow is UB, and negative PIDs wreck havoc.
  55. // TODO: Handle PID overflow
  56. // For example: Use an Atomic<u32>, mask the most significant bit,
  57. // retry if PID is already taken as a PID, taken as a TID,
  58. // takes as a PGID, taken as a SID, or zero.
  59. return next_pid.fetch_add(1, AK::MemoryOrder::memory_order_acq_rel);
  60. }
  61. UNMAP_AFTER_INIT void Process::initialize()
  62. {
  63. next_pid.store(0, AK::MemoryOrder::memory_order_release);
  64. // Note: This is called before scheduling is initialized, and before APs are booted.
  65. // So we can "safely" bypass the lock here.
  66. reinterpret_cast<String&>(hostname()) = "courage";
  67. create_signal_trampoline();
  68. }
  69. bool Process::in_group(GroupID gid) const
  70. {
  71. return this->gid() == gid || extra_gids().contains_slow(gid);
  72. }
  73. void Process::kill_threads_except_self()
  74. {
  75. InterruptDisabler disabler;
  76. if (thread_count() <= 1)
  77. return;
  78. auto* current_thread = Thread::current();
  79. for_each_thread([&](Thread& thread) {
  80. if (&thread == current_thread)
  81. return;
  82. if (auto state = thread.state(); state == Thread::State::Dead
  83. || state == Thread::State::Dying)
  84. return;
  85. // We need to detach this thread in case it hasn't been joined
  86. thread.detach();
  87. thread.set_should_die();
  88. });
  89. u32 dropped_lock_count = 0;
  90. if (big_lock().force_unlock_if_locked(dropped_lock_count) != LockMode::Unlocked)
  91. dbgln("Process {} big lock had {} locks", *this, dropped_lock_count);
  92. }
  93. void Process::kill_all_threads()
  94. {
  95. for_each_thread([&](Thread& thread) {
  96. // We need to detach this thread in case it hasn't been joined
  97. thread.detach();
  98. thread.set_should_die();
  99. });
  100. }
  101. void Process::register_new(Process& process)
  102. {
  103. // Note: this is essentially the same like process->ref()
  104. RefPtr<Process> new_process = process;
  105. all_instances().with([&](auto& list) {
  106. list.prepend(process);
  107. });
  108. }
  109. ErrorOr<NonnullRefPtr<Process>> Process::try_create_user_process(RefPtr<Thread>& first_thread, StringView path, UserID uid, GroupID gid, NonnullOwnPtrVector<KString> arguments, NonnullOwnPtrVector<KString> environment, TTY* tty)
  110. {
  111. auto parts = path.split_view('/');
  112. if (arguments.is_empty()) {
  113. auto last_part = TRY(KString::try_create(parts.last()));
  114. TRY(arguments.try_append(move(last_part)));
  115. }
  116. auto path_string = TRY(KString::try_create(path));
  117. auto name = TRY(KString::try_create(parts.last()));
  118. auto process = TRY(Process::try_create(first_thread, move(name), uid, gid, ProcessID(0), false, VirtualFileSystem::the().root_custody(), nullptr, tty));
  119. TRY(process->m_fds.try_resize(Process::OpenFileDescriptions::max_open()));
  120. auto& device_to_use_as_tty = tty ? (CharacterDevice&)*tty : DeviceManagement::the().null_device();
  121. auto description = TRY(device_to_use_as_tty.open(O_RDWR));
  122. auto setup_description = [&process, &description](int fd) {
  123. process->m_fds.m_fds_metadatas[fd].allocate();
  124. process->m_fds[fd].set(*description);
  125. };
  126. setup_description(0);
  127. setup_description(1);
  128. setup_description(2);
  129. if (auto result = process->exec(move(path_string), move(arguments), move(environment)); result.is_error()) {
  130. dbgln("Failed to exec {}: {}", path, result.error());
  131. first_thread = nullptr;
  132. return result.release_error();
  133. }
  134. register_new(*process);
  135. // NOTE: All user processes have a leaked ref on them. It's balanced by Thread::WaitBlockerSet::finalize().
  136. process->ref();
  137. return process;
  138. }
  139. RefPtr<Process> Process::create_kernel_process(RefPtr<Thread>& first_thread, NonnullOwnPtr<KString> name, void (*entry)(void*), void* entry_data, u32 affinity, RegisterProcess do_register)
  140. {
  141. auto process_or_error = Process::try_create(first_thread, move(name), UserID(0), GroupID(0), ProcessID(0), true);
  142. if (process_or_error.is_error())
  143. return {};
  144. auto process = process_or_error.release_value();
  145. first_thread->regs().set_ip((FlatPtr)entry);
  146. #if ARCH(I386)
  147. first_thread->regs().esp = FlatPtr(entry_data); // entry function argument is expected to be in regs.esp
  148. #else
  149. first_thread->regs().rdi = FlatPtr(entry_data); // entry function argument is expected to be in regs.rdi
  150. #endif
  151. if (do_register == RegisterProcess::Yes)
  152. register_new(*process);
  153. SpinlockLocker lock(g_scheduler_lock);
  154. first_thread->set_affinity(affinity);
  155. first_thread->set_state(Thread::State::Runnable);
  156. return process;
  157. }
  158. void Process::protect_data()
  159. {
  160. m_protected_data_refs.unref([&]() {
  161. MM.set_page_writable_direct(VirtualAddress { &this->m_protected_values }, false);
  162. });
  163. }
  164. void Process::unprotect_data()
  165. {
  166. m_protected_data_refs.ref([&]() {
  167. MM.set_page_writable_direct(VirtualAddress { &this->m_protected_values }, true);
  168. });
  169. }
  170. ErrorOr<NonnullRefPtr<Process>> Process::try_create(RefPtr<Thread>& first_thread, NonnullOwnPtr<KString> name, UserID uid, GroupID gid, ProcessID ppid, bool is_kernel_process, RefPtr<Custody> cwd, RefPtr<Custody> executable, TTY* tty, Process* fork_parent)
  171. {
  172. auto space = TRY(Memory::AddressSpace::try_create(fork_parent ? &fork_parent->address_space() : nullptr));
  173. auto process = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) Process(move(name), uid, gid, ppid, is_kernel_process, move(cwd), move(executable), tty)));
  174. TRY(process->attach_resources(move(space), first_thread, fork_parent));
  175. return process;
  176. }
  177. Process::Process(NonnullOwnPtr<KString> name, UserID uid, GroupID gid, ProcessID ppid, bool is_kernel_process, RefPtr<Custody> cwd, RefPtr<Custody> executable, TTY* tty)
  178. : m_name(move(name))
  179. , m_is_kernel_process(is_kernel_process)
  180. , m_executable(move(executable))
  181. , m_cwd(move(cwd))
  182. , m_tty(tty)
  183. , m_wait_blocker_set(*this)
  184. {
  185. // Ensure that we protect the process data when exiting the constructor.
  186. ProtectedDataMutationScope scope { *this };
  187. m_protected_values.pid = allocate_pid();
  188. m_protected_values.ppid = ppid;
  189. m_protected_values.uid = uid;
  190. m_protected_values.gid = gid;
  191. m_protected_values.euid = uid;
  192. m_protected_values.egid = gid;
  193. m_protected_values.suid = uid;
  194. m_protected_values.sgid = gid;
  195. dbgln_if(PROCESS_DEBUG, "Created new process {}({})", m_name, this->pid().value());
  196. }
  197. ErrorOr<void> Process::attach_resources(NonnullOwnPtr<Memory::AddressSpace>&& preallocated_space, RefPtr<Thread>& first_thread, Process* fork_parent)
  198. {
  199. m_space = move(preallocated_space);
  200. auto create_first_thread = [&] {
  201. if (fork_parent) {
  202. // NOTE: fork() doesn't clone all threads; the thread that called fork() becomes the only thread in the new process.
  203. return Thread::current()->try_clone(*this);
  204. }
  205. // NOTE: This non-forked code path is only taken when the kernel creates a process "manually" (at boot.)
  206. return Thread::try_create(*this);
  207. };
  208. first_thread = TRY(create_first_thread());
  209. if (!fork_parent) {
  210. // FIXME: Figure out if this is really necessary.
  211. first_thread->detach();
  212. }
  213. m_procfs_traits = TRY(ProcessProcFSTraits::try_create({}, *this));
  214. return {};
  215. }
  216. Process::~Process()
  217. {
  218. unprotect_data();
  219. VERIFY(thread_count() == 0); // all threads should have been finalized
  220. VERIFY(!m_alarm_timer);
  221. PerformanceManager::add_process_exit_event(*this);
  222. }
  223. // Make sure the compiler doesn't "optimize away" this function:
  224. extern void signal_trampoline_dummy() __attribute__((used));
  225. void signal_trampoline_dummy()
  226. {
  227. #if ARCH(I386)
  228. // The trampoline preserves the current eax, pushes the signal code and
  229. // then calls the signal handler. We do this because, when interrupting a
  230. // blocking syscall, that syscall may return some special error code in eax;
  231. // This error code would likely be overwritten by the signal handler, so it's
  232. // necessary to preserve it here.
  233. asm(
  234. ".intel_syntax noprefix\n"
  235. ".globl asm_signal_trampoline\n"
  236. "asm_signal_trampoline:\n"
  237. "push ebp\n"
  238. "mov ebp, esp\n"
  239. "push eax\n" // we have to store eax 'cause it might be the return value from a syscall
  240. "sub esp, 4\n" // align the stack to 16 bytes
  241. "mov eax, [ebp+12]\n" // push the signal code
  242. "push eax\n"
  243. "call [ebp+8]\n" // call the signal handler
  244. "add esp, 8\n"
  245. "mov eax, %P0\n"
  246. "int 0x82\n" // sigreturn syscall
  247. ".globl asm_signal_trampoline_end\n"
  248. "asm_signal_trampoline_end:\n"
  249. ".att_syntax" ::"i"(Syscall::SC_sigreturn));
  250. #elif ARCH(X86_64)
  251. // The trampoline preserves the current rax, pushes the signal code and
  252. // then calls the signal handler. We do this because, when interrupting a
  253. // blocking syscall, that syscall may return some special error code in eax;
  254. // This error code would likely be overwritten by the signal handler, so it's
  255. // necessary to preserve it here.
  256. asm(
  257. ".intel_syntax noprefix\n"
  258. ".globl asm_signal_trampoline\n"
  259. "asm_signal_trampoline:\n"
  260. "push rbp\n"
  261. "mov rbp, rsp\n"
  262. "push rax\n" // we have to store rax 'cause it might be the return value from a syscall
  263. "sub rsp, 8\n" // align the stack to 16 bytes
  264. "mov rdi, [rbp+24]\n" // push the signal code
  265. "call [rbp+16]\n" // call the signal handler
  266. "add rsp, 8\n"
  267. "mov rax, %P0\n"
  268. "int 0x82\n" // sigreturn syscall
  269. ".globl asm_signal_trampoline_end\n"
  270. "asm_signal_trampoline_end:\n"
  271. ".att_syntax" ::"i"(Syscall::SC_sigreturn));
  272. #endif
  273. }
  274. extern "C" char const asm_signal_trampoline[];
  275. extern "C" char const asm_signal_trampoline_end[];
  276. void create_signal_trampoline()
  277. {
  278. // NOTE: We leak this region.
  279. g_signal_trampoline_region = MM.allocate_kernel_region(PAGE_SIZE, "Signal trampolines", Memory::Region::Access::ReadWrite).release_value().leak_ptr();
  280. g_signal_trampoline_region->set_syscall_region(true);
  281. size_t trampoline_size = asm_signal_trampoline_end - asm_signal_trampoline;
  282. u8* code_ptr = (u8*)g_signal_trampoline_region->vaddr().as_ptr();
  283. memcpy(code_ptr, asm_signal_trampoline, trampoline_size);
  284. g_signal_trampoline_region->set_writable(false);
  285. g_signal_trampoline_region->remap();
  286. }
  287. void Process::crash(int signal, FlatPtr ip, bool out_of_memory)
  288. {
  289. VERIFY(!is_dead());
  290. VERIFY(&Process::current() == this);
  291. if (out_of_memory) {
  292. dbgln("\033[31;1mOut of memory\033[m, killing: {}", *this);
  293. } else {
  294. if (ip >= kernel_load_base && g_kernel_symbols_available) {
  295. auto const* symbol = symbolicate_kernel_address(ip);
  296. dbgln("\033[31;1m{:p} {} +{}\033[0m\n", ip, (symbol ? symbol->name : "(k?)"), (symbol ? ip - symbol->address : 0));
  297. } else {
  298. dbgln("\033[31;1m{:p} (?)\033[0m\n", ip);
  299. }
  300. dump_backtrace();
  301. }
  302. {
  303. ProtectedDataMutationScope scope { *this };
  304. m_protected_values.termination_signal = signal;
  305. }
  306. set_should_generate_coredump(!out_of_memory);
  307. address_space().dump_regions();
  308. VERIFY(is_user_process());
  309. die();
  310. // We can not return from here, as there is nowhere
  311. // to unwind to, so die right away.
  312. Thread::current()->die_if_needed();
  313. VERIFY_NOT_REACHED();
  314. }
  315. RefPtr<Process> Process::from_pid(ProcessID pid)
  316. {
  317. return all_instances().with([&](const auto& list) -> RefPtr<Process> {
  318. for (auto const& process : list) {
  319. if (process.pid() == pid)
  320. return &process;
  321. }
  322. return {};
  323. });
  324. }
  325. const Process::OpenFileDescriptionAndFlags* Process::OpenFileDescriptions::get_if_valid(size_t i) const
  326. {
  327. SpinlockLocker lock(m_fds_lock);
  328. if (m_fds_metadatas.size() <= i)
  329. return nullptr;
  330. if (auto const& metadata = m_fds_metadatas[i]; metadata.is_valid())
  331. return &metadata;
  332. return nullptr;
  333. }
  334. Process::OpenFileDescriptionAndFlags* Process::OpenFileDescriptions::get_if_valid(size_t i)
  335. {
  336. SpinlockLocker lock(m_fds_lock);
  337. if (m_fds_metadatas.size() <= i)
  338. return nullptr;
  339. if (auto& metadata = m_fds_metadatas[i]; metadata.is_valid())
  340. return &metadata;
  341. return nullptr;
  342. }
  343. const Process::OpenFileDescriptionAndFlags& Process::OpenFileDescriptions::at(size_t i) const
  344. {
  345. SpinlockLocker lock(m_fds_lock);
  346. VERIFY(m_fds_metadatas[i].is_allocated());
  347. return m_fds_metadatas[i];
  348. }
  349. Process::OpenFileDescriptionAndFlags& Process::OpenFileDescriptions::at(size_t i)
  350. {
  351. SpinlockLocker lock(m_fds_lock);
  352. VERIFY(m_fds_metadatas[i].is_allocated());
  353. return m_fds_metadatas[i];
  354. }
  355. ErrorOr<NonnullRefPtr<OpenFileDescription>> Process::OpenFileDescriptions::open_file_description(int fd) const
  356. {
  357. SpinlockLocker lock(m_fds_lock);
  358. if (fd < 0)
  359. return EBADF;
  360. if (static_cast<size_t>(fd) >= m_fds_metadatas.size())
  361. return EBADF;
  362. RefPtr description = m_fds_metadatas[fd].description();
  363. if (!description)
  364. return EBADF;
  365. return description.release_nonnull();
  366. }
  367. void Process::OpenFileDescriptions::enumerate(Function<void(const OpenFileDescriptionAndFlags&)> callback) const
  368. {
  369. SpinlockLocker lock(m_fds_lock);
  370. for (auto const& file_description_metadata : m_fds_metadatas) {
  371. callback(file_description_metadata);
  372. }
  373. }
  374. void Process::OpenFileDescriptions::change_each(Function<void(OpenFileDescriptionAndFlags&)> callback)
  375. {
  376. SpinlockLocker lock(m_fds_lock);
  377. for (auto& file_description_metadata : m_fds_metadatas) {
  378. callback(file_description_metadata);
  379. }
  380. }
  381. size_t Process::OpenFileDescriptions::open_count() const
  382. {
  383. size_t count = 0;
  384. enumerate([&](auto& file_description_metadata) {
  385. if (file_description_metadata.is_valid())
  386. ++count;
  387. });
  388. return count;
  389. }
  390. ErrorOr<Process::ScopedDescriptionAllocation> Process::OpenFileDescriptions::allocate(int first_candidate_fd)
  391. {
  392. SpinlockLocker lock(m_fds_lock);
  393. for (size_t i = first_candidate_fd; i < max_open(); ++i) {
  394. if (!m_fds_metadatas[i].is_allocated()) {
  395. m_fds_metadatas[i].allocate();
  396. return Process::ScopedDescriptionAllocation { static_cast<int>(i), &m_fds_metadatas[i] };
  397. }
  398. }
  399. return EMFILE;
  400. }
  401. Time kgettimeofday()
  402. {
  403. return TimeManagement::now();
  404. }
  405. siginfo_t Process::wait_info() const
  406. {
  407. siginfo_t siginfo {};
  408. siginfo.si_signo = SIGCHLD;
  409. siginfo.si_pid = pid().value();
  410. siginfo.si_uid = uid().value();
  411. if (m_protected_values.termination_signal != 0) {
  412. siginfo.si_status = m_protected_values.termination_signal;
  413. siginfo.si_code = CLD_KILLED;
  414. } else {
  415. siginfo.si_status = m_protected_values.termination_status;
  416. siginfo.si_code = CLD_EXITED;
  417. }
  418. return siginfo;
  419. }
  420. Custody& Process::current_directory()
  421. {
  422. if (!m_cwd)
  423. m_cwd = VirtualFileSystem::the().root_custody();
  424. return *m_cwd;
  425. }
  426. ErrorOr<NonnullOwnPtr<KString>> Process::get_syscall_path_argument(Userspace<char const*> user_path, size_t path_length)
  427. {
  428. if (path_length == 0)
  429. return EINVAL;
  430. if (path_length > PATH_MAX)
  431. return ENAMETOOLONG;
  432. return try_copy_kstring_from_user(user_path, path_length);
  433. }
  434. ErrorOr<NonnullOwnPtr<KString>> Process::get_syscall_path_argument(Syscall::StringArgument const& path)
  435. {
  436. Userspace<char const*> path_characters((FlatPtr)path.characters);
  437. return get_syscall_path_argument(path_characters, path.length);
  438. }
  439. ErrorOr<void> Process::dump_core()
  440. {
  441. VERIFY(is_dumpable());
  442. VERIFY(should_generate_coredump());
  443. dbgln("Generating coredump for pid: {}", pid().value());
  444. auto coredump_path = TRY(KString::formatted("/tmp/coredump/{}_{}_{}", name(), pid().value(), kgettimeofday().to_truncated_seconds()));
  445. auto coredump = TRY(Coredump::try_create(*this, coredump_path->view()));
  446. return coredump->write();
  447. }
  448. bool Process::dump_perfcore()
  449. {
  450. VERIFY(is_dumpable());
  451. VERIFY(m_perf_event_buffer);
  452. dbgln("Generating perfcore for pid: {}", pid().value());
  453. // Try to generate a filename which isn't already used.
  454. auto base_filename = String::formatted("{}_{}", name(), pid().value());
  455. auto perfcore_filename = String::formatted("{}.profile", base_filename);
  456. RefPtr<OpenFileDescription> description;
  457. for (size_t attempt = 1; attempt <= 10; ++attempt) {
  458. auto description_or_error = VirtualFileSystem::the().open(perfcore_filename, O_CREAT | O_EXCL, 0400, current_directory(), UidAndGid { 0, 0 });
  459. if (!description_or_error.is_error()) {
  460. description = description_or_error.release_value();
  461. break;
  462. }
  463. perfcore_filename = String::formatted("{}.{}.profile", base_filename, attempt);
  464. }
  465. if (!description) {
  466. dbgln("Failed to generate perfcore for pid {}: Could not generate filename for the perfcore file.", pid().value());
  467. return false;
  468. }
  469. auto builder_or_error = KBufferBuilder::try_create();
  470. if (builder_or_error.is_error()) {
  471. dbgln("Failed to generate perfcore for pid {}: Could not allocate KBufferBuilder.", pid());
  472. return false;
  473. }
  474. auto builder = builder_or_error.release_value();
  475. if (m_perf_event_buffer->to_json(builder).is_error()) {
  476. dbgln("Failed to generate perfcore for pid {}: Could not serialize performance events to JSON.", pid().value());
  477. return false;
  478. }
  479. auto json = builder.build();
  480. if (!json) {
  481. dbgln("Failed to generate perfcore for pid {}: Could not allocate buffer.", pid().value());
  482. return false;
  483. }
  484. auto json_buffer = UserOrKernelBuffer::for_kernel_buffer(json->data());
  485. if (description->write(json_buffer, json->size()).is_error()) {
  486. dbgln("Failed to generate perfcore for pid {}: Could not write to perfcore file.", pid().value());
  487. return false;
  488. }
  489. dbgln("Wrote perfcore for pid {} to {}", pid().value(), perfcore_filename);
  490. return true;
  491. }
  492. void Process::finalize()
  493. {
  494. VERIFY(Thread::current() == g_finalizer);
  495. dbgln_if(PROCESS_DEBUG, "Finalizing process {}", *this);
  496. if (veil_state() == VeilState::Dropped)
  497. dbgln("\x1b[01;31mProcess '{}' exited with the veil left open\x1b[0m", name());
  498. if (is_dumpable()) {
  499. if (m_should_generate_coredump) {
  500. auto result = dump_core();
  501. if (result.is_error()) {
  502. critical_dmesgln("Failed to write coredump: {}", result.error());
  503. }
  504. }
  505. if (m_perf_event_buffer) {
  506. dump_perfcore();
  507. TimeManagement::the().disable_profile_timer();
  508. }
  509. }
  510. m_threads_for_coredump.clear();
  511. if (m_alarm_timer)
  512. TimerQueue::the().cancel_timer(m_alarm_timer.release_nonnull());
  513. m_fds.clear();
  514. m_tty = nullptr;
  515. m_executable = nullptr;
  516. m_cwd = nullptr;
  517. m_arguments.clear();
  518. m_environment.clear();
  519. m_state.store(State::Dead, AK::MemoryOrder::memory_order_release);
  520. {
  521. // FIXME: PID/TID BUG
  522. if (auto parent_thread = Thread::from_tid(ppid().value())) {
  523. if ((parent_thread->m_signal_action_data[SIGCHLD].flags & SA_NOCLDWAIT) != SA_NOCLDWAIT)
  524. parent_thread->send_signal(SIGCHLD, this);
  525. }
  526. }
  527. if (!!ppid()) {
  528. if (auto parent = Process::from_pid(ppid())) {
  529. parent->m_ticks_in_user_for_dead_children += m_ticks_in_user + m_ticks_in_user_for_dead_children;
  530. parent->m_ticks_in_kernel_for_dead_children += m_ticks_in_kernel + m_ticks_in_kernel_for_dead_children;
  531. }
  532. }
  533. unblock_waiters(Thread::WaitBlocker::UnblockFlags::Terminated);
  534. m_space->remove_all_regions({});
  535. VERIFY(ref_count() > 0);
  536. // WaitBlockerSet::finalize will be in charge of dropping the last
  537. // reference if there are still waiters around, or whenever the last
  538. // waitable states are consumed. Unless there is no parent around
  539. // anymore, in which case we'll just drop it right away.
  540. m_wait_blocker_set.finalize();
  541. }
  542. void Process::disowned_by_waiter(Process& process)
  543. {
  544. m_wait_blocker_set.disowned_by_waiter(process);
  545. }
  546. void Process::unblock_waiters(Thread::WaitBlocker::UnblockFlags flags, u8 signal)
  547. {
  548. RefPtr<Process> waiter_process;
  549. if (auto* my_tracer = tracer())
  550. waiter_process = Process::from_pid(my_tracer->tracer_pid());
  551. else
  552. waiter_process = Process::from_pid(ppid());
  553. if (waiter_process)
  554. waiter_process->m_wait_blocker_set.unblock(*this, flags, signal);
  555. }
  556. void Process::die()
  557. {
  558. auto expected = State::Running;
  559. if (!m_state.compare_exchange_strong(expected, State::Dying, AK::memory_order_acquire)) {
  560. // It's possible that another thread calls this at almost the same time
  561. // as we can't always instantly kill other threads (they may be blocked)
  562. // So if we already were called then other threads should stop running
  563. // momentarily and we only really need to service the first thread
  564. return;
  565. }
  566. // Let go of the TTY, otherwise a slave PTY may keep the master PTY from
  567. // getting an EOF when the last process using the slave PTY dies.
  568. // If the master PTY owner relies on an EOF to know when to wait() on a
  569. // slave owner, we have to allow the PTY pair to be torn down.
  570. m_tty = nullptr;
  571. VERIFY(m_threads_for_coredump.is_empty());
  572. for_each_thread([&](auto& thread) {
  573. m_threads_for_coredump.append(thread);
  574. });
  575. all_instances().with([&](const auto& list) {
  576. for (auto it = list.begin(); it != list.end();) {
  577. auto& process = *it;
  578. ++it;
  579. if (process.has_tracee_thread(pid())) {
  580. dbgln_if(PROCESS_DEBUG, "Process {} ({}) is attached by {} ({}) which will exit", process.name(), process.pid(), name(), pid());
  581. process.stop_tracing();
  582. auto err = process.send_signal(SIGSTOP, this);
  583. if (err.is_error())
  584. dbgln("Failed to send the SIGSTOP signal to {} ({})", process.name(), process.pid());
  585. }
  586. }
  587. });
  588. kill_all_threads();
  589. #ifdef ENABLE_KERNEL_COVERAGE_COLLECTION
  590. KCOVDevice::free_process();
  591. #endif
  592. }
  593. void Process::terminate_due_to_signal(u8 signal)
  594. {
  595. VERIFY_INTERRUPTS_DISABLED();
  596. VERIFY(signal < 32);
  597. VERIFY(&Process::current() == this);
  598. dbgln("Terminating {} due to signal {}", *this, signal);
  599. {
  600. ProtectedDataMutationScope scope { *this };
  601. m_protected_values.termination_status = 0;
  602. m_protected_values.termination_signal = signal;
  603. }
  604. die();
  605. }
  606. ErrorOr<void> Process::send_signal(u8 signal, Process* sender)
  607. {
  608. // Try to send it to the "obvious" main thread:
  609. auto receiver_thread = Thread::from_tid(pid().value());
  610. // If the main thread has died, there may still be other threads:
  611. if (!receiver_thread) {
  612. // The first one should be good enough.
  613. // Neither kill(2) nor kill(3) specify any selection precedure.
  614. for_each_thread([&receiver_thread](Thread& thread) -> IterationDecision {
  615. receiver_thread = &thread;
  616. return IterationDecision::Break;
  617. });
  618. }
  619. if (receiver_thread) {
  620. receiver_thread->send_signal(signal, sender);
  621. return {};
  622. }
  623. return ESRCH;
  624. }
  625. RefPtr<Thread> Process::create_kernel_thread(void (*entry)(void*), void* entry_data, u32 priority, NonnullOwnPtr<KString> name, u32 affinity, bool joinable)
  626. {
  627. VERIFY((priority >= THREAD_PRIORITY_MIN) && (priority <= THREAD_PRIORITY_MAX));
  628. // FIXME: Do something with guard pages?
  629. auto thread_or_error = Thread::try_create(*this);
  630. if (thread_or_error.is_error())
  631. return {};
  632. auto thread = thread_or_error.release_value();
  633. thread->set_name(move(name));
  634. thread->set_affinity(affinity);
  635. thread->set_priority(priority);
  636. if (!joinable)
  637. thread->detach();
  638. auto& regs = thread->regs();
  639. regs.set_ip((FlatPtr)entry);
  640. regs.set_sp((FlatPtr)entry_data); // entry function argument is expected to be in the SP register
  641. SpinlockLocker lock(g_scheduler_lock);
  642. thread->set_state(Thread::State::Runnable);
  643. return thread;
  644. }
  645. void Process::OpenFileDescriptionAndFlags::clear()
  646. {
  647. // FIXME: Verify Process::m_fds_lock is locked!
  648. m_description = nullptr;
  649. m_flags = 0;
  650. }
  651. void Process::OpenFileDescriptionAndFlags::set(NonnullRefPtr<OpenFileDescription>&& description, u32 flags)
  652. {
  653. // FIXME: Verify Process::m_fds_lock is locked!
  654. m_description = move(description);
  655. m_flags = flags;
  656. }
  657. void Process::set_tty(TTY* tty)
  658. {
  659. m_tty = tty;
  660. }
  661. ErrorOr<void> Process::start_tracing_from(ProcessID tracer)
  662. {
  663. m_tracer = TRY(ThreadTracer::try_create(tracer));
  664. return {};
  665. }
  666. void Process::stop_tracing()
  667. {
  668. m_tracer = nullptr;
  669. }
  670. void Process::tracer_trap(Thread& thread, const RegisterState& regs)
  671. {
  672. VERIFY(m_tracer.ptr());
  673. m_tracer->set_regs(regs);
  674. thread.send_urgent_signal_to_self(SIGTRAP);
  675. }
  676. bool Process::create_perf_events_buffer_if_needed()
  677. {
  678. if (!m_perf_event_buffer) {
  679. m_perf_event_buffer = PerformanceEventBuffer::try_create_with_size(4 * MiB);
  680. m_perf_event_buffer->add_process(*this, ProcessEventType::Create);
  681. }
  682. return !!m_perf_event_buffer;
  683. }
  684. void Process::delete_perf_events_buffer()
  685. {
  686. if (m_perf_event_buffer)
  687. m_perf_event_buffer = nullptr;
  688. }
  689. bool Process::remove_thread(Thread& thread)
  690. {
  691. ProtectedDataMutationScope scope { *this };
  692. auto thread_cnt_before = m_protected_values.thread_count.fetch_sub(1, AK::MemoryOrder::memory_order_acq_rel);
  693. VERIFY(thread_cnt_before != 0);
  694. thread_list().with([&](auto& thread_list) {
  695. thread_list.remove(thread);
  696. });
  697. return thread_cnt_before == 1;
  698. }
  699. bool Process::add_thread(Thread& thread)
  700. {
  701. ProtectedDataMutationScope scope { *this };
  702. bool is_first = m_protected_values.thread_count.fetch_add(1, AK::MemoryOrder::memory_order_relaxed) == 0;
  703. thread_list().with([&](auto& thread_list) {
  704. thread_list.append(thread);
  705. });
  706. return is_first;
  707. }
  708. void Process::set_dumpable(bool dumpable)
  709. {
  710. if (dumpable == m_protected_values.dumpable)
  711. return;
  712. ProtectedDataMutationScope scope { *this };
  713. m_protected_values.dumpable = dumpable;
  714. }
  715. ErrorOr<void> Process::set_coredump_property(NonnullOwnPtr<KString> key, NonnullOwnPtr<KString> value)
  716. {
  717. // Write it into the first available property slot.
  718. for (auto& slot : m_coredump_properties) {
  719. if (slot.key)
  720. continue;
  721. slot.key = move(key);
  722. slot.value = move(value);
  723. return {};
  724. }
  725. return ENOBUFS;
  726. }
  727. ErrorOr<void> Process::try_set_coredump_property(StringView key, StringView value)
  728. {
  729. auto key_kstring = TRY(KString::try_create(key));
  730. auto value_kstring = TRY(KString::try_create(value));
  731. return set_coredump_property(move(key_kstring), move(value_kstring));
  732. };
  733. static constexpr StringView to_string(Pledge promise)
  734. {
  735. #define __ENUMERATE_PLEDGE_PROMISE(x) \
  736. case Pledge::x: \
  737. return #x;
  738. switch (promise) {
  739. ENUMERATE_PLEDGE_PROMISES
  740. }
  741. #undef __ENUMERATE_PLEDGE_PROMISE
  742. VERIFY_NOT_REACHED();
  743. }
  744. ErrorOr<void> Process::require_no_promises() const
  745. {
  746. if (!has_promises())
  747. return {};
  748. dbgln("Has made a promise");
  749. Thread::current()->set_promise_violation_pending(true);
  750. return EPROMISEVIOLATION;
  751. }
  752. ErrorOr<void> Process::require_promise(Pledge promise)
  753. {
  754. if (!has_promises())
  755. return {};
  756. if (has_promised(promise))
  757. return {};
  758. dbgln("Has not pledged {}", to_string(promise));
  759. Thread::current()->set_promise_violation_pending(true);
  760. (void)try_set_coredump_property("pledge_violation"sv, to_string(promise));
  761. return EPROMISEVIOLATION;
  762. }
  763. }