Process.cpp 27 KB

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