Thread.cpp 36 KB

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