Process.cpp 28 KB

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