Process.cpp 30 KB

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