Process.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/StdLibExtras.h>
  7. #include <AK/StringBuilder.h>
  8. #include <AK/Time.h>
  9. #include <AK/Types.h>
  10. #include <Kernel/API/Syscall.h>
  11. #include <Kernel/Arch/x86/InterruptDisabler.h>
  12. #include <Kernel/CoreDump.h>
  13. #include <Kernel/Debug.h>
  14. #include <Kernel/Devices/NullDevice.h>
  15. #include <Kernel/FileSystem/Custody.h>
  16. #include <Kernel/FileSystem/FileDescription.h>
  17. #include <Kernel/FileSystem/VirtualFileSystem.h>
  18. #include <Kernel/KBufferBuilder.h>
  19. #include <Kernel/KSyms.h>
  20. #include <Kernel/Module.h>
  21. #include <Kernel/Panic.h>
  22. #include <Kernel/PerformanceEventBuffer.h>
  23. #include <Kernel/PerformanceManager.h>
  24. #include <Kernel/Process.h>
  25. #include <Kernel/ProcessExposed.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. void Process::register_new(Process& process)
  114. {
  115. // Note: this is essentially the same like process->ref()
  116. RefPtr<Process> new_process = process;
  117. ScopedSpinLock lock(g_processes_lock);
  118. g_processes->prepend(process);
  119. ProcFSComponentsRegistrar::the().register_new_process(process);
  120. }
  121. 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)
  122. {
  123. auto parts = path.split('/');
  124. if (arguments.is_empty()) {
  125. arguments.append(parts.last());
  126. }
  127. RefPtr<Custody> cwd;
  128. {
  129. ScopedSpinLock lock(g_processes_lock);
  130. if (auto parent = Process::from_pid(parent_pid)) {
  131. cwd = parent->m_cwd;
  132. }
  133. }
  134. if (!cwd)
  135. cwd = VFS::the().root_custody();
  136. auto process = Process::create(first_thread, parts.take_last(), uid, gid, parent_pid, false, move(cwd), nullptr, tty);
  137. if (!first_thread)
  138. return {};
  139. if (!process->m_fds.try_resize(process->m_fds.max_open())) {
  140. first_thread = nullptr;
  141. return {};
  142. }
  143. auto& device_to_use_as_tty = tty ? (CharacterDevice&)*tty : NullDevice::the();
  144. auto description = device_to_use_as_tty.open(O_RDWR).value();
  145. process->m_fds[0].set(*description);
  146. process->m_fds[1].set(*description);
  147. process->m_fds[2].set(*description);
  148. error = process->exec(path, move(arguments), move(environment));
  149. if (error != 0) {
  150. dbgln("Failed to exec {}: {}", path, error);
  151. first_thread = nullptr;
  152. return {};
  153. }
  154. register_new(*process);
  155. error = 0;
  156. return process;
  157. }
  158. RefPtr<Process> Process::create_kernel_process(RefPtr<Thread>& first_thread, String&& name, void (*entry)(void*), void* entry_data, u32 affinity)
  159. {
  160. auto process = Process::create(first_thread, move(name), (uid_t)0, (gid_t)0, ProcessID(0), true);
  161. if (!first_thread || !process)
  162. return {};
  163. #if ARCH(I386)
  164. first_thread->regs().eip = (FlatPtr)entry;
  165. first_thread->regs().esp = FlatPtr(entry_data); // entry function argument is expected to be in regs.esp
  166. #else
  167. first_thread->regs().rip = (FlatPtr)entry;
  168. first_thread->regs().rdi = FlatPtr(entry_data); // entry function argument is expected to be in regs.rdi
  169. #endif
  170. if (process->pid() != 0) {
  171. register_new(*process);
  172. }
  173. ScopedSpinLock lock(g_scheduler_lock);
  174. first_thread->set_affinity(affinity);
  175. first_thread->set_state(Thread::State::Runnable);
  176. return process;
  177. }
  178. void Process::protect_data()
  179. {
  180. m_protected_data_refs.unref([&]() {
  181. MM.set_page_writable_direct(VirtualAddress { this }, false);
  182. });
  183. }
  184. void Process::unprotect_data()
  185. {
  186. m_protected_data_refs.ref([&]() {
  187. MM.set_page_writable_direct(VirtualAddress { this }, true);
  188. });
  189. }
  190. 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)
  191. {
  192. auto process = adopt_ref_if_nonnull(new (nothrow) Process(name, uid, gid, ppid, is_kernel_process, move(cwd), move(executable), tty));
  193. if (!process)
  194. return {};
  195. auto result = process->attach_resources(first_thread, fork_parent);
  196. if (result.is_error())
  197. return {};
  198. return process;
  199. }
  200. 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)
  201. : m_name(move(name))
  202. , m_is_kernel_process(is_kernel_process)
  203. , m_executable(move(executable))
  204. , m_cwd(move(cwd))
  205. , m_tty(tty)
  206. , m_wait_block_condition(*this)
  207. {
  208. // Ensure that we protect the process data when exiting the constructor.
  209. ProtectedDataMutationScope scope { *this };
  210. m_pid = allocate_pid();
  211. m_ppid = ppid;
  212. m_uid = uid;
  213. m_gid = gid;
  214. m_euid = uid;
  215. m_egid = gid;
  216. m_suid = uid;
  217. m_sgid = gid;
  218. dbgln_if(PROCESS_DEBUG, "Created new process {}({})", m_name, this->pid().value());
  219. }
  220. KResult Process::attach_resources(RefPtr<Thread>& first_thread, Process* fork_parent)
  221. {
  222. m_space = Space::create(*this, fork_parent ? &fork_parent->space() : nullptr);
  223. if (!m_space)
  224. return ENOMEM;
  225. if (fork_parent) {
  226. // NOTE: fork() doesn't clone all threads; the thread that called fork() becomes the only thread in the new process.
  227. first_thread = Thread::current()->clone(*this);
  228. if (!first_thread)
  229. return ENOMEM;
  230. } else {
  231. // NOTE: This non-forked code path is only taken when the kernel creates a process "manually" (at boot.)
  232. auto thread_or_error = Thread::try_create(*this);
  233. if (thread_or_error.is_error())
  234. return thread_or_error.error();
  235. first_thread = thread_or_error.release_value();
  236. first_thread->detach();
  237. }
  238. return KSuccess;
  239. }
  240. Process::~Process()
  241. {
  242. unprotect_data();
  243. VERIFY(thread_count() == 0); // all threads should have been finalized
  244. VERIFY(!m_alarm_timer);
  245. PerformanceManager::add_process_exit_event(*this);
  246. {
  247. ScopedSpinLock processes_lock(g_processes_lock);
  248. if (m_list_node.is_in_list())
  249. g_processes->remove(*this);
  250. }
  251. }
  252. // Make sure the compiler doesn't "optimize away" this function:
  253. extern void signal_trampoline_dummy() __attribute__((used));
  254. void signal_trampoline_dummy()
  255. {
  256. #if ARCH(I386)
  257. // The trampoline preserves the current eax, pushes the signal code and
  258. // then calls the signal handler. We do this because, when interrupting a
  259. // blocking syscall, that syscall may return some special error code in eax;
  260. // This error code would likely be overwritten by the signal handler, so it's
  261. // necessary to preserve it here.
  262. asm(
  263. ".intel_syntax noprefix\n"
  264. "asm_signal_trampoline:\n"
  265. "push ebp\n"
  266. "mov ebp, esp\n"
  267. "push eax\n" // we have to store eax 'cause it might be the return value from a syscall
  268. "sub esp, 4\n" // align the stack to 16 bytes
  269. "mov eax, [ebp+12]\n" // push the signal code
  270. "push eax\n"
  271. "call [ebp+8]\n" // call the signal handler
  272. "add esp, 8\n"
  273. "mov eax, %P0\n"
  274. "int 0x82\n" // sigreturn syscall
  275. "asm_signal_trampoline_end:\n"
  276. ".att_syntax" ::"i"(Syscall::SC_sigreturn));
  277. #elif ARCH(X86_64)
  278. // The trampoline preserves the current rax, pushes the signal code and
  279. // then calls the signal handler. We do this because, when interrupting a
  280. // blocking syscall, that syscall may return some special error code in eax;
  281. // This error code would likely be overwritten by the signal handler, so it's
  282. // necessary to preserve it here.
  283. asm(
  284. ".intel_syntax noprefix\n"
  285. "asm_signal_trampoline:\n"
  286. "push rbp\n"
  287. "mov rbp, rsp\n"
  288. "push rax\n" // we have to store rax 'cause it might be the return value from a syscall
  289. "sub rsp, 8\n" // align the stack to 16 bytes
  290. "mov rdi, [rbp+24]\n" // push the signal code
  291. "call [rbp+16]\n" // call the signal handler
  292. "add rsp, 8\n"
  293. "mov rax, %P0\n"
  294. "int 0x82\n" // sigreturn syscall
  295. "asm_signal_trampoline_end:\n"
  296. ".att_syntax" ::"i"(Syscall::SC_sigreturn));
  297. #endif
  298. }
  299. extern "C" char const asm_signal_trampoline[];
  300. extern "C" char const asm_signal_trampoline_end[];
  301. void create_signal_trampoline()
  302. {
  303. // NOTE: We leak this region.
  304. g_signal_trampoline_region = MM.allocate_kernel_region(PAGE_SIZE, "Signal trampolines", Region::Access::Read | Region::Access::Write).leak_ptr();
  305. g_signal_trampoline_region->set_syscall_region(true);
  306. size_t trampoline_size = asm_signal_trampoline_end - asm_signal_trampoline;
  307. u8* code_ptr = (u8*)g_signal_trampoline_region->vaddr().as_ptr();
  308. memcpy(code_ptr, asm_signal_trampoline, trampoline_size);
  309. g_signal_trampoline_region->set_writable(false);
  310. g_signal_trampoline_region->remap();
  311. }
  312. void Process::crash(int signal, FlatPtr ip, bool out_of_memory)
  313. {
  314. VERIFY(!is_dead());
  315. VERIFY(Process::current() == this);
  316. if (out_of_memory) {
  317. dbgln("\033[31;1mOut of memory\033[m, killing: {}", *this);
  318. } else {
  319. if (ip >= KERNEL_BASE && g_kernel_symbols_available) {
  320. auto* symbol = symbolicate_kernel_address(ip);
  321. dbgln("\033[31;1m{:p} {} +{}\033[0m\n", ip, (symbol ? symbol->name : "(k?)"), (symbol ? ip - symbol->address : 0));
  322. } else {
  323. dbgln("\033[31;1m{:p} (?)\033[0m\n", ip);
  324. }
  325. dump_backtrace();
  326. }
  327. {
  328. ProtectedDataMutationScope scope { *this };
  329. m_termination_signal = signal;
  330. }
  331. set_dump_core(!out_of_memory);
  332. space().dump_regions();
  333. VERIFY(is_user_process());
  334. die();
  335. // We can not return from here, as there is nowhere
  336. // to unwind to, so die right away.
  337. Thread::current()->die_if_needed();
  338. VERIFY_NOT_REACHED();
  339. }
  340. RefPtr<Process> Process::from_pid(ProcessID pid)
  341. {
  342. ScopedSpinLock lock(g_processes_lock);
  343. for (auto& process : *g_processes) {
  344. process.pid();
  345. if (process.pid() == pid)
  346. return &process;
  347. }
  348. return {};
  349. }
  350. const Process::FileDescriptionAndFlags& Process::FileDescriptions::at(size_t i) const
  351. {
  352. ScopedSpinLock lock(m_fds_lock);
  353. return m_fds_metadatas[i];
  354. }
  355. Process::FileDescriptionAndFlags& Process::FileDescriptions::at(size_t i)
  356. {
  357. ScopedSpinLock lock(m_fds_lock);
  358. return m_fds_metadatas[i];
  359. }
  360. RefPtr<FileDescription> Process::FileDescriptions::file_description(int fd) const
  361. {
  362. ScopedSpinLock lock(m_fds_lock);
  363. if (fd < 0)
  364. return nullptr;
  365. if (static_cast<size_t>(fd) < m_fds_metadatas.size())
  366. return m_fds_metadatas[fd].description();
  367. return nullptr;
  368. }
  369. int Process::FileDescriptions::fd_flags(int fd) const
  370. {
  371. ScopedSpinLock lock(m_fds_lock);
  372. if (fd < 0)
  373. return -1;
  374. if (static_cast<size_t>(fd) < m_fds_metadatas.size())
  375. return m_fds_metadatas[fd].flags();
  376. return -1;
  377. }
  378. void Process::FileDescriptions::enumerate(Function<void(const FileDescriptionAndFlags&)> callback) const
  379. {
  380. ScopedSpinLock lock(m_fds_lock);
  381. for (auto& file_description_metadata : m_fds_metadatas) {
  382. callback(file_description_metadata);
  383. }
  384. }
  385. void Process::FileDescriptions::change_each(Function<void(FileDescriptionAndFlags&)> callback)
  386. {
  387. ScopedSpinLock lock(m_fds_lock);
  388. for (auto& file_description_metadata : m_fds_metadatas) {
  389. callback(file_description_metadata);
  390. }
  391. }
  392. size_t Process::FileDescriptions::open_count() const
  393. {
  394. size_t count = 0;
  395. enumerate([&](auto& file_description_metadata) {
  396. if (file_description_metadata.is_valid())
  397. ++count;
  398. });
  399. return count;
  400. }
  401. int Process::FileDescriptions::allocate(int first_candidate_fd)
  402. {
  403. ScopedSpinLock lock(m_fds_lock);
  404. for (size_t i = first_candidate_fd; i < max_open(); ++i) {
  405. if (!m_fds_metadatas[i])
  406. return i;
  407. }
  408. return -EMFILE;
  409. }
  410. Time kgettimeofday()
  411. {
  412. return TimeManagement::now();
  413. }
  414. siginfo_t Process::wait_info()
  415. {
  416. siginfo_t siginfo {};
  417. siginfo.si_signo = SIGCHLD;
  418. siginfo.si_pid = pid().value();
  419. siginfo.si_uid = uid();
  420. if (m_termination_signal) {
  421. siginfo.si_status = m_termination_signal;
  422. siginfo.si_code = CLD_KILLED;
  423. } else {
  424. siginfo.si_status = m_termination_status;
  425. siginfo.si_code = CLD_EXITED;
  426. }
  427. return siginfo;
  428. }
  429. Custody& Process::current_directory()
  430. {
  431. if (!m_cwd)
  432. m_cwd = VFS::the().root_custody();
  433. return *m_cwd;
  434. }
  435. KResultOr<NonnullOwnPtr<KString>> Process::get_syscall_path_argument(char const* user_path, size_t path_length) const
  436. {
  437. if (path_length == 0)
  438. return EINVAL;
  439. if (path_length > PATH_MAX)
  440. return ENAMETOOLONG;
  441. auto string_or_error = try_copy_kstring_from_user(user_path, path_length);
  442. if (string_or_error.is_error())
  443. return string_or_error.error();
  444. return string_or_error.release_value();
  445. }
  446. KResultOr<NonnullOwnPtr<KString>> Process::get_syscall_path_argument(Syscall::StringArgument const& path) const
  447. {
  448. return get_syscall_path_argument(path.characters, path.length);
  449. }
  450. bool Process::dump_core()
  451. {
  452. VERIFY(is_dumpable());
  453. VERIFY(should_core_dump());
  454. dbgln("Generating coredump for pid: {}", pid().value());
  455. auto coredump_path = String::formatted("/tmp/coredump/{}_{}_{}", name(), pid().value(), RTC::now());
  456. auto coredump = CoreDump::create(*this, coredump_path);
  457. if (!coredump)
  458. return false;
  459. return !coredump->write().is_error();
  460. }
  461. bool Process::dump_perfcore()
  462. {
  463. VERIFY(is_dumpable());
  464. VERIFY(m_perf_event_buffer);
  465. dbgln("Generating perfcore for pid: {}", pid().value());
  466. auto description_or_error = VFS::the().open(String::formatted("perfcore.{}", pid().value()), O_CREAT | O_EXCL, 0400, current_directory(), UidAndGid { uid(), gid() });
  467. if (description_or_error.is_error())
  468. return false;
  469. auto& description = description_or_error.value();
  470. KBufferBuilder builder;
  471. if (!m_perf_event_buffer->to_json(builder))
  472. return false;
  473. auto json = builder.build();
  474. if (!json)
  475. return false;
  476. auto json_buffer = UserOrKernelBuffer::for_kernel_buffer(json->data());
  477. if (description->write(json_buffer, json->size()).is_error())
  478. return false;
  479. dbgln("Wrote perfcore to {}", description->absolute_path());
  480. return true;
  481. }
  482. void Process::finalize()
  483. {
  484. VERIFY(Thread::current() == g_finalizer);
  485. dbgln_if(PROCESS_DEBUG, "Finalizing process {}", *this);
  486. if (is_dumpable()) {
  487. if (m_should_dump_core)
  488. dump_core();
  489. if (m_perf_event_buffer) {
  490. dump_perfcore();
  491. TimeManagement::the().disable_profile_timer();
  492. }
  493. }
  494. m_threads_for_coredump.clear();
  495. if (m_alarm_timer)
  496. TimerQueue::the().cancel_timer(m_alarm_timer.release_nonnull());
  497. m_fds.clear();
  498. m_tty = nullptr;
  499. m_executable = nullptr;
  500. m_cwd = nullptr;
  501. m_root_directory = nullptr;
  502. m_root_directory_relative_to_global_root = nullptr;
  503. m_arguments.clear();
  504. m_environment.clear();
  505. // Note: We need to remove the references from the ProcFS registrar
  506. // If we don't do it here, we can't drop the object later, and we can't
  507. // do this from the destructor because the state of the object doesn't
  508. // allow us to take references anymore.
  509. ProcFSComponentsRegistrar::the().unregister_process(*this);
  510. m_dead = true;
  511. {
  512. // FIXME: PID/TID BUG
  513. if (auto parent_thread = Thread::from_tid(ppid().value())) {
  514. if (!(parent_thread->m_signal_action_data[SIGCHLD].flags & SA_NOCLDWAIT))
  515. parent_thread->send_signal(SIGCHLD, this);
  516. }
  517. }
  518. {
  519. ScopedSpinLock processses_lock(g_processes_lock);
  520. if (!!ppid()) {
  521. if (auto parent = Process::from_pid(ppid())) {
  522. parent->m_ticks_in_user_for_dead_children += m_ticks_in_user + m_ticks_in_user_for_dead_children;
  523. parent->m_ticks_in_kernel_for_dead_children += m_ticks_in_kernel + m_ticks_in_kernel_for_dead_children;
  524. }
  525. }
  526. }
  527. unblock_waiters(Thread::WaitBlocker::UnblockFlags::Terminated);
  528. m_space->remove_all_regions({});
  529. VERIFY(ref_count() > 0);
  530. // WaitBlockCondition::finalize will be in charge of dropping the last
  531. // reference if there are still waiters around, or whenever the last
  532. // waitable states are consumed. Unless there is no parent around
  533. // anymore, in which case we'll just drop it right away.
  534. m_wait_block_condition.finalize();
  535. }
  536. void Process::disowned_by_waiter(Process& process)
  537. {
  538. m_wait_block_condition.disowned_by_waiter(process);
  539. }
  540. void Process::unblock_waiters(Thread::WaitBlocker::UnblockFlags flags, u8 signal)
  541. {
  542. if (auto parent = Process::from_pid(ppid()))
  543. parent->m_wait_block_condition.unblock(*this, flags, signal);
  544. }
  545. void Process::die()
  546. {
  547. // Let go of the TTY, otherwise a slave PTY may keep the master PTY from
  548. // getting an EOF when the last process using the slave PTY dies.
  549. // If the master PTY owner relies on an EOF to know when to wait() on a
  550. // slave owner, we have to allow the PTY pair to be torn down.
  551. m_tty = nullptr;
  552. VERIFY(m_threads_for_coredump.is_empty());
  553. for_each_thread([&](auto& thread) {
  554. m_threads_for_coredump.append(thread);
  555. });
  556. {
  557. ScopedSpinLock lock(g_processes_lock);
  558. for (auto it = g_processes->begin(); it != g_processes->end();) {
  559. auto& process = *it;
  560. ++it;
  561. if (process.has_tracee_thread(pid())) {
  562. dbgln_if(PROCESS_DEBUG, "Process {} ({}) is attached by {} ({}) which will exit", process.name(), process.pid(), name(), pid());
  563. process.stop_tracing();
  564. auto err = process.send_signal(SIGSTOP, this);
  565. if (err.is_error())
  566. dbgln("Failed to send the SIGSTOP signal to {} ({})", process.name(), process.pid());
  567. }
  568. }
  569. }
  570. kill_all_threads();
  571. }
  572. void Process::terminate_due_to_signal(u8 signal)
  573. {
  574. VERIFY_INTERRUPTS_DISABLED();
  575. VERIFY(signal < 32);
  576. VERIFY(Process::current() == this);
  577. dbgln("Terminating {} due to signal {}", *this, signal);
  578. {
  579. ProtectedDataMutationScope scope { *this };
  580. m_termination_status = 0;
  581. m_termination_signal = signal;
  582. }
  583. die();
  584. }
  585. KResult Process::send_signal(u8 signal, Process* sender)
  586. {
  587. // Try to send it to the "obvious" main thread:
  588. auto receiver_thread = Thread::from_tid(pid().value());
  589. // If the main thread has died, there may still be other threads:
  590. if (!receiver_thread) {
  591. // The first one should be good enough.
  592. // Neither kill(2) nor kill(3) specify any selection precedure.
  593. for_each_thread([&receiver_thread](Thread& thread) -> IterationDecision {
  594. receiver_thread = &thread;
  595. return IterationDecision::Break;
  596. });
  597. }
  598. if (receiver_thread) {
  599. receiver_thread->send_signal(signal, sender);
  600. return KSuccess;
  601. }
  602. return ESRCH;
  603. }
  604. RefPtr<Thread> Process::create_kernel_thread(void (*entry)(void*), void* entry_data, u32 priority, const String& name, u32 affinity, bool joinable)
  605. {
  606. VERIFY((priority >= THREAD_PRIORITY_MIN) && (priority <= THREAD_PRIORITY_MAX));
  607. // FIXME: Do something with guard pages?
  608. auto thread_or_error = Thread::try_create(*this);
  609. if (thread_or_error.is_error())
  610. return {};
  611. auto thread = thread_or_error.release_value();
  612. thread->set_name(name);
  613. thread->set_affinity(affinity);
  614. thread->set_priority(priority);
  615. if (!joinable)
  616. thread->detach();
  617. auto& regs = thread->regs();
  618. #if ARCH(I386)
  619. regs.eip = (FlatPtr)entry;
  620. regs.esp = FlatPtr(entry_data); // entry function argument is expected to be in regs.rsp
  621. #else
  622. regs.rip = (FlatPtr)entry;
  623. regs.rsp = FlatPtr(entry_data); // entry function argument is expected to be in regs.rsp
  624. #endif
  625. ScopedSpinLock lock(g_scheduler_lock);
  626. thread->set_state(Thread::State::Runnable);
  627. return thread;
  628. }
  629. void Process::FileDescriptionAndFlags::clear()
  630. {
  631. // FIXME: Verify Process::m_fds_lock is locked!
  632. m_description = nullptr;
  633. m_flags = 0;
  634. m_global_procfs_inode_index = 0;
  635. }
  636. void Process::FileDescriptionAndFlags::refresh_inode_index()
  637. {
  638. // FIXME: Verify Process::m_fds_lock is locked!
  639. m_global_procfs_inode_index = ProcFSComponentsRegistrar::the().allocate_inode_index();
  640. }
  641. void Process::FileDescriptionAndFlags::set(NonnullRefPtr<FileDescription>&& description, u32 flags)
  642. {
  643. // FIXME: Verify Process::m_fds_lock is locked!
  644. m_description = move(description);
  645. m_flags = flags;
  646. m_global_procfs_inode_index = ProcFSComponentsRegistrar::the().allocate_inode_index();
  647. }
  648. Custody& Process::root_directory()
  649. {
  650. if (!m_root_directory)
  651. m_root_directory = VFS::the().root_custody();
  652. return *m_root_directory;
  653. }
  654. Custody& Process::root_directory_relative_to_global_root()
  655. {
  656. if (!m_root_directory_relative_to_global_root)
  657. m_root_directory_relative_to_global_root = root_directory();
  658. return *m_root_directory_relative_to_global_root;
  659. }
  660. void Process::set_root_directory(const Custody& root)
  661. {
  662. m_root_directory = root;
  663. }
  664. void Process::set_tty(TTY* tty)
  665. {
  666. m_tty = tty;
  667. }
  668. KResult Process::start_tracing_from(ProcessID tracer)
  669. {
  670. auto thread_tracer = ThreadTracer::create(tracer);
  671. if (!thread_tracer)
  672. return ENOMEM;
  673. m_tracer = move(thread_tracer);
  674. return KSuccess;
  675. }
  676. void Process::stop_tracing()
  677. {
  678. m_tracer = nullptr;
  679. }
  680. void Process::tracer_trap(Thread& thread, const RegisterState& regs)
  681. {
  682. VERIFY(m_tracer.ptr());
  683. m_tracer->set_regs(regs);
  684. thread.send_urgent_signal_to_self(SIGTRAP);
  685. }
  686. bool Process::create_perf_events_buffer_if_needed()
  687. {
  688. if (!m_perf_event_buffer) {
  689. m_perf_event_buffer = PerformanceEventBuffer::try_create_with_size(4 * MiB);
  690. m_perf_event_buffer->add_process(*this, ProcessEventType::Create);
  691. }
  692. return !!m_perf_event_buffer;
  693. }
  694. void Process::delete_perf_events_buffer()
  695. {
  696. if (m_perf_event_buffer)
  697. m_perf_event_buffer = nullptr;
  698. }
  699. bool Process::remove_thread(Thread& thread)
  700. {
  701. ProtectedDataMutationScope scope { *this };
  702. auto thread_cnt_before = m_thread_count.fetch_sub(1, AK::MemoryOrder::memory_order_acq_rel);
  703. VERIFY(thread_cnt_before != 0);
  704. ScopedSpinLock thread_list_lock(m_thread_list_lock);
  705. m_thread_list.remove(thread);
  706. return thread_cnt_before == 1;
  707. }
  708. bool Process::add_thread(Thread& thread)
  709. {
  710. ProtectedDataMutationScope scope { *this };
  711. bool is_first = m_thread_count.fetch_add(1, AK::MemoryOrder::memory_order_relaxed) == 0;
  712. ScopedSpinLock thread_list_lock(m_thread_list_lock);
  713. m_thread_list.append(thread);
  714. return is_first;
  715. }
  716. void Process::set_dumpable(bool dumpable)
  717. {
  718. if (dumpable == m_dumpable)
  719. return;
  720. ProtectedDataMutationScope scope { *this };
  721. m_dumpable = dumpable;
  722. }
  723. void Process::set_coredump_metadata(const String& key, String value)
  724. {
  725. m_coredump_metadata.set(key, move(value));
  726. }
  727. }