Thread.cpp 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/ScopeGuard.h>
  7. #include <AK/Singleton.h>
  8. #include <AK/StringBuilder.h>
  9. #include <AK/TemporaryChange.h>
  10. #include <AK/Time.h>
  11. #include <Kernel/Arch/SmapDisabler.h>
  12. #include <Kernel/Arch/x86/InterruptDisabler.h>
  13. #include <Kernel/Arch/x86/TrapFrame.h>
  14. #include <Kernel/Debug.h>
  15. #include <Kernel/Devices/KCOVDevice.h>
  16. #include <Kernel/FileSystem/OpenFileDescription.h>
  17. #include <Kernel/KSyms.h>
  18. #include <Kernel/Memory/MemoryManager.h>
  19. #include <Kernel/Memory/PageDirectory.h>
  20. #include <Kernel/Memory/ScopedAddressSpaceSwitcher.h>
  21. #include <Kernel/Panic.h>
  22. #include <Kernel/PerformanceEventBuffer.h>
  23. #include <Kernel/Process.h>
  24. #include <Kernel/ProcessExposed.h>
  25. #include <Kernel/Scheduler.h>
  26. #include <Kernel/Sections.h>
  27. #include <Kernel/Thread.h>
  28. #include <Kernel/ThreadTracer.h>
  29. #include <Kernel/TimerQueue.h>
  30. #include <Kernel/kstdio.h>
  31. #include <LibC/signal_numbers.h>
  32. namespace Kernel {
  33. static Singleton<SpinlockProtected<Thread::GlobalList>> s_list;
  34. SpinlockProtected<Thread::GlobalList>& Thread::all_instances()
  35. {
  36. return *s_list;
  37. }
  38. ErrorOr<NonnullRefPtr<Thread>> Thread::try_create(NonnullRefPtr<Process> process)
  39. {
  40. auto kernel_stack_region = TRY(MM.allocate_kernel_region(default_kernel_stack_size, {}, Memory::Region::Access::ReadWrite, AllocationStrategy::AllocateNow));
  41. kernel_stack_region->set_stack(true);
  42. auto block_timer = TRY(try_make_ref_counted<Timer>());
  43. auto name = TRY(KString::try_create(process->name()));
  44. return adopt_nonnull_ref_or_enomem(new (nothrow) Thread(move(process), move(kernel_stack_region), move(block_timer), move(name)));
  45. }
  46. Thread::Thread(NonnullRefPtr<Process> process, NonnullOwnPtr<Memory::Region> kernel_stack_region, NonnullRefPtr<Timer> block_timer, NonnullOwnPtr<KString> name)
  47. : m_process(move(process))
  48. , m_kernel_stack_region(move(kernel_stack_region))
  49. , m_name(move(name))
  50. , m_block_timer(move(block_timer))
  51. {
  52. bool is_first_thread = m_process->add_thread(*this);
  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. // FIXME: Handle KString allocation failure.
  60. m_kernel_stack_region->set_name(MUST(KString::formatted("Kernel stack (thread {})", m_tid.value())));
  61. Thread::all_instances().with([&](auto& list) {
  62. list.append(*this);
  63. });
  64. if constexpr (THREAD_DEBUG)
  65. dbgln("Created new thread {}({}:{})", m_process->name(), m_process->pid().value(), m_tid.value());
  66. reset_fpu_state();
  67. // Only IF is set when a process boots.
  68. m_regs.set_flags(0x0202);
  69. #if ARCH(I386)
  70. if (m_process->is_kernel_process()) {
  71. m_regs.cs = GDT_SELECTOR_CODE0;
  72. m_regs.ds = GDT_SELECTOR_DATA0;
  73. m_regs.es = GDT_SELECTOR_DATA0;
  74. m_regs.fs = 0;
  75. m_regs.ss = GDT_SELECTOR_DATA0;
  76. m_regs.gs = GDT_SELECTOR_PROC;
  77. } else {
  78. m_regs.cs = GDT_SELECTOR_CODE3 | 3;
  79. m_regs.ds = GDT_SELECTOR_DATA3 | 3;
  80. m_regs.es = GDT_SELECTOR_DATA3 | 3;
  81. m_regs.fs = GDT_SELECTOR_DATA3 | 3;
  82. m_regs.ss = GDT_SELECTOR_DATA3 | 3;
  83. m_regs.gs = GDT_SELECTOR_TLS | 3;
  84. }
  85. #else
  86. if (m_process->is_kernel_process())
  87. m_regs.cs = GDT_SELECTOR_CODE0;
  88. else
  89. m_regs.cs = GDT_SELECTOR_CODE3 | 3;
  90. #endif
  91. m_regs.cr3 = m_process->address_space().page_directory().cr3();
  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() & ~(FlatPtr)0x7u;
  94. if (m_process->is_kernel_process()) {
  95. m_regs.set_sp(m_kernel_stack_top);
  96. m_regs.set_sp0(m_kernel_stack_top);
  97. } else {
  98. // Ring 3 processes get a separate stack for ring 0.
  99. // The ring 3 stack will be assigned by exec().
  100. #if ARCH(I386)
  101. m_regs.ss0 = GDT_SELECTOR_DATA0;
  102. #endif
  103. m_regs.set_sp0(m_kernel_stack_top);
  104. }
  105. // We need to add another reference if we could successfully create
  106. // all the resources needed for this thread. The reason for this is that
  107. // we don't want to delete this thread after dropping the reference,
  108. // it may still be running or scheduled to be run.
  109. // The finalizer is responsible for dropping this reference once this
  110. // thread is ready to be cleaned up.
  111. ref();
  112. }
  113. Thread::~Thread()
  114. {
  115. {
  116. // We need to explicitly remove ourselves from the thread list
  117. // here. We may get preempted 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. SpinlockLocker lock(g_scheduler_lock);
  123. VERIFY(!m_process_thread_list_node.is_in_list());
  124. // We shouldn't be queued
  125. VERIFY(m_runnable_priority < 0);
  126. }
  127. }
  128. Thread::BlockResult Thread::block_impl(BlockTimeout const& timeout, Blocker& blocker)
  129. {
  130. VERIFY(!Processor::current_in_irq());
  131. VERIFY(this == Thread::current());
  132. ScopedCritical critical;
  133. VERIFY(!Memory::s_mm_lock.is_locked_by_current_processor());
  134. SpinlockLocker block_lock(m_block_lock);
  135. // We need to hold m_block_lock so that nobody can unblock a blocker as soon
  136. // as it is constructed and registered elsewhere
  137. ScopeGuard finalize_guard([&] {
  138. blocker.finalize();
  139. });
  140. if (!blocker.setup_blocker()) {
  141. blocker.will_unblock_immediately_without_blocking(Blocker::UnblockImmediatelyReason::UnblockConditionAlreadyMet);
  142. return BlockResult::NotBlocked;
  143. }
  144. SpinlockLocker scheduler_lock(g_scheduler_lock);
  145. // Relaxed semantics are fine for timeout_unblocked because we
  146. // synchronize on the spin locks already.
  147. Atomic<bool, AK::MemoryOrder::memory_order_relaxed> timeout_unblocked(false);
  148. bool timer_was_added = false;
  149. switch (state()) {
  150. case Thread::State::Stopped:
  151. // It's possible that we were requested to be stopped!
  152. break;
  153. case Thread::State::Running:
  154. VERIFY(m_blocker == nullptr);
  155. break;
  156. default:
  157. VERIFY_NOT_REACHED();
  158. }
  159. m_blocker = &blocker;
  160. if (auto& block_timeout = blocker.override_timeout(timeout); !block_timeout.is_infinite()) {
  161. // Process::kill_all_threads may be called at any time, which will mark all
  162. // threads to die. In that case
  163. timer_was_added = TimerQueue::the().add_timer_without_id(*m_block_timer, block_timeout.clock_id(), block_timeout.absolute_time(), [&]() {
  164. VERIFY(!Processor::current_in_irq());
  165. VERIFY(!g_scheduler_lock.is_locked_by_current_processor());
  166. VERIFY(!m_block_lock.is_locked_by_current_processor());
  167. // NOTE: this may execute on the same or any other processor!
  168. SpinlockLocker scheduler_lock(g_scheduler_lock);
  169. SpinlockLocker block_lock(m_block_lock);
  170. if (m_blocker && !timeout_unblocked.exchange(true))
  171. unblock();
  172. });
  173. if (!timer_was_added) {
  174. // Timeout is already in the past
  175. blocker.will_unblock_immediately_without_blocking(Blocker::UnblockImmediatelyReason::TimeoutInThePast);
  176. m_blocker = nullptr;
  177. return BlockResult::InterruptedByTimeout;
  178. }
  179. }
  180. blocker.begin_blocking({});
  181. set_state(Thread::State::Blocked);
  182. scheduler_lock.unlock();
  183. block_lock.unlock();
  184. dbgln_if(THREAD_DEBUG, "Thread {} blocking on {} ({}) -->", *this, &blocker, blocker.state_string());
  185. bool did_timeout = false;
  186. u32 lock_count_to_restore = 0;
  187. auto previous_locked = unlock_process_if_locked(lock_count_to_restore);
  188. for (;;) {
  189. // Yield to the scheduler, and wait for us to resume unblocked.
  190. VERIFY(!g_scheduler_lock.is_locked_by_current_processor());
  191. VERIFY(Processor::in_critical());
  192. yield_without_releasing_big_lock();
  193. VERIFY(Processor::in_critical());
  194. SpinlockLocker block_lock2(m_block_lock);
  195. if (m_blocker && !m_blocker->can_be_interrupted() && !m_should_die) {
  196. block_lock2.unlock();
  197. dbgln("Thread should not be unblocking, current state: {}", state_string());
  198. set_state(Thread::State::Blocked);
  199. continue;
  200. }
  201. // Prevent the timeout from unblocking this thread if it happens to
  202. // be in the process of firing already
  203. did_timeout |= timeout_unblocked.exchange(true);
  204. if (m_blocker) {
  205. // Remove ourselves...
  206. VERIFY(m_blocker == &blocker);
  207. m_blocker = nullptr;
  208. }
  209. dbgln_if(THREAD_DEBUG, "<-- Thread {} unblocked from {} ({})", *this, &blocker, blocker.state_string());
  210. break;
  211. }
  212. // Notify the blocker that we are no longer blocking. It may need
  213. // to clean up now while we're still holding m_lock
  214. auto result = blocker.end_blocking({}, did_timeout); // calls was_unblocked internally
  215. if (timer_was_added && !did_timeout) {
  216. // Cancel the timer while not holding any locks. This allows
  217. // the timer function to complete before we remove it
  218. // (e.g. if it's on another processor)
  219. TimerQueue::the().cancel_timer(*m_block_timer);
  220. }
  221. if (previous_locked != LockMode::Unlocked) {
  222. // NOTE: This may trigger another call to Thread::block().
  223. relock_process(previous_locked, lock_count_to_restore);
  224. }
  225. return result;
  226. }
  227. void Thread::block(Kernel::Mutex& lock, SpinlockLocker<Spinlock>& lock_lock, u32 lock_count)
  228. {
  229. VERIFY(!Processor::current_in_irq());
  230. VERIFY(this == Thread::current());
  231. ScopedCritical critical;
  232. VERIFY(!Memory::s_mm_lock.is_locked_by_current_processor());
  233. SpinlockLocker scheduler_lock(g_scheduler_lock);
  234. SpinlockLocker block_lock(m_block_lock);
  235. switch (state()) {
  236. case Thread::State::Stopped:
  237. // It's possible that we were requested to be stopped!
  238. break;
  239. case Thread::State::Running:
  240. VERIFY(m_blocker == nullptr);
  241. break;
  242. default:
  243. dbgln("Error: Attempting to block with invalid thread state - {}", state_string());
  244. VERIFY_NOT_REACHED();
  245. }
  246. // If we're blocking on the big-lock we may actually be in the process
  247. // of unblocking from another lock. If that's the case m_blocking_mutex
  248. // is already set
  249. auto& big_lock = process().big_lock();
  250. VERIFY((&lock == &big_lock && m_blocking_mutex != &big_lock) || !m_blocking_mutex);
  251. auto* previous_blocking_mutex = m_blocking_mutex;
  252. m_blocking_mutex = &lock;
  253. m_lock_requested_count = lock_count;
  254. set_state(Thread::State::Blocked);
  255. scheduler_lock.unlock();
  256. block_lock.unlock();
  257. lock_lock.unlock();
  258. dbgln_if(THREAD_DEBUG, "Thread {} blocking on Mutex {}", *this, &lock);
  259. for (;;) {
  260. // Yield to the scheduler, and wait for us to resume unblocked.
  261. VERIFY(!g_scheduler_lock.is_locked_by_current_processor());
  262. VERIFY(Processor::in_critical());
  263. if (&lock != &big_lock && big_lock.is_exclusively_locked_by_current_thread()) {
  264. // We're locking another lock and already hold the big lock...
  265. // We need to release the big lock
  266. yield_and_release_relock_big_lock();
  267. } else {
  268. // By the time we've reached this another thread might have
  269. // marked us as holding the big lock, so this call must not
  270. // verify that we're not holding it.
  271. yield_without_releasing_big_lock(VerifyLockNotHeld::No);
  272. }
  273. VERIFY(Processor::in_critical());
  274. SpinlockLocker block_lock2(m_block_lock);
  275. VERIFY(!m_blocking_mutex);
  276. m_blocking_mutex = previous_blocking_mutex;
  277. break;
  278. }
  279. lock_lock.lock();
  280. }
  281. u32 Thread::unblock_from_mutex(Kernel::Mutex& mutex)
  282. {
  283. SpinlockLocker scheduler_lock(g_scheduler_lock);
  284. SpinlockLocker block_lock(m_block_lock);
  285. VERIFY(!Processor::current_in_irq());
  286. VERIFY(m_blocking_mutex == &mutex);
  287. dbgln_if(THREAD_DEBUG, "Thread {} unblocked from Mutex {}", *this, &mutex);
  288. auto requested_count = m_lock_requested_count;
  289. m_blocking_mutex = nullptr;
  290. if (Thread::current() == this) {
  291. set_state(Thread::State::Running);
  292. return requested_count;
  293. }
  294. VERIFY(m_state != Thread::State::Runnable && m_state != Thread::State::Running);
  295. set_state(Thread::State::Runnable);
  296. return requested_count;
  297. }
  298. void Thread::unblock_from_blocker(Blocker& blocker)
  299. {
  300. auto do_unblock = [&]() {
  301. SpinlockLocker scheduler_lock(g_scheduler_lock);
  302. SpinlockLocker block_lock(m_block_lock);
  303. if (m_blocker != &blocker)
  304. return;
  305. if (!should_be_stopped() && !is_stopped())
  306. unblock();
  307. };
  308. if (Processor::current_in_irq() != 0) {
  309. Processor::deferred_call_queue([do_unblock = move(do_unblock), self = try_make_weak_ptr().release_value_but_fixme_should_propagate_errors()]() {
  310. if (auto this_thread = self.strong_ref())
  311. do_unblock();
  312. });
  313. } else {
  314. do_unblock();
  315. }
  316. }
  317. void Thread::unblock(u8 signal)
  318. {
  319. VERIFY(!Processor::current_in_irq());
  320. VERIFY(g_scheduler_lock.is_locked_by_current_processor());
  321. VERIFY(m_block_lock.is_locked_by_current_processor());
  322. if (m_state != Thread::State::Blocked)
  323. return;
  324. if (m_blocking_mutex)
  325. return;
  326. VERIFY(m_blocker);
  327. if (signal != 0) {
  328. if (is_handling_page_fault()) {
  329. // Don't let signals unblock threads that are blocked inside a page fault handler.
  330. // This prevents threads from EINTR'ing the inode read in an inode page fault.
  331. // FIXME: There's probably a better way to solve this.
  332. return;
  333. }
  334. if (!m_blocker->can_be_interrupted() && !m_should_die)
  335. return;
  336. m_blocker->set_interrupted_by_signal(signal);
  337. }
  338. m_blocker = nullptr;
  339. if (Thread::current() == this) {
  340. set_state(Thread::State::Running);
  341. return;
  342. }
  343. VERIFY(m_state != Thread::State::Runnable && m_state != Thread::State::Running);
  344. set_state(Thread::State::Runnable);
  345. }
  346. void Thread::set_should_die()
  347. {
  348. if (m_should_die) {
  349. dbgln("{} Should already die", *this);
  350. return;
  351. }
  352. ScopedCritical critical;
  353. // Remember that we should die instead of returning to
  354. // the userspace.
  355. SpinlockLocker lock(g_scheduler_lock);
  356. m_should_die = true;
  357. // NOTE: Even the current thread can technically be in "Stopped"
  358. // state! This is the case when another thread sent a SIGSTOP to
  359. // it while it was running and it calls e.g. exit() before
  360. // the scheduler gets involved again.
  361. if (is_stopped()) {
  362. // If we were stopped, we need to briefly resume so that
  363. // the kernel stacks can clean up. We won't ever return back
  364. // to user mode, though
  365. VERIFY(!process().is_stopped());
  366. resume_from_stopped();
  367. }
  368. if (is_blocked()) {
  369. SpinlockLocker block_lock(m_block_lock);
  370. if (m_blocker) {
  371. // We're blocked in the kernel.
  372. m_blocker->set_interrupted_by_death();
  373. unblock();
  374. }
  375. }
  376. }
  377. void Thread::die_if_needed()
  378. {
  379. VERIFY(Thread::current() == this);
  380. if (!m_should_die)
  381. return;
  382. u32 unlock_count;
  383. [[maybe_unused]] auto rc = unlock_process_if_locked(unlock_count);
  384. dbgln_if(THREAD_DEBUG, "Thread {} is dying", *this);
  385. {
  386. SpinlockLocker lock(g_scheduler_lock);
  387. // It's possible that we don't reach the code after this block if the
  388. // scheduler is invoked and FinalizerTask cleans up this thread, however
  389. // that doesn't matter because we're trying to invoke the scheduler anyway
  390. set_state(Thread::State::Dying);
  391. }
  392. ScopedCritical critical;
  393. // Flag a context switch. Because we're in a critical section,
  394. // Scheduler::yield will actually only mark a pending context switch
  395. // Simply leaving the critical section would not necessarily trigger
  396. // a switch.
  397. Scheduler::yield();
  398. // Now leave the critical section so that we can also trigger the
  399. // actual context switch
  400. Processor::clear_critical();
  401. dbgln("die_if_needed returned from clear_critical!!! in irq: {}", Processor::current_in_irq());
  402. // We should never get here, but the scoped scheduler lock
  403. // will be released by Scheduler::context_switch again
  404. VERIFY_NOT_REACHED();
  405. }
  406. void Thread::exit(void* exit_value)
  407. {
  408. VERIFY(Thread::current() == this);
  409. m_join_blocker_set.thread_did_exit(exit_value);
  410. set_should_die();
  411. u32 unlock_count;
  412. [[maybe_unused]] auto rc = unlock_process_if_locked(unlock_count);
  413. if (m_thread_specific_range.has_value()) {
  414. auto* region = process().address_space().find_region_from_range(m_thread_specific_range.value());
  415. process().address_space().deallocate_region(*region);
  416. }
  417. #ifdef ENABLE_KERNEL_COVERAGE_COLLECTION
  418. KCOVDevice::free_thread();
  419. #endif
  420. die_if_needed();
  421. }
  422. void Thread::yield_without_releasing_big_lock(VerifyLockNotHeld verify_lock_not_held)
  423. {
  424. VERIFY(!g_scheduler_lock.is_locked_by_current_processor());
  425. VERIFY(verify_lock_not_held == VerifyLockNotHeld::No || !process().big_lock().is_exclusively_locked_by_current_thread());
  426. // Disable interrupts here. This ensures we don't accidentally switch contexts twice
  427. InterruptDisabler disable;
  428. Scheduler::yield(); // flag a switch
  429. u32 prev_critical = Processor::clear_critical();
  430. // NOTE: We may be on a different CPU now!
  431. Processor::restore_critical(prev_critical);
  432. }
  433. void Thread::yield_and_release_relock_big_lock()
  434. {
  435. VERIFY(!g_scheduler_lock.is_locked_by_current_processor());
  436. // Disable interrupts here. This ensures we don't accidentally switch contexts twice
  437. InterruptDisabler disable;
  438. Scheduler::yield(); // flag a switch
  439. u32 lock_count_to_restore = 0;
  440. auto previous_locked = unlock_process_if_locked(lock_count_to_restore);
  441. // NOTE: Even though we call Scheduler::yield here, unless we happen
  442. // to be outside of a critical section, the yield will be postponed
  443. // until leaving it in relock_process.
  444. relock_process(previous_locked, lock_count_to_restore);
  445. }
  446. LockMode Thread::unlock_process_if_locked(u32& lock_count_to_restore)
  447. {
  448. return process().big_lock().force_unlock_exclusive_if_locked(lock_count_to_restore);
  449. }
  450. void Thread::relock_process(LockMode previous_locked, u32 lock_count_to_restore)
  451. {
  452. // Clearing the critical section may trigger the context switch
  453. // flagged by calling Scheduler::yield above.
  454. // We have to do it this way because we intentionally
  455. // leave the critical section here to be able to switch contexts.
  456. u32 prev_critical = Processor::clear_critical();
  457. // CONTEXT SWITCH HAPPENS HERE!
  458. // NOTE: We may be on a different CPU now!
  459. Processor::restore_critical(prev_critical);
  460. if (previous_locked != LockMode::Unlocked) {
  461. // We've unblocked, relock the process if needed and carry on.
  462. process().big_lock().restore_exclusive_lock(lock_count_to_restore);
  463. }
  464. }
  465. // NOLINTNEXTLINE(readability-make-member-function-const) False positive; We call block<SleepBlocker> which is not const
  466. auto Thread::sleep(clockid_t clock_id, const Time& duration, Time* remaining_time) -> BlockResult
  467. {
  468. VERIFY(state() == Thread::State::Running);
  469. return Thread::current()->block<Thread::SleepBlocker>({}, Thread::BlockTimeout(false, &duration, nullptr, clock_id), remaining_time);
  470. }
  471. // NOLINTNEXTLINE(readability-make-member-function-const) False positive; We call block<SleepBlocker> which is not const
  472. auto Thread::sleep_until(clockid_t clock_id, const Time& deadline) -> BlockResult
  473. {
  474. VERIFY(state() == Thread::State::Running);
  475. return Thread::current()->block<Thread::SleepBlocker>({}, Thread::BlockTimeout(true, &deadline, nullptr, clock_id));
  476. }
  477. StringView Thread::state_string() const
  478. {
  479. switch (state()) {
  480. case Thread::State::Invalid:
  481. return "Invalid"sv;
  482. case Thread::State::Runnable:
  483. return "Runnable"sv;
  484. case Thread::State::Running:
  485. return "Running"sv;
  486. case Thread::State::Dying:
  487. return "Dying"sv;
  488. case Thread::State::Dead:
  489. return "Dead"sv;
  490. case Thread::State::Stopped:
  491. return "Stopped"sv;
  492. case Thread::State::Blocked: {
  493. SpinlockLocker block_lock(m_block_lock);
  494. if (m_blocking_mutex)
  495. return "Mutex"sv;
  496. if (m_blocker)
  497. return m_blocker->state_string();
  498. VERIFY_NOT_REACHED();
  499. }
  500. }
  501. PANIC("Thread::state_string(): Invalid state: {}", (int)state());
  502. }
  503. void Thread::finalize()
  504. {
  505. VERIFY(Thread::current() == g_finalizer);
  506. VERIFY(Thread::current() != this);
  507. #if LOCK_DEBUG
  508. VERIFY(!m_lock.is_locked_by_current_processor());
  509. if (lock_count() > 0) {
  510. dbgln("Thread {} leaking {} Locks!", *this, lock_count());
  511. SpinlockLocker list_lock(m_holding_locks_lock);
  512. for (auto& info : m_holding_locks_list) {
  513. const auto& location = info.lock_location;
  514. dbgln(" - Mutex: \"{}\" @ {} locked in function \"{}\" at \"{}:{}\" with a count of: {}", info.lock->name(), info.lock, location.function_name(), location.filename(), location.line_number(), info.count);
  515. }
  516. VERIFY_NOT_REACHED();
  517. }
  518. #endif
  519. {
  520. SpinlockLocker lock(g_scheduler_lock);
  521. dbgln_if(THREAD_DEBUG, "Finalizing thread {}", *this);
  522. set_state(Thread::State::Dead);
  523. m_join_blocker_set.thread_finalizing();
  524. }
  525. if (m_dump_backtrace_on_finalization) {
  526. auto trace_or_error = backtrace();
  527. if (!trace_or_error.is_error()) {
  528. auto trace = trace_or_error.release_value();
  529. dbgln("Backtrace:");
  530. kernelputstr(trace->characters(), trace->length());
  531. }
  532. }
  533. drop_thread_count();
  534. }
  535. void Thread::drop_thread_count()
  536. {
  537. bool is_last = process().remove_thread(*this);
  538. if (is_last)
  539. process().finalize();
  540. }
  541. void Thread::finalize_dying_threads()
  542. {
  543. VERIFY(Thread::current() == g_finalizer);
  544. Vector<Thread*, 32> dying_threads;
  545. {
  546. SpinlockLocker lock(g_scheduler_lock);
  547. for_each_in_state(Thread::State::Dying, [&](Thread& thread) {
  548. if (!thread.is_finalizable())
  549. return;
  550. auto result = dying_threads.try_append(&thread);
  551. // We ignore allocation failures above the first 32 guaranteed thread slots, and
  552. // just flag our future-selves to finalize these threads at a later point
  553. if (result.is_error())
  554. g_finalizer_has_work.store(true, AK::MemoryOrder::memory_order_release);
  555. });
  556. }
  557. for (auto* thread : dying_threads) {
  558. RefPtr<Process> process = thread->process();
  559. dbgln_if(PROCESS_DEBUG, "Before finalization, {} has {} refs and its process has {}",
  560. *thread, thread->ref_count(), thread->process().ref_count());
  561. thread->finalize();
  562. dbgln_if(PROCESS_DEBUG, "After finalization, {} has {} refs and its process has {}",
  563. *thread, thread->ref_count(), thread->process().ref_count());
  564. // This thread will never execute again, drop the running reference
  565. // NOTE: This may not necessarily drop the last reference if anything
  566. // else is still holding onto this thread!
  567. thread->unref();
  568. }
  569. }
  570. void Thread::update_time_scheduled(u64 current_scheduler_time, bool is_kernel, bool no_longer_running)
  571. {
  572. if (m_last_time_scheduled.has_value()) {
  573. u64 delta;
  574. if (current_scheduler_time >= m_last_time_scheduled.value())
  575. delta = current_scheduler_time - m_last_time_scheduled.value();
  576. else
  577. delta = m_last_time_scheduled.value() - current_scheduler_time; // the unlikely event that the clock wrapped
  578. if (delta != 0) {
  579. // Add it to the global total *before* updating the thread's value!
  580. Scheduler::add_time_scheduled(delta, is_kernel);
  581. auto& total_time = is_kernel ? m_total_time_scheduled_kernel : m_total_time_scheduled_user;
  582. SpinlockLocker scheduler_lock(g_scheduler_lock);
  583. total_time += delta;
  584. }
  585. }
  586. if (no_longer_running)
  587. m_last_time_scheduled = {};
  588. else
  589. m_last_time_scheduled = current_scheduler_time;
  590. }
  591. bool Thread::tick()
  592. {
  593. if (previous_mode() == PreviousMode::KernelMode) {
  594. ++m_process->m_ticks_in_kernel;
  595. ++m_ticks_in_kernel;
  596. } else {
  597. ++m_process->m_ticks_in_user;
  598. ++m_ticks_in_user;
  599. }
  600. --m_ticks_left;
  601. return m_ticks_left != 0;
  602. }
  603. void Thread::check_dispatch_pending_signal()
  604. {
  605. auto result = DispatchSignalResult::Continue;
  606. {
  607. SpinlockLocker scheduler_lock(g_scheduler_lock);
  608. if (pending_signals_for_state() != 0) {
  609. SpinlockLocker lock(m_lock);
  610. result = dispatch_one_pending_signal();
  611. }
  612. }
  613. if (result == DispatchSignalResult::Yield) {
  614. yield_without_releasing_big_lock();
  615. }
  616. }
  617. u32 Thread::pending_signals() const
  618. {
  619. SpinlockLocker lock(g_scheduler_lock);
  620. return pending_signals_for_state();
  621. }
  622. u32 Thread::pending_signals_for_state() const
  623. {
  624. VERIFY(g_scheduler_lock.is_locked_by_current_processor());
  625. constexpr u32 stopped_signal_mask = (1 << (SIGCONT - 1)) | (1 << (SIGKILL - 1)) | (1 << (SIGTRAP - 1));
  626. if (is_handling_page_fault())
  627. return 0;
  628. return m_state != State::Stopped ? m_pending_signals : m_pending_signals & stopped_signal_mask;
  629. }
  630. void Thread::send_signal(u8 signal, [[maybe_unused]] Process* sender)
  631. {
  632. VERIFY(signal < 32);
  633. VERIFY(process().is_user_process());
  634. SpinlockLocker scheduler_lock(g_scheduler_lock);
  635. // FIXME: Figure out what to do for masked signals. Should we also ignore them here?
  636. if (should_ignore_signal(signal)) {
  637. dbgln_if(SIGNAL_DEBUG, "Signal {} was ignored by {}", signal, process());
  638. return;
  639. }
  640. if constexpr (SIGNAL_DEBUG) {
  641. if (sender)
  642. dbgln("Signal: {} sent {} to {}", *sender, signal, process());
  643. else
  644. dbgln("Signal: Kernel send {} to {}", signal, process());
  645. }
  646. m_pending_signals |= 1 << (signal - 1);
  647. m_have_any_unmasked_pending_signals.store((pending_signals_for_state() & ~m_signal_mask) != 0, AK::memory_order_release);
  648. m_signal_blocker_set.unblock_all_blockers_whose_conditions_are_met();
  649. if (!has_unmasked_pending_signals())
  650. return;
  651. if (m_state == Thread::State::Stopped) {
  652. SpinlockLocker lock(m_lock);
  653. if (pending_signals_for_state() != 0) {
  654. dbgln_if(SIGNAL_DEBUG, "Signal: Resuming stopped {} to deliver signal {}", *this, signal);
  655. resume_from_stopped();
  656. }
  657. } else {
  658. SpinlockLocker block_lock(m_block_lock);
  659. dbgln_if(SIGNAL_DEBUG, "Signal: Unblocking {} to deliver signal {}", *this, signal);
  660. unblock(signal);
  661. }
  662. }
  663. u32 Thread::update_signal_mask(u32 signal_mask)
  664. {
  665. SpinlockLocker lock(g_scheduler_lock);
  666. auto previous_signal_mask = m_signal_mask;
  667. m_signal_mask = signal_mask;
  668. m_have_any_unmasked_pending_signals.store((pending_signals_for_state() & ~m_signal_mask) != 0, AK::memory_order_release);
  669. return previous_signal_mask;
  670. }
  671. u32 Thread::signal_mask() const
  672. {
  673. SpinlockLocker lock(g_scheduler_lock);
  674. return m_signal_mask;
  675. }
  676. u32 Thread::signal_mask_block(sigset_t signal_set, bool block)
  677. {
  678. SpinlockLocker lock(g_scheduler_lock);
  679. auto previous_signal_mask = m_signal_mask;
  680. if (block)
  681. m_signal_mask |= signal_set;
  682. else
  683. m_signal_mask &= ~signal_set;
  684. m_have_any_unmasked_pending_signals.store((pending_signals_for_state() & ~m_signal_mask) != 0, AK::memory_order_release);
  685. return previous_signal_mask;
  686. }
  687. void Thread::reset_signals_for_exec()
  688. {
  689. SpinlockLocker lock(g_scheduler_lock);
  690. // The signal mask is preserved across execve(2).
  691. // The pending signal set is preserved across an execve(2).
  692. m_have_any_unmasked_pending_signals.store(false, AK::memory_order_release);
  693. m_signal_action_data.fill({});
  694. // A successful call to execve(2) removes any existing alternate signal stack
  695. m_alternative_signal_stack = 0;
  696. m_alternative_signal_stack_size = 0;
  697. }
  698. // Certain exceptions, such as SIGSEGV and SIGILL, put a
  699. // thread into a state where the signal handler must be
  700. // invoked immediately, otherwise it will continue to fault.
  701. // This function should be used in an exception handler to
  702. // ensure that when the thread resumes, it's executing in
  703. // the appropriate signal handler.
  704. void Thread::send_urgent_signal_to_self(u8 signal)
  705. {
  706. VERIFY(Thread::current() == this);
  707. DispatchSignalResult result;
  708. {
  709. SpinlockLocker lock(g_scheduler_lock);
  710. result = dispatch_signal(signal);
  711. }
  712. if (result == DispatchSignalResult::Terminate) {
  713. Thread::current()->die_if_needed();
  714. VERIFY_NOT_REACHED(); // dispatch_signal will request termination of the thread, so the above call should never return
  715. }
  716. if (result == DispatchSignalResult::Yield)
  717. yield_and_release_relock_big_lock();
  718. }
  719. DispatchSignalResult Thread::dispatch_one_pending_signal()
  720. {
  721. VERIFY(m_lock.is_locked_by_current_processor());
  722. u32 signal_candidates = pending_signals_for_state() & ~m_signal_mask;
  723. if (signal_candidates == 0)
  724. return DispatchSignalResult::Continue;
  725. u8 signal = 1;
  726. for (; signal < 32; ++signal) {
  727. if ((signal_candidates & (1 << (signal - 1))) != 0) {
  728. break;
  729. }
  730. }
  731. return dispatch_signal(signal);
  732. }
  733. DispatchSignalResult Thread::try_dispatch_one_pending_signal(u8 signal)
  734. {
  735. VERIFY(signal != 0);
  736. SpinlockLocker scheduler_lock(g_scheduler_lock);
  737. SpinlockLocker lock(m_lock);
  738. u32 signal_candidates = pending_signals_for_state() & ~m_signal_mask;
  739. if ((signal_candidates & (1 << (signal - 1))) == 0)
  740. return DispatchSignalResult::Continue;
  741. return dispatch_signal(signal);
  742. }
  743. enum class DefaultSignalAction {
  744. Terminate,
  745. Ignore,
  746. DumpCore,
  747. Stop,
  748. Continue,
  749. };
  750. static DefaultSignalAction default_signal_action(u8 signal)
  751. {
  752. VERIFY(signal && signal < NSIG);
  753. switch (signal) {
  754. case SIGHUP:
  755. case SIGINT:
  756. case SIGKILL:
  757. case SIGPIPE:
  758. case SIGALRM:
  759. case SIGUSR1:
  760. case SIGUSR2:
  761. case SIGVTALRM:
  762. case SIGSTKFLT:
  763. case SIGIO:
  764. case SIGPROF:
  765. case SIGTERM:
  766. return DefaultSignalAction::Terminate;
  767. case SIGCHLD:
  768. case SIGURG:
  769. case SIGWINCH:
  770. case SIGINFO:
  771. return DefaultSignalAction::Ignore;
  772. case SIGQUIT:
  773. case SIGILL:
  774. case SIGTRAP:
  775. case SIGABRT:
  776. case SIGBUS:
  777. case SIGFPE:
  778. case SIGSEGV:
  779. case SIGXCPU:
  780. case SIGXFSZ:
  781. case SIGSYS:
  782. return DefaultSignalAction::DumpCore;
  783. case SIGCONT:
  784. return DefaultSignalAction::Continue;
  785. case SIGSTOP:
  786. case SIGTSTP:
  787. case SIGTTIN:
  788. case SIGTTOU:
  789. return DefaultSignalAction::Stop;
  790. default:
  791. VERIFY_NOT_REACHED();
  792. }
  793. }
  794. bool Thread::should_ignore_signal(u8 signal) const
  795. {
  796. VERIFY(signal < 32);
  797. auto const& action = m_signal_action_data[signal];
  798. if (action.handler_or_sigaction.is_null())
  799. return default_signal_action(signal) == DefaultSignalAction::Ignore;
  800. return ((sighandler_t)action.handler_or_sigaction.get() == SIG_IGN);
  801. }
  802. bool Thread::has_signal_handler(u8 signal) const
  803. {
  804. VERIFY(signal < 32);
  805. auto const& action = m_signal_action_data[signal];
  806. return !action.handler_or_sigaction.is_null();
  807. }
  808. bool Thread::is_signal_masked(u8 signal) const
  809. {
  810. VERIFY(signal < 32);
  811. return (1 << (signal - 1)) & m_signal_mask;
  812. }
  813. bool Thread::has_alternative_signal_stack() const
  814. {
  815. return m_alternative_signal_stack_size != 0;
  816. }
  817. bool Thread::is_in_alternative_signal_stack() const
  818. {
  819. auto sp = get_register_dump_from_stack().userspace_sp();
  820. return sp >= m_alternative_signal_stack && sp < m_alternative_signal_stack + m_alternative_signal_stack_size;
  821. }
  822. static ErrorOr<void> push_value_on_user_stack(FlatPtr& stack, FlatPtr data)
  823. {
  824. stack -= sizeof(FlatPtr);
  825. return copy_to_user((FlatPtr*)stack, &data);
  826. }
  827. void Thread::resume_from_stopped()
  828. {
  829. VERIFY(is_stopped());
  830. VERIFY(m_stop_state != State::Invalid);
  831. VERIFY(g_scheduler_lock.is_locked_by_current_processor());
  832. if (m_stop_state == Thread::State::Blocked) {
  833. SpinlockLocker block_lock(m_block_lock);
  834. if (m_blocker || m_blocking_mutex) {
  835. // Hasn't been unblocked yet
  836. set_state(Thread::State::Blocked, 0);
  837. } else {
  838. // Was unblocked while stopped
  839. set_state(Thread::State::Runnable);
  840. }
  841. } else {
  842. set_state(m_stop_state, 0);
  843. }
  844. }
  845. DispatchSignalResult Thread::dispatch_signal(u8 signal)
  846. {
  847. VERIFY_INTERRUPTS_DISABLED();
  848. VERIFY(g_scheduler_lock.is_locked_by_current_processor());
  849. VERIFY(signal > 0 && signal <= 32);
  850. VERIFY(process().is_user_process());
  851. VERIFY(this == Thread::current());
  852. dbgln_if(SIGNAL_DEBUG, "Dispatch signal {} to {}, state: {}", signal, *this, state_string());
  853. if (m_state == Thread::State::Invalid || !is_initialized()) {
  854. // Thread has barely been created, we need to wait until it is
  855. // at least in Runnable state and is_initialized() returns true,
  856. // which indicates that it is fully set up an we actually have
  857. // a register state on the stack that we can modify
  858. return DispatchSignalResult::Deferred;
  859. }
  860. auto& action = m_signal_action_data[signal];
  861. // FIXME: Implement SA_SIGINFO signal handlers.
  862. VERIFY(!(action.flags & SA_SIGINFO));
  863. if (!current_trap() && !action.handler_or_sigaction.is_null()) {
  864. // We're trying dispatch a handled signal to a user process that was scheduled
  865. // after a yielding/blocking kernel thread, we don't have a register capture of
  866. // the thread, so just defer processing the signal to later.
  867. return DispatchSignalResult::Deferred;
  868. }
  869. // Mark this signal as handled.
  870. m_pending_signals &= ~(1 << (signal - 1));
  871. m_have_any_unmasked_pending_signals.store((m_pending_signals & ~m_signal_mask) != 0, AK::memory_order_release);
  872. auto& process = this->process();
  873. auto* tracer = process.tracer();
  874. if (signal == SIGSTOP || (tracer && default_signal_action(signal) == DefaultSignalAction::DumpCore)) {
  875. dbgln_if(SIGNAL_DEBUG, "Signal {} stopping this thread", signal);
  876. set_state(Thread::State::Stopped, signal);
  877. return DispatchSignalResult::Yield;
  878. }
  879. if (signal == SIGCONT) {
  880. dbgln("signal: SIGCONT resuming {}", *this);
  881. } else {
  882. if (tracer) {
  883. // when a thread is traced, it should be stopped whenever it receives a signal
  884. // the tracer is notified of this by using waitpid()
  885. // only "pending signals" from the tracer are sent to the tracee
  886. if (!tracer->has_pending_signal(signal)) {
  887. dbgln("signal: {} stopping {} for tracer", signal, *this);
  888. set_state(Thread::State::Stopped, signal);
  889. return DispatchSignalResult::Yield;
  890. }
  891. tracer->unset_signal(signal);
  892. }
  893. }
  894. auto handler_vaddr = action.handler_or_sigaction;
  895. if (handler_vaddr.is_null()) {
  896. switch (default_signal_action(signal)) {
  897. case DefaultSignalAction::Stop:
  898. set_state(Thread::State::Stopped, signal);
  899. return DispatchSignalResult::Yield;
  900. case DefaultSignalAction::DumpCore:
  901. process.set_should_generate_coredump(true);
  902. process.for_each_thread([](auto& thread) {
  903. thread.set_dump_backtrace_on_finalization();
  904. });
  905. [[fallthrough]];
  906. case DefaultSignalAction::Terminate:
  907. m_process->terminate_due_to_signal(signal);
  908. return DispatchSignalResult::Terminate;
  909. case DefaultSignalAction::Ignore:
  910. VERIFY_NOT_REACHED();
  911. case DefaultSignalAction::Continue:
  912. return DispatchSignalResult::Continue;
  913. }
  914. VERIFY_NOT_REACHED();
  915. }
  916. if ((sighandler_t)handler_vaddr.as_ptr() == SIG_IGN) {
  917. dbgln_if(SIGNAL_DEBUG, "Ignored signal {}", signal);
  918. return DispatchSignalResult::Continue;
  919. }
  920. ScopedAddressSpaceSwitcher switcher(m_process);
  921. u32 old_signal_mask = m_signal_mask;
  922. u32 new_signal_mask = action.mask;
  923. if ((action.flags & SA_NODEFER) == SA_NODEFER)
  924. new_signal_mask &= ~(1 << (signal - 1));
  925. else
  926. new_signal_mask |= 1 << (signal - 1);
  927. m_signal_mask |= new_signal_mask;
  928. m_have_any_unmasked_pending_signals.store((m_pending_signals & ~m_signal_mask) != 0, AK::memory_order_release);
  929. bool use_alternative_stack = ((action.flags & SA_ONSTACK) != 0) && has_alternative_signal_stack() && !is_in_alternative_signal_stack();
  930. auto setup_stack = [&](RegisterState& state) -> ErrorOr<void> {
  931. FlatPtr old_sp = state.userspace_sp();
  932. FlatPtr stack;
  933. if (use_alternative_stack)
  934. stack = m_alternative_signal_stack + m_alternative_signal_stack_size;
  935. else
  936. stack = old_sp;
  937. FlatPtr ret_ip = state.ip();
  938. FlatPtr ret_flags = state.flags();
  939. dbgln_if(SIGNAL_DEBUG, "Setting up user stack to return to IP {:p}, SP {:p}", ret_ip, old_sp);
  940. #if ARCH(I386)
  941. // Align the stack to 16 bytes.
  942. // Note that we push 52 bytes (4 * 13) on to the stack
  943. // before the return address, so we need to account for this here.
  944. // 56 % 16 = 4, so we only need to take 4 bytes into consideration for
  945. // the stack alignment.
  946. FlatPtr stack_alignment = (stack - 4) % 16;
  947. stack -= stack_alignment;
  948. TRY(push_value_on_user_stack(stack, ret_flags));
  949. TRY(push_value_on_user_stack(stack, ret_ip));
  950. TRY(push_value_on_user_stack(stack, state.eax));
  951. TRY(push_value_on_user_stack(stack, state.ecx));
  952. TRY(push_value_on_user_stack(stack, state.edx));
  953. TRY(push_value_on_user_stack(stack, state.ebx));
  954. TRY(push_value_on_user_stack(stack, old_sp));
  955. TRY(push_value_on_user_stack(stack, state.ebp));
  956. TRY(push_value_on_user_stack(stack, state.esi));
  957. TRY(push_value_on_user_stack(stack, state.edi));
  958. #else
  959. // Align the stack to 16 bytes.
  960. // Note that we push 168 bytes (8 * 21) on to the stack
  961. // before the return address, so we need to account for this here.
  962. // 168 % 16 = 8, so we only need to take 8 bytes into consideration for
  963. // the stack alignment.
  964. // We also are not allowed to touch the thread's red-zone of 128 bytes
  965. FlatPtr stack_alignment = (stack - 8) % 16;
  966. stack -= 128 + stack_alignment;
  967. TRY(push_value_on_user_stack(stack, ret_flags));
  968. TRY(push_value_on_user_stack(stack, ret_ip));
  969. TRY(push_value_on_user_stack(stack, state.r15));
  970. TRY(push_value_on_user_stack(stack, state.r14));
  971. TRY(push_value_on_user_stack(stack, state.r13));
  972. TRY(push_value_on_user_stack(stack, state.r12));
  973. TRY(push_value_on_user_stack(stack, state.r11));
  974. TRY(push_value_on_user_stack(stack, state.r10));
  975. TRY(push_value_on_user_stack(stack, state.r9));
  976. TRY(push_value_on_user_stack(stack, state.r8));
  977. TRY(push_value_on_user_stack(stack, state.rax));
  978. TRY(push_value_on_user_stack(stack, state.rcx));
  979. TRY(push_value_on_user_stack(stack, state.rdx));
  980. TRY(push_value_on_user_stack(stack, state.rbx));
  981. TRY(push_value_on_user_stack(stack, old_sp));
  982. TRY(push_value_on_user_stack(stack, state.rbp));
  983. TRY(push_value_on_user_stack(stack, state.rsi));
  984. TRY(push_value_on_user_stack(stack, state.rdi));
  985. #endif
  986. // PUSH old_signal_mask
  987. TRY(push_value_on_user_stack(stack, old_signal_mask));
  988. TRY(push_value_on_user_stack(stack, signal));
  989. TRY(push_value_on_user_stack(stack, handler_vaddr.get()));
  990. VERIFY((stack % 16) == 0);
  991. TRY(push_value_on_user_stack(stack, 0)); // push fake return address
  992. // We write back the adjusted stack value into the register state.
  993. // We have to do this because we can't just pass around a reference to a packed field, as it's UB.
  994. state.set_userspace_sp(stack);
  995. return {};
  996. };
  997. // We now place the thread state on the userspace stack.
  998. // Note that we use a RegisterState.
  999. // Conversely, when the thread isn't blocking the RegisterState may not be
  1000. // valid (fork, exec etc) but the tss will, so we use that instead.
  1001. auto& regs = get_register_dump_from_stack();
  1002. auto result = setup_stack(regs);
  1003. if (result.is_error()) {
  1004. dbgln("Invalid stack pointer: {}", regs.userspace_sp());
  1005. process.set_should_generate_coredump(true);
  1006. process.for_each_thread([](auto& thread) {
  1007. thread.set_dump_backtrace_on_finalization();
  1008. });
  1009. m_process->terminate_due_to_signal(signal);
  1010. return DispatchSignalResult::Terminate;
  1011. }
  1012. auto signal_trampoline_addr = process.signal_trampoline().get();
  1013. regs.set_ip(signal_trampoline_addr);
  1014. dbgln_if(SIGNAL_DEBUG, "Thread in state '{}' has been primed with signal handler {:#04x}:{:p} to deliver {}", state_string(), m_regs.cs, m_regs.ip(), signal);
  1015. return DispatchSignalResult::Continue;
  1016. }
  1017. RegisterState& Thread::get_register_dump_from_stack()
  1018. {
  1019. auto* trap = current_trap();
  1020. // We should *always* have a trap. If we don't we're probably a kernel
  1021. // thread that hasn't been preempted. If we want to support this, we
  1022. // need to capture the registers probably into m_regs and return it
  1023. VERIFY(trap);
  1024. while (trap) {
  1025. if (!trap->next_trap)
  1026. break;
  1027. trap = trap->next_trap;
  1028. }
  1029. return *trap->regs;
  1030. }
  1031. ErrorOr<NonnullRefPtr<Thread>> Thread::try_clone(Process& process)
  1032. {
  1033. auto clone = TRY(Thread::try_create(process));
  1034. auto signal_action_data_span = m_signal_action_data.span();
  1035. signal_action_data_span.copy_to(clone->m_signal_action_data.span());
  1036. clone->m_signal_mask = m_signal_mask;
  1037. clone->m_fpu_state = m_fpu_state;
  1038. clone->m_thread_specific_data = m_thread_specific_data;
  1039. return clone;
  1040. }
  1041. void Thread::set_state(State new_state, u8 stop_signal)
  1042. {
  1043. State previous_state;
  1044. VERIFY(g_scheduler_lock.is_locked_by_current_processor());
  1045. if (new_state == m_state)
  1046. return;
  1047. {
  1048. SpinlockLocker thread_lock(m_lock);
  1049. previous_state = m_state;
  1050. if (previous_state == Thread::State::Invalid) {
  1051. // If we were *just* created, we may have already pending signals
  1052. if (has_unmasked_pending_signals()) {
  1053. dbgln_if(THREAD_DEBUG, "Dispatch pending signals to new thread {}", *this);
  1054. dispatch_one_pending_signal();
  1055. }
  1056. }
  1057. m_state = new_state;
  1058. dbgln_if(THREAD_DEBUG, "Set thread {} state to {}", *this, state_string());
  1059. }
  1060. if (previous_state == Thread::State::Runnable) {
  1061. Scheduler::dequeue_runnable_thread(*this);
  1062. } else if (previous_state == Thread::State::Stopped) {
  1063. m_stop_state = State::Invalid;
  1064. auto& process = this->process();
  1065. if (process.set_stopped(false)) {
  1066. process.for_each_thread([&](auto& thread) {
  1067. if (&thread == this)
  1068. return;
  1069. if (!thread.is_stopped())
  1070. return;
  1071. dbgln_if(THREAD_DEBUG, "Resuming peer thread {}", thread);
  1072. thread.resume_from_stopped();
  1073. });
  1074. process.unblock_waiters(Thread::WaitBlocker::UnblockFlags::Continued);
  1075. // Tell the parent process (if any) about this change.
  1076. if (auto parent = Process::from_pid(process.ppid())) {
  1077. [[maybe_unused]] auto result = parent->send_signal(SIGCHLD, &process);
  1078. }
  1079. }
  1080. }
  1081. if (m_state == Thread::State::Runnable) {
  1082. Scheduler::enqueue_runnable_thread(*this);
  1083. Processor::smp_wake_n_idle_processors(1);
  1084. } else if (m_state == Thread::State::Stopped) {
  1085. // We don't want to restore to Running state, only Runnable!
  1086. m_stop_state = previous_state != Thread::State::Running ? previous_state : Thread::State::Runnable;
  1087. auto& process = this->process();
  1088. if (!process.set_stopped(true)) {
  1089. process.for_each_thread([&](auto& thread) {
  1090. if (&thread == this)
  1091. return;
  1092. if (thread.is_stopped())
  1093. return;
  1094. dbgln_if(THREAD_DEBUG, "Stopping peer thread {}", thread);
  1095. thread.set_state(Thread::State::Stopped, stop_signal);
  1096. });
  1097. process.unblock_waiters(Thread::WaitBlocker::UnblockFlags::Stopped, stop_signal);
  1098. // Tell the parent process (if any) about this change.
  1099. if (auto parent = Process::from_pid(process.ppid())) {
  1100. [[maybe_unused]] auto result = parent->send_signal(SIGCHLD, &process);
  1101. }
  1102. }
  1103. } else if (m_state == Thread::State::Dying) {
  1104. VERIFY(previous_state != Thread::State::Blocked);
  1105. if (this != Thread::current() && is_finalizable()) {
  1106. // Some other thread set this thread to Dying, notify the
  1107. // finalizer right away as it can be cleaned up now
  1108. Scheduler::notify_finalizer();
  1109. }
  1110. }
  1111. }
  1112. struct RecognizedSymbol {
  1113. FlatPtr address;
  1114. const KernelSymbol* symbol { nullptr };
  1115. };
  1116. static ErrorOr<bool> symbolicate(RecognizedSymbol const& symbol, Process& process, StringBuilder& builder)
  1117. {
  1118. if (symbol.address == 0)
  1119. return false;
  1120. bool mask_kernel_addresses = !process.is_superuser();
  1121. if (!symbol.symbol) {
  1122. if (!Memory::is_user_address(VirtualAddress(symbol.address))) {
  1123. TRY(builder.try_append("0xdeadc0de\n"));
  1124. } else {
  1125. if (auto* region = process.address_space().find_region_containing({ VirtualAddress(symbol.address), sizeof(FlatPtr) })) {
  1126. size_t offset = symbol.address - region->vaddr().get();
  1127. if (auto region_name = region->name(); !region_name.is_null() && !region_name.is_empty())
  1128. TRY(builder.try_appendff("{:p} {} + {:#x}\n", (void*)symbol.address, region_name, offset));
  1129. else
  1130. TRY(builder.try_appendff("{:p} {:p} + {:#x}\n", (void*)symbol.address, region->vaddr().as_ptr(), offset));
  1131. } else {
  1132. TRY(builder.try_appendff("{:p}\n", symbol.address));
  1133. }
  1134. }
  1135. return true;
  1136. }
  1137. unsigned offset = symbol.address - symbol.symbol->address;
  1138. if (symbol.symbol->address == g_highest_kernel_symbol_address && offset > 4096)
  1139. TRY(builder.try_appendff("{:p}\n", (void*)(mask_kernel_addresses ? 0xdeadc0de : symbol.address)));
  1140. else
  1141. TRY(builder.try_appendff("{:p} {} + {:#x}\n", (void*)(mask_kernel_addresses ? 0xdeadc0de : symbol.address), symbol.symbol->name, offset));
  1142. return true;
  1143. }
  1144. ErrorOr<NonnullOwnPtr<KString>> Thread::backtrace()
  1145. {
  1146. Vector<RecognizedSymbol, 128> recognized_symbols;
  1147. auto& process = const_cast<Process&>(this->process());
  1148. auto stack_trace = TRY(Processor::capture_stack_trace(*this));
  1149. VERIFY(!g_scheduler_lock.is_locked_by_current_processor());
  1150. ScopedAddressSpaceSwitcher switcher(process);
  1151. for (auto& frame : stack_trace) {
  1152. if (Memory::is_user_range(VirtualAddress(frame), sizeof(FlatPtr) * 2)) {
  1153. TRY(recognized_symbols.try_append({ frame }));
  1154. } else {
  1155. TRY(recognized_symbols.try_append({ frame, symbolicate_kernel_address(frame) }));
  1156. }
  1157. }
  1158. StringBuilder builder;
  1159. for (auto& symbol : recognized_symbols) {
  1160. if (!TRY(symbolicate(symbol, process, builder)))
  1161. break;
  1162. }
  1163. return KString::try_create(builder.string_view());
  1164. }
  1165. size_t Thread::thread_specific_region_alignment() const
  1166. {
  1167. return max(process().m_master_tls_alignment, alignof(ThreadSpecificData));
  1168. }
  1169. size_t Thread::thread_specific_region_size() const
  1170. {
  1171. return align_up_to(process().m_master_tls_size, thread_specific_region_alignment()) + sizeof(ThreadSpecificData);
  1172. }
  1173. ErrorOr<void> Thread::make_thread_specific_region(Badge<Process>)
  1174. {
  1175. // The process may not require a TLS region, or allocate TLS later with sys$allocate_tls (which is what dynamically loaded programs do)
  1176. if (!process().m_master_tls_region)
  1177. return {};
  1178. auto range = TRY(process().address_space().try_allocate_range({}, thread_specific_region_size()));
  1179. auto* region = TRY(process().address_space().allocate_region(range, "Thread-specific", PROT_READ | PROT_WRITE));
  1180. m_thread_specific_range = range;
  1181. SmapDisabler disabler;
  1182. auto* thread_specific_data = (ThreadSpecificData*)region->vaddr().offset(align_up_to(process().m_master_tls_size, thread_specific_region_alignment())).as_ptr();
  1183. auto* thread_local_storage = (u8*)((u8*)thread_specific_data) - align_up_to(process().m_master_tls_size, process().m_master_tls_alignment);
  1184. m_thread_specific_data = VirtualAddress(thread_specific_data);
  1185. thread_specific_data->self = thread_specific_data;
  1186. if (process().m_master_tls_size != 0)
  1187. memcpy(thread_local_storage, process().m_master_tls_region.unsafe_ptr()->vaddr().as_ptr(), process().m_master_tls_size);
  1188. return {};
  1189. }
  1190. RefPtr<Thread> Thread::from_tid(ThreadID tid)
  1191. {
  1192. return Thread::all_instances().with([&](auto& list) -> RefPtr<Thread> {
  1193. for (Thread& thread : list) {
  1194. if (thread.tid() == tid)
  1195. return thread;
  1196. }
  1197. return nullptr;
  1198. });
  1199. }
  1200. void Thread::reset_fpu_state()
  1201. {
  1202. memcpy(&m_fpu_state, &Processor::clean_fpu_state(), sizeof(FPUState));
  1203. }
  1204. bool Thread::should_be_stopped() const
  1205. {
  1206. return process().is_stopped();
  1207. }
  1208. void Thread::track_lock_acquire(LockRank rank)
  1209. {
  1210. // Nothing to do for locks without a rank.
  1211. if (rank == LockRank::None)
  1212. return;
  1213. if (m_lock_rank_mask != LockRank::None) {
  1214. // Verify we are only attempting to take a lock of a higher rank.
  1215. VERIFY(m_lock_rank_mask > rank);
  1216. }
  1217. m_lock_rank_mask |= rank;
  1218. }
  1219. void Thread::track_lock_release(LockRank rank)
  1220. {
  1221. // Nothing to do for locks without a rank.
  1222. if (rank == LockRank::None)
  1223. return;
  1224. // The rank value from the caller should only contain a single bit, otherwise
  1225. // we are disabling the tracking for multiple locks at once which will corrupt
  1226. // the lock tracking mask, and we will assert somewhere else.
  1227. auto rank_is_a_single_bit = [](auto rank_enum) -> bool {
  1228. auto rank = to_underlying(rank_enum);
  1229. auto rank_without_least_significant_bit = rank - 1;
  1230. return (rank & rank_without_least_significant_bit) == 0;
  1231. };
  1232. // We can't release locks out of order, as that would violate the ranking.
  1233. // This is validated by toggling the least significant bit of the mask, and
  1234. // then bit wise or-ing the rank we are trying to release with the resulting
  1235. // mask. If the rank we are releasing is truly the highest rank then the mask
  1236. // we get back will be equal to the current mask of stored on the thread.
  1237. auto rank_is_in_order = [](auto mask_enum, auto rank_enum) -> bool {
  1238. auto mask = to_underlying(mask_enum);
  1239. auto rank = to_underlying(rank_enum);
  1240. auto mask_without_least_significant_bit = mask - 1;
  1241. return ((mask & mask_without_least_significant_bit) | rank) == mask;
  1242. };
  1243. VERIFY(has_flag(m_lock_rank_mask, rank));
  1244. VERIFY(rank_is_a_single_bit(rank));
  1245. VERIFY(rank_is_in_order(m_lock_rank_mask, rank));
  1246. m_lock_rank_mask ^= rank;
  1247. }
  1248. }
  1249. ErrorOr<void> AK::Formatter<Kernel::Thread>::format(FormatBuilder& builder, Kernel::Thread const& value)
  1250. {
  1251. return AK::Formatter<FormatString>::format(
  1252. builder,
  1253. "{}({}:{})", value.process().name(), value.pid().value(), value.tid().value());
  1254. }