Process.cpp 29 KB

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