Process.cpp 29 KB

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