Process.cpp 23 KB

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