Process.cpp 26 KB

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