Thread.cpp 42 KB

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