Process.cpp 22 KB

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