Process.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146
  1. /*
  2. * Copyright (c) 2018-2023, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2023, Timon Kruiper <timonkruiper@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Singleton.h>
  8. #include <AK/StdLibExtras.h>
  9. #include <AK/Time.h>
  10. #include <AK/Types.h>
  11. #include <Kernel/API/Syscall.h>
  12. #include <Kernel/Coredump.h>
  13. #include <Kernel/Credentials.h>
  14. #include <Kernel/Debug.h>
  15. #include <Kernel/Devices/DeviceManagement.h>
  16. #include <Kernel/InterruptDisabler.h>
  17. #ifdef ENABLE_KERNEL_COVERAGE_COLLECTION
  18. # include <Kernel/Devices/KCOVDevice.h>
  19. #endif
  20. #include <Kernel/API/POSIX/errno.h>
  21. #include <Kernel/API/POSIX/sys/limits.h>
  22. #include <Kernel/Arch/PageDirectory.h>
  23. #include <Kernel/Devices/Generic/NullDevice.h>
  24. #include <Kernel/FileSystem/Custody.h>
  25. #include <Kernel/FileSystem/OpenFileDescription.h>
  26. #include <Kernel/FileSystem/VirtualFileSystem.h>
  27. #include <Kernel/KBufferBuilder.h>
  28. #include <Kernel/KSyms.h>
  29. #include <Kernel/Memory/AnonymousVMObject.h>
  30. #include <Kernel/Memory/SharedInodeVMObject.h>
  31. #include <Kernel/Panic.h>
  32. #include <Kernel/PerformanceEventBuffer.h>
  33. #include <Kernel/PerformanceManager.h>
  34. #include <Kernel/Process.h>
  35. #include <Kernel/Scheduler.h>
  36. #include <Kernel/Sections.h>
  37. #include <Kernel/StdLib.h>
  38. #include <Kernel/TTY/TTY.h>
  39. #include <Kernel/Thread.h>
  40. #include <Kernel/ThreadTracer.h>
  41. #include <Kernel/TimerQueue.h>
  42. namespace Kernel {
  43. static void create_signal_trampoline();
  44. extern ProcessID g_init_pid;
  45. RecursiveSpinlock<LockRank::None> g_profiling_lock {};
  46. static Atomic<pid_t> next_pid;
  47. static Singleton<SpinlockProtected<Process::AllProcessesList, LockRank::None>> s_all_instances;
  48. READONLY_AFTER_INIT Memory::Region* g_signal_trampoline_region;
  49. static Singleton<MutexProtected<OwnPtr<KString>>> s_hostname;
  50. MutexProtected<OwnPtr<KString>>& hostname()
  51. {
  52. return *s_hostname;
  53. }
  54. SpinlockProtected<Process::AllProcessesList, LockRank::None>& Process::all_instances()
  55. {
  56. return *s_all_instances;
  57. }
  58. ErrorOr<void> Process::for_each_in_same_jail(Function<ErrorOr<void>(Process&)> callback)
  59. {
  60. return Process::current().m_jail_process_list.with([&](auto const& list_ptr) -> ErrorOr<void> {
  61. ErrorOr<void> result {};
  62. if (list_ptr) {
  63. list_ptr->attached_processes().with([&](auto const& list) {
  64. for (auto& process : list) {
  65. result = callback(process);
  66. if (result.is_error())
  67. break;
  68. }
  69. });
  70. return result;
  71. }
  72. all_instances().with([&](auto const& list) {
  73. for (auto& process : list) {
  74. result = callback(process);
  75. if (result.is_error())
  76. break;
  77. }
  78. });
  79. return result;
  80. });
  81. }
  82. ErrorOr<void> Process::for_each_child_in_same_jail(Function<ErrorOr<void>(Process&)> callback)
  83. {
  84. ProcessID my_pid = pid();
  85. return m_jail_process_list.with([&](auto const& list_ptr) -> ErrorOr<void> {
  86. ErrorOr<void> result {};
  87. if (list_ptr) {
  88. list_ptr->attached_processes().with([&](auto const& list) {
  89. for (auto& process : list) {
  90. if (process.ppid() == my_pid || process.has_tracee_thread(pid()))
  91. result = callback(process);
  92. if (result.is_error())
  93. break;
  94. }
  95. });
  96. return result;
  97. }
  98. all_instances().with([&](auto const& list) {
  99. for (auto& process : list) {
  100. if (process.ppid() == my_pid || process.has_tracee_thread(pid()))
  101. result = callback(process);
  102. if (result.is_error())
  103. break;
  104. }
  105. });
  106. return result;
  107. });
  108. }
  109. ErrorOr<void> Process::for_each_in_pgrp_in_same_jail(ProcessGroupID pgid, Function<ErrorOr<void>(Process&)> callback)
  110. {
  111. return m_jail_process_list.with([&](auto const& list_ptr) -> ErrorOr<void> {
  112. ErrorOr<void> result {};
  113. if (list_ptr) {
  114. list_ptr->attached_processes().with([&](auto const& list) {
  115. for (auto& process : list) {
  116. if (!process.is_dead() && process.pgid() == pgid)
  117. result = callback(process);
  118. if (result.is_error())
  119. break;
  120. }
  121. });
  122. return result;
  123. }
  124. all_instances().with([&](auto const& list) {
  125. for (auto& process : list) {
  126. if (!process.is_dead() && process.pgid() == pgid)
  127. result = callback(process);
  128. if (result.is_error())
  129. break;
  130. }
  131. });
  132. return result;
  133. });
  134. }
  135. ProcessID Process::allocate_pid()
  136. {
  137. // Overflow is UB, and negative PIDs wreck havoc.
  138. // TODO: Handle PID overflow
  139. // For example: Use an Atomic<u32>, mask the most significant bit,
  140. // retry if PID is already taken as a PID, taken as a TID,
  141. // takes as a PGID, taken as a SID, or zero.
  142. return next_pid.fetch_add(1, AK::MemoryOrder::memory_order_acq_rel);
  143. }
  144. UNMAP_AFTER_INIT void Process::initialize()
  145. {
  146. next_pid.store(0, AK::MemoryOrder::memory_order_release);
  147. // Note: This is called before scheduling is initialized, and before APs are booted.
  148. // So we can "safely" bypass the lock here.
  149. reinterpret_cast<OwnPtr<KString>&>(hostname()) = KString::must_create("courage"sv);
  150. create_signal_trampoline();
  151. }
  152. void Process::kill_threads_except_self()
  153. {
  154. InterruptDisabler disabler;
  155. if (thread_count() <= 1)
  156. return;
  157. auto* current_thread = Thread::current();
  158. for_each_thread([&](Thread& thread) {
  159. if (&thread == current_thread)
  160. return;
  161. if (auto state = thread.state(); state == Thread::State::Dead
  162. || state == Thread::State::Dying)
  163. return;
  164. // We need to detach this thread in case it hasn't been joined
  165. thread.detach();
  166. thread.set_should_die();
  167. });
  168. u32 dropped_lock_count = 0;
  169. if (big_lock().force_unlock_exclusive_if_locked(dropped_lock_count) != LockMode::Unlocked)
  170. dbgln("Process {} big lock had {} locks", *this, dropped_lock_count);
  171. }
  172. void Process::kill_all_threads()
  173. {
  174. for_each_thread([&](Thread& thread) {
  175. // We need to detach this thread in case it hasn't been joined
  176. thread.detach();
  177. thread.set_should_die();
  178. });
  179. }
  180. void Process::register_new(Process& process)
  181. {
  182. // Note: this is essentially the same like process->ref()
  183. NonnullRefPtr<Process> const new_process = process;
  184. all_instances().with([&](auto& list) {
  185. list.prepend(process);
  186. });
  187. }
  188. ErrorOr<Process::ProcessAndFirstThread> Process::create_user_process(StringView path, UserID uid, GroupID gid, Vector<NonnullOwnPtr<KString>> arguments, Vector<NonnullOwnPtr<KString>> environment, RefPtr<TTY> tty)
  189. {
  190. auto parts = path.split_view('/');
  191. if (arguments.is_empty()) {
  192. auto last_part = TRY(KString::try_create(parts.last()));
  193. TRY(arguments.try_append(move(last_part)));
  194. }
  195. auto path_string = TRY(KString::try_create(path));
  196. auto name = TRY(KString::try_create(parts.last()));
  197. auto [process, first_thread] = TRY(Process::create(move(name), uid, gid, ProcessID(0), false, VirtualFileSystem::the().root_custody(), nullptr, tty));
  198. TRY(process->m_fds.with_exclusive([&](auto& fds) -> ErrorOr<void> {
  199. TRY(fds.try_resize(Process::OpenFileDescriptions::max_open()));
  200. auto& device_to_use_as_tty = tty ? (CharacterDevice&)*tty : DeviceManagement::the().null_device();
  201. auto description = TRY(device_to_use_as_tty.open(O_RDWR));
  202. auto setup_description = [&](int fd) {
  203. fds.m_fds_metadatas[fd].allocate();
  204. fds[fd].set(*description);
  205. };
  206. setup_description(0);
  207. setup_description(1);
  208. setup_description(2);
  209. return {};
  210. }));
  211. Thread* new_main_thread = nullptr;
  212. InterruptsState previous_interrupts_state = InterruptsState::Enabled;
  213. TRY(process->exec(move(path_string), move(arguments), move(environment), new_main_thread, previous_interrupts_state));
  214. register_new(*process);
  215. // NOTE: All user processes have a leaked ref on them. It's balanced by Thread::WaitBlockerSet::finalize().
  216. process->ref();
  217. {
  218. SpinlockLocker lock(g_scheduler_lock);
  219. new_main_thread->set_state(Thread::State::Runnable);
  220. }
  221. return ProcessAndFirstThread { move(process), move(first_thread) };
  222. }
  223. ErrorOr<Process::ProcessAndFirstThread> Process::create_kernel_process(NonnullOwnPtr<KString> name, void (*entry)(void*), void* entry_data, u32 affinity, RegisterProcess do_register)
  224. {
  225. auto process_and_first_thread = TRY(Process::create(move(name), UserID(0), GroupID(0), ProcessID(0), true));
  226. auto& process = *process_and_first_thread.process;
  227. auto& thread = *process_and_first_thread.first_thread;
  228. thread.regs().set_entry_function((FlatPtr)entry, (FlatPtr)entry_data);
  229. if (do_register == RegisterProcess::Yes)
  230. register_new(process);
  231. SpinlockLocker lock(g_scheduler_lock);
  232. thread.set_affinity(affinity);
  233. thread.set_state(Thread::State::Runnable);
  234. return process_and_first_thread;
  235. }
  236. void Process::protect_data()
  237. {
  238. m_protected_data_refs.unref([&]() {
  239. MM.set_page_writable_direct(VirtualAddress { &this->m_protected_values_do_not_access_directly }, false);
  240. });
  241. }
  242. void Process::unprotect_data()
  243. {
  244. m_protected_data_refs.ref([&]() {
  245. MM.set_page_writable_direct(VirtualAddress { &this->m_protected_values_do_not_access_directly }, true);
  246. });
  247. }
  248. ErrorOr<Process::ProcessAndFirstThread> Process::create(NonnullOwnPtr<KString> name, UserID uid, GroupID gid, ProcessID ppid, bool is_kernel_process, RefPtr<Custody> current_directory, RefPtr<Custody> executable, RefPtr<TTY> tty, Process* fork_parent)
  249. {
  250. auto unveil_tree = UnveilNode { TRY(KString::try_create("/"sv)), UnveilMetadata(TRY(KString::try_create("/"sv))) };
  251. auto exec_unveil_tree = UnveilNode { TRY(KString::try_create("/"sv)), UnveilMetadata(TRY(KString::try_create("/"sv))) };
  252. auto credentials = TRY(Credentials::create(uid, gid, uid, gid, uid, gid, {}, fork_parent ? fork_parent->sid() : 0, fork_parent ? fork_parent->pgid() : 0));
  253. auto process = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) Process(move(name), move(credentials), ppid, is_kernel_process, move(current_directory), move(executable), tty, move(unveil_tree), move(exec_unveil_tree))));
  254. OwnPtr<Memory::AddressSpace> new_address_space;
  255. if (fork_parent) {
  256. TRY(fork_parent->address_space().with([&](auto& parent_address_space) -> ErrorOr<void> {
  257. new_address_space = TRY(Memory::AddressSpace::try_create(*process, parent_address_space.ptr()));
  258. return {};
  259. }));
  260. } else {
  261. new_address_space = TRY(Memory::AddressSpace::try_create(*process, nullptr));
  262. }
  263. auto first_thread = TRY(process->attach_resources(new_address_space.release_nonnull(), fork_parent));
  264. return ProcessAndFirstThread { move(process), move(first_thread) };
  265. }
  266. Process::Process(NonnullOwnPtr<KString> name, NonnullRefPtr<Credentials> credentials, ProcessID ppid, bool is_kernel_process, RefPtr<Custody> current_directory, RefPtr<Custody> executable, RefPtr<TTY> tty, UnveilNode unveil_tree, UnveilNode exec_unveil_tree)
  267. : m_name(move(name))
  268. , m_is_kernel_process(is_kernel_process)
  269. , m_executable(move(executable))
  270. , m_current_directory(move(current_directory))
  271. , m_unveil_data(move(unveil_tree))
  272. , m_exec_unveil_data(move(exec_unveil_tree))
  273. , m_wait_blocker_set(*this)
  274. {
  275. // Ensure that we protect the process data when exiting the constructor.
  276. with_mutable_protected_data([&](auto& protected_data) {
  277. protected_data.pid = allocate_pid();
  278. protected_data.ppid = ppid;
  279. protected_data.credentials = move(credentials);
  280. protected_data.tty = move(tty);
  281. });
  282. if constexpr (PROCESS_DEBUG) {
  283. this->name().with([&](auto& process_name) {
  284. dbgln("Created new process {}({})", process_name->view(), this->pid().value());
  285. });
  286. }
  287. }
  288. ErrorOr<NonnullRefPtr<Thread>> Process::attach_resources(NonnullOwnPtr<Memory::AddressSpace>&& preallocated_space, Process* fork_parent)
  289. {
  290. m_space.with([&](auto& space) {
  291. space = move(preallocated_space);
  292. });
  293. auto create_first_thread = [&] {
  294. if (fork_parent) {
  295. // NOTE: fork() doesn't clone all threads; the thread that called fork() becomes the only thread in the new process.
  296. return Thread::current()->clone(*this);
  297. }
  298. // NOTE: This non-forked code path is only taken when the kernel creates a process "manually" (at boot.)
  299. return Thread::create(*this);
  300. };
  301. auto first_thread = TRY(create_first_thread());
  302. if (!fork_parent) {
  303. // FIXME: Figure out if this is really necessary.
  304. first_thread->detach();
  305. }
  306. // This is not actually explicitly verified by any official documentation,
  307. // but it's not listed anywhere as being cleared, and rsync expects it to work like this.
  308. if (fork_parent)
  309. m_signal_action_data = fork_parent->m_signal_action_data;
  310. return first_thread;
  311. }
  312. Process::~Process()
  313. {
  314. unprotect_data();
  315. VERIFY(thread_count() == 0); // all threads should have been finalized
  316. PerformanceManager::add_process_exit_event(*this);
  317. }
  318. // Make sure the compiler doesn't "optimize away" this function:
  319. extern void signal_trampoline_dummy() __attribute__((used));
  320. void signal_trampoline_dummy()
  321. {
  322. #if ARCH(X86_64)
  323. // The trampoline preserves the current rax, pushes the signal code and
  324. // then calls the signal handler. We do this because, when interrupting a
  325. // blocking syscall, that syscall may return some special error code in eax;
  326. // This error code would likely be overwritten by the signal handler, so it's
  327. // necessary to preserve it here.
  328. constexpr static auto offset_to_first_register_slot = sizeof(__ucontext) + sizeof(siginfo) + sizeof(FPUState) + 3 * sizeof(FlatPtr);
  329. asm(
  330. ".intel_syntax noprefix\n"
  331. ".globl asm_signal_trampoline\n"
  332. "asm_signal_trampoline:\n"
  333. // stack state: 0, ucontext, signal_info (alignment = 16), fpu_state (alignment = 16), ucontext*, siginfo*, signal, handler
  334. // Pop the handler into rcx
  335. "pop rcx\n" // save handler
  336. // we have to save rax 'cause it might be the return value from a syscall
  337. "mov [rsp+%P1], rax\n"
  338. // pop signal number into rdi (first param)
  339. "pop rdi\n"
  340. // pop siginfo* into rsi (second param)
  341. "pop rsi\n"
  342. // pop ucontext* into rdx (third param)
  343. "pop rdx\n"
  344. // Note that the stack is currently aligned to 16 bytes as we popped the extra entries above.
  345. // call the signal handler
  346. "call rcx\n"
  347. // Current stack state is just saved_rax, ucontext, signal_info, fpu_state.
  348. // syscall SC_sigreturn
  349. "mov rax, %P0\n"
  350. "syscall\n"
  351. ".globl asm_signal_trampoline_end\n"
  352. "asm_signal_trampoline_end:\n"
  353. ".att_syntax"
  354. :
  355. : "i"(Syscall::SC_sigreturn),
  356. "i"(offset_to_first_register_slot));
  357. #elif ARCH(AARCH64)
  358. constexpr static auto offset_to_first_register_slot = align_up_to(sizeof(__ucontext) + sizeof(siginfo) + sizeof(FPUState) + 3 * sizeof(FlatPtr), 16);
  359. asm(
  360. ".global asm_signal_trampoline\n"
  361. "asm_signal_trampoline:\n"
  362. // stack state: 0, ucontext, signal_info (alignment = 16), fpu_state (alignment = 16), ucontext*, siginfo*, signal, handler
  363. // Load the handler address into x3.
  364. "ldr x3, [sp, #0]\n"
  365. // Store x0 (return value from a syscall) into the register slot, such that we can return the correct value in sys$sigreturn.
  366. "str x0, [sp, %[offset_to_first_register_slot]]\n"
  367. // Load the signal number into the first argument.
  368. "ldr x0, [sp, #8]\n"
  369. // Load a pointer to the signal_info structure into the second argument.
  370. "ldr x1, [sp, #16]\n"
  371. // Load a pointer to the ucontext into the third argument.
  372. "ldr x2, [sp, #24]\n"
  373. // Pop the values off the stack.
  374. "add sp, sp, 32\n"
  375. // Call the signal handler.
  376. "blr x3\n"
  377. // Call sys$sigreturn.
  378. "mov x8, %[sigreturn_syscall_number]\n"
  379. "svc #0\n"
  380. // We should never return, so trap if we do return.
  381. "brk #0\n"
  382. "\n"
  383. ".global asm_signal_trampoline_end\n"
  384. "asm_signal_trampoline_end: \n" ::[sigreturn_syscall_number] "i"(Syscall::SC_sigreturn),
  385. [offset_to_first_register_slot] "i"(offset_to_first_register_slot));
  386. #else
  387. # error Unknown architecture
  388. #endif
  389. }
  390. extern "C" char const asm_signal_trampoline[];
  391. extern "C" char const asm_signal_trampoline_end[];
  392. void create_signal_trampoline()
  393. {
  394. // NOTE: We leak this region.
  395. g_signal_trampoline_region = MM.allocate_kernel_region(PAGE_SIZE, "Signal trampolines"sv, Memory::Region::Access::ReadWrite).release_value().leak_ptr();
  396. g_signal_trampoline_region->set_syscall_region(true);
  397. size_t trampoline_size = asm_signal_trampoline_end - asm_signal_trampoline;
  398. u8* code_ptr = (u8*)g_signal_trampoline_region->vaddr().as_ptr();
  399. memcpy(code_ptr, asm_signal_trampoline, trampoline_size);
  400. g_signal_trampoline_region->set_writable(false);
  401. g_signal_trampoline_region->remap();
  402. }
  403. void Process::crash(int signal, Optional<RegisterState const&> regs, bool out_of_memory)
  404. {
  405. VERIFY(!is_dead());
  406. VERIFY(&Process::current() == this);
  407. auto ip = regs.has_value() ? regs->ip() : 0;
  408. if (out_of_memory) {
  409. dbgln("\033[31;1mOut of memory\033[m, killing: {}", *this);
  410. } else {
  411. if (ip >= kernel_load_base && g_kernel_symbols_available) {
  412. auto const* symbol = symbolicate_kernel_address(ip);
  413. dbgln("\033[31;1m{:p} {} +{}\033[0m\n", ip, (symbol ? symbol->name : "(k?)"), (symbol ? ip - symbol->address : 0));
  414. } else {
  415. dbgln("\033[31;1m{:p} (?)\033[0m\n", ip);
  416. }
  417. #if ARCH(X86_64)
  418. constexpr bool userspace_backtrace = false;
  419. #elif ARCH(AARCH64)
  420. constexpr bool userspace_backtrace = true;
  421. #else
  422. # error "Unknown architecture"
  423. #endif
  424. if constexpr (userspace_backtrace) {
  425. dbgln("Userspace backtrace:");
  426. auto bp = regs.has_value() ? regs->bp() : 0;
  427. dump_backtrace_from_base_pointer(bp);
  428. }
  429. dbgln("Kernel backtrace:");
  430. dump_backtrace();
  431. }
  432. with_mutable_protected_data([&](auto& protected_data) {
  433. protected_data.termination_signal = signal;
  434. });
  435. set_should_generate_coredump(!out_of_memory);
  436. if constexpr (DUMP_REGIONS_ON_CRASH) {
  437. address_space().with([](auto& space) { space->dump_regions(); });
  438. }
  439. VERIFY(is_user_process());
  440. die();
  441. // We can not return from here, as there is nowhere
  442. // to unwind to, so die right away.
  443. Thread::current()->die_if_needed();
  444. VERIFY_NOT_REACHED();
  445. }
  446. RefPtr<Process> Process::from_pid_in_same_jail(ProcessID pid)
  447. {
  448. return Process::current().m_jail_process_list.with([&](auto const& list_ptr) -> RefPtr<Process> {
  449. if (list_ptr) {
  450. return list_ptr->attached_processes().with([&](auto const& list) -> RefPtr<Process> {
  451. for (auto& process : list) {
  452. if (process.pid() == pid) {
  453. return process;
  454. }
  455. }
  456. return {};
  457. });
  458. }
  459. return all_instances().with([&](auto const& list) -> RefPtr<Process> {
  460. for (auto& process : list) {
  461. if (process.pid() == pid) {
  462. return process;
  463. }
  464. }
  465. return {};
  466. });
  467. });
  468. }
  469. RefPtr<Process> Process::from_pid_ignoring_jails(ProcessID pid)
  470. {
  471. return all_instances().with([&](auto const& list) -> RefPtr<Process> {
  472. for (auto const& process : list) {
  473. if (process.pid() == pid)
  474. return &process;
  475. }
  476. return {};
  477. });
  478. }
  479. Process::OpenFileDescriptionAndFlags const* Process::OpenFileDescriptions::get_if_valid(size_t i) const
  480. {
  481. if (m_fds_metadatas.size() <= i)
  482. return nullptr;
  483. if (auto const& metadata = m_fds_metadatas[i]; metadata.is_valid())
  484. return &metadata;
  485. return nullptr;
  486. }
  487. Process::OpenFileDescriptionAndFlags* Process::OpenFileDescriptions::get_if_valid(size_t i)
  488. {
  489. if (m_fds_metadatas.size() <= i)
  490. return nullptr;
  491. if (auto& metadata = m_fds_metadatas[i]; metadata.is_valid())
  492. return &metadata;
  493. return nullptr;
  494. }
  495. Process::OpenFileDescriptionAndFlags const& Process::OpenFileDescriptions::at(size_t i) const
  496. {
  497. VERIFY(m_fds_metadatas[i].is_allocated());
  498. return m_fds_metadatas[i];
  499. }
  500. Process::OpenFileDescriptionAndFlags& Process::OpenFileDescriptions::at(size_t i)
  501. {
  502. VERIFY(m_fds_metadatas[i].is_allocated());
  503. return m_fds_metadatas[i];
  504. }
  505. ErrorOr<NonnullRefPtr<OpenFileDescription>> Process::OpenFileDescriptions::open_file_description(int fd) const
  506. {
  507. if (fd < 0)
  508. return EBADF;
  509. if (static_cast<size_t>(fd) >= m_fds_metadatas.size())
  510. return EBADF;
  511. RefPtr description = m_fds_metadatas[fd].description();
  512. if (!description)
  513. return EBADF;
  514. return description.release_nonnull();
  515. }
  516. void Process::OpenFileDescriptions::enumerate(Function<void(OpenFileDescriptionAndFlags const&)> callback) const
  517. {
  518. for (auto const& file_description_metadata : m_fds_metadatas) {
  519. callback(file_description_metadata);
  520. }
  521. }
  522. ErrorOr<void> Process::OpenFileDescriptions::try_enumerate(Function<ErrorOr<void>(OpenFileDescriptionAndFlags const&)> callback) const
  523. {
  524. for (auto const& file_description_metadata : m_fds_metadatas) {
  525. TRY(callback(file_description_metadata));
  526. }
  527. return {};
  528. }
  529. void Process::OpenFileDescriptions::change_each(Function<void(OpenFileDescriptionAndFlags&)> callback)
  530. {
  531. for (auto& file_description_metadata : m_fds_metadatas) {
  532. callback(file_description_metadata);
  533. }
  534. }
  535. size_t Process::OpenFileDescriptions::open_count() const
  536. {
  537. size_t count = 0;
  538. enumerate([&](auto& file_description_metadata) {
  539. if (file_description_metadata.is_valid())
  540. ++count;
  541. });
  542. return count;
  543. }
  544. ErrorOr<Process::ScopedDescriptionAllocation> Process::OpenFileDescriptions::allocate(int first_candidate_fd)
  545. {
  546. for (size_t i = first_candidate_fd; i < max_open(); ++i) {
  547. if (!m_fds_metadatas[i].is_allocated()) {
  548. m_fds_metadatas[i].allocate();
  549. return Process::ScopedDescriptionAllocation { static_cast<int>(i), &m_fds_metadatas[i] };
  550. }
  551. }
  552. return EMFILE;
  553. }
  554. Time kgettimeofday()
  555. {
  556. return TimeManagement::now();
  557. }
  558. siginfo_t Process::wait_info() const
  559. {
  560. auto credentials = this->credentials();
  561. siginfo_t siginfo {};
  562. siginfo.si_signo = SIGCHLD;
  563. siginfo.si_pid = pid().value();
  564. siginfo.si_uid = credentials->uid().value();
  565. with_protected_data([&](auto& protected_data) {
  566. if (protected_data.termination_signal != 0) {
  567. siginfo.si_status = protected_data.termination_signal;
  568. siginfo.si_code = CLD_KILLED;
  569. } else {
  570. siginfo.si_status = protected_data.termination_status;
  571. siginfo.si_code = CLD_EXITED;
  572. }
  573. });
  574. return siginfo;
  575. }
  576. NonnullRefPtr<Custody> Process::current_directory()
  577. {
  578. return m_current_directory.with([&](auto& current_directory) -> NonnullRefPtr<Custody> {
  579. if (!current_directory)
  580. current_directory = VirtualFileSystem::the().root_custody();
  581. return *current_directory;
  582. });
  583. }
  584. ErrorOr<NonnullOwnPtr<KString>> Process::get_syscall_path_argument(Userspace<char const*> user_path, size_t path_length)
  585. {
  586. if (path_length == 0)
  587. return EINVAL;
  588. if (path_length > PATH_MAX)
  589. return ENAMETOOLONG;
  590. return try_copy_kstring_from_user(user_path, path_length);
  591. }
  592. ErrorOr<NonnullOwnPtr<KString>> Process::get_syscall_path_argument(Syscall::StringArgument const& path)
  593. {
  594. Userspace<char const*> path_characters((FlatPtr)path.characters);
  595. return get_syscall_path_argument(path_characters, path.length);
  596. }
  597. ErrorOr<void> Process::dump_core()
  598. {
  599. VERIFY(is_dumpable());
  600. VERIFY(should_generate_coredump());
  601. dbgln("Generating coredump for pid: {}", pid().value());
  602. auto coredump_directory_path = TRY(Coredump::directory_path().with([&](auto& coredump_directory_path) -> ErrorOr<NonnullOwnPtr<KString>> {
  603. if (coredump_directory_path)
  604. return KString::try_create(coredump_directory_path->view());
  605. return KString::try_create(""sv);
  606. }));
  607. if (coredump_directory_path->view() == ""sv) {
  608. dbgln("Generating coredump for pid {} failed because coredump directory was not set.", pid().value());
  609. return {};
  610. }
  611. auto coredump_path = TRY(name().with([&](auto& process_name) {
  612. return KString::formatted("{}/{}_{}_{}", coredump_directory_path->view(), process_name->view(), pid().value(), kgettimeofday().to_truncated_seconds());
  613. }));
  614. auto coredump = TRY(Coredump::try_create(*this, coredump_path->view()));
  615. return coredump->write();
  616. }
  617. ErrorOr<void> Process::dump_perfcore()
  618. {
  619. VERIFY(is_dumpable());
  620. VERIFY(m_perf_event_buffer);
  621. dbgln("Generating perfcore for pid: {}", pid().value());
  622. // Try to generate a filename which isn't already used.
  623. auto base_filename = TRY(name().with([&](auto& process_name) {
  624. return KString::formatted("{}_{}", process_name->view(), pid().value());
  625. }));
  626. auto perfcore_filename = TRY(KString::formatted("{}.profile", base_filename));
  627. RefPtr<OpenFileDescription> description;
  628. auto credentials = this->credentials();
  629. for (size_t attempt = 1; attempt <= 10; ++attempt) {
  630. auto description_or_error = VirtualFileSystem::the().open(*this, credentials, perfcore_filename->view(), O_CREAT | O_EXCL, 0400, current_directory(), UidAndGid { 0, 0 });
  631. if (!description_or_error.is_error()) {
  632. description = description_or_error.release_value();
  633. break;
  634. }
  635. perfcore_filename = TRY(KString::formatted("{}.{}.profile", base_filename, attempt));
  636. }
  637. if (!description) {
  638. dbgln("Failed to generate perfcore for pid {}: Could not generate filename for the perfcore file.", pid().value());
  639. return EEXIST;
  640. }
  641. auto builder = TRY(KBufferBuilder::try_create());
  642. TRY(m_perf_event_buffer->to_json(builder));
  643. auto json = builder.build();
  644. if (!json) {
  645. dbgln("Failed to generate perfcore for pid {}: Could not allocate buffer.", pid().value());
  646. return ENOMEM;
  647. }
  648. auto json_buffer = UserOrKernelBuffer::for_kernel_buffer(json->data());
  649. TRY(description->write(json_buffer, json->size()));
  650. dbgln("Wrote perfcore for pid {} to {}", pid().value(), perfcore_filename);
  651. return {};
  652. }
  653. void Process::finalize()
  654. {
  655. VERIFY(Thread::current() == g_finalizer);
  656. dbgln_if(PROCESS_DEBUG, "Finalizing process {}", *this);
  657. if (veil_state() == VeilState::Dropped) {
  658. name().with([&](auto& process_name) {
  659. dbgln("\x1b[01;31mProcess '{}' exited with the veil left open\x1b[0m", process_name->view());
  660. });
  661. }
  662. if (g_init_pid != 0 && pid() == g_init_pid)
  663. PANIC("Init process quit unexpectedly. Exit code: {}", termination_status());
  664. if (is_dumpable()) {
  665. if (m_should_generate_coredump) {
  666. auto result = dump_core();
  667. if (result.is_error()) {
  668. dmesgln("Failed to write coredump for pid {}: {}", pid(), result.error());
  669. }
  670. }
  671. if (m_perf_event_buffer) {
  672. auto result = dump_perfcore();
  673. if (result.is_error())
  674. dmesgln("Failed to write perfcore for pid {}: {}", pid(), result.error());
  675. TimeManagement::the().disable_profile_timer();
  676. }
  677. }
  678. m_threads_for_coredump.clear();
  679. m_alarm_timer.with([&](auto& timer) {
  680. if (timer)
  681. TimerQueue::the().cancel_timer(timer.release_nonnull());
  682. });
  683. m_fds.with_exclusive([](auto& fds) { fds.clear(); });
  684. with_mutable_protected_data([&](auto& protected_data) { protected_data.tty = nullptr; });
  685. m_executable.with([](auto& executable) { executable = nullptr; });
  686. m_attached_jail.with([](auto& jail) {
  687. if (jail)
  688. jail->detach({});
  689. jail = nullptr;
  690. });
  691. m_arguments.clear();
  692. m_environment.clear();
  693. m_state.store(State::Dead, AK::MemoryOrder::memory_order_release);
  694. {
  695. if (auto parent_process = Process::from_pid_ignoring_jails(ppid())) {
  696. if (parent_process->is_user_process() && (parent_process->m_signal_action_data[SIGCHLD].flags & SA_NOCLDWAIT) != SA_NOCLDWAIT)
  697. (void)parent_process->send_signal(SIGCHLD, this);
  698. }
  699. }
  700. if (!!ppid()) {
  701. if (auto parent = Process::from_pid_ignoring_jails(ppid())) {
  702. parent->m_ticks_in_user_for_dead_children += m_ticks_in_user + m_ticks_in_user_for_dead_children;
  703. parent->m_ticks_in_kernel_for_dead_children += m_ticks_in_kernel + m_ticks_in_kernel_for_dead_children;
  704. }
  705. }
  706. unblock_waiters(Thread::WaitBlocker::UnblockFlags::Terminated);
  707. m_space.with([](auto& space) { space->remove_all_regions({}); });
  708. VERIFY(ref_count() > 0);
  709. // WaitBlockerSet::finalize will be in charge of dropping the last
  710. // reference if there are still waiters around, or whenever the last
  711. // waitable states are consumed. Unless there is no parent around
  712. // anymore, in which case we'll just drop it right away.
  713. m_wait_blocker_set.finalize();
  714. }
  715. void Process::disowned_by_waiter(Process& process)
  716. {
  717. m_wait_blocker_set.disowned_by_waiter(process);
  718. }
  719. void Process::unblock_waiters(Thread::WaitBlocker::UnblockFlags flags, u8 signal)
  720. {
  721. RefPtr<Process> waiter_process;
  722. if (auto* my_tracer = tracer())
  723. waiter_process = Process::from_pid_ignoring_jails(my_tracer->tracer_pid());
  724. else
  725. waiter_process = Process::from_pid_ignoring_jails(ppid());
  726. if (waiter_process)
  727. waiter_process->m_wait_blocker_set.unblock(*this, flags, signal);
  728. }
  729. void Process::remove_from_secondary_lists()
  730. {
  731. m_jail_process_list.with([this](auto& list_ptr) {
  732. if (list_ptr) {
  733. list_ptr->attached_processes().with([&](auto& list) {
  734. list.remove(*this);
  735. });
  736. }
  737. });
  738. }
  739. void Process::die()
  740. {
  741. auto expected = State::Running;
  742. if (!m_state.compare_exchange_strong(expected, State::Dying, AK::memory_order_acquire)) {
  743. // It's possible that another thread calls this at almost the same time
  744. // as we can't always instantly kill other threads (they may be blocked)
  745. // So if we already were called then other threads should stop running
  746. // momentarily and we only really need to service the first thread
  747. return;
  748. }
  749. // Let go of the TTY, otherwise a slave PTY may keep the master PTY from
  750. // getting an EOF when the last process using the slave PTY dies.
  751. // If the master PTY owner relies on an EOF to know when to wait() on a
  752. // slave owner, we have to allow the PTY pair to be torn down.
  753. with_mutable_protected_data([&](auto& protected_data) { protected_data.tty = nullptr; });
  754. VERIFY(m_threads_for_coredump.is_empty());
  755. for_each_thread([&](auto& thread) {
  756. auto result = m_threads_for_coredump.try_append(thread);
  757. if (result.is_error())
  758. dbgln("Failed to add thread {} to coredump due to OOM", thread.tid());
  759. });
  760. all_instances().with([&](auto const& list) {
  761. for (auto it = list.begin(); it != list.end();) {
  762. auto& process = *it;
  763. ++it;
  764. if (process.has_tracee_thread(pid())) {
  765. if constexpr (PROCESS_DEBUG) {
  766. process.name().with([&](auto& process_name) {
  767. name().with([&](auto& name) {
  768. dbgln("Process {} ({}) is attached by {} ({}) which will exit", process_name->view(), process.pid(), name->view(), pid());
  769. });
  770. });
  771. }
  772. process.stop_tracing();
  773. auto err = process.send_signal(SIGSTOP, this);
  774. if (err.is_error()) {
  775. process.name().with([&](auto& process_name) {
  776. dbgln("Failed to send the SIGSTOP signal to {} ({})", process_name->view(), process.pid());
  777. });
  778. }
  779. }
  780. }
  781. });
  782. kill_all_threads();
  783. #ifdef ENABLE_KERNEL_COVERAGE_COLLECTION
  784. KCOVDevice::free_process();
  785. #endif
  786. }
  787. void Process::terminate_due_to_signal(u8 signal)
  788. {
  789. VERIFY_INTERRUPTS_DISABLED();
  790. VERIFY(signal < NSIG);
  791. VERIFY(&Process::current() == this);
  792. dbgln("Terminating {} due to signal {}", *this, signal);
  793. with_mutable_protected_data([&](auto& protected_data) {
  794. protected_data.termination_status = 0;
  795. protected_data.termination_signal = signal;
  796. });
  797. die();
  798. }
  799. ErrorOr<void> Process::send_signal(u8 signal, Process* sender)
  800. {
  801. VERIFY(is_user_process());
  802. // Try to send it to the "obvious" main thread:
  803. auto receiver_thread = Thread::from_tid(pid().value());
  804. // If the main thread has died, there may still be other threads:
  805. if (!receiver_thread) {
  806. // The first one should be good enough.
  807. // Neither kill(2) nor kill(3) specify any selection procedure.
  808. for_each_thread([&receiver_thread](Thread& thread) -> IterationDecision {
  809. receiver_thread = &thread;
  810. return IterationDecision::Break;
  811. });
  812. }
  813. if (receiver_thread) {
  814. receiver_thread->send_signal(signal, sender);
  815. return {};
  816. }
  817. return ESRCH;
  818. }
  819. ErrorOr<NonnullRefPtr<Thread>> Process::create_kernel_thread(void (*entry)(void*), void* entry_data, u32 priority, NonnullOwnPtr<KString> name, u32 affinity, bool joinable)
  820. {
  821. VERIFY((priority >= THREAD_PRIORITY_MIN) && (priority <= THREAD_PRIORITY_MAX));
  822. // FIXME: Do something with guard pages?
  823. auto thread = TRY(Thread::create(*this));
  824. thread->set_name(move(name));
  825. thread->set_affinity(affinity);
  826. thread->set_priority(priority);
  827. if (!joinable)
  828. thread->detach();
  829. auto& regs = thread->regs();
  830. regs.set_ip((FlatPtr)entry);
  831. regs.set_sp((FlatPtr)entry_data); // entry function argument is expected to be in the SP register
  832. SpinlockLocker lock(g_scheduler_lock);
  833. thread->set_state(Thread::State::Runnable);
  834. return thread;
  835. }
  836. void Process::OpenFileDescriptionAndFlags::clear()
  837. {
  838. m_description = nullptr;
  839. m_flags = 0;
  840. }
  841. void Process::OpenFileDescriptionAndFlags::set(NonnullRefPtr<OpenFileDescription> description, u32 flags)
  842. {
  843. m_description = move(description);
  844. m_flags = flags;
  845. }
  846. RefPtr<TTY> Process::tty()
  847. {
  848. return with_protected_data([&](auto& protected_data) { return protected_data.tty; });
  849. }
  850. RefPtr<TTY const> Process::tty() const
  851. {
  852. return with_protected_data([&](auto& protected_data) { return protected_data.tty; });
  853. }
  854. void Process::set_tty(RefPtr<TTY> new_tty)
  855. {
  856. with_mutable_protected_data([&](auto& protected_data) { protected_data.tty = move(new_tty); });
  857. }
  858. ErrorOr<void> Process::start_tracing_from(ProcessID tracer)
  859. {
  860. m_tracer = TRY(ThreadTracer::try_create(tracer));
  861. return {};
  862. }
  863. void Process::stop_tracing()
  864. {
  865. m_tracer = nullptr;
  866. }
  867. void Process::tracer_trap(Thread& thread, RegisterState const& regs)
  868. {
  869. VERIFY(m_tracer.ptr());
  870. m_tracer->set_regs(regs);
  871. thread.send_urgent_signal_to_self(SIGTRAP);
  872. }
  873. bool Process::create_perf_events_buffer_if_needed()
  874. {
  875. if (m_perf_event_buffer)
  876. return true;
  877. m_perf_event_buffer = PerformanceEventBuffer::try_create_with_size(4 * MiB);
  878. if (!m_perf_event_buffer)
  879. return false;
  880. return !m_perf_event_buffer->add_process(*this, ProcessEventType::Create).is_error();
  881. }
  882. void Process::delete_perf_events_buffer()
  883. {
  884. if (m_perf_event_buffer)
  885. m_perf_event_buffer = nullptr;
  886. }
  887. bool Process::remove_thread(Thread& thread)
  888. {
  889. u32 thread_count_before = 0;
  890. thread_list().with([&](auto& thread_list) {
  891. thread_list.remove(thread);
  892. with_mutable_protected_data([&](auto& protected_data) {
  893. thread_count_before = protected_data.thread_count.fetch_sub(1, AK::MemoryOrder::memory_order_acq_rel);
  894. VERIFY(thread_count_before != 0);
  895. });
  896. });
  897. return thread_count_before == 1;
  898. }
  899. bool Process::add_thread(Thread& thread)
  900. {
  901. bool is_first = false;
  902. thread_list().with([&](auto& thread_list) {
  903. thread_list.append(thread);
  904. with_mutable_protected_data([&](auto& protected_data) {
  905. is_first = protected_data.thread_count.fetch_add(1, AK::MemoryOrder::memory_order_relaxed) == 0;
  906. });
  907. });
  908. return is_first;
  909. }
  910. ErrorOr<void> Process::set_coredump_property(NonnullOwnPtr<KString> key, NonnullOwnPtr<KString> value)
  911. {
  912. return m_coredump_properties.with([&](auto& coredump_properties) -> ErrorOr<void> {
  913. // Write it into the first available property slot.
  914. for (auto& slot : coredump_properties) {
  915. if (slot.key)
  916. continue;
  917. slot.key = move(key);
  918. slot.value = move(value);
  919. return {};
  920. }
  921. return ENOBUFS;
  922. });
  923. }
  924. ErrorOr<void> Process::try_set_coredump_property(StringView key, StringView value)
  925. {
  926. auto key_kstring = TRY(KString::try_create(key));
  927. auto value_kstring = TRY(KString::try_create(value));
  928. return set_coredump_property(move(key_kstring), move(value_kstring));
  929. };
  930. static constexpr StringView to_string(Pledge promise)
  931. {
  932. #define __ENUMERATE_PLEDGE_PROMISE(x) \
  933. case Pledge::x: \
  934. return #x##sv;
  935. switch (promise) {
  936. ENUMERATE_PLEDGE_PROMISES
  937. }
  938. #undef __ENUMERATE_PLEDGE_PROMISE
  939. VERIFY_NOT_REACHED();
  940. }
  941. ErrorOr<void> Process::require_no_promises() const
  942. {
  943. if (!has_promises())
  944. return {};
  945. dbgln("Has made a promise");
  946. Thread::current()->set_promise_violation_pending(true);
  947. return EPROMISEVIOLATION;
  948. }
  949. ErrorOr<void> Process::require_promise(Pledge promise)
  950. {
  951. if (!has_promises())
  952. return {};
  953. if (has_promised(promise))
  954. return {};
  955. dbgln("Has not pledged {}", to_string(promise));
  956. Thread::current()->set_promise_violation_pending(true);
  957. (void)try_set_coredump_property("pledge_violation"sv, to_string(promise));
  958. return EPROMISEVIOLATION;
  959. }
  960. NonnullRefPtr<Credentials> Process::credentials() const
  961. {
  962. return with_protected_data([&](auto& protected_data) -> NonnullRefPtr<Credentials> {
  963. return *protected_data.credentials;
  964. });
  965. }
  966. RefPtr<Custody> Process::executable()
  967. {
  968. return m_executable.with([](auto& executable) { return executable; });
  969. }
  970. RefPtr<Custody const> Process::executable() const
  971. {
  972. return m_executable.with([](auto& executable) { return executable; });
  973. }
  974. ErrorOr<NonnullRefPtr<Custody>> Process::custody_for_dirfd(int dirfd)
  975. {
  976. if (dirfd == AT_FDCWD)
  977. return current_directory();
  978. auto description = TRY(open_file_description(dirfd));
  979. if (!description->custody())
  980. return EINVAL;
  981. if (!description->is_directory())
  982. return ENOTDIR;
  983. return *description->custody();
  984. }
  985. SpinlockProtected<NonnullOwnPtr<KString>, LockRank::None> const& Process::name() const
  986. {
  987. return m_name;
  988. }
  989. void Process::set_name(NonnullOwnPtr<KString> name)
  990. {
  991. m_name.with([&](auto& this_name) {
  992. this_name = move(name);
  993. });
  994. }
  995. }