Process.cpp 31 KB

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