Process.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. /*
  2. * Copyright (c) 2018-2020, 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/Devices/NullDevice.h>
  35. #include <Kernel/FileSystem/Custody.h>
  36. #include <Kernel/FileSystem/FileDescription.h>
  37. #include <Kernel/FileSystem/VirtualFileSystem.h>
  38. #include <Kernel/Heap/kmalloc.h>
  39. #include <Kernel/KBufferBuilder.h>
  40. #include <Kernel/KSyms.h>
  41. #include <Kernel/Module.h>
  42. #include <Kernel/PerformanceEventBuffer.h>
  43. #include <Kernel/Process.h>
  44. #include <Kernel/SharedBuffer.h>
  45. #include <Kernel/StdLib.h>
  46. #include <Kernel/TTY/TTY.h>
  47. #include <Kernel/Thread.h>
  48. #include <Kernel/VM/PageDirectory.h>
  49. #include <Kernel/VM/SharedInodeVMObject.h>
  50. #include <LibC/errno_numbers.h>
  51. #include <LibC/limits.h>
  52. #include <LibELF/Loader.h>
  53. //#define DEBUG_IO
  54. //#define DEBUG_POLL_SELECT
  55. //#define MM_DEBUG
  56. //#define PROCESS_DEBUG
  57. //#define SIGNAL_DEBUG
  58. namespace Kernel {
  59. static void create_signal_trampolines();
  60. RecursiveSpinLock g_processes_lock;
  61. static Atomic<pid_t> next_pid;
  62. InlineLinkedList<Process>* g_processes;
  63. String* g_hostname;
  64. Lock* g_hostname_lock;
  65. VirtualAddress g_return_to_ring3_from_signal_trampoline;
  66. HashMap<String, OwnPtr<Module>>* g_modules;
  67. ProcessID Process::allocate_pid()
  68. {
  69. // Overflow is UB, and negative PIDs wreck havoc.
  70. // TODO: Handle PID overflow
  71. // For example: Use an Atomic<u32>, mask the most significant bit,
  72. // retry if PID is already taken as a PID, taken as a TID,
  73. // takes as a PGID, taken as a SID, or zero.
  74. return next_pid.fetch_add(1, AK::MemoryOrder::memory_order_acq_rel);
  75. }
  76. void Process::initialize()
  77. {
  78. g_modules = new HashMap<String, OwnPtr<Module>>;
  79. next_pid.store(0, AK::MemoryOrder::memory_order_release);
  80. g_processes = new InlineLinkedList<Process>;
  81. g_process_groups = new InlineLinkedList<ProcessGroup>;
  82. g_hostname = new String("courage");
  83. g_hostname_lock = new Lock;
  84. create_signal_trampolines();
  85. }
  86. Vector<ProcessID> Process::all_pids()
  87. {
  88. Vector<ProcessID> pids;
  89. ScopedSpinLock lock(g_processes_lock);
  90. pids.ensure_capacity((int)g_processes->size_slow());
  91. for (auto& process : *g_processes)
  92. pids.append(process.pid());
  93. return pids;
  94. }
  95. NonnullRefPtrVector<Process> Process::all_processes()
  96. {
  97. NonnullRefPtrVector<Process> processes;
  98. ScopedSpinLock lock(g_processes_lock);
  99. processes.ensure_capacity((int)g_processes->size_slow());
  100. for (auto& process : *g_processes)
  101. processes.append(NonnullRefPtr<Process>(process));
  102. return processes;
  103. }
  104. bool Process::in_group(gid_t gid) const
  105. {
  106. return m_gid == gid || m_extra_gids.contains_slow(gid);
  107. }
  108. Range Process::allocate_range(VirtualAddress vaddr, size_t size, size_t alignment)
  109. {
  110. vaddr.mask(PAGE_MASK);
  111. size = PAGE_ROUND_UP(size);
  112. if (vaddr.is_null())
  113. return page_directory().range_allocator().allocate_anywhere(size, alignment);
  114. return page_directory().range_allocator().allocate_specific(vaddr, size);
  115. }
  116. Region& Process::allocate_split_region(const Region& source_region, const Range& range, size_t offset_in_vmobject)
  117. {
  118. auto& region = add_region(Region::create_user_accessible(range, source_region.vmobject(), offset_in_vmobject, source_region.name(), source_region.access()));
  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. Region* Process::allocate_region(const Range& range, const String& name, int prot, bool should_commit)
  129. {
  130. ASSERT(range.is_valid());
  131. auto vmobject = AnonymousVMObject::create_with_size(range.size());
  132. auto region = Region::create_user_accessible(range, vmobject, 0, name, prot_to_region_access_flags(prot));
  133. region->map(page_directory());
  134. if (should_commit && !region->commit())
  135. return nullptr;
  136. return &add_region(move(region));
  137. }
  138. Region* Process::allocate_region(VirtualAddress vaddr, size_t size, const String& name, int prot, bool should_commit)
  139. {
  140. auto range = allocate_range(vaddr, size);
  141. if (!range.is_valid())
  142. return nullptr;
  143. return allocate_region(range, name, prot, should_commit);
  144. }
  145. Region* Process::allocate_region_with_vmobject(const Range& range, NonnullRefPtr<VMObject> vmobject, size_t offset_in_vmobject, const String& name, int prot)
  146. {
  147. ASSERT(range.is_valid());
  148. size_t end_in_vmobject = offset_in_vmobject + range.size();
  149. if (end_in_vmobject <= offset_in_vmobject) {
  150. dbg() << "allocate_region_with_vmobject: Overflow (offset + size)";
  151. return nullptr;
  152. }
  153. if (offset_in_vmobject >= vmobject->size()) {
  154. dbg() << "allocate_region_with_vmobject: Attempt to allocate a region with an offset past the end of its VMObject.";
  155. return nullptr;
  156. }
  157. if (end_in_vmobject > vmobject->size()) {
  158. dbg() << "allocate_region_with_vmobject: Attempt to allocate a region with an end past the end of its VMObject.";
  159. return nullptr;
  160. }
  161. offset_in_vmobject &= PAGE_MASK;
  162. auto& region = add_region(Region::create_user_accessible(range, move(vmobject), offset_in_vmobject, name, prot_to_region_access_flags(prot)));
  163. region.map(page_directory());
  164. return &region;
  165. }
  166. Region* Process::allocate_region_with_vmobject(VirtualAddress vaddr, size_t size, NonnullRefPtr<VMObject> vmobject, size_t offset_in_vmobject, const String& name, int prot)
  167. {
  168. auto range = allocate_range(vaddr, size);
  169. if (!range.is_valid())
  170. return nullptr;
  171. return allocate_region_with_vmobject(range, move(vmobject), offset_in_vmobject, name, prot);
  172. }
  173. bool Process::deallocate_region(Region& region)
  174. {
  175. OwnPtr<Region> region_protector;
  176. ScopedSpinLock lock(m_lock);
  177. if (m_region_lookup_cache.region == &region)
  178. m_region_lookup_cache.region = nullptr;
  179. for (size_t i = 0; i < m_regions.size(); ++i) {
  180. if (&m_regions[i] == &region) {
  181. region_protector = m_regions.unstable_take(i);
  182. return true;
  183. }
  184. }
  185. return false;
  186. }
  187. Region* Process::find_region_from_range(const Range& range)
  188. {
  189. ScopedSpinLock lock(m_lock);
  190. if (m_region_lookup_cache.range == range && m_region_lookup_cache.region)
  191. return m_region_lookup_cache.region;
  192. size_t size = PAGE_ROUND_UP(range.size());
  193. for (auto& region : m_regions) {
  194. if (region.vaddr() == range.base() && region.size() == size) {
  195. m_region_lookup_cache.range = range;
  196. m_region_lookup_cache.region = region.make_weak_ptr();
  197. return &region;
  198. }
  199. }
  200. return nullptr;
  201. }
  202. Region* Process::find_region_containing(const Range& range)
  203. {
  204. ScopedSpinLock lock(m_lock);
  205. for (auto& region : m_regions) {
  206. if (region.contains(range))
  207. return &region;
  208. }
  209. return nullptr;
  210. }
  211. void Process::kill_threads_except_self()
  212. {
  213. InterruptDisabler disabler;
  214. if (thread_count() <= 1)
  215. return;
  216. auto current_thread = Thread::current();
  217. for_each_thread([&](Thread& thread) {
  218. if (&thread == current_thread
  219. || thread.state() == Thread::State::Dead
  220. || thread.state() == Thread::State::Dying)
  221. return IterationDecision::Continue;
  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. big_lock().clear_waiters();
  228. }
  229. void Process::kill_all_threads()
  230. {
  231. for_each_thread([&](Thread& thread) {
  232. // We need to detach this thread in case it hasn't been joined
  233. thread.detach();
  234. thread.set_should_die();
  235. return IterationDecision::Continue;
  236. });
  237. }
  238. 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)
  239. {
  240. auto parts = path.split('/');
  241. if (arguments.is_empty()) {
  242. arguments.append(parts.last());
  243. }
  244. RefPtr<Custody> cwd;
  245. RefPtr<Custody> root;
  246. {
  247. ScopedSpinLock lock(g_processes_lock);
  248. if (auto parent = Process::from_pid(parent_pid)) {
  249. cwd = parent->m_cwd;
  250. root = parent->m_root_directory;
  251. }
  252. }
  253. if (!cwd)
  254. cwd = VFS::the().root_custody();
  255. if (!root)
  256. root = VFS::the().root_custody();
  257. auto process = adopt(*new Process(first_thread, parts.take_last(), uid, gid, parent_pid, false, move(cwd), nullptr, tty));
  258. process->m_fds.resize(m_max_open_file_descriptors);
  259. auto& device_to_use_as_tty = tty ? (CharacterDevice&)*tty : NullDevice::the();
  260. auto description = device_to_use_as_tty.open(O_RDWR).value();
  261. process->m_fds[0].set(*description);
  262. process->m_fds[1].set(*description);
  263. process->m_fds[2].set(*description);
  264. error = process->exec(path, move(arguments), move(environment));
  265. if (error != 0) {
  266. dbg() << "Failed to exec " << path << ": " << error;
  267. first_thread = nullptr;
  268. return {};
  269. }
  270. {
  271. ScopedSpinLock lock(g_processes_lock);
  272. g_processes->prepend(process);
  273. process->ref();
  274. }
  275. error = 0;
  276. return process;
  277. }
  278. NonnullRefPtr<Process> Process::create_kernel_process(RefPtr<Thread>& first_thread, String&& name, void (*e)(), u32 affinity)
  279. {
  280. auto process = adopt(*new Process(first_thread, move(name), (uid_t)0, (gid_t)0, ProcessID(0), true));
  281. first_thread->tss().eip = (FlatPtr)e;
  282. if (process->pid() != 0) {
  283. ScopedSpinLock lock(g_processes_lock);
  284. g_processes->prepend(process);
  285. process->ref();
  286. }
  287. first_thread->set_affinity(affinity);
  288. first_thread->set_state(Thread::State::Runnable);
  289. return process;
  290. }
  291. 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)
  292. : m_name(move(name))
  293. , m_pid(allocate_pid())
  294. , m_euid(uid)
  295. , m_egid(gid)
  296. , m_uid(uid)
  297. , m_gid(gid)
  298. , m_suid(uid)
  299. , m_sgid(gid)
  300. , m_is_kernel_process(is_kernel_process)
  301. , m_executable(move(executable))
  302. , m_cwd(move(cwd))
  303. , m_tty(tty)
  304. , m_ppid(ppid)
  305. {
  306. #ifdef PROCESS_DEBUG
  307. dbg() << "Created new process " << m_name << "(" << m_pid.value() << ")";
  308. #endif
  309. m_page_directory = PageDirectory::create_for_userspace(*this, fork_parent ? &fork_parent->page_directory().range_allocator() : nullptr);
  310. #ifdef MM_DEBUG
  311. dbg() << "Process " << pid().value() << " ctor: PD=" << m_page_directory.ptr() << " created";
  312. #endif
  313. if (fork_parent) {
  314. // NOTE: fork() doesn't clone all threads; the thread that called fork() becomes the only thread in the new process.
  315. first_thread = Thread::current()->clone(*this);
  316. } else {
  317. // NOTE: This non-forked code path is only taken when the kernel creates a process "manually" (at boot.)
  318. first_thread = adopt(*new Thread(*this));
  319. first_thread->detach();
  320. }
  321. }
  322. Process::~Process()
  323. {
  324. ASSERT(!m_next && !m_prev); // should have been reaped
  325. ASSERT(thread_count() == 0); // all threads should have been finalized
  326. }
  327. void Process::dump_regions()
  328. {
  329. klog() << "Process regions:";
  330. klog() << "BEGIN END SIZE ACCESS NAME";
  331. ScopedSpinLock lock(m_lock);
  332. Vector<Region*> sorted_regions;
  333. sorted_regions.ensure_capacity(m_regions.size());
  334. for (auto& region : m_regions)
  335. sorted_regions.append(&region);
  336. quick_sort(sorted_regions, [](auto& a, auto& b) {
  337. return a->vaddr() < b->vaddr();
  338. });
  339. for (auto& sorted_region : sorted_regions) {
  340. auto& region = *sorted_region;
  341. klog() << String::format("%08x", region.vaddr().get()) << " -- " << String::format("%08x", region.vaddr().offset(region.size() - 1).get()) << " " << String::format("%08x", 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_purgeable() ? 'P' : ' ') << " " << region.name().characters();
  342. }
  343. MM.dump_kernel_regions();
  344. }
  345. // Make sure the compiler doesn't "optimize away" this function:
  346. extern void signal_trampoline_dummy(void);
  347. void signal_trampoline_dummy(void)
  348. {
  349. // The trampoline preserves the current eax, pushes the signal code and
  350. // then calls the signal handler. We do this because, when interrupting a
  351. // blocking syscall, that syscall may return some special error code in eax;
  352. // This error code would likely be overwritten by the signal handler, so it's
  353. // necessary to preserve it here.
  354. asm(
  355. ".intel_syntax noprefix\n"
  356. "asm_signal_trampoline:\n"
  357. "push ebp\n"
  358. "mov ebp, esp\n"
  359. "push eax\n" // we have to store eax 'cause it might be the return value from a syscall
  360. "sub esp, 4\n" // align the stack to 16 bytes
  361. "mov eax, [ebp+12]\n" // push the signal code
  362. "push eax\n"
  363. "call [ebp+8]\n" // call the signal handler
  364. "add esp, 8\n"
  365. "mov eax, %P0\n"
  366. "int 0x82\n" // sigreturn syscall
  367. "asm_signal_trampoline_end:\n"
  368. ".att_syntax" ::"i"(Syscall::SC_sigreturn));
  369. }
  370. extern "C" void asm_signal_trampoline(void);
  371. extern "C" void asm_signal_trampoline_end(void);
  372. void create_signal_trampolines()
  373. {
  374. InterruptDisabler disabler;
  375. // NOTE: We leak this region.
  376. 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();
  377. g_return_to_ring3_from_signal_trampoline = trampoline_region->vaddr();
  378. u8* trampoline = (u8*)asm_signal_trampoline;
  379. u8* trampoline_end = (u8*)asm_signal_trampoline_end;
  380. size_t trampoline_size = trampoline_end - trampoline;
  381. {
  382. SmapDisabler disabler;
  383. u8* code_ptr = (u8*)trampoline_region->vaddr().as_ptr();
  384. memcpy(code_ptr, trampoline, trampoline_size);
  385. }
  386. trampoline_region->set_writable(false);
  387. trampoline_region->remap();
  388. }
  389. void Process::crash(int signal, u32 eip, bool out_of_memory)
  390. {
  391. ASSERT_INTERRUPTS_DISABLED();
  392. ASSERT(!is_dead());
  393. ASSERT(Process::current() == this);
  394. if (out_of_memory) {
  395. dbg() << "\033[31;1mOut of memory\033[m, killing: " << *this;
  396. } else {
  397. if (eip >= 0xc0000000 && g_kernel_symbols_available) {
  398. auto* symbol = symbolicate_kernel_address(eip);
  399. dbg() << "\033[31;1m" << String::format("%p", eip) << " " << (symbol ? demangle(symbol->name) : "(k?)") << " +" << (symbol ? eip - symbol->address : 0) << "\033[0m\n";
  400. } else if (auto elf_bundle = this->elf_bundle()) {
  401. dbg() << "\033[31;1m" << String::format("%p", eip) << " " << elf_bundle->elf_loader->symbolicate(eip) << "\033[0m\n";
  402. } else {
  403. dbg() << "\033[31;1m" << String::format("%p", eip) << " (?)\033[0m\n";
  404. }
  405. dump_backtrace();
  406. }
  407. m_termination_signal = signal;
  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 g_timeofday;
  462. }
  463. void kgettimeofday(timeval& tv)
  464. {
  465. tv = kgettimeofday();
  466. }
  467. siginfo_t Process::reap(Process& process)
  468. {
  469. siginfo_t siginfo;
  470. memset(&siginfo, 0, sizeof(siginfo));
  471. siginfo.si_signo = SIGCHLD;
  472. siginfo.si_pid = process.pid().value();
  473. siginfo.si_uid = process.uid();
  474. if (process.m_termination_signal) {
  475. siginfo.si_status = process.m_termination_signal;
  476. siginfo.si_code = CLD_KILLED;
  477. } else {
  478. siginfo.si_status = process.m_termination_status;
  479. siginfo.si_code = CLD_EXITED;
  480. }
  481. ASSERT(g_processes_lock.is_locked());
  482. if (!!process.ppid()) {
  483. auto parent = Process::from_pid(process.ppid());
  484. if (parent) {
  485. parent->m_ticks_in_user_for_dead_children += process.m_ticks_in_user + process.m_ticks_in_user_for_dead_children;
  486. parent->m_ticks_in_kernel_for_dead_children += process.m_ticks_in_kernel + process.m_ticks_in_kernel_for_dead_children;
  487. }
  488. }
  489. #ifdef PROCESS_DEBUG
  490. dbg() << "Reaping process " << process;
  491. #endif
  492. ASSERT(process.is_dead());
  493. g_processes->remove(&process);
  494. process.unref();
  495. return siginfo;
  496. }
  497. Custody& Process::current_directory()
  498. {
  499. if (!m_cwd)
  500. m_cwd = VFS::the().root_custody();
  501. return *m_cwd;
  502. }
  503. KResultOr<String> Process::get_syscall_path_argument(const char* user_path, size_t path_length) const
  504. {
  505. if (path_length == 0)
  506. return KResult(-EINVAL);
  507. if (path_length > PATH_MAX)
  508. return KResult(-ENAMETOOLONG);
  509. auto copied_string = copy_string_from_user(user_path, path_length);
  510. if (copied_string.is_null())
  511. return KResult(-EFAULT);
  512. return copied_string;
  513. }
  514. KResultOr<String> Process::get_syscall_path_argument(const Syscall::StringArgument& path) const
  515. {
  516. return get_syscall_path_argument(path.characters, path.length);
  517. }
  518. void Process::finalize()
  519. {
  520. ASSERT(Thread::current() == g_finalizer);
  521. #ifdef PROCESS_DEBUG
  522. dbg() << "Finalizing process " << *this;
  523. #endif
  524. if (m_perf_event_buffer) {
  525. auto description_or_error = VFS::the().open(String::format("perfcore.%d", m_pid), O_CREAT | O_EXCL, 0400, current_directory(), UidAndGid { m_uid, m_gid });
  526. if (!description_or_error.is_error()) {
  527. auto& description = description_or_error.value();
  528. auto json = m_perf_event_buffer->to_json(m_pid, m_executable ? m_executable->absolute_path() : "");
  529. auto json_buffer = UserOrKernelBuffer::for_kernel_buffer(json.data());
  530. auto result = description->write(json_buffer, json.size());
  531. if (result.is_error()) {
  532. dbgln("Error while writing perfcore file: {}", result.error().error());
  533. }
  534. }
  535. }
  536. m_fds.clear();
  537. m_tty = nullptr;
  538. m_executable = nullptr;
  539. m_cwd = nullptr;
  540. m_root_directory = nullptr;
  541. m_root_directory_relative_to_global_root = nullptr;
  542. disown_all_shared_buffers();
  543. {
  544. InterruptDisabler disabler;
  545. // FIXME: PID/TID BUG
  546. if (auto parent_thread = Thread::from_tid(m_ppid.value())) {
  547. if (parent_thread->m_signal_action_data[SIGCHLD].flags & SA_NOCLDWAIT) {
  548. // NOTE: If the parent doesn't care about this process, let it go.
  549. m_ppid = 0;
  550. } else {
  551. parent_thread->send_signal(SIGCHLD, this);
  552. }
  553. }
  554. }
  555. {
  556. ScopedSpinLock lock(m_lock);
  557. m_regions.clear();
  558. }
  559. m_dead = true;
  560. }
  561. void Process::die()
  562. {
  563. // Let go of the TTY, otherwise a slave PTY may keep the master PTY from
  564. // getting an EOF when the last process using the slave PTY dies.
  565. // If the master PTY owner relies on an EOF to know when to wait() on a
  566. // slave owner, we have to allow the PTY pair to be torn down.
  567. m_tty = nullptr;
  568. kill_all_threads();
  569. }
  570. size_t Process::amount_dirty_private() const
  571. {
  572. // FIXME: This gets a bit more complicated for Regions sharing the same underlying VMObject.
  573. // The main issue I'm thinking of is when the VMObject has physical pages that none of the Regions are mapping.
  574. // That's probably a situation that needs to be looked at in general.
  575. size_t amount = 0;
  576. ScopedSpinLock lock(m_lock);
  577. for (auto& region : m_regions) {
  578. if (!region.is_shared())
  579. amount += region.amount_dirty();
  580. }
  581. return amount;
  582. }
  583. size_t Process::amount_clean_inode() const
  584. {
  585. HashTable<const InodeVMObject*> vmobjects;
  586. {
  587. ScopedSpinLock lock(m_lock);
  588. for (auto& region : m_regions) {
  589. if (region.vmobject().is_inode())
  590. vmobjects.set(&static_cast<const InodeVMObject&>(region.vmobject()));
  591. }
  592. }
  593. size_t amount = 0;
  594. for (auto& vmobject : vmobjects)
  595. amount += vmobject->amount_clean();
  596. return amount;
  597. }
  598. size_t Process::amount_virtual() const
  599. {
  600. size_t amount = 0;
  601. ScopedSpinLock lock(m_lock);
  602. for (auto& region : m_regions) {
  603. amount += region.size();
  604. }
  605. return amount;
  606. }
  607. size_t Process::amount_resident() const
  608. {
  609. // FIXME: This will double count if multiple regions use the same physical page.
  610. size_t amount = 0;
  611. ScopedSpinLock lock(m_lock);
  612. for (auto& region : m_regions) {
  613. amount += region.amount_resident();
  614. }
  615. return amount;
  616. }
  617. size_t Process::amount_shared() const
  618. {
  619. // FIXME: This will double count if multiple regions use the same physical page.
  620. // FIXME: It doesn't work at the moment, since it relies on PhysicalPage ref counts,
  621. // and each PhysicalPage is only reffed by its VMObject. This needs to be refactored
  622. // so that every Region contributes +1 ref to each of its PhysicalPages.
  623. size_t amount = 0;
  624. ScopedSpinLock lock(m_lock);
  625. for (auto& region : m_regions) {
  626. amount += region.amount_shared();
  627. }
  628. return amount;
  629. }
  630. size_t Process::amount_purgeable_volatile() const
  631. {
  632. size_t amount = 0;
  633. ScopedSpinLock lock(m_lock);
  634. for (auto& region : m_regions) {
  635. if (region.vmobject().is_purgeable() && static_cast<const PurgeableVMObject&>(region.vmobject()).is_volatile())
  636. amount += region.amount_resident();
  637. }
  638. return amount;
  639. }
  640. size_t Process::amount_purgeable_nonvolatile() const
  641. {
  642. size_t amount = 0;
  643. ScopedSpinLock lock(m_lock);
  644. for (auto& region : m_regions) {
  645. if (region.vmobject().is_purgeable() && !static_cast<const PurgeableVMObject&>(region.vmobject()).is_volatile())
  646. amount += region.amount_resident();
  647. }
  648. return amount;
  649. }
  650. void Process::terminate_due_to_signal(u8 signal)
  651. {
  652. ASSERT_INTERRUPTS_DISABLED();
  653. ASSERT(signal < 32);
  654. dbg() << "Terminating " << *this << " due to signal " << signal;
  655. m_termination_status = 0;
  656. m_termination_signal = signal;
  657. die();
  658. }
  659. KResult Process::send_signal(u8 signal, Process* sender)
  660. {
  661. InterruptDisabler disabler;
  662. Thread* receiver_thread;
  663. // Try to send it to the "obvious" main thread:
  664. receiver_thread = Thread::from_tid(m_pid.value());
  665. // If the main thread has died, there may still be other threads:
  666. if (!receiver_thread) {
  667. // The first one should be good enough.
  668. // Neither kill(2) nor kill(3) specify any selection precedure.
  669. for_each_thread([&receiver_thread](Thread& thread) -> IterationDecision {
  670. receiver_thread = &thread;
  671. return IterationDecision::Break;
  672. });
  673. }
  674. if (receiver_thread) {
  675. receiver_thread->send_signal(signal, sender);
  676. return KSuccess;
  677. }
  678. return KResult(-ESRCH);
  679. }
  680. RefPtr<Thread> Process::create_kernel_thread(void (*entry)(), u32 priority, const String& name, u32 affinity, bool joinable)
  681. {
  682. ASSERT((priority >= THREAD_PRIORITY_MIN) && (priority <= THREAD_PRIORITY_MAX));
  683. // FIXME: Do something with guard pages?
  684. auto thread = adopt(*new Thread(*this));
  685. thread->set_name(name);
  686. thread->set_affinity(affinity);
  687. thread->set_priority(priority);
  688. if (!joinable)
  689. thread->detach();
  690. auto& tss = thread->tss();
  691. tss.eip = (FlatPtr)entry;
  692. thread->set_state(Thread::State::Runnable);
  693. return thread;
  694. }
  695. void Process::FileDescriptionAndFlags::clear()
  696. {
  697. m_description = nullptr;
  698. m_flags = 0;
  699. }
  700. void Process::FileDescriptionAndFlags::set(NonnullRefPtr<FileDescription>&& description, u32 flags)
  701. {
  702. m_description = move(description);
  703. m_flags = flags;
  704. }
  705. KBuffer Process::backtrace() const
  706. {
  707. KBufferBuilder builder;
  708. for_each_thread([&](Thread& thread) {
  709. builder.appendf("Thread %d (%s):\n", thread.tid().value(), thread.name().characters());
  710. builder.append(thread.backtrace());
  711. return IterationDecision::Continue;
  712. });
  713. return builder.build();
  714. }
  715. Custody& Process::root_directory()
  716. {
  717. if (!m_root_directory)
  718. m_root_directory = VFS::the().root_custody();
  719. return *m_root_directory;
  720. }
  721. Custody& Process::root_directory_relative_to_global_root()
  722. {
  723. if (!m_root_directory_relative_to_global_root)
  724. m_root_directory_relative_to_global_root = root_directory();
  725. return *m_root_directory_relative_to_global_root;
  726. }
  727. void Process::set_root_directory(const Custody& root)
  728. {
  729. m_root_directory = root;
  730. }
  731. Region& Process::add_region(NonnullOwnPtr<Region> region)
  732. {
  733. auto* ptr = region.ptr();
  734. ScopedSpinLock lock(m_lock);
  735. m_regions.append(move(region));
  736. return *ptr;
  737. }
  738. void Process::set_tty(TTY* tty)
  739. {
  740. m_tty = tty;
  741. }
  742. OwnPtr<Process::ELFBundle> Process::elf_bundle() const
  743. {
  744. if (!m_executable)
  745. return nullptr;
  746. auto bundle = make<ELFBundle>();
  747. if (!m_executable->inode().shared_vmobject()) {
  748. return nullptr;
  749. }
  750. ASSERT(m_executable->inode().shared_vmobject());
  751. auto& vmobject = *m_executable->inode().shared_vmobject();
  752. bundle->region = MM.allocate_kernel_region_with_vmobject(const_cast<SharedInodeVMObject&>(vmobject), vmobject.size(), "ELF bundle", Region::Access::Read);
  753. if (!bundle->region)
  754. return nullptr;
  755. bundle->elf_loader = ELF::Loader::create(bundle->region->vaddr().as_ptr(), bundle->region->size());
  756. return bundle;
  757. }
  758. }