Thread.cpp 37 KB

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