Thread.cpp 46 KB

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