Process.cpp 32 KB

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