Thread.cpp 36 KB

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