Thread.cpp 43 KB

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