Process.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Demangle.h>
  27. #include <AK/QuickSort.h>
  28. #include <AK/StdLibExtras.h>
  29. #include <AK/StringBuilder.h>
  30. #include <AK/Time.h>
  31. #include <AK/Types.h>
  32. #include <Kernel/API/Syscall.h>
  33. #include <Kernel/Arch/i386/CPU.h>
  34. #include <Kernel/CoreDump.h>
  35. #include <Kernel/Debug.h>
  36. #include <Kernel/Devices/NullDevice.h>
  37. #include <Kernel/FileSystem/Custody.h>
  38. #include <Kernel/FileSystem/FileDescription.h>
  39. #include <Kernel/FileSystem/VirtualFileSystem.h>
  40. #include <Kernel/Heap/kmalloc.h>
  41. #include <Kernel/KBufferBuilder.h>
  42. #include <Kernel/KSyms.h>
  43. #include <Kernel/Module.h>
  44. #include <Kernel/PerformanceEventBuffer.h>
  45. #include <Kernel/Process.h>
  46. #include <Kernel/RTC.h>
  47. #include <Kernel/StdLib.h>
  48. #include <Kernel/TTY/TTY.h>
  49. #include <Kernel/Thread.h>
  50. #include <Kernel/VM/AnonymousVMObject.h>
  51. #include <Kernel/VM/PageDirectory.h>
  52. #include <Kernel/VM/PrivateInodeVMObject.h>
  53. #include <Kernel/VM/ProcessPagingScope.h>
  54. #include <Kernel/VM/SharedInodeVMObject.h>
  55. #include <LibC/errno_numbers.h>
  56. #include <LibC/limits.h>
  57. namespace Kernel {
  58. static void create_signal_trampolines();
  59. RecursiveSpinLock g_processes_lock;
  60. static Atomic<pid_t> next_pid;
  61. InlineLinkedList<Process>* g_processes;
  62. String* g_hostname;
  63. Lock* g_hostname_lock;
  64. VirtualAddress g_return_to_ring3_from_signal_trampoline;
  65. HashMap<String, OwnPtr<Module>>* g_modules;
  66. ProcessID Process::allocate_pid()
  67. {
  68. // Overflow is UB, and negative PIDs wreck havoc.
  69. // TODO: Handle PID overflow
  70. // For example: Use an Atomic<u32>, mask the most significant bit,
  71. // retry if PID is already taken as a PID, taken as a TID,
  72. // takes as a PGID, taken as a SID, or zero.
  73. return next_pid.fetch_add(1, AK::MemoryOrder::memory_order_acq_rel);
  74. }
  75. void Process::initialize()
  76. {
  77. g_modules = new HashMap<String, OwnPtr<Module>>;
  78. next_pid.store(0, AK::MemoryOrder::memory_order_release);
  79. g_processes = new InlineLinkedList<Process>;
  80. g_process_groups = new InlineLinkedList<ProcessGroup>;
  81. g_hostname = new String("courage");
  82. g_hostname_lock = new Lock;
  83. create_signal_trampolines();
  84. }
  85. Vector<ProcessID> Process::all_pids()
  86. {
  87. Vector<ProcessID> pids;
  88. ScopedSpinLock lock(g_processes_lock);
  89. pids.ensure_capacity((int)g_processes->size_slow());
  90. for (auto& process : *g_processes)
  91. pids.append(process.pid());
  92. return pids;
  93. }
  94. NonnullRefPtrVector<Process> Process::all_processes()
  95. {
  96. NonnullRefPtrVector<Process> processes;
  97. ScopedSpinLock lock(g_processes_lock);
  98. processes.ensure_capacity((int)g_processes->size_slow());
  99. for (auto& process : *g_processes)
  100. processes.append(NonnullRefPtr<Process>(process));
  101. return processes;
  102. }
  103. bool Process::in_group(gid_t gid) const
  104. {
  105. return m_gid == gid || m_extra_gids.contains_slow(gid);
  106. }
  107. Optional<Range> Process::allocate_range(VirtualAddress vaddr, size_t size, size_t alignment)
  108. {
  109. vaddr.mask(PAGE_MASK);
  110. size = PAGE_ROUND_UP(size);
  111. if (vaddr.is_null())
  112. return page_directory().range_allocator().allocate_anywhere(size, alignment);
  113. return page_directory().range_allocator().allocate_specific(vaddr, size);
  114. }
  115. Region& Process::allocate_split_region(const Region& source_region, const Range& range, size_t offset_in_vmobject)
  116. {
  117. auto& region = add_region(
  118. Region::create_user_accessible(this, range, source_region.vmobject(), offset_in_vmobject, source_region.name(), source_region.access(), source_region.is_cacheable(), source_region.is_shared()));
  119. region.set_mmap(source_region.is_mmap());
  120. region.set_stack(source_region.is_stack());
  121. size_t page_offset_in_source_region = (offset_in_vmobject - source_region.offset_in_vmobject()) / PAGE_SIZE;
  122. for (size_t i = 0; i < region.page_count(); ++i) {
  123. if (source_region.should_cow(page_offset_in_source_region + i))
  124. region.set_should_cow(i, true);
  125. }
  126. return region;
  127. }
  128. KResultOr<Region*> Process::allocate_region(const Range& range, const String& name, int prot, AllocationStrategy strategy)
  129. {
  130. ASSERT(range.is_valid());
  131. auto vmobject = AnonymousVMObject::create_with_size(range.size(), strategy);
  132. if (!vmobject)
  133. return ENOMEM;
  134. auto region = Region::create_user_accessible(this, range, vmobject.release_nonnull(), 0, name, prot_to_region_access_flags(prot), true, false);
  135. if (!region->map(page_directory()))
  136. return ENOMEM;
  137. return &add_region(move(region));
  138. }
  139. KResultOr<Region*> Process::allocate_region_with_vmobject(const Range& range, NonnullRefPtr<VMObject> vmobject, size_t offset_in_vmobject, const String& name, int prot, bool shared)
  140. {
  141. ASSERT(range.is_valid());
  142. size_t end_in_vmobject = offset_in_vmobject + range.size();
  143. if (end_in_vmobject <= offset_in_vmobject) {
  144. dbgln("allocate_region_with_vmobject: Overflow (offset + size)");
  145. return EINVAL;
  146. }
  147. if (offset_in_vmobject >= vmobject->size()) {
  148. dbgln("allocate_region_with_vmobject: Attempt to allocate a region with an offset past the end of its VMObject.");
  149. return EINVAL;
  150. }
  151. if (end_in_vmobject > vmobject->size()) {
  152. dbgln("allocate_region_with_vmobject: Attempt to allocate a region with an end past the end of its VMObject.");
  153. return EINVAL;
  154. }
  155. offset_in_vmobject &= PAGE_MASK;
  156. auto& region = add_region(Region::create_user_accessible(this, range, move(vmobject), offset_in_vmobject, name, prot_to_region_access_flags(prot), true, shared));
  157. if (!region.map(page_directory())) {
  158. // FIXME: What is an appropriate error code here, really?
  159. return ENOMEM;
  160. }
  161. return &region;
  162. }
  163. bool Process::deallocate_region(Region& region)
  164. {
  165. OwnPtr<Region> region_protector;
  166. ScopedSpinLock lock(m_lock);
  167. if (m_region_lookup_cache.region.unsafe_ptr() == &region)
  168. m_region_lookup_cache.region = nullptr;
  169. for (size_t i = 0; i < m_regions.size(); ++i) {
  170. if (&m_regions[i] == &region) {
  171. region_protector = m_regions.unstable_take(i);
  172. return true;
  173. }
  174. }
  175. return false;
  176. }
  177. Region* Process::find_region_from_range(const Range& range)
  178. {
  179. ScopedSpinLock lock(m_lock);
  180. if (m_region_lookup_cache.range.has_value() && m_region_lookup_cache.range.value() == range && m_region_lookup_cache.region)
  181. return m_region_lookup_cache.region.unsafe_ptr();
  182. size_t size = PAGE_ROUND_UP(range.size());
  183. for (auto& region : m_regions) {
  184. if (region.vaddr() == range.base() && region.size() == size) {
  185. m_region_lookup_cache.range = range;
  186. m_region_lookup_cache.region = region;
  187. return &region;
  188. }
  189. }
  190. return nullptr;
  191. }
  192. Region* Process::find_region_containing(const Range& range)
  193. {
  194. ScopedSpinLock lock(m_lock);
  195. for (auto& region : m_regions) {
  196. if (region.contains(range))
  197. return &region;
  198. }
  199. return nullptr;
  200. }
  201. void Process::kill_threads_except_self()
  202. {
  203. InterruptDisabler disabler;
  204. if (thread_count() <= 1)
  205. return;
  206. auto current_thread = Thread::current();
  207. for_each_thread([&](Thread& thread) {
  208. if (&thread == current_thread
  209. || thread.state() == Thread::State::Dead
  210. || thread.state() == Thread::State::Dying)
  211. return IterationDecision::Continue;
  212. // We need to detach this thread in case it hasn't been joined
  213. thread.detach();
  214. thread.set_should_die();
  215. return IterationDecision::Continue;
  216. });
  217. big_lock().clear_waiters();
  218. }
  219. void Process::kill_all_threads()
  220. {
  221. for_each_thread([&](Thread& thread) {
  222. // We need to detach this thread in case it hasn't been joined
  223. thread.detach();
  224. thread.set_should_die();
  225. return IterationDecision::Continue;
  226. });
  227. }
  228. RefPtr<Process> Process::create_user_process(RefPtr<Thread>& first_thread, const String& path, uid_t uid, gid_t gid, ProcessID parent_pid, int& error, Vector<String>&& arguments, Vector<String>&& environment, TTY* tty)
  229. {
  230. auto parts = path.split('/');
  231. if (arguments.is_empty()) {
  232. arguments.append(parts.last());
  233. }
  234. RefPtr<Custody> cwd;
  235. RefPtr<Custody> root;
  236. {
  237. ScopedSpinLock lock(g_processes_lock);
  238. if (auto parent = Process::from_pid(parent_pid)) {
  239. cwd = parent->m_cwd;
  240. root = parent->m_root_directory;
  241. }
  242. }
  243. if (!cwd)
  244. cwd = VFS::the().root_custody();
  245. if (!root)
  246. root = VFS::the().root_custody();
  247. auto process = adopt(*new Process(first_thread, parts.take_last(), uid, gid, parent_pid, false, move(cwd), nullptr, tty));
  248. if (!first_thread)
  249. return {};
  250. process->m_fds.resize(m_max_open_file_descriptors);
  251. auto& device_to_use_as_tty = tty ? (CharacterDevice&)*tty : NullDevice::the();
  252. auto description = device_to_use_as_tty.open(O_RDWR).value();
  253. process->m_fds[0].set(*description);
  254. process->m_fds[1].set(*description);
  255. process->m_fds[2].set(*description);
  256. error = process->exec(path, move(arguments), move(environment));
  257. if (error != 0) {
  258. dbgln("Failed to exec {}: {}", path, error);
  259. first_thread = nullptr;
  260. return {};
  261. }
  262. {
  263. ScopedSpinLock lock(g_processes_lock);
  264. g_processes->prepend(process);
  265. process->ref();
  266. }
  267. error = 0;
  268. return process;
  269. }
  270. RefPtr<Process> Process::create_kernel_process(RefPtr<Thread>& first_thread, String&& name, void (*entry)(void*), void* entry_data, u32 affinity)
  271. {
  272. auto process = adopt(*new Process(first_thread, move(name), (uid_t)0, (gid_t)0, ProcessID(0), true));
  273. if (!first_thread)
  274. return {};
  275. first_thread->tss().eip = (FlatPtr)entry;
  276. first_thread->tss().esp = FlatPtr(entry_data); // entry function argument is expected to be in tss.esp
  277. if (process->pid() != 0) {
  278. ScopedSpinLock lock(g_processes_lock);
  279. g_processes->prepend(process);
  280. process->ref();
  281. }
  282. ScopedSpinLock lock(g_scheduler_lock);
  283. first_thread->set_affinity(affinity);
  284. first_thread->set_state(Thread::State::Runnable);
  285. return process;
  286. }
  287. Process::Process(RefPtr<Thread>& first_thread, const String& name, uid_t uid, gid_t gid, ProcessID ppid, bool is_kernel_process, RefPtr<Custody> cwd, RefPtr<Custody> executable, TTY* tty, Process* fork_parent)
  288. : m_name(move(name))
  289. , m_pid(allocate_pid())
  290. , m_euid(uid)
  291. , m_egid(gid)
  292. , m_uid(uid)
  293. , m_gid(gid)
  294. , m_suid(uid)
  295. , m_sgid(gid)
  296. , m_is_kernel_process(is_kernel_process)
  297. , m_executable(move(executable))
  298. , m_cwd(move(cwd))
  299. , m_tty(tty)
  300. , m_ppid(ppid)
  301. , m_wait_block_condition(*this)
  302. {
  303. dbgln<PROCESS_DEBUG>("Created new process {}({})", m_name, m_pid.value());
  304. m_page_directory = PageDirectory::create_for_userspace(*this, fork_parent ? &fork_parent->page_directory().range_allocator() : nullptr);
  305. if (fork_parent) {
  306. // NOTE: fork() doesn't clone all threads; the thread that called fork() becomes the only thread in the new process.
  307. first_thread = Thread::current()->clone(*this);
  308. } else {
  309. // NOTE: This non-forked code path is only taken when the kernel creates a process "manually" (at boot.)
  310. first_thread = adopt(*new Thread(*this));
  311. first_thread->detach();
  312. }
  313. if (first_thread && !first_thread->was_created()) {
  314. // We couldn't entirely create or clone this thread, abort
  315. first_thread = nullptr;
  316. }
  317. }
  318. Process::~Process()
  319. {
  320. ASSERT(thread_count() == 0); // all threads should have been finalized
  321. ASSERT(!m_alarm_timer);
  322. {
  323. ScopedSpinLock processses_lock(g_processes_lock);
  324. if (prev() || next())
  325. g_processes->remove(this);
  326. }
  327. }
  328. void Process::dump_regions()
  329. {
  330. klog() << "Process regions:";
  331. klog() << "BEGIN END SIZE ACCESS NAME";
  332. ScopedSpinLock lock(m_lock);
  333. Vector<Region*> sorted_regions;
  334. sorted_regions.ensure_capacity(m_regions.size());
  335. for (auto& region : m_regions)
  336. sorted_regions.append(&region);
  337. quick_sort(sorted_regions, [](auto& a, auto& b) {
  338. return a->vaddr() < b->vaddr();
  339. });
  340. for (auto& sorted_region : sorted_regions) {
  341. auto& region = *sorted_region;
  342. klog() << String::format("%08x", region.vaddr().get()) << " -- " << String::format("%08x", region.vaddr().offset(region.size() - 1).get()) << " " << String::format("%08zx", region.size()) << " " << (region.is_readable() ? 'R' : ' ') << (region.is_writable() ? 'W' : ' ') << (region.is_executable() ? 'X' : ' ') << (region.is_shared() ? 'S' : ' ') << (region.is_stack() ? 'T' : ' ') << (region.vmobject().is_anonymous() ? 'A' : ' ') << " " << region.name().characters();
  343. }
  344. MM.dump_kernel_regions();
  345. }
  346. // Make sure the compiler doesn't "optimize away" this function:
  347. extern void signal_trampoline_dummy();
  348. void signal_trampoline_dummy()
  349. {
  350. // The trampoline preserves the current eax, pushes the signal code and
  351. // then calls the signal handler. We do this because, when interrupting a
  352. // blocking syscall, that syscall may return some special error code in eax;
  353. // This error code would likely be overwritten by the signal handler, so it's
  354. // necessary to preserve it here.
  355. asm(
  356. ".intel_syntax noprefix\n"
  357. "asm_signal_trampoline:\n"
  358. "push ebp\n"
  359. "mov ebp, esp\n"
  360. "push eax\n" // we have to store eax 'cause it might be the return value from a syscall
  361. "sub esp, 4\n" // align the stack to 16 bytes
  362. "mov eax, [ebp+12]\n" // push the signal code
  363. "push eax\n"
  364. "call [ebp+8]\n" // call the signal handler
  365. "add esp, 8\n"
  366. "mov eax, %P0\n"
  367. "int 0x82\n" // sigreturn syscall
  368. "asm_signal_trampoline_end:\n"
  369. ".att_syntax" ::"i"(Syscall::SC_sigreturn));
  370. }
  371. extern "C" void asm_signal_trampoline(void);
  372. extern "C" void asm_signal_trampoline_end(void);
  373. void create_signal_trampolines()
  374. {
  375. InterruptDisabler disabler;
  376. // NOTE: We leak this region.
  377. auto* trampoline_region = MM.allocate_user_accessible_kernel_region(PAGE_SIZE, "Signal trampolines", Region::Access::Read | Region::Access::Write | Region::Access::Execute, false).leak_ptr();
  378. g_return_to_ring3_from_signal_trampoline = trampoline_region->vaddr();
  379. u8* trampoline = (u8*)asm_signal_trampoline;
  380. u8* trampoline_end = (u8*)asm_signal_trampoline_end;
  381. size_t trampoline_size = trampoline_end - trampoline;
  382. {
  383. SmapDisabler disabler;
  384. u8* code_ptr = (u8*)trampoline_region->vaddr().as_ptr();
  385. memcpy(code_ptr, trampoline, trampoline_size);
  386. }
  387. trampoline_region->set_writable(false);
  388. trampoline_region->remap();
  389. }
  390. void Process::crash(int signal, u32 eip, bool out_of_memory)
  391. {
  392. ASSERT_INTERRUPTS_DISABLED();
  393. ASSERT(!is_dead());
  394. ASSERT(Process::current() == this);
  395. if (out_of_memory) {
  396. dbgln("\033[31;1mOut of memory\033[m, killing: {}", *this);
  397. } else {
  398. if (eip >= 0xc0000000 && g_kernel_symbols_available) {
  399. auto* symbol = symbolicate_kernel_address(eip);
  400. dbgln("\033[31;1m{:p} {} +{}\033[0m\n", eip, (symbol ? demangle(symbol->name) : "(k?)"), (symbol ? eip - symbol->address : 0));
  401. } else {
  402. dbgln("\033[31;1m{:p} (?)\033[0m\n", eip);
  403. }
  404. dump_backtrace();
  405. }
  406. m_termination_signal = signal;
  407. set_dump_core(!out_of_memory);
  408. dump_regions();
  409. ASSERT(is_user_process());
  410. die();
  411. // We can not return from here, as there is nowhere
  412. // to unwind to, so die right away.
  413. Thread::current()->die_if_needed();
  414. ASSERT_NOT_REACHED();
  415. }
  416. RefPtr<Process> Process::from_pid(ProcessID pid)
  417. {
  418. ScopedSpinLock lock(g_processes_lock);
  419. for (auto& process : *g_processes) {
  420. process.pid();
  421. if (process.pid() == pid)
  422. return &process;
  423. }
  424. return {};
  425. }
  426. RefPtr<FileDescription> Process::file_description(int fd) const
  427. {
  428. if (fd < 0)
  429. return nullptr;
  430. if (static_cast<size_t>(fd) < m_fds.size())
  431. return m_fds[fd].description();
  432. return nullptr;
  433. }
  434. int Process::fd_flags(int fd) const
  435. {
  436. if (fd < 0)
  437. return -1;
  438. if (static_cast<size_t>(fd) < m_fds.size())
  439. return m_fds[fd].flags();
  440. return -1;
  441. }
  442. int Process::number_of_open_file_descriptors() const
  443. {
  444. int count = 0;
  445. for (auto& description : m_fds) {
  446. if (description)
  447. ++count;
  448. }
  449. return count;
  450. }
  451. int Process::alloc_fd(int first_candidate_fd)
  452. {
  453. for (int i = first_candidate_fd; i < (int)m_max_open_file_descriptors; ++i) {
  454. if (!m_fds[i])
  455. return i;
  456. }
  457. return -EMFILE;
  458. }
  459. timeval kgettimeofday()
  460. {
  461. return TimeManagement::now_as_timeval();
  462. }
  463. void kgettimeofday(timeval& tv)
  464. {
  465. tv = kgettimeofday();
  466. }
  467. siginfo_t Process::wait_info()
  468. {
  469. siginfo_t siginfo;
  470. memset(&siginfo, 0, sizeof(siginfo));
  471. siginfo.si_signo = SIGCHLD;
  472. siginfo.si_pid = pid().value();
  473. siginfo.si_uid = uid();
  474. if (m_termination_signal) {
  475. siginfo.si_status = m_termination_signal;
  476. siginfo.si_code = CLD_KILLED;
  477. } else {
  478. siginfo.si_status = m_termination_status;
  479. siginfo.si_code = CLD_EXITED;
  480. }
  481. return siginfo;
  482. }
  483. Custody& Process::current_directory()
  484. {
  485. if (!m_cwd)
  486. m_cwd = VFS::the().root_custody();
  487. return *m_cwd;
  488. }
  489. KResultOr<String> Process::get_syscall_path_argument(const char* user_path, size_t path_length) const
  490. {
  491. if (path_length == 0)
  492. return EINVAL;
  493. if (path_length > PATH_MAX)
  494. return ENAMETOOLONG;
  495. auto copied_string = copy_string_from_user(user_path, path_length);
  496. if (copied_string.is_null())
  497. return EFAULT;
  498. return copied_string;
  499. }
  500. KResultOr<String> Process::get_syscall_path_argument(const Syscall::StringArgument& path) const
  501. {
  502. return get_syscall_path_argument(path.characters, path.length);
  503. }
  504. bool Process::dump_core()
  505. {
  506. ASSERT(is_dumpable());
  507. ASSERT(should_core_dump());
  508. dbgln("Generating coredump for pid: {}", m_pid.value());
  509. auto coredump_path = String::formatted("/tmp/coredump/{}_{}_{}", name(), m_pid.value(), RTC::now());
  510. auto coredump = CoreDump::create(*this, coredump_path);
  511. if (!coredump)
  512. return false;
  513. return !coredump->write().is_error();
  514. }
  515. bool Process::dump_perfcore()
  516. {
  517. ASSERT(is_dumpable());
  518. ASSERT(m_perf_event_buffer);
  519. dbgln("Generating perfcore for pid: {}", m_pid.value());
  520. auto description_or_error = VFS::the().open(String::formatted("perfcore.{}", m_pid.value()), O_CREAT | O_EXCL, 0400, current_directory(), UidAndGid { m_uid, m_gid });
  521. if (description_or_error.is_error())
  522. return false;
  523. auto& description = description_or_error.value();
  524. auto json = m_perf_event_buffer->to_json(m_pid, m_executable ? m_executable->absolute_path() : "");
  525. if (!json)
  526. return false;
  527. auto json_buffer = UserOrKernelBuffer::for_kernel_buffer(json->data());
  528. return !description->write(json_buffer, json->size()).is_error();
  529. }
  530. void Process::finalize()
  531. {
  532. ASSERT(Thread::current() == g_finalizer);
  533. dbgln<PROCESS_DEBUG>("Finalizing process {}", *this);
  534. if (is_dumpable()) {
  535. if (m_should_dump_core)
  536. dump_core();
  537. if (m_perf_event_buffer)
  538. dump_perfcore();
  539. }
  540. m_threads_for_coredump.clear();
  541. if (m_alarm_timer)
  542. TimerQueue::the().cancel_timer(m_alarm_timer.release_nonnull());
  543. m_fds.clear();
  544. m_tty = nullptr;
  545. m_executable = nullptr;
  546. m_cwd = nullptr;
  547. m_root_directory = nullptr;
  548. m_root_directory_relative_to_global_root = nullptr;
  549. m_arguments.clear();
  550. m_environment.clear();
  551. m_dead = true;
  552. {
  553. // FIXME: PID/TID BUG
  554. if (auto parent_thread = Thread::from_tid(m_ppid.value())) {
  555. if (!(parent_thread->m_signal_action_data[SIGCHLD].flags & SA_NOCLDWAIT))
  556. parent_thread->send_signal(SIGCHLD, this);
  557. }
  558. }
  559. {
  560. ScopedSpinLock processses_lock(g_processes_lock);
  561. if (!!ppid()) {
  562. if (auto parent = Process::from_pid(ppid())) {
  563. parent->m_ticks_in_user_for_dead_children += m_ticks_in_user + m_ticks_in_user_for_dead_children;
  564. parent->m_ticks_in_kernel_for_dead_children += m_ticks_in_kernel + m_ticks_in_kernel_for_dead_children;
  565. }
  566. }
  567. }
  568. unblock_waiters(Thread::WaitBlocker::UnblockFlags::Terminated);
  569. {
  570. ScopedSpinLock lock(m_lock);
  571. m_regions.clear();
  572. }
  573. ASSERT(ref_count() > 0);
  574. // WaitBlockCondition::finalize will be in charge of dropping the last
  575. // reference if there are still waiters around, or whenever the last
  576. // waitable states are consumed. Unless there is no parent around
  577. // anymore, in which case we'll just drop it right away.
  578. m_wait_block_condition.finalize();
  579. }
  580. void Process::disowned_by_waiter(Process& process)
  581. {
  582. m_wait_block_condition.disowned_by_waiter(process);
  583. }
  584. void Process::unblock_waiters(Thread::WaitBlocker::UnblockFlags flags, u8 signal)
  585. {
  586. if (auto parent = Process::from_pid(ppid()))
  587. parent->m_wait_block_condition.unblock(*this, flags, signal);
  588. }
  589. void Process::die()
  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. for_each_thread([&](auto& thread) {
  597. m_threads_for_coredump.append(&thread);
  598. return IterationDecision::Continue;
  599. });
  600. kill_all_threads();
  601. }
  602. size_t Process::amount_dirty_private() const
  603. {
  604. // FIXME: This gets a bit more complicated for Regions sharing the same underlying VMObject.
  605. // The main issue I'm thinking of is when the VMObject has physical pages that none of the Regions are mapping.
  606. // That's probably a situation that needs to be looked at in general.
  607. size_t amount = 0;
  608. ScopedSpinLock lock(m_lock);
  609. for (auto& region : m_regions) {
  610. if (!region.is_shared())
  611. amount += region.amount_dirty();
  612. }
  613. return amount;
  614. }
  615. size_t Process::amount_clean_inode() const
  616. {
  617. HashTable<const InodeVMObject*> vmobjects;
  618. {
  619. ScopedSpinLock lock(m_lock);
  620. for (auto& region : m_regions) {
  621. if (region.vmobject().is_inode())
  622. vmobjects.set(&static_cast<const InodeVMObject&>(region.vmobject()));
  623. }
  624. }
  625. size_t amount = 0;
  626. for (auto& vmobject : vmobjects)
  627. amount += vmobject->amount_clean();
  628. return amount;
  629. }
  630. size_t Process::amount_virtual() const
  631. {
  632. size_t amount = 0;
  633. ScopedSpinLock lock(m_lock);
  634. for (auto& region : m_regions) {
  635. amount += region.size();
  636. }
  637. return amount;
  638. }
  639. size_t Process::amount_resident() const
  640. {
  641. // FIXME: This will double count if multiple regions use the same physical page.
  642. size_t amount = 0;
  643. ScopedSpinLock lock(m_lock);
  644. for (auto& region : m_regions) {
  645. amount += region.amount_resident();
  646. }
  647. return amount;
  648. }
  649. size_t Process::amount_shared() const
  650. {
  651. // FIXME: This will double count if multiple regions use the same physical page.
  652. // FIXME: It doesn't work at the moment, since it relies on PhysicalPage ref counts,
  653. // and each PhysicalPage is only reffed by its VMObject. This needs to be refactored
  654. // so that every Region contributes +1 ref to each of its PhysicalPages.
  655. size_t amount = 0;
  656. ScopedSpinLock lock(m_lock);
  657. for (auto& region : m_regions) {
  658. amount += region.amount_shared();
  659. }
  660. return amount;
  661. }
  662. size_t Process::amount_purgeable_volatile() const
  663. {
  664. size_t amount = 0;
  665. ScopedSpinLock lock(m_lock);
  666. for (auto& region : m_regions) {
  667. if (region.vmobject().is_anonymous() && static_cast<const AnonymousVMObject&>(region.vmobject()).is_any_volatile())
  668. amount += region.amount_resident();
  669. }
  670. return amount;
  671. }
  672. size_t Process::amount_purgeable_nonvolatile() const
  673. {
  674. size_t amount = 0;
  675. ScopedSpinLock lock(m_lock);
  676. for (auto& region : m_regions) {
  677. if (region.vmobject().is_anonymous() && !static_cast<const AnonymousVMObject&>(region.vmobject()).is_any_volatile())
  678. amount += region.amount_resident();
  679. }
  680. return amount;
  681. }
  682. void Process::terminate_due_to_signal(u8 signal)
  683. {
  684. ASSERT_INTERRUPTS_DISABLED();
  685. ASSERT(signal < 32);
  686. ASSERT(Process::current() == this);
  687. dbgln("Terminating {} due to signal {}", *this, signal);
  688. m_termination_status = 0;
  689. m_termination_signal = signal;
  690. die();
  691. }
  692. KResult Process::send_signal(u8 signal, Process* sender)
  693. {
  694. // Try to send it to the "obvious" main thread:
  695. auto receiver_thread = Thread::from_tid(m_pid.value());
  696. // If the main thread has died, there may still be other threads:
  697. if (!receiver_thread) {
  698. // The first one should be good enough.
  699. // Neither kill(2) nor kill(3) specify any selection precedure.
  700. for_each_thread([&receiver_thread](Thread& thread) -> IterationDecision {
  701. receiver_thread = &thread;
  702. return IterationDecision::Break;
  703. });
  704. }
  705. if (receiver_thread) {
  706. receiver_thread->send_signal(signal, sender);
  707. return KSuccess;
  708. }
  709. return ESRCH;
  710. }
  711. RefPtr<Thread> Process::create_kernel_thread(void (*entry)(void*), void* entry_data, u32 priority, const String& name, u32 affinity, bool joinable)
  712. {
  713. ASSERT((priority >= THREAD_PRIORITY_MIN) && (priority <= THREAD_PRIORITY_MAX));
  714. // FIXME: Do something with guard pages?
  715. auto thread = adopt(*new Thread(*this));
  716. if (!thread->was_created()) {
  717. // Could not fully create this thread
  718. return {};
  719. }
  720. thread->set_name(name);
  721. thread->set_affinity(affinity);
  722. thread->set_priority(priority);
  723. if (!joinable)
  724. thread->detach();
  725. auto& tss = thread->tss();
  726. tss.eip = (FlatPtr)entry;
  727. tss.esp = FlatPtr(entry_data); // entry function argument is expected to be in tss.esp
  728. ScopedSpinLock lock(g_scheduler_lock);
  729. thread->set_state(Thread::State::Runnable);
  730. return thread;
  731. }
  732. void Process::FileDescriptionAndFlags::clear()
  733. {
  734. m_description = nullptr;
  735. m_flags = 0;
  736. }
  737. void Process::FileDescriptionAndFlags::set(NonnullRefPtr<FileDescription>&& description, u32 flags)
  738. {
  739. m_description = move(description);
  740. m_flags = flags;
  741. }
  742. OwnPtr<KBuffer> Process::backtrace() const
  743. {
  744. KBufferBuilder builder;
  745. for_each_thread([&](Thread& thread) {
  746. builder.appendf("Thread %d (%s):\n", thread.tid().value(), thread.name().characters());
  747. builder.append(thread.backtrace());
  748. return IterationDecision::Continue;
  749. });
  750. return builder.build();
  751. }
  752. Custody& Process::root_directory()
  753. {
  754. if (!m_root_directory)
  755. m_root_directory = VFS::the().root_custody();
  756. return *m_root_directory;
  757. }
  758. Custody& Process::root_directory_relative_to_global_root()
  759. {
  760. if (!m_root_directory_relative_to_global_root)
  761. m_root_directory_relative_to_global_root = root_directory();
  762. return *m_root_directory_relative_to_global_root;
  763. }
  764. void Process::set_root_directory(const Custody& root)
  765. {
  766. m_root_directory = root;
  767. }
  768. Region& Process::add_region(NonnullOwnPtr<Region> region)
  769. {
  770. auto* ptr = region.ptr();
  771. ScopedSpinLock lock(m_lock);
  772. m_regions.append(move(region));
  773. return *ptr;
  774. }
  775. void Process::set_tty(TTY* tty)
  776. {
  777. m_tty = tty;
  778. }
  779. void Process::start_tracing_from(ProcessID tracer)
  780. {
  781. m_tracer = ThreadTracer::create(tracer);
  782. }
  783. void Process::stop_tracing()
  784. {
  785. m_tracer = nullptr;
  786. }
  787. void Process::tracer_trap(Thread& thread, const RegisterState& regs)
  788. {
  789. ASSERT(m_tracer.ptr());
  790. m_tracer->set_regs(regs);
  791. thread.send_urgent_signal_to_self(SIGTRAP);
  792. }
  793. PerformanceEventBuffer& Process::ensure_perf_events()
  794. {
  795. if (!m_perf_event_buffer)
  796. m_perf_event_buffer = make<PerformanceEventBuffer>();
  797. return *m_perf_event_buffer;
  798. }
  799. bool Process::remove_thread(Thread& thread)
  800. {
  801. auto thread_cnt_before = m_thread_count.fetch_sub(1, AK::MemoryOrder::memory_order_acq_rel);
  802. ASSERT(thread_cnt_before != 0);
  803. ScopedSpinLock thread_list_lock(m_thread_list_lock);
  804. m_thread_list.remove(thread);
  805. return thread_cnt_before == 1;
  806. }
  807. bool Process::add_thread(Thread& thread)
  808. {
  809. bool is_first = m_thread_count.fetch_add(1, AK::MemoryOrder::memory_order_relaxed) == 0;
  810. ScopedSpinLock thread_list_lock(m_thread_list_lock);
  811. m_thread_list.append(thread);
  812. return is_first;
  813. }
  814. }