Thread.cpp 43 KB

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