Process.cpp 39 KB

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