Thread.cpp 54 KB

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