Process.cpp 28 KB

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