Process.cpp 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  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/Arch/PageDirectory.h>
  22. #include <Kernel/Devices/NullDevice.h>
  23. #include <Kernel/FileSystem/Custody.h>
  24. #include <Kernel/FileSystem/OpenFileDescription.h>
  25. #include <Kernel/FileSystem/VirtualFileSystem.h>
  26. #include <Kernel/KBufferBuilder.h>
  27. #include <Kernel/KSyms.h>
  28. #include <Kernel/Memory/AnonymousVMObject.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, Vector<NonnullOwnPtr<KString>> arguments, Vector<NonnullOwnPtr<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. InterruptsState previous_interrupts_state = InterruptsState::Enabled;
  221. if (auto result = process->exec(move(path_string), move(arguments), move(environment), new_main_thread, previous_interrupts_state); 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. if constexpr (PROCESS_DEBUG) {
  296. this->name().with([&](auto& process_name) {
  297. dbgln("Created new process {}({})", process_name->view(), this->pid().value());
  298. });
  299. }
  300. }
  301. ErrorOr<void> Process::attach_resources(NonnullOwnPtr<Memory::AddressSpace>&& preallocated_space, LockRefPtr<Thread>& first_thread, Process* fork_parent)
  302. {
  303. m_space.with([&](auto& space) {
  304. space = move(preallocated_space);
  305. });
  306. auto create_first_thread = [&] {
  307. if (fork_parent) {
  308. // NOTE: fork() doesn't clone all threads; the thread that called fork() becomes the only thread in the new process.
  309. return Thread::current()->try_clone(*this);
  310. }
  311. // NOTE: This non-forked code path is only taken when the kernel creates a process "manually" (at boot.)
  312. return Thread::try_create(*this);
  313. };
  314. first_thread = TRY(create_first_thread());
  315. if (!fork_parent) {
  316. // FIXME: Figure out if this is really necessary.
  317. first_thread->detach();
  318. }
  319. // This is not actually explicitly verified by any official documentation,
  320. // but it's not listed anywhere as being cleared, and rsync expects it to work like this.
  321. if (fork_parent)
  322. m_signal_action_data = fork_parent->m_signal_action_data;
  323. return {};
  324. }
  325. Process::~Process()
  326. {
  327. unprotect_data();
  328. VERIFY(thread_count() == 0); // all threads should have been finalized
  329. VERIFY(!m_alarm_timer);
  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. asm(
  373. ".global asm_signal_trampoline\n"
  374. "asm_signal_trampoline:\n"
  375. // TODO: Implement this when we support userspace for aarch64
  376. "wfi\n"
  377. "\n"
  378. ".global asm_signal_trampoline_end\n"
  379. "asm_signal_trampoline_end: \n");
  380. #else
  381. # error Unknown architecture
  382. #endif
  383. }
  384. extern "C" char const asm_signal_trampoline[];
  385. extern "C" char const asm_signal_trampoline_end[];
  386. void create_signal_trampoline()
  387. {
  388. // NOTE: We leak this region.
  389. g_signal_trampoline_region = MM.allocate_kernel_region(PAGE_SIZE, "Signal trampolines"sv, Memory::Region::Access::ReadWrite).release_value().leak_ptr();
  390. g_signal_trampoline_region->set_syscall_region(true);
  391. size_t trampoline_size = asm_signal_trampoline_end - asm_signal_trampoline;
  392. u8* code_ptr = (u8*)g_signal_trampoline_region->vaddr().as_ptr();
  393. memcpy(code_ptr, asm_signal_trampoline, trampoline_size);
  394. g_signal_trampoline_region->set_writable(false);
  395. g_signal_trampoline_region->remap();
  396. }
  397. void Process::crash(int signal, Optional<RegisterState const&> regs, bool out_of_memory)
  398. {
  399. VERIFY(!is_dead());
  400. VERIFY(&Process::current() == this);
  401. auto ip = regs.has_value() ? regs->ip() : 0;
  402. if (out_of_memory) {
  403. dbgln("\033[31;1mOut of memory\033[m, killing: {}", *this);
  404. } else {
  405. if (ip >= kernel_load_base && g_kernel_symbols_available) {
  406. auto const* symbol = symbolicate_kernel_address(ip);
  407. dbgln("\033[31;1m{:p} {} +{}\033[0m\n", ip, (symbol ? symbol->name : "(k?)"), (symbol ? ip - symbol->address : 0));
  408. } else {
  409. dbgln("\033[31;1m{:p} (?)\033[0m\n", ip);
  410. }
  411. #if ARCH(X86_64)
  412. constexpr bool userspace_backtrace = false;
  413. #elif ARCH(AARCH64)
  414. constexpr bool userspace_backtrace = true;
  415. #else
  416. # error "Unknown architecture"
  417. #endif
  418. if constexpr (userspace_backtrace) {
  419. dbgln("Userspace backtrace:");
  420. auto bp = regs.has_value() ? regs->bp() : 0;
  421. dump_backtrace_from_base_pointer(bp);
  422. }
  423. dbgln("Kernel backtrace:");
  424. dump_backtrace();
  425. }
  426. with_mutable_protected_data([&](auto& protected_data) {
  427. protected_data.termination_signal = signal;
  428. });
  429. set_should_generate_coredump(!out_of_memory);
  430. if constexpr (DUMP_REGIONS_ON_CRASH) {
  431. address_space().with([](auto& space) { space->dump_regions(); });
  432. }
  433. VERIFY(is_user_process());
  434. die();
  435. // We can not return from here, as there is nowhere
  436. // to unwind to, so die right away.
  437. Thread::current()->die_if_needed();
  438. VERIFY_NOT_REACHED();
  439. }
  440. LockRefPtr<Process> Process::from_pid_in_same_jail(ProcessID pid)
  441. {
  442. return Process::current().jail().with([&](auto const& my_jail) -> LockRefPtr<Process> {
  443. return all_instances().with([&](auto const& list) -> LockRefPtr<Process> {
  444. if (!my_jail) {
  445. for (auto& process : list) {
  446. if (process.pid() == pid) {
  447. return process;
  448. }
  449. }
  450. } else {
  451. for (auto& process : list) {
  452. if (process.pid() == pid) {
  453. return process.jail().with([&](auto const& other_process_jail) -> LockRefPtr<Process> {
  454. if (other_process_jail.ptr() == my_jail.ptr())
  455. return process;
  456. return {};
  457. });
  458. }
  459. }
  460. }
  461. return {};
  462. });
  463. });
  464. }
  465. LockRefPtr<Process> Process::from_pid_ignoring_jails(ProcessID pid)
  466. {
  467. return all_instances().with([&](auto const& list) -> LockRefPtr<Process> {
  468. for (auto const& process : list) {
  469. if (process.pid() == pid)
  470. return &process;
  471. }
  472. return {};
  473. });
  474. }
  475. Process::OpenFileDescriptionAndFlags const* Process::OpenFileDescriptions::get_if_valid(size_t i) const
  476. {
  477. if (m_fds_metadatas.size() <= i)
  478. return nullptr;
  479. if (auto const& metadata = m_fds_metadatas[i]; metadata.is_valid())
  480. return &metadata;
  481. return nullptr;
  482. }
  483. Process::OpenFileDescriptionAndFlags* Process::OpenFileDescriptions::get_if_valid(size_t i)
  484. {
  485. if (m_fds_metadatas.size() <= i)
  486. return nullptr;
  487. if (auto& metadata = m_fds_metadatas[i]; metadata.is_valid())
  488. return &metadata;
  489. return nullptr;
  490. }
  491. Process::OpenFileDescriptionAndFlags const& Process::OpenFileDescriptions::at(size_t i) const
  492. {
  493. VERIFY(m_fds_metadatas[i].is_allocated());
  494. return m_fds_metadatas[i];
  495. }
  496. Process::OpenFileDescriptionAndFlags& Process::OpenFileDescriptions::at(size_t i)
  497. {
  498. VERIFY(m_fds_metadatas[i].is_allocated());
  499. return m_fds_metadatas[i];
  500. }
  501. ErrorOr<NonnullLockRefPtr<OpenFileDescription>> Process::OpenFileDescriptions::open_file_description(int fd) const
  502. {
  503. if (fd < 0)
  504. return EBADF;
  505. if (static_cast<size_t>(fd) >= m_fds_metadatas.size())
  506. return EBADF;
  507. LockRefPtr description = m_fds_metadatas[fd].description();
  508. if (!description)
  509. return EBADF;
  510. return description.release_nonnull();
  511. }
  512. void Process::OpenFileDescriptions::enumerate(Function<void(OpenFileDescriptionAndFlags const&)> callback) const
  513. {
  514. for (auto const& file_description_metadata : m_fds_metadatas) {
  515. callback(file_description_metadata);
  516. }
  517. }
  518. ErrorOr<void> Process::OpenFileDescriptions::try_enumerate(Function<ErrorOr<void>(OpenFileDescriptionAndFlags const&)> callback) const
  519. {
  520. for (auto const& file_description_metadata : m_fds_metadatas) {
  521. TRY(callback(file_description_metadata));
  522. }
  523. return {};
  524. }
  525. void Process::OpenFileDescriptions::change_each(Function<void(OpenFileDescriptionAndFlags&)> callback)
  526. {
  527. for (auto& file_description_metadata : m_fds_metadatas) {
  528. callback(file_description_metadata);
  529. }
  530. }
  531. size_t Process::OpenFileDescriptions::open_count() const
  532. {
  533. size_t count = 0;
  534. enumerate([&](auto& file_description_metadata) {
  535. if (file_description_metadata.is_valid())
  536. ++count;
  537. });
  538. return count;
  539. }
  540. ErrorOr<Process::ScopedDescriptionAllocation> Process::OpenFileDescriptions::allocate(int first_candidate_fd)
  541. {
  542. for (size_t i = first_candidate_fd; i < max_open(); ++i) {
  543. if (!m_fds_metadatas[i].is_allocated()) {
  544. m_fds_metadatas[i].allocate();
  545. return Process::ScopedDescriptionAllocation { static_cast<int>(i), &m_fds_metadatas[i] };
  546. }
  547. }
  548. return EMFILE;
  549. }
  550. Time kgettimeofday()
  551. {
  552. return TimeManagement::now();
  553. }
  554. siginfo_t Process::wait_info() const
  555. {
  556. auto credentials = this->credentials();
  557. siginfo_t siginfo {};
  558. siginfo.si_signo = SIGCHLD;
  559. siginfo.si_pid = pid().value();
  560. siginfo.si_uid = credentials->uid().value();
  561. with_protected_data([&](auto& protected_data) {
  562. if (protected_data.termination_signal != 0) {
  563. siginfo.si_status = protected_data.termination_signal;
  564. siginfo.si_code = CLD_KILLED;
  565. } else {
  566. siginfo.si_status = protected_data.termination_status;
  567. siginfo.si_code = CLD_EXITED;
  568. }
  569. });
  570. return siginfo;
  571. }
  572. NonnullRefPtr<Custody> Process::current_directory()
  573. {
  574. return m_current_directory.with([&](auto& current_directory) -> NonnullRefPtr<Custody> {
  575. if (!current_directory)
  576. current_directory = VirtualFileSystem::the().root_custody();
  577. return *current_directory;
  578. });
  579. }
  580. ErrorOr<NonnullOwnPtr<KString>> Process::get_syscall_path_argument(Userspace<char const*> user_path, size_t path_length)
  581. {
  582. if (path_length == 0)
  583. return EINVAL;
  584. if (path_length > PATH_MAX)
  585. return ENAMETOOLONG;
  586. return try_copy_kstring_from_user(user_path, path_length);
  587. }
  588. ErrorOr<NonnullOwnPtr<KString>> Process::get_syscall_path_argument(Syscall::StringArgument const& path)
  589. {
  590. Userspace<char const*> path_characters((FlatPtr)path.characters);
  591. return get_syscall_path_argument(path_characters, path.length);
  592. }
  593. ErrorOr<void> Process::dump_core()
  594. {
  595. VERIFY(is_dumpable());
  596. VERIFY(should_generate_coredump());
  597. dbgln("Generating coredump for pid: {}", pid().value());
  598. auto coredump_directory_path = TRY(Coredump::directory_path().with([&](auto& coredump_directory_path) -> ErrorOr<NonnullOwnPtr<KString>> {
  599. if (coredump_directory_path)
  600. return KString::try_create(coredump_directory_path->view());
  601. return KString::try_create(""sv);
  602. }));
  603. if (coredump_directory_path->view() == ""sv) {
  604. dbgln("Generating coredump for pid {} failed because coredump directory was not set.", pid().value());
  605. return {};
  606. }
  607. auto coredump_path = TRY(name().with([&](auto& process_name) {
  608. return KString::formatted("{}/{}_{}_{}", coredump_directory_path->view(), process_name->view(), pid().value(), kgettimeofday().to_truncated_seconds());
  609. }));
  610. auto coredump = TRY(Coredump::try_create(*this, coredump_path->view()));
  611. return coredump->write();
  612. }
  613. ErrorOr<void> Process::dump_perfcore()
  614. {
  615. VERIFY(is_dumpable());
  616. VERIFY(m_perf_event_buffer);
  617. dbgln("Generating perfcore for pid: {}", pid().value());
  618. // Try to generate a filename which isn't already used.
  619. auto base_filename = TRY(name().with([&](auto& process_name) {
  620. return KString::formatted("{}_{}", process_name->view(), pid().value());
  621. }));
  622. auto perfcore_filename = TRY(KString::formatted("{}.profile", base_filename));
  623. LockRefPtr<OpenFileDescription> description;
  624. auto credentials = this->credentials();
  625. for (size_t attempt = 1; attempt <= 10; ++attempt) {
  626. auto description_or_error = VirtualFileSystem::the().open(*this, credentials, perfcore_filename->view(), O_CREAT | O_EXCL, 0400, current_directory(), UidAndGid { 0, 0 });
  627. if (!description_or_error.is_error()) {
  628. description = description_or_error.release_value();
  629. break;
  630. }
  631. perfcore_filename = TRY(KString::formatted("{}.{}.profile", base_filename, attempt));
  632. }
  633. if (!description) {
  634. dbgln("Failed to generate perfcore for pid {}: Could not generate filename for the perfcore file.", pid().value());
  635. return EEXIST;
  636. }
  637. auto builder = TRY(KBufferBuilder::try_create());
  638. TRY(m_perf_event_buffer->to_json(builder));
  639. auto json = builder.build();
  640. if (!json) {
  641. dbgln("Failed to generate perfcore for pid {}: Could not allocate buffer.", pid().value());
  642. return ENOMEM;
  643. }
  644. auto json_buffer = UserOrKernelBuffer::for_kernel_buffer(json->data());
  645. TRY(description->write(json_buffer, json->size()));
  646. dbgln("Wrote perfcore for pid {} to {}", pid().value(), perfcore_filename);
  647. return {};
  648. }
  649. void Process::finalize()
  650. {
  651. VERIFY(Thread::current() == g_finalizer);
  652. dbgln_if(PROCESS_DEBUG, "Finalizing process {}", *this);
  653. if (veil_state() == VeilState::Dropped) {
  654. name().with([&](auto& process_name) {
  655. dbgln("\x1b[01;31mProcess '{}' exited with the veil left open\x1b[0m", process_name->view());
  656. });
  657. }
  658. if (g_init_pid != 0 && pid() == g_init_pid)
  659. PANIC("Init process quit unexpectedly. Exit code: {}", termination_status());
  660. if (is_dumpable()) {
  661. if (m_should_generate_coredump) {
  662. auto result = dump_core();
  663. if (result.is_error()) {
  664. dmesgln("Failed to write coredump for pid {}: {}", pid(), result.error());
  665. }
  666. }
  667. if (m_perf_event_buffer) {
  668. auto result = dump_perfcore();
  669. if (result.is_error())
  670. dmesgln("Failed to write perfcore for pid {}: {}", pid(), result.error());
  671. TimeManagement::the().disable_profile_timer();
  672. }
  673. }
  674. m_threads_for_coredump.clear();
  675. if (m_alarm_timer)
  676. TimerQueue::the().cancel_timer(m_alarm_timer.release_nonnull());
  677. m_fds.with_exclusive([](auto& fds) { fds.clear(); });
  678. m_tty = nullptr;
  679. m_executable.with([](auto& executable) { executable = nullptr; });
  680. m_attached_jail.with([](auto& jail) {
  681. if (jail)
  682. jail->detach({});
  683. jail = nullptr;
  684. });
  685. m_arguments.clear();
  686. m_environment.clear();
  687. m_state.store(State::Dead, AK::MemoryOrder::memory_order_release);
  688. {
  689. if (auto parent_process = Process::from_pid_ignoring_jails(ppid())) {
  690. if (parent_process->is_user_process() && (parent_process->m_signal_action_data[SIGCHLD].flags & SA_NOCLDWAIT) != SA_NOCLDWAIT)
  691. (void)parent_process->send_signal(SIGCHLD, this);
  692. }
  693. }
  694. if (!!ppid()) {
  695. if (auto parent = Process::from_pid_ignoring_jails(ppid())) {
  696. parent->m_ticks_in_user_for_dead_children += m_ticks_in_user + m_ticks_in_user_for_dead_children;
  697. parent->m_ticks_in_kernel_for_dead_children += m_ticks_in_kernel + m_ticks_in_kernel_for_dead_children;
  698. }
  699. }
  700. unblock_waiters(Thread::WaitBlocker::UnblockFlags::Terminated);
  701. m_space.with([](auto& space) { space->remove_all_regions({}); });
  702. VERIFY(ref_count() > 0);
  703. // WaitBlockerSet::finalize will be in charge of dropping the last
  704. // reference if there are still waiters around, or whenever the last
  705. // waitable states are consumed. Unless there is no parent around
  706. // anymore, in which case we'll just drop it right away.
  707. m_wait_blocker_set.finalize();
  708. }
  709. void Process::disowned_by_waiter(Process& process)
  710. {
  711. m_wait_blocker_set.disowned_by_waiter(process);
  712. }
  713. void Process::unblock_waiters(Thread::WaitBlocker::UnblockFlags flags, u8 signal)
  714. {
  715. LockRefPtr<Process> waiter_process;
  716. if (auto* my_tracer = tracer())
  717. waiter_process = Process::from_pid_ignoring_jails(my_tracer->tracer_pid());
  718. else
  719. waiter_process = Process::from_pid_ignoring_jails(ppid());
  720. if (waiter_process)
  721. waiter_process->m_wait_blocker_set.unblock(*this, flags, signal);
  722. }
  723. void Process::die()
  724. {
  725. auto expected = State::Running;
  726. if (!m_state.compare_exchange_strong(expected, State::Dying, AK::memory_order_acquire)) {
  727. // It's possible that another thread calls this at almost the same time
  728. // as we can't always instantly kill other threads (they may be blocked)
  729. // So if we already were called then other threads should stop running
  730. // momentarily and we only really need to service the first thread
  731. return;
  732. }
  733. // Let go of the TTY, otherwise a slave PTY may keep the master PTY from
  734. // getting an EOF when the last process using the slave PTY dies.
  735. // If the master PTY owner relies on an EOF to know when to wait() on a
  736. // slave owner, we have to allow the PTY pair to be torn down.
  737. m_tty = nullptr;
  738. VERIFY(m_threads_for_coredump.is_empty());
  739. for_each_thread([&](auto& thread) {
  740. auto result = m_threads_for_coredump.try_append(thread);
  741. if (result.is_error())
  742. dbgln("Failed to add thread {} to coredump due to OOM", thread.tid());
  743. });
  744. all_instances().with([&](auto const& list) {
  745. for (auto it = list.begin(); it != list.end();) {
  746. auto& process = *it;
  747. ++it;
  748. if (process.has_tracee_thread(pid())) {
  749. if constexpr (PROCESS_DEBUG) {
  750. process.name().with([&](auto& process_name) {
  751. name().with([&](auto& name) {
  752. dbgln("Process {} ({}) is attached by {} ({}) which will exit", process_name->view(), process.pid(), name->view(), pid());
  753. });
  754. });
  755. }
  756. process.stop_tracing();
  757. auto err = process.send_signal(SIGSTOP, this);
  758. if (err.is_error()) {
  759. process.name().with([&](auto& process_name) {
  760. dbgln("Failed to send the SIGSTOP signal to {} ({})", process_name->view(), process.pid());
  761. });
  762. }
  763. }
  764. }
  765. });
  766. kill_all_threads();
  767. #ifdef ENABLE_KERNEL_COVERAGE_COLLECTION
  768. KCOVDevice::free_process();
  769. #endif
  770. }
  771. void Process::terminate_due_to_signal(u8 signal)
  772. {
  773. VERIFY_INTERRUPTS_DISABLED();
  774. VERIFY(signal < NSIG);
  775. VERIFY(&Process::current() == this);
  776. dbgln("Terminating {} due to signal {}", *this, signal);
  777. with_mutable_protected_data([&](auto& protected_data) {
  778. protected_data.termination_status = 0;
  779. protected_data.termination_signal = signal;
  780. });
  781. die();
  782. }
  783. ErrorOr<void> Process::send_signal(u8 signal, Process* sender)
  784. {
  785. VERIFY(is_user_process());
  786. // Try to send it to the "obvious" main thread:
  787. auto receiver_thread = Thread::from_tid(pid().value());
  788. // If the main thread has died, there may still be other threads:
  789. if (!receiver_thread) {
  790. // The first one should be good enough.
  791. // Neither kill(2) nor kill(3) specify any selection procedure.
  792. for_each_thread([&receiver_thread](Thread& thread) -> IterationDecision {
  793. receiver_thread = &thread;
  794. return IterationDecision::Break;
  795. });
  796. }
  797. if (receiver_thread) {
  798. receiver_thread->send_signal(signal, sender);
  799. return {};
  800. }
  801. return ESRCH;
  802. }
  803. LockRefPtr<Thread> Process::create_kernel_thread(void (*entry)(void*), void* entry_data, u32 priority, NonnullOwnPtr<KString> name, u32 affinity, bool joinable)
  804. {
  805. VERIFY((priority >= THREAD_PRIORITY_MIN) && (priority <= THREAD_PRIORITY_MAX));
  806. // FIXME: Do something with guard pages?
  807. auto thread_or_error = Thread::try_create(*this);
  808. if (thread_or_error.is_error())
  809. return {};
  810. auto thread = thread_or_error.release_value();
  811. thread->set_name(move(name));
  812. thread->set_affinity(affinity);
  813. thread->set_priority(priority);
  814. if (!joinable)
  815. thread->detach();
  816. auto& regs = thread->regs();
  817. regs.set_ip((FlatPtr)entry);
  818. regs.set_sp((FlatPtr)entry_data); // entry function argument is expected to be in the SP register
  819. SpinlockLocker lock(g_scheduler_lock);
  820. thread->set_state(Thread::State::Runnable);
  821. return thread;
  822. }
  823. void Process::OpenFileDescriptionAndFlags::clear()
  824. {
  825. // FIXME: Verify Process::m_fds_lock is locked!
  826. m_description = nullptr;
  827. m_flags = 0;
  828. }
  829. void Process::OpenFileDescriptionAndFlags::set(NonnullLockRefPtr<OpenFileDescription>&& description, u32 flags)
  830. {
  831. // FIXME: Verify Process::m_fds_lock is locked!
  832. m_description = move(description);
  833. m_flags = flags;
  834. }
  835. void Process::set_tty(TTY* tty)
  836. {
  837. m_tty = tty;
  838. }
  839. ErrorOr<void> Process::start_tracing_from(ProcessID tracer)
  840. {
  841. m_tracer = TRY(ThreadTracer::try_create(tracer));
  842. return {};
  843. }
  844. void Process::stop_tracing()
  845. {
  846. m_tracer = nullptr;
  847. }
  848. void Process::tracer_trap(Thread& thread, RegisterState const& regs)
  849. {
  850. VERIFY(m_tracer.ptr());
  851. m_tracer->set_regs(regs);
  852. thread.send_urgent_signal_to_self(SIGTRAP);
  853. }
  854. bool Process::create_perf_events_buffer_if_needed()
  855. {
  856. if (m_perf_event_buffer)
  857. return true;
  858. m_perf_event_buffer = PerformanceEventBuffer::try_create_with_size(4 * MiB);
  859. if (!m_perf_event_buffer)
  860. return false;
  861. return !m_perf_event_buffer->add_process(*this, ProcessEventType::Create).is_error();
  862. }
  863. void Process::delete_perf_events_buffer()
  864. {
  865. if (m_perf_event_buffer)
  866. m_perf_event_buffer = nullptr;
  867. }
  868. bool Process::remove_thread(Thread& thread)
  869. {
  870. u32 thread_count_before = 0;
  871. thread_list().with([&](auto& thread_list) {
  872. thread_list.remove(thread);
  873. with_mutable_protected_data([&](auto& protected_data) {
  874. thread_count_before = protected_data.thread_count.fetch_sub(1, AK::MemoryOrder::memory_order_acq_rel);
  875. VERIFY(thread_count_before != 0);
  876. });
  877. });
  878. return thread_count_before == 1;
  879. }
  880. bool Process::add_thread(Thread& thread)
  881. {
  882. bool is_first = false;
  883. thread_list().with([&](auto& thread_list) {
  884. thread_list.append(thread);
  885. with_mutable_protected_data([&](auto& protected_data) {
  886. is_first = protected_data.thread_count.fetch_add(1, AK::MemoryOrder::memory_order_relaxed) == 0;
  887. });
  888. });
  889. return is_first;
  890. }
  891. ErrorOr<void> Process::set_coredump_property(NonnullOwnPtr<KString> key, NonnullOwnPtr<KString> value)
  892. {
  893. return m_coredump_properties.with([&](auto& coredump_properties) -> ErrorOr<void> {
  894. // Write it into the first available property slot.
  895. for (auto& slot : coredump_properties) {
  896. if (slot.key)
  897. continue;
  898. slot.key = move(key);
  899. slot.value = move(value);
  900. return {};
  901. }
  902. return ENOBUFS;
  903. });
  904. }
  905. ErrorOr<void> Process::try_set_coredump_property(StringView key, StringView value)
  906. {
  907. auto key_kstring = TRY(KString::try_create(key));
  908. auto value_kstring = TRY(KString::try_create(value));
  909. return set_coredump_property(move(key_kstring), move(value_kstring));
  910. };
  911. static constexpr StringView to_string(Pledge promise)
  912. {
  913. #define __ENUMERATE_PLEDGE_PROMISE(x) \
  914. case Pledge::x: \
  915. return #x##sv;
  916. switch (promise) {
  917. ENUMERATE_PLEDGE_PROMISES
  918. }
  919. #undef __ENUMERATE_PLEDGE_PROMISE
  920. VERIFY_NOT_REACHED();
  921. }
  922. ErrorOr<void> Process::require_no_promises() const
  923. {
  924. if (!has_promises())
  925. return {};
  926. dbgln("Has made a promise");
  927. Thread::current()->set_promise_violation_pending(true);
  928. return EPROMISEVIOLATION;
  929. }
  930. ErrorOr<void> Process::require_promise(Pledge promise)
  931. {
  932. if (!has_promises())
  933. return {};
  934. if (has_promised(promise))
  935. return {};
  936. dbgln("Has not pledged {}", to_string(promise));
  937. Thread::current()->set_promise_violation_pending(true);
  938. (void)try_set_coredump_property("pledge_violation"sv, to_string(promise));
  939. return EPROMISEVIOLATION;
  940. }
  941. NonnullRefPtr<Credentials> Process::credentials() const
  942. {
  943. return with_protected_data([&](auto& protected_data) -> NonnullRefPtr<Credentials> {
  944. return *protected_data.credentials;
  945. });
  946. }
  947. RefPtr<Custody> Process::executable()
  948. {
  949. return m_executable.with([](auto& executable) { return executable; });
  950. }
  951. RefPtr<Custody const> Process::executable() const
  952. {
  953. return m_executable.with([](auto& executable) { return executable; });
  954. }
  955. ErrorOr<NonnullRefPtr<Custody>> Process::custody_for_dirfd(int dirfd)
  956. {
  957. if (dirfd == AT_FDCWD)
  958. return current_directory();
  959. auto base_description = TRY(open_file_description(dirfd));
  960. if (!base_description->custody())
  961. return EINVAL;
  962. return *base_description->custody();
  963. }
  964. SpinlockProtected<NonnullOwnPtr<KString>, LockRank::None> const& Process::name() const
  965. {
  966. return m_name;
  967. }
  968. void Process::set_name(NonnullOwnPtr<KString> name)
  969. {
  970. m_name.with([&](auto& this_name) {
  971. this_name = move(name);
  972. });
  973. }
  974. }