Process.cpp 30 KB

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