Thread.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069
  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/ScopeGuard.h>
  28. #include <AK/StringBuilder.h>
  29. #include <AK/Time.h>
  30. #include <Kernel/Arch/i386/CPU.h>
  31. #include <Kernel/Debug.h>
  32. #include <Kernel/FileSystem/FileDescription.h>
  33. #include <Kernel/KSyms.h>
  34. #include <Kernel/PerformanceEventBuffer.h>
  35. #include <Kernel/Process.h>
  36. #include <Kernel/Scheduler.h>
  37. #include <Kernel/Thread.h>
  38. #include <Kernel/ThreadTracer.h>
  39. #include <Kernel/TimerQueue.h>
  40. #include <Kernel/VM/MemoryManager.h>
  41. #include <Kernel/VM/PageDirectory.h>
  42. #include <Kernel/VM/ProcessPagingScope.h>
  43. #include <LibC/signal_numbers.h>
  44. namespace Kernel {
  45. SpinLock<u8> Thread::g_tid_map_lock;
  46. READONLY_AFTER_INIT HashMap<ThreadID, Thread*>* Thread::g_tid_map;
  47. void Thread::initialize()
  48. {
  49. g_tid_map = new HashMap<ThreadID, Thread*>();
  50. }
  51. KResultOr<NonnullRefPtr<Thread>> Thread::try_create(NonnullRefPtr<Process> process)
  52. {
  53. auto kernel_stack_region = MM.allocate_kernel_region(default_kernel_stack_size, {}, Region::Access::Read | Region::Access::Write, AllocationStrategy::AllocateNow);
  54. if (!kernel_stack_region)
  55. return ENOMEM;
  56. kernel_stack_region->set_stack(true);
  57. return adopt(*new Thread(move(process), kernel_stack_region.release_nonnull()));
  58. }
  59. Thread::Thread(NonnullRefPtr<Process> process, NonnullOwnPtr<Region> kernel_stack_region)
  60. : m_process(move(process))
  61. , m_kernel_stack_region(move(kernel_stack_region))
  62. , m_name(m_process->name())
  63. {
  64. bool is_first_thread = m_process->add_thread(*this);
  65. if (is_first_thread) {
  66. // First thread gets TID == PID
  67. m_tid = m_process->pid().value();
  68. } else {
  69. m_tid = Process::allocate_pid().value();
  70. }
  71. m_kernel_stack_region->set_name(String::formatted("Kernel stack (thread {})", m_tid.value()));
  72. {
  73. ScopedSpinLock lock(g_tid_map_lock);
  74. auto result = g_tid_map->set(m_tid, this);
  75. ASSERT(result == AK::HashSetResult::InsertedNewEntry);
  76. }
  77. if constexpr (THREAD_DEBUG)
  78. dbgln("Created new thread {}({}:{})", m_process->name(), m_process->pid().value(), m_tid.value());
  79. set_default_signal_dispositions();
  80. m_fpu_state = (FPUState*)kmalloc_aligned<16>(sizeof(FPUState));
  81. reset_fpu_state();
  82. m_tss.iomapbase = sizeof(TSS32);
  83. // Only IF is set when a process boots.
  84. m_tss.eflags = 0x0202;
  85. if (m_process->is_kernel_process()) {
  86. m_tss.cs = GDT_SELECTOR_CODE0;
  87. m_tss.ds = GDT_SELECTOR_DATA0;
  88. m_tss.es = GDT_SELECTOR_DATA0;
  89. m_tss.fs = GDT_SELECTOR_PROC;
  90. m_tss.ss = GDT_SELECTOR_DATA0;
  91. m_tss.gs = 0;
  92. } else {
  93. m_tss.cs = GDT_SELECTOR_CODE3 | 3;
  94. m_tss.ds = GDT_SELECTOR_DATA3 | 3;
  95. m_tss.es = GDT_SELECTOR_DATA3 | 3;
  96. m_tss.fs = GDT_SELECTOR_DATA3 | 3;
  97. m_tss.ss = GDT_SELECTOR_DATA3 | 3;
  98. m_tss.gs = GDT_SELECTOR_TLS | 3;
  99. }
  100. m_tss.cr3 = m_process->space().page_directory().cr3();
  101. m_kernel_stack_base = m_kernel_stack_region->vaddr().get();
  102. m_kernel_stack_top = m_kernel_stack_region->vaddr().offset(default_kernel_stack_size).get() & 0xfffffff8u;
  103. if (m_process->is_kernel_process()) {
  104. m_tss.esp = m_tss.esp0 = m_kernel_stack_top;
  105. } else {
  106. // Ring 3 processes get a separate stack for ring 0.
  107. // The ring 3 stack will be assigned by exec().
  108. m_tss.ss0 = GDT_SELECTOR_DATA0;
  109. m_tss.esp0 = m_kernel_stack_top;
  110. }
  111. // We need to add another reference if we could successfully create
  112. // all the resources needed for this thread. The reason for this is that
  113. // we don't want to delete this thread after dropping the reference,
  114. // it may still be running or scheduled to be run.
  115. // The finalizer is responsible for dropping this reference once this
  116. // thread is ready to be cleaned up.
  117. ref();
  118. }
  119. Thread::~Thread()
  120. {
  121. {
  122. // We need to explicitly remove ourselves from the thread list
  123. // here. We may get pre-empted in the middle of destructing this
  124. // thread, which causes problems if the thread list is iterated.
  125. // Specifically, if this is the last thread of a process, checking
  126. // block conditions would access m_process, which would be in
  127. // the middle of being destroyed.
  128. ScopedSpinLock lock(g_scheduler_lock);
  129. ASSERT(!m_process_thread_list_node.is_in_list());
  130. // We shouldn't be queued
  131. ASSERT(m_runnable_priority < 0);
  132. }
  133. {
  134. ScopedSpinLock lock(g_tid_map_lock);
  135. auto result = g_tid_map->remove(m_tid);
  136. ASSERT(result);
  137. }
  138. }
  139. void Thread::unblock_from_blocker(Blocker& blocker)
  140. {
  141. auto do_unblock = [&]() {
  142. ScopedSpinLock scheduler_lock(g_scheduler_lock);
  143. ScopedSpinLock block_lock(m_block_lock);
  144. if (m_blocker != &blocker)
  145. return;
  146. if (!should_be_stopped() && !is_stopped())
  147. unblock();
  148. };
  149. if (Processor::current().in_irq()) {
  150. Processor::current().deferred_call_queue([do_unblock = move(do_unblock), self = make_weak_ptr()]() {
  151. if (auto this_thread = self.strong_ref())
  152. do_unblock();
  153. });
  154. } else {
  155. do_unblock();
  156. }
  157. }
  158. void Thread::unblock(u8 signal)
  159. {
  160. ASSERT(!Processor::current().in_irq());
  161. ASSERT(g_scheduler_lock.own_lock());
  162. ASSERT(m_block_lock.own_lock());
  163. if (m_state != Thread::Blocked)
  164. return;
  165. ASSERT(m_blocker);
  166. if (signal != 0) {
  167. if (is_handling_page_fault()) {
  168. // Don't let signals unblock threads that are blocked inside a page fault handler.
  169. // This prevents threads from EINTR'ing the inode read in an inode page fault.
  170. // FIXME: There's probably a better way to solve this.
  171. return;
  172. }
  173. if (!m_blocker->can_be_interrupted() && !m_should_die)
  174. return;
  175. m_blocker->set_interrupted_by_signal(signal);
  176. }
  177. m_blocker = nullptr;
  178. if (Thread::current() == this) {
  179. set_state(Thread::Running);
  180. return;
  181. }
  182. ASSERT(m_state != Thread::Runnable && m_state != Thread::Running);
  183. set_state(Thread::Runnable);
  184. }
  185. void Thread::set_should_die()
  186. {
  187. if (m_should_die) {
  188. dbgln("{} Should already die", *this);
  189. return;
  190. }
  191. ScopedCritical critical;
  192. // Remember that we should die instead of returning to
  193. // the userspace.
  194. ScopedSpinLock lock(g_scheduler_lock);
  195. m_should_die = true;
  196. // NOTE: Even the current thread can technically be in "Stopped"
  197. // state! This is the case when another thread sent a SIGSTOP to
  198. // it while it was running and it calls e.g. exit() before
  199. // the scheduler gets involved again.
  200. if (is_stopped()) {
  201. // If we were stopped, we need to briefly resume so that
  202. // the kernel stacks can clean up. We won't ever return back
  203. // to user mode, though
  204. ASSERT(!process().is_stopped());
  205. resume_from_stopped();
  206. }
  207. if (is_blocked()) {
  208. ScopedSpinLock block_lock(m_block_lock);
  209. if (m_blocker) {
  210. // We're blocked in the kernel.
  211. m_blocker->set_interrupted_by_death();
  212. unblock();
  213. }
  214. }
  215. }
  216. void Thread::die_if_needed()
  217. {
  218. ASSERT(Thread::current() == this);
  219. if (!m_should_die)
  220. return;
  221. u32 unlock_count;
  222. [[maybe_unused]] auto rc = unlock_process_if_locked(unlock_count);
  223. ScopedCritical critical;
  224. // Flag a context switch. Because we're in a critical section,
  225. // Scheduler::yield will actually only mark a pending context switch
  226. // Simply leaving the critical section would not necessarily trigger
  227. // a switch.
  228. Scheduler::yield();
  229. // Now leave the critical section so that we can also trigger the
  230. // actual context switch
  231. u32 prev_flags;
  232. Processor::current().clear_critical(prev_flags, false);
  233. dbgln("die_if_needed returned from clear_critical!!! in irq: {}", Processor::current().in_irq());
  234. // We should never get here, but the scoped scheduler lock
  235. // will be released by Scheduler::context_switch again
  236. ASSERT_NOT_REACHED();
  237. }
  238. void Thread::exit(void* exit_value)
  239. {
  240. ASSERT(Thread::current() == this);
  241. m_join_condition.thread_did_exit(exit_value);
  242. set_should_die();
  243. u32 unlock_count;
  244. [[maybe_unused]] auto rc = unlock_process_if_locked(unlock_count);
  245. die_if_needed();
  246. }
  247. void Thread::yield_while_not_holding_big_lock()
  248. {
  249. ASSERT(!g_scheduler_lock.own_lock());
  250. u32 prev_flags;
  251. u32 prev_crit = Processor::current().clear_critical(prev_flags, true);
  252. Scheduler::yield();
  253. // NOTE: We may be on a different CPU now!
  254. Processor::current().restore_critical(prev_crit, prev_flags);
  255. }
  256. void Thread::yield_without_holding_big_lock()
  257. {
  258. ASSERT(!g_scheduler_lock.own_lock());
  259. u32 lock_count_to_restore = 0;
  260. auto previous_locked = unlock_process_if_locked(lock_count_to_restore);
  261. // NOTE: Even though we call Scheduler::yield here, unless we happen
  262. // to be outside of a critical section, the yield will be postponed
  263. // until leaving it in relock_process.
  264. Scheduler::yield();
  265. relock_process(previous_locked, lock_count_to_restore);
  266. }
  267. void Thread::donate_without_holding_big_lock(RefPtr<Thread>& thread, const char* reason)
  268. {
  269. ASSERT(!g_scheduler_lock.own_lock());
  270. u32 lock_count_to_restore = 0;
  271. auto previous_locked = unlock_process_if_locked(lock_count_to_restore);
  272. // NOTE: Even though we call Scheduler::yield here, unless we happen
  273. // to be outside of a critical section, the yield will be postponed
  274. // until leaving it in relock_process.
  275. Scheduler::donate_to(thread, reason);
  276. relock_process(previous_locked, lock_count_to_restore);
  277. }
  278. LockMode Thread::unlock_process_if_locked(u32& lock_count_to_restore)
  279. {
  280. return process().big_lock().force_unlock_if_locked(lock_count_to_restore);
  281. }
  282. void Thread::relock_process(LockMode previous_locked, u32 lock_count_to_restore)
  283. {
  284. // Clearing the critical section may trigger the context switch
  285. // flagged by calling Scheduler::donate_to or Scheduler::yield
  286. // above. We have to do it this way because we intentionally
  287. // leave the critical section here to be able to switch contexts.
  288. u32 prev_flags;
  289. u32 prev_crit = Processor::current().clear_critical(prev_flags, true);
  290. // CONTEXT SWITCH HAPPENS HERE!
  291. // NOTE: We may be on a different CPU now!
  292. Processor::current().restore_critical(prev_crit, prev_flags);
  293. if (previous_locked != LockMode::Unlocked) {
  294. // We've unblocked, relock the process if needed and carry on.
  295. RESTORE_LOCK(process().big_lock(), previous_locked, lock_count_to_restore);
  296. }
  297. }
  298. auto Thread::sleep(clockid_t clock_id, const timespec& duration, timespec* remaining_time) -> BlockResult
  299. {
  300. ASSERT(state() == Thread::Running);
  301. return Thread::current()->block<Thread::SleepBlocker>({}, Thread::BlockTimeout(false, &duration, nullptr, clock_id), remaining_time);
  302. }
  303. auto Thread::sleep_until(clockid_t clock_id, const timespec& deadline) -> BlockResult
  304. {
  305. ASSERT(state() == Thread::Running);
  306. return Thread::current()->block<Thread::SleepBlocker>({}, Thread::BlockTimeout(true, &deadline, nullptr, clock_id));
  307. }
  308. const char* Thread::state_string() const
  309. {
  310. switch (state()) {
  311. case Thread::Invalid:
  312. return "Invalid";
  313. case Thread::Runnable:
  314. return "Runnable";
  315. case Thread::Running:
  316. return "Running";
  317. case Thread::Dying:
  318. return "Dying";
  319. case Thread::Dead:
  320. return "Dead";
  321. case Thread::Stopped:
  322. return "Stopped";
  323. case Thread::Blocked: {
  324. ScopedSpinLock block_lock(m_block_lock);
  325. ASSERT(m_blocker != nullptr);
  326. return m_blocker->state_string();
  327. }
  328. }
  329. klog() << "Thread::state_string(): Invalid state: " << state();
  330. ASSERT_NOT_REACHED();
  331. return nullptr;
  332. }
  333. void Thread::finalize()
  334. {
  335. ASSERT(Thread::current() == g_finalizer);
  336. ASSERT(Thread::current() != this);
  337. #if LOCK_DEBUG
  338. ASSERT(!m_lock.own_lock());
  339. if (lock_count() > 0) {
  340. dbgln("Thread {} leaking {} Locks!", *this, lock_count());
  341. ScopedSpinLock list_lock(m_holding_locks_lock);
  342. for (auto& info : m_holding_locks_list)
  343. dbgln(" - {} @ {} locked at {}:{} count: {}", info.lock->name(), info.lock, info.file, info.line, info.count);
  344. ASSERT_NOT_REACHED();
  345. }
  346. #endif
  347. {
  348. ScopedSpinLock lock(g_scheduler_lock);
  349. dbgln_if(THREAD_DEBUG, "Finalizing thread {}", *this);
  350. set_state(Thread::State::Dead);
  351. m_join_condition.thread_finalizing();
  352. }
  353. if (m_dump_backtrace_on_finalization)
  354. dbgln("{}", backtrace());
  355. kfree_aligned(m_fpu_state);
  356. drop_thread_count(false);
  357. }
  358. void Thread::drop_thread_count(bool initializing_first_thread)
  359. {
  360. bool is_last = process().remove_thread(*this);
  361. if (!initializing_first_thread && is_last)
  362. process().finalize();
  363. }
  364. void Thread::finalize_dying_threads()
  365. {
  366. ASSERT(Thread::current() == g_finalizer);
  367. Vector<Thread*, 32> dying_threads;
  368. {
  369. ScopedSpinLock lock(g_scheduler_lock);
  370. for_each_in_state(Thread::State::Dying, [&](Thread& thread) {
  371. if (thread.is_finalizable())
  372. dying_threads.append(&thread);
  373. return IterationDecision::Continue;
  374. });
  375. }
  376. for (auto* thread : dying_threads) {
  377. thread->finalize();
  378. // This thread will never execute again, drop the running reference
  379. // NOTE: This may not necessarily drop the last reference if anything
  380. // else is still holding onto this thread!
  381. thread->unref();
  382. }
  383. }
  384. bool Thread::tick()
  385. {
  386. if (previous_mode() == PreviousMode::KernelMode) {
  387. ++m_process->m_ticks_in_kernel;
  388. ++m_ticks_in_kernel;
  389. } else {
  390. ++m_process->m_ticks_in_user;
  391. ++m_ticks_in_user;
  392. }
  393. return --m_ticks_left;
  394. }
  395. void Thread::check_dispatch_pending_signal()
  396. {
  397. auto result = DispatchSignalResult::Continue;
  398. {
  399. ScopedSpinLock scheduler_lock(g_scheduler_lock);
  400. if (pending_signals_for_state()) {
  401. ScopedSpinLock lock(m_lock);
  402. result = dispatch_one_pending_signal();
  403. }
  404. }
  405. switch (result) {
  406. case DispatchSignalResult::Yield:
  407. yield_while_not_holding_big_lock();
  408. break;
  409. case DispatchSignalResult::Terminate:
  410. process().die();
  411. break;
  412. default:
  413. break;
  414. }
  415. }
  416. u32 Thread::pending_signals() const
  417. {
  418. ScopedSpinLock lock(g_scheduler_lock);
  419. return pending_signals_for_state();
  420. }
  421. u32 Thread::pending_signals_for_state() const
  422. {
  423. ASSERT(g_scheduler_lock.own_lock());
  424. constexpr u32 stopped_signal_mask = (1 << (SIGCONT - 1)) | (1 << (SIGKILL - 1)) | (1 << (SIGTRAP - 1));
  425. if (is_handling_page_fault())
  426. return 0;
  427. return m_state != Stopped ? m_pending_signals : m_pending_signals & stopped_signal_mask;
  428. }
  429. void Thread::send_signal(u8 signal, [[maybe_unused]] Process* sender)
  430. {
  431. ASSERT(signal < 32);
  432. ScopedSpinLock scheduler_lock(g_scheduler_lock);
  433. // FIXME: Figure out what to do for masked signals. Should we also ignore them here?
  434. if (should_ignore_signal(signal)) {
  435. dbgln_if(SIGNAL_DEBUG, "Signal {} was ignored by {}", signal, process());
  436. return;
  437. }
  438. if constexpr (SIGNAL_DEBUG) {
  439. if (sender)
  440. dbgln("Signal: {} sent {} to {}", *sender, signal, process());
  441. else
  442. dbgln("Signal: Kernel send {} to {}", signal, process());
  443. }
  444. m_pending_signals |= 1 << (signal - 1);
  445. m_have_any_unmasked_pending_signals.store(pending_signals_for_state() & ~m_signal_mask, AK::memory_order_release);
  446. if (m_state == Stopped) {
  447. ScopedSpinLock lock(m_lock);
  448. if (pending_signals_for_state()) {
  449. dbgln_if(SIGNAL_DEBUG, "Signal: Resuming stopped {} to deliver signal {}", *this, signal);
  450. resume_from_stopped();
  451. }
  452. } else {
  453. ScopedSpinLock block_lock(m_block_lock);
  454. dbgln_if(SIGNAL_DEBUG, "Signal: Unblocking {} to deliver signal {}", *this, signal);
  455. unblock(signal);
  456. }
  457. }
  458. u32 Thread::update_signal_mask(u32 signal_mask)
  459. {
  460. ScopedSpinLock lock(g_scheduler_lock);
  461. auto previous_signal_mask = m_signal_mask;
  462. m_signal_mask = signal_mask;
  463. m_have_any_unmasked_pending_signals.store(pending_signals_for_state() & ~m_signal_mask, AK::memory_order_release);
  464. return previous_signal_mask;
  465. }
  466. u32 Thread::signal_mask() const
  467. {
  468. ScopedSpinLock lock(g_scheduler_lock);
  469. return m_signal_mask;
  470. }
  471. u32 Thread::signal_mask_block(sigset_t signal_set, bool block)
  472. {
  473. ScopedSpinLock lock(g_scheduler_lock);
  474. auto previous_signal_mask = m_signal_mask;
  475. if (block)
  476. m_signal_mask &= ~signal_set;
  477. else
  478. m_signal_mask |= signal_set;
  479. m_have_any_unmasked_pending_signals.store(pending_signals_for_state() & ~m_signal_mask, AK::memory_order_release);
  480. return previous_signal_mask;
  481. }
  482. void Thread::clear_signals()
  483. {
  484. ScopedSpinLock lock(g_scheduler_lock);
  485. m_signal_mask = 0;
  486. m_pending_signals = 0;
  487. m_have_any_unmasked_pending_signals.store(false, AK::memory_order_release);
  488. }
  489. // Certain exceptions, such as SIGSEGV and SIGILL, put a
  490. // thread into a state where the signal handler must be
  491. // invoked immediately, otherwise it will continue to fault.
  492. // This function should be used in an exception handler to
  493. // ensure that when the thread resumes, it's executing in
  494. // the appropriate signal handler.
  495. void Thread::send_urgent_signal_to_self(u8 signal)
  496. {
  497. ASSERT(Thread::current() == this);
  498. DispatchSignalResult result;
  499. {
  500. ScopedSpinLock lock(g_scheduler_lock);
  501. result = dispatch_signal(signal);
  502. }
  503. if (result == DispatchSignalResult::Yield)
  504. yield_without_holding_big_lock();
  505. }
  506. DispatchSignalResult Thread::dispatch_one_pending_signal()
  507. {
  508. ASSERT(m_lock.own_lock());
  509. u32 signal_candidates = pending_signals_for_state() & ~m_signal_mask;
  510. if (signal_candidates == 0)
  511. return DispatchSignalResult::Continue;
  512. u8 signal = 1;
  513. for (; signal < 32; ++signal) {
  514. if (signal_candidates & (1 << (signal - 1))) {
  515. break;
  516. }
  517. }
  518. return dispatch_signal(signal);
  519. }
  520. DispatchSignalResult Thread::try_dispatch_one_pending_signal(u8 signal)
  521. {
  522. ASSERT(signal != 0);
  523. ScopedSpinLock scheduler_lock(g_scheduler_lock);
  524. ScopedSpinLock lock(m_lock);
  525. u32 signal_candidates = pending_signals_for_state() & ~m_signal_mask;
  526. if (!(signal_candidates & (1 << (signal - 1))))
  527. return DispatchSignalResult::Continue;
  528. return dispatch_signal(signal);
  529. }
  530. enum class DefaultSignalAction {
  531. Terminate,
  532. Ignore,
  533. DumpCore,
  534. Stop,
  535. Continue,
  536. };
  537. static DefaultSignalAction default_signal_action(u8 signal)
  538. {
  539. ASSERT(signal && signal < NSIG);
  540. switch (signal) {
  541. case SIGHUP:
  542. case SIGINT:
  543. case SIGKILL:
  544. case SIGPIPE:
  545. case SIGALRM:
  546. case SIGUSR1:
  547. case SIGUSR2:
  548. case SIGVTALRM:
  549. case SIGSTKFLT:
  550. case SIGIO:
  551. case SIGPROF:
  552. case SIGTERM:
  553. return DefaultSignalAction::Terminate;
  554. case SIGCHLD:
  555. case SIGURG:
  556. case SIGWINCH:
  557. case SIGINFO:
  558. return DefaultSignalAction::Ignore;
  559. case SIGQUIT:
  560. case SIGILL:
  561. case SIGTRAP:
  562. case SIGABRT:
  563. case SIGBUS:
  564. case SIGFPE:
  565. case SIGSEGV:
  566. case SIGXCPU:
  567. case SIGXFSZ:
  568. case SIGSYS:
  569. return DefaultSignalAction::DumpCore;
  570. case SIGCONT:
  571. return DefaultSignalAction::Continue;
  572. case SIGSTOP:
  573. case SIGTSTP:
  574. case SIGTTIN:
  575. case SIGTTOU:
  576. return DefaultSignalAction::Stop;
  577. }
  578. ASSERT_NOT_REACHED();
  579. }
  580. bool Thread::should_ignore_signal(u8 signal) const
  581. {
  582. ASSERT(signal < 32);
  583. auto& action = m_signal_action_data[signal];
  584. if (action.handler_or_sigaction.is_null())
  585. return default_signal_action(signal) == DefaultSignalAction::Ignore;
  586. if (action.handler_or_sigaction.as_ptr() == SIG_IGN)
  587. return true;
  588. return false;
  589. }
  590. bool Thread::has_signal_handler(u8 signal) const
  591. {
  592. ASSERT(signal < 32);
  593. auto& action = m_signal_action_data[signal];
  594. return !action.handler_or_sigaction.is_null();
  595. }
  596. static bool push_value_on_user_stack(u32* stack, u32 data)
  597. {
  598. *stack -= 4;
  599. return copy_to_user((u32*)*stack, &data);
  600. }
  601. void Thread::resume_from_stopped()
  602. {
  603. ASSERT(is_stopped());
  604. ASSERT(m_stop_state != State::Invalid);
  605. ASSERT(g_scheduler_lock.own_lock());
  606. if (m_stop_state == Blocked) {
  607. ScopedSpinLock block_lock(m_block_lock);
  608. if (m_blocker) {
  609. // Hasn't been unblocked yet
  610. set_state(Blocked, 0);
  611. } else {
  612. // Was unblocked while stopped
  613. set_state(Runnable);
  614. }
  615. } else {
  616. set_state(m_stop_state, 0);
  617. }
  618. }
  619. DispatchSignalResult Thread::dispatch_signal(u8 signal)
  620. {
  621. ASSERT_INTERRUPTS_DISABLED();
  622. ASSERT(g_scheduler_lock.own_lock());
  623. ASSERT(signal > 0 && signal <= 32);
  624. ASSERT(process().is_user_process());
  625. ASSERT(this == Thread::current());
  626. #if SIGNAL_DEBUG
  627. klog() << "signal: dispatch signal " << signal << " to " << *this << " state: " << state_string();
  628. #endif
  629. if (m_state == Invalid || !is_initialized()) {
  630. // Thread has barely been created, we need to wait until it is
  631. // at least in Runnable state and is_initialized() returns true,
  632. // which indicates that it is fully set up an we actually have
  633. // a register state on the stack that we can modify
  634. return DispatchSignalResult::Deferred;
  635. }
  636. ASSERT(previous_mode() == PreviousMode::UserMode);
  637. auto& action = m_signal_action_data[signal];
  638. // FIXME: Implement SA_SIGINFO signal handlers.
  639. ASSERT(!(action.flags & SA_SIGINFO));
  640. // Mark this signal as handled.
  641. m_pending_signals &= ~(1 << (signal - 1));
  642. m_have_any_unmasked_pending_signals.store(m_pending_signals & ~m_signal_mask, AK::memory_order_release);
  643. auto& process = this->process();
  644. auto tracer = process.tracer();
  645. if (signal == SIGSTOP || (tracer && default_signal_action(signal) == DefaultSignalAction::DumpCore)) {
  646. dbgln_if(SIGNAL_DEBUG, "signal: signal {} sopping thread {}", signal, *this);
  647. set_state(State::Stopped, signal);
  648. return DispatchSignalResult::Yield;
  649. }
  650. if (signal == SIGCONT) {
  651. dbgln("signal: SIGCONT resuming {}", *this);
  652. } else {
  653. if (tracer) {
  654. // when a thread is traced, it should be stopped whenever it receives a signal
  655. // the tracer is notified of this by using waitpid()
  656. // only "pending signals" from the tracer are sent to the tracee
  657. if (!tracer->has_pending_signal(signal)) {
  658. dbgln("signal: {} stopping {} for tracer", signal, *this);
  659. set_state(Stopped, signal);
  660. return DispatchSignalResult::Yield;
  661. }
  662. tracer->unset_signal(signal);
  663. }
  664. }
  665. auto handler_vaddr = action.handler_or_sigaction;
  666. if (handler_vaddr.is_null()) {
  667. switch (default_signal_action(signal)) {
  668. case DefaultSignalAction::Stop:
  669. set_state(Stopped, signal);
  670. return DispatchSignalResult::Yield;
  671. case DefaultSignalAction::DumpCore:
  672. process.set_dump_core(true);
  673. process.for_each_thread([](auto& thread) {
  674. thread.set_dump_backtrace_on_finalization();
  675. return IterationDecision::Continue;
  676. });
  677. [[fallthrough]];
  678. case DefaultSignalAction::Terminate:
  679. m_process->terminate_due_to_signal(signal);
  680. return DispatchSignalResult::Terminate;
  681. case DefaultSignalAction::Ignore:
  682. ASSERT_NOT_REACHED();
  683. case DefaultSignalAction::Continue:
  684. return DispatchSignalResult::Continue;
  685. }
  686. ASSERT_NOT_REACHED();
  687. }
  688. if (handler_vaddr.as_ptr() == SIG_IGN) {
  689. #if SIGNAL_DEBUG
  690. klog() << "signal: " << *this << " ignored signal " << signal;
  691. #endif
  692. return DispatchSignalResult::Continue;
  693. }
  694. ASSERT(previous_mode() == PreviousMode::UserMode);
  695. ASSERT(current_trap());
  696. ProcessPagingScope paging_scope(m_process);
  697. u32 old_signal_mask = m_signal_mask;
  698. u32 new_signal_mask = action.mask;
  699. if (action.flags & SA_NODEFER)
  700. new_signal_mask &= ~(1 << (signal - 1));
  701. else
  702. new_signal_mask |= 1 << (signal - 1);
  703. m_signal_mask |= new_signal_mask;
  704. m_have_any_unmasked_pending_signals.store(m_pending_signals & ~m_signal_mask, AK::memory_order_release);
  705. auto setup_stack = [&](RegisterState& state) {
  706. u32* stack = &state.userspace_esp;
  707. u32 old_esp = *stack;
  708. u32 ret_eip = state.eip;
  709. u32 ret_eflags = state.eflags;
  710. #if SIGNAL_DEBUG
  711. klog() << "signal: setting up user stack to return to eip: " << String::format("%p", (void*)ret_eip) << " esp: " << String::format("%p", (void*)old_esp);
  712. #endif
  713. // Align the stack to 16 bytes.
  714. // Note that we push 56 bytes (4 * 14) on to the stack,
  715. // so we need to account for this here.
  716. u32 stack_alignment = (*stack - 56) % 16;
  717. *stack -= stack_alignment;
  718. push_value_on_user_stack(stack, ret_eflags);
  719. push_value_on_user_stack(stack, ret_eip);
  720. push_value_on_user_stack(stack, state.eax);
  721. push_value_on_user_stack(stack, state.ecx);
  722. push_value_on_user_stack(stack, state.edx);
  723. push_value_on_user_stack(stack, state.ebx);
  724. push_value_on_user_stack(stack, old_esp);
  725. push_value_on_user_stack(stack, state.ebp);
  726. push_value_on_user_stack(stack, state.esi);
  727. push_value_on_user_stack(stack, state.edi);
  728. // PUSH old_signal_mask
  729. push_value_on_user_stack(stack, old_signal_mask);
  730. push_value_on_user_stack(stack, signal);
  731. push_value_on_user_stack(stack, handler_vaddr.get());
  732. push_value_on_user_stack(stack, 0); //push fake return address
  733. ASSERT((*stack % 16) == 0);
  734. };
  735. // We now place the thread state on the userspace stack.
  736. // Note that we use a RegisterState.
  737. // Conversely, when the thread isn't blocking the RegisterState may not be
  738. // valid (fork, exec etc) but the tss will, so we use that instead.
  739. auto& regs = get_register_dump_from_stack();
  740. setup_stack(regs);
  741. regs.eip = process.signal_trampoline().get();
  742. #if SIGNAL_DEBUG
  743. dbgln("signal: Thread in state '{}' has been primed with signal handler {:04x}:{:08x} to deliver {}", state_string(), m_tss.cs, m_tss.eip, signal);
  744. #endif
  745. return DispatchSignalResult::Continue;
  746. }
  747. void Thread::set_default_signal_dispositions()
  748. {
  749. // FIXME: Set up all the right default actions. See signal(7).
  750. memset(&m_signal_action_data, 0, sizeof(m_signal_action_data));
  751. m_signal_action_data[SIGCHLD].handler_or_sigaction = VirtualAddress(SIG_IGN);
  752. m_signal_action_data[SIGWINCH].handler_or_sigaction = VirtualAddress(SIG_IGN);
  753. }
  754. RegisterState& Thread::get_register_dump_from_stack()
  755. {
  756. auto* trap = current_trap();
  757. // We should *always* have a trap. If we don't we're probably a kernel
  758. // thread that hasn't been pre-empted. If we want to support this, we
  759. // need to capture the registers probably into m_tss and return it
  760. ASSERT(trap);
  761. while (trap) {
  762. if (!trap->next_trap)
  763. break;
  764. trap = trap->next_trap;
  765. }
  766. return *trap->regs;
  767. }
  768. RefPtr<Thread> Thread::clone(Process& process)
  769. {
  770. auto thread_or_error = Thread::try_create(process);
  771. if (thread_or_error.is_error())
  772. return {};
  773. auto& clone = thread_or_error.value();
  774. memcpy(clone->m_signal_action_data, m_signal_action_data, sizeof(m_signal_action_data));
  775. clone->m_signal_mask = m_signal_mask;
  776. memcpy(clone->m_fpu_state, m_fpu_state, sizeof(FPUState));
  777. clone->m_thread_specific_data = m_thread_specific_data;
  778. return clone;
  779. }
  780. void Thread::set_state(State new_state, u8 stop_signal)
  781. {
  782. State previous_state;
  783. ASSERT(g_scheduler_lock.own_lock());
  784. if (new_state == m_state)
  785. return;
  786. {
  787. ScopedSpinLock thread_lock(m_lock);
  788. previous_state = m_state;
  789. if (previous_state == Invalid) {
  790. // If we were *just* created, we may have already pending signals
  791. if (has_unmasked_pending_signals()) {
  792. dbgln_if(THREAD_DEBUG, "Dispatch pending signals to new thread {}", *this);
  793. dispatch_one_pending_signal();
  794. }
  795. }
  796. m_state = new_state;
  797. dbgln_if(THREAD_DEBUG, "Set thread {} state to {}", *this, state_string());
  798. }
  799. if (previous_state == Runnable) {
  800. Scheduler::dequeue_runnable_thread(*this);
  801. } else if (previous_state == Stopped) {
  802. m_stop_state = State::Invalid;
  803. auto& process = this->process();
  804. if (process.set_stopped(false) == true) {
  805. process.for_each_thread([&](auto& thread) {
  806. if (&thread == this || !thread.is_stopped())
  807. return IterationDecision::Continue;
  808. dbgln_if(THREAD_DEBUG, "Resuming peer thread {}", thread);
  809. thread.resume_from_stopped();
  810. return IterationDecision::Continue;
  811. });
  812. process.unblock_waiters(Thread::WaitBlocker::UnblockFlags::Continued);
  813. }
  814. }
  815. if (m_state == Runnable) {
  816. Scheduler::queue_runnable_thread(*this);
  817. Processor::smp_wake_n_idle_processors(1);
  818. } else if (m_state == Stopped) {
  819. // We don't want to restore to Running state, only Runnable!
  820. m_stop_state = previous_state != Running ? previous_state : Runnable;
  821. auto& process = this->process();
  822. if (process.set_stopped(true) == false) {
  823. process.for_each_thread([&](auto& thread) {
  824. if (&thread == this || thread.is_stopped())
  825. return IterationDecision::Continue;
  826. dbgln_if(THREAD_DEBUG, "Stopping peer thread {}", thread);
  827. thread.set_state(Stopped, stop_signal);
  828. return IterationDecision::Continue;
  829. });
  830. process.unblock_waiters(Thread::WaitBlocker::UnblockFlags::Stopped, stop_signal);
  831. }
  832. } else if (m_state == Dying) {
  833. ASSERT(previous_state != Blocked);
  834. if (this != Thread::current() && is_finalizable()) {
  835. // Some other thread set this thread to Dying, notify the
  836. // finalizer right away as it can be cleaned up now
  837. Scheduler::notify_finalizer();
  838. }
  839. }
  840. }
  841. struct RecognizedSymbol {
  842. u32 address;
  843. const KernelSymbol* symbol { nullptr };
  844. };
  845. static bool symbolicate(const RecognizedSymbol& symbol, const Process& process, StringBuilder& builder)
  846. {
  847. if (!symbol.address)
  848. return false;
  849. bool mask_kernel_addresses = !process.is_superuser();
  850. if (!symbol.symbol) {
  851. if (!is_user_address(VirtualAddress(symbol.address))) {
  852. builder.append("0xdeadc0de\n");
  853. } else {
  854. builder.appendff("{:p}\n", symbol.address);
  855. }
  856. return true;
  857. }
  858. unsigned offset = symbol.address - symbol.symbol->address;
  859. if (symbol.symbol->address == g_highest_kernel_symbol_address && offset > 4096) {
  860. builder.appendff("{:p}\n", (void*)(mask_kernel_addresses ? 0xdeadc0de : symbol.address));
  861. } else {
  862. builder.appendff("{:p} {} +{}\n", (void*)(mask_kernel_addresses ? 0xdeadc0de : symbol.address), demangle(symbol.symbol->name), offset);
  863. }
  864. return true;
  865. }
  866. String Thread::backtrace()
  867. {
  868. Vector<RecognizedSymbol, 128> recognized_symbols;
  869. auto& process = const_cast<Process&>(this->process());
  870. auto stack_trace = Processor::capture_stack_trace(*this);
  871. ASSERT(!g_scheduler_lock.own_lock());
  872. ProcessPagingScope paging_scope(process);
  873. for (auto& frame : stack_trace) {
  874. if (is_user_range(VirtualAddress(frame), sizeof(FlatPtr) * 2)) {
  875. recognized_symbols.append({ frame });
  876. } else {
  877. recognized_symbols.append({ frame, symbolicate_kernel_address(frame) });
  878. }
  879. }
  880. StringBuilder builder;
  881. for (auto& symbol : recognized_symbols) {
  882. if (!symbolicate(symbol, process, builder))
  883. break;
  884. }
  885. return builder.to_string();
  886. }
  887. size_t Thread::thread_specific_region_alignment() const
  888. {
  889. return max(process().m_master_tls_alignment, alignof(ThreadSpecificData));
  890. }
  891. size_t Thread::thread_specific_region_size() const
  892. {
  893. return align_up_to(process().m_master_tls_size, thread_specific_region_alignment()) + sizeof(ThreadSpecificData);
  894. }
  895. KResult Thread::make_thread_specific_region(Badge<Process>)
  896. {
  897. // The process may not require a TLS region
  898. if (!process().m_master_tls_region)
  899. return KSuccess;
  900. auto range = process().space().allocate_range({}, thread_specific_region_size());
  901. if (!range.has_value())
  902. return ENOMEM;
  903. auto region_or_error = process().space().allocate_region(range.value(), "Thread-specific", PROT_READ | PROT_WRITE);
  904. if (region_or_error.is_error())
  905. return region_or_error.error();
  906. SmapDisabler disabler;
  907. auto* thread_specific_data = (ThreadSpecificData*)region_or_error.value()->vaddr().offset(align_up_to(process().m_master_tls_size, thread_specific_region_alignment())).as_ptr();
  908. auto* thread_local_storage = (u8*)((u8*)thread_specific_data) - align_up_to(process().m_master_tls_size, process().m_master_tls_alignment);
  909. m_thread_specific_data = VirtualAddress(thread_specific_data);
  910. thread_specific_data->self = thread_specific_data;
  911. if (process().m_master_tls_size)
  912. memcpy(thread_local_storage, process().m_master_tls_region.unsafe_ptr()->vaddr().as_ptr(), process().m_master_tls_size);
  913. return KSuccess;
  914. }
  915. const LogStream& operator<<(const LogStream& stream, const Thread& value)
  916. {
  917. return stream << value.process().name() << "(" << value.pid().value() << ":" << value.tid().value() << ")";
  918. }
  919. RefPtr<Thread> Thread::from_tid(ThreadID tid)
  920. {
  921. RefPtr<Thread> found_thread;
  922. {
  923. ScopedSpinLock lock(g_tid_map_lock);
  924. auto it = g_tid_map->find(tid);
  925. if (it != g_tid_map->end())
  926. found_thread = it->value;
  927. }
  928. return found_thread;
  929. }
  930. void Thread::reset_fpu_state()
  931. {
  932. memcpy(m_fpu_state, &Processor::current().clean_fpu_state(), sizeof(FPUState));
  933. }
  934. bool Thread::should_be_stopped() const
  935. {
  936. return process().is_stopped();
  937. }
  938. }
  939. void AK::Formatter<Kernel::Thread>::format(FormatBuilder& builder, const Kernel::Thread& value)
  940. {
  941. return AK::Formatter<FormatString>::format(
  942. builder,
  943. "{}({}:{})", value.process().name(), value.pid().value(), value.tid().value());
  944. }