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