Process.cpp 30 KB

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