Process.cpp 37 KB

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