Thread.cpp 35 KB

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