Thread.cpp 35 KB

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