Thread.cpp 43 KB

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