Thread.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  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. if (m_thread_specific_range.has_value()) {
  238. auto* region = process().space().find_region_from_range(m_thread_specific_range.value());
  239. VERIFY(region);
  240. if (!process().space().deallocate_region(*region))
  241. dbgln("Failed to unmap TLS range, exiting thread anyway.");
  242. }
  243. die_if_needed();
  244. }
  245. void Thread::yield_while_not_holding_big_lock()
  246. {
  247. VERIFY(!g_scheduler_lock.own_lock());
  248. u32 prev_flags;
  249. u32 prev_crit = Processor::current().clear_critical(prev_flags, true);
  250. Scheduler::yield();
  251. // NOTE: We may be on a different CPU now!
  252. Processor::current().restore_critical(prev_crit, prev_flags);
  253. }
  254. void Thread::yield_without_holding_big_lock()
  255. {
  256. VERIFY(!g_scheduler_lock.own_lock());
  257. u32 lock_count_to_restore = 0;
  258. auto previous_locked = unlock_process_if_locked(lock_count_to_restore);
  259. // NOTE: Even though we call Scheduler::yield here, unless we happen
  260. // to be outside of a critical section, the yield will be postponed
  261. // until leaving it in relock_process.
  262. Scheduler::yield();
  263. relock_process(previous_locked, lock_count_to_restore);
  264. }
  265. void Thread::donate_without_holding_big_lock(RefPtr<Thread>& thread, const char* reason)
  266. {
  267. VERIFY(!g_scheduler_lock.own_lock());
  268. u32 lock_count_to_restore = 0;
  269. auto previous_locked = unlock_process_if_locked(lock_count_to_restore);
  270. // NOTE: Even though we call Scheduler::yield here, unless we happen
  271. // to be outside of a critical section, the yield will be postponed
  272. // until leaving it in relock_process.
  273. Scheduler::donate_to(thread, reason);
  274. relock_process(previous_locked, lock_count_to_restore);
  275. }
  276. LockMode Thread::unlock_process_if_locked(u32& lock_count_to_restore)
  277. {
  278. return process().big_lock().force_unlock_if_locked(lock_count_to_restore);
  279. }
  280. void Thread::relock_process(LockMode previous_locked, u32 lock_count_to_restore)
  281. {
  282. // Clearing the critical section may trigger the context switch
  283. // flagged by calling Scheduler::donate_to or Scheduler::yield
  284. // above. We have to do it this way because we intentionally
  285. // leave the critical section here to be able to switch contexts.
  286. u32 prev_flags;
  287. u32 prev_crit = Processor::current().clear_critical(prev_flags, true);
  288. // CONTEXT SWITCH HAPPENS HERE!
  289. // NOTE: We may be on a different CPU now!
  290. Processor::current().restore_critical(prev_crit, prev_flags);
  291. if (previous_locked != LockMode::Unlocked) {
  292. // We've unblocked, relock the process if needed and carry on.
  293. process().big_lock().restore_lock(previous_locked, lock_count_to_restore);
  294. }
  295. }
  296. auto Thread::sleep(clockid_t clock_id, const Time& duration, Time* remaining_time) -> BlockResult
  297. {
  298. VERIFY(state() == Thread::Running);
  299. return Thread::current()->block<Thread::SleepBlocker>({}, Thread::BlockTimeout(false, &duration, nullptr, clock_id), remaining_time);
  300. }
  301. auto Thread::sleep_until(clockid_t clock_id, const Time& deadline) -> BlockResult
  302. {
  303. VERIFY(state() == Thread::Running);
  304. return Thread::current()->block<Thread::SleepBlocker>({}, Thread::BlockTimeout(true, &deadline, nullptr, clock_id));
  305. }
  306. const char* Thread::state_string() const
  307. {
  308. switch (state()) {
  309. case Thread::Invalid:
  310. return "Invalid";
  311. case Thread::Runnable:
  312. return "Runnable";
  313. case Thread::Running:
  314. return "Running";
  315. case Thread::Dying:
  316. return "Dying";
  317. case Thread::Dead:
  318. return "Dead";
  319. case Thread::Stopped:
  320. return "Stopped";
  321. case Thread::Blocked: {
  322. ScopedSpinLock block_lock(m_block_lock);
  323. VERIFY(m_blocker != nullptr);
  324. return m_blocker->state_string();
  325. }
  326. }
  327. PANIC("Thread::state_string(): Invalid state: {}", (int)state());
  328. }
  329. void Thread::finalize()
  330. {
  331. VERIFY(Thread::current() == g_finalizer);
  332. VERIFY(Thread::current() != this);
  333. #if LOCK_DEBUG
  334. VERIFY(!m_lock.own_lock());
  335. if (lock_count() > 0) {
  336. dbgln("Thread {} leaking {} Locks!", *this, lock_count());
  337. ScopedSpinLock list_lock(m_holding_locks_lock);
  338. for (auto& info : m_holding_locks_list) {
  339. const auto& location = info.source_location;
  340. 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);
  341. }
  342. VERIFY_NOT_REACHED();
  343. }
  344. #endif
  345. {
  346. ScopedSpinLock lock(g_scheduler_lock);
  347. dbgln_if(THREAD_DEBUG, "Finalizing thread {}", *this);
  348. set_state(Thread::State::Dead);
  349. m_join_condition.thread_finalizing();
  350. }
  351. if (m_dump_backtrace_on_finalization)
  352. dbgln("{}", backtrace());
  353. kfree_aligned(m_fpu_state);
  354. drop_thread_count(false);
  355. }
  356. void Thread::drop_thread_count(bool initializing_first_thread)
  357. {
  358. bool is_last = process().remove_thread(*this);
  359. if (!initializing_first_thread && is_last)
  360. process().finalize();
  361. }
  362. void Thread::finalize_dying_threads()
  363. {
  364. VERIFY(Thread::current() == g_finalizer);
  365. Vector<Thread*, 32> dying_threads;
  366. {
  367. ScopedSpinLock lock(g_scheduler_lock);
  368. for_each_in_state(Thread::State::Dying, [&](Thread& thread) {
  369. if (thread.is_finalizable())
  370. dying_threads.append(&thread);
  371. });
  372. }
  373. for (auto* thread : dying_threads) {
  374. thread->finalize();
  375. // This thread will never execute again, drop the running reference
  376. // NOTE: This may not necessarily drop the last reference if anything
  377. // else is still holding onto this thread!
  378. thread->unref();
  379. }
  380. }
  381. bool Thread::tick()
  382. {
  383. if (previous_mode() == PreviousMode::KernelMode) {
  384. ++m_process->m_ticks_in_kernel;
  385. ++m_ticks_in_kernel;
  386. } else {
  387. ++m_process->m_ticks_in_user;
  388. ++m_ticks_in_user;
  389. }
  390. return --m_ticks_left;
  391. }
  392. void Thread::check_dispatch_pending_signal()
  393. {
  394. auto result = DispatchSignalResult::Continue;
  395. {
  396. ScopedSpinLock scheduler_lock(g_scheduler_lock);
  397. if (pending_signals_for_state()) {
  398. ScopedSpinLock lock(m_lock);
  399. result = dispatch_one_pending_signal();
  400. }
  401. }
  402. switch (result) {
  403. case DispatchSignalResult::Yield:
  404. yield_while_not_holding_big_lock();
  405. break;
  406. case DispatchSignalResult::Terminate:
  407. process().die();
  408. break;
  409. default:
  410. break;
  411. }
  412. }
  413. u32 Thread::pending_signals() const
  414. {
  415. ScopedSpinLock lock(g_scheduler_lock);
  416. return pending_signals_for_state();
  417. }
  418. u32 Thread::pending_signals_for_state() const
  419. {
  420. VERIFY(g_scheduler_lock.own_lock());
  421. constexpr u32 stopped_signal_mask = (1 << (SIGCONT - 1)) | (1 << (SIGKILL - 1)) | (1 << (SIGTRAP - 1));
  422. if (is_handling_page_fault())
  423. return 0;
  424. return m_state != Stopped ? m_pending_signals : m_pending_signals & stopped_signal_mask;
  425. }
  426. void Thread::send_signal(u8 signal, [[maybe_unused]] Process* sender)
  427. {
  428. VERIFY(signal < 32);
  429. ScopedSpinLock scheduler_lock(g_scheduler_lock);
  430. // FIXME: Figure out what to do for masked signals. Should we also ignore them here?
  431. if (should_ignore_signal(signal)) {
  432. dbgln_if(SIGNAL_DEBUG, "Signal {} was ignored by {}", signal, process());
  433. return;
  434. }
  435. if constexpr (SIGNAL_DEBUG) {
  436. if (sender)
  437. dbgln("Signal: {} sent {} to {}", *sender, signal, process());
  438. else
  439. dbgln("Signal: Kernel send {} to {}", signal, process());
  440. }
  441. m_pending_signals |= 1 << (signal - 1);
  442. m_have_any_unmasked_pending_signals.store(pending_signals_for_state() & ~m_signal_mask, AK::memory_order_release);
  443. if (m_state == Stopped) {
  444. ScopedSpinLock lock(m_lock);
  445. if (pending_signals_for_state()) {
  446. dbgln_if(SIGNAL_DEBUG, "Signal: Resuming stopped {} to deliver signal {}", *this, signal);
  447. resume_from_stopped();
  448. }
  449. } else {
  450. ScopedSpinLock block_lock(m_block_lock);
  451. dbgln_if(SIGNAL_DEBUG, "Signal: Unblocking {} to deliver signal {}", *this, signal);
  452. unblock(signal);
  453. }
  454. }
  455. u32 Thread::update_signal_mask(u32 signal_mask)
  456. {
  457. ScopedSpinLock lock(g_scheduler_lock);
  458. auto previous_signal_mask = m_signal_mask;
  459. m_signal_mask = signal_mask;
  460. m_have_any_unmasked_pending_signals.store(pending_signals_for_state() & ~m_signal_mask, AK::memory_order_release);
  461. return previous_signal_mask;
  462. }
  463. u32 Thread::signal_mask() const
  464. {
  465. ScopedSpinLock lock(g_scheduler_lock);
  466. return m_signal_mask;
  467. }
  468. u32 Thread::signal_mask_block(sigset_t signal_set, bool block)
  469. {
  470. ScopedSpinLock lock(g_scheduler_lock);
  471. auto previous_signal_mask = m_signal_mask;
  472. if (block)
  473. m_signal_mask &= ~signal_set;
  474. else
  475. m_signal_mask |= signal_set;
  476. m_have_any_unmasked_pending_signals.store(pending_signals_for_state() & ~m_signal_mask, AK::memory_order_release);
  477. return previous_signal_mask;
  478. }
  479. void Thread::clear_signals()
  480. {
  481. ScopedSpinLock lock(g_scheduler_lock);
  482. m_signal_mask = 0;
  483. m_pending_signals = 0;
  484. m_have_any_unmasked_pending_signals.store(false, AK::memory_order_release);
  485. m_signal_action_data.fill({});
  486. }
  487. // Certain exceptions, such as SIGSEGV and SIGILL, put a
  488. // thread into a state where the signal handler must be
  489. // invoked immediately, otherwise it will continue to fault.
  490. // This function should be used in an exception handler to
  491. // ensure that when the thread resumes, it's executing in
  492. // the appropriate signal handler.
  493. void Thread::send_urgent_signal_to_self(u8 signal)
  494. {
  495. VERIFY(Thread::current() == this);
  496. DispatchSignalResult result;
  497. {
  498. ScopedSpinLock lock(g_scheduler_lock);
  499. result = dispatch_signal(signal);
  500. }
  501. if (result == DispatchSignalResult::Yield)
  502. yield_without_holding_big_lock();
  503. }
  504. DispatchSignalResult Thread::dispatch_one_pending_signal()
  505. {
  506. VERIFY(m_lock.own_lock());
  507. u32 signal_candidates = pending_signals_for_state() & ~m_signal_mask;
  508. if (signal_candidates == 0)
  509. return DispatchSignalResult::Continue;
  510. u8 signal = 1;
  511. for (; signal < 32; ++signal) {
  512. if (signal_candidates & (1 << (signal - 1))) {
  513. break;
  514. }
  515. }
  516. return dispatch_signal(signal);
  517. }
  518. DispatchSignalResult Thread::try_dispatch_one_pending_signal(u8 signal)
  519. {
  520. VERIFY(signal != 0);
  521. ScopedSpinLock scheduler_lock(g_scheduler_lock);
  522. ScopedSpinLock lock(m_lock);
  523. u32 signal_candidates = pending_signals_for_state() & ~m_signal_mask;
  524. if (!(signal_candidates & (1 << (signal - 1))))
  525. return DispatchSignalResult::Continue;
  526. return dispatch_signal(signal);
  527. }
  528. enum class DefaultSignalAction {
  529. Terminate,
  530. Ignore,
  531. DumpCore,
  532. Stop,
  533. Continue,
  534. };
  535. static DefaultSignalAction default_signal_action(u8 signal)
  536. {
  537. VERIFY(signal && signal < NSIG);
  538. switch (signal) {
  539. case SIGHUP:
  540. case SIGINT:
  541. case SIGKILL:
  542. case SIGPIPE:
  543. case SIGALRM:
  544. case SIGUSR1:
  545. case SIGUSR2:
  546. case SIGVTALRM:
  547. case SIGSTKFLT:
  548. case SIGIO:
  549. case SIGPROF:
  550. case SIGTERM:
  551. return DefaultSignalAction::Terminate;
  552. case SIGCHLD:
  553. case SIGURG:
  554. case SIGWINCH:
  555. case SIGINFO:
  556. return DefaultSignalAction::Ignore;
  557. case SIGQUIT:
  558. case SIGILL:
  559. case SIGTRAP:
  560. case SIGABRT:
  561. case SIGBUS:
  562. case SIGFPE:
  563. case SIGSEGV:
  564. case SIGXCPU:
  565. case SIGXFSZ:
  566. case SIGSYS:
  567. return DefaultSignalAction::DumpCore;
  568. case SIGCONT:
  569. return DefaultSignalAction::Continue;
  570. case SIGSTOP:
  571. case SIGTSTP:
  572. case SIGTTIN:
  573. case SIGTTOU:
  574. return DefaultSignalAction::Stop;
  575. }
  576. VERIFY_NOT_REACHED();
  577. }
  578. bool Thread::should_ignore_signal(u8 signal) const
  579. {
  580. VERIFY(signal < 32);
  581. auto& action = m_signal_action_data[signal];
  582. if (action.handler_or_sigaction.is_null())
  583. return default_signal_action(signal) == DefaultSignalAction::Ignore;
  584. if (action.handler_or_sigaction.as_ptr() == SIG_IGN)
  585. return true;
  586. return false;
  587. }
  588. bool Thread::has_signal_handler(u8 signal) const
  589. {
  590. VERIFY(signal < 32);
  591. auto& action = m_signal_action_data[signal];
  592. return !action.handler_or_sigaction.is_null();
  593. }
  594. static bool push_value_on_user_stack(FlatPtr* stack, FlatPtr data)
  595. {
  596. *stack -= sizeof(FlatPtr);
  597. return copy_to_user((FlatPtr*)*stack, &data);
  598. }
  599. void Thread::resume_from_stopped()
  600. {
  601. VERIFY(is_stopped());
  602. VERIFY(m_stop_state != State::Invalid);
  603. VERIFY(g_scheduler_lock.own_lock());
  604. if (m_stop_state == Blocked) {
  605. ScopedSpinLock block_lock(m_block_lock);
  606. if (m_blocker) {
  607. // Hasn't been unblocked yet
  608. set_state(Blocked, 0);
  609. } else {
  610. // Was unblocked while stopped
  611. set_state(Runnable);
  612. }
  613. } else {
  614. set_state(m_stop_state, 0);
  615. }
  616. }
  617. DispatchSignalResult Thread::dispatch_signal(u8 signal)
  618. {
  619. VERIFY_INTERRUPTS_DISABLED();
  620. VERIFY(g_scheduler_lock.own_lock());
  621. VERIFY(signal > 0 && signal <= 32);
  622. VERIFY(process().is_user_process());
  623. VERIFY(this == Thread::current());
  624. dbgln_if(SIGNAL_DEBUG, "Dispatch signal {} to {}, state: {}", signal, *this, state_string());
  625. if (m_state == Invalid || !is_initialized()) {
  626. // Thread has barely been created, we need to wait until it is
  627. // at least in Runnable state and is_initialized() returns true,
  628. // which indicates that it is fully set up an we actually have
  629. // a register state on the stack that we can modify
  630. return DispatchSignalResult::Deferred;
  631. }
  632. VERIFY(previous_mode() == PreviousMode::UserMode);
  633. auto& action = m_signal_action_data[signal];
  634. // FIXME: Implement SA_SIGINFO signal handlers.
  635. VERIFY(!(action.flags & SA_SIGINFO));
  636. // Mark this signal as handled.
  637. m_pending_signals &= ~(1 << (signal - 1));
  638. m_have_any_unmasked_pending_signals.store(m_pending_signals & ~m_signal_mask, AK::memory_order_release);
  639. auto& process = this->process();
  640. auto tracer = process.tracer();
  641. if (signal == SIGSTOP || (tracer && default_signal_action(signal) == DefaultSignalAction::DumpCore)) {
  642. dbgln_if(SIGNAL_DEBUG, "Signal {} stopping this thread", signal);
  643. set_state(State::Stopped, signal);
  644. return DispatchSignalResult::Yield;
  645. }
  646. if (signal == SIGCONT) {
  647. dbgln("signal: SIGCONT resuming {}", *this);
  648. } else {
  649. if (tracer) {
  650. // when a thread is traced, it should be stopped whenever it receives a signal
  651. // the tracer is notified of this by using waitpid()
  652. // only "pending signals" from the tracer are sent to the tracee
  653. if (!tracer->has_pending_signal(signal)) {
  654. dbgln("signal: {} stopping {} for tracer", signal, *this);
  655. set_state(Stopped, signal);
  656. return DispatchSignalResult::Yield;
  657. }
  658. tracer->unset_signal(signal);
  659. }
  660. }
  661. auto handler_vaddr = action.handler_or_sigaction;
  662. if (handler_vaddr.is_null()) {
  663. switch (default_signal_action(signal)) {
  664. case DefaultSignalAction::Stop:
  665. set_state(Stopped, signal);
  666. return DispatchSignalResult::Yield;
  667. case DefaultSignalAction::DumpCore:
  668. process.set_dump_core(true);
  669. process.for_each_thread([](auto& thread) {
  670. thread.set_dump_backtrace_on_finalization();
  671. });
  672. [[fallthrough]];
  673. case DefaultSignalAction::Terminate:
  674. m_process->terminate_due_to_signal(signal);
  675. return DispatchSignalResult::Terminate;
  676. case DefaultSignalAction::Ignore:
  677. VERIFY_NOT_REACHED();
  678. case DefaultSignalAction::Continue:
  679. return DispatchSignalResult::Continue;
  680. }
  681. VERIFY_NOT_REACHED();
  682. }
  683. if (handler_vaddr.as_ptr() == SIG_IGN) {
  684. dbgln_if(SIGNAL_DEBUG, "Ignored signal {}", signal);
  685. return DispatchSignalResult::Continue;
  686. }
  687. VERIFY(previous_mode() == PreviousMode::UserMode);
  688. VERIFY(current_trap());
  689. ProcessPagingScope paging_scope(m_process);
  690. u32 old_signal_mask = m_signal_mask;
  691. u32 new_signal_mask = action.mask;
  692. if (action.flags & SA_NODEFER)
  693. new_signal_mask &= ~(1 << (signal - 1));
  694. else
  695. new_signal_mask |= 1 << (signal - 1);
  696. m_signal_mask |= new_signal_mask;
  697. m_have_any_unmasked_pending_signals.store(m_pending_signals & ~m_signal_mask, AK::memory_order_release);
  698. auto setup_stack = [&](RegisterState& state) {
  699. #if ARCH(I386)
  700. FlatPtr* stack = &state.userspace_esp;
  701. FlatPtr old_esp = *stack;
  702. FlatPtr ret_eip = state.eip;
  703. FlatPtr ret_eflags = state.eflags;
  704. #elif ARCH(X86_64)
  705. FlatPtr* stack = &state.userspace_esp;
  706. #endif
  707. dbgln_if(SIGNAL_DEBUG, "Setting up user stack to return to EIP {:p}, ESP {:p}", ret_eip, old_esp);
  708. #if ARCH(I386)
  709. // Align the stack to 16 bytes.
  710. // Note that we push 56 bytes (4 * 14) on to the stack,
  711. // so we need to account for this here.
  712. FlatPtr stack_alignment = (*stack - 56) % 16;
  713. *stack -= stack_alignment;
  714. push_value_on_user_stack(stack, ret_eflags);
  715. push_value_on_user_stack(stack, ret_eip);
  716. push_value_on_user_stack(stack, state.eax);
  717. push_value_on_user_stack(stack, state.ecx);
  718. push_value_on_user_stack(stack, state.edx);
  719. push_value_on_user_stack(stack, state.ebx);
  720. push_value_on_user_stack(stack, old_esp);
  721. push_value_on_user_stack(stack, state.ebp);
  722. push_value_on_user_stack(stack, state.esi);
  723. push_value_on_user_stack(stack, state.edi);
  724. #elif ARCH(X86_64)
  725. // FIXME
  726. #endif
  727. // PUSH old_signal_mask
  728. push_value_on_user_stack(stack, old_signal_mask);
  729. push_value_on_user_stack(stack, signal);
  730. push_value_on_user_stack(stack, handler_vaddr.get());
  731. push_value_on_user_stack(stack, 0); //push fake return address
  732. VERIFY((*stack % 16) == 0);
  733. };
  734. // We now place the thread state on the userspace stack.
  735. // Note that we use a RegisterState.
  736. // Conversely, when the thread isn't blocking the RegisterState may not be
  737. // valid (fork, exec etc) but the tss will, so we use that instead.
  738. auto& regs = get_register_dump_from_stack();
  739. setup_stack(regs);
  740. regs.eip = process.signal_trampoline().get();
  741. 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);
  742. return DispatchSignalResult::Continue;
  743. }
  744. RegisterState& Thread::get_register_dump_from_stack()
  745. {
  746. auto* trap = current_trap();
  747. // We should *always* have a trap. If we don't we're probably a kernel
  748. // thread that hasn't been pre-empted. If we want to support this, we
  749. // need to capture the registers probably into m_tss and return it
  750. VERIFY(trap);
  751. while (trap) {
  752. if (!trap->next_trap)
  753. break;
  754. trap = trap->next_trap;
  755. }
  756. return *trap->regs;
  757. }
  758. RefPtr<Thread> Thread::clone(Process& process)
  759. {
  760. auto thread_or_error = Thread::try_create(process);
  761. if (thread_or_error.is_error())
  762. return {};
  763. auto& clone = thread_or_error.value();
  764. auto signal_action_data_span = m_signal_action_data.span();
  765. signal_action_data_span.copy_to(clone->m_signal_action_data.span());
  766. clone->m_signal_mask = m_signal_mask;
  767. memcpy(clone->m_fpu_state, m_fpu_state, sizeof(FPUState));
  768. clone->m_thread_specific_data = m_thread_specific_data;
  769. return clone;
  770. }
  771. void Thread::set_state(State new_state, u8 stop_signal)
  772. {
  773. State previous_state;
  774. VERIFY(g_scheduler_lock.own_lock());
  775. if (new_state == m_state)
  776. return;
  777. {
  778. ScopedSpinLock thread_lock(m_lock);
  779. previous_state = m_state;
  780. if (previous_state == Invalid) {
  781. // If we were *just* created, we may have already pending signals
  782. if (has_unmasked_pending_signals()) {
  783. dbgln_if(THREAD_DEBUG, "Dispatch pending signals to new thread {}", *this);
  784. dispatch_one_pending_signal();
  785. }
  786. }
  787. m_state = new_state;
  788. dbgln_if(THREAD_DEBUG, "Set thread {} state to {}", *this, state_string());
  789. }
  790. if (previous_state == Runnable) {
  791. Scheduler::dequeue_runnable_thread(*this);
  792. } else if (previous_state == Stopped) {
  793. m_stop_state = State::Invalid;
  794. auto& process = this->process();
  795. if (process.set_stopped(false) == true) {
  796. process.for_each_thread([&](auto& thread) {
  797. if (&thread == this)
  798. return;
  799. if (!thread.is_stopped())
  800. return;
  801. dbgln_if(THREAD_DEBUG, "Resuming peer thread {}", thread);
  802. thread.resume_from_stopped();
  803. });
  804. process.unblock_waiters(Thread::WaitBlocker::UnblockFlags::Continued);
  805. // Tell the parent process (if any) about this change.
  806. if (auto parent = Process::from_pid(process.ppid())) {
  807. [[maybe_unused]] auto result = parent->send_signal(SIGCHLD, &process);
  808. }
  809. }
  810. }
  811. if (m_state == Runnable) {
  812. Scheduler::queue_runnable_thread(*this);
  813. Processor::smp_wake_n_idle_processors(1);
  814. } else if (m_state == Stopped) {
  815. // We don't want to restore to Running state, only Runnable!
  816. m_stop_state = previous_state != Running ? previous_state : Runnable;
  817. auto& process = this->process();
  818. if (process.set_stopped(true) == false) {
  819. process.for_each_thread([&](auto& thread) {
  820. if (&thread == this)
  821. return;
  822. if (thread.is_stopped())
  823. return;
  824. dbgln_if(THREAD_DEBUG, "Stopping peer thread {}", thread);
  825. thread.set_state(Stopped, stop_signal);
  826. });
  827. process.unblock_waiters(Thread::WaitBlocker::UnblockFlags::Stopped, stop_signal);
  828. // Tell the parent process (if any) about this change.
  829. if (auto parent = Process::from_pid(process.ppid())) {
  830. [[maybe_unused]] auto result = parent->send_signal(SIGCHLD, &process);
  831. }
  832. }
  833. } else if (m_state == Dying) {
  834. VERIFY(previous_state != Blocked);
  835. if (this != Thread::current() && is_finalizable()) {
  836. // Some other thread set this thread to Dying, notify the
  837. // finalizer right away as it can be cleaned up now
  838. Scheduler::notify_finalizer();
  839. }
  840. }
  841. }
  842. struct RecognizedSymbol {
  843. FlatPtr address;
  844. const KernelSymbol* symbol { nullptr };
  845. };
  846. static bool symbolicate(const RecognizedSymbol& symbol, const Process& process, StringBuilder& builder)
  847. {
  848. if (!symbol.address)
  849. return false;
  850. bool mask_kernel_addresses = !process.is_superuser();
  851. if (!symbol.symbol) {
  852. if (!is_user_address(VirtualAddress(symbol.address))) {
  853. builder.append("0xdeadc0de\n");
  854. } else {
  855. builder.appendff("{:p}\n", symbol.address);
  856. }
  857. return true;
  858. }
  859. unsigned offset = symbol.address - symbol.symbol->address;
  860. if (symbol.symbol->address == g_highest_kernel_symbol_address && offset > 4096) {
  861. builder.appendff("{:p}\n", (void*)(mask_kernel_addresses ? 0xdeadc0de : symbol.address));
  862. } else {
  863. builder.appendff("{:p} {} +{}\n", (void*)(mask_kernel_addresses ? 0xdeadc0de : symbol.address), demangle(symbol.symbol->name), offset);
  864. }
  865. return true;
  866. }
  867. String Thread::backtrace()
  868. {
  869. Vector<RecognizedSymbol, 128> recognized_symbols;
  870. auto& process = const_cast<Process&>(this->process());
  871. auto stack_trace = Processor::capture_stack_trace(*this);
  872. VERIFY(!g_scheduler_lock.own_lock());
  873. ProcessPagingScope paging_scope(process);
  874. for (auto& frame : stack_trace) {
  875. if (is_user_range(VirtualAddress(frame), sizeof(FlatPtr) * 2)) {
  876. recognized_symbols.append({ frame });
  877. } else {
  878. recognized_symbols.append({ frame, symbolicate_kernel_address(frame) });
  879. }
  880. }
  881. StringBuilder builder;
  882. for (auto& symbol : recognized_symbols) {
  883. if (!symbolicate(symbol, process, builder))
  884. break;
  885. }
  886. return builder.to_string();
  887. }
  888. size_t Thread::thread_specific_region_alignment() const
  889. {
  890. return max(process().m_master_tls_alignment, alignof(ThreadSpecificData));
  891. }
  892. size_t Thread::thread_specific_region_size() const
  893. {
  894. return align_up_to(process().m_master_tls_size, thread_specific_region_alignment()) + sizeof(ThreadSpecificData);
  895. }
  896. KResult Thread::make_thread_specific_region(Badge<Process>)
  897. {
  898. // The process may not require a TLS region, or allocate TLS later with sys$allocate_tls (which is what dynamically loaded programs do)
  899. if (!process().m_master_tls_region)
  900. return KSuccess;
  901. auto range = process().space().allocate_range({}, thread_specific_region_size());
  902. if (!range.has_value())
  903. return ENOMEM;
  904. auto region_or_error = process().space().allocate_region(range.value(), "Thread-specific", PROT_READ | PROT_WRITE);
  905. if (region_or_error.is_error())
  906. return region_or_error.error();
  907. m_thread_specific_range = range.value();
  908. SmapDisabler disabler;
  909. 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();
  910. auto* thread_local_storage = (u8*)((u8*)thread_specific_data) - align_up_to(process().m_master_tls_size, process().m_master_tls_alignment);
  911. m_thread_specific_data = VirtualAddress(thread_specific_data);
  912. thread_specific_data->self = thread_specific_data;
  913. if (process().m_master_tls_size)
  914. memcpy(thread_local_storage, process().m_master_tls_region.unsafe_ptr()->vaddr().as_ptr(), process().m_master_tls_size);
  915. return KSuccess;
  916. }
  917. RefPtr<Thread> Thread::from_tid(ThreadID tid)
  918. {
  919. RefPtr<Thread> found_thread;
  920. {
  921. ScopedSpinLock lock(g_tid_map_lock);
  922. if (auto it = g_tid_map->find(tid); it != g_tid_map->end()) {
  923. // We need to call try_ref() here as there is a window between
  924. // dropping the last reference and calling the Thread's destructor!
  925. // We shouldn't remove the threads from that list until it is truly
  926. // destructed as it may stick around past finalization in order to
  927. // be able to wait() on it!
  928. if (it->value->try_ref()) {
  929. found_thread = adopt_ref(*it->value);
  930. }
  931. }
  932. }
  933. return found_thread;
  934. }
  935. void Thread::reset_fpu_state()
  936. {
  937. memcpy(m_fpu_state, &Processor::current().clean_fpu_state(), sizeof(FPUState));
  938. }
  939. bool Thread::should_be_stopped() const
  940. {
  941. return process().is_stopped();
  942. }
  943. }
  944. void AK::Formatter<Kernel::Thread>::format(FormatBuilder& builder, const Kernel::Thread& value)
  945. {
  946. return AK::Formatter<FormatString>::format(
  947. builder,
  948. "{}({}:{})", value.process().name(), value.pid().value(), value.tid().value());
  949. }