Thread.cpp 54 KB

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