Process.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  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.unsafe_ptr() == &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.unsafe_ptr();
  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;
  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 (*entry)(void*), void* entry_data, 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)entry;
  282. first_thread->tss().esp = FlatPtr(entry_data); // entry function argument is expected to be in tss.esp
  283. if (process->pid() != 0) {
  284. ScopedSpinLock lock(g_processes_lock);
  285. g_processes->prepend(process);
  286. process->ref();
  287. }
  288. ScopedSpinLock lock(g_scheduler_lock);
  289. first_thread->set_affinity(affinity);
  290. first_thread->set_state(Thread::State::Runnable);
  291. return process;
  292. }
  293. 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)
  294. : m_name(move(name))
  295. , m_pid(allocate_pid())
  296. , m_euid(uid)
  297. , m_egid(gid)
  298. , m_uid(uid)
  299. , m_gid(gid)
  300. , m_suid(uid)
  301. , m_sgid(gid)
  302. , m_is_kernel_process(is_kernel_process)
  303. , m_executable(move(executable))
  304. , m_cwd(move(cwd))
  305. , m_tty(tty)
  306. , m_ppid(ppid)
  307. , m_wait_block_condition(*this)
  308. {
  309. #ifdef PROCESS_DEBUG
  310. dbg() << "Created new process " << m_name << "(" << m_pid.value() << ")";
  311. #endif
  312. m_page_directory = PageDirectory::create_for_userspace(*this, fork_parent ? &fork_parent->page_directory().range_allocator() : nullptr);
  313. #ifdef MM_DEBUG
  314. dbg() << "Process " << pid().value() << " ctor: PD=" << m_page_directory.ptr() << " created";
  315. #endif
  316. if (fork_parent) {
  317. // NOTE: fork() doesn't clone all threads; the thread that called fork() becomes the only thread in the new process.
  318. first_thread = Thread::current()->clone(*this);
  319. } else {
  320. // NOTE: This non-forked code path is only taken when the kernel creates a process "manually" (at boot.)
  321. first_thread = adopt(*new Thread(*this));
  322. first_thread->detach();
  323. }
  324. }
  325. Process::~Process()
  326. {
  327. ASSERT(thread_count() == 0); // all threads should have been finalized
  328. ASSERT(!m_alarm_timer);
  329. {
  330. ScopedSpinLock processses_lock(g_processes_lock);
  331. if (prev() || next())
  332. g_processes->remove(this);
  333. }
  334. }
  335. void Process::dump_regions()
  336. {
  337. klog() << "Process regions:";
  338. klog() << "BEGIN END SIZE ACCESS NAME";
  339. ScopedSpinLock lock(m_lock);
  340. Vector<Region*> sorted_regions;
  341. sorted_regions.ensure_capacity(m_regions.size());
  342. for (auto& region : m_regions)
  343. sorted_regions.append(&region);
  344. quick_sort(sorted_regions, [](auto& a, auto& b) {
  345. return a->vaddr() < b->vaddr();
  346. });
  347. for (auto& sorted_region : sorted_regions) {
  348. auto& region = *sorted_region;
  349. 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();
  350. }
  351. MM.dump_kernel_regions();
  352. }
  353. // Make sure the compiler doesn't "optimize away" this function:
  354. extern void signal_trampoline_dummy(void);
  355. void signal_trampoline_dummy(void)
  356. {
  357. // The trampoline preserves the current eax, pushes the signal code and
  358. // then calls the signal handler. We do this because, when interrupting a
  359. // blocking syscall, that syscall may return some special error code in eax;
  360. // This error code would likely be overwritten by the signal handler, so it's
  361. // necessary to preserve it here.
  362. asm(
  363. ".intel_syntax noprefix\n"
  364. "asm_signal_trampoline:\n"
  365. "push ebp\n"
  366. "mov ebp, esp\n"
  367. "push eax\n" // we have to store eax 'cause it might be the return value from a syscall
  368. "sub esp, 4\n" // align the stack to 16 bytes
  369. "mov eax, [ebp+12]\n" // push the signal code
  370. "push eax\n"
  371. "call [ebp+8]\n" // call the signal handler
  372. "add esp, 8\n"
  373. "mov eax, %P0\n"
  374. "int 0x82\n" // sigreturn syscall
  375. "asm_signal_trampoline_end:\n"
  376. ".att_syntax" ::"i"(Syscall::SC_sigreturn));
  377. }
  378. extern "C" void asm_signal_trampoline(void);
  379. extern "C" void asm_signal_trampoline_end(void);
  380. void create_signal_trampolines()
  381. {
  382. InterruptDisabler disabler;
  383. // NOTE: We leak this region.
  384. 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();
  385. g_return_to_ring3_from_signal_trampoline = trampoline_region->vaddr();
  386. u8* trampoline = (u8*)asm_signal_trampoline;
  387. u8* trampoline_end = (u8*)asm_signal_trampoline_end;
  388. size_t trampoline_size = trampoline_end - trampoline;
  389. {
  390. SmapDisabler disabler;
  391. u8* code_ptr = (u8*)trampoline_region->vaddr().as_ptr();
  392. memcpy(code_ptr, trampoline, trampoline_size);
  393. }
  394. trampoline_region->set_writable(false);
  395. trampoline_region->remap();
  396. }
  397. void Process::crash(int signal, u32 eip, bool out_of_memory)
  398. {
  399. ASSERT_INTERRUPTS_DISABLED();
  400. ASSERT(!is_dead());
  401. ASSERT(Process::current() == this);
  402. if (out_of_memory) {
  403. dbg() << "\033[31;1mOut of memory\033[m, killing: " << *this;
  404. } else {
  405. if (eip >= 0xc0000000 && g_kernel_symbols_available) {
  406. auto* symbol = symbolicate_kernel_address(eip);
  407. dbg() << "\033[31;1m" << String::format("%p", eip) << " " << (symbol ? demangle(symbol->name) : "(k?)") << " +" << (symbol ? eip - symbol->address : 0) << "\033[0m\n";
  408. } else if (auto elf_bundle = this->elf_bundle()) {
  409. dbg() << "\033[31;1m" << String::format("%p", eip) << " " << elf_bundle->elf_loader->symbolicate(eip) << "\033[0m\n";
  410. } else {
  411. dbg() << "\033[31;1m" << String::format("%p", eip) << " (?)\033[0m\n";
  412. }
  413. dump_backtrace();
  414. }
  415. m_termination_signal = signal;
  416. dump_regions();
  417. ASSERT(is_user_process());
  418. die();
  419. // We can not return from here, as there is nowhere
  420. // to unwind to, so die right away.
  421. Thread::current()->die_if_needed();
  422. ASSERT_NOT_REACHED();
  423. }
  424. RefPtr<Process> Process::from_pid(ProcessID pid)
  425. {
  426. ScopedSpinLock lock(g_processes_lock);
  427. for (auto& process : *g_processes) {
  428. process.pid();
  429. if (process.pid() == pid)
  430. return &process;
  431. }
  432. return {};
  433. }
  434. RefPtr<FileDescription> Process::file_description(int fd) const
  435. {
  436. if (fd < 0)
  437. return nullptr;
  438. if (static_cast<size_t>(fd) < m_fds.size())
  439. return m_fds[fd].description();
  440. return nullptr;
  441. }
  442. int Process::fd_flags(int fd) const
  443. {
  444. if (fd < 0)
  445. return -1;
  446. if (static_cast<size_t>(fd) < m_fds.size())
  447. return m_fds[fd].flags();
  448. return -1;
  449. }
  450. int Process::number_of_open_file_descriptors() const
  451. {
  452. int count = 0;
  453. for (auto& description : m_fds) {
  454. if (description)
  455. ++count;
  456. }
  457. return count;
  458. }
  459. int Process::alloc_fd(int first_candidate_fd)
  460. {
  461. for (int i = first_candidate_fd; i < (int)m_max_open_file_descriptors; ++i) {
  462. if (!m_fds[i])
  463. return i;
  464. }
  465. return -EMFILE;
  466. }
  467. timeval kgettimeofday()
  468. {
  469. return TimeManagement::now_as_timeval();
  470. }
  471. void kgettimeofday(timeval& tv)
  472. {
  473. tv = kgettimeofday();
  474. }
  475. siginfo_t Process::wait_info()
  476. {
  477. siginfo_t siginfo;
  478. memset(&siginfo, 0, sizeof(siginfo));
  479. siginfo.si_signo = SIGCHLD;
  480. siginfo.si_pid = pid().value();
  481. siginfo.si_uid = uid();
  482. if (m_termination_signal) {
  483. siginfo.si_status = m_termination_signal;
  484. siginfo.si_code = CLD_KILLED;
  485. } else {
  486. siginfo.si_status = m_termination_status;
  487. siginfo.si_code = CLD_EXITED;
  488. }
  489. return siginfo;
  490. }
  491. Custody& Process::current_directory()
  492. {
  493. if (!m_cwd)
  494. m_cwd = VFS::the().root_custody();
  495. return *m_cwd;
  496. }
  497. KResultOr<String> Process::get_syscall_path_argument(const char* user_path, size_t path_length) const
  498. {
  499. if (path_length == 0)
  500. return KResult(-EINVAL);
  501. if (path_length > PATH_MAX)
  502. return KResult(-ENAMETOOLONG);
  503. auto copied_string = copy_string_from_user(user_path, path_length);
  504. if (copied_string.is_null())
  505. return KResult(-EFAULT);
  506. return copied_string;
  507. }
  508. KResultOr<String> Process::get_syscall_path_argument(const Syscall::StringArgument& path) const
  509. {
  510. return get_syscall_path_argument(path.characters, path.length);
  511. }
  512. void Process::finalize(Thread& last_thread)
  513. {
  514. ASSERT(Thread::current() == g_finalizer);
  515. #ifdef PROCESS_DEBUG
  516. dbg() << "Finalizing process " << *this;
  517. #endif
  518. if (m_perf_event_buffer) {
  519. 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 });
  520. if (!description_or_error.is_error()) {
  521. auto& description = description_or_error.value();
  522. auto json = m_perf_event_buffer->to_json(m_pid, m_executable ? m_executable->absolute_path() : "");
  523. auto json_buffer = UserOrKernelBuffer::for_kernel_buffer(json.data());
  524. auto result = description->write(json_buffer, json.size());
  525. if (result.is_error()) {
  526. dbgln("Error while writing perfcore file: {}", result.error().error());
  527. }
  528. }
  529. }
  530. if (m_alarm_timer)
  531. TimerQueue::the().cancel_timer(m_alarm_timer.release_nonnull());
  532. m_fds.clear();
  533. m_tty = nullptr;
  534. m_executable = nullptr;
  535. m_cwd = nullptr;
  536. m_root_directory = nullptr;
  537. m_root_directory_relative_to_global_root = nullptr;
  538. m_dead = true;
  539. disown_all_shared_buffers();
  540. {
  541. // FIXME: PID/TID BUG
  542. if (auto parent_thread = Thread::from_tid(m_ppid.value())) {
  543. if (!(parent_thread->m_signal_action_data[SIGCHLD].flags & SA_NOCLDWAIT))
  544. parent_thread->send_signal(SIGCHLD, this);
  545. }
  546. }
  547. {
  548. ScopedSpinLock processses_lock(g_processes_lock);
  549. if (!!ppid()) {
  550. if (auto parent = Process::from_pid(ppid())) {
  551. parent->m_ticks_in_user_for_dead_children += m_ticks_in_user + m_ticks_in_user_for_dead_children;
  552. parent->m_ticks_in_kernel_for_dead_children += m_ticks_in_kernel + m_ticks_in_kernel_for_dead_children;
  553. }
  554. }
  555. }
  556. unblock_waiters(last_thread, Thread::WaitBlocker::UnblockFlags::Terminated);
  557. {
  558. ScopedSpinLock lock(m_lock);
  559. m_regions.clear();
  560. }
  561. ASSERT(ref_count() > 0);
  562. // WaitBlockCondition::finalize will be in charge of dropping the last
  563. // reference if there are still waiters around, or whenever the last
  564. // waitable states are consumed. Unless there is no parent around
  565. // anymore, in which case we'll just drop it right away.
  566. m_wait_block_condition.finalize();
  567. }
  568. void Process::disowned_by_waiter(Process& process)
  569. {
  570. m_wait_block_condition.disowned_by_waiter(process);
  571. }
  572. void Process::unblock_waiters(Thread& thread, Thread::WaitBlocker::UnblockFlags flags, u8 signal)
  573. {
  574. if (auto parent = Process::from_pid(ppid()))
  575. parent->m_wait_block_condition.unblock(thread, flags, signal);
  576. }
  577. void Process::die()
  578. {
  579. // Let go of the TTY, otherwise a slave PTY may keep the master PTY from
  580. // getting an EOF when the last process using the slave PTY dies.
  581. // If the master PTY owner relies on an EOF to know when to wait() on a
  582. // slave owner, we have to allow the PTY pair to be torn down.
  583. m_tty = nullptr;
  584. kill_all_threads();
  585. }
  586. size_t Process::amount_dirty_private() const
  587. {
  588. // FIXME: This gets a bit more complicated for Regions sharing the same underlying VMObject.
  589. // The main issue I'm thinking of is when the VMObject has physical pages that none of the Regions are mapping.
  590. // That's probably a situation that needs to be looked at in general.
  591. size_t amount = 0;
  592. ScopedSpinLock lock(m_lock);
  593. for (auto& region : m_regions) {
  594. if (!region.is_shared())
  595. amount += region.amount_dirty();
  596. }
  597. return amount;
  598. }
  599. size_t Process::amount_clean_inode() const
  600. {
  601. HashTable<const InodeVMObject*> vmobjects;
  602. {
  603. ScopedSpinLock lock(m_lock);
  604. for (auto& region : m_regions) {
  605. if (region.vmobject().is_inode())
  606. vmobjects.set(&static_cast<const InodeVMObject&>(region.vmobject()));
  607. }
  608. }
  609. size_t amount = 0;
  610. for (auto& vmobject : vmobjects)
  611. amount += vmobject->amount_clean();
  612. return amount;
  613. }
  614. size_t Process::amount_virtual() const
  615. {
  616. size_t amount = 0;
  617. ScopedSpinLock lock(m_lock);
  618. for (auto& region : m_regions) {
  619. amount += region.size();
  620. }
  621. return amount;
  622. }
  623. size_t Process::amount_resident() const
  624. {
  625. // FIXME: This will double count if multiple regions use the same physical page.
  626. size_t amount = 0;
  627. ScopedSpinLock lock(m_lock);
  628. for (auto& region : m_regions) {
  629. amount += region.amount_resident();
  630. }
  631. return amount;
  632. }
  633. size_t Process::amount_shared() const
  634. {
  635. // FIXME: This will double count if multiple regions use the same physical page.
  636. // FIXME: It doesn't work at the moment, since it relies on PhysicalPage ref counts,
  637. // and each PhysicalPage is only reffed by its VMObject. This needs to be refactored
  638. // so that every Region contributes +1 ref to each of its PhysicalPages.
  639. size_t amount = 0;
  640. ScopedSpinLock lock(m_lock);
  641. for (auto& region : m_regions) {
  642. amount += region.amount_shared();
  643. }
  644. return amount;
  645. }
  646. size_t Process::amount_purgeable_volatile() const
  647. {
  648. size_t amount = 0;
  649. ScopedSpinLock lock(m_lock);
  650. for (auto& region : m_regions) {
  651. if (region.vmobject().is_purgeable() && static_cast<const PurgeableVMObject&>(region.vmobject()).is_volatile())
  652. amount += region.amount_resident();
  653. }
  654. return amount;
  655. }
  656. size_t Process::amount_purgeable_nonvolatile() const
  657. {
  658. size_t amount = 0;
  659. ScopedSpinLock lock(m_lock);
  660. for (auto& region : m_regions) {
  661. if (region.vmobject().is_purgeable() && !static_cast<const PurgeableVMObject&>(region.vmobject()).is_volatile())
  662. amount += region.amount_resident();
  663. }
  664. return amount;
  665. }
  666. void Process::terminate_due_to_signal(u8 signal)
  667. {
  668. ASSERT_INTERRUPTS_DISABLED();
  669. ASSERT(signal < 32);
  670. ASSERT(Process::current() == this);
  671. dbg() << "Terminating " << *this << " due to signal " << signal;
  672. m_termination_status = 0;
  673. m_termination_signal = signal;
  674. die();
  675. }
  676. KResult Process::send_signal(u8 signal, Process* sender)
  677. {
  678. // Try to send it to the "obvious" main thread:
  679. auto receiver_thread = Thread::from_tid(m_pid.value());
  680. // If the main thread has died, there may still be other threads:
  681. if (!receiver_thread) {
  682. // The first one should be good enough.
  683. // Neither kill(2) nor kill(3) specify any selection precedure.
  684. for_each_thread([&receiver_thread](Thread& thread) -> IterationDecision {
  685. receiver_thread = &thread;
  686. return IterationDecision::Break;
  687. });
  688. }
  689. if (receiver_thread) {
  690. receiver_thread->send_signal(signal, sender);
  691. return KSuccess;
  692. }
  693. return KResult(-ESRCH);
  694. }
  695. RefPtr<Thread> Process::create_kernel_thread(void (*entry)(void*), void* entry_data, u32 priority, const String& name, u32 affinity, bool joinable)
  696. {
  697. ASSERT((priority >= THREAD_PRIORITY_MIN) && (priority <= THREAD_PRIORITY_MAX));
  698. // FIXME: Do something with guard pages?
  699. auto thread = adopt(*new Thread(*this));
  700. thread->set_name(name);
  701. thread->set_affinity(affinity);
  702. thread->set_priority(priority);
  703. if (!joinable)
  704. thread->detach();
  705. auto& tss = thread->tss();
  706. tss.eip = (FlatPtr)entry;
  707. tss.esp = FlatPtr(entry_data); // entry function argument is expected to be in tss.esp
  708. ScopedSpinLock lock(g_scheduler_lock);
  709. thread->set_state(Thread::State::Runnable);
  710. return thread;
  711. }
  712. void Process::FileDescriptionAndFlags::clear()
  713. {
  714. m_description = nullptr;
  715. m_flags = 0;
  716. }
  717. void Process::FileDescriptionAndFlags::set(NonnullRefPtr<FileDescription>&& description, u32 flags)
  718. {
  719. m_description = move(description);
  720. m_flags = flags;
  721. }
  722. KBuffer Process::backtrace() const
  723. {
  724. KBufferBuilder builder;
  725. for_each_thread([&](Thread& thread) {
  726. builder.appendf("Thread %d (%s):\n", thread.tid().value(), thread.name().characters());
  727. builder.append(thread.backtrace());
  728. return IterationDecision::Continue;
  729. });
  730. return builder.build();
  731. }
  732. Custody& Process::root_directory()
  733. {
  734. if (!m_root_directory)
  735. m_root_directory = VFS::the().root_custody();
  736. return *m_root_directory;
  737. }
  738. Custody& Process::root_directory_relative_to_global_root()
  739. {
  740. if (!m_root_directory_relative_to_global_root)
  741. m_root_directory_relative_to_global_root = root_directory();
  742. return *m_root_directory_relative_to_global_root;
  743. }
  744. void Process::set_root_directory(const Custody& root)
  745. {
  746. m_root_directory = root;
  747. }
  748. Region& Process::add_region(NonnullOwnPtr<Region> region)
  749. {
  750. auto* ptr = region.ptr();
  751. ScopedSpinLock lock(m_lock);
  752. m_regions.append(move(region));
  753. return *ptr;
  754. }
  755. void Process::set_tty(TTY* tty)
  756. {
  757. m_tty = tty;
  758. }
  759. OwnPtr<Process::ELFBundle> Process::elf_bundle() const
  760. {
  761. if (!m_executable)
  762. return nullptr;
  763. auto bundle = make<ELFBundle>();
  764. if (!m_executable->inode().shared_vmobject()) {
  765. return nullptr;
  766. }
  767. ASSERT(m_executable->inode().shared_vmobject());
  768. auto& vmobject = *m_executable->inode().shared_vmobject();
  769. bundle->region = MM.allocate_kernel_region_with_vmobject(const_cast<SharedInodeVMObject&>(vmobject), vmobject.size(), "ELF bundle", Region::Access::Read);
  770. if (!bundle->region)
  771. return nullptr;
  772. bundle->elf_loader = ELF::Loader::create(bundle->region->vaddr().as_ptr(), bundle->region->size());
  773. return bundle;
  774. }
  775. }