Thread.cpp 43 KB

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