Process.cpp 30 KB

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