Thread.cpp 34 KB

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