Thread.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  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 = GDT_SELECTOR_PROC;
  91. m_regs.ss = GDT_SELECTOR_DATA0;
  92. m_regs.gs = 0;
  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. thread->finalize();
  408. // This thread will never execute again, drop the running reference
  409. // NOTE: This may not necessarily drop the last reference if anything
  410. // else is still holding onto this thread!
  411. thread->unref();
  412. }
  413. }
  414. bool Thread::tick()
  415. {
  416. if (previous_mode() == PreviousMode::KernelMode) {
  417. ++m_process->m_ticks_in_kernel;
  418. ++m_ticks_in_kernel;
  419. } else {
  420. ++m_process->m_ticks_in_user;
  421. ++m_ticks_in_user;
  422. }
  423. return --m_ticks_left;
  424. }
  425. void Thread::check_dispatch_pending_signal()
  426. {
  427. auto result = DispatchSignalResult::Continue;
  428. {
  429. ScopedSpinLock scheduler_lock(g_scheduler_lock);
  430. if (pending_signals_for_state()) {
  431. ScopedSpinLock lock(m_lock);
  432. result = dispatch_one_pending_signal();
  433. }
  434. }
  435. switch (result) {
  436. case DispatchSignalResult::Yield:
  437. yield_while_not_holding_big_lock();
  438. break;
  439. default:
  440. break;
  441. }
  442. }
  443. u32 Thread::pending_signals() const
  444. {
  445. ScopedSpinLock lock(g_scheduler_lock);
  446. return pending_signals_for_state();
  447. }
  448. u32 Thread::pending_signals_for_state() const
  449. {
  450. VERIFY(g_scheduler_lock.own_lock());
  451. constexpr u32 stopped_signal_mask = (1 << (SIGCONT - 1)) | (1 << (SIGKILL - 1)) | (1 << (SIGTRAP - 1));
  452. if (is_handling_page_fault())
  453. return 0;
  454. return m_state != Stopped ? m_pending_signals : m_pending_signals & stopped_signal_mask;
  455. }
  456. void Thread::send_signal(u8 signal, [[maybe_unused]] Process* sender)
  457. {
  458. VERIFY(signal < 32);
  459. ScopedSpinLock scheduler_lock(g_scheduler_lock);
  460. // FIXME: Figure out what to do for masked signals. Should we also ignore them here?
  461. if (should_ignore_signal(signal)) {
  462. dbgln_if(SIGNAL_DEBUG, "Signal {} was ignored by {}", signal, process());
  463. return;
  464. }
  465. if constexpr (SIGNAL_DEBUG) {
  466. if (sender)
  467. dbgln("Signal: {} sent {} to {}", *sender, signal, process());
  468. else
  469. dbgln("Signal: Kernel send {} to {}", signal, process());
  470. }
  471. m_pending_signals |= 1 << (signal - 1);
  472. m_have_any_unmasked_pending_signals.store(pending_signals_for_state() & ~m_signal_mask, AK::memory_order_release);
  473. if (m_state == Stopped) {
  474. ScopedSpinLock lock(m_lock);
  475. if (pending_signals_for_state()) {
  476. dbgln_if(SIGNAL_DEBUG, "Signal: Resuming stopped {} to deliver signal {}", *this, signal);
  477. resume_from_stopped();
  478. }
  479. } else {
  480. ScopedSpinLock block_lock(m_block_lock);
  481. dbgln_if(SIGNAL_DEBUG, "Signal: Unblocking {} to deliver signal {}", *this, signal);
  482. unblock(signal);
  483. }
  484. }
  485. u32 Thread::update_signal_mask(u32 signal_mask)
  486. {
  487. ScopedSpinLock lock(g_scheduler_lock);
  488. auto previous_signal_mask = m_signal_mask;
  489. m_signal_mask = signal_mask;
  490. m_have_any_unmasked_pending_signals.store(pending_signals_for_state() & ~m_signal_mask, AK::memory_order_release);
  491. return previous_signal_mask;
  492. }
  493. u32 Thread::signal_mask() const
  494. {
  495. ScopedSpinLock lock(g_scheduler_lock);
  496. return m_signal_mask;
  497. }
  498. u32 Thread::signal_mask_block(sigset_t signal_set, bool block)
  499. {
  500. ScopedSpinLock lock(g_scheduler_lock);
  501. auto previous_signal_mask = m_signal_mask;
  502. if (block)
  503. m_signal_mask &= ~signal_set;
  504. else
  505. m_signal_mask |= signal_set;
  506. m_have_any_unmasked_pending_signals.store(pending_signals_for_state() & ~m_signal_mask, AK::memory_order_release);
  507. return previous_signal_mask;
  508. }
  509. void Thread::clear_signals()
  510. {
  511. ScopedSpinLock lock(g_scheduler_lock);
  512. m_signal_mask = 0;
  513. m_pending_signals = 0;
  514. m_have_any_unmasked_pending_signals.store(false, AK::memory_order_release);
  515. m_signal_action_data.fill({});
  516. }
  517. // Certain exceptions, such as SIGSEGV and SIGILL, put a
  518. // thread into a state where the signal handler must be
  519. // invoked immediately, otherwise it will continue to fault.
  520. // This function should be used in an exception handler to
  521. // ensure that when the thread resumes, it's executing in
  522. // the appropriate signal handler.
  523. void Thread::send_urgent_signal_to_self(u8 signal)
  524. {
  525. VERIFY(Thread::current() == this);
  526. DispatchSignalResult result;
  527. {
  528. ScopedSpinLock lock(g_scheduler_lock);
  529. result = dispatch_signal(signal);
  530. }
  531. if (result == DispatchSignalResult::Yield)
  532. yield_without_holding_big_lock();
  533. }
  534. DispatchSignalResult Thread::dispatch_one_pending_signal()
  535. {
  536. VERIFY(m_lock.own_lock());
  537. u32 signal_candidates = pending_signals_for_state() & ~m_signal_mask;
  538. if (signal_candidates == 0)
  539. return DispatchSignalResult::Continue;
  540. u8 signal = 1;
  541. for (; signal < 32; ++signal) {
  542. if (signal_candidates & (1 << (signal - 1))) {
  543. break;
  544. }
  545. }
  546. return dispatch_signal(signal);
  547. }
  548. DispatchSignalResult Thread::try_dispatch_one_pending_signal(u8 signal)
  549. {
  550. VERIFY(signal != 0);
  551. ScopedSpinLock scheduler_lock(g_scheduler_lock);
  552. ScopedSpinLock lock(m_lock);
  553. u32 signal_candidates = pending_signals_for_state() & ~m_signal_mask;
  554. if (!(signal_candidates & (1 << (signal - 1))))
  555. return DispatchSignalResult::Continue;
  556. return dispatch_signal(signal);
  557. }
  558. enum class DefaultSignalAction {
  559. Terminate,
  560. Ignore,
  561. DumpCore,
  562. Stop,
  563. Continue,
  564. };
  565. static DefaultSignalAction default_signal_action(u8 signal)
  566. {
  567. VERIFY(signal && signal < NSIG);
  568. switch (signal) {
  569. case SIGHUP:
  570. case SIGINT:
  571. case SIGKILL:
  572. case SIGPIPE:
  573. case SIGALRM:
  574. case SIGUSR1:
  575. case SIGUSR2:
  576. case SIGVTALRM:
  577. case SIGSTKFLT:
  578. case SIGIO:
  579. case SIGPROF:
  580. case SIGTERM:
  581. return DefaultSignalAction::Terminate;
  582. case SIGCHLD:
  583. case SIGURG:
  584. case SIGWINCH:
  585. case SIGINFO:
  586. return DefaultSignalAction::Ignore;
  587. case SIGQUIT:
  588. case SIGILL:
  589. case SIGTRAP:
  590. case SIGABRT:
  591. case SIGBUS:
  592. case SIGFPE:
  593. case SIGSEGV:
  594. case SIGXCPU:
  595. case SIGXFSZ:
  596. case SIGSYS:
  597. return DefaultSignalAction::DumpCore;
  598. case SIGCONT:
  599. return DefaultSignalAction::Continue;
  600. case SIGSTOP:
  601. case SIGTSTP:
  602. case SIGTTIN:
  603. case SIGTTOU:
  604. return DefaultSignalAction::Stop;
  605. }
  606. VERIFY_NOT_REACHED();
  607. }
  608. bool Thread::should_ignore_signal(u8 signal) const
  609. {
  610. VERIFY(signal < 32);
  611. auto& action = m_signal_action_data[signal];
  612. if (action.handler_or_sigaction.is_null())
  613. return default_signal_action(signal) == DefaultSignalAction::Ignore;
  614. if (action.handler_or_sigaction.as_ptr() == SIG_IGN)
  615. return true;
  616. return false;
  617. }
  618. bool Thread::has_signal_handler(u8 signal) const
  619. {
  620. VERIFY(signal < 32);
  621. auto& action = m_signal_action_data[signal];
  622. return !action.handler_or_sigaction.is_null();
  623. }
  624. static bool push_value_on_user_stack(FlatPtr* stack, FlatPtr data)
  625. {
  626. *stack -= sizeof(FlatPtr);
  627. return copy_to_user((FlatPtr*)*stack, &data);
  628. }
  629. void Thread::resume_from_stopped()
  630. {
  631. VERIFY(is_stopped());
  632. VERIFY(m_stop_state != State::Invalid);
  633. VERIFY(g_scheduler_lock.own_lock());
  634. if (m_stop_state == Blocked) {
  635. ScopedSpinLock block_lock(m_block_lock);
  636. if (m_blocker) {
  637. // Hasn't been unblocked yet
  638. set_state(Blocked, 0);
  639. } else {
  640. // Was unblocked while stopped
  641. set_state(Runnable);
  642. }
  643. } else {
  644. set_state(m_stop_state, 0);
  645. }
  646. }
  647. DispatchSignalResult Thread::dispatch_signal(u8 signal)
  648. {
  649. VERIFY_INTERRUPTS_DISABLED();
  650. VERIFY(g_scheduler_lock.own_lock());
  651. VERIFY(signal > 0 && signal <= 32);
  652. VERIFY(process().is_user_process());
  653. VERIFY(this == Thread::current());
  654. dbgln_if(SIGNAL_DEBUG, "Dispatch signal {} to {}, state: {}", signal, *this, state_string());
  655. if (m_state == Invalid || !is_initialized()) {
  656. // Thread has barely been created, we need to wait until it is
  657. // at least in Runnable state and is_initialized() returns true,
  658. // which indicates that it is fully set up an we actually have
  659. // a register state on the stack that we can modify
  660. return DispatchSignalResult::Deferred;
  661. }
  662. VERIFY(previous_mode() == PreviousMode::UserMode);
  663. auto& action = m_signal_action_data[signal];
  664. // FIXME: Implement SA_SIGINFO signal handlers.
  665. VERIFY(!(action.flags & SA_SIGINFO));
  666. // Mark this signal as handled.
  667. m_pending_signals &= ~(1 << (signal - 1));
  668. m_have_any_unmasked_pending_signals.store(m_pending_signals & ~m_signal_mask, AK::memory_order_release);
  669. auto& process = this->process();
  670. auto tracer = process.tracer();
  671. if (signal == SIGSTOP || (tracer && default_signal_action(signal) == DefaultSignalAction::DumpCore)) {
  672. dbgln_if(SIGNAL_DEBUG, "Signal {} stopping this thread", signal);
  673. set_state(State::Stopped, signal);
  674. return DispatchSignalResult::Yield;
  675. }
  676. if (signal == SIGCONT) {
  677. dbgln("signal: SIGCONT resuming {}", *this);
  678. } else {
  679. if (tracer) {
  680. // when a thread is traced, it should be stopped whenever it receives a signal
  681. // the tracer is notified of this by using waitpid()
  682. // only "pending signals" from the tracer are sent to the tracee
  683. if (!tracer->has_pending_signal(signal)) {
  684. dbgln("signal: {} stopping {} for tracer", signal, *this);
  685. set_state(Stopped, signal);
  686. return DispatchSignalResult::Yield;
  687. }
  688. tracer->unset_signal(signal);
  689. }
  690. }
  691. auto handler_vaddr = action.handler_or_sigaction;
  692. if (handler_vaddr.is_null()) {
  693. switch (default_signal_action(signal)) {
  694. case DefaultSignalAction::Stop:
  695. set_state(Stopped, signal);
  696. return DispatchSignalResult::Yield;
  697. case DefaultSignalAction::DumpCore:
  698. process.set_dump_core(true);
  699. process.for_each_thread([](auto& thread) {
  700. thread.set_dump_backtrace_on_finalization();
  701. });
  702. [[fallthrough]];
  703. case DefaultSignalAction::Terminate:
  704. m_process->terminate_due_to_signal(signal);
  705. return DispatchSignalResult::Terminate;
  706. case DefaultSignalAction::Ignore:
  707. VERIFY_NOT_REACHED();
  708. case DefaultSignalAction::Continue:
  709. return DispatchSignalResult::Continue;
  710. }
  711. VERIFY_NOT_REACHED();
  712. }
  713. if (handler_vaddr.as_ptr() == SIG_IGN) {
  714. dbgln_if(SIGNAL_DEBUG, "Ignored signal {}", signal);
  715. return DispatchSignalResult::Continue;
  716. }
  717. VERIFY(previous_mode() == PreviousMode::UserMode);
  718. VERIFY(current_trap());
  719. ProcessPagingScope paging_scope(m_process);
  720. u32 old_signal_mask = m_signal_mask;
  721. u32 new_signal_mask = action.mask;
  722. if (action.flags & SA_NODEFER)
  723. new_signal_mask &= ~(1 << (signal - 1));
  724. else
  725. new_signal_mask |= 1 << (signal - 1);
  726. m_signal_mask |= new_signal_mask;
  727. m_have_any_unmasked_pending_signals.store(m_pending_signals & ~m_signal_mask, AK::memory_order_release);
  728. auto setup_stack = [&](RegisterState& state) {
  729. #if ARCH(I386)
  730. FlatPtr* stack = &state.userspace_esp;
  731. FlatPtr old_esp = *stack;
  732. FlatPtr ret_eip = state.eip;
  733. FlatPtr ret_eflags = state.eflags;
  734. dbgln_if(SIGNAL_DEBUG, "Setting up user stack to return to EIP {:p}, ESP {:p}", ret_eip, old_esp);
  735. #elif ARCH(X86_64)
  736. FlatPtr* stack = &state.userspace_rsp;
  737. FlatPtr old_rsp = *stack;
  738. FlatPtr ret_rip = state.rip;
  739. FlatPtr ret_rflags = state.rflags;
  740. dbgln_if(SIGNAL_DEBUG, "Setting up user stack to return to RIP {:p}, RSP {:p}", ret_rip, old_rsp);
  741. #endif
  742. #if ARCH(I386)
  743. // Align the stack to 16 bytes.
  744. // Note that we push 56 bytes (4 * 14) on to the stack,
  745. // so we need to account for this here.
  746. FlatPtr stack_alignment = (*stack - 56) % 16;
  747. *stack -= stack_alignment;
  748. push_value_on_user_stack(stack, ret_eflags);
  749. push_value_on_user_stack(stack, ret_eip);
  750. push_value_on_user_stack(stack, state.eax);
  751. push_value_on_user_stack(stack, state.ecx);
  752. push_value_on_user_stack(stack, state.edx);
  753. push_value_on_user_stack(stack, state.ebx);
  754. push_value_on_user_stack(stack, old_esp);
  755. push_value_on_user_stack(stack, state.ebp);
  756. push_value_on_user_stack(stack, state.esi);
  757. push_value_on_user_stack(stack, state.edi);
  758. #else
  759. // Align the stack to 16 bytes.
  760. // Note that we push 176 bytes (8 * 22) on to the stack,
  761. // so we need to account for this here.
  762. FlatPtr stack_alignment = (*stack - 112) % 16;
  763. *stack -= stack_alignment;
  764. push_value_on_user_stack(stack, ret_rflags);
  765. push_value_on_user_stack(stack, ret_rip);
  766. push_value_on_user_stack(stack, state.r15);
  767. push_value_on_user_stack(stack, state.r14);
  768. push_value_on_user_stack(stack, state.r13);
  769. push_value_on_user_stack(stack, state.r12);
  770. push_value_on_user_stack(stack, state.r11);
  771. push_value_on_user_stack(stack, state.r10);
  772. push_value_on_user_stack(stack, state.r9);
  773. push_value_on_user_stack(stack, state.r8);
  774. push_value_on_user_stack(stack, state.rax);
  775. push_value_on_user_stack(stack, state.rcx);
  776. push_value_on_user_stack(stack, state.rdx);
  777. push_value_on_user_stack(stack, state.rbx);
  778. push_value_on_user_stack(stack, old_rsp);
  779. push_value_on_user_stack(stack, state.rbp);
  780. push_value_on_user_stack(stack, state.rsi);
  781. push_value_on_user_stack(stack, state.rdi);
  782. #endif
  783. // PUSH old_signal_mask
  784. push_value_on_user_stack(stack, old_signal_mask);
  785. push_value_on_user_stack(stack, signal);
  786. push_value_on_user_stack(stack, handler_vaddr.get());
  787. push_value_on_user_stack(stack, 0); //push fake return address
  788. VERIFY((*stack % 16) == 0);
  789. };
  790. // We now place the thread state on the userspace stack.
  791. // Note that we use a RegisterState.
  792. // Conversely, when the thread isn't blocking the RegisterState may not be
  793. // valid (fork, exec etc) but the tss will, so we use that instead.
  794. auto& regs = get_register_dump_from_stack();
  795. setup_stack(regs);
  796. auto signal_trampoline_addr = process.signal_trampoline().get();
  797. #if ARCH(I386)
  798. regs.eip = signal_trampoline_addr;
  799. #else
  800. regs.rip = signal_trampoline_addr;
  801. #endif
  802. #if ARCH(I386)
  803. 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);
  804. #else
  805. 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);
  806. #endif
  807. return DispatchSignalResult::Continue;
  808. }
  809. RegisterState& Thread::get_register_dump_from_stack()
  810. {
  811. auto* trap = current_trap();
  812. // We should *always* have a trap. If we don't we're probably a kernel
  813. // thread that hasn't been pre-empted. If we want to support this, we
  814. // need to capture the registers probably into m_regs and return it
  815. VERIFY(trap);
  816. while (trap) {
  817. if (!trap->next_trap)
  818. break;
  819. trap = trap->next_trap;
  820. }
  821. return *trap->regs;
  822. }
  823. RefPtr<Thread> Thread::clone(Process& process)
  824. {
  825. auto thread_or_error = Thread::try_create(process);
  826. if (thread_or_error.is_error())
  827. return {};
  828. auto& clone = thread_or_error.value();
  829. auto signal_action_data_span = m_signal_action_data.span();
  830. signal_action_data_span.copy_to(clone->m_signal_action_data.span());
  831. clone->m_signal_mask = m_signal_mask;
  832. memcpy(clone->m_fpu_state, m_fpu_state, sizeof(FPUState));
  833. clone->m_thread_specific_data = m_thread_specific_data;
  834. return clone;
  835. }
  836. void Thread::set_state(State new_state, u8 stop_signal)
  837. {
  838. State previous_state;
  839. VERIFY(g_scheduler_lock.own_lock());
  840. if (new_state == m_state)
  841. return;
  842. {
  843. ScopedSpinLock thread_lock(m_lock);
  844. previous_state = m_state;
  845. if (previous_state == Invalid) {
  846. // If we were *just* created, we may have already pending signals
  847. if (has_unmasked_pending_signals()) {
  848. dbgln_if(THREAD_DEBUG, "Dispatch pending signals to new thread {}", *this);
  849. dispatch_one_pending_signal();
  850. }
  851. }
  852. m_state = new_state;
  853. dbgln_if(THREAD_DEBUG, "Set thread {} state to {}", *this, state_string());
  854. }
  855. if (previous_state == Runnable) {
  856. Scheduler::dequeue_runnable_thread(*this);
  857. } else if (previous_state == Stopped) {
  858. m_stop_state = State::Invalid;
  859. auto& process = this->process();
  860. if (process.set_stopped(false) == true) {
  861. process.for_each_thread([&](auto& thread) {
  862. if (&thread == this)
  863. return;
  864. if (!thread.is_stopped())
  865. return;
  866. dbgln_if(THREAD_DEBUG, "Resuming peer thread {}", thread);
  867. thread.resume_from_stopped();
  868. });
  869. process.unblock_waiters(Thread::WaitBlocker::UnblockFlags::Continued);
  870. // Tell the parent process (if any) about this change.
  871. if (auto parent = Process::from_pid(process.ppid())) {
  872. [[maybe_unused]] auto result = parent->send_signal(SIGCHLD, &process);
  873. }
  874. }
  875. }
  876. if (m_state == Runnable) {
  877. Scheduler::queue_runnable_thread(*this);
  878. Processor::smp_wake_n_idle_processors(1);
  879. } else if (m_state == Stopped) {
  880. // We don't want to restore to Running state, only Runnable!
  881. m_stop_state = previous_state != Running ? previous_state : Runnable;
  882. auto& process = this->process();
  883. if (process.set_stopped(true) == false) {
  884. process.for_each_thread([&](auto& thread) {
  885. if (&thread == this)
  886. return;
  887. if (thread.is_stopped())
  888. return;
  889. dbgln_if(THREAD_DEBUG, "Stopping peer thread {}", thread);
  890. thread.set_state(Stopped, stop_signal);
  891. });
  892. process.unblock_waiters(Thread::WaitBlocker::UnblockFlags::Stopped, stop_signal);
  893. // Tell the parent process (if any) about this change.
  894. if (auto parent = Process::from_pid(process.ppid())) {
  895. [[maybe_unused]] auto result = parent->send_signal(SIGCHLD, &process);
  896. }
  897. }
  898. } else if (m_state == Dying) {
  899. VERIFY(previous_state != Blocked);
  900. if (this != Thread::current() && is_finalizable()) {
  901. // Some other thread set this thread to Dying, notify the
  902. // finalizer right away as it can be cleaned up now
  903. Scheduler::notify_finalizer();
  904. }
  905. }
  906. }
  907. struct RecognizedSymbol {
  908. FlatPtr address;
  909. const KernelSymbol* symbol { nullptr };
  910. };
  911. static bool symbolicate(const RecognizedSymbol& symbol, const Process& process, StringBuilder& builder)
  912. {
  913. if (!symbol.address)
  914. return false;
  915. bool mask_kernel_addresses = !process.is_superuser();
  916. if (!symbol.symbol) {
  917. if (!is_user_address(VirtualAddress(symbol.address))) {
  918. builder.append("0xdeadc0de\n");
  919. } else {
  920. builder.appendff("{:p}\n", symbol.address);
  921. }
  922. return true;
  923. }
  924. unsigned offset = symbol.address - symbol.symbol->address;
  925. if (symbol.symbol->address == g_highest_kernel_symbol_address && offset > 4096) {
  926. builder.appendff("{:p}\n", (void*)(mask_kernel_addresses ? 0xdeadc0de : symbol.address));
  927. } else {
  928. builder.appendff("{:p} {} +{}\n", (void*)(mask_kernel_addresses ? 0xdeadc0de : symbol.address), demangle(symbol.symbol->name), offset);
  929. }
  930. return true;
  931. }
  932. String Thread::backtrace()
  933. {
  934. Vector<RecognizedSymbol, 128> recognized_symbols;
  935. auto& process = const_cast<Process&>(this->process());
  936. auto stack_trace = Processor::capture_stack_trace(*this);
  937. VERIFY(!g_scheduler_lock.own_lock());
  938. ProcessPagingScope paging_scope(process);
  939. for (auto& frame : stack_trace) {
  940. if (is_user_range(VirtualAddress(frame), sizeof(FlatPtr) * 2)) {
  941. recognized_symbols.append({ frame });
  942. } else {
  943. recognized_symbols.append({ frame, symbolicate_kernel_address(frame) });
  944. }
  945. }
  946. StringBuilder builder;
  947. for (auto& symbol : recognized_symbols) {
  948. if (!symbolicate(symbol, process, builder))
  949. break;
  950. }
  951. return builder.to_string();
  952. }
  953. size_t Thread::thread_specific_region_alignment() const
  954. {
  955. return max(process().m_master_tls_alignment, alignof(ThreadSpecificData));
  956. }
  957. size_t Thread::thread_specific_region_size() const
  958. {
  959. return align_up_to(process().m_master_tls_size, thread_specific_region_alignment()) + sizeof(ThreadSpecificData);
  960. }
  961. KResult Thread::make_thread_specific_region(Badge<Process>)
  962. {
  963. // The process may not require a TLS region, or allocate TLS later with sys$allocate_tls (which is what dynamically loaded programs do)
  964. if (!process().m_master_tls_region)
  965. return KSuccess;
  966. auto range = process().space().allocate_range({}, thread_specific_region_size());
  967. if (!range.has_value())
  968. return ENOMEM;
  969. auto region_or_error = process().space().allocate_region(range.value(), "Thread-specific", PROT_READ | PROT_WRITE);
  970. if (region_or_error.is_error())
  971. return region_or_error.error();
  972. m_thread_specific_range = range.value();
  973. SmapDisabler disabler;
  974. 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();
  975. auto* thread_local_storage = (u8*)((u8*)thread_specific_data) - align_up_to(process().m_master_tls_size, process().m_master_tls_alignment);
  976. m_thread_specific_data = VirtualAddress(thread_specific_data);
  977. thread_specific_data->self = thread_specific_data;
  978. if (process().m_master_tls_size)
  979. memcpy(thread_local_storage, process().m_master_tls_region.unsafe_ptr()->vaddr().as_ptr(), process().m_master_tls_size);
  980. return KSuccess;
  981. }
  982. RefPtr<Thread> Thread::from_tid(ThreadID tid)
  983. {
  984. RefPtr<Thread> found_thread;
  985. {
  986. ScopedSpinLock lock(g_tid_map_lock);
  987. if (auto it = g_tid_map->find(tid); it != g_tid_map->end()) {
  988. // We need to call try_ref() here as there is a window between
  989. // dropping the last reference and calling the Thread's destructor!
  990. // We shouldn't remove the threads from that list until it is truly
  991. // destructed as it may stick around past finalization in order to
  992. // be able to wait() on it!
  993. if (it->value->try_ref()) {
  994. found_thread = adopt_ref(*it->value);
  995. }
  996. }
  997. }
  998. return found_thread;
  999. }
  1000. void Thread::reset_fpu_state()
  1001. {
  1002. memcpy(m_fpu_state, &Processor::current().clean_fpu_state(), sizeof(FPUState));
  1003. }
  1004. bool Thread::should_be_stopped() const
  1005. {
  1006. return process().is_stopped();
  1007. }
  1008. }
  1009. void AK::Formatter<Kernel::Thread>::format(FormatBuilder& builder, const Kernel::Thread& value)
  1010. {
  1011. return AK::Formatter<FormatString>::format(
  1012. builder,
  1013. "{}({}:{})", value.process().name(), value.pid().value(), value.tid().value());
  1014. }