Thread.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333
  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 (!has_unmasked_pending_signals())
  562. return;
  563. if (m_state == Stopped) {
  564. SpinlockLocker lock(m_lock);
  565. if (pending_signals_for_state() != 0) {
  566. dbgln_if(SIGNAL_DEBUG, "Signal: Resuming stopped {} to deliver signal {}", *this, signal);
  567. resume_from_stopped();
  568. }
  569. } else {
  570. SpinlockLocker block_lock(m_block_lock);
  571. dbgln_if(SIGNAL_DEBUG, "Signal: Unblocking {} to deliver signal {}", *this, signal);
  572. unblock(signal);
  573. }
  574. }
  575. u32 Thread::update_signal_mask(u32 signal_mask)
  576. {
  577. SpinlockLocker lock(g_scheduler_lock);
  578. auto previous_signal_mask = m_signal_mask;
  579. m_signal_mask = signal_mask;
  580. m_have_any_unmasked_pending_signals.store((pending_signals_for_state() & ~m_signal_mask) != 0, AK::memory_order_release);
  581. return previous_signal_mask;
  582. }
  583. u32 Thread::signal_mask() const
  584. {
  585. SpinlockLocker lock(g_scheduler_lock);
  586. return m_signal_mask;
  587. }
  588. u32 Thread::signal_mask_block(sigset_t signal_set, bool block)
  589. {
  590. SpinlockLocker lock(g_scheduler_lock);
  591. auto previous_signal_mask = m_signal_mask;
  592. if (block)
  593. m_signal_mask |= signal_set;
  594. else
  595. m_signal_mask &= ~signal_set;
  596. m_have_any_unmasked_pending_signals.store((pending_signals_for_state() & ~m_signal_mask) != 0, AK::memory_order_release);
  597. return previous_signal_mask;
  598. }
  599. void Thread::reset_signals_for_exec()
  600. {
  601. SpinlockLocker lock(g_scheduler_lock);
  602. // The signal mask is preserved across execve(2).
  603. // The pending signal set is preserved across an execve(2).
  604. m_have_any_unmasked_pending_signals.store(false, AK::memory_order_release);
  605. m_signal_action_data.fill({});
  606. // A successful call to execve(2) removes any existing alternate signal stack
  607. m_alternative_signal_stack = 0;
  608. m_alternative_signal_stack_size = 0;
  609. }
  610. // Certain exceptions, such as SIGSEGV and SIGILL, put a
  611. // thread into a state where the signal handler must be
  612. // invoked immediately, otherwise it will continue to fault.
  613. // This function should be used in an exception handler to
  614. // ensure that when the thread resumes, it's executing in
  615. // the appropriate signal handler.
  616. void Thread::send_urgent_signal_to_self(u8 signal)
  617. {
  618. VERIFY(Thread::current() == this);
  619. DispatchSignalResult result;
  620. {
  621. SpinlockLocker lock(g_scheduler_lock);
  622. result = dispatch_signal(signal);
  623. }
  624. if (result == DispatchSignalResult::Terminate) {
  625. Thread::current()->die_if_needed();
  626. VERIFY_NOT_REACHED(); // dispatch_signal will request termination of the thread, so the above call should never return
  627. }
  628. if (result == DispatchSignalResult::Yield)
  629. yield_and_release_relock_big_lock();
  630. }
  631. DispatchSignalResult Thread::dispatch_one_pending_signal()
  632. {
  633. VERIFY(m_lock.is_locked_by_current_processor());
  634. u32 signal_candidates = pending_signals_for_state() & ~m_signal_mask;
  635. if (signal_candidates == 0)
  636. return DispatchSignalResult::Continue;
  637. u8 signal = 1;
  638. for (; signal < 32; ++signal) {
  639. if ((signal_candidates & (1 << (signal - 1))) != 0) {
  640. break;
  641. }
  642. }
  643. return dispatch_signal(signal);
  644. }
  645. DispatchSignalResult Thread::try_dispatch_one_pending_signal(u8 signal)
  646. {
  647. VERIFY(signal != 0);
  648. SpinlockLocker scheduler_lock(g_scheduler_lock);
  649. SpinlockLocker lock(m_lock);
  650. u32 signal_candidates = pending_signals_for_state() & ~m_signal_mask;
  651. if ((signal_candidates & (1 << (signal - 1))) == 0)
  652. return DispatchSignalResult::Continue;
  653. return dispatch_signal(signal);
  654. }
  655. enum class DefaultSignalAction {
  656. Terminate,
  657. Ignore,
  658. DumpCore,
  659. Stop,
  660. Continue,
  661. };
  662. static DefaultSignalAction default_signal_action(u8 signal)
  663. {
  664. VERIFY(signal && signal < NSIG);
  665. switch (signal) {
  666. case SIGHUP:
  667. case SIGINT:
  668. case SIGKILL:
  669. case SIGPIPE:
  670. case SIGALRM:
  671. case SIGUSR1:
  672. case SIGUSR2:
  673. case SIGVTALRM:
  674. case SIGSTKFLT:
  675. case SIGIO:
  676. case SIGPROF:
  677. case SIGTERM:
  678. return DefaultSignalAction::Terminate;
  679. case SIGCHLD:
  680. case SIGURG:
  681. case SIGWINCH:
  682. case SIGINFO:
  683. return DefaultSignalAction::Ignore;
  684. case SIGQUIT:
  685. case SIGILL:
  686. case SIGTRAP:
  687. case SIGABRT:
  688. case SIGBUS:
  689. case SIGFPE:
  690. case SIGSEGV:
  691. case SIGXCPU:
  692. case SIGXFSZ:
  693. case SIGSYS:
  694. return DefaultSignalAction::DumpCore;
  695. case SIGCONT:
  696. return DefaultSignalAction::Continue;
  697. case SIGSTOP:
  698. case SIGTSTP:
  699. case SIGTTIN:
  700. case SIGTTOU:
  701. return DefaultSignalAction::Stop;
  702. default:
  703. VERIFY_NOT_REACHED();
  704. }
  705. }
  706. bool Thread::should_ignore_signal(u8 signal) const
  707. {
  708. VERIFY(signal < 32);
  709. auto const& action = m_signal_action_data[signal];
  710. if (action.handler_or_sigaction.is_null())
  711. return default_signal_action(signal) == DefaultSignalAction::Ignore;
  712. return ((sighandler_t)action.handler_or_sigaction.get() == SIG_IGN);
  713. }
  714. bool Thread::has_signal_handler(u8 signal) const
  715. {
  716. VERIFY(signal < 32);
  717. auto const& action = m_signal_action_data[signal];
  718. return !action.handler_or_sigaction.is_null();
  719. }
  720. bool Thread::is_signal_masked(u8 signal) const
  721. {
  722. VERIFY(signal < 32);
  723. return (1 << (signal - 1)) & m_signal_mask;
  724. }
  725. bool Thread::has_alternative_signal_stack() const
  726. {
  727. return m_alternative_signal_stack_size != 0;
  728. }
  729. bool Thread::is_in_alternative_signal_stack() const
  730. {
  731. auto sp = get_register_dump_from_stack().userspace_sp();
  732. return sp >= m_alternative_signal_stack && sp < m_alternative_signal_stack + m_alternative_signal_stack_size;
  733. }
  734. static ErrorOr<void> push_value_on_user_stack(FlatPtr& stack, FlatPtr data)
  735. {
  736. stack -= sizeof(FlatPtr);
  737. return copy_to_user((FlatPtr*)stack, &data);
  738. }
  739. void Thread::resume_from_stopped()
  740. {
  741. VERIFY(is_stopped());
  742. VERIFY(m_stop_state != State::Invalid);
  743. VERIFY(g_scheduler_lock.is_locked_by_current_processor());
  744. if (m_stop_state == Blocked) {
  745. SpinlockLocker block_lock(m_block_lock);
  746. if (m_blocker || m_blocking_lock) {
  747. // Hasn't been unblocked yet
  748. set_state(Blocked, 0);
  749. } else {
  750. // Was unblocked while stopped
  751. set_state(Runnable);
  752. }
  753. } else {
  754. set_state(m_stop_state, 0);
  755. }
  756. }
  757. DispatchSignalResult Thread::dispatch_signal(u8 signal)
  758. {
  759. VERIFY_INTERRUPTS_DISABLED();
  760. VERIFY(g_scheduler_lock.is_locked_by_current_processor());
  761. VERIFY(signal > 0 && signal <= 32);
  762. VERIFY(process().is_user_process());
  763. VERIFY(this == Thread::current());
  764. dbgln_if(SIGNAL_DEBUG, "Dispatch signal {} to {}, state: {}", signal, *this, state_string());
  765. if (m_state == Invalid || !is_initialized()) {
  766. // Thread has barely been created, we need to wait until it is
  767. // at least in Runnable state and is_initialized() returns true,
  768. // which indicates that it is fully set up an we actually have
  769. // a register state on the stack that we can modify
  770. return DispatchSignalResult::Deferred;
  771. }
  772. VERIFY(previous_mode() == PreviousMode::UserMode);
  773. auto& action = m_signal_action_data[signal];
  774. // FIXME: Implement SA_SIGINFO signal handlers.
  775. VERIFY(!(action.flags & SA_SIGINFO));
  776. // Mark this signal as handled.
  777. m_pending_signals &= ~(1 << (signal - 1));
  778. m_have_any_unmasked_pending_signals.store((m_pending_signals & ~m_signal_mask) != 0, AK::memory_order_release);
  779. auto& process = this->process();
  780. auto* tracer = process.tracer();
  781. if (signal == SIGSTOP || (tracer && default_signal_action(signal) == DefaultSignalAction::DumpCore)) {
  782. dbgln_if(SIGNAL_DEBUG, "Signal {} stopping this thread", signal);
  783. set_state(State::Stopped, signal);
  784. return DispatchSignalResult::Yield;
  785. }
  786. if (signal == SIGCONT) {
  787. dbgln("signal: SIGCONT resuming {}", *this);
  788. } else {
  789. if (tracer) {
  790. // when a thread is traced, it should be stopped whenever it receives a signal
  791. // the tracer is notified of this by using waitpid()
  792. // only "pending signals" from the tracer are sent to the tracee
  793. if (!tracer->has_pending_signal(signal)) {
  794. dbgln("signal: {} stopping {} for tracer", signal, *this);
  795. set_state(Stopped, signal);
  796. return DispatchSignalResult::Yield;
  797. }
  798. tracer->unset_signal(signal);
  799. }
  800. }
  801. auto handler_vaddr = action.handler_or_sigaction;
  802. if (handler_vaddr.is_null()) {
  803. switch (default_signal_action(signal)) {
  804. case DefaultSignalAction::Stop:
  805. set_state(Stopped, signal);
  806. return DispatchSignalResult::Yield;
  807. case DefaultSignalAction::DumpCore:
  808. process.set_should_generate_coredump(true);
  809. process.for_each_thread([](auto& thread) {
  810. thread.set_dump_backtrace_on_finalization();
  811. });
  812. [[fallthrough]];
  813. case DefaultSignalAction::Terminate:
  814. m_process->terminate_due_to_signal(signal);
  815. return DispatchSignalResult::Terminate;
  816. case DefaultSignalAction::Ignore:
  817. VERIFY_NOT_REACHED();
  818. case DefaultSignalAction::Continue:
  819. return DispatchSignalResult::Continue;
  820. }
  821. VERIFY_NOT_REACHED();
  822. }
  823. if ((sighandler_t)handler_vaddr.as_ptr() == SIG_IGN) {
  824. dbgln_if(SIGNAL_DEBUG, "Ignored signal {}", signal);
  825. return DispatchSignalResult::Continue;
  826. }
  827. VERIFY(previous_mode() == PreviousMode::UserMode);
  828. VERIFY(current_trap());
  829. ScopedAddressSpaceSwitcher switcher(m_process);
  830. u32 old_signal_mask = m_signal_mask;
  831. u32 new_signal_mask = action.mask;
  832. if ((action.flags & SA_NODEFER) == SA_NODEFER)
  833. new_signal_mask &= ~(1 << (signal - 1));
  834. else
  835. new_signal_mask |= 1 << (signal - 1);
  836. m_signal_mask |= new_signal_mask;
  837. m_have_any_unmasked_pending_signals.store((m_pending_signals & ~m_signal_mask) != 0, AK::memory_order_release);
  838. bool use_alternative_stack = ((action.flags & SA_ONSTACK) != 0) && has_alternative_signal_stack() && !is_in_alternative_signal_stack();
  839. auto setup_stack = [&](RegisterState& state) -> ErrorOr<void> {
  840. FlatPtr old_sp = state.userspace_sp();
  841. FlatPtr stack;
  842. if (use_alternative_stack)
  843. stack = m_alternative_signal_stack + m_alternative_signal_stack_size;
  844. else
  845. stack = old_sp;
  846. FlatPtr ret_ip = state.ip();
  847. FlatPtr ret_flags = state.flags();
  848. dbgln_if(SIGNAL_DEBUG, "Setting up user stack to return to IP {:p}, SP {:p}", ret_ip, old_sp);
  849. #if ARCH(I386)
  850. // Align the stack to 16 bytes.
  851. // Note that we push 52 bytes (4 * 13) on to the stack
  852. // before the return address, so we need to account for this here.
  853. // 56 % 16 = 4, so we only need to take 4 bytes into consideration for
  854. // the stack alignment.
  855. FlatPtr stack_alignment = (stack - 4) % 16;
  856. stack -= stack_alignment;
  857. TRY(push_value_on_user_stack(stack, ret_flags));
  858. TRY(push_value_on_user_stack(stack, ret_ip));
  859. TRY(push_value_on_user_stack(stack, state.eax));
  860. TRY(push_value_on_user_stack(stack, state.ecx));
  861. TRY(push_value_on_user_stack(stack, state.edx));
  862. TRY(push_value_on_user_stack(stack, state.ebx));
  863. TRY(push_value_on_user_stack(stack, old_sp));
  864. TRY(push_value_on_user_stack(stack, state.ebp));
  865. TRY(push_value_on_user_stack(stack, state.esi));
  866. TRY(push_value_on_user_stack(stack, state.edi));
  867. #else
  868. // Align the stack to 16 bytes.
  869. // Note that we push 168 bytes (8 * 21) on to the stack
  870. // before the return address, so we need to account for this here.
  871. // 168 % 16 = 8, so we only need to take 8 bytes into consideration for
  872. // the stack alignment.
  873. // We also are not allowed to touch the thread's red-zone of 128 bytes
  874. FlatPtr stack_alignment = (stack - 8) % 16;
  875. stack -= 128 + stack_alignment;
  876. TRY(push_value_on_user_stack(stack, ret_flags));
  877. TRY(push_value_on_user_stack(stack, ret_ip));
  878. TRY(push_value_on_user_stack(stack, state.r15));
  879. TRY(push_value_on_user_stack(stack, state.r14));
  880. TRY(push_value_on_user_stack(stack, state.r13));
  881. TRY(push_value_on_user_stack(stack, state.r12));
  882. TRY(push_value_on_user_stack(stack, state.r11));
  883. TRY(push_value_on_user_stack(stack, state.r10));
  884. TRY(push_value_on_user_stack(stack, state.r9));
  885. TRY(push_value_on_user_stack(stack, state.r8));
  886. TRY(push_value_on_user_stack(stack, state.rax));
  887. TRY(push_value_on_user_stack(stack, state.rcx));
  888. TRY(push_value_on_user_stack(stack, state.rdx));
  889. TRY(push_value_on_user_stack(stack, state.rbx));
  890. TRY(push_value_on_user_stack(stack, old_sp));
  891. TRY(push_value_on_user_stack(stack, state.rbp));
  892. TRY(push_value_on_user_stack(stack, state.rsi));
  893. TRY(push_value_on_user_stack(stack, state.rdi));
  894. #endif
  895. // PUSH old_signal_mask
  896. TRY(push_value_on_user_stack(stack, old_signal_mask));
  897. TRY(push_value_on_user_stack(stack, signal));
  898. TRY(push_value_on_user_stack(stack, handler_vaddr.get()));
  899. VERIFY((stack % 16) == 0);
  900. TRY(push_value_on_user_stack(stack, 0)); // push fake return address
  901. // We write back the adjusted stack value into the register state.
  902. // We have to do this because we can't just pass around a reference to a packed field, as it's UB.
  903. state.set_userspace_sp(stack);
  904. return {};
  905. };
  906. // We now place the thread state on the userspace stack.
  907. // Note that we use a RegisterState.
  908. // Conversely, when the thread isn't blocking the RegisterState may not be
  909. // valid (fork, exec etc) but the tss will, so we use that instead.
  910. auto& regs = get_register_dump_from_stack();
  911. auto result = setup_stack(regs);
  912. if (result.is_error()) {
  913. dbgln("Invalid stack pointer: {}", regs.userspace_sp());
  914. process.set_should_generate_coredump(true);
  915. process.for_each_thread([](auto& thread) {
  916. thread.set_dump_backtrace_on_finalization();
  917. });
  918. m_process->terminate_due_to_signal(signal);
  919. return DispatchSignalResult::Terminate;
  920. }
  921. auto signal_trampoline_addr = process.signal_trampoline().get();
  922. regs.set_ip(signal_trampoline_addr);
  923. 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);
  924. return DispatchSignalResult::Continue;
  925. }
  926. RegisterState& Thread::get_register_dump_from_stack()
  927. {
  928. auto* trap = current_trap();
  929. // We should *always* have a trap. If we don't we're probably a kernel
  930. // thread that hasn't been preempted. If we want to support this, we
  931. // need to capture the registers probably into m_regs and return it
  932. VERIFY(trap);
  933. while (trap) {
  934. if (!trap->next_trap)
  935. break;
  936. trap = trap->next_trap;
  937. }
  938. return *trap->regs;
  939. }
  940. ErrorOr<NonnullRefPtr<Thread>> Thread::try_clone(Process& process)
  941. {
  942. auto clone = TRY(Thread::try_create(process));
  943. auto signal_action_data_span = m_signal_action_data.span();
  944. signal_action_data_span.copy_to(clone->m_signal_action_data.span());
  945. clone->m_signal_mask = m_signal_mask;
  946. clone->m_fpu_state = m_fpu_state;
  947. clone->m_thread_specific_data = m_thread_specific_data;
  948. return clone;
  949. }
  950. void Thread::set_state(State new_state, u8 stop_signal)
  951. {
  952. State previous_state;
  953. VERIFY(g_scheduler_lock.is_locked_by_current_processor());
  954. if (new_state == m_state)
  955. return;
  956. {
  957. SpinlockLocker thread_lock(m_lock);
  958. previous_state = m_state;
  959. if (previous_state == Invalid) {
  960. // If we were *just* created, we may have already pending signals
  961. if (has_unmasked_pending_signals()) {
  962. dbgln_if(THREAD_DEBUG, "Dispatch pending signals to new thread {}", *this);
  963. dispatch_one_pending_signal();
  964. }
  965. }
  966. m_state = new_state;
  967. dbgln_if(THREAD_DEBUG, "Set thread {} state to {}", *this, state_string());
  968. }
  969. if (previous_state == Runnable) {
  970. Scheduler::dequeue_runnable_thread(*this);
  971. } else if (previous_state == Stopped) {
  972. m_stop_state = State::Invalid;
  973. auto& process = this->process();
  974. if (process.set_stopped(false)) {
  975. process.for_each_thread([&](auto& thread) {
  976. if (&thread == this)
  977. return;
  978. if (!thread.is_stopped())
  979. return;
  980. dbgln_if(THREAD_DEBUG, "Resuming peer thread {}", thread);
  981. thread.resume_from_stopped();
  982. });
  983. process.unblock_waiters(Thread::WaitBlocker::UnblockFlags::Continued);
  984. // Tell the parent process (if any) about this change.
  985. if (auto parent = Process::from_pid(process.ppid())) {
  986. [[maybe_unused]] auto result = parent->send_signal(SIGCHLD, &process);
  987. }
  988. }
  989. }
  990. if (m_state == Runnable) {
  991. Scheduler::enqueue_runnable_thread(*this);
  992. Processor::smp_wake_n_idle_processors(1);
  993. } else if (m_state == Stopped) {
  994. // We don't want to restore to Running state, only Runnable!
  995. m_stop_state = previous_state != Running ? previous_state : Runnable;
  996. auto& process = this->process();
  997. if (!process.set_stopped(true)) {
  998. process.for_each_thread([&](auto& thread) {
  999. if (&thread == this)
  1000. return;
  1001. if (thread.is_stopped())
  1002. return;
  1003. dbgln_if(THREAD_DEBUG, "Stopping peer thread {}", thread);
  1004. thread.set_state(Stopped, stop_signal);
  1005. });
  1006. process.unblock_waiters(Thread::WaitBlocker::UnblockFlags::Stopped, stop_signal);
  1007. // Tell the parent process (if any) about this change.
  1008. if (auto parent = Process::from_pid(process.ppid())) {
  1009. [[maybe_unused]] auto result = parent->send_signal(SIGCHLD, &process);
  1010. }
  1011. }
  1012. } else if (m_state == Dying) {
  1013. VERIFY(previous_state != Blocked);
  1014. if (this != Thread::current() && is_finalizable()) {
  1015. // Some other thread set this thread to Dying, notify the
  1016. // finalizer right away as it can be cleaned up now
  1017. Scheduler::notify_finalizer();
  1018. }
  1019. }
  1020. }
  1021. struct RecognizedSymbol {
  1022. FlatPtr address;
  1023. const KernelSymbol* symbol { nullptr };
  1024. };
  1025. static bool symbolicate(RecognizedSymbol const& symbol, Process& process, StringBuilder& builder)
  1026. {
  1027. if (symbol.address == 0)
  1028. return false;
  1029. bool mask_kernel_addresses = !process.is_superuser();
  1030. if (!symbol.symbol) {
  1031. if (!Memory::is_user_address(VirtualAddress(symbol.address))) {
  1032. builder.append("0xdeadc0de\n");
  1033. } else {
  1034. if (auto* region = process.address_space().find_region_containing({ VirtualAddress(symbol.address), sizeof(FlatPtr) })) {
  1035. size_t offset = symbol.address - region->vaddr().get();
  1036. if (auto region_name = region->name(); !region_name.is_null() && !region_name.is_empty())
  1037. builder.appendff("{:p} {} + {:#x}\n", (void*)symbol.address, region_name, offset);
  1038. else
  1039. builder.appendff("{:p} {:p} + {:#x}\n", (void*)symbol.address, region->vaddr().as_ptr(), offset);
  1040. } else {
  1041. builder.appendff("{:p}\n", symbol.address);
  1042. }
  1043. }
  1044. return true;
  1045. }
  1046. unsigned offset = symbol.address - symbol.symbol->address;
  1047. if (symbol.symbol->address == g_highest_kernel_symbol_address && offset > 4096) {
  1048. builder.appendff("{:p}\n", (void*)(mask_kernel_addresses ? 0xdeadc0de : symbol.address));
  1049. } else {
  1050. builder.appendff("{:p} {} + {:#x}\n", (void*)(mask_kernel_addresses ? 0xdeadc0de : symbol.address), symbol.symbol->name, offset);
  1051. }
  1052. return true;
  1053. }
  1054. String Thread::backtrace()
  1055. {
  1056. Vector<RecognizedSymbol, 128> recognized_symbols;
  1057. auto& process = const_cast<Process&>(this->process());
  1058. auto stack_trace = Processor::capture_stack_trace(*this);
  1059. VERIFY(!g_scheduler_lock.is_locked_by_current_processor());
  1060. ScopedAddressSpaceSwitcher switcher(process);
  1061. for (auto& frame : stack_trace) {
  1062. if (Memory::is_user_range(VirtualAddress(frame), sizeof(FlatPtr) * 2)) {
  1063. recognized_symbols.append({ frame });
  1064. } else {
  1065. recognized_symbols.append({ frame, symbolicate_kernel_address(frame) });
  1066. }
  1067. }
  1068. StringBuilder builder;
  1069. for (auto& symbol : recognized_symbols) {
  1070. if (!symbolicate(symbol, process, builder))
  1071. break;
  1072. }
  1073. return builder.to_string();
  1074. }
  1075. size_t Thread::thread_specific_region_alignment() const
  1076. {
  1077. return max(process().m_master_tls_alignment, alignof(ThreadSpecificData));
  1078. }
  1079. size_t Thread::thread_specific_region_size() const
  1080. {
  1081. return align_up_to(process().m_master_tls_size, thread_specific_region_alignment()) + sizeof(ThreadSpecificData);
  1082. }
  1083. ErrorOr<void> Thread::make_thread_specific_region(Badge<Process>)
  1084. {
  1085. // The process may not require a TLS region, or allocate TLS later with sys$allocate_tls (which is what dynamically loaded programs do)
  1086. if (!process().m_master_tls_region)
  1087. return {};
  1088. auto range = TRY(process().address_space().try_allocate_range({}, thread_specific_region_size()));
  1089. auto* region = TRY(process().address_space().allocate_region(range, "Thread-specific", PROT_READ | PROT_WRITE));
  1090. m_thread_specific_range = range;
  1091. SmapDisabler disabler;
  1092. auto* thread_specific_data = (ThreadSpecificData*)region->vaddr().offset(align_up_to(process().m_master_tls_size, thread_specific_region_alignment())).as_ptr();
  1093. auto* thread_local_storage = (u8*)((u8*)thread_specific_data) - align_up_to(process().m_master_tls_size, process().m_master_tls_alignment);
  1094. m_thread_specific_data = VirtualAddress(thread_specific_data);
  1095. thread_specific_data->self = thread_specific_data;
  1096. if (process().m_master_tls_size != 0)
  1097. memcpy(thread_local_storage, process().m_master_tls_region.unsafe_ptr()->vaddr().as_ptr(), process().m_master_tls_size);
  1098. return {};
  1099. }
  1100. RefPtr<Thread> Thread::from_tid(ThreadID tid)
  1101. {
  1102. return Thread::all_instances().with([&](auto& list) -> RefPtr<Thread> {
  1103. for (Thread& thread : list) {
  1104. if (thread.tid() == tid)
  1105. return thread;
  1106. }
  1107. return nullptr;
  1108. });
  1109. }
  1110. void Thread::reset_fpu_state()
  1111. {
  1112. memcpy(&m_fpu_state, &Processor::clean_fpu_state(), sizeof(FPUState));
  1113. }
  1114. bool Thread::should_be_stopped() const
  1115. {
  1116. return process().is_stopped();
  1117. }
  1118. void Thread::track_lock_acquire(LockRank rank)
  1119. {
  1120. // Nothing to do for locks without a rank.
  1121. if (rank == LockRank::None)
  1122. return;
  1123. if (m_lock_rank_mask != LockRank::None) {
  1124. // Verify we are only attempting to take a lock of a higher rank.
  1125. VERIFY(m_lock_rank_mask > rank);
  1126. }
  1127. m_lock_rank_mask |= rank;
  1128. }
  1129. void Thread::track_lock_release(LockRank rank)
  1130. {
  1131. // Nothing to do for locks without a rank.
  1132. if (rank == LockRank::None)
  1133. return;
  1134. // The rank value from the caller should only contain a single bit, otherwise
  1135. // we are disabling the tracking for multiple locks at once which will corrupt
  1136. // the lock tracking mask, and we will assert somewhere else.
  1137. auto rank_is_a_single_bit = [](auto rank_enum) -> bool {
  1138. auto rank = to_underlying(rank_enum);
  1139. auto rank_without_least_significant_bit = rank - 1;
  1140. return (rank & rank_without_least_significant_bit) == 0;
  1141. };
  1142. // We can't release locks out of order, as that would violate the ranking.
  1143. // This is validated by toggling the least significant bit of the mask, and
  1144. // then bit wise or-ing the rank we are trying to release with the resulting
  1145. // mask. If the rank we are releasing is truly the highest rank then the mask
  1146. // we get back will be equal to the current mask of stored on the thread.
  1147. auto rank_is_in_order = [](auto mask_enum, auto rank_enum) -> bool {
  1148. auto mask = to_underlying(mask_enum);
  1149. auto rank = to_underlying(rank_enum);
  1150. auto mask_without_least_significant_bit = mask - 1;
  1151. return ((mask & mask_without_least_significant_bit) | rank) == mask;
  1152. };
  1153. VERIFY(has_flag(m_lock_rank_mask, rank));
  1154. VERIFY(rank_is_a_single_bit(rank));
  1155. VERIFY(rank_is_in_order(m_lock_rank_mask, rank));
  1156. m_lock_rank_mask ^= rank;
  1157. }
  1158. }
  1159. ErrorOr<void> AK::Formatter<Kernel::Thread>::format(FormatBuilder& builder, Kernel::Thread const& value)
  1160. {
  1161. return AK::Formatter<FormatString>::format(
  1162. builder,
  1163. "{}({}:{})", value.process().name(), value.pid().value(), value.tid().value());
  1164. }