Thread.cpp 42 KB

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