Process.cpp 29 KB

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