Process.cpp 29 KB

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