Process.cpp 22 KB

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