Thread.cpp 35 KB

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