Process.cpp 41 KB

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