Thread.cpp 46 KB

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