Process.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  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. if (g_profiling_all_threads) {
  211. VERIFY(g_global_perf_events);
  212. [[maybe_unused]] auto rc = g_global_perf_events->append_with_eip_and_ebp(
  213. pid(), 0, 0, 0, PERF_EVENT_PROCESS_EXIT, 0, 0, nullptr);
  214. }
  215. {
  216. ScopedSpinLock processes_lock(g_processes_lock);
  217. if (prev() || next())
  218. g_processes->remove(this);
  219. }
  220. }
  221. // Make sure the compiler doesn't "optimize away" this function:
  222. extern void signal_trampoline_dummy();
  223. void signal_trampoline_dummy()
  224. {
  225. #if ARCH(I386)
  226. // The trampoline preserves the current eax, pushes the signal code and
  227. // then calls the signal handler. We do this because, when interrupting a
  228. // blocking syscall, that syscall may return some special error code in eax;
  229. // This error code would likely be overwritten by the signal handler, so it's
  230. // necessary to preserve it here.
  231. asm(
  232. ".intel_syntax noprefix\n"
  233. "asm_signal_trampoline:\n"
  234. "push ebp\n"
  235. "mov ebp, esp\n"
  236. "push eax\n" // we have to store eax 'cause it might be the return value from a syscall
  237. "sub esp, 4\n" // align the stack to 16 bytes
  238. "mov eax, [ebp+12]\n" // push the signal code
  239. "push eax\n"
  240. "call [ebp+8]\n" // call the signal handler
  241. "add esp, 8\n"
  242. "mov eax, %P0\n"
  243. "int 0x82\n" // sigreturn syscall
  244. "asm_signal_trampoline_end:\n"
  245. ".att_syntax" ::"i"(Syscall::SC_sigreturn));
  246. #elif ARCH(X86_64)
  247. asm("asm_signal_trampoline:\n"
  248. "cli;hlt\n"
  249. "asm_signal_trampoline_end:\n");
  250. #endif
  251. }
  252. extern "C" void asm_signal_trampoline(void);
  253. extern "C" void asm_signal_trampoline_end(void);
  254. void create_signal_trampoline()
  255. {
  256. // NOTE: We leak this region.
  257. g_signal_trampoline_region = MM.allocate_kernel_region(PAGE_SIZE, "Signal trampolines", Region::Access::Read | Region::Access::Write).leak_ptr();
  258. g_signal_trampoline_region->set_syscall_region(true);
  259. u8* trampoline = (u8*)asm_signal_trampoline;
  260. u8* trampoline_end = (u8*)asm_signal_trampoline_end;
  261. size_t trampoline_size = trampoline_end - trampoline;
  262. u8* code_ptr = (u8*)g_signal_trampoline_region->vaddr().as_ptr();
  263. memcpy(code_ptr, trampoline, trampoline_size);
  264. g_signal_trampoline_region->set_writable(false);
  265. g_signal_trampoline_region->remap();
  266. }
  267. void Process::crash(int signal, u32 eip, bool out_of_memory)
  268. {
  269. VERIFY(!is_dead());
  270. VERIFY(Process::current() == this);
  271. if (out_of_memory) {
  272. dbgln("\033[31;1mOut of memory\033[m, killing: {}", *this);
  273. } else {
  274. if (eip >= 0xc0000000 && g_kernel_symbols_available) {
  275. auto* symbol = symbolicate_kernel_address(eip);
  276. dbgln("\033[31;1m{:p} {} +{}\033[0m\n", eip, (symbol ? demangle(symbol->name) : "(k?)"), (symbol ? eip - symbol->address : 0));
  277. } else {
  278. dbgln("\033[31;1m{:p} (?)\033[0m\n", eip);
  279. }
  280. dump_backtrace();
  281. }
  282. {
  283. ProtectedDataMutationScope scope { *this };
  284. m_termination_signal = signal;
  285. }
  286. set_dump_core(!out_of_memory);
  287. space().dump_regions();
  288. VERIFY(is_user_process());
  289. die();
  290. // We can not return from here, as there is nowhere
  291. // to unwind to, so die right away.
  292. Thread::current()->die_if_needed();
  293. VERIFY_NOT_REACHED();
  294. }
  295. RefPtr<Process> Process::from_pid(ProcessID pid)
  296. {
  297. ScopedSpinLock lock(g_processes_lock);
  298. for (auto& process : *g_processes) {
  299. process.pid();
  300. if (process.pid() == pid)
  301. return &process;
  302. }
  303. return {};
  304. }
  305. RefPtr<FileDescription> Process::file_description(int fd) const
  306. {
  307. if (fd < 0)
  308. return nullptr;
  309. if (static_cast<size_t>(fd) < m_fds.size())
  310. return m_fds[fd].description();
  311. return nullptr;
  312. }
  313. int Process::fd_flags(int fd) const
  314. {
  315. if (fd < 0)
  316. return -1;
  317. if (static_cast<size_t>(fd) < m_fds.size())
  318. return m_fds[fd].flags();
  319. return -1;
  320. }
  321. int Process::number_of_open_file_descriptors() const
  322. {
  323. int count = 0;
  324. for (auto& description : m_fds) {
  325. if (description)
  326. ++count;
  327. }
  328. return count;
  329. }
  330. int Process::alloc_fd(int first_candidate_fd)
  331. {
  332. for (int i = first_candidate_fd; i < (int)m_max_open_file_descriptors; ++i) {
  333. if (!m_fds[i])
  334. return i;
  335. }
  336. return -EMFILE;
  337. }
  338. Time kgettimeofday()
  339. {
  340. return TimeManagement::now();
  341. }
  342. siginfo_t Process::wait_info()
  343. {
  344. siginfo_t siginfo {};
  345. siginfo.si_signo = SIGCHLD;
  346. siginfo.si_pid = pid().value();
  347. siginfo.si_uid = uid();
  348. if (m_termination_signal) {
  349. siginfo.si_status = m_termination_signal;
  350. siginfo.si_code = CLD_KILLED;
  351. } else {
  352. siginfo.si_status = m_termination_status;
  353. siginfo.si_code = CLD_EXITED;
  354. }
  355. return siginfo;
  356. }
  357. Custody& Process::current_directory()
  358. {
  359. if (!m_cwd)
  360. m_cwd = VFS::the().root_custody();
  361. return *m_cwd;
  362. }
  363. KResultOr<String> Process::get_syscall_path_argument(const char* user_path, size_t path_length) const
  364. {
  365. if (path_length == 0)
  366. return EINVAL;
  367. if (path_length > PATH_MAX)
  368. return ENAMETOOLONG;
  369. auto copied_string = copy_string_from_user(user_path, path_length);
  370. if (copied_string.is_null())
  371. return EFAULT;
  372. return copied_string;
  373. }
  374. KResultOr<String> Process::get_syscall_path_argument(const Syscall::StringArgument& path) const
  375. {
  376. return get_syscall_path_argument(path.characters, path.length);
  377. }
  378. bool Process::dump_core()
  379. {
  380. VERIFY(is_dumpable());
  381. VERIFY(should_core_dump());
  382. dbgln("Generating coredump for pid: {}", pid().value());
  383. auto coredump_path = String::formatted("/tmp/coredump/{}_{}_{}", name(), pid().value(), RTC::now());
  384. auto coredump = CoreDump::create(*this, coredump_path);
  385. if (!coredump)
  386. return false;
  387. return !coredump->write().is_error();
  388. }
  389. bool Process::dump_perfcore()
  390. {
  391. VERIFY(is_dumpable());
  392. VERIFY(m_perf_event_buffer);
  393. dbgln("Generating perfcore for pid: {}", pid().value());
  394. auto description_or_error = VFS::the().open(String::formatted("perfcore.{}", pid().value()), O_CREAT | O_EXCL, 0400, current_directory(), UidAndGid { uid(), gid() });
  395. if (description_or_error.is_error())
  396. return false;
  397. auto& description = description_or_error.value();
  398. KBufferBuilder builder;
  399. if (!m_perf_event_buffer->to_json(builder))
  400. return false;
  401. auto json = builder.build();
  402. if (!json)
  403. return false;
  404. auto json_buffer = UserOrKernelBuffer::for_kernel_buffer(json->data());
  405. return !description->write(json_buffer, json->size()).is_error();
  406. }
  407. void Process::finalize()
  408. {
  409. VERIFY(Thread::current() == g_finalizer);
  410. dbgln_if(PROCESS_DEBUG, "Finalizing process {}", *this);
  411. if (is_dumpable()) {
  412. if (m_should_dump_core)
  413. dump_core();
  414. if (m_perf_event_buffer)
  415. dump_perfcore();
  416. }
  417. m_threads_for_coredump.clear();
  418. if (m_alarm_timer)
  419. TimerQueue::the().cancel_timer(m_alarm_timer.release_nonnull());
  420. m_fds.clear();
  421. m_tty = nullptr;
  422. m_executable = nullptr;
  423. m_cwd = nullptr;
  424. m_root_directory = nullptr;
  425. m_root_directory_relative_to_global_root = nullptr;
  426. m_arguments.clear();
  427. m_environment.clear();
  428. m_dead = true;
  429. {
  430. // FIXME: PID/TID BUG
  431. if (auto parent_thread = Thread::from_tid(ppid().value())) {
  432. if (!(parent_thread->m_signal_action_data[SIGCHLD].flags & SA_NOCLDWAIT))
  433. parent_thread->send_signal(SIGCHLD, this);
  434. }
  435. }
  436. {
  437. ScopedSpinLock processses_lock(g_processes_lock);
  438. if (!!ppid()) {
  439. if (auto parent = Process::from_pid(ppid())) {
  440. parent->m_ticks_in_user_for_dead_children += m_ticks_in_user + m_ticks_in_user_for_dead_children;
  441. parent->m_ticks_in_kernel_for_dead_children += m_ticks_in_kernel + m_ticks_in_kernel_for_dead_children;
  442. }
  443. }
  444. }
  445. unblock_waiters(Thread::WaitBlocker::UnblockFlags::Terminated);
  446. m_space->remove_all_regions({});
  447. VERIFY(ref_count() > 0);
  448. // WaitBlockCondition::finalize will be in charge of dropping the last
  449. // reference if there are still waiters around, or whenever the last
  450. // waitable states are consumed. Unless there is no parent around
  451. // anymore, in which case we'll just drop it right away.
  452. m_wait_block_condition.finalize();
  453. }
  454. void Process::disowned_by_waiter(Process& process)
  455. {
  456. m_wait_block_condition.disowned_by_waiter(process);
  457. }
  458. void Process::unblock_waiters(Thread::WaitBlocker::UnblockFlags flags, u8 signal)
  459. {
  460. if (auto parent = Process::from_pid(ppid()))
  461. parent->m_wait_block_condition.unblock(*this, flags, signal);
  462. }
  463. void Process::die()
  464. {
  465. // Let go of the TTY, otherwise a slave PTY may keep the master PTY from
  466. // getting an EOF when the last process using the slave PTY dies.
  467. // If the master PTY owner relies on an EOF to know when to wait() on a
  468. // slave owner, we have to allow the PTY pair to be torn down.
  469. m_tty = nullptr;
  470. for_each_thread([&](auto& thread) {
  471. m_threads_for_coredump.append(thread);
  472. return IterationDecision::Continue;
  473. });
  474. {
  475. ScopedSpinLock lock(g_processes_lock);
  476. for (auto* process = g_processes->head(); process;) {
  477. auto* next_process = process->next();
  478. if (process->has_tracee_thread(pid())) {
  479. dbgln_if(PROCESS_DEBUG, "Process {} ({}) is attached by {} ({}) which will exit", process->name(), process->pid(), name(), pid());
  480. process->stop_tracing();
  481. auto err = process->send_signal(SIGSTOP, this);
  482. if (err.is_error())
  483. dbgln("Failed to send the SIGSTOP signal to {} ({})", process->name(), process->pid());
  484. }
  485. process = next_process;
  486. }
  487. }
  488. kill_all_threads();
  489. }
  490. void Process::terminate_due_to_signal(u8 signal)
  491. {
  492. VERIFY_INTERRUPTS_DISABLED();
  493. VERIFY(signal < 32);
  494. VERIFY(Process::current() == this);
  495. dbgln("Terminating {} due to signal {}", *this, signal);
  496. {
  497. ProtectedDataMutationScope scope { *this };
  498. m_termination_status = 0;
  499. m_termination_signal = signal;
  500. }
  501. die();
  502. }
  503. KResult Process::send_signal(u8 signal, Process* sender)
  504. {
  505. // Try to send it to the "obvious" main thread:
  506. auto receiver_thread = Thread::from_tid(pid().value());
  507. // If the main thread has died, there may still be other threads:
  508. if (!receiver_thread) {
  509. // The first one should be good enough.
  510. // Neither kill(2) nor kill(3) specify any selection precedure.
  511. for_each_thread([&receiver_thread](Thread& thread) -> IterationDecision {
  512. receiver_thread = &thread;
  513. return IterationDecision::Break;
  514. });
  515. }
  516. if (receiver_thread) {
  517. receiver_thread->send_signal(signal, sender);
  518. return KSuccess;
  519. }
  520. return ESRCH;
  521. }
  522. RefPtr<Thread> Process::create_kernel_thread(void (*entry)(void*), void* entry_data, u32 priority, const String& name, u32 affinity, bool joinable)
  523. {
  524. VERIFY((priority >= THREAD_PRIORITY_MIN) && (priority <= THREAD_PRIORITY_MAX));
  525. // FIXME: Do something with guard pages?
  526. auto thread_or_error = Thread::try_create(*this);
  527. if (thread_or_error.is_error())
  528. return {};
  529. auto thread = thread_or_error.release_value();
  530. thread->set_name(name);
  531. thread->set_affinity(affinity);
  532. thread->set_priority(priority);
  533. if (!joinable)
  534. thread->detach();
  535. auto& tss = thread->tss();
  536. tss.eip = (FlatPtr)entry;
  537. tss.esp = FlatPtr(entry_data); // entry function argument is expected to be in tss.esp
  538. ScopedSpinLock lock(g_scheduler_lock);
  539. thread->set_state(Thread::State::Runnable);
  540. return thread;
  541. }
  542. void Process::FileDescriptionAndFlags::clear()
  543. {
  544. m_description = nullptr;
  545. m_flags = 0;
  546. }
  547. void Process::FileDescriptionAndFlags::set(NonnullRefPtr<FileDescription>&& description, u32 flags)
  548. {
  549. m_description = move(description);
  550. m_flags = flags;
  551. }
  552. Custody& Process::root_directory()
  553. {
  554. if (!m_root_directory)
  555. m_root_directory = VFS::the().root_custody();
  556. return *m_root_directory;
  557. }
  558. Custody& Process::root_directory_relative_to_global_root()
  559. {
  560. if (!m_root_directory_relative_to_global_root)
  561. m_root_directory_relative_to_global_root = root_directory();
  562. return *m_root_directory_relative_to_global_root;
  563. }
  564. void Process::set_root_directory(const Custody& root)
  565. {
  566. m_root_directory = root;
  567. }
  568. void Process::set_tty(TTY* tty)
  569. {
  570. m_tty = tty;
  571. }
  572. void Process::start_tracing_from(ProcessID tracer)
  573. {
  574. m_tracer = ThreadTracer::create(tracer);
  575. }
  576. void Process::stop_tracing()
  577. {
  578. m_tracer = nullptr;
  579. }
  580. void Process::tracer_trap(Thread& thread, const RegisterState& regs)
  581. {
  582. VERIFY(m_tracer.ptr());
  583. m_tracer->set_regs(regs);
  584. thread.send_urgent_signal_to_self(SIGTRAP);
  585. }
  586. bool Process::create_perf_events_buffer_if_needed()
  587. {
  588. if (!m_perf_event_buffer) {
  589. m_perf_event_buffer = PerformanceEventBuffer::try_create_with_size(4 * MiB);
  590. m_perf_event_buffer->add_process(*this, ProcessEventType::Create);
  591. }
  592. return !!m_perf_event_buffer;
  593. }
  594. void Process::delete_perf_events_buffer()
  595. {
  596. if (m_perf_event_buffer)
  597. m_perf_event_buffer = nullptr;
  598. }
  599. bool Process::remove_thread(Thread& thread)
  600. {
  601. ProtectedDataMutationScope scope { *this };
  602. auto thread_cnt_before = m_thread_count.fetch_sub(1, AK::MemoryOrder::memory_order_acq_rel);
  603. VERIFY(thread_cnt_before != 0);
  604. ScopedSpinLock thread_list_lock(m_thread_list_lock);
  605. m_thread_list.remove(thread);
  606. return thread_cnt_before == 1;
  607. }
  608. bool Process::add_thread(Thread& thread)
  609. {
  610. ProtectedDataMutationScope scope { *this };
  611. bool is_first = m_thread_count.fetch_add(1, AK::MemoryOrder::memory_order_relaxed) == 0;
  612. ScopedSpinLock thread_list_lock(m_thread_list_lock);
  613. m_thread_list.append(thread);
  614. return is_first;
  615. }
  616. void Process::set_dumpable(bool dumpable)
  617. {
  618. if (dumpable == m_dumpable)
  619. return;
  620. ProtectedDataMutationScope scope { *this };
  621. m_dumpable = dumpable;
  622. }
  623. void Process::set_coredump_metadata(const String& key, String value)
  624. {
  625. m_coredump_metadata.set(key, move(value));
  626. }
  627. }