Process.cpp 33 KB

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