Thread.cpp 36 KB

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