Process.cpp 22 KB

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