Thread.cpp 34 KB

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