Thread.cpp 39 KB

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