Process.cpp 30 KB

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