Process.cpp 37 KB

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