Process.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Demangle.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/CPU.h>
  13. #include <Kernel/CoreDump.h>
  14. #include <Kernel/Debug.h>
  15. #include <Kernel/Devices/NullDevice.h>
  16. #include <Kernel/FileSystem/Custody.h>
  17. #include <Kernel/FileSystem/FileDescription.h>
  18. #include <Kernel/FileSystem/VirtualFileSystem.h>
  19. #include <Kernel/KBufferBuilder.h>
  20. #include <Kernel/KSyms.h>
  21. #include <Kernel/Module.h>
  22. #include <Kernel/PerformanceEventBuffer.h>
  23. #include <Kernel/Process.h>
  24. #include <Kernel/RTC.h>
  25. #include <Kernel/StdLib.h>
  26. #include <Kernel/TTY/TTY.h>
  27. #include <Kernel/Thread.h>
  28. #include <Kernel/VM/AnonymousVMObject.h>
  29. #include <Kernel/VM/PageDirectory.h>
  30. #include <Kernel/VM/PrivateInodeVMObject.h>
  31. #include <Kernel/VM/SharedInodeVMObject.h>
  32. #include <LibC/errno_numbers.h>
  33. #include <LibC/limits.h>
  34. namespace Kernel {
  35. static void create_signal_trampoline();
  36. RecursiveSpinLock g_processes_lock;
  37. static Atomic<pid_t> next_pid;
  38. READONLY_AFTER_INIT InlineLinkedList<Process>* g_processes;
  39. READONLY_AFTER_INIT String* g_hostname;
  40. READONLY_AFTER_INIT Lock* g_hostname_lock;
  41. READONLY_AFTER_INIT HashMap<String, OwnPtr<Module>>* g_modules;
  42. READONLY_AFTER_INIT Region* g_signal_trampoline_region;
  43. ProcessID Process::allocate_pid()
  44. {
  45. // Overflow is UB, and negative PIDs wreck havoc.
  46. // TODO: Handle PID overflow
  47. // For example: Use an Atomic<u32>, mask the most significant bit,
  48. // retry if PID is already taken as a PID, taken as a TID,
  49. // takes as a PGID, taken as a SID, or zero.
  50. return next_pid.fetch_add(1, AK::MemoryOrder::memory_order_acq_rel);
  51. }
  52. UNMAP_AFTER_INIT void Process::initialize()
  53. {
  54. g_modules = new HashMap<String, OwnPtr<Module>>;
  55. next_pid.store(0, AK::MemoryOrder::memory_order_release);
  56. g_processes = new InlineLinkedList<Process>;
  57. g_process_groups = new InlineLinkedList<ProcessGroup>;
  58. g_hostname = new String("courage");
  59. g_hostname_lock = new Lock;
  60. create_signal_trampoline();
  61. }
  62. Vector<ProcessID> Process::all_pids()
  63. {
  64. Vector<ProcessID> pids;
  65. ScopedSpinLock lock(g_processes_lock);
  66. pids.ensure_capacity((int)g_processes->size_slow());
  67. for (auto& process : *g_processes)
  68. pids.append(process.pid());
  69. return pids;
  70. }
  71. NonnullRefPtrVector<Process> Process::all_processes()
  72. {
  73. NonnullRefPtrVector<Process> processes;
  74. ScopedSpinLock lock(g_processes_lock);
  75. processes.ensure_capacity((int)g_processes->size_slow());
  76. for (auto& process : *g_processes)
  77. processes.append(NonnullRefPtr<Process>(process));
  78. return processes;
  79. }
  80. bool Process::in_group(gid_t 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. || thread.state() == Thread::State::Dead
  93. || thread.state() == Thread::State::Dying)
  94. return IterationDecision::Continue;
  95. // We need to detach this thread in case it hasn't been joined
  96. thread.detach();
  97. thread.set_should_die();
  98. return IterationDecision::Continue;
  99. });
  100. big_lock().clear_waiters();
  101. }
  102. void Process::kill_all_threads()
  103. {
  104. for_each_thread([&](Thread& thread) {
  105. // We need to detach this thread in case it hasn't been joined
  106. thread.detach();
  107. thread.set_should_die();
  108. return IterationDecision::Continue;
  109. });
  110. }
  111. RefPtr<Process> Process::create_user_process(RefPtr<Thread>& first_thread, const String& path, uid_t uid, gid_t gid, ProcessID parent_pid, int& error, Vector<String>&& arguments, Vector<String>&& environment, TTY* tty)
  112. {
  113. auto parts = path.split('/');
  114. if (arguments.is_empty()) {
  115. arguments.append(parts.last());
  116. }
  117. RefPtr<Custody> cwd;
  118. {
  119. ScopedSpinLock lock(g_processes_lock);
  120. if (auto parent = Process::from_pid(parent_pid)) {
  121. cwd = parent->m_cwd;
  122. }
  123. }
  124. if (!cwd)
  125. cwd = VFS::the().root_custody();
  126. auto process = adopt_ref(*new Process(first_thread, parts.take_last(), uid, gid, parent_pid, false, move(cwd), nullptr, tty));
  127. if (!first_thread)
  128. return {};
  129. process->m_fds.resize(m_max_open_file_descriptors);
  130. auto& device_to_use_as_tty = tty ? (CharacterDevice&)*tty : NullDevice::the();
  131. auto description = device_to_use_as_tty.open(O_RDWR).value();
  132. process->m_fds[0].set(*description);
  133. process->m_fds[1].set(*description);
  134. process->m_fds[2].set(*description);
  135. error = process->exec(path, move(arguments), move(environment));
  136. if (error != 0) {
  137. dbgln("Failed to exec {}: {}", path, error);
  138. first_thread = nullptr;
  139. return {};
  140. }
  141. {
  142. ScopedSpinLock lock(g_processes_lock);
  143. g_processes->prepend(process);
  144. process->ref();
  145. }
  146. error = 0;
  147. return process;
  148. }
  149. RefPtr<Process> Process::create_kernel_process(RefPtr<Thread>& first_thread, String&& name, void (*entry)(void*), void* entry_data, u32 affinity)
  150. {
  151. auto process = adopt_ref(*new Process(first_thread, move(name), (uid_t)0, (gid_t)0, ProcessID(0), true));
  152. if (!first_thread)
  153. return {};
  154. first_thread->tss().eip = (FlatPtr)entry;
  155. first_thread->tss().esp = FlatPtr(entry_data); // entry function argument is expected to be in tss.esp
  156. if (process->pid() != 0) {
  157. ScopedSpinLock lock(g_processes_lock);
  158. g_processes->prepend(process);
  159. process->ref();
  160. }
  161. ScopedSpinLock lock(g_scheduler_lock);
  162. first_thread->set_affinity(affinity);
  163. first_thread->set_state(Thread::State::Runnable);
  164. return process;
  165. }
  166. void Process::protect_data()
  167. {
  168. MM.set_page_writable_direct(VirtualAddress { this }, false);
  169. }
  170. void Process::unprotect_data()
  171. {
  172. MM.set_page_writable_direct(VirtualAddress { this }, true);
  173. }
  174. Process::Process(RefPtr<Thread>& first_thread, const String& name, uid_t uid, gid_t gid, ProcessID ppid, bool is_kernel_process, RefPtr<Custody> cwd, RefPtr<Custody> executable, TTY* tty, Process* fork_parent)
  175. : m_name(move(name))
  176. , m_is_kernel_process(is_kernel_process)
  177. , m_executable(move(executable))
  178. , m_cwd(move(cwd))
  179. , m_tty(tty)
  180. , m_wait_block_condition(*this)
  181. {
  182. // Ensure that we protect the process data when exiting the constructor.
  183. ProtectedDataMutationScope scope { *this };
  184. m_pid = allocate_pid();
  185. m_ppid = ppid;
  186. m_uid = uid;
  187. m_gid = gid;
  188. m_euid = uid;
  189. m_egid = gid;
  190. m_suid = uid;
  191. m_sgid = gid;
  192. dbgln_if(PROCESS_DEBUG, "Created new process {}({})", m_name, this->pid().value());
  193. m_space = Space::create(*this, fork_parent ? &fork_parent->space() : nullptr);
  194. if (fork_parent) {
  195. // NOTE: fork() doesn't clone all threads; the thread that called fork() becomes the only thread in the new process.
  196. first_thread = Thread::current()->clone(*this);
  197. } else {
  198. // NOTE: This non-forked code path is only taken when the kernel creates a process "manually" (at boot.)
  199. auto thread_or_error = Thread::try_create(*this);
  200. VERIFY(!thread_or_error.is_error());
  201. first_thread = thread_or_error.release_value();
  202. first_thread->detach();
  203. }
  204. }
  205. Process::~Process()
  206. {
  207. unprotect_data();
  208. VERIFY(thread_count() == 0); // all threads should have been finalized
  209. VERIFY(!m_alarm_timer);
  210. {
  211. ScopedSpinLock processses_lock(g_processes_lock);
  212. if (prev() || next())
  213. g_processes->remove(this);
  214. }
  215. }
  216. // Make sure the compiler doesn't "optimize away" this function:
  217. extern void signal_trampoline_dummy();
  218. void signal_trampoline_dummy()
  219. {
  220. #if ARCH(I386)
  221. // The trampoline preserves the current eax, pushes the signal code and
  222. // then calls the signal handler. We do this because, when interrupting a
  223. // blocking syscall, that syscall may return some special error code in eax;
  224. // This error code would likely be overwritten by the signal handler, so it's
  225. // necessary to preserve it here.
  226. asm(
  227. ".intel_syntax noprefix\n"
  228. "asm_signal_trampoline:\n"
  229. "push ebp\n"
  230. "mov ebp, esp\n"
  231. "push eax\n" // we have to store eax 'cause it might be the return value from a syscall
  232. "sub esp, 4\n" // align the stack to 16 bytes
  233. "mov eax, [ebp+12]\n" // push the signal code
  234. "push eax\n"
  235. "call [ebp+8]\n" // call the signal handler
  236. "add esp, 8\n"
  237. "mov eax, %P0\n"
  238. "int 0x82\n" // sigreturn syscall
  239. "asm_signal_trampoline_end:\n"
  240. ".att_syntax" ::"i"(Syscall::SC_sigreturn));
  241. #elif ARCH(X86_64)
  242. asm("asm_signal_trampoline:\n"
  243. "cli;hlt\n"
  244. "asm_signal_trampoline_end:\n");
  245. #endif
  246. }
  247. extern "C" void asm_signal_trampoline(void);
  248. extern "C" void asm_signal_trampoline_end(void);
  249. void create_signal_trampoline()
  250. {
  251. // NOTE: We leak this region.
  252. g_signal_trampoline_region = MM.allocate_kernel_region(PAGE_SIZE, "Signal trampolines", Region::Access::Read | Region::Access::Write).leak_ptr();
  253. g_signal_trampoline_region->set_syscall_region(true);
  254. u8* trampoline = (u8*)asm_signal_trampoline;
  255. u8* trampoline_end = (u8*)asm_signal_trampoline_end;
  256. size_t trampoline_size = trampoline_end - trampoline;
  257. u8* code_ptr = (u8*)g_signal_trampoline_region->vaddr().as_ptr();
  258. memcpy(code_ptr, trampoline, trampoline_size);
  259. g_signal_trampoline_region->set_writable(false);
  260. g_signal_trampoline_region->remap();
  261. }
  262. void Process::crash(int signal, u32 eip, bool out_of_memory)
  263. {
  264. VERIFY(!is_dead());
  265. VERIFY(Process::current() == this);
  266. if (out_of_memory) {
  267. dbgln("\033[31;1mOut of memory\033[m, killing: {}", *this);
  268. } else {
  269. if (eip >= 0xc0000000 && g_kernel_symbols_available) {
  270. auto* symbol = symbolicate_kernel_address(eip);
  271. dbgln("\033[31;1m{:p} {} +{}\033[0m\n", eip, (symbol ? demangle(symbol->name) : "(k?)"), (symbol ? eip - symbol->address : 0));
  272. } else {
  273. dbgln("\033[31;1m{:p} (?)\033[0m\n", eip);
  274. }
  275. dump_backtrace();
  276. }
  277. {
  278. ProtectedDataMutationScope scope { *this };
  279. m_termination_signal = signal;
  280. }
  281. set_dump_core(!out_of_memory);
  282. space().dump_regions();
  283. VERIFY(is_user_process());
  284. die();
  285. // We can not return from here, as there is nowhere
  286. // to unwind to, so die right away.
  287. Thread::current()->die_if_needed();
  288. VERIFY_NOT_REACHED();
  289. }
  290. RefPtr<Process> Process::from_pid(ProcessID pid)
  291. {
  292. ScopedSpinLock lock(g_processes_lock);
  293. for (auto& process : *g_processes) {
  294. process.pid();
  295. if (process.pid() == pid)
  296. return &process;
  297. }
  298. return {};
  299. }
  300. RefPtr<FileDescription> Process::file_description(int fd) const
  301. {
  302. if (fd < 0)
  303. return nullptr;
  304. if (static_cast<size_t>(fd) < m_fds.size())
  305. return m_fds[fd].description();
  306. return nullptr;
  307. }
  308. int Process::fd_flags(int fd) const
  309. {
  310. if (fd < 0)
  311. return -1;
  312. if (static_cast<size_t>(fd) < m_fds.size())
  313. return m_fds[fd].flags();
  314. return -1;
  315. }
  316. int Process::number_of_open_file_descriptors() const
  317. {
  318. int count = 0;
  319. for (auto& description : m_fds) {
  320. if (description)
  321. ++count;
  322. }
  323. return count;
  324. }
  325. int Process::alloc_fd(int first_candidate_fd)
  326. {
  327. for (int i = first_candidate_fd; i < (int)m_max_open_file_descriptors; ++i) {
  328. if (!m_fds[i])
  329. return i;
  330. }
  331. return -EMFILE;
  332. }
  333. Time kgettimeofday()
  334. {
  335. return TimeManagement::now();
  336. }
  337. siginfo_t Process::wait_info()
  338. {
  339. siginfo_t siginfo {};
  340. siginfo.si_signo = SIGCHLD;
  341. siginfo.si_pid = pid().value();
  342. siginfo.si_uid = uid();
  343. if (m_termination_signal) {
  344. siginfo.si_status = m_termination_signal;
  345. siginfo.si_code = CLD_KILLED;
  346. } else {
  347. siginfo.si_status = m_termination_status;
  348. siginfo.si_code = CLD_EXITED;
  349. }
  350. return siginfo;
  351. }
  352. Custody& Process::current_directory()
  353. {
  354. if (!m_cwd)
  355. m_cwd = VFS::the().root_custody();
  356. return *m_cwd;
  357. }
  358. KResultOr<String> Process::get_syscall_path_argument(const char* user_path, size_t path_length) const
  359. {
  360. if (path_length == 0)
  361. return EINVAL;
  362. if (path_length > PATH_MAX)
  363. return ENAMETOOLONG;
  364. auto copied_string = copy_string_from_user(user_path, path_length);
  365. if (copied_string.is_null())
  366. return EFAULT;
  367. return copied_string;
  368. }
  369. KResultOr<String> Process::get_syscall_path_argument(const Syscall::StringArgument& path) const
  370. {
  371. return get_syscall_path_argument(path.characters, path.length);
  372. }
  373. bool Process::dump_core()
  374. {
  375. VERIFY(is_dumpable());
  376. VERIFY(should_core_dump());
  377. dbgln("Generating coredump for pid: {}", pid().value());
  378. auto coredump_path = String::formatted("/tmp/coredump/{}_{}_{}", name(), pid().value(), RTC::now());
  379. auto coredump = CoreDump::create(*this, coredump_path);
  380. if (!coredump)
  381. return false;
  382. return !coredump->write().is_error();
  383. }
  384. bool Process::dump_perfcore()
  385. {
  386. VERIFY(is_dumpable());
  387. VERIFY(m_perf_event_buffer);
  388. dbgln("Generating perfcore for pid: {}", pid().value());
  389. auto description_or_error = VFS::the().open(String::formatted("perfcore.{}", pid().value()), O_CREAT | O_EXCL, 0400, current_directory(), UidAndGid { uid(), gid() });
  390. if (description_or_error.is_error())
  391. return false;
  392. auto& description = description_or_error.value();
  393. KBufferBuilder builder;
  394. if (!m_perf_event_buffer->to_json(builder))
  395. return false;
  396. auto json = builder.build();
  397. if (!json)
  398. return false;
  399. auto json_buffer = UserOrKernelBuffer::for_kernel_buffer(json->data());
  400. return !description->write(json_buffer, json->size()).is_error();
  401. }
  402. void Process::finalize()
  403. {
  404. VERIFY(Thread::current() == g_finalizer);
  405. dbgln_if(PROCESS_DEBUG, "Finalizing process {}", *this);
  406. if (is_dumpable()) {
  407. if (m_should_dump_core)
  408. dump_core();
  409. if (m_perf_event_buffer)
  410. dump_perfcore();
  411. }
  412. m_threads_for_coredump.clear();
  413. if (m_alarm_timer)
  414. TimerQueue::the().cancel_timer(m_alarm_timer.release_nonnull());
  415. m_fds.clear();
  416. m_tty = nullptr;
  417. m_executable = nullptr;
  418. m_cwd = nullptr;
  419. m_root_directory = nullptr;
  420. m_root_directory_relative_to_global_root = nullptr;
  421. m_arguments.clear();
  422. m_environment.clear();
  423. m_dead = true;
  424. {
  425. // FIXME: PID/TID BUG
  426. if (auto parent_thread = Thread::from_tid(ppid().value())) {
  427. if (!(parent_thread->m_signal_action_data[SIGCHLD].flags & SA_NOCLDWAIT))
  428. parent_thread->send_signal(SIGCHLD, this);
  429. }
  430. }
  431. {
  432. ScopedSpinLock processses_lock(g_processes_lock);
  433. if (!!ppid()) {
  434. if (auto parent = Process::from_pid(ppid())) {
  435. parent->m_ticks_in_user_for_dead_children += m_ticks_in_user + m_ticks_in_user_for_dead_children;
  436. parent->m_ticks_in_kernel_for_dead_children += m_ticks_in_kernel + m_ticks_in_kernel_for_dead_children;
  437. }
  438. }
  439. }
  440. unblock_waiters(Thread::WaitBlocker::UnblockFlags::Terminated);
  441. m_space->remove_all_regions({});
  442. VERIFY(ref_count() > 0);
  443. // WaitBlockCondition::finalize will be in charge of dropping the last
  444. // reference if there are still waiters around, or whenever the last
  445. // waitable states are consumed. Unless there is no parent around
  446. // anymore, in which case we'll just drop it right away.
  447. m_wait_block_condition.finalize();
  448. }
  449. void Process::disowned_by_waiter(Process& process)
  450. {
  451. m_wait_block_condition.disowned_by_waiter(process);
  452. }
  453. void Process::unblock_waiters(Thread::WaitBlocker::UnblockFlags flags, u8 signal)
  454. {
  455. if (auto parent = Process::from_pid(ppid()))
  456. parent->m_wait_block_condition.unblock(*this, flags, signal);
  457. }
  458. void Process::die()
  459. {
  460. // Let go of the TTY, otherwise a slave PTY may keep the master PTY from
  461. // getting an EOF when the last process using the slave PTY dies.
  462. // If the master PTY owner relies on an EOF to know when to wait() on a
  463. // slave owner, we have to allow the PTY pair to be torn down.
  464. m_tty = nullptr;
  465. for_each_thread([&](auto& thread) {
  466. m_threads_for_coredump.append(thread);
  467. return IterationDecision::Continue;
  468. });
  469. {
  470. ScopedSpinLock lock(g_processes_lock);
  471. for (auto* process = g_processes->head(); process;) {
  472. auto* next_process = process->next();
  473. if (process->has_tracee_thread(pid())) {
  474. dbgln_if(PROCESS_DEBUG, "Process {} ({}) is attached by {} ({}) which will exit", process->name(), process->pid(), name(), pid());
  475. process->stop_tracing();
  476. auto err = process->send_signal(SIGSTOP, this);
  477. if (err.is_error())
  478. dbgln("Failed to send the SIGSTOP signal to {} ({})", process->name(), process->pid());
  479. }
  480. process = next_process;
  481. }
  482. }
  483. kill_all_threads();
  484. }
  485. void Process::terminate_due_to_signal(u8 signal)
  486. {
  487. VERIFY_INTERRUPTS_DISABLED();
  488. VERIFY(signal < 32);
  489. VERIFY(Process::current() == this);
  490. dbgln("Terminating {} due to signal {}", *this, signal);
  491. {
  492. ProtectedDataMutationScope scope { *this };
  493. m_termination_status = 0;
  494. m_termination_signal = signal;
  495. }
  496. die();
  497. }
  498. KResult Process::send_signal(u8 signal, Process* sender)
  499. {
  500. // Try to send it to the "obvious" main thread:
  501. auto receiver_thread = Thread::from_tid(pid().value());
  502. // If the main thread has died, there may still be other threads:
  503. if (!receiver_thread) {
  504. // The first one should be good enough.
  505. // Neither kill(2) nor kill(3) specify any selection precedure.
  506. for_each_thread([&receiver_thread](Thread& thread) -> IterationDecision {
  507. receiver_thread = &thread;
  508. return IterationDecision::Break;
  509. });
  510. }
  511. if (receiver_thread) {
  512. receiver_thread->send_signal(signal, sender);
  513. return KSuccess;
  514. }
  515. return ESRCH;
  516. }
  517. RefPtr<Thread> Process::create_kernel_thread(void (*entry)(void*), void* entry_data, u32 priority, const String& name, u32 affinity, bool joinable)
  518. {
  519. VERIFY((priority >= THREAD_PRIORITY_MIN) && (priority <= THREAD_PRIORITY_MAX));
  520. // FIXME: Do something with guard pages?
  521. auto thread_or_error = Thread::try_create(*this);
  522. if (thread_or_error.is_error())
  523. return {};
  524. auto thread = thread_or_error.release_value();
  525. thread->set_name(name);
  526. thread->set_affinity(affinity);
  527. thread->set_priority(priority);
  528. if (!joinable)
  529. thread->detach();
  530. auto& tss = thread->tss();
  531. tss.eip = (FlatPtr)entry;
  532. tss.esp = FlatPtr(entry_data); // entry function argument is expected to be in tss.esp
  533. ScopedSpinLock lock(g_scheduler_lock);
  534. thread->set_state(Thread::State::Runnable);
  535. return thread;
  536. }
  537. void Process::FileDescriptionAndFlags::clear()
  538. {
  539. m_description = nullptr;
  540. m_flags = 0;
  541. }
  542. void Process::FileDescriptionAndFlags::set(NonnullRefPtr<FileDescription>&& description, u32 flags)
  543. {
  544. m_description = move(description);
  545. m_flags = flags;
  546. }
  547. Custody& Process::root_directory()
  548. {
  549. if (!m_root_directory)
  550. m_root_directory = VFS::the().root_custody();
  551. return *m_root_directory;
  552. }
  553. Custody& Process::root_directory_relative_to_global_root()
  554. {
  555. if (!m_root_directory_relative_to_global_root)
  556. m_root_directory_relative_to_global_root = root_directory();
  557. return *m_root_directory_relative_to_global_root;
  558. }
  559. void Process::set_root_directory(const Custody& root)
  560. {
  561. m_root_directory = root;
  562. }
  563. void Process::set_tty(TTY* tty)
  564. {
  565. m_tty = tty;
  566. }
  567. void Process::start_tracing_from(ProcessID tracer)
  568. {
  569. m_tracer = ThreadTracer::create(tracer);
  570. }
  571. void Process::stop_tracing()
  572. {
  573. m_tracer = nullptr;
  574. }
  575. void Process::tracer_trap(Thread& thread, const RegisterState& regs)
  576. {
  577. VERIFY(m_tracer.ptr());
  578. m_tracer->set_regs(regs);
  579. thread.send_urgent_signal_to_self(SIGTRAP);
  580. }
  581. bool Process::create_perf_events_buffer_if_needed()
  582. {
  583. if (!m_perf_event_buffer) {
  584. m_perf_event_buffer = PerformanceEventBuffer::try_create_with_size(4 * MiB);
  585. m_perf_event_buffer->add_process(*this);
  586. }
  587. return !!m_perf_event_buffer;
  588. }
  589. void Process::delete_perf_events_buffer()
  590. {
  591. if (m_perf_event_buffer)
  592. m_perf_event_buffer = nullptr;
  593. }
  594. bool Process::remove_thread(Thread& thread)
  595. {
  596. ProtectedDataMutationScope scope { *this };
  597. auto thread_cnt_before = m_thread_count.fetch_sub(1, AK::MemoryOrder::memory_order_acq_rel);
  598. VERIFY(thread_cnt_before != 0);
  599. ScopedSpinLock thread_list_lock(m_thread_list_lock);
  600. m_thread_list.remove(thread);
  601. return thread_cnt_before == 1;
  602. }
  603. bool Process::add_thread(Thread& thread)
  604. {
  605. ProtectedDataMutationScope scope { *this };
  606. bool is_first = m_thread_count.fetch_add(1, AK::MemoryOrder::memory_order_relaxed) == 0;
  607. ScopedSpinLock thread_list_lock(m_thread_list_lock);
  608. m_thread_list.append(thread);
  609. return is_first;
  610. }
  611. void Process::set_dumpable(bool dumpable)
  612. {
  613. if (dumpable == m_dumpable)
  614. return;
  615. ProtectedDataMutationScope scope { *this };
  616. m_dumpable = dumpable;
  617. }
  618. void Process::set_coredump_metadata(const String& key, String value)
  619. {
  620. m_coredump_metadata.set(key, move(value));
  621. }
  622. }