Thread.cpp 36 KB

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